sync update from LAN repo (source master @ ca48c4ec)

This commit is contained in:
gozeros committed 2026-11-05 10:53:54 +08:00
1 parent 8bc8b0e082
commit ea9dcff9c0
873 files changed
+107866 -14011

No files matched your search

@@ -83,7 +83,7 @@ function UserInfoPanel({ user }: { user: UserListItem }) {
<Badge variant="secondary">普通用户</Badge>
)}
</dd>
<dt className="text-muted-foreground font-medium">问答次数</dt>
<dt className="text-muted-foreground font-medium">近30天问答次数</dt>
<dd className="tabular-nums">{user.qa_count}</dd>
<dt className="text-muted-foreground font-medium">Skills</dt>
<dd className="tabular-nums">{user.skill_count}</dd>
@@ -304,7 +304,7 @@ export function AdminUserHub() {
const [userQuery, setUserQuery] = useState("");
// 活动审计 放到前面 → 默认进入审计标签页。
const [activeTab, setActiveTab] = useState<"audit" | "info" | "memory">("audit");
// 是否按问答次数(降序)排序用户列表。
// 是否按近 30 天问答次数(降序)排序用户列表。
const [sortByQa, setSortByQa] = useState(false);
const filteredUsers = useMemo(() => {
@@ -332,7 +332,7 @@ export function AdminUserHub() {
<div className="border-b px-6 py-4">
<h1 className="text-xl font-semibold">Admin 用户中心</h1>
<p className="text-muted-foreground mt-0.5 text-sm">
管理用户信息、审计历史问答、编辑用户记忆。
管理用户信息、审计近 30 天问答、编辑用户记忆。
</p>
</div>
@@ -357,10 +357,10 @@ export function AdminUserHub() {
? "border-primary/40 bg-primary/5 text-primary"
: "text-muted-foreground hover:bg-muted",
)}
title="按问答次数从高到低排序"
title="按近 30 天问答次数从高到低排序"
>
<ArrowDownWideNarrow className="size-3.5" />
{sortByQa ? "按问答次数排序中" : "按问答次数排序"}
{sortByQa ? "按近30天问答排序中" : "按近30天问答排序"}
</button>
<ScrollArea className="min-h-0 flex-1">
{usersLoading && (
@@ -395,7 +395,7 @@ export function AdminUserHub() {
)}
<span
className="text-muted-foreground shrink-0 tabular-nums text-xs"
title="问答次数"
title="近 30 天问答次数"
>
{u.qa_count ?? 0}
</span>
@@ -27,6 +27,7 @@ import {
type ToolMetric,
type ToolMetricsFilters,
} from "@/core/tool-metrics/api";
import { getAdminQueryDateTimeBounds } from "@/core/admin/query-window";
import { useToolMetrics, useToolMetricsSummary } from "@/core/tool-metrics/hooks";
import { cn } from "@/lib/utils";
import { useTheme } from "@/contexts/ThemeContext";
@@ -68,6 +69,7 @@ function categoryLabel(category?: string | null): string {
export function ToolMetricsPanel() {
const { theme } = useTheme();
const queryDateTimeBounds = getAdminQueryDateTimeBounds();
const [page, setPage] = useState(0);
const [tool, setTool] = useState("");
const [user, setUser] = useState("");
@@ -77,8 +79,8 @@ export function ToolMetricsPanel() {
const [kind, setKind] = useState<KindFilter>("skill");
const [status, setStatus] = useState<StatusFilter>("all");
const [category, setCategory] = useState<string>("all");
const [since, setSince] = useState("");
const [until, setUntil] = useState("");
const [since, setSince] = useState(() => getAdminQueryDateTimeBounds().min);
const [until, setUntil] = useState(() => getAdminQueryDateTimeBounds().max);
const [exporting, setExporting] = useState(false);
const [detailRow, setDetailRow] = useState<ToolMetric | null>(null);
/** 成功 toast:仅暗色模式,浅色走 Sonner 默认 */
@@ -153,14 +155,15 @@ const errorToastDarkOptions = {
};
const resetFilters = () => {
const nextBounds = getAdminQueryDateTimeBounds();
setTool("");
setUser("");
setSkill("");
setKind("skill");
setStatus("all");
setCategory("all");
setSince("");
setUntil("");
setSince(nextBounds.min);
setUntil(nextBounds.max);
setPage(0);
};
@@ -180,7 +183,7 @@ const errorToastDarkOptions = {
<h2 className="text-lg font-semibold">工具调用统计</h2>
<p className="text-muted-foreground mt-1 text-sm">
记录每一次工具 / 技能 / MCP 调用,并对失败进行归类:检索为空、IP
被封、限流、超时、鉴权失败等。后台无条件记录。
被封、限流、超时、鉴权失败等。后台无条件记录,默认仅查询最近 30 天。
</p>
</div>
<Button onClick={handleExport} disabled={exporting}>
@@ -391,8 +394,10 @@ const errorToastDarkOptions = {
<Input
type="datetime-local"
value={since}
min={queryDateTimeBounds.min}
max={until || queryDateTimeBounds.max}
onChange={(e) => {
setSince(e.target.value);
setSince(e.target.value || queryDateTimeBounds.min);
setPage(0);
}}
/>
@@ -402,8 +407,10 @@ const errorToastDarkOptions = {
<Input
type="datetime-local"
value={until}
min={since || queryDateTimeBounds.min}
max={queryDateTimeBounds.max}
onChange={(e) => {
setUntil(e.target.value);
setUntil(e.target.value || queryDateTimeBounds.max);
setPage(0);
}}
/>
@@ -4,6 +4,7 @@ import {
BotIcon,
ClockIcon,
CopyIcon,
EyeIcon,
EyeOffIcon,
GlobeIcon,
LockIcon,
@@ -59,6 +60,7 @@ import { Textarea } from "@/components/ui/textarea";
import { usePublishSquares } from "@/core/system-settings/hooks";
import { PublishSquarePickerDialog } from "@/components/workspace/publish-square-picker-dialog";
import { SkillDetailDialog } from "@/components/workspace/skills/skill-detail-dialog";
// import { AgentChatLinkFields } from "@/components/workspace/agents/agent-chat-link-fields";
import { AgentQuestionEditor } from "@/components/workspace/agents/agent-question-editor";
import { SkillTransferSelector } from "@/components/workspace/agents/skill-transfer-selector";
import { TagChipList } from "@/components/workspace/tags/tag-chip";
@@ -75,7 +77,15 @@ import {
useUpdateAgent,
} from "@/core/agents";
import { getAgent } from "@/core/agents/api";
import type { Agent, AgentQuestion, UpdateAgentRequest } from "@/core/agents";
import type { Agent, AgentChatLink, AgentQuestion, UpdateAgentRequest } from "@/core/agents";
import {
agentChatLinksEqual,
canonicalAgentChatLink,
isAllowedAgentChatUrl,
openResolvedAgentChatUrl,
} from "@/core/agents/chat-link";
import { emptyAgentChatLink } from "@/core/agents/types";
import { appendResolvedRouteParams } from "@/strategy-components/lib/light-app";
import { getStoredAuth } from "@/core/auth";
import { useLiveAccount } from "@/core/auth/use-live-account";
import { useI18n } from "@/core/i18n/hooks";
@@ -92,6 +102,11 @@ interface AgentCardProps {
/** Click the 发布者 line to filter the gallery to that publisher. Receives the
* owner user_id + its desensitized display label. */
onPublisherClick?: (publisher: { id: string; label: string }) => void;
/** Admin console (智能体管理) only: renders the hide/restore eye button.
* Undefined everywhere else, so the gallery never shows it. */
onToggleHidden?: (next: boolean) => void | Promise<void>;
/** Disable the eye button while the admin toggle request is in flight. */
toggleHiddenPending?: boolean;
}
interface BadgeItem {
@@ -203,7 +218,13 @@ function ClampedBadgeRow({ items }: { items: BadgeItem[] }) {
);
}
export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCardProps) {
export function AgentCard({
agent,
layout = "card",
onPublisherClick,
onToggleHidden,
toggleHiddenPending = false,
}: AgentCardProps) {
const isList = layout === "list";
const { t } = useI18n();
const router = useRouter();
@@ -214,9 +235,11 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
const setPrivate = useSetAgentPrivate();
const toggleFavorite = useToggleAgentFavorite();
const togglePin = useToggleAgentPin();
const { skills, isLoading: isSkillsLoading } = useSkills();
const [deleteOpen, setDeleteOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
// The full skill catalog is only needed by the edit dialog. Cards render
// Chinese names from `agent.skill_labels` on the list response.
const { skills, isLoading: isSkillsLoading } = useSkills({ enabled: editOpen });
const [tagPickerOpen, setTagPickerOpen] = useState(false);
const [editName, setEditName] = useState(agent.name);
const [editDescription, setEditDescription] = useState(agent.description ?? "");
@@ -234,6 +257,12 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
const [editSeatSkillDirective, setEditSeatSkillDirective] = useState(
agent.seat_skill_directive ?? false,
);
const [editModelPromptSuffixEnabled, setEditModelPromptSuffixEnabled] = useState(
agent.model_prompt_suffix_enabled ?? true,
);
const [editChatLink, setEditChatLink] = useState<AgentChatLink>(
() => agent.chat_link ?? emptyAgentChatLink(),
);
const [editSquareId, setEditSquareId] = useState(agent.square_id ?? "");
const [publishPickerOpen, setPublishPickerOpen] = useState(false);
const { data: publishSquares } = usePublishSquares();
@@ -282,6 +311,8 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
setSelectedSkills(agent.skills ?? []);
setEditCommonQuestions(normalizeAgentQuestions(agent.common_questions));
setEditSeatSkillDirective(agent.seat_skill_directive ?? false);
setEditModelPromptSuffixEnabled(agent.model_prompt_suffix_enabled ?? true);
setEditChatLink(agent.chat_link ?? emptyAgentChatLink());
}, [
agent.common_questions,
agent.description,
@@ -291,6 +322,8 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
agent.square_id,
agent.skills,
agent.seat_skill_directive,
agent.model_prompt_suffix_enabled,
agent.chat_link,
editOpen,
]);
@@ -306,12 +339,28 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
setEditCommonQuestions(normalizeAgentQuestions(agentDetail.common_questions));
// 列表响应不带 config 额外字段(seat_skill_directive 为 null),详情才有真值。
setEditSeatSkillDirective(agentDetail.seat_skill_directive ?? false);
setEditModelPromptSuffixEnabled(agentDetail.model_prompt_suffix_enabled ?? true);
setEditChatLink(agentDetail.chat_link ?? emptyAgentChatLink());
} else {
setEditSoul(agent.soul ?? "");
}
}, [agent.soul, agentDetail, editOpen]);
function handleChat() {
async function handleChat() {
let link = agent.chat_link;
if (link === undefined) {
try {
link = (await getAgent(agent.id)).chat_link ?? null;
} catch {
link = null;
}
}
const target = canonicalAgentChatLink(link);
if (target && isAllowedAgentChatUrl(target.url)) {
const href = appendResolvedRouteParams(target.url, target.route_params);
openResolvedAgentChatUrl(href, target.open_mode, (path) => router.push(path));
return;
}
router.push(`/page/workspace/agents/${agent.id}/chats/new`);
}
@@ -334,9 +383,11 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
// row to carry the source agent's personality into the copy. Fall back
// to whatever the list happened to include if the detail fetch fails.
let soul = agent.soul ?? "";
let chatLink = canonicalAgentChatLink(agent.chat_link);
try {
const detail = await getAgent(agent.id);
soul = detail.soul ?? soul;
chatLink = canonicalAgentChatLink(detail.chat_link);
} catch {
// keep the list fallback
}
@@ -347,6 +398,7 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
skills: agent.skills ?? [],
model: agent.model ?? null,
tool_groups: agent.tool_groups ?? null,
chat_link: chatLink,
// A copy starts as a private, unpublished draft the owner can refine
// before sharing — never inherit the source's published/private state.
published: false,
@@ -399,6 +451,24 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
request.common_questions = nextQuestions;
if (editSeatSkillDirective !== ((agentDetail?.seat_skill_directive ?? agent.seat_skill_directive) ?? false))
request.seat_skill_directive = editSeatSkillDirective;
if (editModelPromptSuffixEnabled !== ((agentDetail?.model_prompt_suffix_enabled ?? agent.model_prompt_suffix_enabled) ?? true))
request.model_prompt_suffix_enabled = editModelPromptSuffixEnabled;
const nextChatLink = canonicalAgentChatLink(editChatLink);
if (nextChatLink && !isAllowedAgentChatUrl(nextChatLink.url)) {
toast.error("对话链接只支持 http(s) 地址,或以 /、#/ 开头的站内路径");
return;
}
if (
editChatLink.route_params.some((param) => !param.key.trim()) &&
nextChatLink
) {
toast.error("路由参数键名不可为空");
return;
}
const baselineChatLink = agentDetail?.chat_link ?? agent.chat_link;
if (!agentChatLinksEqual(nextChatLink, baselineChatLink)) {
request.chat_link = nextChatLink;
}
if (Object.keys(request).length === 0) {
setEditOpen(false);
@@ -590,6 +660,16 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
私密
</Badge>
)}
{agent.hidden && (
<Badge
variant="outline"
className="border-zinc-500/40 bg-zinc-500/10 text-zinc-600 dark:text-zinc-300 text-xs"
title="已被管理员隐藏:除本管理页外不再展示,但仍可正常使用"
>
<EyeOffIcon className="size-3" />
已隐藏
</Badge>
)}
{agent.featured_order != null && (
<Badge
variant="outline"
@@ -646,15 +726,6 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
</div>
) : null;
// 技能英文名 → 中文名映射,用于把智能体的技能徽章显示为中文(agent.skills 只存英文名)。
const skillNameZhMap = useMemo(() => {
const map = new Map<string, string>();
for (const s of skills) {
if (s.name_zh?.trim()) map.set(s.name, s.name_zh.trim());
}
return map;
}, [skills]);
const skillBadgeItems = [
...(agent.tool_groups ?? []).map((group) => ({
key: `tg:${group}`,
@@ -677,7 +748,7 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
setDetailSkillName(skill);
}}
>
{skillNameZhMap.get(skill) ?? desensitize(skill)}
{agent.skill_labels?.[skill]?.trim() || desensitize(skill)}
</Badge>
),
})),
@@ -783,6 +854,31 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
<ShieldIcon className="h-3.5 w-3.5" />
</Button>
)}
{onToggleHidden && (
<Button
size="icon"
variant="ghost"
className={cn(
"h-8 w-8 shrink-0",
agent.hidden
? "text-zinc-500 hover:text-zinc-600 dark:text-zinc-400"
: "text-zinc-400 hover:text-zinc-500",
)}
onClick={() => void onToggleHidden(!agent.hidden)}
disabled={toggleHiddenPending}
title={
agent.hidden
? "取消隐藏:恢复在广场等列表中展示"
: "隐藏:除本管理页外不再展示,智能体仍可正常使用"
}
>
{agent.hidden ? (
<EyeIcon className="h-3.5 w-3.5" />
) : (
<EyeOffIcon className="h-3.5 w-3.5" />
)}
</Button>
)}
<Button
size="icon"
variant="ghost"
@@ -822,7 +918,7 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
<Button
size="sm"
className={cn(isList ? "shrink-0" : "w-full")}
onClick={handleChat}
onClick={() => void handleChat()}
>
<MessageSquareIcon className="mr-1.5 h-3.5 w-3.5" />
{t.agents.chat}
@@ -831,7 +927,10 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
const cardLayout = (
<Card
className="group flex min-w-0 flex-col transition-shadow hover:shadow-md"
className={cn(
"group flex min-w-0 flex-col transition-shadow hover:shadow-md",
agent.hidden && "opacity-60",
)}
data-agent-guide="agent-card"
>
<CardHeader className="min-w-0 pb-2">
@@ -892,7 +991,10 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
const listLayout = (
<div
className="group flex min-w-0 items-center gap-3 rounded-lg border p-2.5 transition-shadow hover:shadow-sm dark:border-[#213D5E] dark:bg-[#02244C]"
className={cn(
"group flex min-w-0 items-center gap-3 rounded-lg border p-2.5 transition-shadow hover:shadow-sm dark:border-[#213D5E] dark:bg-[#02244C]",
agent.hidden && "opacity-60",
)}
data-agent-guide="agent-card"
>
<div className="agent-avatar bg-primary/10 text-primary flex h-9 w-9 shrink-0 items-center justify-center rounded-lg">
@@ -960,9 +1062,9 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
已选 {selectedSkills.length} 个
</span>
</div>
<SkillTransferSelector
skills={skills}
selected={selectedSkills}
<SkillTransferSelector
skills={skills}
selected={selectedSkills}
onChange={setSelectedSkills}
isLoading={isSkillsLoading}
onViewDetail={setDetailSkillName}
@@ -994,6 +1096,19 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
onChange={setEditCommonQuestions}
/>
</div>
<div className="flex items-center justify-between gap-3 rounded-md border p-3">
<div>
<p className="text-sm font-medium">使用模型追加提示词</p>
<p className="text-muted-foreground text-xs">
默认开启。关闭后,该智能体的问答不会附加管理员为所选模型设置的全局提示词。
</p>
</div>
<Switch
checked={editModelPromptSuffixEnabled}
onCheckedChange={setEditModelPromptSuffixEnabled}
aria-label="使用模型追加提示词"
/>
</div>
<div className="flex items-center justify-between gap-3 rounded-md border p-3">
<div>
<p className="text-sm font-medium">会商技能识别强化</p>
@@ -1074,6 +1189,7 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
}}
/>
</div>
{/* <AgentChatLinkFields value={editChatLink} onChange={setEditChatLink} /> */}
</div>
<DialogFooter>
<Button
@@ -0,0 +1,224 @@
"use client";
import { PlusIcon, XIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import type { AgentChatLink, AgentChatRouteParam } from "@/core/agents/types";
import { emptyAgentChatLink } from "@/core/agents/types";
import {
APP_THEME_COLORS,
LOGIN_SOURCE_OPTIONS,
parseThemeMap,
stringifyThemeMap,
} from "@/strategy-components/lib/light-app";
function newParam(): AgentChatRouteParam {
return {
key: "",
paramType: "login",
source: "access_token",
customValue: "",
themeValue: null,
};
}
export function AgentChatLinkFields({
value,
onChange,
}: {
value: AgentChatLink;
onChange: (next: AgentChatLink) => void;
}) {
const link = value ?? emptyAgentChatLink();
function patch(partial: Partial<AgentChatLink>) {
onChange({ ...link, ...partial });
}
function patchParam(index: number, partial: Partial<AgentChatRouteParam>) {
patch({
route_params: link.route_params.map((param, i) =>
i === index ? { ...param, ...partial } : param,
),
});
}
return (
<div className="space-y-3 rounded-md border p-3">
<div>
<p className="text-sm font-medium">对话跳转</p>
<p className="text-muted-foreground text-xs">
配置后,智能体管理里的「对话」按钮会打开这个地址。留空则仍进入本系统问答。
</p>
</div>
<Input
value={link.url}
onChange={(event) => patch({ url: event.currentTarget.value })}
placeholder="https://... ,或以 / 开头的站内路径"
/>
<div className="space-y-1">
<p className="text-muted-foreground text-xs">打开方式</p>
<Select
value={link.open_mode}
onValueChange={(next) => patch({ open_mode: next === "self" ? "self" : "blank" })}
>
<SelectTrigger className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="blank">新窗口</SelectItem>
<SelectItem value="self">当前窗口</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between gap-2">
<div>
<p className="text-sm font-medium">路由参数</p>
<p className="text-muted-foreground text-xs">
点击「对话」时拼到地址后面。登录参数取当前登录信息,主题参数跟随当前主题。
</p>
</div>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => patch({ route_params: [...link.route_params, newParam()] })}
>
<PlusIcon className="h-3.5 w-3.5" />
添加
</Button>
</div>
{link.route_params.length === 0 ? (
<p className="text-muted-foreground rounded-md border border-dashed px-3 py-3 text-center text-xs">
暂无路由参数
</p>
) : (
<div className="space-y-2">
{link.route_params.map((param, index) => {
const themeMap = param.paramType === "theme" ? parseThemeMap(param.themeValue) : {};
return (
<div key={index} className="space-y-2 rounded-md border p-2">
<div className="flex items-center gap-2">
<Input
value={param.key}
onChange={(event) => patchParam(index, { key: event.currentTarget.value })}
placeholder="参数名"
className="h-8 font-mono text-xs"
/>
<Select
value={param.paramType}
onValueChange={(next) =>
patchParam(index, {
paramType: next === "theme" ? "theme" : "login",
source: next === "login" ? param.source || "access_token" : null,
themeValue:
next === "theme"
? param.themeValue || stringifyThemeMap({})
: null,
})
}
>
<SelectTrigger className="h-8 w-[120px] shrink-0">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="login">登录参数</SelectItem>
<SelectItem value="theme">主题参数</SelectItem>
</SelectContent>
</Select>
<Button
type="button"
variant="ghost"
size="icon"
className="h-8 w-8 shrink-0"
onClick={() =>
patch({
route_params: link.route_params.filter((_, i) => i !== index),
})
}
title="移除参数"
>
<XIcon className="h-4 w-4" />
</Button>
</div>
{param.paramType === "login" && (
<div className="flex items-center gap-2">
<Select
value={param.source || "access_token"}
onValueChange={(next) => patchParam(index, { source: next })}
>
<SelectTrigger className="h-8 min-w-0 flex-1">
<SelectValue />
</SelectTrigger>
<SelectContent>
{LOGIN_SOURCE_OPTIONS.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
{param.source === "other" && (
<Input
value={param.customValue ?? ""}
onChange={(event) =>
patchParam(index, { customValue: event.currentTarget.value })
}
placeholder="自定义值"
className="h-8 w-[140px] text-xs"
/>
)}
</div>
)}
{param.paramType === "theme" && (
<div className="space-y-1.5">
<p className="text-muted-foreground text-[11px]">
各系统主题色跳转时传给目标地址的值
</p>
{APP_THEME_COLORS.map((color) => (
<div key={color.key} className="flex items-center gap-2">
<span className="flex w-[72px] shrink-0 items-center gap-1.5 text-xs">
<span
className="h-2.5 w-2.5 shrink-0 rounded-full"
style={{ backgroundColor: color.dot }}
/>
{color.label}
</span>
<Input
value={themeMap[color.key] ?? color.key}
onChange={(event) =>
patchParam(index, {
themeValue: stringifyThemeMap({
...themeMap,
[color.key]: event.currentTarget.value,
}),
})
}
className="h-7 font-mono text-xs"
/>
</div>
))}
</div>
)}
</div>
);
})}
</div>
)}
</div>
</div>
);
}
@@ -7,6 +7,7 @@ import {
DatabaseIcon,
GlobeIcon,
InfoIcon,
// Link2Icon,
Loader2Icon,
LockIcon,
MessageCircleQuestionIcon,
@@ -25,6 +26,7 @@ import { useRouter } from "next/navigation";
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { toast } from "sonner";
// import { AgentChatLinkFields } from "@/components/workspace/agents/agent-chat-link-fields";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
@@ -59,9 +61,16 @@ import {
useSetAgentFeatured,
useUpdateAgent,
type Agent,
type AgentChatLink,
type AgentQuestion,
type UpdateAgentRequest,
} from "@/core/agents";
import {
agentChatLinksEqual,
canonicalAgentChatLink,
isAllowedAgentChatUrl,
} from "@/core/agents/chat-link";
import { emptyAgentChatLink } from "@/core/agents/types";
import { getStoredAuth } from "@/core/auth";
import { useLiveAccount } from "@/core/auth/use-live-account";
import { isAgentSkillCandidate } from "@/core/skills";
@@ -81,9 +90,11 @@ interface AgentDraft {
published: boolean;
featured: boolean;
templateName: string;
modelPromptSuffixEnabled: boolean;
/** 会商席位「技能识别强化」开关。 */
seatSkillDirective: boolean;
knowledgeBaseIds: string[];
chatLink: AgentChatLink;
}
function draftFromAgent(agent: Agent): AgentDraft {
@@ -96,8 +107,10 @@ function draftFromAgent(agent: Agent): AgentDraft {
published: agent.published,
featured: agent.featured_order != null,
templateName: agent.template_name ?? "",
modelPromptSuffixEnabled: agent.model_prompt_suffix_enabled ?? true,
seatSkillDirective: agent.seat_skill_directive ?? false,
knowledgeBaseIds: agent.llmwiki_knowledge_base_ids ?? [],
chatLink: agent.chat_link ?? emptyAgentChatLink(),
};
}
@@ -367,8 +380,22 @@ export function AgentDetailPanel({
if (draft.soul !== (agent.soul ?? "")) request.soul = draft.soul;
if (draft.templateName.trim() !== (agent.template_name ?? ""))
request.template_name = draft.templateName.trim();
if (draft.modelPromptSuffixEnabled !== (agent.model_prompt_suffix_enabled ?? true))
request.model_prompt_suffix_enabled = draft.modelPromptSuffixEnabled;
if (draft.seatSkillDirective !== (agent.seat_skill_directive ?? false))
request.seat_skill_directive = draft.seatSkillDirective;
const nextChatLink = canonicalAgentChatLink(draft.chatLink);
if (nextChatLink && !isAllowedAgentChatUrl(nextChatLink.url)) {
toast.error("对话链接只支持 http(s) 地址,或以 /、#/ 开头的站内路径");
return;
}
if (draft.chatLink.route_params.some((param) => !param.key.trim()) && nextChatLink) {
toast.error("路由参数键名不可为空");
return;
}
if (!agentChatLinksEqual(nextChatLink, agent.chat_link)) {
request.chat_link = nextChatLink;
}
if (
JSON.stringify(draft.knowledgeBaseIds) !==
JSON.stringify(agent.llmwiki_knowledge_base_ids ?? [])
@@ -663,6 +690,13 @@ export function AgentDetailPanel({
</div>
{/* 入库模板名 — view mode shows a hint row when configured. */}
{/* {!editing && agent.chat_link?.url?.trim() && (
<div className="text-muted-foreground mt-2 flex items-center gap-1 text-xs">
<Link2Icon className="size-3 shrink-0" />
对话跳转:{agent.chat_link.open_mode === "self" ? "当前窗口" : "新窗口"}
</div>
)} */}
{!editing && agent.template_name?.trim() && (
<div className="text-muted-foreground mt-2 flex items-center gap-1 text-xs">
<UploadCloudIcon className="size-3 shrink-0" />
@@ -702,6 +736,21 @@ export function AgentDetailPanel({
}
variant="panel"
/>
<div className="bg-background/60 flex items-center justify-between rounded-lg border px-3 py-2">
<div className="pr-3">
<p className="text-sm font-medium">使用模型追加提示词</p>
<p className="text-muted-foreground text-xs">
默认开启。关闭后,该智能体的问答不会附加管理员为所选模型设置的全局提示词。
</p>
</div>
<Switch
checked={draft.modelPromptSuffixEnabled}
onCheckedChange={(checked) =>
setDraft({ ...draft, modelPromptSuffixEnabled: checked })
}
aria-label="使用模型追加提示词"
/>
</div>
<div className="bg-background/60 flex items-center justify-between rounded-lg border px-3 py-2">
<div className="pr-3">
<p className="text-sm font-medium">会商技能识别强化</p>
@@ -948,6 +997,13 @@ export function AgentDetailPanel({
/>
</Section>
{/* {editing && draft && (
<AgentChatLinkFields
value={draft.chatLink}
onChange={(chatLink) => setDraft({ ...draft, chatLink })}
/>
)} */}
{/* ── 技能列表下方插槽(8BF 产物提交 position 等)────────────────── */}
{belowSkillsSlot}
@@ -1,6 +1,6 @@
"use client";
import { ArrowDownUpIcon, BotIcon, Compass, Loader2, LockIcon, PlusIcon, ShieldIcon, XIcon } from "lucide-react";
import { ArrowDownUpIcon, BotIcon, Compass, Loader2, LockIcon, PlusIcon, RefreshCwIcon, ShieldIcon, XIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { toast } from "sonner";
@@ -13,7 +13,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { TagSearchBar } from "@/components/workspace/tags/tag-search-bar";
import { ViewModeToggle } from "@/components/workspace/view-mode-toggle";
import { getStoredAuth } from "@/core/auth";
import { useAgentsPaginated, usePrivateAgentsPaginated } from "@/core/agents";
import { useAgentsPaginated, usePrivateAgentsPaginated, useSyncAgentDirectory } from "@/core/agents";
import type { Agent, AgentSort } from "@/core/agents";
import { useI18n } from "@/core/i18n/hooks";
import { useRouteBase } from "@/core/route-base";
@@ -54,6 +54,7 @@ export function AgentGallery({
const sentimentAgentVisible = isSentimentAgentVisible();
// 「内置智能体」筛选仅管理员可见(后端 scope=builtin 也做了 admin 闸门兜底)。
const isAdmin = getStoredAuth()?.system_role === "admin";
const syncDirectory = useSyncAgentDirectory();
const [viewMode, setViewMode] = useViewMode("agent");
const [activeTab, setActiveTab] = useState<string>("mine");
const [search, setSearch] = useState("");
@@ -460,6 +461,33 @@ export function AgentGallery({
</p>
</div>
<div className="flex items-center gap-2">
{isAdmin && (
<Button
variant="outline"
size="sm"
title="扫描 .deer-flow/agents 目录,把目录里的智能体同步进列表"
disabled={syncDirectory.isPending}
onClick={() => {
void syncDirectory.mutateAsync().then(
(result) => {
toast.success(
result.scanned > 0
? `已扫描并同步 ${result.scanned} 个目录智能体`
: "目录里没有可同步的智能体",
);
},
(err: unknown) => {
toast.error(err instanceof Error ? err.message : "扫描智能体目录失败");
},
);
}}
>
<RefreshCwIcon
className={`mr-1.5 h-4 w-4 ${syncDirectory.isPending ? "animate-spin" : ""}`}
/>
{syncDirectory.isPending ? "扫描中…" : "重新扫描智能体目录"}
</Button>
)}
<Button
variant="outline"
size="sm"
@@ -53,8 +53,8 @@ export function AgentManageDialog({
open,
onOpenChange,
}: AgentManageDialogProps) {
const { agents, isLoading } = useAgentSelector();
const { agents: allAgents } = useAgents();
const { agents, isLoading } = useAgentSelector({ enabled: open });
const { agents: allAgents } = useAgents({ enabled: open });
const setFeaturedMutation = useSetAgentFeatured();
const reorderMutation = useReorderFeaturedAgents();
const [pickerOpen, setPickerOpen] = useState(false);
@@ -21,7 +21,7 @@ import {
import { PromptInputButton } from "@/components/ai-elements/prompt-input";
import { AgentManageDialog } from "@/components/workspace/agents/agent-manage-dialog";
import { Tooltip } from "@/components/workspace/tooltip";
import { useAgentSelector, useAgentsPaginated } from "@/core/agents";
import { useAgent, useAgentSelector } from "@/core/agents";
import type { Agent } from "@/core/agents";
import { getStoredAuth } from "@/core/auth";
import { desensitize } from "@/lib/desensitize";
@@ -59,22 +59,19 @@ export function AgentSelector({
}: AgentSelectorProps) {
const [open, setOpen] = useState(false);
const [manageOpen, setManageOpen] = useState(false);
const { agents, isLoading } = useAgentSelector();
// 弹窗列表只展示管理弹窗里配置的 agent(agents);但「已选中 agent」的名称解析要更宽——
// 侧边栏「常用智能体」可以选中未配置进管理弹窗的 agent(如用户自己的智能体),
// 这些 agent 也要能在胶囊上显示名称,故额外用「我的 / 广场」列表兜底解析(缓存与侧边栏共享)。
const { agents: mineAgents } = useAgentsPaginated({ scope: "mine", page: 1, pageSize: 20 });
const { agents: squareAgents } = useAgentsPaginated({ scope: "square", page: 1, pageSize: 20 });
const { agents, isLoading } = useAgentSelector({ enabled: open });
// Resolve a remembered personal agent with a single detail lookup instead of
// preloading both complete homepage gallery pages.
const { agent: selectedAgentDetail } = useAgent(selectedAgentId, {
enabled: !!selectedAgentId,
retry: false,
});
const isAdmin = useMemo(() => getStoredAuth()?.system_role === "admin", []);
const selectedAgent = useMemo<Agent | null>(() => {
if (!selectedAgentId) return null;
return (
[...agents, ...mineAgents, ...squareAgents].find(
(a) => a.id === selectedAgentId,
) ?? null
);
}, [agents, mineAgents, squareAgents, selectedAgentId]);
return agents.find((a) => a.id === selectedAgentId) ?? selectedAgentDetail;
}, [agents, selectedAgentDetail, selectedAgentId]);
const handleSelect = (agent: Agent) => {
onAgentChange(agent.id);
@@ -362,11 +362,27 @@ export function ArtifactFileDetail({
isMock,
writeFileInFlight,
]);
/** write_file 流式预览走 tool args 文本;图片等二进制产物始终走 artifacts API;
* 圆桌结束后可编辑的 md(editVirtualMarkdown)亦回到真实 API(可加载 + PATCH 保存)。 */
const isVirtualHtmlArtifact = useMemo(() => {
if (!isWriteFileVirtual) return false;
return (writeFileLanguageHint ?? checkCodeFile(filepath).language) === "html";
}, [filepath, isWriteFileVirtual, writeFileLanguageHint]);
/** write_file 流式阶段走 tool args 文本;图片等二进制产物始终走 artifacts API;
* HTML 写完后也必须切回真实文件,因为后续渲染脚本可能在同一路径覆盖最终数据;
* 圆桌结束后可编辑的 md(editVirtualMarkdown)同样回到真实 API(可加载 + PATCH 保存)。 */
const useWriteFileStreaming = useMemo(() => {
return isWriteFileVirtual && !isImageFile(filepath) && !editVirtualMarkdown;
}, [filepath, isWriteFileVirtual, editVirtualMarkdown]);
return (
isWriteFileVirtual &&
!isImageFile(filepath) &&
!editVirtualMarkdown &&
(!isVirtualHtmlArtifact || writeFileInFlight)
);
}, [
filepath,
isWriteFileVirtual,
editVirtualMarkdown,
isVirtualHtmlArtifact,
writeFileInFlight,
]);
const { isCodeFile, language } = useMemo(() => {
if (useWriteFileStreaming) {
let nextLanguage =
@@ -398,11 +414,10 @@ export function ArtifactFileDetail({
refetch: refetchArtifactContent,
} = useArtifactContent({
threadId,
// editVirtualMarkdown:用解码后的真实路径走 artifacts API(而非 write-file 虚拟
// URL),这样保存后 useUpdateArtifactContent 写入的查询缓存才能命中,编辑内容
// 不会被旧的内存 stub 值覆盖回退。
filepath:
editVirtualMarkdown || !isWriteFileVirtual ? filepath : filepathFromProps,
// 流式结束后统一用解码后的真实路径走 artifacts API(而非 write-file 虚拟
// URL)。HTML 可能已被后续渲染脚本覆盖;Markdown 保存后的查询缓存也需要
// 命中真实路径,不能继续读取旧的内存 stub。
filepath: useWriteFileStreaming ? filepathFromProps : filepath,
enabled: isCodeFile && !useWriteFileStreaming,
});
@@ -458,9 +473,10 @@ export function ArtifactFileDetail({
const sandboxDisplayText = useMemo(() => {
const raw = displayContent ?? "";
if (disableDesensitize) return raw;
if (language === "html") return raw;
if (streamPerfEnabled && isLiveStreaming) return raw;
return desensitize(raw);
}, [disableDesensitize, displayContent, isLiveStreaming, streamPerfEnabled]);
}, [disableDesensitize, displayContent, isLiveStreaming, language, streamPerfEnabled]);
const artifactContentPending =
isCodeFile &&
!useWriteFileStreaming &&
@@ -2205,6 +2221,7 @@ export function ArtifactFilePreview({
if (language === "html") {
return (
<iframe
key={htmlPreviewUrl ?? "html-preview"}
className={cn(
"size-full bg-white",
animated && "animate-[sandbox-preview-enter_320ms_ease-out]",
@@ -171,7 +171,14 @@ const ChatBox: React.FC<{
const referencesEnabled = ragModeEnabled || hasFrontendRag;
const shouldFetchBackendReferenceBatches =
referencesEnabled && !hasFrontendRag && !!threadId && threadId !== "new";
const { skills } = useSkills();
const hasThreadMessages = (thread.values.messages?.length ?? 0) > 0;
const { skills } = useSkills({
enabled:
referencesEnabled &&
!!threadId &&
threadId !== "new" &&
(hasThreadMessages || thread.isLoading),
});
const canScanArtifactDirectory =
(artifactDirectoryModeEnabled || !!requestedArtifact || !!preferredArtifact) &&
@@ -1,12 +1,11 @@
"use client";
import { useState } from "react";
import { useTheme } from "@/contexts/ThemeContext";
import { getWelcomeBrandAsset } from "@/core/branding/brand-assets";
import { AppBrandImage } from "@/core/branding/app-brand-image";
import { useDisplayDesensitizer } from "@/core/sensitive-words/use-display-desensitizer";
import { useAppSystemName } from "@/core/system-settings/hooks";
import { readRuntimeFlag } from "@/env";
import { cn } from "@/lib/utils";
import { useDisplayDesensitizer } from "@/core/sensitive-words/use-display-desensitizer";
/**
* 紧凑模式(正常 App)新对话落地页的品牌欢迎块 —— 按 CM-assistant 参考图重画。
@@ -16,11 +15,8 @@ import { useDisplayDesensitizer } from "@/core/sensitive-words/use-display-desen
export function CompactWelcome({ className }: { className?: string }) {
const desensitizeText = useDisplayDesensitizer();
const { theme } = useTheme();
const brandTheme = theme;
const welcomeLogo = getWelcomeBrandAsset(brandTheme);
const [failedWelcomeLogo, setFailedWelcomeLogo] = useState<string | null>(null);
const shouldShowWelcomeLogo =
Boolean(welcomeLogo) && failedWelcomeLogo !== welcomeLogo;
const systemName = useAppSystemName("");
const welcomeTitle = systemName ? `欢迎使用${systemName}` : "欢迎使用CM助手";
const isWelcomeLogoVisible = readRuntimeFlag("VITE_WELCOME_LOGO_VISIBLE");
return (
@@ -30,44 +26,24 @@ export function CompactWelcome({ className }: { className?: string }) {
className,
)}
>
{/* CM logo:浅底圆环 + 主色渐变圆角方块 */}
{/* 与全量模式共用同一套系统 Logo;简洁模式仅保留欢迎区的展示容器。 */}
{/* Controlled by VITE_WELCOME_LOGO_VISIBLE in runtime-config.js. */}
{isWelcomeLogoVisible && (
<div
className="mb-3.5 inline-flex items-center justify-center rounded-full p-3"
style={{
backgroundColor:
"rgb(var(--legacy-workspace-brand-rgb) / 5%)",
border:
"1px solid rgb(var(--legacy-workspace-brand-rgb) / 12%)",
}}
>
{shouldShowWelcomeLogo && welcomeLogo ? (
<img
src={welcomeLogo}
alt=""
aria-hidden="true"
className="size-16 object-contain"
onError={() => setFailedWelcomeLogo(welcomeLogo)}
/>
) : (
<div
className="flex size-14 items-center justify-center rounded-2xl shadow-md"
style={{
backgroundImage:
"linear-gradient(to top right, var(--workspace-brand), var(--brand-200))",
}}
>
<span className="text-2xl font-black tracking-wide text-white italic">
{desensitizeText("CM")}
</span>
</div>
)}
</div>
<div
className="mb-3.5 inline-flex items-center justify-center rounded-full p-3"
style={{
backgroundColor:
"rgb(var(--legacy-workspace-brand-rgb) / 5%)",
border:
"1px solid rgb(var(--legacy-workspace-brand-rgb) / 12%)",
}}
>
<AppBrandImage theme={theme} className="size-16 object-contain" />
</div>
)}
<h1 className="flex items-center justify-center text-2xl font-bold tracking-tight text-foreground/90">
{desensitizeText("欢迎使用CM助手")}
{desensitizeText(welcomeTitle)}
</h1>
<p className="text-muted-foreground mx-auto mt-2 max-w-sm text-xs leading-relaxed">
基于先进深度推理模型,为您提供高效的市场分析、专业报告撰写、调研设计与协同脑暴支持。
@@ -0,0 +1,43 @@
"use client";
import { FileSpreadsheet } from "lucide-react";
import { useCallback } from "react";
import { Button } from "@/components/ui/button";
import { consumerThreadMaterialsDownloadUrl } from "@/core/threads/consumer-thread-values-client";
import { useThread } from "./messages/context";
import { Tooltip } from "./tooltip";
/** Downloads the Consumer-maintained source-material workbook for this chat. */
export function ConsumerMaterialsExportTrigger({
threadId,
}: {
threadId: string;
}) {
const { thread } = useThread();
const downloadUrl = consumerThreadMaterialsDownloadUrl(threadId);
const handleDownload = useCallback(() => {
if (!downloadUrl) return;
window.open(downloadUrl, "_blank", "noopener,noreferrer");
}, [downloadUrl]);
if (thread.messages.length === 0) return null;
return (
<Tooltip
content={downloadUrl ? "导出本对话检索资料" : "未配置资料导出服务"}
>
<Button
type="button"
className="text-muted-foreground hover:text-foreground"
variant="ghost"
disabled={!downloadUrl}
onClick={handleDownload}
>
<FileSpreadsheet />
导出资料
</Button>
</Tooltip>
);
}
@@ -194,7 +194,7 @@ function ManagePromptsDialog({
const createPrompt = useCreateCustomPrompt();
const updatePrompt = useUpdateCustomPrompt();
const deletePrompt = useDeleteCustomPrompt();
const { agents } = useAgentSelector();
const { agents } = useAgentSelector({ enabled: open });
const preferences = useUserPreferences();
const updatePreferences = useUpdateUserPreferences();
const [editingId, setEditingId] = useState<string | null>(null);
@@ -3,7 +3,6 @@
import { Bot, ChevronRight } from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useMemo } from "react";
import {
SidebarGroup,
@@ -13,12 +12,10 @@ import {
SidebarMenuButton,
SidebarMenuItem,
} from "@/components/ui/sidebar";
import { useAgentsPaginated } from "@/core/agents";
import type { Agent } from "@/core/agents";
import { useSidebarAgents } from "@/core/agents";
import { desensitize } from "@/lib/desensitize";
/** 常用智能体最多展示个数(需求 1.2 ②)。 */
const MAX_FREQUENT = 3;
/** 「更多」跳转目标:智能体管理页(需求 1.3)。 */
const MORE_HREF = "/page/strategy/agents";
@@ -40,33 +37,7 @@ function agentHomeHref(agentId: string): string {
*/
export function FrequentAgentsList() {
const pathname = usePathname();
const { agents: mine } = useAgentsPaginated({
scope: "mine",
page: 1,
pageSize: 20,
});
const { agents: square } = useAgentsPaginated({
scope: "square",
page: 1,
pageSize: 20,
});
const frequent = useMemo<Agent[]>(() => {
const out: Agent[] = [];
const seen = new Set<string>();
const add = (agent: Agent | undefined) => {
if (!agent || out.length >= MAX_FREQUENT || seen.has(agent.id)) return;
seen.add(agent.id);
out.push(agent);
};
// 1. 置顶组优先(够 3 个则下面我的/广场都不再补)。
[...mine, ...square].filter((a) => a.is_pinned).forEach(add);
// 2. 我的智能体补足。
mine.forEach(add);
// 3. 广场默认推荐补足。
square.forEach(add);
return out;
}, [mine, square]);
const { agents: frequent } = useSidebarAgents();
if (frequent.length === 0) {
return null;
@@ -68,7 +68,7 @@ import {
MyProjectThreadBadge,
MyProjectThreadIcon,
} from "@/components/workspace/my-project-thread-indicator";
import { useAgentsPaginated, type Agent } from "@/core/agents";
import { useAgentsPaginated, useSidebarAgents, type Agent } from "@/core/agents";
import { getAPIClient } from "@/core/api";
import { useI18n } from "@/core/i18n/hooks";
import {
@@ -112,9 +112,6 @@ import {
import { agentColor } from "./agent-icon-color";
import { SidebarCollapseButton } from "./workspace-header";
/** 常用智能体最多展示个数。 */
const MAX_FREQUENT = 4;
// 智能体图标配色(按 id 稳定散列、分主题)抽到共享模块 ./agent-icon-color,
// 与 zzJC/zzXD 模块左栏(AgentModuleSidebar)共用,保证彩色卡片配色完全一致。
@@ -156,7 +153,7 @@ function SectionLabel({
);
}
type CommonAgent = Pick<Agent, "id" | "name" | "description">;
type CommonAgent = Pick<Agent, "id" | "name"> & { description?: string };
/** wx 左栏固定的智能体类型;南京-db 广场尚未创建时筛空列表。 */
const WX_AGENT_TYPE_MINE = "mine";
@@ -253,19 +250,9 @@ export function GeneralQaSidebar({
return !v;
});
// ── 常用智能体取数:wx 走类型筛选;其它页面仍是置顶 → 我的 → 广场 ──
const { agents: mine } = useAgentsPaginated({
scope: "mine",
page: 1,
pageSize: 20,
enabled: !wxCommonAgents,
});
const { agents: square } = useAgentsPaginated({
scope: "square",
page: 1,
pageSize: 20,
enabled: !wxCommonAgents,
});
// The ordinary full-page sidebar only needs three id/name rows. WX-specific
// catalog pages keep their richer, filtered result below.
const { agents: sidebarAgents } = useSidebarAgents({ enabled: !wxCommonAgents });
const {
agents: wxAgents,
total: wxTotal,
@@ -283,18 +270,8 @@ export function GeneralQaSidebar({
if (wxCommonAgents) {
return wxFetchEnabled ? wxAgents : [];
}
const out: Agent[] = [];
const seen = new Set<string>();
const add = (agent: Agent | undefined) => {
if (!agent || out.length >= MAX_FREQUENT || seen.has(agent.id)) return;
seen.add(agent.id);
out.push(agent);
};
[...mine, ...square].filter((a) => a.is_pinned).forEach(add);
mine.forEach(add);
square.forEach(add);
return out;
}, [mine, square, wxAgents, wxCommonAgents, wxFetchEnabled]);
return sidebarAgents;
}, [sidebarAgents, wxAgents, wxCommonAgents, wxFetchEnabled]);
const wxEmptyHint =
wxAgentType === WX_AGENT_TYPE_NANJING_DB && !wxSquareId
? "该类型暂无智能体"
@@ -641,7 +618,7 @@ export function GeneralQaSidebar({
: "text-muted-foreground",
)}
>
{agent.description ? desensitize(agent.description) : "智能体助手"}
{wxCommonAgents && agent.description ? desensitize(agent.description) : "智能体助手"}
</span>
</span>
{isActive && (
@@ -1,10 +1,10 @@
"use client";
import type { ChatStatus } from "ai";
import { toast } from "sonner";
import {
import type { ChatStatus } from "ai";
import { toast } from "sonner";
import {
BookMarkedIcon,
BrainCircuitIcon,
BrainCircuitIcon,
CheckIcon,
FileTextIcon,
FolderTreeIcon,
@@ -26,6 +26,7 @@ import {
useRef,
useState,
type ComponentProps,
type CSSProperties,
type ReactNode,
} from "react";
@@ -63,23 +64,22 @@ import {
DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import { apiFetch } from "@/core/api";
import { getBackendBaseURL } from "@/core/config";
import {
isDocumentRewriteActiveStage,
useDocumentRewritePresentation,
} from "@/core/document-rewrite/context";
import { useI18n } from "@/core/i18n/hooks";
import { composerMinHeightCss } from "@/core/settings/composer-width";
import { getBackendBaseURL } from "@/core/config";
import {
isDocumentRewriteActiveStage,
useDocumentRewritePresentation,
} from "@/core/document-rewrite/context";
import { useI18n } from "@/core/i18n/hooks";
import { isHiddenFromUIMessage } from "@/core/messages/utils";
import { useModels } from "@/core/models/hooks";
import {
REASONING_EFFORTS,
resolveModelReasoningEffort,
type ReasoningEffort,
type StoredReasoningEffort,
} from "@/core/models/reasoning-effort";
import type { Model } from "@/core/models/types";
import type { AgentThreadContext } from "@/core/threads";
import type { KnowledgeRetrievalMode } from "@/core/threads/knowledge-retrieval-mode";
import type { KnowledgeRetrievalMode } from "@/core/threads/knowledge-retrieval-mode";
import { textOfMessage } from "@/core/threads/utils";
import { desensitize } from "@/lib/desensitize";
import { cn } from "@/lib/utils";
@@ -105,19 +105,19 @@ import {
import { useRecommendedQuestions } from "@/core/recommended-questions/hooks";
import { useUserPreferences } from "@/core/user-preferences";
import {
isThreadRagModeLocked,
lockThreadRagMode,
useLocalSettings,
} from "@/core/settings";
import { useCitationDisplaySettings } from "@/core/system-settings/hooks";
import { CustomPromptBar } from "./custom-prompt-menu";
import { resolveInputMode, type InputMode } from "./input-mode";
import { hasPromptInputPayload } from "./input-box-submit";
import { useThread } from "./messages/context";
import { ModeHoverGuide } from "./mode-hover-guide";
import { Tooltip } from "./tooltip";
import {
isThreadRagModeLocked,
lockThreadRagMode,
useLocalSettings,
} from "@/core/settings";
import { useCitationDisplaySettings } from "@/core/system-settings/hooks";
import { CustomPromptBar } from "./custom-prompt-menu";
import { resolveInputMode, type InputMode } from "./input-mode";
import { hasPromptInputPayload } from "./input-box-submit";
import { useThread } from "./messages/context";
import { ModeHoverGuide } from "./mode-hover-guide";
import { Tooltip } from "./tooltip";
export function InputBox({
className,
@@ -128,22 +128,23 @@ export function InputBox({
extraHeader,
isNewThread,
threadId,
initialValue,
onContextChange,
onFollowupsPresenceChange,
followupsDisplayAllowed = true,
onSubmit,
initialValue,
onContextChange,
onFollowupsPresenceChange,
followupsDisplayAllowed = true,
onSubmit,
onStop,
promptPrefix,
agentSelector,
knowledgeSelector,
knowledgeRetrieval,
knowledgeSuggestedQuestions = [],
knowledgeSelector,
knowledgeRetrieval,
knowledgeSuggestedQuestions = [],
extraModels = [],
assistantId,
hideAdminRecommendedQuestions,
compact,
hideContextTools,
composerHeightPercent,
...props
}: Omit<ComponentProps<typeof PromptInput>, "onSubmit"> & {
assistantId?: string | null;
@@ -151,9 +152,14 @@ export function InputBox({
/** 紧凑模式(正常 App)新对话落地态:去掉旋转彩边、用 CM 参考图的白卡输入框,
* 并在推荐问题上方加「试试这些高频业务场景」标题。仅落地态生效,默认 false。 */
compact?: boolean;
/** 隐藏输入框工具条上的「写作 / 参考文献」上下文开关按钮(任务深链工作区等
/** 隐藏输入框工具条上的「写作 / 参考文献」上下文开关按钮(任务深链工作区等
* 受控场景用;文件/模型等其他按钮不受影响)。 */
hideContextTools?: boolean;
/**
* Appearance height scale. 100 (or omitted) keeps the built-in min-height.
* Other values scale the landing / compact-landing / conversation base.
*/
composerHeightPercent?: number;
disabled?: boolean;
context: Omit<
AgentThreadContext,
@@ -179,15 +185,15 @@ export function InputBox({
reasoning_effort?: StoredReasoningEffort;
writing_mode?: boolean;
},
) => void;
/**
* Whether generated follow-up questions may be rendered. Hosts with a
* scrollable transcript disable this while the user is reviewing history;
* the generated questions are retained and reappear on returning to bottom.
*/
followupsDisplayAllowed?: boolean;
/** Reports whether follow-ups need layout space, even while scroll-hidden. */
onFollowupsPresenceChange?: (present: boolean) => void;
) => void;
/**
* Whether generated follow-up questions may be rendered. Hosts with a
* scrollable transcript disable this while the user is reviewing history;
* the generated questions are retained and reappear on returning to bottom.
*/
followupsDisplayAllowed?: boolean;
/** Reports whether follow-ups need layout space, even while scroll-hidden. */
onFollowupsPresenceChange?: (present: boolean) => void;
onSubmit?: (message: PromptInputMessage) => void;
onStop?: () => void;
/**
@@ -209,19 +215,16 @@ export function InputBox({
selectedAgentId: string | null;
onAgentChange: (agentId: string | null) => void;
};
/** WeKnora-style knowledge-space picker rendered inside the composer toolbar. */
knowledgeSelector?: ReactNode;
/** Per-thread ordinary-knowledge retrieval mode. Omit when unavailable. */
knowledgeRetrieval?: {
mode: KnowledgeRetrievalMode;
smartAvailable: boolean;
smartAvailabilityReason: string;
/** The administrator policy used only when a new conversation is created. */
smartIsDefault: boolean;
onModeChange: (mode: KnowledgeRetrievalMode) => void;
};
/** High-value starter questions derived from the currently selected spaces. */
knowledgeSuggestedQuestions?: string[];
/** WeKnora-style knowledge-space picker rendered inside the composer toolbar. */
knowledgeSelector?: ReactNode;
/** Per-thread ordinary-knowledge retrieval mode. Omit when unavailable. */
knowledgeRetrieval?: {
mode: KnowledgeRetrievalMode;
smartAvailable: boolean;
onModeChange: (mode: KnowledgeRetrievalMode) => void;
};
/** High-value starter questions derived from the currently selected spaces. */
knowledgeSuggestedQuestions?: string[];
/** Page-scoped model choices implemented outside the DeerFlow model API. */
extraModels?: Model[];
}) {
@@ -238,26 +241,26 @@ export function InputBox({
const modelOptions = useMemo(() => {
return singleRoundRagActive ? extraModels : models;
}, [extraModels, models, singleRoundRagActive]);
const { thread, isMock } = useThread();
const rewritePresentation = useDocumentRewritePresentation();
const { textInput } = usePromptInputController();
const promptRootRef = useRef<HTMLDivElement | null>(null);
const { data: citationDisplay } = useCitationDisplaySettings();
const referenceModeEntryEnabled =
citationDisplay?.reference_mode_enabled ?? false;
const documentRewriteActive = useMemo(
() =>
rewritePresentation?.forThread(threadId).some((item) =>
isDocumentRewriteActiveStage(item.stage),
) ?? false,
[rewritePresentation, threadId],
);
// Keep normal chat generation authoritative when both states overlap. In
// the usual rewrite-only case this gives the composer the same square stop
// affordance as a normal streamed reply.
const composerStatus: ChatStatus = documentRewriteActive
? "streaming"
: status;
const { thread, isMock } = useThread();
const rewritePresentation = useDocumentRewritePresentation();
const { textInput } = usePromptInputController();
const promptRootRef = useRef<HTMLDivElement | null>(null);
const { data: citationDisplay } = useCitationDisplaySettings();
const referenceModeEntryEnabled =
citationDisplay?.reference_mode_enabled ?? false;
const documentRewriteActive = useMemo(
() =>
rewritePresentation?.forThread(threadId).some((item) =>
isDocumentRewriteActiveStage(item.stage),
) ?? false,
[rewritePresentation, threadId],
);
// Keep normal chat generation authoritative when both states overlap. In
// the usual rewrite-only case this gives the composer the same square stop
// affordance as a normal streamed reply.
const composerStatus: ChatStatus = documentRewriteActive
? "streaming"
: status;
const [followups, setFollowups] = useState<string[]>([]);
const [followupsHidden, setFollowupsHidden] = useState(false);
@@ -273,9 +276,9 @@ export function InputBox({
const { questions: recommendedQuestions } = useRecommendedQuestions();
const userPreferences = useUserPreferences();
const followupsEnabled = userPreferences.followup_suggestions_enabled;
const showAdminRecommendedQuestions =
!hideAdminRecommendedQuestions &&
knowledgeSuggestedQuestions.length === 0 &&
const showAdminRecommendedQuestions =
!hideAdminRecommendedQuestions &&
knowledgeSuggestedQuestions.length === 0 &&
!userPreferences.hide_admin_prompt_prefix &&
recommendedQuestions.length > 0;
@@ -294,11 +297,12 @@ export function InputBox({
const supportsReasoningEffort =
fallbackModel.supports_reasoning_effort ?? false;
const nextModelName = fallbackModel.name;
const nextMode = resolveInputMode(context.mode, supportsThinking);
const nextMode = resolveInputMode(context.mode, supportsThinking);
const nextReasoningEffort = resolveModelReasoningEffort(
supportsReasoningEffort,
context.reasoning_effort,
context.model_name !== nextModelName,
fallbackModel.default_reasoning_effort,
);
if (
@@ -344,26 +348,11 @@ export function InputBox({
resolveModelReasoningEffort(
supportReasoningEffort,
context.reasoning_effort,
false,
selectedModel?.default_reasoning_effort,
),
[context.reasoning_effort, supportReasoningEffort],
[context.reasoning_effort, selectedModel?.default_reasoning_effort, supportReasoningEffort],
);
const reasoningEffortIndex = Math.max(
0,
REASONING_EFFORTS.indexOf(selectedReasoningEffort ?? "xhigh"),
);
const reasoningEffortThumbLeft =
reasoningEffortIndex === 0
? "0.5rem"
: reasoningEffortIndex === 1
? "50%"
: "calc(100% - 0.5rem)";
const reasoningEffortLabel =
selectedReasoningEffort === "low"
? t.inputBox.reasoningEffortLow
: selectedReasoningEffort === "medium"
? t.inputBox.reasoningEffortMedium
: t.inputBox.reasoningEffortXHigh;
const handleModelSelect = useCallback(
(model_name: string) => {
const model = modelOptions.find((m) => m.name === model_name);
@@ -373,11 +362,12 @@ export function InputBox({
onContextChange?.({
...context,
model_name,
mode: resolveInputMode(context.mode, model.supports_thinking ?? false),
mode: resolveInputMode(context.mode, model.supports_thinking ?? false),
reasoning_effort: resolveModelReasoningEffort(
model.supports_reasoning_effort ?? false,
context.reasoning_effort,
model_name !== context.model_name,
model.default_reasoning_effort,
),
execution_profile: model.execution_profile,
});
@@ -393,13 +383,15 @@ export function InputBox({
onContextChange?.({
...context,
model_name: ordinaryModel?.name ?? context.model_name,
mode: resolveInputMode(
mode: resolveInputMode(
mode,
ordinaryModel?.supports_thinking ?? supportThinking,
),
reasoning_effort: resolveModelReasoningEffort(
ordinaryModel?.supports_reasoning_effort ?? supportReasoningEffort,
context.reasoning_effort,
false,
ordinaryModel?.default_reasoning_effort,
),
execution_profile: undefined,
});
@@ -424,7 +416,7 @@ export function InputBox({
onContextChange?.({
...context,
model_name: ragModel.name,
mode: resolveInputMode(
mode: resolveInputMode(
context.mode,
ragModel.supports_thinking ?? false,
),
@@ -439,16 +431,6 @@ export function InputBox({
});
}, [context, onContextChange]);
const handleReasoningEffortSelect = useCallback(
(effort: ReasoningEffort) => {
onContextChange?.({
...context,
reasoning_effort: effort,
});
},
[onContextChange, context],
);
const handleWritingModeToggle = useCallback(() => {
onContextChange?.({
...context,
@@ -464,13 +446,13 @@ export function InputBox({
});
}, [artifactDirectoryModeEnabled, setLocalSettings]);
const smartKnowledgeRetrievalActive =
knowledgeRetrieval?.mode === "smart_reasoning";
const ragModeLocked =
!smartKnowledgeRetrievalActive && isThreadRagModeLocked(threadId);
const ragModeEnabled =
!smartKnowledgeRetrievalActive &&
(localSettings.display.ragModeEnabled || ragModeLocked);
const smartKnowledgeRetrievalActive =
knowledgeRetrieval?.mode === "smart_reasoning";
const ragModeLocked =
!smartKnowledgeRetrievalActive && isThreadRagModeLocked(threadId);
const ragModeEnabled =
!smartKnowledgeRetrievalActive &&
(localSettings.display.ragModeEnabled || ragModeLocked);
const handleRagModeToggle = useCallback(() => {
if (ragModeLocked) {
return;
@@ -486,19 +468,19 @@ export function InputBox({
});
}, [contextCompressionEnabled, setLocalSettings]);
const handleSubmit = useCallback(
async (message: PromptInputMessage) => {
if (composerStatus === "streaming") {
toast.info("正在生成中,请等待当前回复完成后再发送。", {
description: "已保留您输入的内容。",
});
// Reject rather than resolve: PromptInput treats a resolved submit as
// accepted and clears its draft. The current message has not been sent.
throw new Error("Cannot submit while a response is streaming.");
}
if (!hasPromptInputPayload(message)) {
return;
}
const handleSubmit = useCallback(
async (message: PromptInputMessage) => {
if (composerStatus === "streaming") {
toast.info("正在生成中,请等待当前回复完成后再发送。", {
description: "已保留您输入的内容。",
});
// Reject rather than resolve: PromptInput treats a resolved submit as
// accepted and clears its draft. The current message has not been sent.
throw new Error("Cannot submit while a response is streaming.");
}
if (!hasPromptInputPayload(message)) {
return;
}
setFollowups([]);
setFollowupsHidden(false);
setFollowupsLoading(false);
@@ -516,7 +498,7 @@ export function InputBox({
onContextChange?.({
...context,
model_name: resolvedModelName,
mode: resolveInputMode(
mode: resolveInputMode(
context.mode,
selectedModel?.supports_thinking ?? false,
),
@@ -531,15 +513,14 @@ export function InputBox({
},
[
context,
onContextChange,
onSubmit,
composerStatus,
resolvedModelName,
onContextChange,
onSubmit,
composerStatus,
resolvedModelName,
ragModeEnabled,
selectedModel?.supports_thinking,
selectedModel?.execution_profile,
selectedReasoningEffort,
status,
threadId,
],
);
@@ -562,9 +543,24 @@ export function InputBox({
form?.requestSubmit();
}, []);
const handleFollowupClick = useCallback(
(suggestion: string) => {
if (composerStatus === "streaming") {
const fillPromptForEditing = useCallback(
(prompt: string) => {
textInput.setInput(prompt);
setFollowupsHidden(true);
// Wait for the controlled textarea to receive the inserted value before
// focusing it, so the user can review and edit before sending.
setTimeout(() => {
promptRootRef.current
?.querySelector<HTMLTextAreaElement>("textarea[name='message']")
?.focus();
}, 0);
},
[textInput],
);
const handleFollowupClick = useCallback(
(suggestion: string) => {
if (composerStatus === "streaming") {
return;
}
const current = (textInput.value ?? "").trim();
@@ -577,7 +573,7 @@ export function InputBox({
setFollowupsHidden(true);
setTimeout(() => requestFormSubmit(), 0);
},
[composerStatus, requestFormSubmit, textInput],
[composerStatus, requestFormSubmit, textInput],
);
const confirmReplaceAndSend = useCallback(() => {
@@ -608,28 +604,28 @@ export function InputBox({
setTimeout(() => requestFormSubmit(), 0);
}, [pendingSuggestion, requestFormSubmit, textInput]);
const followupsPresent =
const followupsPresent =
followupsEnabled &&
!disabled &&
!isNewThread &&
!selectedSingleRoundRag &&
!followupsHidden &&
(followupsLoading || followups.length > 0);
const showFollowups = followupsDisplayAllowed && followupsPresent;
const followupsPresenceChangeRef = useRef(onFollowupsPresenceChange);
useEffect(() => {
followupsPresenceChangeRef.current = onFollowupsPresenceChange;
}, [onFollowupsPresenceChange]);
useEffect(() => {
followupsPresenceChangeRef.current?.(followupsPresent);
}, [followupsPresent]);
useEffect(() => {
return () => followupsPresenceChangeRef.current?.(false);
}, []);
!disabled &&
!isNewThread &&
!selectedSingleRoundRag &&
!followupsHidden &&
(followupsLoading || followups.length > 0);
const showFollowups = followupsDisplayAllowed && followupsPresent;
const followupsPresenceChangeRef = useRef(onFollowupsPresenceChange);
useEffect(() => {
followupsPresenceChangeRef.current = onFollowupsPresenceChange;
}, [onFollowupsPresenceChange]);
useEffect(() => {
followupsPresenceChangeRef.current?.(followupsPresent);
}, [followupsPresent]);
useEffect(() => {
return () => followupsPresenceChangeRef.current?.(false);
}, []);
useEffect(() => {
if (followupsEnabled) return;
@@ -718,37 +714,46 @@ export function InputBox({
};
}, [context.model_name, disabled, followupsEnabled, isMock, selectedSingleRoundRag, status, thread.messages, threadId]);
const composerMinHeight = composerMinHeightCss(
composerHeightPercent ?? 100,
compact ? "84px" : isNewThread ? "110px" : "4rem",
);
const composerHeightStyle: CSSProperties | undefined = composerMinHeight
? {
minHeight: composerMinHeight,
maxHeight: `max(12rem, calc(${composerMinHeight} + 8rem))`,
}
: undefined;
return (
<div ref={promptRootRef} className="relative flex flex-col gap-6">
{extraHeader && (
{extraHeader && (
<div className="flex items-center justify-center">
{extraHeader}
</div>
)}
{isNewThread && searchParams.get("mode") !== "skill" && knowledgeSuggestedQuestions.length > 0 && (
<div className="px-4 mb-[10px]">
<div className="mb-2 text-center text-xs text-muted-foreground">基于已选知识空间,试试这样问</div>
<div className="flex flex-wrap justify-center gap-2.5">
{knowledgeSuggestedQuestions.slice(0, 4).map((question) => (
<button
key={question}
type="button"
className="max-w-full rounded-full border border-primary/20 bg-primary/5 px-4 py-2 text-left text-sm text-foreground transition-colors hover:bg-primary/10"
onClick={() => {
textInput.setInput(question);
setFollowupsHidden(true);
setTimeout(() => requestFormSubmit(), 0);
}}
>
{question}
</button>
))}
</div>
</div>
)}
{isNewThread && searchParams.get("mode") !== "skill" && showAdminRecommendedQuestions && (
)}
{isNewThread && searchParams.get("mode") !== "skill" && knowledgeSuggestedQuestions.length > 0 && (
<div className="px-4 mb-[10px]">
<div className="mb-2 text-center text-xs text-muted-foreground">基于已选知识空间,试试这样问</div>
<div className="flex flex-wrap justify-center gap-2.5">
{knowledgeSuggestedQuestions.slice(0, 4).map((question) => (
<button
key={question}
type="button"
className="max-w-full rounded-full border border-primary/20 bg-primary/5 px-4 py-2 text-left text-sm text-foreground transition-colors hover:bg-primary/10"
onClick={() => {
fillPromptForEditing(question);
}}
>
{question}
</button>
))}
</div>
</div>
)}
{isNewThread && searchParams.get("mode") !== "skill" && showAdminRecommendedQuestions && (
<div className="flex flex-wrap justify-center gap-2.5 px-4 mb-[10px]">
{recommendedQuestions.map((q) => (
<button
@@ -756,9 +761,7 @@ export function InputBox({
type="button"
className="rounded-full border border-[#e4e4e7] bg-white px-4 py-2 text-sm text-[#18181b] shadow-none transition-colors hover:bg-[#f4f4f5] cursor-pointer dark:border-slate-600 dark:bg-slate-700/50 dark:text-slate-300 dark:hover:bg-slate-700"
onClick={() => {
textInput.setInput(q.content);
setFollowupsHidden(true);
setTimeout(() => requestFormSubmit(), 0);
fillPromptForEditing(q.content);
}}
>
{desensitize(q.title)}
@@ -816,6 +819,9 @@ export function InputBox({
)}
<div className={cn(isNewThread && !compact && "gemini-gradient-border gemini-shadow")}>
<PromptInput
style={
composerMinHeight ? { minHeight: composerMinHeight } : undefined
}
className={cn(
"transition-all duration-300 ease-out",
// 紧凑落地态(CM 参考图):表单作为白卡,内部 input-group 透明无边框,
@@ -848,9 +854,12 @@ export function InputBox({
<PromptInputTextarea
className={cn(
"size-full px-2 py-1 text-[15px] leading-7 placeholder:text-muted-foreground/60",
isNewThread && "min-h-[110px]!",
compact && "min-h-[84px]! px-3 pt-3 pb-1 text-[14px]",
!composerMinHeight && isNewThread && "min-h-[110px]!",
compact && "px-3 pt-3 pb-1 text-[14px]",
compact && !composerMinHeight && "min-h-[84px]!",
)}
data-composer-height={composerMinHeight ? "" : undefined}
style={composerHeightStyle}
disabled={disabled}
placeholder={t.inputBox.placeholder}
autoFocus={autoFocus}
@@ -859,12 +868,12 @@ export function InputBox({
</PromptInputBody>
<PromptInputFooter
className={cn(
"flex flex-wrap items-center gap-y-2 border-t-0 px-2 pt-1 pb-1.5",
"flex flex-wrap items-center gap-y-2 border-t-0 px-2 pt-1 pb-1.5",
compact && "gap-2 px-3 pt-1.5 pb-3",
)}
>
<PromptInputTools
className={cn("min-w-0 flex-1 flex-wrap gap-1.5", compact && "gap-2")}
className={cn("min-w-0 flex-1 flex-wrap gap-1.5", compact && "gap-2")}
>
{/* TODO: Add more connectors here
<PromptInputActionMenu>
@@ -884,7 +893,7 @@ export function InputBox({
)}
/>
)}
{!frontendRagActive && !hideContextTools && <Tooltip
{!frontendRagActive && !hideContextTools && <Tooltip
content={
context.writing_mode
? "写作模式已开启:报告由深度研究管线按「通用分析结构」撰写,优先使用对话中已检索的资料"
@@ -939,42 +948,42 @@ export function InputBox({
<span className="text-xs font-normal">文件</span>
</PromptInputButton>
</Tooltip>}
{referenceModeEntryEnabled &&
!frontendRagActive &&
!smartKnowledgeRetrievalActive &&
!hideContextTools && (
<Tooltip
content={
ragModeEnabled
? "参考文献模式已开启:检索类结果会按编号引用展示"
: "参考文献模式已关闭:点击开启"
}
>
<PromptInputButton
type="button"
aria-pressed={ragModeEnabled}
disabled={ragModeLocked || disabled}
className={cn(
"gap-1.5! rounded-full px-3! shadow-none",
compact &&
"rounded-lg px-2.5! py-1! text-[11px] font-medium",
ragModeLocked && "cursor-not-allowed opacity-80",
ragModeEnabled
? "border border-emerald-300 bg-emerald-50 text-emerald-700 hover:bg-emerald-100 dark:border-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-200"
: compact
? "border border-transparent bg-muted/40 text-muted-foreground hover:bg-muted hover:text-foreground"
: "border-0 bg-transparent text-muted-foreground hover:bg-muted/70 hover:text-foreground dark:text-slate-400 dark:hover:bg-slate-700/70 dark:hover:text-slate-100",
)}
onClick={handleRagModeToggle}
>
{ragModeEnabled && (
<CheckIcon className="size-3 text-emerald-700 dark:text-emerald-200" />
)}
<BookMarkedIcon className="size-3" />
<span className="text-xs font-normal">参考文献</span>
</PromptInputButton>
</Tooltip>
)}
{referenceModeEntryEnabled &&
!frontendRagActive &&
!smartKnowledgeRetrievalActive &&
!hideContextTools && (
<Tooltip
content={
ragModeEnabled
? "参考文献模式已开启:检索类结果会按编号引用展示"
: "参考文献模式已关闭:点击开启"
}
>
<PromptInputButton
type="button"
aria-pressed={ragModeEnabled}
disabled={ragModeLocked || disabled}
className={cn(
"gap-1.5! rounded-full px-3! shadow-none",
compact &&
"rounded-lg px-2.5! py-1! text-[11px] font-medium",
ragModeLocked && "cursor-not-allowed opacity-80",
ragModeEnabled
? "border border-emerald-300 bg-emerald-50 text-emerald-700 hover:bg-emerald-100 dark:border-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-200"
: compact
? "border border-transparent bg-muted/40 text-muted-foreground hover:bg-muted hover:text-foreground"
: "border-0 bg-transparent text-muted-foreground hover:bg-muted/70 hover:text-foreground dark:text-slate-400 dark:hover:bg-slate-700/70 dark:hover:text-slate-100",
)}
onClick={handleRagModeToggle}
>
{ragModeEnabled && (
<CheckIcon className="size-3 text-emerald-700 dark:text-emerald-200" />
)}
<BookMarkedIcon className="size-3" />
<span className="text-xs font-normal">参考文献</span>
</PromptInputButton>
</Tooltip>
)}
{!frontendRagActive && <Tooltip
content={
contextCompressionEnabled
@@ -1235,6 +1244,7 @@ export function InputBox({
</PromptInputActionMenuItem>
</>
)}
{/* 多轮 RAG 问答选项暂时下线,需要恢复时取消下面注释即可
<PromptInputActionMenuItem
className={cn(
multiRoundRagActive
@@ -1263,67 +1273,13 @@ export function InputBox({
<div className="ml-auto size-4" />
)}
</PromptInputActionMenuItem>
*/}
</PromptInputActionMenu>
</DropdownMenuGroup>
</PromptInputActionMenuContent>
</PromptInputActionMenu>
{!frontendRagActive &&
supportReasoningEffort &&
context.mode !== "flash" && (
<PromptInputActionMenu>
<PromptInputActionMenuTrigger
aria-label={`${t.inputBox.reasoningEffortSelect}: ${reasoningEffortLabel}`}
className={cn(
"gap-1.5! rounded-full border-0 bg-transparent px-3! text-muted-foreground shadow-none hover:bg-muted/70 hover:text-foreground dark:text-slate-400 dark:hover:bg-slate-700/70 dark:hover:text-slate-100",
compact &&
"rounded-lg border border-border px-2.5! py-1! text-[13px]",
)}
>
<div className="flex items-center gap-1.5 text-xs font-medium">
<SparklesIcon className="size-3" />
<span className="text-foreground">
{reasoningEffortLabel}
</span>
</div>
</PromptInputActionMenuTrigger>
<PromptInputActionMenuContent className="w-56 p-3">
<div className="flex items-center justify-between gap-3 px-1">
<span className="text-xs text-muted-foreground">
{t.inputBox.reasoningEffortSelect}
</span>
<span className="text-sm font-semibold text-violet-600 dark:text-violet-300">
{reasoningEffortLabel}
</span>
</div>
<div className="mt-2 px-1">
<div className="relative h-9 w-full">
<input
type="range"
aria-label={`${t.inputBox.reasoningEffortSelect}: ${selectedModel?.display_name || selectedModel?.name || ""}`}
aria-valuetext={reasoningEffortLabel}
className="peer absolute inset-x-0 -inset-y-1 z-10 h-auto w-full cursor-grab touch-none opacity-0 active:cursor-grabbing"
value={reasoningEffortIndex}
min={0}
max={2}
step={1}
onChange={(event) => {
const effort =
REASONING_EFFORTS[Number(event.currentTarget.value)];
if (effort) handleReasoningEffortSelect(effort);
}}
/>
<div className="pointer-events-none absolute inset-x-2 top-1/2 h-1.5 -translate-y-1/2 rounded-full bg-gradient-to-r from-sky-400 via-violet-500 to-fuchsia-500 peer-focus-visible:ring-2 peer-focus-visible:ring-violet-500/70 peer-focus-visible:ring-offset-2" />
<div
className="pointer-events-none absolute top-1/2 size-5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white bg-violet-600 shadow-md peer-active:scale-110 dark:border-slate-800"
style={{ left: reasoningEffortThumbLeft }}
/>
</div>
</div>
</PromptInputActionMenuContent>
</PromptInputActionMenu>
)}
</PromptInputTools>
<PromptInputTools className={cn("ml-auto shrink-0 gap-1.5", compact && "gap-2")}>
<PromptInputTools className={cn("ml-auto shrink-0 gap-1.5", compact && "gap-2")}>
{!frontendRagActive && agentSelector && (
<AgentSelector
selectedAgentId={agentSelector.selectedAgentId}
@@ -1333,100 +1289,83 @@ export function InputBox({
/>
)}
{!frontendRagActive && knowledgeSelector}
{!frontendRagActive && knowledgeRetrieval && (
<DropdownMenu>
<Tooltip
content={
knowledgeRetrieval.mode === "smart_reasoning"
? "智能检索已开启:直接提问即可,系统会检索原文分片并沿 Wiki 线索扩展背景资料"
: knowledgeRetrieval.smartAvailabilityReason
}
>
<DropdownMenuTrigger asChild>
<PromptInputButton
type="button"
disabled={disabled}
aria-label={`普通知识库检索模式:${
knowledgeRetrieval.mode === "smart_reasoning"
? "智能检索"
: "经典检索"
}`}
aria-haspopup="menu"
className={cn(
"rounded-full px-3 shadow-none transition-colors",
knowledgeRetrieval.mode === "smart_reasoning"
? "border border-emerald-300 bg-emerald-50 text-emerald-700 hover:bg-emerald-100 dark:border-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-200"
: "border border-transparent bg-transparent text-muted-foreground hover:bg-muted/70 hover:text-foreground",
)}
>
<BrainCircuitIcon className="size-3.5" />
<span className="max-w-[160px] truncate text-xs font-normal">
{knowledgeRetrieval.mode === "smart_reasoning" ? "智能检索" : "经典检索"}
</span>
</PromptInputButton>
</DropdownMenuTrigger>
</Tooltip>
<DropdownMenuContent
align="end"
sideOffset={8}
className="w-80 rounded-xl p-1.5"
>
<DropdownMenuLabel className="px-2 pb-1 text-xs text-muted-foreground">
普通知识库检索模式
</DropdownMenuLabel>
<DropdownMenuItem
className="min-h-16 items-start rounded-lg py-2"
disabled={!knowledgeRetrieval.smartAvailable}
onSelect={() =>
knowledgeRetrieval.onModeChange("smart_reasoning")
}
>
<BrainCircuitIcon className="mt-0.5 size-4" />
<div className="min-w-0 flex-1">
<div className="text-sm font-medium">
智能检索
{knowledgeRetrieval.smartIsDefault ? "(新对话默认)" : ""}
</div>
<div className="mt-0.5 text-xs text-muted-foreground">
先检索原文分片,再按命中线索查阅并扩展 Wiki;资料仅作为回答背景
</div>
</div>
{knowledgeRetrieval.mode === "smart_reasoning" && (
<CheckIcon className="mt-0.5 size-4 text-emerald-600" />
)}
</DropdownMenuItem>
<DropdownMenuItem
className="min-h-14 items-start rounded-lg py-2"
onSelect={() => knowledgeRetrieval.onModeChange("classic")}
>
<BookMarkedIcon className="mt-0.5 size-4" />
<div className="min-w-0 flex-1">
<div className="text-sm font-medium">
经典检索
{knowledgeRetrieval.smartIsDefault ? "(候选)" : "(新对话默认)"}
</div>
<div className="mt-0.5 text-xs text-muted-foreground">
沿用原有知识库检索与回答方式
</div>
</div>
{knowledgeRetrieval.mode === "classic" && (
<CheckIcon className="mt-0.5 size-4 text-primary" />
)}
</DropdownMenuItem>
<DropdownMenuSeparator />
<p
className={cn(
"px-2 py-1 text-xs leading-5",
knowledgeRetrieval.smartAvailable
? "text-muted-foreground"
: "text-amber-600 dark:text-amber-300",
)}
>
{knowledgeRetrieval.smartAvailabilityReason}
</p>
</DropdownMenuContent>
</DropdownMenu>
)}
{!frontendRagActive && knowledgeRetrieval && (
<DropdownMenu>
<Tooltip
content={
knowledgeRetrieval.mode === "smart_reasoning"
? "智能检索:综合原文与 Wiki 线索,提供更全面的背景和解释"
: "经典检索:细粒度召回原文,优先回答具体事实与细节"
}
>
<DropdownMenuTrigger asChild>
<PromptInputButton
type="button"
disabled={disabled}
aria-label={`普通知识库检索模式:${
knowledgeRetrieval.mode === "smart_reasoning"
? "智能检索"
: "经典检索"
}`}
aria-haspopup="menu"
className={cn(
"rounded-full px-3 shadow-none transition-colors",
knowledgeRetrieval.mode === "smart_reasoning"
? "border border-emerald-300 bg-emerald-50 text-emerald-700 hover:bg-emerald-100 dark:border-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-200"
: "border border-transparent bg-transparent text-muted-foreground hover:bg-muted/70 hover:text-foreground",
)}
>
<BrainCircuitIcon className="size-3.5" />
<span className="max-w-[160px] truncate text-xs font-normal">
{knowledgeRetrieval.mode === "smart_reasoning" ? "智能检索" : "经典检索"}
</span>
</PromptInputButton>
</DropdownMenuTrigger>
</Tooltip>
<DropdownMenuContent
align="end"
sideOffset={8}
className="w-80 rounded-xl p-1.5"
>
<DropdownMenuLabel className="px-2 pb-1 text-xs text-muted-foreground">
普通知识库检索模式
</DropdownMenuLabel>
<DropdownMenuItem
className="min-h-16 items-start rounded-lg py-2"
onSelect={() => knowledgeRetrieval.onModeChange("classic")}
>
<BookMarkedIcon className="mt-0.5 size-4" />
<div className="min-w-0 flex-1">
<div className="text-sm font-medium">经典检索(默认)</div>
<div className="mt-0.5 text-xs text-muted-foreground">
细粒度召回知识库原文,优先定位与问题最相关的具体段落,适合查询事实、条款、数字和原文细节
</div>
</div>
{knowledgeRetrieval.mode === "classic" && (
<CheckIcon className="mt-0.5 size-4 text-primary" />
)}
</DropdownMenuItem>
<DropdownMenuItem
className="min-h-16 items-start rounded-lg py-2"
disabled={!knowledgeRetrieval.smartAvailable}
onSelect={() =>
knowledgeRetrieval.onModeChange("smart_reasoning")
}
>
<BrainCircuitIcon className="mt-0.5 size-4" />
<div className="min-w-0 flex-1">
<div className="text-sm font-medium">智能检索</div>
<div className="mt-0.5 text-xs text-muted-foreground">
综合原文分片与 Wiki 目录、页面和关联线索扩展检索,适合全面梳理背景、关联关系和综合解释
</div>
</div>
{knowledgeRetrieval.mode === "smart_reasoning" && (
<CheckIcon className="mt-0.5 size-4 text-emerald-600" />
)}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
{!frontendRagActive && promptPrefix && (
<Tooltip
content={
@@ -1511,21 +1450,21 @@ export function InputBox({
"rounded-full border-border bg-background shadow-sm hover:bg-muted dark:bg-blue-500 dark:border-blue-500 dark:text-white dark:hover:bg-blue-400 dark:shadow-none",
compact &&
"size-7 rounded-lg border-0 bg-[var(--primary)] text-[var(--button-foreground,var(--primary-foreground))] hover:opacity-90 disabled:bg-muted disabled:text-muted-foreground/40 dark:bg-[var(--primary)] dark:border-0 dark:text-[var(--button-foreground,var(--primary-foreground))] dark:hover:opacity-90 dark:disabled:bg-muted",
)}
disabled={disabled}
onClick={(event) => {
if (composerStatus !== "streaming") return;
// A deliberate press of the square button stops the stream.
// Prevent the enclosing form from treating it as a new submit.
event.preventDefault();
handleStopCurrentGeneration();
}}
variant="outline"
status={composerStatus}
{...(documentRewriteActive
? { "aria-label": "停止 AI 全文改写" }
: {})}
/>
)}
disabled={disabled}
onClick={(event) => {
if (composerStatus !== "streaming") return;
// A deliberate press of the square button stops the stream.
// Prevent the enclosing form from treating it as a new submit.
event.preventDefault();
handleStopCurrentGeneration();
}}
variant="outline"
status={composerStatus}
{...(documentRewriteActive
? { "aria-label": "停止 AI 全文改写" }
: {})}
/>
</PromptInputTools>
</PromptInputFooter>
{!isNewThread && (
@@ -1,102 +1,23 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { BookOpen /* , Database, SearchCheck */ } from "lucide-react";
import { BookOpen } from "lucide-react";
import { useLocation, useNavigate } from "react-router-dom";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { getStoredAuth } from "@/core/auth";
// import { canAccessAssistantKnowledge } from "@/core/llmwiki/assistant-knowledge-access-policy";
// import {
// useAssistantKnowledgeVisibility,
// useUpdateAssistantKnowledgeVisibility,
// } from "@/core/system-settings/hooks";
import { useLlmWikiRuntime } from "@/strategy-components/api/llmwiki";
import {
loadOrdinaryKnowledgeLanding,
saveOrdinaryKnowledgeLanding,
type OrdinaryKnowledgeLanding,
} from "@/core/system-settings/api";
const LANDING_KEY = ["system-settings", "ordinary-knowledge-landing"] as const;
export function useOrdinaryKnowledgeLanding(enabled = true) {
return useQuery({
queryKey: LANDING_KEY,
queryFn: ({ signal }) => loadOrdinaryKnowledgeLanding(signal),
enabled,
staleTime: 30_000,
retry: false,
});
}
export const KNOWLEDGE_NORMAL_VIEW_VALUE = "normal";
export const KNOWLEDGE_NORMAL_VIEW_SEARCH = `?view=${KNOWLEDGE_NORMAL_VIEW_VALUE}`;
export function KnowledgeProductNav() {
const location = useLocation();
const navigate = useNavigate();
const client = useQueryClient();
// const assistantVisibility = useAssistantKnowledgeVisibility();
const isAdmin = getStoredAuth()?.system_role === "admin";
const landing = useOrdinaryKnowledgeLanding(isAdmin);
const saveLanding = useMutation({
mutationFn: saveOrdinaryKnowledgeLanding,
onSuccess: (mode) => { client.setQueryData(LANDING_KEY, mode); toast.success("普通知识库默认页面已更新"); },
onError: (error) => toast.error(error.message),
});
const runtime = useLlmWikiRuntime();
const normalAvailable = runtime.data?.provider === "weknora" && Boolean(runtime.data.api_base_url?.trim());
// const assistantAllowed = canAccessAssistantKnowledge(
// isAdmin,
// assistantVisibility.isError ? undefined : assistantVisibility.data,
// );
// const saveAssistantVisibility = useUpdateAssistantKnowledgeVisibility();
const retrievalDebug = location.pathname.includes("/knowledge/retrieval-debug");
const assistant = location.pathname.includes("/knowledge/assistant");
const ordinary = !assistant && !retrievalDebug;
const ordinary = !location.pathname.includes("/knowledge/assistant") && !location.pathname.includes("/knowledge/retrieval-debug");
return (
<div className="flex flex-wrap items-center gap-2 border-b bg-card px-6 py-2">
<Button size="sm" disabled={!normalAvailable} title={normalAvailable ? "普通知识库" : "管理员配置知识服务地址后可用"} variant={ordinary ? "secondary" : "ghost"} onClick={() => navigate(`/page/workspace/knowledge${KNOWLEDGE_NORMAL_VIEW_SEARCH}`)}>
<BookOpen />普通知识库
</Button>
{/* 助手知识库、检索调试暂时隐藏,后续放开时去掉这段注释。
{assistantAllowed && (
<Button size="sm" variant={assistant ? "secondary" : "ghost"} onClick={() => navigate("/page/workspace/knowledge/assistant")}>
<Database />助手知识库
</Button>
)}
{isAdmin && (
<Button size="sm" variant={retrievalDebug ? "secondary" : "ghost"} onClick={() => navigate("/page/workspace/knowledge/retrieval-debug")}>
<SearchCheck />检索调试
</Button>
)}
*/}
{isAdmin && (
<div className="ml-auto flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
普通知识库默认页面
<Select disabled={landing.isLoading || saveLanding.isPending} value={landing.data ?? "wiki"} onValueChange={(value) => saveLanding.mutate(value as OrdinaryKnowledgeLanding)}>
<SelectTrigger className="h-8 w-40" aria-label="普通知识库默认页面"><SelectValue /></SelectTrigger>
<SelectContent><SelectItem value="wiki">本系统 Wiki 索引</SelectItem><SelectItem value="weknora">知识库管理页面</SelectItem></SelectContent>
</Select>
{/* 助手知识库日常展示暂时隐藏,和上面两个入口一起放开。
助手知识库日常展示
<Select
disabled={assistantVisibility.isLoading || saveAssistantVisibility.isPending}
value={assistantVisibility.data === true ? "visible" : "hidden"}
onValueChange={(value) =>
saveAssistantVisibility.mutate(value === "visible", {
onSuccess: (visible) => toast.success(visible ? "已向普通用户开放助手知识库" : "已隐藏普通用户的助手知识库"),
onError: (error) => toast.error(error.message),
})
}
>
<SelectTrigger className="h-8 w-52" aria-label="助手知识库日常展示"><SelectValue /></SelectTrigger>
<SelectContent><SelectItem value="hidden">隐藏(仅管理员可用)</SelectItem><SelectItem value="visible">开放给普通用户</SelectItem></SelectContent>
</Select>
*/}
</div>
)}
</div>
);
}
@@ -32,21 +32,21 @@ import {
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet";
import {
buildWriteFileVirtualUrl,
isAutoPreviewableArtifactPath,
languageOfStreamingArtifact,
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet";
import {
buildWriteFileVirtualUrl,
isAutoPreviewableArtifactPath,
languageOfStreamingArtifact,
normalizeStreamingArtifactPath,
namedStreamingWriteFilePath,
} from "@/core/artifacts/streaming-write-preview";
import { listStreamingWriteFileCalls } from "@/core/artifacts/parse-partial-json";
namedStreamingWriteFilePath,
} from "@/core/artifacts/streaming-write-preview";
import { listStreamingWriteFileCalls } from "@/core/artifacts/parse-partial-json";
import { useI18n } from "@/core/i18n/hooks";
import {
normalizeSearchResults,
@@ -57,11 +57,11 @@ import {
extractReasoningContentFromMessage,
findToolCallResult,
} from "@/core/messages/utils";
import { collectRetrievedFiles } from "@/core/messages/retrieved-files";
import { collectRetrievedFiles } from "@/core/messages/retrieved-files";
import { useRehypeSplitWordsIntoSpans } from "@/core/rehype";
import { useLocalSettings } from "@/core/settings";
import { useSkills } from "@/core/skills/hooks";
import { useCitationDisplaySettings } from "@/core/system-settings/hooks";
import { useSkills } from "@/core/skills/hooks";
import { useCitationDisplaySettings } from "@/core/system-settings/hooks";
import { isInternalToolCallName } from "@/core/tools/visibility";
import {
applyInlineCitations,
@@ -85,26 +85,26 @@ import { Tooltip } from "../tooltip";
import { SourceCard } from "../skill-display-sources";
import { MarkdownContent } from "./markdown-content";
import { SingleRoundRagCitationDrawer } from "./message-list-item";
import { RetrievedFileList } from "./retrieved-file-list";
import { SingleRoundRagCitationDrawer } from "./message-list-item";
import { RetrievedFileList } from "./retrieved-file-list";
export function MessageGroup({
className,
messages,
isLoading = false,
displaySources = [],
ragModeEnabled = false,
threadId,
}: {
className?: string;
messages: Message[];
isLoading?: boolean;
displaySources?: RuntimeDisplaySource[];
ragModeEnabled?: boolean;
threadId?: string;
export function MessageGroup({
className,
messages,
isLoading = false,
displaySources = [],
ragModeEnabled = false,
threadId,
}: {
className?: string;
messages: Message[];
isLoading?: boolean;
displaySources?: RuntimeDisplaySource[];
ragModeEnabled?: boolean;
threadId?: string;
}) {
const { t } = useI18n();
const { data: citationDisplay } = useCitationDisplaySettings();
const { data: citationDisplay } = useCitationDisplaySettings();
const [showAbove, setShowAbove] = useState(
env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true",
);
@@ -119,16 +119,20 @@ export function MessageGroup({
() => convertToSteps(messages, writingModeEnabled),
[messages, writingModeEnabled],
);
const { skills } = useSkills();
const retrievedFiles = useMemo(
() => citationDisplay?.retrieved_files_enabled === true
? collectRetrievedFiles(messages, new Set(skills.map((skill) => skill.name)))
: [],
[messages, skills, citationDisplay?.retrieved_files_enabled],
);
const skillDisplayMap = useMemo(
() => (ragModeEnabled ? buildSkillDisplayMap(skills) : new Map()),
[ragModeEnabled, skills],
const { skills } = useSkills({
enabled:
messages.length > 0 &&
(ragModeEnabled || citationDisplay?.retrieved_files_enabled === true),
});
const retrievedFiles = useMemo(
() => citationDisplay?.retrieved_files_enabled === true
? collectRetrievedFiles(messages, new Set(skills.map((skill) => skill.name)))
: [],
[messages, skills, citationDisplay?.retrieved_files_enabled],
);
const skillDisplayMap = useMemo(
() => (ragModeEnabled ? buildSkillDisplayMap(skills) : new Map()),
[ragModeEnabled, skills],
);
const lastToolCallStep = useMemo(() => {
const filteredSteps = steps.filter((step) => step.type === "toolCall");
@@ -223,8 +227,8 @@ export function MessageGroup({
{...step}
isLoading={isLoading}
skillDisplayMap={skillDisplayMap}
displaySources={displaySources}
ragModeEnabled={ragModeEnabled}
displaySources={displaySources}
ragModeEnabled={ragModeEnabled}
/>
),
)}
@@ -236,8 +240,8 @@ export function MessageGroup({
isLast={true}
isLoading={isLoading}
skillDisplayMap={skillDisplayMap}
displaySources={displaySources}
ragModeEnabled={ragModeEnabled}
displaySources={displaySources}
ragModeEnabled={ragModeEnabled}
/>
</FlipDisplay>
)}
@@ -286,8 +290,8 @@ export function MessageGroup({
</>
)}
</ChainOfThought>
{threadId && <RetrievedFileList files={retrievedFiles} threadId={threadId} />}
<SingleRoundRagCitationDrawer
{threadId && <RetrievedFileList files={retrievedFiles} threadId={threadId} />}
<SingleRoundRagCitationDrawer
source={selectedCitation}
onOpenChange={(open) => {
if (!open) setSelectedCitation(null);
@@ -352,7 +356,7 @@ function ToolCall({
isLast = false,
isLoading = false,
skillDisplayMap = new Map(),
displaySources = [],
displaySources = [],
ragModeEnabled = false,
}: {
id?: string;
@@ -363,7 +367,7 @@ function ToolCall({
isLast?: boolean;
isLoading?: boolean;
skillDisplayMap?: ReturnType<typeof buildSkillDisplayMap>;
displaySources?: RuntimeDisplaySource[];
displaySources?: RuntimeDisplaySource[];
ragModeEnabled?: boolean;
}) {
const { t } = useI18n();
@@ -374,42 +378,42 @@ function ToolCall({
null);
const displayItems =
displayMatch && result !== undefined
? syncDisplaySourceIndexes(
rankDisplaySources(
normalizeDisplaySources(result, displayMatch.display).map(
(item, index) => ({
...item,
index: index + 1,
skillName: displayMatch.skillName,
mode: item.displayMode ?? displayMatch.display.mode,
}),
),
),
displaySources,
)
? syncDisplaySourceIndexes(
rankDisplaySources(
normalizeDisplaySources(result, displayMatch.display).map(
(item, index) => ({
...item,
index: index + 1,
skillName: displayMatch.skillName,
mode: item.displayMode ?? displayMatch.display.mode,
}),
),
),
displaySources,
)
: [];
const isLlmWikiTool =
name === "llmwiki_search" ||
name === "llmwiki_read_wiki_page" ||
name === "llmwiki_browse_wiki_index";
const wikiQuery = isLlmWikiTool
? resolveSearchQuery(args, result) ||
(name === "llmwiki_read_wiki_page"
? normalizeSearchResults(result)[0]?.title ||
(typeof args.wiki_slug === "string" ? args.wiki_slug : "")
: "")
: "";
const isLlmWikiTool =
name === "llmwiki_search" ||
name === "llmwiki_read_wiki_page" ||
name === "llmwiki_browse_wiki_index";
const wikiQuery = isLlmWikiTool
? resolveSearchQuery(args, result) ||
(name === "llmwiki_read_wiki_page"
? normalizeSearchResults(result)[0]?.title ||
(typeof args.wiki_slug === "string" ? args.wiki_slug : "")
: "")
: "";
const wikiSearchLabel = name === "llmwiki_search"
? wikiQuery
? `Wiki 文档检索 "${wikiQuery}"`
: "Wiki 文档检索"
: name === "llmwiki_read_wiki_page"
? wikiQuery
? `读取 Wiki 页面「${wikiQuery}」`
: "读取 Wiki 页面"
: name === "llmwiki_browse_wiki_index"
? "读取 Wiki 索引与知识库摘要"
: null;
: name === "llmwiki_read_wiki_page"
? wikiQuery
? `读取 Wiki 页面「${wikiQuery}」`
: "读取 Wiki 页面"
: name === "llmwiki_browse_wiki_index"
? "读取 Wiki 索引与知识库摘要"
: null;
if (displayItems.length > 0) {
return (
<ChainOfThoughtStep
@@ -435,17 +439,17 @@ function ToolCall({
const searchItems = normalizeSearchResults(result);
if (ragModeEnabled && shouldUseDefaultCitationMode(name, result, args) && searchItems.length > 0) {
const defaultItems = syncDisplaySourceIndexes(
rankDisplaySources(
normalizeDefaultDisplaySources(result).map((item, index) => ({
...item,
index: index + 1,
skillName: name,
mode: "citation" as const,
})),
),
displaySources,
);
const defaultItems = syncDisplaySourceIndexes(
rankDisplaySources(
normalizeDefaultDisplaySources(result).map((item, index) => ({
...item,
index: index + 1,
skillName: name,
mode: "citation" as const,
})),
),
displaySources,
);
return (
<ChainOfThoughtStep key={id} label={wikiSearchLabel || "检索参考来源"} icon={SearchIcon}>
<DisplayResultsList results={defaultItems} />
@@ -827,10 +831,10 @@ function ArtifactWriteToolCall({
const rawPath = typeof args.path === "string" ? args.path : "";
const content = typeof args.content === "string" ? args.content : "";
const normalizedPath = normalizeStreamingArtifactPath(rawPath);
const sourcePath = namedStreamingWriteFilePath(rawPath);
const showInlineContent = name === "write_file" && !sourcePath;
const sourcePath = namedStreamingWriteFilePath(rawPath);
const showInlineContent = name === "write_file" && !sourcePath;
const previewKey = messageId && id ? `${messageId}:${id}` : null;
// Until a real path arrives, both auto-open and manual clicks stay inline.
// Until a real path arrives, both auto-open and manual clicks stay inline.
const artifactPath =
sourcePath && name === "write_file" && messageId && id
? buildWriteFileVirtualUrl({ path: sourcePath, messageId, toolCallId: id })
@@ -842,10 +846,10 @@ function ArtifactWriteToolCall({
!artifactPath ||
!previewKey ||
!isLoading ||
result !== undefined ||
!sourcePath ||
!languageOfStreamingArtifact(sourcePath) ||
!isAutoPreviewableArtifactPath(sourcePath)
result !== undefined ||
!sourcePath ||
!languageOfStreamingArtifact(sourcePath) ||
!isAutoPreviewableArtifactPath(sourcePath)
) {
return;
}
@@ -871,9 +875,9 @@ function ArtifactWriteToolCall({
artifacts.setOpen(true);
}}
>
{showInlineContent ? (
content && <InlineWritePreview content={content} />
) : (normalizedPath || sourcePath) && (
{showInlineContent ? (
content && <InlineWritePreview content={content} />
) : (normalizedPath || sourcePath) && (
<ChainOfThoughtSearchResult className="cursor-pointer">
{artifactDisplayName(normalizedPath || (sourcePath ?? ""))}
</ChainOfThoughtSearchResult>
@@ -882,29 +886,29 @@ function ArtifactWriteToolCall({
);
}
function InlineWritePreview({ content }: { content: string }) {
const ref = useRef<HTMLPreElement>(null);
const follow = useRef(true);
useLayoutEffect(() => {
if (follow.current && ref.current) {
ref.current.scrollTop = ref.current.scrollHeight;
}
}, [content]);
return (
<pre
ref={ref}
onScroll={(event) => {
const node = event.currentTarget;
follow.current = node.scrollHeight - node.scrollTop - node.clientHeight < 24;
}}
className="border-border m-0 max-h-64 overflow-auto border-l pl-3 font-mono text-xs leading-6 whitespace-pre-wrap break-words text-emerald-600 dark:text-emerald-400"
>
<code>{content}</code>
</pre>
);
}
interface GenericCoTStep<T extends string = string> {
function InlineWritePreview({ content }: { content: string }) {
const ref = useRef<HTMLPreElement>(null);
const follow = useRef(true);
useLayoutEffect(() => {
if (follow.current && ref.current) {
ref.current.scrollTop = ref.current.scrollHeight;
}
}, [content]);
return (
<pre
ref={ref}
onScroll={(event) => {
const node = event.currentTarget;
follow.current = node.scrollHeight - node.scrollTop - node.clientHeight < 24;
}}
className="border-border m-0 max-h-64 overflow-auto border-l pl-3 font-mono text-xs leading-6 whitespace-pre-wrap break-words text-emerald-600 dark:text-emerald-400"
>
<code>{content}</code>
</pre>
);
}
interface GenericCoTStep<T extends string = string> {
id?: string;
messageId?: string;
type: T;
@@ -924,10 +928,10 @@ type CoTStep = CoTReasoningStep | CoTToolCallStep;
function convertToSteps(messages: Message[], writingMode: boolean): CoTStep[] {
const steps: CoTStep[] = [];
// Some streaming providers omit tool_call_id on ToolMessages. Keep a
// per-name cursor so parallel searches consume distinct unbound results in
// order instead of every step reusing the first page.
const toolCallNameFallbackIndexes = new Map<string, number>();
// Some streaming providers omit tool_call_id on ToolMessages. Keep a
// per-name cursor so parallel searches consume distinct unbound results in
// order instead of every step reusing the first page.
const toolCallNameFallbackIndexes = new Map<string, number>();
for (const message of messages) {
if (message.type === "ai") {
const reasoning = extractReasoningContentFromMessage(message);
@@ -940,37 +944,37 @@ function convertToSteps(messages: Message[], writingMode: boolean): CoTStep[] {
};
steps.push(step);
}
const writes = new Map(
listStreamingWriteFileCalls(message).map((write) => [write.id, write]),
);
const chunks = (message as Parameters<typeof listStreamingWriteFileCalls>[0])
.tool_call_chunks;
const toolCalls = [...(message.tool_calls ?? [])];
for (const write of writes.values()) {
if (
!toolCalls.some((call) => call.id === write.id) &&
chunks?.some(
(chunk) => chunk.id === write.id && chunk.name === "write_file",
)
) {
toolCalls.push({
id: write.id,
name: "write_file",
args: { path: write.path, content: write.content },
});
}
}
for (const tool_call of toolCalls) {
const writes = new Map(
listStreamingWriteFileCalls(message).map((write) => [write.id, write]),
);
const chunks = (message as Parameters<typeof listStreamingWriteFileCalls>[0])
.tool_call_chunks;
const toolCalls = [...(message.tool_calls ?? [])];
for (const write of writes.values()) {
if (
!toolCalls.some((call) => call.id === write.id) &&
chunks?.some(
(chunk) => chunk.id === write.id && chunk.name === "write_file",
)
) {
toolCalls.push({
id: write.id,
name: "write_file",
args: { path: write.path, content: write.content },
});
}
}
for (const tool_call of toolCalls) {
if (tool_call.name === "task" || isInternalToolCallName(tool_call.name)) {
continue;
}
const write = tool_call.name === "write_file" && tool_call.id
? writes.get(tool_call.id)
: undefined;
const args = write
? { ...tool_call.args, path: write.path, content: write.content }
: tool_call.args;
const writePath = typeof args?.path === "string" ? args.path : "";
const write = tool_call.name === "write_file" && tool_call.id
? writes.get(tool_call.id)
: undefined;
const args = write
? { ...tool_call.args, path: write.path, content: write.content }
: tool_call.args;
const writePath = typeof args?.path === "string" ? args.path : "";
if (
(
tool_call.name === "write_file" ||
@@ -988,27 +992,27 @@ function convertToSteps(messages: Message[], writingMode: boolean): CoTStep[] {
messageId: message.id,
type: "toolCall",
name: tool_call.name,
args,
args,
};
const toolCallId = tool_call.id;
if (toolCallId) {
let toolCallResult = findToolCallResult(
let toolCallResult = findToolCallResult(
toolCallId,
messages,
tool_call.name,
{ allowNameFallback: false },
{ allowNameFallback: false },
);
if (toolCallResult === undefined) {
const nameKey = tool_call.name.toLowerCase();
const fallbackIndex = toolCallNameFallbackIndexes.get(nameKey) ?? 0;
toolCallResult = findToolCallResult(
toolCallId,
messages,
tool_call.name,
{ allowNameFallback: true, nameFallbackIndex: fallbackIndex },
);
toolCallNameFallbackIndexes.set(nameKey, fallbackIndex + 1);
}
if (toolCallResult === undefined) {
const nameKey = tool_call.name.toLowerCase();
const fallbackIndex = toolCallNameFallbackIndexes.get(nameKey) ?? 0;
toolCallResult = findToolCallResult(
toolCallId,
messages,
tool_call.name,
{ allowNameFallback: true, nameFallbackIndex: fallbackIndex },
);
toolCallNameFallbackIndexes.set(nameKey, fallbackIndex + 1);
}
if (toolCallResult !== undefined) {
if (typeof toolCallResult === "string") {
try {
@@ -1075,48 +1079,48 @@ function DisplayResultsList({ results }: { results: RuntimeDisplaySource[] }) {
);
}
function rankDisplaySources(
sources: RuntimeDisplaySource[],
): RuntimeDisplaySource[] {
return sources
.map((source, originalOrder) => ({ source, originalOrder }))
.sort((left, right) => {
const leftScore =
typeof left.source.score === "number" && Number.isFinite(left.source.score)
? left.source.score
: Number.NEGATIVE_INFINITY;
const rightScore =
typeof right.source.score === "number" && Number.isFinite(right.source.score)
? right.source.score
: Number.NEGATIVE_INFINITY;
return rightScore - leftScore || left.originalOrder - right.originalOrder;
})
.map(({ source }, index) => ({ ...source, index: index + 1 }));
}
function syncDisplaySourceIndexes(
sources: RuntimeDisplaySource[],
globalSources: RuntimeDisplaySource[],
): RuntimeDisplaySource[] {
const indexByCitationId = new Map(
globalSources.flatMap((source) => {
const citationId =
typeof source.raw?.citation_id === "string"
? source.raw.citation_id.trim()
: "";
return citationId ? [[citationId, source.index] as const] : [];
}),
);
return sources.map((source) => {
const citationId =
typeof source.raw?.citation_id === "string"
? source.raw.citation_id.trim()
: "";
const index = citationId ? indexByCitationId.get(citationId) : undefined;
return index ? { ...source, index } : source;
});
}
function rankDisplaySources(
sources: RuntimeDisplaySource[],
): RuntimeDisplaySource[] {
return sources
.map((source, originalOrder) => ({ source, originalOrder }))
.sort((left, right) => {
const leftScore =
typeof left.source.score === "number" && Number.isFinite(left.source.score)
? left.source.score
: Number.NEGATIVE_INFINITY;
const rightScore =
typeof right.source.score === "number" && Number.isFinite(right.source.score)
? right.source.score
: Number.NEGATIVE_INFINITY;
return rightScore - leftScore || left.originalOrder - right.originalOrder;
})
.map(({ source }, index) => ({ ...source, index: index + 1 }));
}
function syncDisplaySourceIndexes(
sources: RuntimeDisplaySource[],
globalSources: RuntimeDisplaySource[],
): RuntimeDisplaySource[] {
const indexByCitationId = new Map(
globalSources.flatMap((source) => {
const citationId =
typeof source.raw?.citation_id === "string"
? source.raw.citation_id.trim()
: "";
return citationId ? [[citationId, source.index] as const] : [];
}),
);
return sources.map((source) => {
const citationId =
typeof source.raw?.citation_id === "string"
? source.raw.citation_id.trim()
: "";
const index = citationId ? indexByCitationId.get(citationId) : undefined;
return index ? { ...source, index } : source;
});
}
function SearchResultCard({ item }: { item: SearchResultItem }) {
const [open, setOpen] = useState(false);
const content = item.snippet ?? item.content;
@@ -1154,46 +1158,46 @@ function SearchResultCard({ item }: { item: SearchResultItem }) {
</div>
)}
</button>
<Sheet open={open} onOpenChange={setOpen}>
<SheetContent
side="right"
className="w-[min(92vw,760px)] gap-0 overflow-hidden p-0 sm:max-w-none"
>
<SheetHeader className="shrink-0 border-b px-5 py-4 pr-12 text-left">
<SheetTitle className="text-base leading-relaxed">
{item.title ?? "检索结果"}
</SheetTitle>
{(sourceLabel || date) && (
<SheetDescription className="flex items-center gap-2 text-xs">
{sourceLabel && <span>{sourceLabel}</span>}
{sourceLabel && date && <span>·</span>}
{date && <span>{date}</span>}
</SheetDescription>
)}
{!sourceLabel && !date && (
<SheetDescription className="sr-only">检索结果详情</SheetDescription>
)}
</SheetHeader>
<div className="min-h-0 flex-1 overflow-y-auto bg-muted/20 p-4 sm:p-6">
<div className="mx-auto max-w-3xl space-y-4">
{content ? (
<article className="text-foreground rounded-xl border bg-background px-4 py-5 text-sm leading-7 whitespace-pre-wrap shadow-sm sm:px-6">
{content}
</article>
) : (
<div className="flex min-h-64 items-center justify-center rounded-xl border border-dashed bg-background text-sm text-muted-foreground">
暂无可展示的检索内容
</div>
)}
{item.url && (
<div className="text-muted-foreground border-t pt-3 text-xs break-all">
{item.url}
</div>
)}
</div>
</div>
</SheetContent>
</Sheet>
<Sheet open={open} onOpenChange={setOpen}>
<SheetContent
side="right"
className="w-[min(92vw,760px)] gap-0 overflow-hidden p-0 sm:max-w-none"
>
<SheetHeader className="shrink-0 border-b px-5 py-4 pr-12 text-left">
<SheetTitle className="text-base leading-relaxed">
{item.title ?? "检索结果"}
</SheetTitle>
{(sourceLabel || date) && (
<SheetDescription className="flex items-center gap-2 text-xs">
{sourceLabel && <span>{sourceLabel}</span>}
{sourceLabel && date && <span>·</span>}
{date && <span>{date}</span>}
</SheetDescription>
)}
{!sourceLabel && !date && (
<SheetDescription className="sr-only">检索结果详情</SheetDescription>
)}
</SheetHeader>
<div className="min-h-0 flex-1 overflow-y-auto bg-muted/20 p-4 sm:p-6">
<div className="mx-auto max-w-3xl space-y-4">
{content ? (
<article className="text-foreground rounded-xl border bg-background px-4 py-5 text-sm leading-7 whitespace-pre-wrap shadow-sm sm:px-6">
{content}
</article>
) : (
<div className="flex min-h-64 items-center justify-center rounded-xl border border-dashed bg-background text-sm text-muted-foreground">
暂无可展示的检索内容
</div>
)}
{item.url && (
<div className="text-muted-foreground border-t pt-3 text-xs break-all">
{item.url}
</div>
)}
</div>
</div>
</SheetContent>
</Sheet>
</>
);
}
File diff suppressed because it is too large. Load diff
@@ -13,6 +13,8 @@ import {
} from "@/components/ui/sheet";
import { cn } from "@/lib/utils";
import { REVEAL_CHAT_HISTORY_EVENT } from "@/core/messages/history-window";
import { buildQuestionItems, type QuestionItem } from "./question-navigator-data";
import { Tooltip } from "./tooltip";
@@ -142,9 +144,17 @@ export function QuestionNavigator({
}, [visible, questions]);
const scrollToQuestion = useCallback((anchorId: string) => {
document
.getElementById(anchorId)
?.scrollIntoView({ behavior: "smooth", block: "start" });
const scroll = () => {
document
.getElementById(anchorId)
?.scrollIntoView({ behavior: "smooth", block: "start" });
};
if (!document.getElementById(anchorId)) {
window.dispatchEvent(new Event(REVEAL_CHAT_HISTORY_EVENT));
requestAnimationFrame(() => requestAnimationFrame(scroll));
} else {
scroll();
}
setActiveId(anchorId);
}, []);
@@ -7,6 +7,9 @@ import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { apiFetch } from "@/core/api/fetch-client";
import { clearStoredAuth, getAccountDisplayName, getStoredAuth } from "@/core/auth";
import { authStorageRemove } from "@/core/auth/scoped-storage";
import { EXTERNAL_LOGIN_STORAGE_KEYS } from "@/core/auth/external-login";
import { clearLoginCredentials } from "@/core/auth/login-credentials";
import { useLiveAccount } from "@/core/auth/use-live-account";
import { getBackendBaseURL } from "@/core/config";
import { OptType, writeYLog } from "@/core/log/y-log";
@@ -57,6 +60,11 @@ export function AccountSettingsPage() {
});
clearStoredAuth();
clearYLogToken();
for (const key of [
"userInfo", "userId", "tools_token", "access_token",
...Object.values(EXTERNAL_LOGIN_STORAGE_KEYS),
]) authStorageRemove(key);
clearLoginCredentials();
// Match the rest of the app's logout flow: blow away the cookie session
// by hitting the gateway logout endpoint and then forcing a full reload
// so any cached query state goes too.
@@ -0,0 +1,297 @@
"use client";
import { useEffect, useState } from "react";
import { Clock3Icon, DatabaseIcon, GlobeIcon, RefreshCwIcon, SaveIcon, SearchIcon } from "lucide-react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { getAuditRetentionStatus, setAuditRetentionPaused, type AuditRetentionStatus } from "@/core/admin/audit-retention";
import { apiFetch } from "@/core/api";
import { getBackendBaseURL } from "@/core/config";
type CacheCollection = {
id: string;
label: string;
paths: string[];
scope: string;
enabled: boolean;
ttl_seconds: number;
};
type ApiReadCacheStatus = {
enabled: boolean;
redis_configured: boolean;
ttl_seconds: number;
max_value_bytes: number;
browser_status_enabled: boolean;
collections: CacheCollection[];
};
type ApiReadCacheUpdate = {
enabled?: boolean;
ttl_seconds?: number;
browser_status_enabled?: boolean;
collection_overrides?: Record<string, boolean>;
};
async function requestStatus(update?: ApiReadCacheUpdate): Promise<ApiReadCacheStatus> {
const response = await apiFetch(`${getBackendBaseURL()}/api/system-settings/api-read-cache`, update ? {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(update),
} : undefined);
const data = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(typeof data.detail === "string" ? data.detail : `${update ? "保存" : "读取"}失败(${response.status})`);
}
return data as ApiReadCacheStatus;
}
function retentionLabel(status: string) {
switch (status) {
case "running": return "正在清理";
case "pausing": return "正在停止";
case "paused": return "已关闭";
case "error": return "本轮异常";
default: return "等待执行";
}
}
function dateTime(value?: string | number | null) {
if (!value) return "暂无";
const date = new Date(typeof value === "number" ? value * 1000 : value);
return Number.isNaN(date.getTime()) ? "暂无" : date.toLocaleString("zh-CN", { timeZone: "Asia/Shanghai", hour12: false });
}
export function ApiReadCacheSettingsPage() {
const [status, setStatus] = useState<ApiReadCacheStatus>();
const [retention, setRetention] = useState<AuditRetentionStatus>();
const [ttlInput, setTtlInput] = useState("300");
const [search, setSearch] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [retentionError, setRetentionError] = useState("");
const refresh = async () => {
setBusy(true);
const [cacheResult, retentionResult] = await Promise.allSettled([
requestStatus(),
getAuditRetentionStatus(),
]);
if (cacheResult.status === "fulfilled") {
setStatus(cacheResult.value);
setTtlInput(String(cacheResult.value.ttl_seconds));
setError("");
} else {
setError(cacheResult.reason instanceof Error ? cacheResult.reason.message : "读取缓存设置失败");
}
if (retentionResult.status === "fulfilled") {
setRetention(retentionResult.value);
setRetentionError("");
} else {
setRetentionError(retentionResult.reason instanceof Error ? retentionResult.reason.message : "读取清理设置失败");
}
setBusy(false);
};
useEffect(() => { void refresh(); }, []);
const save = async (update: ApiReadCacheUpdate, message: string) => {
setBusy(true);
try {
const saved = await requestStatus(update);
setStatus(saved);
if (update.ttl_seconds !== undefined) setTtlInput(String(saved.ttl_seconds));
setError("");
toast.success(message);
} catch (err) {
toast.error(err instanceof Error ? err.message : "保存设置失败");
} finally {
setBusy(false);
}
};
const toggleRetention = async (enabled: boolean) => {
setBusy(true);
try {
const saved = await setAuditRetentionPaused(!enabled);
setRetention(saved);
setRetentionError("");
toast.success(enabled ? "定时清理已开启" : saved.pause_requested ? "已关闭定时清理,当前批次结束后停止" : "定时清理已关闭");
} catch (err) {
toast.error(err instanceof Error ? err.message : "保存清理设置失败");
} finally {
setBusy(false);
}
};
const parsedTtl = Number(ttlInput);
const validTtl = Number.isInteger(parsedTtl) && parsedTtl >= 1 && parsedTtl <= 3600;
const collections = status?.collections ?? [];
const searchText = search.trim().toLowerCase();
const visibleCollections = collections.filter((item) =>
[item.label, item.id, item.scope, ...item.paths].join(" ").toLowerCase().includes(searchText),
);
const enabledCount = collections.filter((item) => item.enabled).length;
return (
<section className="space-y-5" data-testid="api-read-cache-settings" aria-busy={busy}>
<header className="flex flex-wrap items-start justify-between gap-3">
<div>
<h2 className="flex items-center gap-2 text-xl font-semibold"><DatabaseIcon className="size-5 text-primary" />Redis 与性能管理</h2>
<p className="mt-1 text-sm text-muted-foreground">统一管理接口缓存、浏览器状态查询和历史数据定时清理。</p>
</div>
<Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void refresh()}>
<RefreshCwIcon className={`size-4 ${busy ? "animate-spin" : ""}`} />刷新状态
</Button>
</header>
{error && <p role="alert" className="rounded-lg border border-destructive/30 p-3 text-sm text-destructive">{error}</p>}
<div className="overflow-hidden rounded-xl border">
<div className="flex items-center justify-between gap-4 bg-muted/30 p-4">
<div>
<h3 className="font-medium">Redis 读取缓存总开关</h3>
<p className="mt-1 text-sm text-muted-foreground">开关和有效期保存在 MySQL,服务重启后仍生效。</p>
</div>
<Switch
checked={status?.enabled ?? false}
disabled={!status || busy}
onCheckedChange={(enabled) => void save({ enabled }, enabled ? "Redis 读取缓存已开启" : "Redis 读取缓存已关闭")}
aria-label="启用 Redis 读取缓存"
/>
</div>
<div className="space-y-3 border-t p-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<label htmlFor="api-cache-ttl" className="text-sm font-medium">默认缓存有效期</label>
<p id="api-cache-ttl-help" className="mt-1 text-xs text-muted-foreground">1–3600 秒,默认 300 秒;保存后刷新缓存。</p>
</div>
<div className="flex items-center gap-2">
<Input
id="api-cache-ttl"
type="number"
min={1}
max={3600}
step={1}
value={ttlInput}
disabled={!status || busy}
onChange={(event) => setTtlInput(event.target.value)}
aria-label="Redis 缓存有效期(秒)"
aria-describedby="api-cache-ttl-help"
aria-invalid={!validTtl}
className="w-24"
/>
<span className="text-sm text-muted-foreground">秒</span>
<Button type="button" size="sm" variant="outline" disabled={!status || busy || !validTtl || parsedTtl === status.ttl_seconds} onClick={() => void save({ ttl_seconds: parsedTtl }, "Redis 缓存有效期已保存")}>
<SaveIcon className="size-4" />保存有效期
</Button>
</div>
</div>
{status && <div className="flex flex-wrap items-center gap-x-3 gap-y-2 text-xs text-muted-foreground">
<Badge variant="secondary">Redis 地址{status.redis_configured ? "已配置" : "未配置"}</Badge>
<span>单条结果上限 {Math.round(status.max_value_bytes / 1024)} KiB</span>
<span>关闭或连接失败时自动使用原查询</span>
</div>}
{status && !status.redis_configured && <p className="text-xs text-amber-700 dark:text-amber-400">当前未配置 Redis 地址。可以保存开关,但配置连接后才会使用缓存。</p>}
</div>
</div>
<div className="rounded-xl border p-4" data-testid="browser-status-control">
<div className="flex items-start justify-between gap-4">
<div className="min-w-0">
<h3 className="flex items-center gap-2 font-medium"><GlobeIcon className="size-4 text-primary" />允许浏览器状态查询</h3>
<p className="mt-1 break-all font-mono text-xs text-muted-foreground">GET /api/browser-context/status</p>
<p className="mt-2 text-sm text-muted-foreground">控制浏览器插件能否访问状态接口;关闭后,服务器会拒绝该接口的查询。</p>
</div>
<Switch
checked={status?.browser_status_enabled ?? false}
disabled={!status || busy}
onCheckedChange={(enabled) => void save({ browser_status_enabled: enabled }, enabled ? "浏览器状态查询已允许" : "浏览器状态查询已关闭")}
aria-label="允许浏览器状态查询"
/>
</div>
</div>
<div className="space-y-3 rounded-xl border p-4" data-testid="audit-retention-control">
<div className="flex items-start justify-between gap-4">
<div>
<h3 className="flex items-center gap-2 font-medium"><Clock3Icon className="size-4 text-primary" />开启历史数据定时清理</h3>
<p className="mt-1 text-sm text-muted-foreground">分批清理超过 {retention?.retention_days ?? 90} 天的工具调用、模型调用、已结束任务摘要和排行榜快照。</p>
</div>
<Switch
checked={retention ? !retention.paused : false}
disabled={!retention || busy}
onCheckedChange={(enabled) => void toggleRetention(enabled)}
aria-label="开启历史数据定时清理"
/>
</div>
<p className="text-xs text-muted-foreground">包含 tool_call_metrics、llm_call_metrics;关闭后在当前小批次结束时停止,关闭状态在服务重启后保留。</p>
{retentionError && <p role="alert" className="text-sm text-destructive">{retentionError}</p>}
{retention && <div className="flex flex-wrap items-center gap-x-4 gap-y-2 rounded-lg bg-muted/40 px-3 py-2 text-xs">
<Badge variant={retention.display_status === "error" ? "destructive" : "secondary"}>{retentionLabel(retention.display_status)}</Badge>
<span className="text-muted-foreground">间隔 {Math.round((retention.interval_seconds ?? 900) / 60)} 分钟</span>
<span className="text-muted-foreground">下次执行:{retention.paused ? "已关闭" : dateTime(retention.next_run_at)}</span>
<span className="text-muted-foreground">最近完成:{dateTime(retention.last_sweep?.finished_at)}</span>
</div>}
{retention?.pause_requested && <p role="status" className="text-sm text-amber-700 dark:text-amber-400">关闭请求已保存,正在等待当前批次结束。可点击“刷新状态”查看结果。</p>}
{retention?.last_error && <p role="alert" className="text-sm text-destructive">{retention.last_error}</p>}
</div>
<div className="space-y-3" data-testid="cache-collection-list">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h3 className="font-medium">已接入 Redis 的接口</h3>
<p className="mt-1 text-xs text-muted-foreground">共 {collections.length} 组,单项开启 {enabledCount} 组;同组接口共用开关。</p>
</div>
<div className="relative w-full sm:w-56">
<SearchIcon className="pointer-events-none absolute top-2.5 left-3 size-4 text-muted-foreground" />
<Input value={search} onChange={(event) => setSearch(event.target.value)} placeholder="搜索名称或接口地址" aria-label="搜索缓存接口" className="pl-9" />
</div>
</div>
<p className="text-xs text-muted-foreground">每组可独立开关,数据修改后缓存失效。总开关关闭时仍可配置单项,重新开启总开关后生效;各接口实际有效期见列表。</p>
{status && !status.enabled && <p className="rounded-lg bg-muted px-3 py-2 text-sm">总开关已关闭,当前所有接口均使用原查询。</p>}
<div className="overflow-x-auto rounded-xl border">
<table className="w-full table-fixed text-left text-sm">
<thead className="bg-muted/40 text-xs text-muted-foreground">
<tr>
<th className="w-[56%] px-4 py-3 font-medium" scope="col">接口 / 缓存范围</th>
<th className="w-[18%] px-2 py-3 font-medium" scope="col">有效期</th>
<th className="w-[26%] px-4 py-3 text-right font-medium" scope="col">使用 Redis</th>
</tr>
</thead>
<tbody className="divide-y">
{visibleCollections.map((item) => {
const effective = item.enabled && status?.enabled && status.redis_configured;
const description = !item.enabled ? "单项已关闭" : !status?.enabled ? "总开关关闭" : !status.redis_configured ? "待配置连接" : "缓存已启用";
return <tr key={item.id} data-testid={`cache-collection-${item.id}`}>
<td className="px-4 py-3 align-top">
<p className="font-medium">{item.label}</p>
<div className="mt-1 space-y-1 text-[11px] text-muted-foreground">
{item.paths.map((path) => <p key={path} className="break-all font-mono">{path}</p>)}
</div>
<p className="mt-1 text-xs text-muted-foreground">{item.scope}</p>
</td>
<td className="px-2 py-3 align-top text-xs">{item.ttl_seconds} 秒</td>
<td className="px-4 py-3 text-right align-top">
<Switch
checked={item.enabled}
disabled={busy}
onCheckedChange={(enabled) => void save({ collection_overrides: { [item.id]: enabled } }, `${item.label}缓存${enabled ? "已开启" : "已关闭"}`)}
aria-label={`${item.label}使用 Redis 缓存`}
/>
<p className={`mt-1 text-[11px] ${effective ? "text-primary" : "text-muted-foreground"}`}>{description}</p>
</td>
</tr>;
})}
{!visibleCollections.length && <tr><td colSpan={3} className="px-4 py-8 text-center text-muted-foreground">{!status ? error ? "接口列表读取失败,请刷新重试" : "正在读取接口列表…" : searchText ? "没有匹配的接口" : "暂无已接入的接口"}</td></tr>}
</tbody>
</table>
</div>
</div>
</section>
);
}
@@ -0,0 +1,273 @@
"use client";
import { ImageUp, Loader2, RotateCcw } from "lucide-react";
import { useEffect, useMemo, useRef, useState, type ChangeEvent } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { useTheme } from "@/contexts/ThemeContext";
import {
getHeaderBrandAsset,
getHeaderBrandFallback,
} from "@/core/branding/brand-assets";
import { resolveAppIdentityLogoUrl } from "@/core/system-settings/api";
import {
useAppIdentitySettings,
useDeleteAppIdentitySettings,
useUpdateAppIdentitySettings,
} from "@/core/system-settings/hooks";
import { SettingsSection } from "./settings-section";
const MAX_LOGO_BYTES = 10 * 1024 * 1024;
const ACCEPTED_LOGO_TYPES = new Set([
"image/png",
"image/jpeg",
"image/webp",
]);
export function AppIdentitySettingsPage() {
const { theme } = useTheme();
const staticLogo = getHeaderBrandAsset(theme);
const staticFallback = getHeaderBrandFallback(theme);
const [staticLogoFailed, setStaticLogoFailed] = useState(false);
const { data: identity, isPending } = useAppIdentitySettings();
const updateIdentity = useUpdateAppIdentitySettings();
const deleteIdentity = useDeleteAppIdentitySettings();
const fileInputRef = useRef<HTMLInputElement>(null);
const [systemName, setSystemName] = useState("");
const [pendingLogo, setPendingLogo] = useState<File | null>(null);
const [removeLogo, setRemoveLogo] = useState(false);
const [resetOpen, setResetOpen] = useState(false);
useEffect(() => {
setSystemName(identity?.system_name ?? "");
setPendingLogo(null);
setRemoveLogo(false);
if (fileInputRef.current) fileInputRef.current.value = "";
}, [identity?.system_name, identity?.logo_version, identity?.has_logo]);
const previewUrl = useMemo(
() => (pendingLogo ? URL.createObjectURL(pendingLogo) : undefined),
[pendingLogo],
);
useEffect(
() => () => {
if (previewUrl) URL.revokeObjectURL(previewUrl);
},
[previewUrl],
);
const savedLogoUrl = removeLogo
? undefined
: resolveAppIdentityLogoUrl(identity?.logo_url);
const displayedLogoUrl = previewUrl ?? savedLogoUrl;
const normalizedName = systemName.trim().replace(/\s+/g, " ");
const hasChanges =
normalizedName !== (identity?.system_name ?? "") ||
Boolean(pendingLogo) ||
removeLogo;
const customized = Boolean(identity?.system_name || identity?.has_logo);
const busy = updateIdentity.isPending || deleteIdentity.isPending;
const handleLogoChange = (event: ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
if (!ACCEPTED_LOGO_TYPES.has(file.type)) {
toast.error("Logo 仅支持 PNG、JPG 或 WebP 图片");
event.target.value = "";
return;
}
if (file.size > MAX_LOGO_BYTES) {
toast.error("Logo 文件不能超过 10MB");
event.target.value = "";
return;
}
setPendingLogo(file);
setRemoveLogo(false);
};
const handleUseStaticLogo = () => {
setPendingLogo(null);
setRemoveLogo(true);
if (fileInputRef.current) fileInputRef.current.value = "";
};
const handleSave = async () => {
try {
await updateIdentity.mutateAsync({
systemName: normalizedName,
logo: pendingLogo,
removeLogo,
});
toast.success("系统名称已保存", {
description: "导航、侧栏和欢迎区会使用这里的名称和 Logo。",
});
} catch (error) {
toast.error(error instanceof Error ? error.message : "系统名称保存失败");
}
};
const handleReset = async () => {
try {
await deleteIdentity.mutateAsync();
setResetOpen(false);
toast.success("已恢复默认系统名称和 Logo");
} catch (error) {
toast.error(error instanceof Error ? error.message : "清除系统名称失败");
}
};
return (
<>
<SettingsSection
title="系统名称"
description="修改本系统导航栏、侧栏和欢迎区显示的名称与 Logo。名称留空时继续使用现有名称;没有上传 Logo 时继续使用内置静态图片。这里不会改「生成网页标识」。"
>
<div className="space-y-6">
<div className="space-y-2">
<label htmlFor="app-identity-name" className="text-sm font-medium">
系统名称
</label>
<Input
id="app-identity-name"
value={systemName}
onChange={(event) => setSystemName(event.target.value)}
placeholder="留空则继续使用 CM业务中心 / CM 助手"
maxLength={80}
disabled={isPending || busy}
/>
<div className="flex justify-between gap-4 text-xs text-muted-foreground">
<span>最多 80 个字符。</span>
<span className="tabular-nums">{systemName.length}/80</span>
</div>
</div>
<div className="space-y-3">
<div>
<div className="text-sm font-medium">系统 Logo</div>
<p className="mt-1 text-xs leading-5 text-muted-foreground">
上传后,导航、侧栏和欢迎区都使用这一张图片。未上传时按当前主题使用内置 Logo。
</p>
</div>
<div className="grid gap-4 rounded-lg border bg-muted/20 p-4 sm:grid-cols-[160px_minmax(0,1fr)]">
<div className="flex h-28 items-center justify-center overflow-hidden rounded-lg border border-dashed bg-background p-3">
{displayedLogoUrl ? (
<img
src={displayedLogoUrl}
alt="系统 Logo 预览"
className="max-h-full max-w-full object-contain"
/>
) : (
<img
src={staticLogoFailed ? staticFallback : staticLogo}
alt="当前静态 Logo"
className="max-h-full max-w-full object-contain"
onError={() => setStaticLogoFailed(true)}
/>
)}
</div>
<div className="flex min-w-0 flex-col justify-center gap-3">
<input
ref={fileInputRef}
id="app-identity-logo"
type="file"
accept="image/png,image/jpeg,image/webp"
className="sr-only"
onChange={handleLogoChange}
disabled={isPending || busy}
/>
<div className="flex flex-wrap gap-2">
<Button
type="button"
variant="outline"
className="h-11"
onClick={() => fileInputRef.current?.click()}
disabled={isPending || busy}
>
<ImageUp aria-hidden />
{displayedLogoUrl ? "更换 Logo" : "上传 Logo"}
</Button>
<Button
type="button"
variant="outline"
className="h-11"
onClick={handleUseStaticLogo}
disabled={
isPending ||
busy ||
(!identity?.has_logo && !pendingLogo) ||
(removeLogo && !pendingLogo)
}
>
使用静态 Logo
</Button>
</div>
{pendingLogo && (
<p className="truncate text-xs text-muted-foreground" title={pendingLogo.name}>
待上传:{pendingLogo.name}
</p>
)}
{removeLogo && (
<p className="text-xs text-muted-foreground">
保存后恢复为内置静态 Logo。
</p>
)}
</div>
</div>
</div>
<div className="flex flex-wrap items-center justify-between gap-3 border-t pt-5">
<Button
type="button"
variant="outline"
className="h-11"
onClick={() => setResetOpen(true)}
disabled={!customized || busy}
>
<RotateCcw aria-hidden />
清除配置
</Button>
<Button
type="button"
className="h-11 min-w-28"
onClick={handleSave}
disabled={!hasChanges || isPending || busy}
>
{updateIdentity.isPending && <Loader2 className="animate-spin" aria-hidden />}
{updateIdentity.isPending ? "保存中..." : "保存系统名称"}
</Button>
</div>
</div>
</SettingsSection>
<Dialog open={resetOpen} onOpenChange={setResetOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>清除系统名称和 Logo?</DialogTitle>
</DialogHeader>
<p className="text-sm text-muted-foreground">
清除后,导航和欢迎区恢复为原来的名称,Logo 恢复为内置静态图片。
</p>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => setResetOpen(false)}>
取消
</Button>
<Button type="button" onClick={handleReset} disabled={busy}>
清除
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}
@@ -42,6 +42,22 @@ import { isIsolatedSession, setIsolatedSession } from "@/core/embed/embed-sessio
import { enUS, isLocale, zhCN, type Locale } from "@/core/i18n";
import { useI18n } from "@/core/i18n/hooks";
import { useLocalSettings } from "@/core/settings";
import {
AGENT_COMPOSER_WIDTH_MAX,
AGENT_COMPOSER_WIDTH_MIN,
COMPOSER_HEIGHT_MAX,
COMPOSER_HEIGHT_MIN,
COMPOSER_SCALE_DEFAULT,
COMPOSER_WIDTH_MAX,
COMPOSER_WIDTH_MIN,
isComposerWidthChoice,
normalizeAgentComposerWidthPercent,
normalizeComposerHeightPercent,
normalizeComposerWidthPercent,
resolveAgentComposerWidthPercent,
resolveComposerHeightPercent,
resolveComposerWidthPercent,
} from "@/core/settings/composer-width";
import {
useUpdateUserPreferences,
useUserPreferencesQuery,
@@ -50,13 +66,16 @@ import {
useAppearanceSettings,
useCitationDisplaySettings,
useHtmlMapSettings,
useHtmlRuntimeSettings,
useLayoutMode,
useUpdateAppearanceSettings,
useUpdateCitationDisplaySettings,
useUpdateHtmlMapSettings,
useUpdateHtmlRuntimeSettings,
} from "@/core/system-settings/hooks";
import type { HtmlMapEngine } from "@/core/system-settings/api";
import type {
AppearanceUpdate,
CompactShortcutButton,
CompactShortcutRouteParam,
} from "@/core/system-settings/api";
@@ -98,6 +117,278 @@ function newShortcutParam(): CompactShortcutRouteParam {
};
}
type ScaleAxisConfig = {
min: number;
max: number;
value: number;
normalize: (raw: string) => number;
onChange: (next: number) => void;
onCommit?: (next: number) => void;
};
function ScaleAxis({
title,
ariaLabel,
low,
high,
preview,
axis,
}: {
title: string;
ariaLabel: string;
low: string;
high: string;
preview: "width" | "height";
axis: ScaleAxisConfig;
}) {
const span = Math.max(1, axis.max - axis.min);
const previewPercent = 8 + ((axis.value - axis.min) / span) * 92;
const readValue = (raw: string) => axis.normalize(raw);
return (
<div className="space-y-2">
<div className="text-muted-foreground text-xs">{title}</div>
<input
type="range"
min={axis.min}
max={axis.max}
step={1}
value={axis.value}
aria-label={ariaLabel}
onChange={(event) => axis.onChange(readValue(event.target.value))}
onPointerUp={(event) =>
axis.onCommit?.(readValue(event.currentTarget.value))
}
onKeyUp={(event) =>
axis.onCommit?.(readValue(event.currentTarget.value))
}
className="accent-primary h-2 w-full cursor-pointer"
/>
{preview === "height" ? (
<div className="bg-muted/60 flex h-14 items-end rounded-lg border px-3 py-1.5">
<div
className="bg-background w-full rounded-md border shadow-sm"
style={{ height: `${previewPercent}%` }}
/>
</div>
) : (
<div className="bg-muted/60 flex h-11 items-center rounded-lg border px-3">
<div
className="bg-background h-7 rounded-md border shadow-sm"
style={{ width: `${previewPercent}%` }}
/>
</div>
)}
<div className="text-muted-foreground flex items-center justify-between text-xs">
<span>{low}</span>
<span>{high}</span>
</div>
</div>
);
}
function ComposerSizeCard({
label,
hint,
width,
height,
resetDisabled,
resetLabel = "恢复默认",
onReset,
}: {
label: string;
hint?: string;
width: ScaleAxisConfig;
height: ScaleAxisConfig;
resetDisabled?: boolean;
resetLabel?: string;
onReset: () => void;
}) {
return (
<div className="space-y-4 rounded-lg border p-4">
<div>
<div className="text-sm font-medium">{label}</div>
{hint ? (
<p className="text-muted-foreground mt-1 text-xs leading-5">{hint}</p>
) : null}
</div>
<ScaleAxis
title="宽度"
ariaLabel={`${label}宽度`}
low="较窄"
high="较宽"
preview="width"
axis={width}
/>
<ScaleAxis
title="高度"
ariaLabel={`${label}高度`}
low="较矮"
high="较高"
preview="height"
axis={height}
/>
<div className="flex justify-center">
<Button
type="button"
variant="outline"
size="sm"
disabled={resetDisabled}
onClick={onReset}
>
{resetLabel}
</Button>
</div>
</div>
);
}
type ComposerDefaultKey =
| "widthFull"
| "heightFull"
| "widthCompact"
| "heightCompact"
| "agentWidth"
| "agentHeight";
const COMPOSER_DEFAULT_FIELDS: Record<ComposerDefaultKey, keyof AppearanceUpdate> = {
widthFull: "default_composer_width_full",
heightFull: "default_composer_height_full",
widthCompact: "default_composer_width_compact",
heightCompact: "default_composer_height_compact",
agentWidth: "default_agent_composer_width",
agentHeight: "default_agent_composer_height",
};
function AdminComposerSizeDefaults({
values,
saving,
onSave,
}: {
values: Record<ComposerDefaultKey, number>;
saving: boolean;
onSave: (patch: AppearanceUpdate) => Promise<void>;
}) {
const [draft, setDraft] = useState<Partial<Record<ComposerDefaultKey, number>>>({});
const shown = {
widthFull: draft.widthFull ?? values.widthFull,
heightFull: draft.heightFull ?? values.heightFull,
widthCompact: draft.widthCompact ?? values.widthCompact,
heightCompact: draft.heightCompact ?? values.heightCompact,
agentWidth: draft.agentWidth ?? values.agentWidth,
agentHeight: draft.agentHeight ?? values.agentHeight,
};
const commit = (key: ComposerDefaultKey, next: number) => {
if (next === values[key]) {
setDraft((prev) => ({ ...prev, [key]: undefined }));
return;
}
const field = COMPOSER_DEFAULT_FIELDS[key];
void onSave({ [field]: next }).finally(() => {
setDraft((prev) => ({ ...prev, [key]: undefined }));
});
};
const axis = (
key: ComposerDefaultKey,
min: number,
max: number,
normalize: (raw: string) => number,
): ScaleAxisConfig => ({
min,
max,
value: shown[key],
normalize,
onChange: (next) => setDraft((prev) => ({ ...prev, [key]: next })),
onCommit: (next) => commit(key, next),
});
const resetCard = (widthKey: ComposerDefaultKey, heightKey: ComposerDefaultKey) => {
setDraft((prev) => ({
...prev,
[widthKey]: COMPOSER_SCALE_DEFAULT,
[heightKey]: COMPOSER_SCALE_DEFAULT,
}));
const widthField = COMPOSER_DEFAULT_FIELDS[widthKey];
const heightField = COMPOSER_DEFAULT_FIELDS[heightKey];
void onSave({
[widthField]: COMPOSER_SCALE_DEFAULT,
[heightField]: COMPOSER_SCALE_DEFAULT,
}).finally(() => {
setDraft((prev) => ({
...prev,
[widthKey]: undefined,
[heightKey]: undefined,
}));
});
};
const cards: Array<{
key: string;
label: string;
hint?: string;
widthKey: ComposerDefaultKey;
heightKey: ComposerDefaultKey;
widthMin: number;
widthMax: number;
normalizeWidth: (raw: string) => number;
}> = [
{
key: "full",
label: "全量模式",
widthKey: "widthFull",
heightKey: "heightFull",
widthMin: COMPOSER_WIDTH_MIN,
widthMax: COMPOSER_WIDTH_MAX,
normalizeWidth: normalizeComposerWidthPercent,
},
{
key: "compact",
label: "简洁模式",
widthKey: "widthCompact",
heightKey: "heightCompact",
widthMin: COMPOSER_WIDTH_MIN,
widthMax: COMPOSER_WIDTH_MAX,
normalizeWidth: normalizeComposerWidthPercent,
},
{
key: "agent",
label: "智能体问答",
hint: "宽度最多铺满输入框所在的中间区域,不会超出两侧面板。",
widthKey: "agentWidth",
heightKey: "agentHeight",
widthMin: AGENT_COMPOSER_WIDTH_MIN,
widthMax: AGENT_COMPOSER_WIDTH_MAX,
normalizeWidth: normalizeAgentComposerWidthPercent,
},
];
return (
<div className="grid gap-3 lg:grid-cols-2">
{cards.map((card) => (
<ComposerSizeCard
key={card.key}
label={card.label}
hint={card.hint}
width={axis(
card.widthKey,
card.widthMin,
card.widthMax,
card.normalizeWidth,
)}
height={axis(
card.heightKey,
COMPOSER_HEIGHT_MIN,
COMPOSER_HEIGHT_MAX,
normalizeComposerHeightPercent,
)}
resetDisabled={
saving ||
(shown[card.widthKey] === COMPOSER_SCALE_DEFAULT &&
shown[card.heightKey] === COMPOSER_SCALE_DEFAULT)
}
onReset={() => resetCard(card.widthKey, card.heightKey)}
/>
))}
</div>
);
}
function newShortcutButton(): CompactShortcutButton {
return {
id: makeShortcutId(),
@@ -196,6 +487,15 @@ export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
const updateCitationDisplay = useUpdateCitationDisplaySettings();
const { data: htmlMap } = useHtmlMapSettings();
const updateHtmlMap = useUpdateHtmlMapSettings();
const { data: htmlRuntime } = useHtmlRuntimeSettings();
const updateHtmlRuntime = useUpdateHtmlRuntimeSettings();
const [htmlRuntimeDraft, setHtmlRuntimeDraft] = useState<{
base_url: string;
map_tile_url: string;
} | null>(null);
const runtimeBaseUrl = htmlRuntimeDraft?.base_url ?? htmlRuntime?.base_url ?? "";
const runtimeTileUrl =
htmlRuntimeDraft?.map_tile_url ?? htmlRuntime?.map_tile_url ?? "";
const globalDefault = appearance?.default_theme ?? "light";
const globalSkillView = appearance?.default_skill_view ?? "list";
const globalAgentView = appearance?.default_agent_view ?? "card";
@@ -272,6 +572,14 @@ export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
}
};
const handleSetDefaultComposerSize = async (patch: AppearanceUpdate) => {
try {
await updateAppearance.mutateAsync(patch);
} catch (e) {
toast.error(e instanceof Error ? e.message : "保存失败");
}
};
const handleSetDefaultLayoutMode = async (value: "full" | "compact") => {
if (value === globalLayoutMode) return;
try {
@@ -536,6 +844,160 @@ export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
</div>
</SettingsSection>
<Separator />
<SettingsSection
title="输入框尺寸"
description="分别调整普通问答在全量模式、简洁模式下的输入框,以及智能体问答的输入框。没有自己调整时,使用管理员设置的系统默认。"
>
<div className="grid gap-3 lg:grid-cols-2">
<ComposerSizeCard
label="全量模式"
resetLabel="跟随系统默认"
resetDisabled={
!isComposerWidthChoice(settings.display.composerWidthFull) &&
!isComposerWidthChoice(settings.display.composerHeightFull)
}
width={{
min: COMPOSER_WIDTH_MIN,
max: COMPOSER_WIDTH_MAX,
value: resolveComposerWidthPercent(
settings.display.composerWidthFull,
appearance?.default_composer_width_full,
),
normalize: normalizeComposerWidthPercent,
onChange: (next) =>
setSettings("display", { composerWidthFull: next }),
}}
height={{
min: COMPOSER_HEIGHT_MIN,
max: COMPOSER_HEIGHT_MAX,
value: resolveComposerHeightPercent(
settings.display.composerHeightFull,
appearance?.default_composer_height_full,
),
normalize: normalizeComposerHeightPercent,
onChange: (next) =>
setSettings("display", { composerHeightFull: next }),
}}
onReset={() =>
setSettings("display", {
composerWidthFull: undefined,
composerHeightFull: undefined,
})
}
/>
<ComposerSizeCard
label="简洁模式"
resetLabel="跟随系统默认"
resetDisabled={
!isComposerWidthChoice(settings.display.composerWidthCompact) &&
!isComposerWidthChoice(settings.display.composerHeightCompact)
}
width={{
min: COMPOSER_WIDTH_MIN,
max: COMPOSER_WIDTH_MAX,
value: resolveComposerWidthPercent(
settings.display.composerWidthCompact,
appearance?.default_composer_width_compact,
),
normalize: normalizeComposerWidthPercent,
onChange: (next) =>
setSettings("display", { composerWidthCompact: next }),
}}
height={{
min: COMPOSER_HEIGHT_MIN,
max: COMPOSER_HEIGHT_MAX,
value: resolveComposerHeightPercent(
settings.display.composerHeightCompact,
appearance?.default_composer_height_compact,
),
normalize: normalizeComposerHeightPercent,
onChange: (next) =>
setSettings("display", { composerHeightCompact: next }),
}}
onReset={() =>
setSettings("display", {
composerWidthCompact: undefined,
composerHeightCompact: undefined,
})
}
/>
<ComposerSizeCard
label="智能体问答"
hint="宽度最多铺满输入框所在的中间区域,不会超出两侧面板。"
resetLabel="跟随系统默认"
resetDisabled={
!isComposerWidthChoice(settings.display.agentComposerWidth) &&
!isComposerWidthChoice(settings.display.agentComposerHeight)
}
width={{
min: AGENT_COMPOSER_WIDTH_MIN,
max: AGENT_COMPOSER_WIDTH_MAX,
value: resolveAgentComposerWidthPercent(
settings.display.agentComposerWidth,
appearance?.default_agent_composer_width,
),
normalize: normalizeAgentComposerWidthPercent,
onChange: (next) =>
setSettings("display", { agentComposerWidth: next }),
}}
height={{
min: COMPOSER_HEIGHT_MIN,
max: COMPOSER_HEIGHT_MAX,
value: resolveComposerHeightPercent(
settings.display.agentComposerHeight,
appearance?.default_agent_composer_height,
),
normalize: normalizeComposerHeightPercent,
onChange: (next) =>
setSettings("display", { agentComposerHeight: next }),
}}
onReset={() =>
setSettings("display", {
agentComposerWidth: undefined,
agentComposerHeight: undefined,
})
}
/>
</div>
</SettingsSection>
{isAdmin && (
<>
<Separator />
<SettingsSection
title="系统默认输入框尺寸(管理员)"
description="给还没有自己调整过输入框尺寸的用户使用。已经调整过的人保持自己的尺寸。"
>
<AdminComposerSizeDefaults
values={{
widthFull: normalizeComposerWidthPercent(
appearance?.default_composer_width_full,
),
heightFull: normalizeComposerHeightPercent(
appearance?.default_composer_height_full,
),
widthCompact: normalizeComposerWidthPercent(
appearance?.default_composer_width_compact,
),
heightCompact: normalizeComposerHeightPercent(
appearance?.default_composer_height_compact,
),
agentWidth: normalizeAgentComposerWidthPercent(
appearance?.default_agent_composer_width,
),
agentHeight: normalizeComposerHeightPercent(
appearance?.default_agent_composer_height,
),
}}
saving={updateAppearance.isPending}
onSave={handleSetDefaultComposerSize}
/>
</SettingsSection>
</>
)}
{isAdmin && (
<>
<Separator />
@@ -930,7 +1392,7 @@ export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
<div>
<div className="text-sm font-medium">HTML 地图</div>
<p className="text-muted-foreground mt-1 max-w-md text-xs leading-relaxed">
管理员配置。生成带地图的 HTML 网页时使用哪种地图。ECharts 使用本地行政区划;地图网页使用 Leaflet 瓦片,地址在后台 config.yaml 的 html_runtime.map_tile_url。下一次生成的页面生效。
管理员配置。生成带地图的 HTML 网页时使用哪种地图。ECharts 使用本地行政区划;地图网页使用 Leaflet 瓦片,瓦片地址在下面的「地图瓦片地址」里填写。下一次生成的页面生效。
</p>
</div>
<Select
@@ -953,6 +1415,77 @@ export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
</Select>
</div>
)}
{isAdmin && (
<div className="rounded-lg border p-4">
<div className="text-sm font-medium">HTML 运行地址</div>
<p className="text-muted-foreground mt-1 max-w-2xl text-xs leading-relaxed">
管理员配置。画网页时,图表、流程图、地图脚本和上传图片都从这里加载。请填写用户浏览器真正能够打开的地址。只填写域名时,会自动补上 /api/public/html-runtime;如果前面还有访问前缀,请写成完整地址,例如 https://域名/前缀/api/public/html-runtime。保存后只影响之后新画的网页。
</p>
<label className="mt-3 block text-xs font-medium" htmlFor="html-runtime-base-url">
运行库地址
</label>
<Input
id="html-runtime-base-url"
value={runtimeBaseUrl}
disabled={!htmlRuntime || updateHtmlRuntime.isPending}
onChange={(event) =>
setHtmlRuntimeDraft({
base_url: event.target.value,
map_tile_url: runtimeTileUrl,
})
}
placeholder="https://你的域名/api/public/html-runtime"
className="mt-1 font-mono text-xs"
spellCheck={false}
/>
<label className="mt-3 block text-xs font-medium" htmlFor="html-map-tile-url">
地图瓦片地址
</label>
<p className="text-muted-foreground mt-1 text-xs leading-relaxed">
地图网页使用的瓦片模板,需要包含 {"{z}"}、{"{x}"}、{"{y}"}。浏览器重新打开页面后生效。
</p>
<Input
id="html-map-tile-url"
value={runtimeTileUrl}
disabled={!htmlRuntime || updateHtmlRuntime.isPending}
onChange={(event) =>
setHtmlRuntimeDraft({
base_url: runtimeBaseUrl,
map_tile_url: event.target.value,
})
}
placeholder="https://tiles.example/{z}/{x}/{y}.png"
className="mt-1 font-mono text-xs"
spellCheck={false}
/>
<div className="mt-3 flex justify-end">
<Button
type="button"
size="sm"
disabled={
!htmlRuntime ||
updateHtmlRuntime.isPending ||
(runtimeBaseUrl === htmlRuntime.base_url &&
runtimeTileUrl === htmlRuntime.map_tile_url)
}
onClick={() =>
updateHtmlRuntime.mutate(
{ base_url: runtimeBaseUrl.trim(), map_tile_url: runtimeTileUrl.trim() },
{
onSuccess: () => {
setHtmlRuntimeDraft(null);
toast.success("HTML 运行地址已保存,之后新画的网页会使用这个地址");
},
onError: (error) => toast.error(error.message || "保存失败"),
},
)
}
>
{updateHtmlRuntime.isPending ? "保存中..." : "保存地址"}
</Button>
</div>
</div>
)}
{isAdmin && (
<div className="flex items-start justify-between gap-4 rounded-lg border p-4">
<div>
@@ -0,0 +1,253 @@
"use client";
import { ArchiveIcon, DatabaseIcon, RotateCcwIcon, Trash2Icon } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { getStoredAuth } from "@/core/auth";
import { apiFetch } from "@/core/api";
import { getBackendBaseURL } from "@/core/config";
import {
ACTIVE_ARCHIVE_JOB_STATUSES as ACTIVE,
archiveMonthDisplayStatus,
canPurgeArchivedMonth,
isArchiveMonthActive,
} from "@/core/chat-archive-state";
type ArchiveJob = {
job_id: string;
action: "archive" | "purge" | "rollback";
status: string;
total_threads: number;
processed_threads: number;
failed_threads: number;
current_thread_id?: string | null;
snapshot_at?: string;
processed_through?: string | null;
message?: string;
error?: string | null;
};
type ArchiveMonth = {
month: string;
thread_count: number;
status: string;
copied_threads: number;
deleted_threads: number;
sqlite_bytes: number;
latest_job?: ArchiveJob;
};
type Inventory = {
archive_dir: string;
disk_total_bytes: number;
disk_free_bytes: number;
month_basis: string;
warning: string;
months: ArchiveMonth[];
};
function formatBytes(bytes: number) {
if (!bytes) return "尚无归档文件";
const units = ["B", "KB", "MB", "GB", "TB"];
let value = bytes;
let unit = 0;
while (value >= 1024 && unit < units.length - 1) {
value /= 1024;
unit += 1;
}
return `${value.toFixed(unit >= 3 ? 2 : 1)} ${units[unit]}`;
}
function currentLocalMonth() {
const now = new Date();
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;
}
function statusLabel(status: string) {
switch (status) {
case "ready": return "归档已校验";
case "deleted": return "PG 已清理";
case "copying": return "正在归档";
case "deleting": return "正在清理 PG";
case "restoring": return "正在回滚";
case "cancelling": return "正在停止";
case "partial": return "部分完成";
case "interrupted": return "已中断,可重新归档";
default: return "尚未归档";
}
}
function statusTone(status: string): "default" | "secondary" | "outline" | "destructive" {
if (status === "deleted" || status === "ready") return "default";
if (status === "partial" || status === "interrupted") return "destructive";
if (ACTIVE.has(status) || ["copying", "deleting", "restoring"].includes(status)) return "secondary";
return "outline";
}
export function ChatArchiveSettingsPage() {
const [inventory, setInventory] = useState<Inventory | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [busyMonth, setBusyMonth] = useState<string | null>(null);
const load = useCallback(async (signal?: AbortSignal) => {
try {
const response = await apiFetch(`${getBackendBaseURL()}/api/admin/chat-archive/months`, { signal });
if (!response.ok) throw new Error((await response.text()) || `加载失败 (${response.status})`);
setInventory(await response.json() as Inventory);
setError(null);
} catch (cause) {
if (signal?.aborted) return;
setError(cause instanceof Error ? cause.message : "读取归档月份失败");
} finally {
if (!signal?.aborted) setLoading(false);
}
}, []);
useEffect(() => {
const controller = new AbortController();
void load(controller.signal);
return () => controller.abort();
}, [load]);
useEffect(() => {
const activeJobs = inventory?.months
.map((month) => month.latest_job)
.filter((job): job is ArchiveJob => Boolean(job && ACTIVE.has(job.status)));
if (!activeJobs?.length) return;
const timer = window.setInterval(() => {
void Promise.all(activeJobs.map(async (job) => {
const response = await apiFetch(`${getBackendBaseURL()}/api/admin/chat-archive/jobs/${job.job_id}`);
if (!response.ok) return null;
return await response.json() as ArchiveJob;
})).then((jobs) => {
const updates = jobs.filter((job): job is ArchiveJob => Boolean(job));
if (!updates.length) return;
setInventory((current) => current ? {
...current,
months: current.months.map((month) => {
const job = updates.find((item) => item.job_id === month.latest_job?.job_id);
return job ? { ...month, latest_job: job } : month;
}),
} : current);
if (updates.some((job) => !ACTIVE.has(job.status))) void load();
}).catch(() => undefined);
}, 2500);
return () => window.clearInterval(timer);
}, [inventory, load]);
const runAction = async (month: ArchiveMonth, action: ArchiveJob["action"]) => {
const confirmation = action === "purge"
? "确认清理该月已归档的 PostgreSQL 数据?系统会逐会话重新校验 SQLite 备份,只清理校验通过的会话;失败、未归档和正在运行的会话不会清理。"
: "确认回滚到 PostgreSQL?月度 SQLite 文件中的归档记录会保留。";
if (action !== "archive" && !window.confirm(confirmation)) return;
setBusyMonth(month.month);
setError(null);
try {
const response = await apiFetch(`${getBackendBaseURL()}/api/admin/chat-archive/months/${month.month}/${action === "purge" ? "delete-postgres" : action}`, { method: "POST" });
if (!response.ok) throw new Error((await response.text()) || `操作失败 (${response.status})`);
await load();
} catch (cause) {
setError(cause instanceof Error ? cause.message : "操作失败");
} finally {
setBusyMonth(null);
}
};
const isAdmin = getStoredAuth()?.system_role === "admin";
if (!isAdmin) return <Alert><AlertTitle>仅管理员可用</AlertTitle><AlertDescription>聊天归档管理需要管理员权限。</AlertDescription></Alert>;
return (
<section className="space-y-5" data-testid="chat-archive-settings">
<div>
<h2 className="text-lg font-semibold">聊天记录月度归档</h2>
<p className="text-muted-foreground mt-1 text-sm">整条会话按创建月份归档(跨月消息一起保留):先复制并校验到按月 SQLite 文件,再单独清理 PostgreSQL;历史会话仍可读取,必要时可回滚。单纯部署或打开此页不会扫描检查点表或改变当前聊天存储;只有管理员启动归档、清理或回滚任务后才会处理数据。</p>
</div>
<Alert>
<DatabaseIcon className="size-4" />
<AlertTitle>归档目录</AlertTitle>
<AlertDescription className="space-y-1 break-all">
<div>{inventory?.archive_dir ?? "正在读取…"}</div>
<div>目标磁盘可用 {inventory ? formatBytes(inventory.disk_free_bytes) : "…"} / {inventory ? formatBytes(inventory.disk_total_bytes) : "…"}。归档过程中保留至少 2 GiB 空间;若不足,任务会暂停并保留 PG 数据。</div>
</AlertDescription>
</Alert>
<Alert>
<AlertTitle>低负载处理方式</AlertTitle>
<AlertDescription>{inventory?.warning ?? "月份按会话创建时间展示;归档任务在后台逐会话处理,页面关闭不影响执行;中断后可重新执行。"} 单个会话失败会记录错误并继续处理其他会话;部分归档完成后也可清理已校验的 PG 数据,未归档或校验失败的会话会保留。磁盘不足等整体故障仍会停止任务。删除 PostgreSQL 前会重新校验目标 SQLite 文件中的检查点;清理按会话逐条执行,每条间隔 0.5 秒,运行中的问答会跳过并计入进度,结束后可重新清理。清理后空间可供 PostgreSQL 后续复用;表文件大小不会保证立即缩小,系统不会自动运行可能带来较大 I/O 的 VACUUM FULL。</AlertDescription>
</Alert>
{error && <Alert variant="destructive"><AlertTitle>操作未完成</AlertTitle><AlertDescription className="break-all">{error}</AlertDescription></Alert>}
{loading ? <p className="text-muted-foreground text-sm">正在读取月份…</p> : inventory?.months.length ? (
<div className="space-y-3">
{inventory.months.map((month) => {
const job = month.latest_job;
const active = isArchiveMonthActive(month);
const displayStatus = archiveMonthDisplayStatus(month);
const canPurge = canPurgeArchivedMonth(month);
const canRollback = month.deleted_threads > 0;
return (
<Card key={month.month}>
<CardHeader className="pb-3">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<CardTitle className="text-base">{month.month}</CardTitle>
<CardDescription className="mt-1">{month.thread_count.toLocaleString()} 个会话 · SQLite:{formatBytes(month.sqlite_bytes)}</CardDescription>
</div>
<Badge variant={statusTone(displayStatus)}>{statusLabel(displayStatus)}</Badge>
</div>
</CardHeader>
<CardContent className="space-y-3">
<p className="text-muted-foreground text-xs">已复制 {month.copied_threads.toLocaleString()} 个 · PG 已清理 {month.deleted_threads.toLocaleString()} 个</p>
{job && <div className="bg-muted/50 rounded-md p-3 text-sm">
<div>{job.message || "任务状态已更新"}</div>
<div className="text-muted-foreground mt-1 text-xs">
已处理 {job.processed_threads.toLocaleString()} / {job.total_threads.toLocaleString()} 个
{job.failed_threads > 0 && ` · 失败或跳过 ${job.failed_threads.toLocaleString()} 个`}
</div>
{job.failed_threads > 0 && <div className="text-muted-foreground mt-1 text-xs">{ACTIVE.has(job.status) ? "将继续处理其他会话,未完成项可稍后重试。" : "未完成项可重新执行;已有备份不会因单个会话失败而丢弃。"}</div>}
{job.action === "archive" && job.snapshot_at && <div className="text-muted-foreground mt-1 text-xs">本次数据快照截至:{new Date(job.snapshot_at).toLocaleString()}</div>}
{job.action === "archive" && job.processed_through && <div className="text-muted-foreground mt-1 text-xs">已处理到会话创建时间:{new Date(job.processed_through).toLocaleString()}</div>}
{ACTIVE.has(job.status) && <div className="mt-2 space-y-1">
<div
role="progressbar"
aria-label={`${month.month} ${job.action === "archive" ? "聊天归档" : job.action === "purge" ? "PostgreSQL 清理" : "聊天回滚"}进度`}
aria-valuemin={0}
aria-valuemax={Math.max(1, job.total_threads)}
aria-valuenow={Math.min(job.processed_threads, job.total_threads)}
className="bg-background h-2 overflow-hidden rounded-full"
>
<div className="bg-primary h-full transition-[width]" style={{ width: `${job.total_threads ? Math.min(100, (job.processed_threads / job.total_threads) * 100) : 100}%` }} />
</div>
<div className="text-muted-foreground text-xs">{job.total_threads ? Math.floor((job.processed_threads / job.total_threads) * 100) : 100}%</div>
</div>}
{job.current_thread_id && <div className="text-muted-foreground mt-1 break-all text-xs">{ACTIVE.has(job.status) ? "当前会话" : "最后处理会话"}:{job.current_thread_id}</div>}
{job.error && <div className="text-destructive mt-1 break-all text-xs">最近错误:{job.error}</div>}
</div>}
<div className="flex flex-wrap gap-2">
<Button size="sm" variant="outline" disabled={active || busyMonth === month.month || month.month > currentLocalMonth()} onClick={() => void runAction(month, "archive")}>
<ArchiveIcon className="mr-2 size-4" />{displayStatus === "interrupted" || displayStatus === "partial" ? "重新归档并校验" : month.month === currentLocalMonth() ? "归档本月快照" : month.copied_threads ? "重新校验归档" : "归档到 SQLite"}
</Button>
<Button size="sm" variant="destructive" disabled={active || !canPurge || busyMonth === month.month} onClick={() => void runAction(month, "purge")}>
<Trash2Icon className="mr-2 size-4" />{month.status === "deleted" ? "再次清理 PG" : "删除已归档 PG 数据"}
</Button>
<Button size="sm" variant="outline" disabled={active || !canRollback || busyMonth === month.month} onClick={() => void runAction(month, "rollback")}>
<RotateCcwIcon className="mr-2 size-4" />回滚到 PostgreSQL
</Button>
</div>
</CardContent>
</Card>
);
})}
</div>
) : (
<Alert><AlertTitle>暂无可归档月份</AlertTitle><AlertDescription>业务库中还没有可识别的会话元数据。</AlertDescription></Alert>
)}
</section>
);
}
@@ -1,9 +1,11 @@
"use client";
import { Loader2Icon, ShrinkIcon } from "lucide-react";
import { ListOrderedIcon, Loader2Icon, ShrinkIcon } from "lucide-react";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import {
useConversationContextSettings,
@@ -16,6 +18,35 @@ export function ContextWindowSettingsPage() {
const update = useUpdateConversationContextSettings();
const enabled = data?.recent_turn_window_enabled ?? false;
const recentTurns = data?.recent_turns ?? 3;
const currentRoundLimit = data?.max_conversation_rounds ?? 20;
const [roundLimit, setRoundLimit] = useState(String(currentRoundLimit));
const [roundLimitTouched, setRoundLimitTouched] = useState(false);
const parsedRoundLimit = Number(roundLimit);
const roundLimitInvalid =
!Number.isInteger(parsedRoundLimit) ||
parsedRoundLimit < 1 ||
parsedRoundLimit > 50;
const useQuestionAsTitle = data?.use_question_as_title ?? false;
const [stepDraft, setStepDraft] = useState<string | null>(null);
const stepValue = stepDraft ?? String(data?.max_run_steps ?? 1000);
const steps = Number(stepValue);
const validSteps = stepValue.trim() !== "" && Number.isInteger(steps) && steps >= 20 && steps <= 10000;
useEffect(() => {
setRoundLimit(String(currentRoundLimit));
setRoundLimitTouched(false);
}, [currentRoundLimit]);
const saveSteps = async () => {
if (!validSteps) return;
try {
await update.mutateAsync({ max_run_steps: steps });
setStepDraft(null);
toast.success("单次问答步骤上限已保存,从下一次问答生效");
} catch (error) {
toast.error(error instanceof Error ? error.message : "保存失败");
}
};
const handleChange = async (checked: boolean) => {
try {
@@ -30,6 +61,33 @@ export function ContextWindowSettingsPage() {
}
};
const saveRoundLimit = async () => {
setRoundLimitTouched(true);
if (roundLimitInvalid) {
toast.error("对话轮数限制请填写 1 到 50 的整数");
return;
}
try {
await update.mutateAsync({ max_conversation_rounds: parsedRoundLimit });
toast.success(`单个对话最多可进行 ${parsedRoundLimit} 轮`);
} catch (error) {
toast.error(error instanceof Error ? error.message : "保存失败");
}
};
const handleQuestionTitleChange = async (checked: boolean) => {
try {
await update.mutateAsync({ use_question_as_title: checked });
toast.success(
checked
? "已开启:对话标题使用首个问题的前 20 个字"
: "已关闭:恢复回答后的标题生成",
);
} catch (error) {
toast.error(error instanceof Error ? error.message : "保存失败");
}
};
return (
<section className="space-y-6">
<div className="space-y-1">
@@ -38,7 +96,7 @@ export function ContextWindowSettingsPage() {
上下文管理
</h3>
<p className="text-muted-foreground text-sm">
控制长对话发给模型的历史范围。该模式默认关闭,只有管理员显式开启后才会生效。
管理对话历史范围、单个对话轮数、标题生成方式和单次问答步骤上限。设置对所有用户生效,仅管理员可修改。
</p>
</div>
@@ -62,6 +120,105 @@ export function ContextWindowSettingsPage() {
)}
</div>
<div className="flex flex-wrap items-end justify-between gap-4 rounded-lg border p-4">
<div className="min-w-0 space-y-1">
<label
htmlFor="max-conversation-rounds"
className="flex items-center gap-2 font-medium"
>
<ListOrderedIcon className="size-4" />
单个对话轮数限制
</label>
<p
id="max-conversation-rounds-help"
className="text-muted-foreground text-sm"
>
一轮按一条真实用户提问计算。默认 20,可设置为 1 到 50;达到上限后用户需要新建对话才能继续。
</p>
<div className="mt-2 flex items-center gap-2">
<Input
id="max-conversation-rounds"
type="number"
min={1}
max={50}
inputMode="numeric"
value={roundLimit}
disabled={isLoading || isError || update.isPending}
onChange={(event) => setRoundLimit(event.target.value)}
onBlur={() => setRoundLimitTouched(true)}
aria-invalid={roundLimitTouched && roundLimitInvalid}
aria-describedby="max-conversation-rounds-help max-conversation-rounds-error"
className="w-28"
/>
<span className="text-muted-foreground text-sm">轮</span>
</div>
<p
id="max-conversation-rounds-error"
className={
roundLimitTouched && roundLimitInvalid
? "text-destructive min-h-5 text-xs"
: "text-muted-foreground min-h-5 text-xs"
}
role={roundLimitTouched && roundLimitInvalid ? "alert" : undefined}
>
{roundLimitTouched && roundLimitInvalid
? "请输入 1 到 50 的整数。"
: "保存后,新限制会应用到当前及后续普通对话。"}
</p>
</div>
<Button
type="button"
size="sm"
disabled={
isLoading ||
isError ||
update.isPending ||
(!roundLimitInvalid && parsedRoundLimit === currentRoundLimit)
}
onClick={() => void saveRoundLimit()}
>
{update.isPending ? "保存中…" : "保存轮数"}
</Button>
</div>
<div className="flex items-center justify-between gap-6 rounded-lg border p-4">
<div className="space-y-1">
<div className="font-medium">标题直接使用首个问题</div>
<p className="text-muted-foreground text-sm">
开启后,取首个问题的前 20 个字作为最终标题,不足 20 个字则完整保留;回答结束后不再额外调用模型生成标题,也不轮询标题状态,避免影响下一轮提问。关闭后恢复原来的回答后标题生成方式。
</p>
</div>
{isLoading ? (
<Loader2Icon className="text-muted-foreground size-5 animate-spin" />
) : (
<Switch
checked={useQuestionAsTitle}
disabled={isError || update.isPending}
onCheckedChange={handleQuestionTitleChange}
aria-label="标题直接使用首个问题"
/>
)}
</div>
<div className="space-y-3 rounded-lg border p-4">
<label htmlFor="max-run-steps" className="font-medium">单次问答步骤上限</label>
<p className="text-muted-foreground text-sm">
控制普通问答和智能体问答每次运行的最大执行步数(20–10000,默认 1000)。步骤包括模型、工具及内部处理,不等于界面显示的步骤条数。提高上限可支持更复杂的任务,也会增加耗时和用量。
</p>
<div className="flex items-center gap-3">
<Input id="max-run-steps" type="number" min={20} max={10000} step={1}
className="w-40" value={stepValue}
disabled={isLoading || isError || update.isPending}
onChange={(event) => setStepDraft(event.target.value)} />
<Button disabled={isLoading || isError || update.isPending || !validSteps}
onClick={() => void saveSteps()}>保存上限</Button>
</div>
{!validSteps && <p className="text-destructive text-sm">请输入 20 到 10000 之间的整数。</p>}
<p className="text-muted-foreground text-sm">
达到上限时保留已有对话内容并提示暂停;用户可发送“继续”,在当前对话中接着处理。
</p>
</div>
{isError && (
<div className="flex items-center justify-between gap-3">
<p className="text-destructive text-sm">
@@ -48,7 +48,7 @@ export function KnowledgeRetrievalSettingsPage() {
知识检索
</h3>
<p className="text-muted-foreground text-sm">
控制普通知识库问答是否默认使用智能检索。该能力默认关闭,经典检索模式始终保留为候选。
配置普通知识库可用的检索模式。新对话始终默认使用经典检索。
</p>
</div>
@@ -56,9 +56,7 @@ export function KnowledgeRetrievalSettingsPage() {
<div className="space-y-1">
<div className="font-medium">普通知识库智能推理检索</div>
<p className="text-muted-foreground text-sm">
开启后,新对话默认使用智能检索:先召回原文分片,再根据命中线索查阅并扩展
Wiki,把知识库资料作为回答背景。已有对话继续使用各自保存的模式,用户仍可在
输入框的检索模式菜单中切换到经典检索。
开启后,用户可在问答输入框中从经典检索切换到智能检索;经典检索仍位于首项并作为默认模式。
</p>
</div>
{isLoading ? (
@@ -109,12 +107,6 @@ export function KnowledgeRetrievalSettingsPage() {
</Button>
</div>
)}
<p className="text-muted-foreground text-xs">
用户只需直接提问,无需填写“先检索什么、再检索什么”的固定模板;系统不会向输入框
注入检索提示词。智能检索将检索资料与模型原有能力结合后回答,不强制生成参考文献编号。
关闭后不会删除历史对话;已保存为智能检索的线程需要切回经典模式后才能继续发送。
</p>
</section>
);
}
@@ -0,0 +1,110 @@
"use client";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { apiFetch } from "@/core/api";
import { getBackendBaseURL } from "@/core/config";
import { useModels } from "@/core/models/hooks";
type ModelPrompt = { enabled: boolean; prompt: string };
const queryKey = ["system-settings", "model-prompt-suffixes"];
const endpoint = () => `${getBackendBaseURL()}/api/system-settings/model-prompt-suffixes`;
async function readResponse<T>(response: Response): Promise<T> {
if (!response.ok) {
const body = await response.json().catch(() => null);
throw new Error(typeof body?.detail === "string" ? body.detail : "模型提示词设置请求失败");
}
return response.json() as Promise<T>;
}
export function ModelPromptSettingsPage() {
const client = useQueryClient();
const { models, isLoading: modelsLoading, error: modelsError } = useModels();
const query = useQuery({
queryKey,
queryFn: async () => readResponse<Record<string, ModelPrompt>>(await apiFetch(endpoint())),
});
const [selected, setSelected] = useState("");
const [drafts, setDrafts] = useState<Record<string, ModelPrompt>>({});
const names = [...new Set([...models.map((model) => model.name), ...Object.keys(query.data ?? {})])];
const modelName = selected || names[0] || "";
const saved = query.data?.[modelName] ?? { enabled: false, prompt: "" };
const draft = drafts[modelName] ?? saved;
const mutation = useMutation({
mutationFn: async ({ name, value }: { name: string; value: ModelPrompt }) =>
readResponse<ModelPrompt>(await apiFetch(`${endpoint()}/${encodeURIComponent(name)}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(value),
})),
onSuccess: (value, { name }) => {
client.setQueryData<Record<string, ModelPrompt>>(queryKey, (old) => ({ ...old, [name]: value }));
setDrafts((old) => {
const next = { ...old };
delete next[name];
return next;
});
toast.success("已保存,所有用户下一次调用该模型时生效");
},
onError: (error) => toast.error(error.message),
});
const edit = (patch: Partial<ModelPrompt>) => setDrafts((old) => ({ ...old, [modelName]: { ...draft, ...patch } }));
if (query.isLoading || modelsLoading) return <p>正在加载模型提示词设置…</p>;
if (query.isError || modelsError) return (
<div className="space-y-3">
<p role="alert">加载失败,请重试。</p>
<Button onClick={() => { void query.refetch(); void client.invalidateQueries({ queryKey: ["models"] }); }}>重试</Button>
</div>
);
return (
<section className="space-y-5">
<div className="space-y-2">
<h3 className="text-lg font-semibold">模型追加提示词</h3>
<p className="text-muted-foreground text-sm">
为指定模型设置固定提示词,自动追加到系统提示词末尾。仅管理员可修改,对所有用户生效,保存后无需重启。
</p>
<p className="text-muted-foreground text-sm">
适用于平台统一模型入口的问答、智能体及其他模型调用。追加提示词用于引导回答方式,不能保证模型一定回答。
</p>
</div>
{names.length === 0 ? <p>暂无可配置的模型。</p> : <>
<label className="block space-y-2">
<span className="text-sm font-medium">选择模型</span>
<select className="bg-background w-full rounded-md border px-3 py-2" value={modelName}
disabled={mutation.isPending} onChange={(event) => setSelected(event.target.value)}>
{names.map((name) => {
const model = models.find((item) => item.name === name);
return <option key={name} value={name}>{model ? `${model.display_name || name}(${name})` : `${name}(当前未配置)`}</option>;
})}
</select>
</label>
<div className="flex items-center justify-between gap-4 rounded-lg border p-4">
<label htmlFor="model-prompt-enabled" className="text-sm font-medium">启用此模型的追加提示词</label>
<Switch id="model-prompt-enabled" checked={draft.enabled} disabled={mutation.isPending}
onCheckedChange={(enabled) => edit({ enabled })} />
</div>
<label className="block space-y-2">
<span className="text-sm font-medium">追加提示词</span>
<Textarea rows={12} maxLength={20000} value={draft.prompt} disabled={mutation.isPending}
placeholder="填写希望该模型遵循的回答要求"
onChange={(event) => edit({ prompt: event.target.value })} />
</label>
<div className="flex items-center justify-between gap-4">
<span className="text-muted-foreground text-xs">{draft.prompt.length} / 20000 字符;关闭开关可停用并保留内容。</span>
<Button disabled={mutation.isPending || (draft.enabled && !draft.prompt.trim())}
onClick={() => mutation.mutate({ name: modelName, value: draft })}>
{mutation.isPending ? "保存中…" : "保存此模型设置"}
</Button>
</div>
</>}
</section>
);
}
@@ -0,0 +1,74 @@
"use client";
import { HistoryIcon, Loader2Icon } from "lucide-react";
import { toast } from "sonner";
import { Switch } from "@/components/ui/switch";
import {
useRetryKeepPartialSettings,
useUpdateRetryKeepPartialSettings,
} from "@/core/system-settings/hooks";
export function RetryKeepPartialSettingsPage() {
const { data, isLoading, isError } = useRetryKeepPartialSettings();
const update = useUpdateRetryKeepPartialSettings();
const enabled = data?.enabled ?? true;
const handleChange = async (checked: boolean) => {
try {
await update.mutateAsync({ enabled: checked });
toast.success(
checked ? "保留中间正文已开启" : "保留中间正文已关闭",
);
} catch (error) {
toast.error(error instanceof Error ? error.message : "保存失败");
}
};
return (
<section className="space-y-6">
<div className="space-y-1">
<h3 className="flex items-center gap-2 text-lg font-semibold">
<HistoryIcon className="size-5" />
保留中间正文
</h3>
<p className="text-muted-foreground text-sm">
步骤条执行过程中模型有时会先吐出一段正文再发起工具调用或开始下一轮思考。
开启后,本轮所有过程正文会合并成一条,集中显示在步骤条下方(步骤条保持
一个整体不被拆开,最终回答紧随其后);大模型响应中断触发后台自动重试时,
重试前已流出的半截回答同样保留。关闭则恢复原有行为——工具调用到达或
重试开始时清空未完成的正文。
</p>
</div>
<div className="flex items-center justify-between gap-6 rounded-lg border p-4">
<div className="space-y-1">
<div className="font-medium">保留步骤条执行中生成的正文</div>
<p className="text-muted-foreground text-sm">
仅影响问答页的显示,不改变后台执行与落库逻辑;重试保留的半截内容
刷新页面后不会保留。
</p>
</div>
{isLoading ? (
<Loader2Icon className="text-muted-foreground size-5 animate-spin" />
) : (
<Switch
checked={enabled}
disabled={isError || update.isPending}
onCheckedChange={handleChange}
aria-label="自动重试时保留已生成的正文"
/>
)}
</div>
{isError && (
<p className="text-destructive text-sm">
无法读取保留中间正文开关,系统将按开启处理。
</p>
)}
<p className="text-muted-foreground text-xs">
保存后无需重启后台,对下一次触发的自动重试立即生效;正在生成中的回答不会中途切换。
</p>
</section>
);
}
@@ -0,0 +1,268 @@
"use client";
import { Clock3Icon, FileOutputIcon, ListOrderedIcon, Loader2Icon, UsersIcon } from "lucide-react";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import {
useRoundtableRoomLimitSettings,
useUpdateRoundtableRoomLimitSettings,
useWriteFileCompatibilitySettings,
} from "@/core/system-settings/hooks";
import { loadRoundtableRoomSummary } from "@/roundtable-planning/api/rooms";
export function RoundtableRoomSettingsPage() {
const { data, isLoading, isError, isFetching, refetch } =
useRoundtableRoomLimitSettings();
const update = useUpdateRoundtableRoomLimitSettings();
const globalFileStream = useWriteFileCompatibilitySettings();
const enabled = data?.enabled ?? true;
const fileStreamEnabled = data?.write_file_compatibility_enabled ?? false;
const globalFileStreamEnabled = globalFileStream.data?.enabled ?? false;
const [maxRooms, setMaxRooms] = useState(String(data?.max_rooms ?? 3));
const [maxHoldMinutes, setMaxHoldMinutes] = useState(
String(data?.max_hold_minutes ?? 30),
);
const [maxCycles, setMaxCycles] = useState(String(data?.max_cycles ?? 8));
const [activeCount, setActiveCount] = useState<number | null>(null);
useEffect(() => {
if (data?.max_rooms != null) setMaxRooms(String(data.max_rooms));
}, [data?.max_rooms]);
useEffect(() => {
if (data?.max_hold_minutes != null) {
setMaxHoldMinutes(String(data.max_hold_minutes));
}
}, [data?.max_hold_minutes]);
useEffect(() => {
if (data?.max_cycles != null) setMaxCycles(String(data.max_cycles));
}, [data?.max_cycles]);
useEffect(() => {
let cancelled = false;
const load = () => {
void loadRoundtableRoomSummary()
.then((summary) => {
if (!cancelled) setActiveCount(summary.activeCount);
})
.catch(() => {
if (!cancelled) setActiveCount(null);
});
};
load();
const timer = window.setInterval(load, 15000);
return () => {
cancelled = true;
window.clearInterval(timer);
};
}, []);
const save = async (next: {
enabled?: boolean;
max_rooms?: number;
max_hold_minutes?: number;
max_cycles?: number;
write_file_compatibility_enabled?: boolean;
}) => {
try {
await update.mutateAsync(next);
toast.success("会商运行设置已保存");
} catch (error) {
toast.error(error instanceof Error ? error.message : "保存失败");
}
};
const saveMaxRooms = () => {
const parsed = Number(maxRooms);
if (!Number.isInteger(parsed) || parsed < 1 || parsed > 20) {
toast.error("房间上限请填写 1 到 20 的整数");
return;
}
void save({ max_rooms: parsed });
};
const saveMaxHoldMinutes = () => {
const parsed = Number(maxHoldMinutes);
if (!Number.isInteger(parsed) || parsed < 1 || parsed > 1440) {
toast.error("最长占用时间请填写 1 到 1440 分钟的整数");
return;
}
void save({ max_hold_minutes: parsed });
};
const saveMaxCycles = () => {
const parsed = Number(maxCycles);
if (!Number.isInteger(parsed) || parsed < 2 || parsed > 100) {
toast.error("总控收口轮数请填写 2 到 100 的整数");
return;
}
void save({ max_cycles: parsed });
};
return (
<section className="space-y-6">
<div className="space-y-1">
<h3 className="flex items-center gap-2 text-lg font-semibold">
<UsersIcon className="size-5" />
会商并发与收口
</h3>
<p className="text-muted-foreground text-sm">
配置第二步的全站并发名额、最长占用时间和总控强制收口轮数。所有账号共用房间名额;仅打开页面或查看历史记录不占用。
</p>
</div>
<div className="flex items-center justify-between gap-6 rounded-lg border p-4">
<div className="space-y-1">
<div className="font-medium">第二步房间上限</div>
<p className="text-muted-foreground text-sm">
开启后,全站第二步房间达到上限时,新的会商会停留在第一步并提示稍后再试。已获准进入的会商可正常暂停和继续。
</p>
</div>
{isLoading ? (
<Loader2Icon className="text-muted-foreground size-5 animate-spin" />
) : (
<Switch
checked={enabled}
disabled={isError || update.isPending}
onCheckedChange={(checked) => void save({ enabled: checked })}
aria-label="启用会商第二步房间上限"
/>
)}
</div>
<div className="flex flex-wrap items-end justify-between gap-4 rounded-lg border p-4">
<label className="space-y-1">
<span className="font-medium">同时进行的房间数</span>
<p className="text-muted-foreground text-sm">默认 3,可改为 1 到 20。保存后立即生效,无需重启。</p>
<input
type="number"
min={1}
max={20}
value={maxRooms}
disabled={isError || update.isPending}
onChange={(event) => setMaxRooms(event.target.value)}
className="border-input bg-background mt-2 h-9 w-24 rounded-md border px-3 text-sm"
aria-label="会商房间上限"
/>
</label>
<Button type="button" size="sm" disabled={isError || update.isPending} onClick={saveMaxRooms}>
保存上限
</Button>
</div>
<div className="flex flex-wrap items-end justify-between gap-4 rounded-lg border p-4">
<label className="space-y-1">
<span className="flex items-center gap-2 font-medium">
<Clock3Icon className="size-4" />
单个房间最长占用时间
</span>
<p className="text-muted-foreground text-sm">
默认 30 分钟,可改为 1 到 1440 分钟。到时会自动停止第二步并释放名额,避免异常任务长期占用。
</p>
<div className="mt-2 flex items-center gap-2">
<input
type="number"
min={1}
max={1440}
value={maxHoldMinutes}
disabled={isError || update.isPending}
onChange={(event) => setMaxHoldMinutes(event.target.value)}
className="border-input bg-background h-9 w-24 rounded-md border px-3 text-sm"
aria-label="会商房间最长占用分钟数"
/>
<span className="text-muted-foreground text-sm">分钟</span>
</div>
</label>
<Button
type="button"
size="sm"
disabled={isError || update.isPending}
onClick={saveMaxHoldMinutes}
>
保存时长
</Button>
</div>
<div className="flex flex-wrap items-end justify-between gap-4 rounded-lg border p-4">
<label className="space-y-1">
<span className="flex items-center gap-2 font-medium">
<ListOrderedIcon className="size-4" />
总控强制收口轮数
</span>
<p className="text-muted-foreground text-sm">
用于总控自由派活模式,默认第 8 轮,可改为第 2 到 100 轮。到达该轮时不会停止会商,而是关闭总控工具并输出最终总结;业务链与 DAG 在既定席位完成后自然收口。保存后从下一次研讨开始生效。
</p>
<div className="mt-2 flex items-center gap-2">
<input
type="number"
min={2}
max={100}
value={maxCycles}
disabled={isError || update.isPending}
onChange={(event) => setMaxCycles(event.target.value)}
className="border-input bg-background h-9 w-24 rounded-md border px-3 text-sm"
aria-label="总控强制收口轮数"
/>
<span className="text-muted-foreground text-sm">轮</span>
</div>
</label>
<Button
type="button"
size="sm"
disabled={isError || update.isPending}
onClick={saveMaxCycles}
>
保存轮数
</Button>
</div>
<div className="flex items-center justify-between gap-6 rounded-lg border p-4">
<div className="space-y-1">
<div className="flex items-center gap-2 font-medium">
<FileOutputIcon className="size-4" />
会商文件流式兼容
</div>
<p className="text-muted-foreground text-sm">
会商生成文件并打开沙箱时使用兼容写入。全局「文件流式兼容」开着时,会商自动使用;全局关着时,打开本开关后只有会商使用,普通对话保持原来的写入方式。
</p>
<p className="text-muted-foreground text-xs">
{globalFileStreamEnabled
? "当前会商会使用兼容写入,因为全局开关已开启。"
: fileStreamEnabled
? "当前只有会商使用兼容写入。"
: "当前会商使用各模型原来的写入方式。"}
</p>
</div>
{isLoading ? (
<Loader2Icon className="text-muted-foreground size-5 animate-spin" />
) : (
<Switch
checked={fileStreamEnabled}
disabled={isError || update.isPending}
onCheckedChange={(checked) =>
void save({ write_file_compatibility_enabled: checked })
}
aria-label="会商启用文件流式兼容"
/>
)}
</div>
<p className="text-muted-foreground text-sm">
当前全站占用:{activeCount == null ? "暂时无法读取" : `${activeCount} / ${data?.max_rooms ?? maxRooms}`}
</p>
{isError && (
<div className="flex items-center justify-between gap-3">
<p className="text-destructive text-sm">无法读取会商房间设置,本页暂不能修改。</p>
<Button type="button" variant="outline" size="sm" disabled={isFetching} onClick={() => void refetch()}>
{isFetching ? "重新加载中…" : "重新加载"}
</Button>
</div>
)}
</section>
);
}
@@ -1,19 +1,23 @@
"use client";
import {
BellIcon,
BrainIcon,
CpuIcon,
FileOutputIcon,
PaletteIcon,
import {
BellIcon,
BrainIcon,
CpuIcon,
DatabaseIcon,
ArchiveIcon,
FileOutputIcon,
HistoryIcon,
PaletteIcon,
SearchIcon,
ShieldCheckIcon,
ShrinkIcon,
SparklesIcon,
UploadCloudIcon,
UserIcon,
WrenchIcon,
} from "lucide-react";
SparklesIcon,
TypeIcon,
UploadCloudIcon,
UserIcon,
UsersIcon,
WrenchIcon,
} from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import {
@@ -25,32 +29,45 @@ import {
import { ScrollArea } from "@/components/ui/scroll-area";
import { AboutSettingsPage } from "@/components/workspace/settings/about-settings-page";
import { AccountSettingsPage } from "@/components/workspace/settings/account-settings-page";
import { AuthenticationSettingsPage } from "@/components/workspace/settings/authentication-settings-page";
import { AppearanceSettingsPage } from "@/components/workspace/settings/appearance-settings-page";
import { ContextWindowSettingsPage } from "@/components/workspace/settings/context-window-settings-page";
import { KnowledgeRetrievalSettingsPage } from "@/components/workspace/settings/knowledge-retrieval-settings-page";
import { MemoryRuntimeSettingsPage } from "@/components/workspace/settings/memory-runtime-settings-page";
import { ToolSettingsPage } from "@/components/workspace/settings/tool-settings-page";
import { UploadSettingsPage } from "@/components/workspace/settings/upload-settings-page";
import { WriteFileCompatibilitySettingsPage } from "@/components/workspace/settings/write-file-compatibility-settings-page";
import { getStoredAuth } from "@/core/auth";
import { useLiveAccount } from "@/core/auth/use-live-account";
import { useI18n } from "@/core/i18n/hooks";
import { cn } from "@/lib/utils";
import { LocalEncoderSettingsCard } from "@/strategy-components/components/resource-management/llmwiki/WeKnoraKnowledgeWorkspace";
import { AppIdentitySettingsPage } from "@/components/workspace/settings/app-identity-settings-page";
import { ContextWindowSettingsPage } from "@/components/workspace/settings/context-window-settings-page";
import { ModelPromptSettingsPage } from "@/components/workspace/settings/model-prompt-settings-page";
import { WorkerPoolSettingsPage } from "@/components/workspace/settings/worker-pool-settings-page";
import { ApiReadCacheSettingsPage } from "@/components/workspace/settings/api-read-cache-settings-page";
import { ChatArchiveSettingsPage } from "@/components/workspace/settings/chat-archive-settings-page";
import { RoundtableRoomSettingsPage } from "@/components/workspace/settings/roundtable-room-settings-page";
import { RetryKeepPartialSettingsPage } from "@/components/workspace/settings/retry-keep-partial-settings-page";
import { KnowledgeRetrievalSettingsPage } from "@/components/workspace/settings/knowledge-retrieval-settings-page";
import { MemoryRuntimeSettingsPage } from "@/components/workspace/settings/memory-runtime-settings-page";
import { ToolSettingsPage } from "@/components/workspace/settings/tool-settings-page";
import { UploadSettingsPage } from "@/components/workspace/settings/upload-settings-page";
import { WriteFileCompatibilitySettingsPage } from "@/components/workspace/settings/write-file-compatibility-settings-page";
import { getStoredAuth } from "@/core/auth";
import { useI18n } from "@/core/i18n/hooks";
import { cn } from "@/lib/utils";
import { LocalEncoderSettingsCard } from "@/strategy-components/components/resource-management/llmwiki/WeKnoraKnowledgeWorkspace";
import { ServerDiagnosticsPanel } from "@/pages/ServerDiagnosticsPage";
type SettingsSection =
| "account"
| "authentication"
| "appearance"
| "conversation-context"
| "knowledge-retrieval"
| "memory"
| "fileWriting"
| "uploads"
| "tools"
| "encoder"
| "about";
| "conversation-context"
| "model-prompts"
| "server-diagnostics"
| "api-read-cache"
| "worker-pool"
| "chat-archive"
| "roundtable-rooms"
| "knowledge-retrieval"
| "appIdentity"
| "memory"
| "fileWriting"
| "retryKeepPartial"
| "uploads"
| "tools"
| "encoder"
| "about";
type SettingsDialogProps = React.ComponentProps<typeof Dialog> & {
defaultSection?: SettingsSection;
@@ -58,9 +75,8 @@ type SettingsDialogProps = React.ComponentProps<typeof Dialog> & {
export function SettingsDialog(props: SettingsDialogProps) {
const { defaultSection = "appearance", ...dialogProps } = props;
const { t } = useI18n();
const live = useLiveAccount();
const isAdmin = getStoredAuth()?.system_role === "admin";
const { t } = useI18n();
const isAdmin = getStoredAuth()?.system_role === "admin";
const [activeSection, setActiveSection] =
useState<SettingsSection>(defaultSection);
@@ -86,20 +102,27 @@ export function SettingsDialog(props: SettingsDialogProps) {
// },
// { id: "tools", label: t.settings.sections.tools, icon: WrenchIcon },
// { id: "skills", label: t.settings.sections.skills, icon: SparklesIcon },
...(isAdmin
? [
{ id: "conversation-context", label: "上下文管理", icon: ShrinkIcon },
{ id: "knowledge-retrieval", label: "知识检索", icon: SearchIcon },
{ id: "memory", label: "问答记忆", icon: BrainIcon },
{ id: "fileWriting", label: "文件流式兼容", icon: FileOutputIcon },
{ id: "uploads", label: "上传设置", icon: UploadCloudIcon },
{ id: "authentication", label: "登录与注册", icon: ShieldCheckIcon },
]
: []),
{ id: "tools", label: t.settings.sections.tools, icon: WrenchIcon },
...(isAdmin
? [{ id: "encoder", label: "Wiki 镜像编码器", icon: CpuIcon }]
: []),
...(isAdmin
? [
{ id: "conversation-context", label: "上下文管理", icon: ShrinkIcon },
{ id: "model-prompts", label: "模型追加提示词", icon: SparklesIcon },
{ id: "server-diagnostics", label: "服务器诊断", icon: CpuIcon },
{ id: "api-read-cache", label: "Redis 与性能", icon: DatabaseIcon },
{ id: "worker-pool", label: "执行节点管理", icon: CpuIcon },
{ id: "chat-archive", label: "聊天记录归档", icon: ArchiveIcon },
{ id: "roundtable-rooms", label: "会商并发", icon: UsersIcon },
{ id: "knowledge-retrieval", label: "知识检索", icon: SearchIcon },
{ id: "appIdentity", label: "系统名称", icon: TypeIcon },
{ id: "memory", label: "问答记忆", icon: BrainIcon },
{ id: "fileWriting", label: "文件流式兼容", icon: FileOutputIcon },
{ id: "retryKeepPartial", label: "保留中间正文", icon: HistoryIcon },
{ id: "uploads", label: "上传设置", icon: UploadCloudIcon },
]
: []),
{ id: "tools", label: t.settings.sections.tools, icon: WrenchIcon },
...(isAdmin
? [{ id: "encoder", label: "Wiki 镜像编码器", icon: CpuIcon }]
: []),
{
id: "account",
label: "个人信息",
@@ -111,8 +134,8 @@ export function SettingsDialog(props: SettingsDialogProps) {
t.settings.sections.appearance,
t.settings.sections.memory,
t.settings.sections.tools,
t.settings.sections.about,
isAdmin,
t.settings.sections.about,
isAdmin,
],
);
return (
@@ -158,36 +181,54 @@ export function SettingsDialog(props: SettingsDialogProps) {
<ScrollArea className="h-full min-h-0 min-w-0 rounded-lg border">
<div className="min-w-0 space-y-8 p-6">
{activeSection === "account" && <AccountSettingsPage />}
{activeSection === "authentication" && isAdmin && (
<AuthenticationSettingsPage
key={live.userId}
{activeSection === "server-diagnostics" && isAdmin && (
<ServerDiagnosticsPanel />
)}
{activeSection === "api-read-cache" && isAdmin && (
<ApiReadCacheSettingsPage />
)}
{activeSection === "worker-pool" && isAdmin && (
<WorkerPoolSettingsPage />
)}
{activeSection === "chat-archive" && isAdmin && (
<ChatArchiveSettingsPage />
)}
{activeSection === "appearance" && (
<AppearanceSettingsPage
onClose={() => props.onOpenChange?.(false)}
/>
)}
{activeSection === "appearance" && (
<AppearanceSettingsPage
onClose={() => props.onOpenChange?.(false)}
/>
{activeSection === "conversation-context" && isAdmin && (
<ContextWindowSettingsPage />
)}
{activeSection === "model-prompts" && isAdmin && (
<ModelPromptSettingsPage />
)}
{activeSection === "roundtable-rooms" && isAdmin && (
<RoundtableRoomSettingsPage />
)}
{activeSection === "knowledge-retrieval" && isAdmin && (
<KnowledgeRetrievalSettingsPage />
)}
{activeSection === "appIdentity" && isAdmin && (
<AppIdentitySettingsPage />
)}
{activeSection === "memory" && isAdmin && (
<MemoryRuntimeSettingsPage />
)}
{activeSection === "fileWriting" && isAdmin && (
<WriteFileCompatibilitySettingsPage />
)}
{activeSection === "retryKeepPartial" && isAdmin && (
<RetryKeepPartialSettingsPage />
)}
{activeSection === "uploads" && isAdmin && (
<UploadSettingsPage />
)}
{activeSection === "tools" && <ToolSettingsPage />}
{activeSection === "encoder" && isAdmin && (
<LocalEncoderSettingsCard />
)}
{activeSection === "conversation-context" && isAdmin && (
<ContextWindowSettingsPage />
)}
{activeSection === "knowledge-retrieval" && isAdmin && (
<KnowledgeRetrievalSettingsPage />
)}
{activeSection === "memory" && isAdmin && (
<MemoryRuntimeSettingsPage />
)}
{activeSection === "fileWriting" && isAdmin && (
<WriteFileCompatibilitySettingsPage />
)}
{activeSection === "uploads" && isAdmin && (
<UploadSettingsPage />
)}
{activeSection === "tools" && <ToolSettingsPage />}
{activeSection === "encoder" && isAdmin && (
<LocalEncoderSettingsCard />
)}
{activeSection === "about" && <AboutSettingsPage />}
</div>
</ScrollArea>
@@ -558,6 +558,7 @@ function SkillSettingsList({
<TagSearchBar
targetType="skill"
onSearchChange={setSearch}
searchPlaceholder="搜索名称 / 中文名 / 描述 / 详情 / 标签,多关键词空格分隔"
tagIds={tagIds}
onTagIdsChange={setTagIds}
actions={
@@ -36,8 +36,10 @@ import { SettingsSection } from "./settings-section";
export function ToolSettingsPage() {
const { t } = useI18n();
const { config, isLoading, error } = useMCPConfig();
const isAdmin = getStoredAuth()?.system_role === "admin";
// MCP configuration is an admin-only API. Keep ordinary users from making
// a request that will always return 403, and show an explicit access state.
const { config, isLoading, error } = useMCPConfig(isAdmin);
const isStaticMode = env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true";
const [editOpen, setEditOpen] = useState(false);
@@ -74,7 +76,14 @@ export function ToolSettingsPage() {
title={t.settings.tools.title}
description={t.settings.tools.description}
>
{isLoading ? (
{!isAdmin ? (
<div
role="status"
className="text-muted-foreground rounded-md border p-6 text-center text-sm"
>
MCP 工具由管理员统一配置和管理。如需调整,请联系管理员。
</div>
) : isLoading ? (
<div className="text-muted-foreground text-sm">{t.common.loading}</div>
) : error ? (
<div className="text-destructive text-sm">Error: {error.message}</div>
@@ -102,19 +111,23 @@ export function ToolSettingsPage() {
</div>
)}
<MCPServerEditDialog
open={editOpen}
onOpenChange={setEditOpen}
mode={editMode}
originalName={editingName}
initialServer={editingServer}
existingNames={existingNames}
/>
{isAdmin && (
<MCPServerEditDialog
open={editOpen}
onOpenChange={setEditOpen}
mode={editMode}
originalName={editingName}
initialServer={editingServer}
existingNames={existingNames}
/>
)}
<DeleteConfirmDialog
target={deleteTarget}
onOpenChange={(open) => !open && setDeleteTarget(null)}
/>
{isAdmin && (
<DeleteConfirmDialog
target={deleteTarget}
onOpenChange={(open) => !open && setDeleteTarget(null)}
/>
)}
</SettingsSection>
);
}
@@ -0,0 +1,166 @@
import { Link } from "react-router-dom";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { apiFetch } from "@/core/api";
import { getBackendBaseURL } from "@/core/config";
type Settings = {
enabled: boolean; transport: "ssh" | "socket"; host: string; port: number;
username: string; host_key_sha256: string; source_container: string; network: string;
python_executable: string; working_dir: string;
database_pool_size: number; postgres_pool_size: number; database_connection_budget: number;
desired: number; concurrency: number; queue_limit: number; queue_timeout: number;
cpu: number; memory_mb: number; total_cpu: number; total_memory_mb: number;
password_set: boolean;
};
type Node = { name: string; ready: boolean; active: number; capacity?: number; draining: boolean; error?: string };
type Discovery = { cpus: number; memory_mb: number; note: string; containers: { name: string; networks: string[] }[]; recommendation: Partial<Settings> & { desired: number } };
type Status = { settings: Settings; nodes: Node[]; error: string | null };
async function call<T>(path = "", method = "GET", body?: unknown): Promise<T> {
const response = await apiFetch(`${getBackendBaseURL()}/api/system-settings/worker-pool${path}`, {
method, headers: { "Content-Type": "application/json" },
body: body === undefined ? undefined : JSON.stringify(body),
});
const data = await response.json();
if (!response.ok) throw new Error(typeof data.detail === "string" ? data.detail : `请求失败(${response.status})`);
return data as T;
}
export function WorkerPoolSettingsPage() {
const [status, setStatus] = useState<Status>();
const [draft, setDraft] = useState<Settings>();
const [password, setPassword] = useState("");
const [discovery, setDiscovery] = useState<Discovery>();
const [fingerprint, setFingerprint] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const lastServerPython = useRef<string | undefined>(undefined);
useEffect(() => {
let disposed = false;
const refresh = async () => {
try {
const value = await call<Status>();
if (!disposed) {
const previousPython = lastServerPython.current;
setStatus(value);
setDraft((old) => {
if (!old) return value.settings;
if (previousPython !== undefined && old.python_executable === previousPython) {
return { ...old, python_executable: value.settings.python_executable };
}
return old;
});
lastServerPython.current = value.settings.python_executable;
setError("");
}
} catch (e) { if (!disposed) setError(e instanceof Error ? e.message : "读取失败"); }
};
void refresh();
const timer = setInterval(() => void refresh(), 5000);
return () => { disposed = true; clearInterval(timer); };
}, []);
const update = (key: keyof Settings, value: string | number | boolean) => setDraft((old) => old ? { ...old, [key]: value } : old);
const save = async () => {
if (!draft) return;
setBusy(true);
try {
const { password_set: _passwordSet, ...settings } = draft;
const value = await call<Status>("", "PUT", { ...settings, password: password || null });
setStatus(value); setDraft(value.settings); setPassword("");
toast.success("设置已保存,系统正在调整执行节点");
} catch (e) { toast.error(e instanceof Error ? e.message : "保存失败"); }
finally { setBusy(false); }
};
const inspectServer = async () => {
if (!draft) return;
setBusy(true);
try {
const { password_set: _passwordSet, ...settings } = draft;
const result = await call<Discovery>("/discover", "POST", { ...settings, password: password || null });
setDiscovery(result);
toast.success("服务器资源已读取,请查看推荐配置");
} catch (e) { toast.error(e instanceof Error ? e.message : "检测失败"); }
finally { setBusy(false); }
};
const readFingerprint = async () => {
if (!draft) return;
setBusy(true);
try {
const result = await call<{ fingerprint: string }>("/fingerprint", "POST", { host: draft.host, port: draft.port });
setFingerprint(result.fingerprint);
} catch (e) { toast.error(e instanceof Error ? e.message : "读取失败"); }
finally { setBusy(false); }
};
const test = async () => {
setBusy(true);
try { toast.success((await call<{ message: string }>("/test", "POST")).message); }
catch (e) { toast.error(e instanceof Error ? e.message : "连接失败"); }
finally { setBusy(false); }
};
return <section className="space-y-5">
<Button variant="outline" asChild><Link to="/page/workspace/admin/server-diagnostics" target="_blank" rel="noreferrer">服务器诊断与日志 ↗</Link></Button>
<div><h3 className="text-lg font-semibold">执行节点管理</h3>
<p className="text-muted-foreground text-sm">在同一台 Docker 服务器上动态扩容普通问答和智能体问答。定时任务、会商、研究和工作流继续由主服务统一执行。</p></div>
{error && <p role="alert" className="text-destructive">{error}</p>}
{!draft ? <p>正在读取配置…</p> : <>
<label className="flex items-center gap-3"><Switch checked={draft.enabled} disabled={busy} onCheckedChange={(v) => update("enabled", v)} />启用在线 Worker 池</label>
<label className="block space-y-1"><span>服务器连接方式</span><select className="w-full rounded border bg-background p-2" value={draft.transport} onChange={(e) => update("transport", e.target.value)}>
<option value="ssh">SSH 账号密码(主容器与 Worker 在同一 Docker 网络)</option>
<option value="socket">本机 Docker Socket(需要预先挂载)</option>
</select></label>
<div className="grid gap-4 sm:grid-cols-2">
{draft.transport === "ssh" && <>
{([ ["host", "服务器 IP / 主机名"], ["username", "SSH 账号"], ["host_key_sha256", "SSH 主机密钥指纹(SHA256:…)"] ] as const).map(([key, label]) => <label className="space-y-1" key={key}><span>{label}</span><Input value={draft[key]} onChange={(e) => { update(key, e.target.value); setFingerprint(""); setDiscovery(undefined); }} /></label>)}
<label className="space-y-1"><span>SSH 端口</span><Input type="number" min={1} max={65535} value={draft.port} onChange={(e) => update("port", Number(e.target.value))} /></label>
<label className="space-y-1"><span>SSH 密码{draft.password_set ? "(已设置,留空保留)" : ""}</span><Input type="password" autoComplete="new-password" value={password} onChange={(e) => setPassword(e.target.value)} /></label>
</>}
{([ ["source_container", "主服务容器名称"], ["network", "Docker 网络名称"], ["python_executable", "镜像内 Python 路径"], ["working_dir", "镜像内后端目录"] ] as const).map(([key, label]) => <label className="space-y-1" key={key}><span>{label}</span><Input value={draft[key]} onChange={(e) => update(key, e.target.value)} /></label>)}
{([ ["desired", "期望 Worker 数量", 0, 32], ["concurrency", "每节点同时执行数", 1, 32], ["queue_limit", "每节点最大排队数", 1, 1024], ["queue_timeout", "最长排队秒数", 1, 300], ["cpu", "每节点 CPU 核数", 0.25, 64], ["memory_mb", "每节点内存 MB", 512, 131072], ["total_cpu", "Worker 总 CPU 预算", 0.25, 512], ["total_memory_mb", "Worker 总内存预算 MB", 512, 1048576] ] as const).map(([key, label, min, max]) => <label className="space-y-1" key={key}><span>{label}</span><Input type="number" min={min} max={max} step={key.includes("cpu") ? 0.25 : 1} value={draft[key]} onChange={(e) => update(key, Number(e.target.value))} /></label>)}
</div>
<div className="rounded border p-4 space-y-3">
<h4 className="font-medium">连接检测与资源推荐</h4>
{draft.transport === "ssh" && <>
<p className="text-sm text-muted-foreground">账号和密码用于登录。主机指纹用来识别服务器,不是密码。先读取并确认指纹,再连接检测。</p>
<Button variant="outline" disabled={busy || !draft.host} onClick={() => void readFingerprint()}>读取服务器指纹</Button>
{fingerprint && <div className="space-y-2"><p className="break-all text-sm">本次读取:{fingerprint}</p>
{draft.host_key_sha256 && draft.host_key_sha256 !== fingerprint && <p className="text-destructive text-sm">指纹与已保存的服务器不同,请核实服务器是否更换。</p>}
<Button variant="outline" disabled={busy} onClick={() => { update("host_key_sha256", fingerprint); setFingerprint(""); }}>确认使用此服务器指纹</Button></div>}
</>}
<Button variant="outline" disabled={busy || (draft.transport === "ssh" && !draft.host_key_sha256)} onClick={() => void inspectServer()}>连接并读取资源</Button>
{discovery && <div className="space-y-3 text-sm">
<p>服务器:{discovery.cpus} 核 CPU · {(discovery.memory_mb / 1024).toFixed(1)} GB 内存</p>
<p>{discovery.note}</p>
<label className="block space-y-1"><span>选择当前系统的主服务容器</span><select className="w-full rounded border bg-background p-2" value={draft.source_container} onChange={(e) => {
const container = discovery.containers.find((c) => c.name === e.target.value);
update("source_container", e.target.value); if (container?.networks.length === 1) update("network", container.networks[0]!);
}}><option value="">请选择</option>{discovery.containers.map((c) => <option key={c.name} value={c.name}>{c.name}</option>)}</select></label>
<label className="block space-y-1"><span>主服务与 Worker 共用网络</span><select className="w-full rounded border bg-background p-2" value={draft.network} onChange={(e) => update("network", e.target.value)}><option value="">请选择</option>{discovery.containers.find((c) => c.name === draft.source_container)?.networks.map((n) => <option key={n} value={n}>{n}</option>)}</select></label>
{discovery.recommendation.desired > 0 ? <>
<p>推荐起步:{discovery.recommendation.desired} 个 Worker,每个 {discovery.recommendation.cpu} 核 / {discovery.recommendation.memory_mb} MB,同时执行 {discovery.recommendation.concurrency} 个问答,超出后排队。</p>
<Button variant="outline" disabled={busy || !!status?.nodes.length} onClick={() => setDraft((old) => old ? { ...old, ...discovery.recommendation } : old)}>填入推荐配置</Button>
{!!status?.nodes.length && <p>修改单节点资源前,先将期望数量设为 0,保存并等待现有节点完成任务退出。</p>}
</> : <p className="text-destructive">预留资源后不足以启动节点,请调整服务器资源或其他服务的配额。</p>}
</div>}
<p className="text-sm text-muted-foreground">检测不会创建容器。保存并应用后生效;账号密码加密保存到服务器持久化目录,重启后保留设置并按期望数量恢复节点。</p>
</div>
<div className="grid gap-4 sm:grid-cols-2">
{([ ["database_pool_size", "每节点业务数据库连接上限", 1, 32], ["postgres_pool_size", "每节点检查点 / Store 各自连接上限", 1, 32], ["database_connection_budget", "全部 Worker 数据库连接预算", 3, 1024] ] as const).map(([key, label, min, max]) => <label className="space-y-1" key={key}><span>{label}</span><Input type="number" min={min} max={max} value={draft[key]} onChange={(e) => update(key, Number(e.target.value))} /></label>)}
</div>
<p className="text-muted-foreground text-sm">Worker 连接额度合计:{draft.desired * (draft.database_pool_size + 2 * draft.postgres_pool_size)}。预算需从数据库总连接数中扣除主服务及其他应用所需连接。</p>
<p className="text-muted-foreground text-sm">先读取指纹、检测资源并填写配置,再启用保存。资源预算需为主服务、数据库及操作系统保留余量。修改单节点配置前,将数量设为 0 并等待节点退出。</p>
<p className="text-muted-foreground text-sm">创建 Worker 前,系统会在所选主容器内验证 Python 3.12+、uvicorn 和 Worker 入口;默认路径不可用时会自动查找并保存可用路径。无需使用宿主机 Python 或联网下载。</p>
<p className="text-muted-foreground text-sm">主机密钥指纹可通过上方按钮读取并确认。账号需要运行 Docker 的权限。本机 Socket 需在主容器挂载 /var/run/docker.sock:/var/run/docker.sock;Worker 不继承该挂载。源容器的数据目录和配置必须已持久化挂载;聊天存储支持 PostgreSQL 或 SQLite,沿用现有配置;SQLite 必须共享本机数据目录。控制器私有目录需要独立持久化,不能与 Worker 共享。</p>
<div className="flex gap-3"><Button disabled={busy || !!error} onClick={() => void save()}>保存并应用</Button><Button variant="outline" disabled={busy || !!error} onClick={() => void test()}>测试已保存的连接</Button></div>
</>}
{status?.error && <p role="alert" className="text-destructive">{status.error}</p>}
<div className="space-y-2"><h4 className="font-medium">执行节点(每 5 秒更新)</h4>
{status?.nodes.length === 0 && <p className="text-muted-foreground text-sm">暂无节点。启用后按期望数量创建。</p>}
{status?.nodes.map((node) => <div className="rounded border p-3 text-sm" key={node.name}><div className="flex justify-between gap-2"><span>{node.name}</span><span>{node.draining ? "停止接单,等待完成" : node.ready ? "就绪" : "等待就绪"}</span></div><p>执行与排队:{node.active} / 同时执行额度:{node.capacity ?? "—"}</p>{node.error && <p className="text-destructive">{node.error}</p>}</div>)}
</div>
</section>;
}
@@ -2,6 +2,7 @@ import type { BaseStream } from "@langchain/langgraph-sdk";
import { useEffect } from "react";
import { useI18n } from "@/core/i18n/hooks";
import { useAppSystemName } from "@/core/system-settings/hooks";
import type { AgentThreadState } from "@/core/threads";
import { sanitizeThreadTitleForDisplay } from "@/core/threads/utils";
import { desensitize } from "@/lib/desensitize";
@@ -20,6 +21,7 @@ export function ThreadTitle({
thread: BaseStream<AgentThreadState>;
}) {
const { t } = useI18n();
const appName = useAppSystemName(t.pages.appName);
const { isNewThread } = useThreadChat();
const displayTitle = sanitizeThreadTitleForDisplay(thread.values?.title);
@@ -32,15 +34,15 @@ export function ThreadTitle({
_title = t.pages.newChat;
}
if (thread.isThreadLoading) {
document.title = `Loading... - ${t.pages.appName}`;
document.title = `Loading... - ${appName}`;
} else {
document.title = `${_title} - ${t.pages.appName}`;
document.title = `${_title} - ${appName}`;
}
}, [
appName,
isNewThread,
t.pages.newChat,
t.pages.untitled,
t.pages.appName,
thread.isThreadLoading,
thread.values,
displayTitle,
@@ -7,6 +7,20 @@ import { AlertTriangle, MapPinned, RefreshCw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { getMapTileAttribution, getMapTileUrl } from "@/core/utils/map-tile-config";
import {
coordinatesMatch,
curvedLineCoordinates,
flowArrowsForLines,
initialMapCamera,
overlayPadding,
resolveLineColor,
resolveMarkerColor,
shortenProjectedPath,
svgPathFromPoints,
type FlowLine,
type MapCamera,
type MapPoint,
} from "./map-style";
import type { MapSpec } from "./visualization-spec";
import { VisualizationCard } from "./visualization-card";
@@ -33,31 +47,162 @@ function allCoordinates(spec: MapSpec): Array<[number, number]> {
];
}
function defaultCenter(spec: MapSpec): [number, number] {
if (spec.center) return spec.center;
const coordinates = allCoordinates(spec);
if (coordinates.length === 0) return [104.1954, 35.8617];
const total = coordinates.reduce(([lng, lat], coordinate) => [lng + coordinate[0], lat + coordinate[1]], [0, 0]);
return [total[0] / coordinates.length, total[1] / coordinates.length];
function bootCamera(camera: MapCamera): { center: MapPoint; zoom: number } {
if (camera.kind === "center") return { center: camera.center, zoom: camera.zoom };
return {
center: [(camera.sw[0] + camera.ne[0]) / 2, (camera.sw[1] + camera.ne[1]) / 2],
zoom: 4,
};
}
function applyMapCamera(map: maplibregl.Map, camera: MapCamera, padding: number) {
if (camera.kind === "center") {
map.jumpTo({ center: camera.center, zoom: camera.zoom });
return;
}
map.fitBounds([camera.sw, camera.ne], { padding, maxZoom: camera.maxZoom, duration: 0 });
}
function prefersReducedMotion(): boolean {
return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches === true;
}
function markerColorLookup(spec: MapSpec): Map<string, string> {
const colors = new Map<string, string>();
spec.markers.forEach((marker, index) => {
colors.set(marker.name, resolveMarkerColor(index, marker.color));
});
return colors;
}
function styledLines(spec: MapSpec): FlowLine[] {
const markerColors = markerColorLookup(spec);
return spec.lines.map((line, index) => {
const start = line.coordinates[0];
const startMarker = start
? spec.markers.find((marker) => coordinatesMatch(marker.coordinate, start))
: undefined;
const fromColor = startMarker ? markerColors.get(startMarker.name) : undefined;
return {
coordinates: line.coordinates,
color: resolveLineColor(index, line.color, fromColor),
name: line.name,
arrow: line.arrow,
flow: line.flow,
};
});
}
function escapeHtml(value: string): string {
return value.replace(/[&<>'"]/g, (character) => ({
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
"'": "&#39;",
'"': "&quot;",
})[character] ?? character);
}
function projectPoint(map: maplibregl.Map, point: MapPoint): { x: number; y: number } {
const projected = map.project({ lng: point[0], lat: point[1] });
return { x: projected.x, y: projected.y };
}
function paintMapOverlay(
svg: SVGSVGElement,
map: maplibregl.Map,
lines: FlowLine[],
markers: Array<{ coordinate: MapPoint; color: string; name: string }>,
progress: number,
reducedMotion: boolean,
) {
const root = map.getContainer();
const width = root.clientWidth || 1;
const height = root.clientHeight || 1;
svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
svg.setAttribute("width", String(width));
svg.setAttribute("height", String(height));
const arrowDefs = lines
.filter((line) => line.arrow !== false)
.map((line) => {
const id = `df-map-arrow-${line.color.slice(1)}`;
return `<marker id="${id}" markerWidth="8" markerHeight="8" refX="6.4" refY="4" orient="auto" markerUnits="userSpaceOnUse"><path d="M0.6,1.1 L7.2,4 L0.6,6.9 Z" fill="${line.color}" stroke="#fff" stroke-width="0.6" stroke-linejoin="round"/></marker>`;
})
.filter((value, index, all) => all.indexOf(value) === index)
.join("");
const paths = lines
.map((line) => {
const projected = curvedLineCoordinates(line.coordinates).map((point) => projectPoint(map, point));
const d = svgPathFromPoints(shortenProjectedPath(projected, 10, 13));
if (!d) return "";
const markerId = `df-map-arrow-${line.color.slice(1)}`;
const end = line.arrow !== false ? ` marker-end="url(#${markerId})"` : "";
const flow =
line.arrow !== false && line.flow !== false && !reducedMotion
? `<path d="${d}" fill="none" stroke="#fff" stroke-width="1.1" stroke-linecap="round" stroke-dasharray="6 10" class="df-map-line-flow"/>`
: "";
return `<path d="${d}" fill="none" stroke="#fff" stroke-width="3.2" stroke-linecap="round" stroke-linejoin="round" opacity="0.88"/>
<path d="${d}" fill="none" stroke="${line.color}" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"${end}/>
${flow}`;
})
.join("");
const arrows = flowArrowsForLines(lines, progress, { reducedMotion })
.map((arrow) => {
const { x, y } = projectPoint(map, arrow.point);
return `<g transform="translate(${x.toFixed(1)} ${y.toFixed(1)}) rotate(${arrow.bearing.toFixed(1)})"><path d="M0,-4.5 L3.6,4.2 L0,2 L-3.6,4.2 Z" fill="${arrow.color}" stroke="#fff" stroke-width="0.7" stroke-linejoin="round"/></g>`;
})
.join("");
const dots = markers
.map((marker, index) => {
const { x, y } = projectPoint(map, marker.coordinate);
const label = escapeHtml(marker.name);
return `<g class="df-map-marker" data-marker-index="${index}" transform="translate(${x.toFixed(1)} ${y.toFixed(1)})" style="cursor:pointer;pointer-events:auto">
<title>${label}</title>
<circle r="16" fill="transparent"/>
<circle r="8" fill="${marker.color}" stroke="#fff" stroke-width="2.5" paint-order="stroke" style="filter:drop-shadow(0 1px 3px rgba(15,23,42,0.45))"/>
</g>`;
})
.join("");
svg.innerHTML = `<defs>${arrowDefs}</defs>${paths}${arrows}${dots}`;
}
export default function MapRenderer({ spec }: { spec: MapSpec }) {
const containerRef = useRef<HTMLDivElement>(null);
const overlayRef = useRef<SVGSVGElement>(null);
const mapRef = useRef<maplibregl.Map | null>(null);
const [tileFailed, setTileFailed] = useState(false);
const [reloadToken, setReloadToken] = useState(0);
const coordinates = useMemo(() => allCoordinates(spec), [spec]);
const lines = useMemo(() => styledLines(spec), [spec]);
const markerColors = useMemo(
() => spec.markers.map((marker, index) => resolveMarkerColor(index, marker.color)),
[spec],
);
useEffect(() => {
const container = containerRef.current;
const overlay = overlayRef.current;
if (!container) return;
setTileFailed(false);
const camera = initialMapCamera(coordinates, { center: spec.center, zoom: spec.zoom });
const boot = bootCamera(camera);
const overlayMarkers = spec.markers.map((marker, index) => ({
coordinate: marker.coordinate,
color: markerColors[index] ?? resolveMarkerColor(index, marker.color),
name: marker.name,
}));
const map = new maplibregl.Map({
container,
style: createStyle(),
center: defaultCenter(spec),
zoom: spec.zoom ?? (coordinates.length > 1 ? 4 : 8),
center: boot.center,
zoom: boot.zoom,
minZoom: 1,
maxZoom: 20,
attributionControl: { compact: true },
@@ -65,18 +210,59 @@ export default function MapRenderer({ spec }: { spec: MapSpec }) {
mapRef.current = map;
map.addControl(new maplibregl.NavigationControl({ showCompass: false }), "top-right");
const markers: maplibregl.Marker[] = [];
for (const marker of spec.markers) {
const element = document.createElement("button");
element.type = "button";
element.className = "size-5 rounded-full border-2 border-white bg-primary shadow-md focus:outline-none focus:ring-2 focus:ring-primary/50";
element.title = marker.name;
element.setAttribute("aria-label", marker.name);
const popup = new maplibregl.Popup({ offset: 14 }).setHTML(
`<div style="max-width:240px"><strong>${escapeHtml(marker.name)}</strong>${marker.description ? `<p style="margin:6px 0 0">${escapeHtml(marker.description)}</p>` : ""}</div>`,
);
markers.push(new maplibregl.Marker({ element }).setLngLat(marker.coordinate).setPopup(popup).addTo(map));
}
let raf = 0;
let lastPaint = 0;
let alive = true;
let viewReady = false;
let applyingView = false;
let popup: maplibregl.Popup | null = null;
const motionQuery = window.matchMedia?.("(prefers-reduced-motion: reduce)");
let reducedMotion = prefersReducedMotion();
const redrawOverlay = (progress = (performance.now() / 4000) % 1) => {
if (!alive || !overlay) return;
paintMapOverlay(overlay, map, lines, overlayMarkers, reducedMotion ? 0.72 : progress, reducedMotion);
};
const onMove = () => redrawOverlay();
map.on("move", onMove);
map.on("resize", onMove);
const tick = (now: number) => {
if (!alive) return;
const flowing = !reducedMotion && lines.some((line) => line.arrow !== false && line.flow !== false);
if (flowing && now - lastPaint >= 32) {
lastPaint = now;
redrawOverlay((now / 4000) % 1);
}
raf = requestAnimationFrame(tick);
};
const onMotionChange = () => {
reducedMotion = prefersReducedMotion();
redrawOverlay();
};
motionQuery?.addEventListener("change", onMotionChange);
const openMarkerPopup = (index: number) => {
const marker = spec.markers[index];
if (!marker) return;
popup?.remove();
popup = new maplibregl.Popup({ offset: 16, closeButton: true })
.setLngLat(marker.coordinate)
.setHTML(
`<div style="max-width:240px"><strong>${escapeHtml(marker.name)}</strong>${marker.description ? `<p style="margin:6px 0 0">${escapeHtml(marker.description)}</p>` : ""}</div>`,
)
.addTo(map);
};
const onOverlayClick = (event: MouseEvent) => {
const target = event.target instanceof Element ? event.target.closest("[data-marker-index]") : null;
if (!target) return;
event.stopPropagation();
openMarkerPopup(Number(target.getAttribute("data-marker-index")));
};
overlay?.addEventListener("click", onOverlayClick);
let baseTileLoaded = false;
const onSourceData = (event: maplibregl.MapSourceDataEvent) => {
@@ -91,70 +277,60 @@ export default function MapRenderer({ spec }: { spec: MapSpec }) {
map.on("sourcedata", onSourceData);
map.on("error", onError);
map.on("load", () => {
if (spec.lines.length > 0) {
map.addSource("visual-lines", {
type: "geojson",
data: {
type: "FeatureCollection",
features: spec.lines.map((line) => ({
type: "Feature",
properties: { name: line.name ?? "" },
geometry: { type: "LineString", coordinates: line.coordinates },
})),
},
});
map.addLayer({
id: "visual-lines",
type: "line",
source: "visual-lines",
paint: { "line-color": "#2563eb", "line-width": 3, "line-opacity": 0.85 },
});
}
const applyView = () => {
if (!alive) return false;
map.resize();
const width = container.clientWidth;
const height = container.clientHeight;
if (width < 80 || height < 80) return false;
if (!map.loaded() && !map.isStyleLoaded()) return false;
applyMapCamera(map, camera, overlayPadding(width, height));
redrawOverlay();
return true;
};
if (spec.polygons.length > 0) {
map.addSource("visual-polygons", {
type: "geojson",
data: {
type: "FeatureCollection",
features: spec.polygons.map((polygon) => ({
type: "Feature",
properties: { name: polygon.name ?? "" },
geometry: { type: "Polygon", coordinates: [[...polygon.coordinates, polygon.coordinates[0]]] },
})),
},
});
map.addLayer({
id: "visual-polygons-fill",
type: "fill",
source: "visual-polygons",
paint: { "fill-color": "#2563eb", "fill-opacity": 0.18 },
});
map.addLayer({
id: "visual-polygons-border",
type: "line",
source: "visual-polygons",
paint: { "line-color": "#2563eb", "line-width": 2 },
});
const ensureView = () => {
if (!alive || applyingView) return;
if (viewReady) {
map.resize();
redrawOverlay();
return;
}
applyingView = true;
const fitted = applyView();
applyingView = false;
if (!fitted) return;
viewReady = true;
map.once("idle", () => {
if (!alive) return;
map.resize();
redrawOverlay();
});
raf = requestAnimationFrame(tick);
};
if (!spec.center && coordinates.length > 1) {
const bounds = coordinates.reduce(
(current, coordinate) => current.extend(coordinate),
new maplibregl.LngLatBounds(coordinates[0], coordinates[0]),
);
map.fitBounds(bounds, { padding: 52, maxZoom: 12, duration: 0 });
}
});
map.on("load", ensureView);
map.once("idle", ensureView);
const resizeObserver = new ResizeObserver(ensureView);
resizeObserver.observe(container);
requestAnimationFrame(ensureView);
return () => {
alive = false;
cancelAnimationFrame(raf);
resizeObserver.disconnect();
motionQuery?.removeEventListener("change", onMotionChange);
overlay?.removeEventListener("click", onOverlayClick);
popup?.remove();
map.off("move", onMove);
map.off("resize", onMove);
map.off("load", ensureView);
map.off("sourcedata", onSourceData);
map.off("error", onError);
markers.forEach((marker) => marker.remove());
mapRef.current = null;
map.remove();
};
}, [coordinates, reloadToken, spec]);
}, [coordinates, lines, markerColors, reloadToken, spec]);
return (
<VisualizationCard>
@@ -165,6 +341,18 @@ export default function MapRenderer({ spec }: { spec: MapSpec }) {
</div>
<div className="relative">
<div ref={containerRef} className="h-[420px] w-full" role="img" aria-label={`${spec.title},包含 ${spec.markers.length} 个地点`} />
<style>{`
.df-map-line-flow { animation: df-map-line-flow 1.2s linear infinite; }
@keyframes df-map-line-flow { to { stroke-dashoffset: -32; } }
@media (prefers-reduced-motion: reduce) {
.df-map-line-flow { animation: none; }
}
`}</style>
<svg
ref={overlayRef}
aria-hidden="true"
className="pointer-events-none absolute inset-x-0 top-0 z-[1] h-[420px] w-full overflow-visible"
/>
{tileFailed ? (
<div className="absolute inset-x-3 top-3 z-10 flex items-center gap-2 rounded-lg border border-amber-300 bg-amber-50/95 p-3 text-xs text-amber-900 shadow-sm" role="status">
<AlertTriangle aria-hidden="true" className="mt-0.5 size-4 shrink-0" />
@@ -185,30 +373,46 @@ export default function MapRenderer({ spec }: { spec: MapSpec }) {
</div>
) : null}
</div>
{spec.markers.length > 0 ? (
{spec.markers.length > 0 || spec.lines.length > 0 ? (
<details className="border-t px-3 py-2 text-xs text-muted-foreground">
<summary className="cursor-pointer select-none">查看地点列表</summary>
<ul className="mt-2 space-y-1">
{spec.markers.map((marker, index) => (
<li key={`${marker.name}-${index}`}>
<span className="font-medium text-foreground">{marker.name}</span>
<span>({marker.coordinate[0]},{marker.coordinate[1]})</span>
{marker.description ? <span>:{marker.description}</span> : null}
</li>
))}
</ul>
{spec.markers.length > 0 ? (
<ul className="mt-2 space-y-1">
{spec.markers.map((marker, index) => (
<li key={`${marker.name}-${index}`} className="flex items-start gap-2">
<span
aria-hidden="true"
className="mt-0.5 inline-block size-2.5 shrink-0 rounded-full border border-black/10"
style={{ background: markerColors[index] }}
/>
<span>
<span className="font-medium text-foreground">{marker.name}</span>
<span>({marker.coordinate[0]},{marker.coordinate[1]})</span>
{marker.description ? <span>:{marker.description}</span> : null}
</span>
</li>
))}
</ul>
) : null}
{spec.lines.length > 0 ? (
<ul className="mt-2 space-y-1">
{lines.map((line, index) => (
<li key={`${line.name ?? "line"}-${index}`} className="flex items-start gap-2">
<span
aria-hidden="true"
className="mt-1 inline-block h-0.5 w-4 shrink-0 rounded-full"
style={{ background: line.color }}
/>
<span>
<span className="font-medium text-foreground">{line.name || `连线 ${index + 1}`}</span>
{line.arrow !== false ? <span>,带箭头{line.flow === false ? "" : "并沿线流动"}</span> : null}
</span>
</li>
))}
</ul>
) : null}
</details>
) : null}
</VisualizationCard>
);
}
function escapeHtml(value: string): string {
return value.replace(/[&<>'"]/g, (character) => ({
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
"'": "&#39;",
'"': "&quot;",
})[character] ?? character);
}
@@ -0,0 +1,116 @@
import assert from "node:assert/strict";
import test from "node:test";
// @ts-expect-error Node's type-stripping test runner requires the explicit .ts suffix.
import {
curvedLineCoordinates,
flowArrowsForLines,
initialMapCamera,
overlayPadding,
pointAndBearing,
polylineMetrics,
resolveMarkerColor,
shortenProjectedPath,
svgPathFromCoordinates,
} from "./map-style.ts";
test("assigns distinct colors when the model omits them", () => {
assert.notEqual(resolveMarkerColor(0), resolveMarkerColor(1));
assert.equal(resolveMarkerColor(0, "#111111"), "#111111");
});
test("walks a line and wraps flowing arrows", () => {
const metrics = polylineMetrics([
[0, 0],
[10, 0],
]);
assert.ok(metrics);
const start = pointAndBearing(metrics!, 0);
const mid = pointAndBearing(metrics!, 5);
const wrapped = pointAndBearing(metrics!, 12);
assert.deepEqual(start.point, [0, 0]);
assert.equal(start.bearing, 90);
assert.deepEqual(mid.point, [5, 0]);
assert.equal(wrapped.point[0], 2);
assert.equal(wrapped.bearing, 90);
const arrows = flowArrowsForLines(
[{ coordinates: [[0, 0], [10, 0]], color: "#2563eb", arrow: true, flow: true }],
0,
);
assert.equal(arrows.length, 3);
const staticArrow = flowArrowsForLines(
[{ coordinates: [[0, 0], [10, 0]], color: "#2563eb", arrow: true, flow: true }],
0,
{ reducedMotion: true },
);
assert.equal(staticArrow.length, 1);
assert.ok(staticArrow[0]!.point[0] > 5);
});
test("builds an svg path from projected coordinates", () => {
const path = svgPathFromCoordinates(
[
[116.4, 39.9],
[121.47, 31.23],
],
([lng, lat]) => ({ x: lng, y: lat }),
);
assert.equal(path, "M116.4 39.9 L121.5 31.2");
});
test("turns a two-point connection into a bulging arc", () => {
const points = curvedLineCoordinates([
[0, 0],
[10, 0],
]);
assert.ok(points.length > 2);
const mid = points[Math.floor(points.length / 2)]!;
assert.ok(mid[1] > 0.8);
assert.deepEqual(points[0], [0, 0]);
assert.equal(points[points.length - 1]![0], 10);
assert.ok(Math.abs(points[points.length - 1]![1]) < 1e-9);
const arrows = flowArrowsForLines(
[{ coordinates: [[0, 0], [10, 0]], color: "#2563eb", arrow: true, flow: true }],
0.2,
);
assert.ok(arrows[0]!.point[1] > 0);
});
test("shortens a projected path so arrows sit off the markers", () => {
const trimmed = shortenProjectedPath(
[
{ x: 0, y: 0 },
{ x: 100, y: 0 },
],
10,
13,
);
assert.equal(trimmed.length, 2);
assert.ok(trimmed[0]!.x >= 9.9);
assert.ok(trimmed[1]!.x <= 87.1);
});
test("frames Beijing and Shanghai even when the model sent a China-wide camera", () => {
const beijing: [number, number] = [116.4074, 39.9042];
const shanghai: [number, number] = [121.4737, 31.2304];
const camera = initialMapCamera([beijing, shanghai], { center: [104.1954, 35.8617], zoom: 4 });
assert.equal(camera.kind, "bounds");
if (camera.kind !== "bounds") return;
assert.ok(camera.sw[0] <= beijing[0] && camera.sw[1] <= shanghai[1]);
assert.ok(camera.ne[0] >= shanghai[0] && camera.ne[1] >= beijing[1]);
assert.equal(camera.maxZoom, 12);
});
test("centers a single marker instead of using the model overview", () => {
const camera = initialMapCamera([[116.4, 39.9]], { center: [104.2, 35.8], zoom: 4 });
assert.deepEqual(camera, { kind: "center", center: [116.4, 39.9], zoom: 8 });
});
test("keeps padding inside a typical map card", () => {
const padding = overlayPadding(800, 420);
assert.ok(padding >= 32 && padding <= 80);
assert.ok(padding * 2 < 420);
});
@@ -0,0 +1,294 @@
export const MAP_MARKER_PALETTE = [
"#2563eb",
"#dc2626",
"#16a34a",
"#d97706",
"#7c3aed",
"#0891b2",
"#db2777",
"#4f46e5",
] as const;
export type MapPoint = [number, number];
export function resolveMarkerColor(index: number, explicit?: string): string {
return explicit ?? MAP_MARKER_PALETTE[index % MAP_MARKER_PALETTE.length]!;
}
export function resolveLineColor(
index: number,
explicit?: string,
fromMarkerColor?: string,
): string {
return explicit ?? fromMarkerColor ?? MAP_MARKER_PALETTE[index % MAP_MARKER_PALETTE.length]!;
}
export function coordinatesMatch(left: MapPoint, right: MapPoint, epsilon = 1e-4): boolean {
return Math.abs(left[0] - right[0]) <= epsilon && Math.abs(left[1] - right[1]) <= epsilon;
}
export type PolylineMetrics = {
coordinates: MapPoint[];
parts: number[];
total: number;
};
export function polylineMetrics(coordinates: MapPoint[]): PolylineMetrics | null {
if (coordinates.length < 2) return null;
const parts: number[] = [];
let total = 0;
for (let index = 1; index < coordinates.length; index += 1) {
const current = coordinates[index]!;
const previous = coordinates[index - 1]!;
const length = Math.hypot(current[0] - previous[0], current[1] - previous[1]);
parts.push(length);
total += length;
}
if (!(total > 0)) return null;
return { coordinates, parts, total };
}
export function pointAndBearing(
metrics: PolylineMetrics,
distance: number,
): { point: MapPoint; bearing: number } {
const wrapped = ((distance % metrics.total) + metrics.total) % metrics.total;
let remaining = wrapped;
for (let index = 0; index < metrics.parts.length; index += 1) {
const part = metrics.parts[index]!;
const start = metrics.coordinates[index]!;
const end = metrics.coordinates[index + 1]!;
if (remaining > part && index < metrics.parts.length - 1) {
remaining -= part;
continue;
}
const t = part === 0 ? 0 : Math.min(1, remaining / part);
const dlng = end[0] - start[0];
const dlat = end[1] - start[1];
return {
point: [start[0] + dlng * t, start[1] + dlat * t],
bearing: (Math.atan2(dlng, dlat) * 180) / Math.PI,
};
}
const last = metrics.coordinates[metrics.coordinates.length - 1]!;
const prev = metrics.coordinates[metrics.coordinates.length - 2]!;
return {
point: last,
bearing: (Math.atan2(last[0] - prev[0], last[1] - prev[1]) * 180) / Math.PI,
};
}
export type FlowLine = {
coordinates: MapPoint[];
color: string;
name?: string;
arrow?: boolean;
flow?: boolean;
};
export type FlowArrow = {
point: MapPoint;
bearing: number;
color: string;
lineName: string;
};
export const LINE_ARC_BULGE = 0.22;
export const LINE_ARC_SAMPLES = 20;
export function quadraticPoint(start: MapPoint, control: MapPoint, end: MapPoint, t: number): MapPoint {
const u = 1 - t;
return [
u * u * start[0] + 2 * u * t * control[0] + t * t * end[0],
u * u * start[1] + 2 * u * t * control[1] + t * t * end[1],
];
}
export function arcControlPoint(start: MapPoint, end: MapPoint, bulge = LINE_ARC_BULGE): MapPoint {
const dx = end[0] - start[0];
const dy = end[1] - start[1];
const length = Math.hypot(dx, dy);
if (!(length > 0)) return start;
const offset = length * bulge;
return [(start[0] + end[0]) / 2 - (dy / length) * offset, (start[1] + end[1]) / 2 + (dx / length) * offset];
}
export function curvedLineCoordinates(coordinates: MapPoint[], samples = LINE_ARC_SAMPLES): MapPoint[] {
if (coordinates.length < 2) return coordinates;
const points: MapPoint[] = [];
for (let index = 1; index < coordinates.length; index += 1) {
const start = coordinates[index - 1]!;
const end = coordinates[index]!;
if (coordinatesMatch(start, end)) {
if (points.length === 0) points.push(start);
continue;
}
const control = arcControlPoint(start, end);
const from = index === 1 ? 0 : 1;
for (let step = from; step <= samples; step += 1) {
points.push(quadraticPoint(start, control, end, step / samples));
}
}
return points.length >= 2 ? points : coordinates;
}
export function flowArrowsForLines(
lines: FlowLine[],
progress: number,
options?: { reducedMotion?: boolean },
): FlowArrow[] {
const arrows: FlowArrow[] = [];
const reducedMotion = options?.reducedMotion === true;
for (const line of lines) {
if (line.arrow === false) continue;
const metrics = polylineMetrics(curvedLineCoordinates(line.coordinates));
if (!metrics) continue;
const animate = line.flow !== false && !reducedMotion;
const count = animate ? 3 : 1;
const offset = animate ? progress : 0.72;
for (let index = 0; index < count; index += 1) {
const distance = ((offset + index / count) % 1) * metrics.total;
const placed = pointAndBearing(metrics, distance);
arrows.push({
...placed,
color: line.color,
lineName: line.name ?? "",
});
}
}
return arrows;
}
export function svgPathFromPoints(points: Array<{ x: number; y: number }>): string {
return points
.map((point, index) => `${index === 0 ? "M" : "L"}${point.x.toFixed(1)} ${point.y.toFixed(1)}`)
.join(" ");
}
export function svgPathFromCoordinates(
coordinates: MapPoint[],
project: (point: MapPoint) => { x: number; y: number },
): string {
return svgPathFromPoints(coordinates.map(project));
}
function projectedPathLength(points: Array<{ x: number; y: number }>): number {
let total = 0;
for (let index = 1; index < points.length; index += 1) {
const current = points[index]!;
const previous = points[index - 1]!;
total += Math.hypot(current.x - previous.x, current.y - previous.y);
}
return total;
}
function trimProjectedPath(
points: Array<{ x: number; y: number }>,
gap: number,
edge: "start" | "end",
): Array<{ x: number; y: number }> {
if (points.length < 2 || gap <= 0) return points;
let remaining = gap;
if (edge === "start") {
let index = 0;
while (index < points.length - 1 && remaining > 0) {
const current = points[index]!;
const next = points[index + 1]!;
const part = Math.hypot(next.x - current.x, next.y - current.y);
if (part <= remaining) {
remaining -= part;
index += 1;
continue;
}
const t = remaining / part;
const cut = { x: current.x + (next.x - current.x) * t, y: current.y + (next.y - current.y) * t };
return [cut, ...points.slice(index + 1)];
}
return points.slice(-1);
}
let index = points.length - 1;
while (index > 0 && remaining > 0) {
const current = points[index]!;
const previous = points[index - 1]!;
const part = Math.hypot(current.x - previous.x, current.y - previous.y);
if (part <= remaining) {
remaining -= part;
index -= 1;
continue;
}
const t = remaining / part;
const cut = { x: current.x + (previous.x - current.x) * t, y: current.y + (previous.y - current.y) * t };
return [...points.slice(0, index), cut];
}
return points.slice(0, 1);
}
export function shortenProjectedPath(
points: Array<{ x: number; y: number }>,
startGap: number,
endGap: number,
): Array<{ x: number; y: number }> {
if (points.length < 2) return points;
const total = projectedPathLength(points);
if (!(total > 0)) return points;
const maxGap = total / 2 - 4;
if (maxGap <= 0) return points;
return trimProjectedPath(
trimProjectedPath(points, Math.min(startGap, maxGap), "start"),
Math.min(endGap, maxGap),
"end",
);
}
export const FALLBACK_MAP_CENTER: MapPoint = [104.1954, 35.8617];
export const SINGLE_POINT_ZOOM = 8;
export const MULTI_POINT_MAX_ZOOM = 12;
export const FALLBACK_MAP_ZOOM = 4;
export type MapCamera =
| { kind: "center"; center: MapPoint; zoom: number }
| { kind: "bounds"; sw: MapPoint; ne: MapPoint; maxZoom: number };
export function boundsFromCoordinates(coordinates: MapPoint[]): { sw: MapPoint; ne: MapPoint } | null {
if (coordinates.length === 0) return null;
let minLng = coordinates[0]![0];
let minLat = coordinates[0]![1];
let maxLng = minLng;
let maxLat = minLat;
for (const [lng, lat] of coordinates) {
minLng = Math.min(minLng, lng);
minLat = Math.min(minLat, lat);
maxLng = Math.max(maxLng, lng);
maxLat = Math.max(maxLat, lat);
}
return { sw: [minLng, minLat], ne: [maxLng, maxLat] };
}
export function isDegenerateBounds(sw: MapPoint, ne: MapPoint, epsilon = 1e-5): boolean {
return Math.abs(ne[0] - sw[0]) <= epsilon && Math.abs(ne[1] - sw[1]) <= epsilon;
}
export function overlayPadding(width: number, height: number): number {
return Math.max(32, Math.min(80, Math.floor(Math.min(width, height) * 0.14)));
}
export function initialMapCamera(
coordinates: MapPoint[],
hint?: { center?: MapPoint; zoom?: number },
): MapCamera {
if (coordinates.length === 0) {
return {
kind: "center",
center: hint?.center ?? FALLBACK_MAP_CENTER,
zoom: hint?.zoom ?? FALLBACK_MAP_ZOOM,
};
}
if (coordinates.length === 1) {
return { kind: "center", center: coordinates[0]!, zoom: hint?.zoom && hint.zoom >= 6 ? hint.zoom : SINGLE_POINT_ZOOM };
}
const bounds = boundsFromCoordinates(coordinates);
if (!bounds || isDegenerateBounds(bounds.sw, bounds.ne)) {
return { kind: "center", center: coordinates[0]!, zoom: SINGLE_POINT_ZOOM };
}
return { kind: "bounds", sw: bounds.sw, ne: bounds.ne, maxZoom: MULTI_POINT_MAX_ZOOM };
}
@@ -2,7 +2,12 @@ import assert from "node:assert/strict";
import test from "node:test";
// @ts-expect-error Node's type-stripping test runner requires the explicit .ts suffix.
import { parseVisualizationSpec, splitVisualizationContent } from "./visualization-spec.ts";
import {
parseMapColor,
parseOptionalBoolean,
parseVisualizationSpec,
splitVisualizationContent,
} from "./visualization-spec.ts";
test("ordinary markdown remains one unchanged segment", () => {
const content = "普通回答\n\n```ts\nconst value = 1;\n```";
@@ -230,6 +235,139 @@ test("rejects invalid map coordinates", () => {
assert.equal(result.ok, false);
});
test("recovers Beijing-Shanghai lines that omit coordinates", () => {
const fromToByName = parseVisualizationSpec(
"map-json",
JSON.stringify({
title: "北京上海位置地图",
markers: [
{ name: "北京", coordinate: [116.4, 39.9] },
{ name: "上海", coordinate: [121.47, 31.23] },
],
lines: [{ name: "北京-上海", from: "北京", to: "上海" }],
}),
);
assert.equal(fromToByName.ok, true);
assert.equal(fromToByName.ok && fromToByName.spec.type, "map");
if (fromToByName.ok && fromToByName.spec.type === "map") {
assert.equal(fromToByName.spec.markers.length, 2);
assert.deepEqual(fromToByName.spec.lines[0]?.coordinates, [
[116.4, 39.9],
[121.47, 31.23],
]);
}
const singularCoordinate = parseVisualizationSpec(
"map-json",
JSON.stringify({
markers: [
{ name: "北京", coordinate: [116.4, 39.9] },
{ name: "上海", coordinate: [121.47, 31.23] },
],
lines: [{ name: "联络", coordinate: [[116.4, 39.9], [121.47, 31.23]] }],
}),
);
assert.equal(singularCoordinate.ok, true);
if (singularCoordinate.ok && singularCoordinate.spec.type === "map") {
assert.equal(singularCoordinate.spec.lines.length, 1);
}
const echartsCoords = parseVisualizationSpec(
"map-json",
JSON.stringify({
markers: [
{ name: "北京", coordinate: [116.4, 39.9] },
{ name: "上海", coordinate: [121.47, 31.23] },
],
lines: [{ name: "联络", coords: [[116.4, 39.9], [121.47, 31.23]] }],
}),
);
assert.equal(echartsCoords.ok, true);
if (echartsCoords.ok && echartsCoords.spec.type === "map") {
assert.equal(echartsCoords.spec.lines.length, 1);
}
const fromToPoints = parseVisualizationSpec(
"map-json",
JSON.stringify({
markers: [
{ name: "北京", lng: 116.4, lat: 39.9 },
{ name: "上海", longitude: "121.47", latitude: "31.23" },
],
lines: [{ from: [116.4, 39.9], to: [121.47, 31.23] }],
}),
);
assert.equal(fromToPoints.ok, true);
if (fromToPoints.ok && fromToPoints.spec.type === "map") {
assert.equal(fromToPoints.spec.markers.length, 2);
assert.equal(fromToPoints.spec.lines.length, 1);
}
});
test("keeps markers when a line cannot be recovered", () => {
const result = parseVisualizationSpec(
"map-json",
JSON.stringify({
title: "北京上海位置地图",
markers: [
{ name: "北京", coordinate: [116.4, 39.9] },
{ name: "上海", coordinate: [121.47, 31.23] },
],
lines: [{ name: "北京-上海" }],
}),
);
assert.equal(result.ok, true);
if (result.ok && result.spec.type === "map") {
assert.equal(result.spec.markers.length, 2);
assert.equal(result.spec.lines.length, 0);
}
});
test("parses named, Chinese and hex marker colors", () => {
assert.equal(parseMapColor("red"), "#dc2626");
assert.equal(parseMapColor("蓝色"), "#2563eb");
assert.equal(parseMapColor("#0f8"), "#00ff88");
assert.equal(parseMapColor("#2563EB"), "#2563eb");
assert.equal(parseMapColor("javascript:alert(1)"), undefined);
assert.equal(parseOptionalBoolean("是"), true);
assert.equal(parseOptionalBoolean("false"), false);
});
test("keeps marker colors and line arrow/flow flags", () => {
const result = parseVisualizationSpec(
"map-json",
JSON.stringify({
markers: [
{ name: "北京", coordinate: [116.4, 39.9], color: "red" },
{ name: "上海", coordinate: [121.47, 31.23], colour: "#16a34a" },
],
lines: [
{
name: "北京-上海",
from: "北京",
to: "上海",
color: "蓝色",
arrow: "是",
flow: true,
},
],
}),
);
assert.equal(result.ok, true);
if (result.ok && result.spec.type === "map") {
assert.equal(result.spec.markers[0]?.color, "#dc2626");
assert.equal(result.spec.markers[1]?.color, "#16a34a");
assert.equal(result.spec.lines[0]?.color, "#2563eb");
assert.equal(result.spec.lines[0]?.arrow, true);
assert.equal(result.spec.lines[0]?.flow, true);
}
});
test("does not treat a generic json log as a map after dropping invalid lines", () => {
const content = '```json\n{"title":"日志","lines":["error 1","error 2"]}\n```';
assert.deepEqual(splitVisualizationContent(content), [{ type: "markdown", content }]);
});
test("flow and chart fences stay on the ordinary Markdown path", () => {
const content = "```flow-json\n{}\n```\n```chart-json\n{}\n```";
assert.deepEqual(splitVisualizationContent(content), [{ type: "markdown", content }]);
@@ -10,6 +10,10 @@ const optionalText = z.string().trim().max(2_000).optional();
const longitude = z.number().finite().min(-180).max(180);
const latitude = z.number().finite().min(-90).max(90);
const coordinateSchema = z.tuple([longitude, latitude]);
const mapColorSchema = z
.string()
.regex(/^#[0-9a-f]{6}$/i, "颜色必须是 #rrggbb")
.optional();
const mapSchema = z.object({
type: z.literal("map").default("map"),
@@ -22,6 +26,7 @@ const mapSchema = z.object({
name: safeText,
coordinate: coordinateSchema,
description: optionalText,
color: mapColorSchema,
}),
)
.max(500)
@@ -31,6 +36,9 @@ const mapSchema = z.object({
z.object({
name: z.string().trim().max(120).optional(),
coordinates: z.array(coordinateSchema).min(2).max(2_000),
color: mapColorSchema,
arrow: z.boolean().default(true),
flow: z.boolean().default(true),
}),
)
.max(100)
@@ -40,6 +48,7 @@ const mapSchema = z.object({
z.object({
name: z.string().trim().max(120).optional(),
coordinates: z.array(coordinateSchema).min(3).max(2_000),
color: mapColorSchema,
}),
)
.max(100)
@@ -95,13 +104,300 @@ export type VisualizationParseResult =
| { ok: true; spec: VisualizationSpec }
| { ok: false; error: string };
const NAMED_MAP_COLORS: Record<string, string> = {
red: "#dc2626",
orange: "#ea580c",
amber: "#d97706",
yellow: "#ca8a04",
green: "#16a34a",
emerald: "#059669",
teal: "#0d9488",
cyan: "#0891b2",
blue: "#2563eb",
indigo: "#4f46e5",
violet: "#7c3aed",
purple: "#7c3aed",
pink: "#db2777",
rose: "#e11d48",
gray: "#64748b",
grey: "#64748b",
slate: "#64748b",
black: "#0f172a",
white: "#f8fafc",
红: "#dc2626",
红色: "#dc2626",
橙: "#ea580c",
橙色: "#ea580c",
黄: "#ca8a04",
黄色: "#ca8a04",
绿: "#16a34a",
绿色: "#16a34a",
青: "#0891b2",
青色: "#0891b2",
蓝: "#2563eb",
蓝色: "#2563eb",
紫: "#7c3aed",
紫色: "#7c3aed",
粉: "#db2777",
粉色: "#db2777",
灰: "#64748b",
灰色: "#64748b",
};
const HEX_COLOR = /^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
export function parseMapColor(value: unknown): string | undefined {
if (typeof value !== "string") return undefined;
const raw = value.trim();
if (!raw || raw.length > 24) return undefined;
if (/url\s*\(|javascript:|expression\s*\(/i.test(raw)) return undefined;
const named = NAMED_MAP_COLORS[raw.toLowerCase()] ?? NAMED_MAP_COLORS[raw];
if (named) return named;
if (!HEX_COLOR.test(raw)) return undefined;
const hex = raw.slice(1);
if (hex.length === 3) {
return `#${hex[0]}${hex[0]}${hex[1]}${hex[1]}${hex[2]}${hex[2]}`.toLowerCase();
}
return `#${hex.slice(0, 6).toLowerCase()}`;
}
export function parseOptionalBoolean(value: unknown): boolean | undefined {
if (typeof value === "boolean") return value;
if (value === 1 || value === "1") return true;
if (value === 0 || value === "0") return false;
if (typeof value !== "string") return undefined;
const normalized = value.trim().toLowerCase();
if (["true", "yes", "on", "是"].includes(normalized)) return true;
if (["false", "no", "off", "否"].includes(normalized)) return false;
return undefined;
}
function asRecord(value: unknown): Record<string, unknown> | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
return value as Record<string, unknown>;
}
function asFiniteNumber(value: unknown): number | null {
if (typeof value === "number" && Number.isFinite(value)) return value;
if (typeof value === "string" && value.trim()) {
const parsed = Number(value);
if (Number.isFinite(parsed)) return parsed;
}
return null;
}
function parseCoordinate(value: unknown): [number, number] | null {
if (Array.isArray(value) && value.length >= 2) {
const lng = asFiniteNumber(value[0]);
const lat = asFiniteNumber(value[1]);
if (lng != null && lat != null && lng >= -180 && lng <= 180 && lat >= -90 && lat <= 90) {
return [lng, lat];
}
return null;
}
const record = asRecord(value);
if (!record) return null;
const nested =
record.coordinate ?? record.coordinates ?? record.coord ?? record.position ?? record.location;
if (nested !== value && (Array.isArray(nested) || asRecord(nested))) {
const nestedCoordinate = parseCoordinate(nested);
if (nestedCoordinate) return nestedCoordinate;
}
const lng = asFiniteNumber(record.lng ?? record.lon ?? record.longitude ?? record.x);
const lat = asFiniteNumber(record.lat ?? record.latitude ?? record.y);
if (lng != null && lat != null && lng >= -180 && lng <= 180 && lat >= -90 && lat <= 90) {
return [lng, lat];
}
return null;
}
function parseCoordinateList(value: unknown): Array<[number, number]> {
if (!Array.isArray(value) || value.length === 0) return [];
const direct = value
.map(parseCoordinate)
.filter((item): item is [number, number] => item != null);
if (direct.length >= 2) return direct;
if (value.length === 1 && Array.isArray(value[0])) return parseCoordinateList(value[0]);
return direct;
}
function featureName(record: Record<string, unknown>): string | undefined {
const value = record.name ?? record.label ?? record.title ?? record.city ?? record.text;
if (typeof value !== "string") return undefined;
const name = value.trim();
return name.length > 0 ? name : undefined;
}
function featureColor(record: Record<string, unknown>): string | undefined {
return parseMapColor(
record.color ?? record.colour ?? record.fill ?? record.fillColor ?? record.stroke,
);
}
function withOptionalStyle(
record: Record<string, unknown>,
extra?: Record<string, unknown>,
): Record<string, unknown> {
const color = featureColor(record);
return {
...extra,
...(color ? { color } : {}),
};
}
function normalizeMarkers(value: unknown): Array<Record<string, unknown>> {
const items = Array.isArray(value) ? value : value ? [value] : [];
const markers: Array<Record<string, unknown>> = [];
for (const item of items) {
const record = asRecord(item);
if (!record) continue;
const name = featureName(record);
const coordinate = parseCoordinate(item);
if (!name || !coordinate) continue;
markers.push({
name,
coordinate,
...withOptionalStyle(record, {
...(typeof record.description === "string" ? { description: record.description } : {}),
}),
});
}
return markers;
}
function resolvePoint(
value: unknown,
markersByName: Map<string, [number, number]>,
): [number, number] | null {
const coordinate = parseCoordinate(value);
if (coordinate) return coordinate;
if (typeof value === "string") return markersByName.get(value.trim()) ?? null;
const record = asRecord(value);
if (!record) return null;
const name = featureName(record);
return name ? (markersByName.get(name) ?? null) : null;
}
function normalizeLines(
value: unknown,
markersByName: Map<string, [number, number]>,
): Array<Record<string, unknown>> {
const items = Array.isArray(value) ? value : value ? [value] : [];
const lines: Array<Record<string, unknown>> = [];
for (const item of items) {
if (Array.isArray(item)) {
const coordinates = parseCoordinateList(item);
if (coordinates.length >= 2) lines.push({ coordinates });
continue;
}
const record = asRecord(item);
if (!record) continue;
const listed = parseCoordinateList(
record.coordinates ??
record.coordinate ??
record.coords ??
record.path ??
record.points ??
record.positions,
);
const from = resolvePoint(record.from ?? record.start ?? record.source, markersByName);
const to = resolvePoint(record.to ?? record.end ?? record.target, markersByName);
const coordinates = listed.length >= 2 ? listed : from && to ? [from, to] : [];
if (coordinates.length < 2) continue;
const name = featureName(record);
const arrow = parseOptionalBoolean(record.arrow ?? record.arrows ?? record.directed);
const flow = parseOptionalBoolean(record.flow ?? record.animate ?? record.animated);
lines.push({
...(name ? { name } : {}),
coordinates,
...withOptionalStyle(record),
...(arrow != null ? { arrow } : {}),
...(flow != null ? { flow } : {}),
});
}
return lines;
}
function normalizePolygons(value: unknown): Array<Record<string, unknown>> {
const items = Array.isArray(value) ? value : value ? [value] : [];
const polygons: Array<Record<string, unknown>> = [];
for (const item of items) {
if (Array.isArray(item)) {
const coordinates = parseCoordinateList(item);
if (coordinates.length >= 3) polygons.push({ coordinates });
continue;
}
const record = asRecord(item);
if (!record) continue;
const coordinates = parseCoordinateList(
record.coordinates ??
record.coordinate ??
record.coords ??
record.path ??
record.points ??
record.positions,
);
if (coordinates.length < 3) continue;
const name = featureName(record);
polygons.push({
...(name ? { name } : {}),
coordinates,
...withOptionalStyle(record),
});
}
return polygons;
}
function normalizeMapPayload(value: Record<string, unknown>): Record<string, unknown> {
const markers = Object.prototype.hasOwnProperty.call(value, "markers")
? normalizeMarkers(value.markers)
: undefined;
const markersByName = new Map<string, [number, number]>();
for (const marker of markers ?? []) {
const name = typeof marker.name === "string" ? marker.name : "";
const coordinate = marker.coordinate;
if (name && Array.isArray(coordinate) && coordinate.length === 2) {
markersByName.set(name, coordinate as [number, number]);
}
}
const lines = Object.prototype.hasOwnProperty.call(value, "lines")
? normalizeLines(value.lines, markersByName)
: undefined;
const polygons = Object.prototype.hasOwnProperty.call(value, "polygons")
? normalizePolygons(value.polygons)
: undefined;
const center = parseCoordinate(value.center) ?? undefined;
const zoom = asFiniteNumber(value.zoom) ?? undefined;
return {
...value,
type: "map",
...(center ? { center } : {}),
...(zoom != null ? { zoom } : {}),
...(markers ? { markers } : {}),
...(lines ? { lines } : {}),
...(polygons ? { polygons } : {}),
};
}
function mapHasRenderable(record: Record<string, unknown>): boolean {
return (
(Array.isArray(record.markers) && record.markers.length > 0) ||
(Array.isArray(record.lines) && record.lines.length > 0) ||
(Array.isArray(record.polygons) && record.polygons.length > 0) ||
parseCoordinate(record.center) != null
);
}
function normalizeLanguageType(
language: VisualizationLanguage,
value: unknown,
): unknown {
if (!value || typeof value !== "object" || Array.isArray(value)) return value;
const record = { ...(value as Record<string, unknown>) };
if (language === "map-json") record.type = "map";
if (language === "map-json") {
const normalized = normalizeMapPayload(record);
return mapHasRenderable(normalized) ? normalized : { ...record, type: "map" };
}
if (language === "mindmap-json") record.type = "mindmap";
return record;
}
@@ -221,18 +517,14 @@ export type VisualizationSegment =
const FENCE_PATTERN = /(^|\n)```(map-json|mindmap-json|mindmap|json)[ \t]*\r?\n/gi;
function isMapJsonSource(source: string): boolean {
let raw: unknown;
try {
raw = JSON.parse(source);
} catch {
return false;
}
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return false;
const record = raw as Record<string, unknown>;
const hasMapField = ["center", "zoom", "markers", "lines", "polygons"].some(
(field) => Object.prototype.hasOwnProperty.call(record, field),
const parsed = parseVisualizationSpec("map-json", source);
if (!parsed.ok || parsed.spec.type !== "map") return false;
return (
parsed.spec.markers.length > 0 ||
parsed.spec.lines.length > 0 ||
parsed.spec.polygons.length > 0 ||
parsed.spec.center != null
);
return hasMapField && parseVisualizationSpec("map-json", source).ok;
}
/** Split only our dedicated fences. With no match, the caller keeps the exact legacy renderer path. */
@@ -6,6 +6,7 @@ import Link from "next/link";
import { Button } from "@/components/ui/button";
import { useSidebar } from "@/components/ui/sidebar";
import { useI18n } from "@/core/i18n/hooks";
import { useAppSystemName } from "@/core/system-settings/hooks";
import { env } from "@/env";
import { cn } from "@/lib/utils";
@@ -50,12 +51,13 @@ export function SidebarCollapseButton({ className }: { className?: string }) {
export function WorkspaceHeader({ className }: { className?: string }) {
const { t } = useI18n();
const systemName = useAppSystemName(t.pages.appName);
const { state } = useSidebar();
const titleBlock = (
<div className="min-w-0 flex-1">
<div className="text-sidebar-foreground truncate text-sm font-semibold leading-tight tracking-tight">
{t.pages.appName}
{systemName}
</div>
</div>
);
@@ -13,7 +13,6 @@ import {
SidebarMenuButton,
SidebarMenuItem,
} from "@/components/ui/sidebar";
import { useI18n } from "@/core/i18n/hooks";
import { BookOpen, BotIcon, BrainIcon, FileSearch, FileText, FolderKanban, Landmark, Library, ListChecks, MessageSquarePlus, MessagesSquare, PenLine, Plus, SparklesIcon, Telescope, Users } from "lucide-react";
import { KnowledgeRagToggle } from "./knowledge-rag-toggle";
@@ -188,7 +187,6 @@ export function WorkspaceNavChatList({
showCollapseTrigger?: boolean;
compact?: boolean;
}) {
const { t } = useI18n();
const pathname = usePathname();
const navigate = useNavigate();
const { sidebarItems } = useWorkspaceCompactNavItems();
@@ -219,38 +217,42 @@ export function WorkspaceNavChatList({
{compact ? (
// 紧凑模式:新对话占满整行白卡样式 + 右侧收起钮(点击收起整列历史栏)。
<div className="flex items-center gap-1">
<SidebarMenuButton
isActive={pathname === "/page/workspace/chats/new"}
asChild
className={cn(NEW_CHAT_COMPACT_CLASS, "min-w-0 flex-1")}
>
<Link href="/page/workspace/chats/new" onClick={handleNewChatClick}>
<Plus className="stroke-[2.5] text-[var(--primary)]" />
<span>{newChatItem?.label ?? t.sidebar.newChat}</span>
</Link>
</SidebarMenuButton>
{newChatItem && (
<SidebarMenuButton
isActive={pathname === "/page/workspace/chats/new"}
asChild
className={cn(NEW_CHAT_COMPACT_CLASS, "min-w-0 flex-1")}
>
<Link href="/page/workspace/chats/new" onClick={handleNewChatClick}>
<Plus className="stroke-[2.5] text-[var(--primary)]" />
<span>{newChatItem.label}</span>
</Link>
</SidebarMenuButton>
)}
{showCollapseTrigger && (
<SidebarCollapseButton className="size-8 shrink-0 rounded-xl" />
)}
</div>
) : (
<div className="flex items-center gap-1">
<SidebarMenuButton
isActive={pathname === "/page/workspace/chats/new"}
asChild
className={cn(
NEW_CHAT_CLASS,
showCollapseTrigger && "min-w-0 flex-1",
)}
>
<Link
href="/page/workspace/chats/new"
onClick={handleNewChatClick}
{newChatItem && (
<SidebarMenuButton
isActive={pathname === "/page/workspace/chats/new"}
asChild
className={cn(
NEW_CHAT_CLASS,
showCollapseTrigger && "min-w-0 flex-1",
)}
>
<MessageSquarePlus />
<span>{newChatItem?.label ?? t.sidebar.newChat}</span>
</Link>
</SidebarMenuButton>
<Link
href="/page/workspace/chats/new"
onClick={handleNewChatClick}
>
<MessageSquarePlus />
<span>{newChatItem.label}</span>
</Link>
</SidebarMenuButton>
)}
{showCollapseTrigger && (
<SidebarCollapseButton className="size-8 shrink-0 rounded-xl" />
)}
@@ -18,6 +18,7 @@ import {
ScrollTextIcon,
Settings2Icon,
SettingsIcon,
ShieldAlertIcon,
SparklesIcon,
TagsIcon,
TimerIcon,
@@ -317,6 +318,14 @@ export function WorkspaceNavMenu() {
模型配置
</DropdownMenuItem>
)}
{isAdmin && (
<DropdownMenuItem
onClick={() => navigate("/page/workspace/admin/stream-truncations")}
>
<ShieldAlertIcon />
模型截断记录
</DropdownMenuItem>
)}
{/* 与全量模式左下角「设置和更多」下拉里的菜单管理同入口:
简洁模式没有全局侧边栏,走工作区地址带上 WorkspaceSidebar;
/page/strategy/admin/menu-management 保留给全量模式侧边栏。 */}
@@ -35,11 +35,10 @@ const NAV_ITEM_CLASS =
"dark:hover:bg-primary/15 dark:data-[active=true]:bg-primary/25 dark:data-[active=true]:text-primary-foreground";
export function WorkspaceNavStudio() {
const { notebooks, isLoading, isError } = useStudioNotebooks();
const { pathname } = useLocation();
const queryClient = useQueryClient();
const [open, setOpen] = useState(true);
const [open, setOpen] = useState(false);
const { notebooks, isLoading, isError, token } = useStudioNotebooks(open);
const [dialogOpen, setDialogOpen] = useState(false);
const [name, setName] = useState("");
const [creating, setCreating] = useState(false);
@@ -65,11 +64,6 @@ export function WorkspaceNavStudio() {
}
};
// 加载中、token 失败、空列表都不渲染整段,避免在 token 未确认前先闪一段工作室 UI 再消失。
if (isLoading || isError || notebooks.length === 0) {
return null;
}
const SIDEBAR_PREVIEW_COUNT = 2;
const preview = notebooks.slice(0, SIDEBAR_PREVIEW_COUNT);
@@ -96,12 +90,29 @@ export function WorkspaceNavStudio() {
<SidebarMenuButton
className={cn(NAV_ITEM_CLASS)}
onClick={() => { setDialogOpen(true); setError(""); setName(""); }}
disabled={!token}
>
<Plus className="shrink-0" />
<span>新建空间</span>
</SidebarMenuButton>
</SidebarMenuItem>
{isLoading && (
<SidebarMenuItem>
<div className="px-3 py-2 text-xs text-sidebar-foreground/60">正在连接工作室…</div>
</SidebarMenuItem>
)}
{isError && (
<SidebarMenuItem>
<div className="px-3 py-2 text-xs text-sidebar-foreground/60">工作室暂不可用</div>
</SidebarMenuItem>
)}
{!isLoading && !isError && notebooks.length === 0 && (
<SidebarMenuItem>
<div className="px-3 py-2 text-xs text-sidebar-foreground/60">暂无工作室空间</div>
</SidebarMenuItem>
)}
{/* 空间列表(最多展示 SIDEBAR_PREVIEW_COUNT 条) */}
{preview.map((nb) => (
<SidebarMenuItem key={nb.id}>