Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into dhk-1
This commit is contained in:
commit
c6b17d5946
90 files changed
+3612
-1452
No files matched your search
+31
-10
@@ -7,8 +7,15 @@ import { QueryClientProvider } from "@/components/query-client-provider";
|
||||
import { AuthSyncWatcher } from "@/core/auth/sync";
|
||||
import { I18nProvider } from "@/core/i18n/context";
|
||||
import { detectLocale } from "@/core/i18n/locale";
|
||||
import { resolveForcedThemeForPath } from "@/core/page-layout/chats-iframe-route";
|
||||
import { ChatProvider } from "@/contexts/ChatContext";
|
||||
import { ThemeProvider } from "@/contexts/ThemeContext";
|
||||
import {
|
||||
resolveEmbedRoundtableTheme,
|
||||
resolveEmbedTheme,
|
||||
} from "@/core/embed/params";
|
||||
import { usePublicEmbedTheme } from "@/core/embed/background";
|
||||
import { readWujieProps } from "@/core/embed/wujie";
|
||||
|
||||
import { HashRouter, useLocation } from "react-router-dom";
|
||||
|
||||
@@ -26,10 +33,32 @@ import EmbedRoundtablePage from "./pages/EmbedRoundtablePage";
|
||||
import { ChatRuntime } from "./pages/WorkspaceRoutes";
|
||||
import { NotFoundPage } from "./pages/NotFoundPage";
|
||||
|
||||
const PUBLIC_EMBED_PREFIXES = ["/share/", "/public/", "/roundtable-share/"];
|
||||
|
||||
function AppProviders({ children }: { children: React.ReactNode }) {
|
||||
const locale = useMemo(() => detectLocale(), []);
|
||||
const location = useLocation();
|
||||
const forcedTheme = location.pathname === "/landing" ? "light" : undefined;
|
||||
const publicEmbedTheme = usePublicEmbedTheme();
|
||||
const forcedTheme = useMemo(() => {
|
||||
const routeTheme = resolveForcedThemeForPath(location.pathname);
|
||||
if (routeTheme) return routeTheme;
|
||||
if (location.pathname === "/embed/roundtable") {
|
||||
const wp = readWujieProps();
|
||||
const raw =
|
||||
(typeof wp.theme === "string" && wp.theme.trim()) ||
|
||||
new URLSearchParams(location.search).get("theme")?.trim() ||
|
||||
"dark";
|
||||
return resolveEmbedRoundtableTheme(raw);
|
||||
}
|
||||
if (location.pathname.startsWith("/embed/chats")) {
|
||||
const raw = new URLSearchParams(location.search).get("theme")?.trim();
|
||||
return raw ? resolveEmbedTheme(raw) : undefined;
|
||||
}
|
||||
if (PUBLIC_EMBED_PREFIXES.some((p) => location.pathname.startsWith(p))) {
|
||||
return publicEmbedTheme;
|
||||
}
|
||||
return undefined;
|
||||
}, [location.pathname, location.search, publicEmbedTheme]);
|
||||
|
||||
return (
|
||||
<NextThemesProvider
|
||||
@@ -40,8 +69,6 @@ function AppProviders({ children }: { children: React.ReactNode }) {
|
||||
disableTransitionOnChange
|
||||
forcedTheme={forcedTheme}
|
||||
>
|
||||
{/* QueryClientProvider must wrap ThemeProvider because the custom
|
||||
ThemeProvider reads the admin-configured default via useQuery. */}
|
||||
<QueryClientProvider>
|
||||
<I18nProvider initialLocale={locale}>
|
||||
<ThemeProvider>
|
||||
@@ -66,11 +93,8 @@ export function App() {
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route path="/login/:username" element={<LoginPage />} />
|
||||
<Route path="/landing" element={<LandingPage />} />
|
||||
{/* Public read-only conversation viewer — no authentication. */}
|
||||
<Route path="/share/:shareCode" element={<PublicSharePage />} />
|
||||
{/* Public read-only user leaderboard publish page — no authentication. */}
|
||||
<Route path="/public/leaderboard" element={<PublicLeaderboardPage />} />
|
||||
{/* Public read-only roundtable share — landing + full result report. */}
|
||||
<Route
|
||||
path="/roundtable-share/:shareCode"
|
||||
element={<PublicRoundtableSharePage />}
|
||||
@@ -79,7 +103,6 @@ export function App() {
|
||||
path="/roundtable-share/:shareCode/report"
|
||||
element={<PublicRoundtableSharePage report />}
|
||||
/>
|
||||
{/* Public read-only scheduled-task runs viewer — no authentication. */}
|
||||
<Route
|
||||
path="/public/scheduled-tasks/:taskId"
|
||||
element={<PublicScheduledTaskPage />}
|
||||
@@ -88,7 +111,6 @@ export function App() {
|
||||
path="/public/scheduled-tasks/:taskId/runs/:runId/fullscreen"
|
||||
element={<PublicScheduledTaskFullscreenPage />}
|
||||
/>
|
||||
{/* Embedded workspace Q&A — no page/workspace sidebars; parent passes message/username/theme */}
|
||||
<Route
|
||||
path="/embed/chats/:thread_id"
|
||||
element={
|
||||
@@ -97,7 +119,6 @@ export function App() {
|
||||
</ChatRuntime>
|
||||
}
|
||||
/>
|
||||
{/* Embedded roundtable planning — body only, no sidebars; username login (not wujie ticket) */}
|
||||
<Route path="/embed/roundtable" element={<EmbedRoundtablePage />} />
|
||||
<Route path="/page/*" element={<PageRoutes />} />
|
||||
<Route path="*" element={<NotFoundPage />} />
|
||||
@@ -105,4 +126,4 @@ export function App() {
|
||||
</AppProviders>
|
||||
</HashRouter>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -26,13 +26,24 @@ import {
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { toast } from "sonner";
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
import { queryClient } from "@/components/query-client-provider";
|
||||
import Empty from "./empty";
|
||||
import { NetworkActor } from "./network-actor";
|
||||
|
||||
// ── 适配层 ─────────────────────────────────────────────────
|
||||
|
||||
function authenticatedFetch(url: string, init?: RequestInit) {
|
||||
const token = getStoredAuth()?.access_token;
|
||||
// 本组件只对接「我的笔记/空间」后端,用不到本系统(DeerFlow)token。
|
||||
// notebook token 由 fetchStudioToken(getTokenByEmail) 获取,缓存在 react-query
|
||||
// 的 ["studio","token",email] 下(见 core/studio/hooks)。
|
||||
function getNotebookToken(): string | undefined {
|
||||
const email = getStoredAuth()?.email ?? "";
|
||||
return queryClient.getQueryData<string>(["studio", "token", email]);
|
||||
}
|
||||
|
||||
// 上传到笔记后端时传 useNotebookToken=true 注入我的笔记 token;
|
||||
// 其余请求不注入本系统 token,调用方自行在 init.headers 里带 Authorization。
|
||||
export function authenticatedFetch(url: string, init?: RequestInit, useNotebookToken = false): Promise<Response> {
|
||||
const token = useNotebookToken ? getNotebookToken() : undefined;
|
||||
return fetch(url, {
|
||||
...init,
|
||||
headers: {
|
||||
@@ -334,7 +345,7 @@ const DocumentUploadPopupContent: FC<{
|
||||
if (!files.length) return;
|
||||
setUploading(true);
|
||||
try {
|
||||
const token = getStoredAuth()?.access_token ?? "";
|
||||
const token = getNotebookToken() ?? "";
|
||||
const formData = new FormData();
|
||||
formData.append("search_space_id", searchSpaceId);
|
||||
for (const file of files) {
|
||||
@@ -389,7 +400,7 @@ const DocumentUploadPopupContent: FC<{
|
||||
search_space_id: Number(searchSpaceId),
|
||||
source_list: dataList,
|
||||
}),
|
||||
});
|
||||
}, true);
|
||||
if (response.ok) {
|
||||
const data = await response.json() as { imported_count?: number };
|
||||
toast.success(`成功导入 ${data.imported_count || dataList.length} 个来源`);
|
||||
|
||||
@@ -10,17 +10,8 @@ import { Loader2, Plus, Search, Trash2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { toast } from "sonner";
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
import { authenticatedFetch } from "@/components/assistant-ui/document-upload-popup";
|
||||
|
||||
function authenticatedFetch(url: string, init?: RequestInit) {
|
||||
const token = getStoredAuth()?.access_token;
|
||||
return fetch(url, {
|
||||
...init,
|
||||
headers: {
|
||||
...(init?.headers ?? {}),
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
interface NetworkActorProps {
|
||||
inputValue: string;
|
||||
@@ -195,7 +186,7 @@ export function NetworkActor({ inputValue, searchSpaceId, onSuccess }: NetworkAc
|
||||
const [actorCount, setActorCount] = useState<number>(0);
|
||||
const [directionType, setDirectionType] = useState<string>('TW');
|
||||
const directionValue = useRef<string>('TW');
|
||||
const consumerUrl = 'http://ch1.b.uat.4.cn/consumer';
|
||||
const consumerUrl = import.meta.env.VITE_AIPI_CONSUMER_URL || 'https://ch1.b.uat.4.cn/consumer';
|
||||
const backendUrl = typeof window !== 'undefined'
|
||||
? (import.meta.env.VITE_BACKEND_BASE_URL || 'http://localhost:8001')
|
||||
: 'http://localhost:8001';
|
||||
@@ -395,7 +386,7 @@ export function NetworkActor({ inputValue, searchSpaceId, onSuccess }: NetworkAc
|
||||
search_space_id: Number(searchSpaceId),
|
||||
source_list: dataList,
|
||||
}),
|
||||
});
|
||||
}, true);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
toast.success(`成功导入 ${data.imported_count || dataList.length} 个来源`);
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
QueryClientProvider as TanStackQueryClientProvider,
|
||||
} from "@tanstack/react-query";
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
export const queryClient = new QueryClient();
|
||||
|
||||
export function QueryClientProvider({
|
||||
children,
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
import {
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
FileText,
|
||||
Hash,
|
||||
Loader2,
|
||||
Search,
|
||||
Sparkles,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { useKnowledgeNotes } from "@/core/knowledge/hooks";
|
||||
import type { KnowledgeNote } from "@/core/knowledge/types";
|
||||
|
||||
import { SOURCE_TYPE_LABELS, formatDateTime } from "./wikiUtils";
|
||||
|
||||
/** What was clicked: a tag (exact filter) or an entity (relation-graph match). */
|
||||
export type RelatedNotesFilter =
|
||||
| { kind: "tag"; value: string }
|
||||
| { kind: "entity"; value: string };
|
||||
|
||||
const PAGE_SIZE = 20;
|
||||
|
||||
function useDebounced<T>(value: T, delay = 300): T {
|
||||
const [debounced, setDebounced] = useState(value);
|
||||
useEffect(() => {
|
||||
const id = window.setTimeout(() => setDebounced(value), delay);
|
||||
return () => window.clearTimeout(id);
|
||||
}, [value, delay]);
|
||||
return debounced;
|
||||
}
|
||||
|
||||
/**
|
||||
* Click a tag / entity chip → list every other note that shares it.
|
||||
* Server-side keyword search + pagination so huge graphs stay usable:
|
||||
* tags use the backend's exact `tag` filter, entities the exact `entity`
|
||||
* filter (note→entity relations), both combinable with `keyword`.
|
||||
*/
|
||||
export function RelatedNotesDialog({
|
||||
filter,
|
||||
currentNoteId,
|
||||
onOpenChange,
|
||||
onSelect,
|
||||
}: {
|
||||
filter: RelatedNotesFilter | null;
|
||||
currentNoteId?: string;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onSelect: (noteId: string) => void;
|
||||
}) {
|
||||
const [search, setSearch] = useState("");
|
||||
const debouncedSearch = useDebounced(search.trim());
|
||||
const [page, setPage] = useState(0);
|
||||
|
||||
// New chip or new search term → back to the first page.
|
||||
useEffect(() => {
|
||||
setPage(0);
|
||||
}, [filter?.kind, filter?.value, debouncedSearch]);
|
||||
// Reset the search box whenever a different chip is opened.
|
||||
useEffect(() => {
|
||||
setSearch("");
|
||||
}, [filter?.kind, filter?.value]);
|
||||
|
||||
const params = {
|
||||
...(filter?.kind === "tag" ? { tag: filter.value } : {}),
|
||||
...(filter?.kind === "entity" ? { entity: filter.value } : {}),
|
||||
keyword: debouncedSearch || undefined,
|
||||
limit: filter ? PAGE_SIZE : 0,
|
||||
offset: page * PAGE_SIZE,
|
||||
};
|
||||
|
||||
const { data, isLoading, isFetching } = useKnowledgeNotes(params);
|
||||
const items = (data?.items ?? []).filter(
|
||||
(n: KnowledgeNote) => n.id !== currentNoteId,
|
||||
);
|
||||
const total = data?.total ?? 0;
|
||||
const pageCount = Math.max(1, Math.ceil(total / PAGE_SIZE));
|
||||
|
||||
return (
|
||||
<Dialog open={!!filter} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
{filter?.kind === "entity" ? (
|
||||
<Sparkles className="size-4 text-violet-500" />
|
||||
) : (
|
||||
<Hash className="size-4 text-rose-500" />
|
||||
)}
|
||||
<span className="truncate">{filter?.value}</span>
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{filter?.kind === "entity"
|
||||
? "提到该实体的关联知识"
|
||||
: "使用该标签的关联知识"}
|
||||
{total > 0 ? ` · 共 ${total} 条` : ""}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="relative">
|
||||
<Search className="text-muted-foreground pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2" />
|
||||
<Input
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="在关联知识中搜索标题/内容..."
|
||||
className="h-9 pl-8"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ScrollArea className="max-h-[50vh]">
|
||||
{isLoading || (isFetching && items.length === 0) ? (
|
||||
<div className="text-muted-foreground flex items-center gap-2 p-4 text-sm">
|
||||
<Loader2 className="size-4 animate-spin" /> 加载中...
|
||||
</div>
|
||||
) : items.length === 0 ? (
|
||||
<div className="text-muted-foreground rounded-md border border-dashed p-6 text-center text-sm">
|
||||
{debouncedSearch ? "没有匹配的关联知识。" : "暂无其他关联知识。"}
|
||||
</div>
|
||||
) : (
|
||||
<ul className="flex flex-col gap-1 pr-2">
|
||||
{items.map((note) => (
|
||||
<li key={note.id}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onSelect(note.id)}
|
||||
className="flex w-full flex-col gap-0.5 rounded-md border border-transparent px-3 py-2 text-left transition-colors hover:border-slate-200 hover:bg-slate-50 dark:hover:border-slate-700 dark:hover:bg-slate-800/60"
|
||||
>
|
||||
<span className="flex items-center gap-2 text-sm font-medium text-slate-800 dark:text-slate-100">
|
||||
<FileText className="size-3.5 shrink-0 text-slate-400" />
|
||||
<span className="truncate">{note.title}</span>
|
||||
</span>
|
||||
{note.summary ? (
|
||||
<span className="line-clamp-2 pl-[1.375rem] text-xs text-slate-500 dark:text-slate-400">
|
||||
{note.summary}
|
||||
</span>
|
||||
) : null}
|
||||
<span className="text-muted-foreground pl-[1.375rem] text-[11px]">
|
||||
{SOURCE_TYPE_LABELS[note.source_type] ?? note.source_type}
|
||||
{note.updated_at
|
||||
? ` · ${formatDateTime(note.updated_at).slice(0, 10)}`
|
||||
: ""}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</ScrollArea>
|
||||
|
||||
{pageCount > 1 ? (
|
||||
<div className="flex items-center justify-between border-t pt-3">
|
||||
<span className="text-muted-foreground text-xs">
|
||||
第 {page + 1} / {pageCount} 页
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={page === 0 || isFetching}
|
||||
onClick={() => setPage((p) => Math.max(0, p - 1))}
|
||||
>
|
||||
<ChevronLeft className="size-4" /> 上一页
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={page >= pageCount - 1 || isFetching}
|
||||
onClick={() => setPage((p) => Math.min(pageCount - 1, p + 1))}
|
||||
>
|
||||
下一页 <ChevronRight className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -25,6 +25,10 @@ import { DocumentToolbar } from "./DocumentToolbar";
|
||||
import { FloatingToc } from "./FloatingToc";
|
||||
import { MarkdownViewer } from "./MarkdownViewer";
|
||||
import { RelatedDocs } from "./RelatedDocs";
|
||||
import {
|
||||
RelatedNotesDialog,
|
||||
type RelatedNotesFilter,
|
||||
} from "./RelatedNotesDialog";
|
||||
import {
|
||||
SOURCE_TYPE_LABELS,
|
||||
STATUS_LABELS,
|
||||
@@ -91,6 +95,10 @@ export function WikiContent({
|
||||
const [draftContent, setDraftContent] = useState(note.content_md);
|
||||
const [draftStatus, setDraftStatus] = useState<string>(note.status);
|
||||
const [activeHeadingId, setActiveHeadingId] = useState<string | null>(null);
|
||||
// Tag / entity chip clicked → show notes that share it.
|
||||
const [relatedFilter, setRelatedFilter] = useState<RelatedNotesFilter | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
// Pull the backend-injected `## Related` wikilinks out of the body so they
|
||||
// render as a structured module; editing still works on the full source.
|
||||
@@ -270,12 +278,15 @@ export function WikiContent({
|
||||
<MetaTag>创建:{formatDateTime(note.created_at).slice(0, 10)}</MetaTag>
|
||||
) : null}
|
||||
{note.tags.map((tag) => (
|
||||
<span
|
||||
<button
|
||||
key={tag}
|
||||
className="inline-flex h-6 items-center rounded-md bg-rose-50 px-2 text-xs font-medium text-rose-500 dark:bg-rose-500/10 dark:text-rose-300"
|
||||
type="button"
|
||||
title={`查看「${tag}」的关联知识`}
|
||||
onClick={() => setRelatedFilter({ kind: "tag", value: tag })}
|
||||
className="inline-flex h-6 cursor-pointer items-center rounded-md bg-rose-50 px-2 text-xs font-medium text-rose-500 transition-colors hover:bg-rose-100 hover:text-rose-600 dark:bg-rose-500/10 dark:text-rose-300 dark:hover:bg-rose-500/20"
|
||||
>
|
||||
#{tag}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -287,11 +298,15 @@ export function WikiContent({
|
||||
{note.entities.map((ent) => {
|
||||
const meta = entityMeta(ent.entity_type);
|
||||
return (
|
||||
<span
|
||||
<button
|
||||
key={`${ent.name}-${ent.entity_type ?? ""}`}
|
||||
title={meta.label}
|
||||
type="button"
|
||||
title={`查看与「${ent.name}」(${meta.label})相关的知识`}
|
||||
onClick={() =>
|
||||
setRelatedFilter({ kind: "entity", value: ent.name })
|
||||
}
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 rounded-full border py-1 pl-2 pr-1 text-xs font-medium",
|
||||
"inline-flex cursor-pointer items-center gap-1.5 rounded-full border py-1 pl-2 pr-1 text-xs font-medium transition-opacity hover:opacity-80",
|
||||
meta.className,
|
||||
)}
|
||||
>
|
||||
@@ -300,7 +315,7 @@ export function WikiContent({
|
||||
<span className="rounded-full bg-current/15 px-1.5 py-0.5 text-[10px] leading-none opacity-90">
|
||||
{meta.label}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
@@ -373,6 +388,18 @@ export function WikiContent({
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<RelatedNotesDialog
|
||||
filter={relatedFilter}
|
||||
currentNoteId={note.id}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setRelatedFilter(null);
|
||||
}}
|
||||
onSelect={(id) => {
|
||||
setRelatedFilter(null);
|
||||
navigate(`/page/workspace/knowledge/${id}`);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import {
|
||||
BookOpen,
|
||||
Copy,
|
||||
Menu,
|
||||
Network,
|
||||
@@ -41,7 +40,7 @@ function HeaderButton({
|
||||
);
|
||||
}
|
||||
|
||||
/** Light 56px wiki header: logo + product name on the left, action entries on the right. */
|
||||
/** Light 56px wiki header: plain page title on the left, action entries on the right. */
|
||||
export function WikiHeader({
|
||||
onToggleSidebar,
|
||||
onImportFile,
|
||||
@@ -68,14 +67,8 @@ export function WikiHeader({
|
||||
>
|
||||
<Menu className="size-5" />
|
||||
</button>
|
||||
<div className="flex size-9 items-center justify-center rounded-[9px] bg-red-600 text-white">
|
||||
<BookOpen className="size-5" />
|
||||
</div>
|
||||
<div className="leading-none">
|
||||
<div className="text-base font-extrabold tracking-tight text-slate-900 dark:text-slate-100">
|
||||
问答梳理
|
||||
</div>
|
||||
<div className="mt-1 text-xs text-emerald-500">LLM Wiki · 问答梳理中心</div>
|
||||
<div className="text-base font-semibold tracking-tight text-slate-900 dark:text-slate-100">
|
||||
问答梳理
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import {
|
||||
BotIcon,
|
||||
CopyIcon,
|
||||
EyeOffIcon,
|
||||
GlobeIcon,
|
||||
LockIcon,
|
||||
MessageSquareIcon,
|
||||
@@ -529,7 +530,7 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
||||
来自他人
|
||||
</Badge>
|
||||
)}
|
||||
{isOwned && agent.published && !agent.is_private && (
|
||||
{(isOwned || isAdmin) && !isBuiltin && agent.published && !agent.is_private && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="border-sky-500/30 text-sky-700 dark:text-sky-300 text-xs"
|
||||
@@ -539,6 +540,16 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
||||
已发布
|
||||
</Badge>
|
||||
)}
|
||||
{(isOwned || isAdmin) && !isBuiltin && !agent.published && !agent.is_private && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="border-zinc-400/40 text-zinc-500 dark:text-zinc-400 text-xs"
|
||||
title="该智能体尚未发布,仅所有者可见"
|
||||
>
|
||||
<EyeOffIcon className="size-3" />
|
||||
未发布
|
||||
</Badge>
|
||||
)}
|
||||
{agent.is_private && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
|
||||
@@ -15,11 +15,12 @@ import {
|
||||
SparklesIcon,
|
||||
SquarePenIcon,
|
||||
Trash2Icon,
|
||||
UploadCloudIcon,
|
||||
UserRoundIcon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useMemo, useState, type ReactNode } from "react";
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
@@ -42,6 +43,7 @@ import {
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { AgentQuestionEditor } from "@/components/workspace/agents/agent-question-editor";
|
||||
import { useArtifactsOptional } from "@/components/workspace/artifacts";
|
||||
import { EnabledSkillList } from "@/components/workspace/agents/enabled-skill-list";
|
||||
import { SkillPickerSheet } from "@/components/workspace/agents/skill-picker-sheet";
|
||||
import { PublishSquarePickerDialog } from "@/components/workspace/publish-square-picker-dialog";
|
||||
@@ -57,33 +59,12 @@ import {
|
||||
type UpdateAgentRequest,
|
||||
} from "@/core/agents";
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
import { isAgentSkillCandidate } from "@/core/skills";
|
||||
import { useSkills } from "@/core/skills/hooks";
|
||||
import { usePublishSquares } from "@/core/system-settings/hooks";
|
||||
import { desensitize } from "@/lib/desensitize";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/**
|
||||
* Turn the admin-authored SOUL.md markdown into a clean, readable profile blurb
|
||||
* for the narrow panel. The view mode is a profile card, not a document view —
|
||||
* so we strip markdown syntax (headings, emphasis, inline code, list bullets,
|
||||
* blockquotes) rather than rendering it, keeping the line structure intact.
|
||||
*/
|
||||
function cleanProfileText(raw: string): string {
|
||||
return raw
|
||||
.split("\n")
|
||||
.map((line) =>
|
||||
line
|
||||
.replace(/^\s{0,3}#{1,6}\s*/, "")
|
||||
.replace(/^\s{0,3}>\s?/, "")
|
||||
.replace(/^(\s*)[-*+]\s+/, "$1• ")
|
||||
.replace(/(\*\*|__)(.*?)\1/g, "$2")
|
||||
.replace(/(\*|_)(.*?)\1/g, "$2")
|
||||
.replace(/`([^`]+)`/g, "$1"),
|
||||
)
|
||||
.join("\n")
|
||||
.replace(/\n{3,}/g, "\n\n")
|
||||
.trim();
|
||||
}
|
||||
|
||||
/** Local edit-mode draft — committed in one `updateAgent` call on 保存. */
|
||||
interface AgentDraft {
|
||||
@@ -94,6 +75,7 @@ interface AgentDraft {
|
||||
skills: string[];
|
||||
published: boolean;
|
||||
featured: boolean;
|
||||
templateName: string;
|
||||
}
|
||||
|
||||
function draftFromAgent(agent: Agent): AgentDraft {
|
||||
@@ -105,6 +87,7 @@ function draftFromAgent(agent: Agent): AgentDraft {
|
||||
skills: agent.skills ?? [],
|
||||
published: agent.published,
|
||||
featured: agent.featured_order != null,
|
||||
templateName: agent.template_name ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -176,18 +159,22 @@ export function AgentDetailPanel({
|
||||
const setFeatured = useSetAgentFeatured();
|
||||
const { data: publishSquares } = usePublishSquares();
|
||||
const { skills, isLoading: isSkillsLoading } = useSkills();
|
||||
// Same pool the edit dialog offers: only globally enabled skills are
|
||||
// whitelist candidates.
|
||||
const enabledPool = useMemo(
|
||||
() => skills.filter((skill) => skill.enabled),
|
||||
[skills],
|
||||
);
|
||||
|
||||
// Permission model mirrors agent-card: admins manage the full catalog,
|
||||
// owners manage their own agents, everyone else is read-only.
|
||||
const storedAuth = useMemo(() => getStoredAuth(), []);
|
||||
const currentUserId = storedAuth?.user_id ?? null;
|
||||
const isAdmin = storedAuth?.system_role === "admin";
|
||||
|
||||
// 可配置的技能限定为「内置 + 自己的 + 已发布到广场的」,
|
||||
// 其他用户未发布的自定义技能不可选(管理员例外)。
|
||||
const enabledPool = useMemo(
|
||||
() =>
|
||||
skills.filter((skill) =>
|
||||
isAgentSkillCandidate(skill, currentUserId, isAdmin),
|
||||
),
|
||||
[skills, currentUserId, isAdmin],
|
||||
);
|
||||
const isOwned =
|
||||
!!agent &&
|
||||
!agent.builtin &&
|
||||
@@ -199,14 +186,30 @@ export function AgentDetailPanel({
|
||||
|
||||
const isSaving = updateAgent.isPending || setFeatured.isPending;
|
||||
|
||||
// 对话生成文件(md/txt 等 artifact)并在右侧展开预览时,自动收起智能体
|
||||
// 信息面板给预览让位;新文件落地时同样收起。编辑中不打断用户,用户随时
|
||||
// 可手动重新展开。
|
||||
const artifactsCtx = useArtifactsOptional();
|
||||
const artifactCount = artifactsCtx?.artifacts.length ?? 0;
|
||||
const artifactPanelVisible = !!artifactsCtx?.open && artifactCount > 0;
|
||||
const prevArtifactPanelVisible = useRef(false);
|
||||
const prevArtifactCount = useRef(0);
|
||||
useEffect(() => {
|
||||
const opened = artifactPanelVisible && !prevArtifactPanelVisible.current;
|
||||
const grew =
|
||||
artifactPanelVisible && artifactCount > prevArtifactCount.current;
|
||||
prevArtifactPanelVisible.current = artifactPanelVisible;
|
||||
prevArtifactCount.current = artifactCount;
|
||||
if ((opened || grew) && !editing) {
|
||||
setCollapsed(true);
|
||||
}
|
||||
}, [artifactPanelVisible, artifactCount, editing]);
|
||||
|
||||
const displayName = desensitize(agent?.name ?? agentName);
|
||||
const questions = useMemo(
|
||||
() => normalizeAgentQuestions(agent?.common_questions),
|
||||
[agent?.common_questions],
|
||||
);
|
||||
const soulPreview = agent?.soul?.trim()
|
||||
? cleanProfileText(desensitize(agent.soul))
|
||||
: undefined;
|
||||
|
||||
function beginEdit() {
|
||||
if (!agent || !canEdit) return;
|
||||
@@ -280,6 +283,8 @@ export function AgentDetailPanel({
|
||||
if (draft.description !== (agent.description ?? ""))
|
||||
request.description = draft.description;
|
||||
if (draft.soul !== (agent.soul ?? "")) request.soul = draft.soul;
|
||||
if (draft.templateName.trim() !== (agent.template_name ?? ""))
|
||||
request.template_name = draft.templateName.trim();
|
||||
if (nextPublished !== agent.published) request.published = nextPublished;
|
||||
if (JSON.stringify(draft.skills) !== JSON.stringify(agent.skills ?? []))
|
||||
request.skills = draft.skills;
|
||||
@@ -422,14 +427,7 @@ export function AgentDetailPanel({
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="hidden"
|
||||
onClick={beginEdit}
|
||||
aria-hidden="true"
|
||||
tabIndex={-1}
|
||||
>
|
||||
<Button size="sm" variant="outline" onClick={beginEdit}>
|
||||
<SquarePenIcon className="size-3.5" />
|
||||
编辑
|
||||
</Button>
|
||||
@@ -528,9 +526,31 @@ export function AgentDetailPanel({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 入库模板名 — view mode shows a hint row when configured. */}
|
||||
{!editing && agent.template_name?.trim() && (
|
||||
<div className="text-muted-foreground mt-2 flex items-center gap-1 text-xs">
|
||||
<UploadCloudIcon className="size-3 shrink-0" />
|
||||
入库模板:{desensitize(agent.template_name)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Publish / featured toggles — only meaningful in edit mode. */}
|
||||
{editing && draft && (
|
||||
<div className="mt-3 space-y-2">
|
||||
<div className="bg-background/60 space-y-1 rounded-lg border px-3 py-2">
|
||||
<p className="text-sm font-medium">入库模板名</p>
|
||||
<Input
|
||||
value={draft.templateName}
|
||||
onChange={(e) =>
|
||||
setDraft({ ...draft, templateName: e.currentTarget.value })
|
||||
}
|
||||
placeholder="例如:临时策略库(留空表示不支持入库)"
|
||||
className="h-8 text-sm"
|
||||
/>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
配置后,对话生成的 Markdown 文件可一键发布到知识入库接口。
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-background/60 flex items-center justify-between rounded-lg border px-3 py-2">
|
||||
<div>
|
||||
<p className="text-sm font-medium">公开发布</p>
|
||||
@@ -564,41 +584,31 @@ export function AgentDetailPanel({
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* ── SOUL / 人设 ────────────────────────────────────────────────── */}
|
||||
{(editing || soulPreview) && (
|
||||
<Section
|
||||
icon={<SparklesIcon className="size-3.5" />}
|
||||
title="人设(SOUL)"
|
||||
>
|
||||
{editing && draft ? (
|
||||
<Textarea
|
||||
value={draft.soul}
|
||||
onChange={(e) =>
|
||||
setDraft({ ...draft, soul: e.currentTarget.value })
|
||||
}
|
||||
placeholder="输入 SOUL.md 内容"
|
||||
className="max-h-[45vh] min-h-48 resize-y font-mono text-xs"
|
||||
/>
|
||||
) : (
|
||||
// Viewport-relative cap: the SOUL preview expands with the screen
|
||||
// (taller than the old fixed 240px box) but never swallows the
|
||||
// whole panel — long content still scrolls inside.
|
||||
<p className="text-muted-foreground max-h-[40vh] overflow-y-auto whitespace-pre-wrap text-sm leading-relaxed">
|
||||
{soulPreview}
|
||||
</p>
|
||||
)}
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{/* ── 常用问题 ───────────────────────────────────────────────────── */}
|
||||
{(editing || questions.length > 0) && (
|
||||
{(editing || questions.length > 0 || canEdit) && (
|
||||
<Section
|
||||
icon={<MessageCircleQuestionIcon className="size-3.5" />}
|
||||
title="常用问题"
|
||||
extra={
|
||||
<span className="text-muted-foreground text-xs tabular-nums">
|
||||
{(editing && draft ? draft.questions : questions).length} 个
|
||||
</span>
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-muted-foreground text-xs tabular-nums">
|
||||
{(editing && draft ? draft.questions : questions).length} 个
|
||||
</span>
|
||||
{!editing && canEdit && (
|
||||
<Tooltip content="管理常用问题(新增 / 删除 / 排序)">
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
onClick={beginEdit}
|
||||
aria-label="管理常用问题"
|
||||
>
|
||||
<SquarePenIcon className="size-3.5" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{editing && draft ? (
|
||||
@@ -607,6 +617,15 @@ export function AgentDetailPanel({
|
||||
onChange={(next) => setDraft({ ...draft, questions: next })}
|
||||
disabled={isSaving}
|
||||
/>
|
||||
) : questions.length === 0 ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={beginEdit}
|
||||
className="text-muted-foreground hover:text-foreground hover:border-border w-full rounded-lg border border-dashed px-3 py-4 text-center text-xs transition-colors"
|
||||
>
|
||||
<PlusIcon className="mr-1 inline size-3.5 align-[-2px]" />
|
||||
添加常用问题
|
||||
</button>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{questions.map((question, index) => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { ArrowDownUpIcon, BotIcon, LockIcon, PlusIcon, ShieldIcon, XIcon } from "lucide-react";
|
||||
import { ArrowDownUpIcon, BotIcon, Loader2, LockIcon, PlusIcon, ShieldIcon, XIcon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
@@ -190,16 +190,21 @@ export function AgentGallery() {
|
||||
list: Agent[];
|
||||
total: number;
|
||||
isLoading: boolean;
|
||||
isFetching: boolean;
|
||||
tab: string;
|
||||
emptyDescription: string;
|
||||
showNewButton?: boolean;
|
||||
}) => {
|
||||
const { list, total, isLoading, tab, emptyDescription, showNewButton } = opts;
|
||||
const { list, total, isLoading, isFetching, tab, emptyDescription, showNewButton } =
|
||||
opts;
|
||||
// keepPreviousData keeps the old page visible while a new page loads, so
|
||||
// only show the spinner on the very first load (no rows yet).
|
||||
if (isLoading && list.length === 0) {
|
||||
// this full-height spinner only covers the very first load (no rows yet),
|
||||
// or a filter change while the previous result was already empty (where
|
||||
// isLoading stays false but there is nothing to keep on screen).
|
||||
if ((isLoading || isFetching) && list.length === 0) {
|
||||
return (
|
||||
<div className="text-muted-foreground flex h-40 items-center justify-center text-sm">
|
||||
<div className="text-muted-foreground flex h-40 items-center justify-center gap-2 text-sm">
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
{t.common.loading}
|
||||
</div>
|
||||
);
|
||||
@@ -208,8 +213,29 @@ export function AgentGallery() {
|
||||
return renderEmpty(emptyDescription, showNewButton);
|
||||
}
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{renderGrid(list)}
|
||||
<div className="relative flex flex-col gap-4">
|
||||
{/* While a server-side search/tag/page query is in flight the stale
|
||||
keepPreviousData rows stay mounted — dim them and float a spinner
|
||||
on top so a slow backend query never looks like the filter was
|
||||
ignored, and block clicks on results that are about to change. */}
|
||||
<div
|
||||
className={
|
||||
isFetching
|
||||
? "pointer-events-none opacity-40 transition-opacity duration-200"
|
||||
: "transition-opacity duration-200"
|
||||
}
|
||||
aria-busy={isFetching}
|
||||
>
|
||||
{renderGrid(list)}
|
||||
</div>
|
||||
{isFetching && (
|
||||
<div className="absolute inset-0 z-10 flex items-start justify-center pt-24">
|
||||
<div className="bg-background/90 text-muted-foreground flex items-center gap-2 rounded-full border px-4 py-2 text-sm shadow-sm">
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
正在查询…
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<Pagination
|
||||
page={pages[tab] ?? 1}
|
||||
pageSize={PAGE_SIZE}
|
||||
@@ -315,6 +341,7 @@ export function AgentGallery() {
|
||||
list: privateAgents,
|
||||
total: privateTotal,
|
||||
isLoading: isPrivateLoading,
|
||||
isFetching: isPrivateFetching,
|
||||
tab: "private",
|
||||
emptyDescription: "私密广场暂时还没有智能体。",
|
||||
});
|
||||
@@ -444,6 +471,7 @@ export function AgentGallery() {
|
||||
list: mainAgents,
|
||||
total: mainTotal,
|
||||
isLoading: mainLoading,
|
||||
isFetching: mainFetching,
|
||||
tab: sq.id,
|
||||
emptyDescription: `「${sq.name}」广场暂时还没有智能体。`,
|
||||
})}
|
||||
@@ -455,6 +483,7 @@ export function AgentGallery() {
|
||||
list: mainAgents,
|
||||
total: mainTotal,
|
||||
isLoading: mainLoading,
|
||||
isFetching: mainFetching,
|
||||
tab: "mine",
|
||||
emptyDescription: t.agents.emptyDescription,
|
||||
showNewButton: true,
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
"use client";
|
||||
|
||||
import { ArrowRightIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
|
||||
import type { AgentQuestion } from "@/core/agents";
|
||||
import { desensitize } from "@/lib/desensitize";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/** Chips shown before the rest folds behind the 更多问题 toggle. */
|
||||
const VISIBLE_COUNT = 4;
|
||||
|
||||
/**
|
||||
* 常用问题 prompt chips on the agent chat landing screen — light-gray
|
||||
* borderless pills stacked left-aligned between the welcome hero and the
|
||||
* input box. Clicking a chip sends the question's full prompt through the
|
||||
* page's existing submit flow. Lists longer than {@link VISIBLE_COUNT} fold
|
||||
* behind a 更多问题 toggle; an empty list renders nothing.
|
||||
*/
|
||||
export function AgentQuestionChips({
|
||||
questions,
|
||||
onAsk,
|
||||
disabled,
|
||||
className,
|
||||
}: {
|
||||
questions: AgentQuestion[];
|
||||
onAsk: (prompt: string) => void;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
}) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
|
||||
if (questions.length === 0) return null;
|
||||
|
||||
const visible = expanded ? questions : questions.slice(0, VISIBLE_COUNT);
|
||||
const foldedCount = questions.length - VISIBLE_COUNT;
|
||||
|
||||
return (
|
||||
<div className={cn("flex flex-col items-start gap-2 px-1", className)}>
|
||||
{visible.map((question, index) => (
|
||||
<button
|
||||
key={index}
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
onClick={() => onAsk(question.prompt)}
|
||||
title={desensitize(question.prompt)}
|
||||
className={cn(
|
||||
"group bg-muted text-foreground/90 flex max-w-full items-center gap-2 rounded-full px-4 py-2.5 text-left text-sm leading-5 transition",
|
||||
"hover:bg-accent active:scale-[0.98]",
|
||||
"disabled:cursor-not-allowed disabled:opacity-50",
|
||||
)}
|
||||
>
|
||||
<span className="min-w-0 truncate">{desensitize(question.title)}</span>
|
||||
<ArrowRightIcon className="text-muted-foreground size-3.5 shrink-0 transition-transform group-hover:translate-x-0.5" />
|
||||
</button>
|
||||
))}
|
||||
{foldedCount > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setExpanded((v) => !v)}
|
||||
className="text-muted-foreground hover:text-foreground flex items-center gap-1 rounded-full px-4 py-1.5 text-xs transition-colors"
|
||||
>
|
||||
{expanded ? (
|
||||
<>
|
||||
收起
|
||||
<ChevronUpIcon className="size-3.5" />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
更多问题({foldedCount})
|
||||
<ChevronDownIcon className="size-3.5" />
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -12,10 +12,20 @@ import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import type { AgentQuestion } from "@/core/agents";
|
||||
|
||||
/** Soft cap on the chip label length — beyond this the landing chip truncates. */
|
||||
const TITLE_SOFT_LIMIT = 80;
|
||||
|
||||
/** The text a question row would actually persist as (panel save falls back
|
||||
* title↔prompt), used for duplicate detection. */
|
||||
function effectivePrompt(q: AgentQuestion): string {
|
||||
return (q.prompt.trim() || q.title.trim()).toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Editable list of an agent's 常用问题 (recommended questions). Each row has a
|
||||
* short `title` (the chip label) and the full `prompt` sent on click. Supports
|
||||
* add / remove / inline edit / reorder (move up & down). Pure controlled
|
||||
* add / remove / inline edit / reorder (move up & down), with non-blocking
|
||||
* hints for over-long titles and duplicate questions. Pure controlled
|
||||
* component — persistence stays with the caller (edit dialog or detail panel).
|
||||
*/
|
||||
export function AgentQuestionEditor({
|
||||
@@ -52,7 +62,13 @@ export function AgentQuestionEditor({
|
||||
尚未配置常用问题,点击下方按钮添加。
|
||||
</p>
|
||||
)}
|
||||
{value.map((item, index) => (
|
||||
{value.map((item, index) => {
|
||||
const titleLength = item.title.trim().length;
|
||||
const prompt = effectivePrompt(item);
|
||||
const duplicateOf = prompt
|
||||
? value.findIndex((other, i) => i < index && effectivePrompt(other) === prompt)
|
||||
: -1;
|
||||
return (
|
||||
<div key={index} className="bg-background/60 space-y-1.5 rounded-lg border p-2.5">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Input
|
||||
@@ -103,8 +119,19 @@ export function AgentQuestionEditor({
|
||||
onChange={(e) => update(index, { prompt: e.currentTarget.value })}
|
||||
className="min-h-16 resize-none text-sm"
|
||||
/>
|
||||
{titleLength > TITLE_SOFT_LIMIT && (
|
||||
<p className="text-destructive text-xs">
|
||||
标题建议不超过 {TITLE_SOFT_LIMIT} 字(当前 {titleLength} 字),过长会在聊天区被截断。
|
||||
</p>
|
||||
)}
|
||||
{duplicateOf >= 0 && (
|
||||
<p className="text-xs text-amber-600 dark:text-amber-400">
|
||||
与第 {duplicateOf + 1} 条问题内容重复。
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
|
||||
@@ -4,15 +4,16 @@ import {
|
||||
ArrowDownIcon,
|
||||
Code2Icon,
|
||||
CopyIcon,
|
||||
DownloadIcon,
|
||||
EyeIcon,
|
||||
FileType2Icon,
|
||||
LoaderIcon,
|
||||
PackageIcon,
|
||||
SaveIcon,
|
||||
SquareArrowOutUpRightIcon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
DownloadIcon,
|
||||
EyeIcon,
|
||||
FileType2Icon,
|
||||
LoaderIcon,
|
||||
PackageIcon,
|
||||
SaveIcon,
|
||||
UploadCloudIcon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { useParams } from "next/navigation";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { AnchorHTMLAttributes, HTMLAttributes, ReactNode } from "react";
|
||||
import { toast } from "sonner";
|
||||
@@ -35,11 +36,12 @@ import {
|
||||
} from "@/components/ui/select";
|
||||
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
|
||||
import { CodeEditor } from "@/components/workspace/code-editor";
|
||||
import { apiFetch } from "@/core/api";
|
||||
import {
|
||||
downloadArtifactFile,
|
||||
openArtifactInNewTab,
|
||||
} from "@/core/artifacts/download";
|
||||
import { publishArtifactToKnowledge } from "@/core/agents/api";
|
||||
import { useAgent } from "@/core/agents/hooks";
|
||||
import { apiFetch } from "@/core/api";
|
||||
import {
|
||||
downloadArtifactFile,
|
||||
} from "@/core/artifacts/download";
|
||||
import {
|
||||
useArtifactContent,
|
||||
useUpdateArtifactContent,
|
||||
@@ -86,6 +88,13 @@ function extractTextFromChildren(children: ReactNode): string {
|
||||
return "";
|
||||
}
|
||||
|
||||
/** 取 md 标题用于入库:优先文中第一个标题行,否则退回文件名(去扩展名)。 */
|
||||
function extractMarkdownTitle(content: string, filepath: string): string {
|
||||
const heading = /^\s{0,3}#{1,6}\s+(.+?)\s*#*\s*$/m.exec(content);
|
||||
if (heading?.[1]) return heading[1].trim();
|
||||
return getFileName(filepath).replace(/\.(md|markdown)$/i, "");
|
||||
}
|
||||
|
||||
function findScrollableArtifactElement(root: HTMLElement | null) {
|
||||
if (!root) {
|
||||
return null;
|
||||
@@ -439,6 +448,50 @@ export function ArtifactFileDetail({
|
||||
updateArtifact,
|
||||
]);
|
||||
|
||||
// 发布入库:仅当当前路由是智能体会话(agents/:agent_id/chats/…)且该智能体
|
||||
// 配置了入库模板名(template_name)时,md 产物右上角才出现发布按钮。
|
||||
const { agent_id: routeAgentId } = useParams<{ agent_id?: string }>();
|
||||
const { agent: routeAgent } = useAgent(routeAgentId ?? null);
|
||||
const ingestTemplateName = routeAgent?.template_name?.trim() ?? "";
|
||||
const canPublishToKnowledge =
|
||||
!!routeAgentId &&
|
||||
!!ingestTemplateName &&
|
||||
language === "markdown" &&
|
||||
!isSkillFile &&
|
||||
!isMock;
|
||||
const [isPublishingToKnowledge, setIsPublishingToKnowledge] = useState(false);
|
||||
const handlePublishToKnowledge = useCallback(async () => {
|
||||
if (!routeAgentId || isPublishingToKnowledge) {
|
||||
return;
|
||||
}
|
||||
const source = (displayContent ?? "").trim();
|
||||
if (!source) {
|
||||
toast.error("Markdown 内容为空,无法发布入库");
|
||||
return;
|
||||
}
|
||||
setIsPublishingToKnowledge(true);
|
||||
try {
|
||||
const result = await publishArtifactToKnowledge({
|
||||
agent_id: routeAgentId,
|
||||
title: extractMarkdownTitle(source, filepath),
|
||||
content: source,
|
||||
});
|
||||
if (result.success) {
|
||||
toast.success(`已发布入库:${result.node_name}`);
|
||||
} else {
|
||||
const last = result.attempts[result.attempts.length - 1];
|
||||
toast.error(
|
||||
`发布入库失败:${last?.error ?? last?.response_text ?? "接口返回失败"}`,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to publish artifact to knowledge base:", error);
|
||||
toast.error(error instanceof Error ? error.message : "发布入库失败");
|
||||
} finally {
|
||||
setIsPublishingToKnowledge(false);
|
||||
}
|
||||
}, [displayContent, filepath, isPublishingToKnowledge, routeAgentId]);
|
||||
|
||||
const [isExportingWord, setIsExportingWord] = useState(false);
|
||||
const handleDownloadAsWord = useCallback(async () => {
|
||||
const source = (displayContent ?? "").trim();
|
||||
@@ -459,32 +512,7 @@ export function ArtifactFileDetail({
|
||||
}
|
||||
}, [displayContent, filepath]);
|
||||
|
||||
const handleOpenWriteFileInNewTab = useCallback(() => {
|
||||
const source = displayContent ?? "";
|
||||
if (!source.trim()) {
|
||||
toast.error("文件内容为空,暂时无法打开");
|
||||
return;
|
||||
}
|
||||
if (language === "mermaid") {
|
||||
void openMermaidSvgInNewTab(source).catch((error) => {
|
||||
console.error("Failed to open mermaid artifact:", error);
|
||||
toast.error(error instanceof Error ? error.message : "Failed to open artifact");
|
||||
});
|
||||
return;
|
||||
}
|
||||
const blobType =
|
||||
language === "html"
|
||||
? "text/html;charset=utf-8"
|
||||
: language === "markdown"
|
||||
? "text/markdown;charset=utf-8"
|
||||
: "text/plain;charset=utf-8";
|
||||
const blob = new Blob([source], { type: blobType });
|
||||
const url = URL.createObjectURL(blob);
|
||||
window.open(url, "_blank", "noopener,noreferrer");
|
||||
window.setTimeout(() => URL.revokeObjectURL(url), 60_000);
|
||||
}, [displayContent, language]);
|
||||
|
||||
const handleDownloadWriteFile = useCallback(() => {
|
||||
const handleDownloadWriteFile = useCallback(() => {
|
||||
const source = displayContent ?? "";
|
||||
if (!source.trim()) {
|
||||
toast.error("文件内容为空,暂时无法下载");
|
||||
@@ -516,7 +544,7 @@ export function ArtifactFileDetail({
|
||||
|
||||
return (
|
||||
<Artifact className={cn(className)}>
|
||||
<ArtifactHeader className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-3 px-4 py-3">
|
||||
<ArtifactHeader className="flex flex-wrap items-center gap-3 px-4 py-3">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<div className="bg-muted/65 inline-flex min-w-0 items-center rounded-full border border-black/6 p-1 shadow-sm dark:border-white/8">
|
||||
<span className="bg-background text-muted-foreground inline-flex h-7 shrink-0 items-center rounded-full border border-black/6 px-2.5 text-[10px] font-semibold tracking-[0.16em] dark:border-white/8">
|
||||
@@ -546,7 +574,7 @@ export function ArtifactFileDetail({
|
||||
</ArtifactTitle>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-center">
|
||||
<div className="flex w-full items-center justify-center md:w-auto md:flex-1">
|
||||
{isSupportPreview && (
|
||||
<div className="flex items-center gap-2">
|
||||
<ToggleGroup
|
||||
@@ -589,8 +617,17 @@ export function ArtifactFileDetail({
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<ArtifactActions className="bg-muted/45 rounded-full border border-black/6 p-1 dark:border-white/8">
|
||||
<div className="flex w-full items-center justify-end gap-2 md:ml-auto md:w-auto">
|
||||
<ArtifactActions className="bg-muted/45 max-w-full flex-wrap justify-end rounded-3xl border border-black/6 p-1 dark:border-white/8">
|
||||
{canPublishToKnowledge && (
|
||||
<ArtifactAction
|
||||
icon={isPublishingToKnowledge ? LoaderIcon : UploadCloudIcon}
|
||||
label="发布入库"
|
||||
tooltip={`发布到知识库(模板:${ingestTemplateName})`}
|
||||
disabled={isPublishingToKnowledge || !displayContent}
|
||||
onClick={() => void handlePublishToKnowledge()}
|
||||
/>
|
||||
)}
|
||||
{canEditArtifact && (
|
||||
<ArtifactAction
|
||||
icon={updateArtifact.isPending ? LoaderIcon : SaveIcon}
|
||||
@@ -614,45 +651,6 @@ export function ArtifactFileDetail({
|
||||
/>
|
||||
</Tooltip>
|
||||
)}
|
||||
<ArtifactAction
|
||||
icon={SquareArrowOutUpRightIcon}
|
||||
label={t.common.openInNewWindow}
|
||||
tooltip={t.common.openInNewWindow}
|
||||
onClick={async () => {
|
||||
if (useWriteFileStreaming) {
|
||||
handleOpenWriteFileInNewTab();
|
||||
return;
|
||||
}
|
||||
if (language === "mermaid") {
|
||||
try {
|
||||
await openMermaidSvgInNewTab(displayContent ?? "");
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
toast.error(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Failed to open artifact",
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await openArtifactInNewTab({
|
||||
filepath,
|
||||
threadId,
|
||||
isMock,
|
||||
publicShareCode,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
toast.error(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Failed to open artifact",
|
||||
);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{isCodeFile && (
|
||||
<ArtifactAction
|
||||
icon={CopyIcon}
|
||||
|
||||
@@ -1,44 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import { Database } from "lucide-react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useThreadSettings } from "@/core/settings";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { Tooltip } from "./tooltip";
|
||||
|
||||
/**
|
||||
* Per-conversation toggle for knowledge-base RAG injection (phase 2).
|
||||
*
|
||||
* Writes ``context.knowledge_rag_enabled`` into the thread settings, which the
|
||||
* run forwards as ``runtime.context`` so ``KnowledgeRagMiddleware`` injects
|
||||
* recalled knowledge before each model call for this conversation only.
|
||||
*/
|
||||
export function KnowledgeRagToggle({ threadId }: { threadId: string }) {
|
||||
const [settings, setSettings] = useThreadSettings(threadId);
|
||||
const enabled = settings.context.knowledge_rag_enabled === true;
|
||||
|
||||
const toggle = () => {
|
||||
setSettings("context", {
|
||||
...settings.context,
|
||||
knowledge_rag_enabled: !enabled,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Tooltip content={enabled ? "知识库召回:已开启" : "知识库召回:已关闭"}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={toggle}
|
||||
className={cn(
|
||||
"text-muted-foreground hover:text-foreground",
|
||||
enabled && "text-primary hover:text-primary",
|
||||
)}
|
||||
>
|
||||
<Database />
|
||||
知识库
|
||||
</Button>
|
||||
</Tooltip>
|
||||
);
|
||||
export function KnowledgeRagToggle({
|
||||
className: _className,
|
||||
}: {
|
||||
className?: string;
|
||||
}) {
|
||||
void _className;
|
||||
return null;
|
||||
}
|
||||
@@ -129,6 +129,7 @@ function useArtifactResolver(threadId: string): (path: string) => string {
|
||||
export function MessageListItem({
|
||||
className,
|
||||
fitRowToContent = false,
|
||||
anchorId,
|
||||
message,
|
||||
isLoading,
|
||||
threadId,
|
||||
@@ -140,6 +141,11 @@ export function MessageListItem({
|
||||
}: {
|
||||
className?: string;
|
||||
fitRowToContent?: boolean;
|
||||
/**
|
||||
* Stable DOM id so the question navigator can scrollIntoView to this
|
||||
* message. `scroll-mt` keeps the target clear of the overlay header.
|
||||
*/
|
||||
anchorId?: string;
|
||||
message: Message;
|
||||
isLoading?: boolean;
|
||||
threadId: string;
|
||||
@@ -156,10 +162,12 @@ export function MessageListItem({
|
||||
'';
|
||||
return (
|
||||
<AIElementMessage
|
||||
id={anchorId}
|
||||
className={cn(
|
||||
'group/conversation-message relative',
|
||||
fitRowToContent ? 'max-w-full w-fit' : 'w-full',
|
||||
isHuman && fitRowToContent && 'ml-auto',
|
||||
anchorId && 'scroll-mt-20',
|
||||
className,
|
||||
)}
|
||||
from={isHuman ? 'user' : 'assistant'}
|
||||
|
||||
@@ -35,6 +35,7 @@ import { cn } from "@/lib/utils";
|
||||
import { resolveAllowMultiple } from "@/roundtable-planning/lib/clarification";
|
||||
|
||||
import { ArtifactFileList } from "../artifacts/artifact-file-list";
|
||||
import { getQuestionAnchorId } from "../question-navigator";
|
||||
import { StreamingIndicator } from "../streaming-indicator";
|
||||
|
||||
import { ReferenceBatchesContext, ThreadContext } from "./context";
|
||||
@@ -297,6 +298,11 @@ export function MessageList({
|
||||
<MessageListItem
|
||||
key={`${group.id}/${msg.id}`}
|
||||
fitRowToContent={fitMessageRowsToContent}
|
||||
anchorId={
|
||||
msg.type === "human"
|
||||
? getQuestionAnchorId(msg, messages.indexOf(msg))
|
||||
: undefined
|
||||
}
|
||||
message={msg}
|
||||
isLoading={thread.isLoading}
|
||||
threadId={threadId}
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
"use client";
|
||||
|
||||
import type { Message } from "@langchain/langgraph-sdk";
|
||||
import { ChevronsRightIcon, ListIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet";
|
||||
import {
|
||||
extractContentFromMessage,
|
||||
stripArtifactTag,
|
||||
stripUploadedFilesTag,
|
||||
} from "@/core/messages/utils";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { Tooltip } from "./tooltip";
|
||||
|
||||
/** Width of the expanded floating panel, in px. */
|
||||
const PANEL_WIDTH = 300;
|
||||
/** Minimum side gutter (beyond the panel itself) required to float the panel. */
|
||||
const PANEL_GUTTER_MARGIN = 24;
|
||||
/** Max characters kept in a question summary card. */
|
||||
const SUMMARY_MAX_LENGTH = 80;
|
||||
/** Questions needed before the navigator shows up at all. */
|
||||
const MIN_QUESTIONS = 2;
|
||||
const COLLAPSE_STORAGE_KEY = "deerflow.question-navigator.collapsed";
|
||||
|
||||
/**
|
||||
* Stable DOM anchor id for a message. Prefers the server-side message id and
|
||||
* falls back to the render index so messages without ids still get a target
|
||||
* (requirement: `message-${index}` style fallback).
|
||||
*/
|
||||
export function getQuestionAnchorId(
|
||||
message: Pick<Message, "id">,
|
||||
index: number,
|
||||
): string {
|
||||
return `message-${message.id ?? index}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn the raw markdown of a user question into a short plain-text summary:
|
||||
* strips upload/artifact/page-context envelopes and common Markdown syntax,
|
||||
* collapses whitespace, and truncates with an ellipsis.
|
||||
*/
|
||||
function summarizeQuestion(raw: string): string {
|
||||
let text = stripArtifactTag(stripUploadedFilesTag(raw));
|
||||
text = text
|
||||
.replace(/<page_context>[\s\S]*?<\/page_context>/gi, " ")
|
||||
.replace(/```[\s\S]*?(```|$)/g, " ")
|
||||
.replace(/!\[[^\]]*\]\([^)]*\)/g, " ")
|
||||
.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
|
||||
.replace(/`([^`]*)`/g, "$1")
|
||||
.replace(/^#{1,6}\s+/gm, "")
|
||||
.replace(/^\s*>\s?/gm, "")
|
||||
.replace(/^\s*[-*+]\s+/gm, "")
|
||||
.replace(/^\s*\d+\.\s+/gm, "")
|
||||
.replace(/(\*\*|__|~~)/g, "")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
if (text.length > SUMMARY_MAX_LENGTH) {
|
||||
return `${text.slice(0, SUMMARY_MAX_LENGTH)}…`;
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
type QuestionItem = {
|
||||
anchorId: string;
|
||||
summary: string;
|
||||
};
|
||||
|
||||
/** Walk up from a message anchor to the element that actually scrolls. */
|
||||
function findScrollParent(el: HTMLElement | null): HTMLElement | null {
|
||||
let node = el?.parentElement ?? null;
|
||||
while (node) {
|
||||
const overflowY = window.getComputedStyle(node).overflowY;
|
||||
if (
|
||||
(overflowY === "auto" || overflowY === "scroll") &&
|
||||
node.scrollHeight > node.clientHeight
|
||||
) {
|
||||
return node;
|
||||
}
|
||||
node = node.parentElement;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function readCollapsedPreference(): boolean {
|
||||
if (typeof window === "undefined") return false;
|
||||
try {
|
||||
return window.localStorage.getItem(COLLAPSE_STORAGE_KEY) === "1";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ChatGPT-style question index floating at the right edge of the conversation
|
||||
* column. Reads questions straight from the live `messages` array (no global
|
||||
* state copy), so it stays in sync with streaming, history switches and new
|
||||
* turns for free.
|
||||
*
|
||||
* Layout contract: render inside a `relative` ancestor that spans the chat
|
||||
* content area, and pass the inset via `className` (e.g. `top-16 bottom-48
|
||||
* left-0 right-0`). The component measures its own width: when the side gutter
|
||||
* next to the centered message column is wide enough it floats an expandable
|
||||
* panel there; on narrower viewports it degrades to a small pill button that
|
||||
* opens a right-side drawer, so it never covers the chat body or input box.
|
||||
*/
|
||||
export function QuestionNavigator({
|
||||
messages,
|
||||
className,
|
||||
contentMaxWidth = 1024,
|
||||
}: {
|
||||
messages: Message[];
|
||||
className?: string;
|
||||
/** Max width (px) of the centered message column, used to size the gutter. */
|
||||
contentMaxWidth?: number;
|
||||
}) {
|
||||
const rootRef = useRef<HTMLDivElement | null>(null);
|
||||
const [panelFits, setPanelFits] = useState(false);
|
||||
const [collapsed, setCollapsed] = useState(readCollapsedPreference);
|
||||
const [sheetOpen, setSheetOpen] = useState(false);
|
||||
const [activeId, setActiveId] = useState<string | null>(null);
|
||||
|
||||
const questions = useMemo(() => {
|
||||
const items: QuestionItem[] = [];
|
||||
messages.forEach((message, index) => {
|
||||
if (message.type !== "human") return;
|
||||
const summary = summarizeQuestion(extractContentFromMessage(message));
|
||||
if (!summary) return;
|
||||
items.push({ anchorId: getQuestionAnchorId(message, index), summary });
|
||||
});
|
||||
return items;
|
||||
}, [messages]);
|
||||
|
||||
const visible = questions.length >= MIN_QUESTIONS;
|
||||
|
||||
// Decide between floating panel and drawer mode from the actual gutter width
|
||||
// next to the centered message column — not from the browser viewport — so
|
||||
// opening the artifact preview or the sidebar reflows the mode correctly.
|
||||
useEffect(() => {
|
||||
if (!visible) return;
|
||||
const root = rootRef.current;
|
||||
if (!root) return;
|
||||
const update = () => {
|
||||
const gutter = (root.clientWidth - contentMaxWidth) / 2;
|
||||
setPanelFits(gutter >= PANEL_WIDTH + PANEL_GUTTER_MARGIN);
|
||||
};
|
||||
update();
|
||||
const observer = new ResizeObserver(update);
|
||||
observer.observe(root);
|
||||
return () => observer.disconnect();
|
||||
}, [visible, contentMaxWidth]);
|
||||
|
||||
// Highlight the question nearest the top of the chat viewport. A plain
|
||||
// rAF-throttled scroll listener over a handful of anchors is cheaper and
|
||||
// more predictable here than juggling IntersectionObserver thresholds.
|
||||
useEffect(() => {
|
||||
if (!visible) {
|
||||
setActiveId(null);
|
||||
return;
|
||||
}
|
||||
const firstAnchor = document.getElementById(questions[0]!.anchorId);
|
||||
const scroller = findScrollParent(firstAnchor);
|
||||
if (!scroller) return;
|
||||
|
||||
let raf = 0;
|
||||
const update = () => {
|
||||
raf = 0;
|
||||
const viewportTop = scroller.getBoundingClientRect().top;
|
||||
let current = questions[0]!.anchorId;
|
||||
for (const question of questions) {
|
||||
const el = document.getElementById(question.anchorId);
|
||||
if (!el) continue;
|
||||
if (el.getBoundingClientRect().top - viewportTop <= 140) {
|
||||
current = question.anchorId;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
setActiveId(current);
|
||||
};
|
||||
const onScroll = () => {
|
||||
if (!raf) raf = requestAnimationFrame(update);
|
||||
};
|
||||
update();
|
||||
scroller.addEventListener("scroll", onScroll, { passive: true });
|
||||
return () => {
|
||||
scroller.removeEventListener("scroll", onScroll);
|
||||
if (raf) cancelAnimationFrame(raf);
|
||||
};
|
||||
}, [visible, questions]);
|
||||
|
||||
const scrollToQuestion = useCallback((anchorId: string) => {
|
||||
document
|
||||
.getElementById(anchorId)
|
||||
?.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
setActiveId(anchorId);
|
||||
}, []);
|
||||
|
||||
const toggleCollapsed = useCallback(() => {
|
||||
setCollapsed((prev) => {
|
||||
const next = !prev;
|
||||
try {
|
||||
window.localStorage.setItem(COLLAPSE_STORAGE_KEY, next ? "1" : "0");
|
||||
} catch {
|
||||
// localStorage unavailable (private mode) — keep in-memory state only.
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
if (!visible) return null;
|
||||
|
||||
const pillButton = (label: string, onClick: () => void) => (
|
||||
<Tooltip content={label}>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="bg-background/80 pointer-events-auto h-8 gap-1.5 rounded-full px-3 shadow-md backdrop-blur-md"
|
||||
onClick={onClick}
|
||||
>
|
||||
<ListIcon className="size-3.5" />
|
||||
<span className="text-xs">问题列表</span>
|
||||
<span className="text-muted-foreground text-xs tabular-nums">
|
||||
{questions.length}
|
||||
</span>
|
||||
</Button>
|
||||
</Tooltip>
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={rootRef}
|
||||
className={cn("pointer-events-none absolute z-20", className)}
|
||||
>
|
||||
<div className="absolute inset-y-0 right-3 flex items-start justify-end">
|
||||
{panelFits ? (
|
||||
collapsed ? (
|
||||
pillButton("展开问题导航", toggleCollapsed)
|
||||
) : (
|
||||
<div
|
||||
className="border-border/60 bg-background/85 pointer-events-auto flex max-h-full flex-col overflow-hidden rounded-xl border shadow-lg backdrop-blur-md"
|
||||
style={{ width: PANEL_WIDTH }}
|
||||
>
|
||||
<div className="border-border/50 flex shrink-0 items-center gap-2 border-b px-3 py-2">
|
||||
<Tooltip content="收起问题导航">
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
className="size-6"
|
||||
onClick={toggleCollapsed}
|
||||
>
|
||||
<ChevronsRightIcon className="size-3.5" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<span className="text-xs font-medium">本轮问题</span>
|
||||
<span className="text-muted-foreground ml-auto text-xs tabular-nums">
|
||||
{questions.length}
|
||||
</span>
|
||||
</div>
|
||||
<QuestionCardList
|
||||
questions={questions}
|
||||
activeId={activeId}
|
||||
onSelect={scrollToQuestion}
|
||||
className="min-h-0 flex-1"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
) : (
|
||||
<>
|
||||
{pillButton("打开问题导航", () => setSheetOpen(true))}
|
||||
<Sheet open={sheetOpen} onOpenChange={setSheetOpen}>
|
||||
<SheetContent
|
||||
side="right"
|
||||
className="flex w-[320px] flex-col gap-0 p-0 sm:max-w-[320px]"
|
||||
>
|
||||
<SheetHeader className="border-border/50 border-b px-4 py-3">
|
||||
<SheetTitle className="text-sm">
|
||||
本轮问题({questions.length})
|
||||
</SheetTitle>
|
||||
</SheetHeader>
|
||||
<QuestionCardList
|
||||
questions={questions}
|
||||
activeId={activeId}
|
||||
onSelect={(anchorId) => {
|
||||
setSheetOpen(false);
|
||||
scrollToQuestion(anchorId);
|
||||
}}
|
||||
className="min-h-0 flex-1"
|
||||
/>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function QuestionCardList({
|
||||
questions,
|
||||
activeId,
|
||||
onSelect,
|
||||
className,
|
||||
}: {
|
||||
questions: QuestionItem[];
|
||||
activeId: string | null;
|
||||
onSelect: (anchorId: string) => void;
|
||||
className?: string;
|
||||
}) {
|
||||
const itemRefs = useRef(new Map<string, HTMLButtonElement>());
|
||||
|
||||
// Keep the active card visible as the chat scrolls. `block: "nearest"` only
|
||||
// nudges this inner list — the card is already inside the on-screen panel,
|
||||
// so no outer container moves.
|
||||
useEffect(() => {
|
||||
if (!activeId) return;
|
||||
itemRefs.current.get(activeId)?.scrollIntoView({ block: "nearest" });
|
||||
}, [activeId]);
|
||||
|
||||
return (
|
||||
<nav
|
||||
aria-label="问题导航"
|
||||
className={cn("flex flex-col gap-2 overflow-y-auto p-2", className)}
|
||||
>
|
||||
{questions.map((question, index) => {
|
||||
const isActive = question.anchorId === activeId;
|
||||
return (
|
||||
<button
|
||||
key={question.anchorId}
|
||||
ref={(el) => {
|
||||
if (el) itemRefs.current.set(question.anchorId, el);
|
||||
else itemRefs.current.delete(question.anchorId);
|
||||
}}
|
||||
type="button"
|
||||
title={question.summary}
|
||||
onClick={() => onSelect(question.anchorId)}
|
||||
className={cn(
|
||||
"w-full cursor-pointer rounded-lg border px-3 py-2 text-left text-[13px] leading-5 shadow-xs transition-colors",
|
||||
isActive
|
||||
? "border-primary/40 border-l-primary bg-primary/10 text-foreground border-l-2 font-medium"
|
||||
: "border-border/50 bg-background/60 text-muted-foreground hover:bg-accent/60 hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<span className="flex items-start gap-1.5">
|
||||
<span
|
||||
className={cn(
|
||||
"shrink-0 text-[11px] leading-5 tabular-nums",
|
||||
isActive ? "text-primary" : "text-muted-foreground/60",
|
||||
)}
|
||||
>
|
||||
{index + 1}.
|
||||
</span>
|
||||
<span className="line-clamp-2 break-words">
|
||||
{question.summary}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -10,12 +10,14 @@ import {
|
||||
ChevronRightIcon,
|
||||
ClockIcon,
|
||||
CopyIcon,
|
||||
EyeOffIcon,
|
||||
FileArchive,
|
||||
GlobeIcon,
|
||||
InfoIcon,
|
||||
Loader2,
|
||||
LockIcon,
|
||||
PinIcon,
|
||||
PlusIcon,
|
||||
RefreshCwIcon,
|
||||
SparklesIcon,
|
||||
TagsIcon,
|
||||
@@ -436,6 +438,18 @@ function SkillSettingsList({ onClose }: { onClose?: () => void }) {
|
||||
<Upload className="size-4" />
|
||||
{t.settings.skills.installSkill}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
onClose?.();
|
||||
router.push("/page/workspace/chats/new?mode=skill");
|
||||
}}
|
||||
disabled={env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true"}
|
||||
title="在对话中描述需求,由 AI 帮你创建一个新技能"
|
||||
>
|
||||
<PlusIcon className="size-4" />
|
||||
{t.settings.skills.createSkill}
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
<TagSearchBar
|
||||
@@ -736,7 +750,7 @@ export function SkillRow({
|
||||
{t.settings.skills.badgeFromOthers}
|
||||
</Badge>
|
||||
)}
|
||||
{isOwned && skill.published && (
|
||||
{(isOwned || isAdmin) && !isBuiltin && skill.published && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="border-sky-500/30 text-sky-700 dark:text-sky-300 text-xs"
|
||||
@@ -746,6 +760,16 @@ export function SkillRow({
|
||||
{t.settings.skills.badgePublished}
|
||||
</Badge>
|
||||
)}
|
||||
{(isOwned || isAdmin) && !isBuiltin && !skill.published && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="border-zinc-400/40 text-zinc-500 dark:text-zinc-400 text-xs"
|
||||
title={t.settings.skills.badgeUnpublishedTitle}
|
||||
>
|
||||
<EyeOffIcon className="size-3" />
|
||||
{t.settings.skills.badgeUnpublished}
|
||||
</Badge>
|
||||
)}
|
||||
{isCustom && !isBuiltin && skill.source === "agent" && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { ChevronLeft, ChevronRight } from "lucide-react";
|
||||
import { ChevronLeft, ChevronRight, Trophy } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -86,6 +86,20 @@ export function WorkspaceHeader({ className }: { className?: string }) {
|
||||
) : (
|
||||
titleBlock
|
||||
)}
|
||||
{/* 用户排行榜入口:紧挨左上角的应用名,新标签打开免登录的公开排行榜页。 */}
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
window.open("#/public/leaderboard", "_blank", "noopener")
|
||||
}
|
||||
title="打开用户排行榜公开页"
|
||||
className="text-muted-foreground hover:text-sidebar-foreground h-8 shrink-0 gap-1 px-1.5 text-xs font-medium"
|
||||
>
|
||||
<Trophy className="size-4" />
|
||||
<span>排行榜</span>
|
||||
</Button>
|
||||
<SidebarCollapseButton />
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -16,6 +16,7 @@ import { useI18n } from "@/core/i18n/hooks";
|
||||
// import { BotIcon, BrainIcon, ListChecks, MessageSquarePlus, MessagesSquare, SparklesIcon, UsersIcon } from "lucide-react";
|
||||
import { BookOpen, BotIcon, BrainIcon, ListChecks, MessageSquarePlus, MessagesSquare, PenLine, SparklesIcon, Users } from "lucide-react";
|
||||
|
||||
import { KnowledgeRagToggle } from "./knowledge-rag-toggle";
|
||||
import { SidebarCollapseButton } from "./workspace-header";
|
||||
import { WorkspaceNavStudio } from "./workspace-nav-studio";
|
||||
import { cn } from "@/lib/utils";
|
||||
@@ -161,6 +162,7 @@ export function WorkspaceNavChatList({
|
||||
</Link>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
<KnowledgeRagToggle className={NAV_ITEM_CLASS} />
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
isActive={pathname.startsWith("/page/workspace/knowledge")}
|
||||
|
||||
@@ -128,7 +128,10 @@ interface ThemeProviderProps {
|
||||
}
|
||||
|
||||
export const ThemeProvider: React.FC<ThemeProviderProps> = ({ children }) => {
|
||||
const { resolvedTheme, setTheme: setNextTheme } = useNextTheme();
|
||||
// forcedTheme:嵌入路由 / landing 由 AppProviders 强制的主题。强制期间
|
||||
// 它决定渲染,且本组件不得写 localStorage(嵌入子应用与主站同域共享
|
||||
// 存储,写入会覆盖用户在主站的选择)。
|
||||
const { resolvedTheme, forcedTheme, setTheme: setNextTheme } = useNextTheme();
|
||||
const [mounted, setMounted] = useState(false);
|
||||
// Admin-configured global default. If the user hasn't explicitly chosen
|
||||
// a theme yet, this value drives the rendered theme — and re-syncs on
|
||||
@@ -144,7 +147,7 @@ export const ThemeProvider: React.FC<ThemeProviderProps> = ({ children }) => {
|
||||
// 注意:不要在这里强制写入一个 fallback —— 那会让 next-themes 视作
|
||||
// 「用户已选过」,admin 默认就再也注入不进来了。
|
||||
useEffect(() => {
|
||||
if (!mounted) return;
|
||||
if (!mounted || forcedTheme) return;
|
||||
const current = localStorage.getItem(STORAGE_KEY);
|
||||
const legacy = localStorage.getItem('theme');
|
||||
|
||||
@@ -162,24 +165,25 @@ export const ThemeProvider: React.FC<ThemeProviderProps> = ({ children }) => {
|
||||
if (legacy) {
|
||||
localStorage.removeItem('theme');
|
||||
}
|
||||
}, [mounted, setNextTheme]);
|
||||
}, [mounted, forcedTheme, setNextTheme]);
|
||||
|
||||
// Boot-time sync: when the user has never picked a theme themselves,
|
||||
// apply whatever the admin configured. Re-runs whenever the admin
|
||||
// setting changes (so a logged-in user sees the new default after
|
||||
// refreshing without having to clear cookies).
|
||||
useEffect(() => {
|
||||
if (!mounted) return;
|
||||
if (!mounted || forcedTheme) return;
|
||||
if (hasExplicitChoice()) return;
|
||||
const adminDefault = appearance?.default_theme;
|
||||
if (!adminDefault) return;
|
||||
if (resolvedTheme !== adminDefault) {
|
||||
setNextTheme(adminDefault);
|
||||
}
|
||||
}, [mounted, appearance?.default_theme, resolvedTheme, setNextTheme]);
|
||||
}, [mounted, forcedTheme, appearance?.default_theme, resolvedTheme, setNextTheme]);
|
||||
|
||||
const effectiveTheme = forcedTheme ?? resolvedTheme;
|
||||
const theme: ThemeType = mounted
|
||||
? resolvedTheme === 'dark'
|
||||
? effectiveTheme === 'dark'
|
||||
? 'dark'
|
||||
: 'light'
|
||||
: readPersistedTheme();
|
||||
|
||||
@@ -335,6 +335,44 @@ export async function adminSyncAgentSkills(): Promise<AgentSkillsSyncResult> {
|
||||
return res.json() as Promise<AgentSkillsSyncResult>;
|
||||
}
|
||||
|
||||
export interface KnowledgeIngestAttempt {
|
||||
title_field: string;
|
||||
status_code: number | null;
|
||||
response_text: string;
|
||||
success: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export interface KnowledgeIngestPublishResult {
|
||||
success: boolean;
|
||||
template_name: string;
|
||||
node_name: string;
|
||||
batch_number: string;
|
||||
attempts: KnowledgeIngestAttempt[];
|
||||
}
|
||||
|
||||
/** 把一份 md 产物(标题 + 全文)发布到外部知识入库接口。后端会先按
|
||||
* 「名称」字段映射发送,失败后用同一 nodeName 换「标题」字段重试一次。 */
|
||||
export async function publishArtifactToKnowledge(request: {
|
||||
agent_id: string;
|
||||
title: string;
|
||||
content: string;
|
||||
}): Promise<KnowledgeIngestPublishResult> {
|
||||
const res = await apiFetch(
|
||||
`${getBackendBaseURL()}/api/knowledge-ingest/publish`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(request),
|
||||
},
|
||||
);
|
||||
if (!res.ok) {
|
||||
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
||||
throw new Error(err.detail ?? `发布入库失败: ${res.statusText}`);
|
||||
}
|
||||
return res.json() as Promise<KnowledgeIngestPublishResult>;
|
||||
}
|
||||
|
||||
export async function checkAgentName(
|
||||
name: string,
|
||||
): Promise<{ available: boolean; name: string }> {
|
||||
|
||||
@@ -55,6 +55,9 @@ export interface Agent {
|
||||
* New agents store `{title, prompt}`; legacy agents may still return `string[]`.
|
||||
* Read via {@link normalizeAgentQuestions}. */
|
||||
common_questions?: (string | AgentQuestion)[] | null;
|
||||
/** 入库模板名(外部知识入库接口的 templateName)。配置后该智能体会话中的
|
||||
* Markdown 产物右上角出现"发布入库"按钮。空/缺省 = 不支持入库。 */
|
||||
template_name?: string | null;
|
||||
tags?: Tag[];
|
||||
featured_order?: number | null;
|
||||
/** Whether the current user has favorited (收藏) this agent. */
|
||||
@@ -87,6 +90,7 @@ export interface CreateAgentRequest {
|
||||
model?: string | null;
|
||||
tool_groups?: string[] | null;
|
||||
common_questions?: AgentQuestion[] | null;
|
||||
template_name?: string | null;
|
||||
}
|
||||
|
||||
export interface UpdateAgentRequest {
|
||||
@@ -100,4 +104,6 @@ export interface UpdateAgentRequest {
|
||||
model?: string | null;
|
||||
tool_groups?: string[] | null;
|
||||
common_questions?: AgentQuestion[] | null;
|
||||
/** 入库模板名;传空字符串表示清除。 */
|
||||
template_name?: string | null;
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useLocation } from "react-router-dom";
|
||||
|
||||
/**
|
||||
* 公开页(被第三方 iframe 嵌套)的可配置外观:背景色 + 整体明暗主题。
|
||||
*
|
||||
* 这些 `/public/*`、`/share/*`、`/roundtable-share/*` 页面会被别的系统用
|
||||
* `<iframe>` 嵌进去。嵌套方希望外观跟自己的站点保持一致,所以我们把
|
||||
* 「背景色 / 前景文字色 / light·dark 主题」抽成可外部传入的参数,两种传法都支持:
|
||||
*
|
||||
* 1. URL 查询参数(嵌套时一次性指定,最常用):
|
||||
* `<iframe src=".../#/public/leaderboard?theme=dark&bg=%23ffffff&text=%23111111">`
|
||||
* —— `theme` 切整体明暗(`dark`/`light`,兼容 `dark-blue`/`red` 等别名),
|
||||
* `bg`/`background` 设背景,`text`/`fg` 设文字色。
|
||||
* 2. `postMessage`(嵌套后动态切换,比如宿主切主题时同步):
|
||||
* `iframe.contentWindow.postMessage({ type: "deerflow:set-bg", bg: "#fff", text: "#111" }, "*")`
|
||||
* `iframe.contentWindow.postMessage({ type: "deerflow:set-theme", theme: "dark" }, "*")`
|
||||
*
|
||||
* 不传时沿用页面自带的默认配色(Tailwind 类)与站内主题,互不影响。
|
||||
* 主题经 `usePublicEmbedTheme` 在 App 层接成 next-themes 的 `forcedTheme`,
|
||||
* 只影响当前渲染、不写 localStorage(原因见 App.tsx 内注释)。
|
||||
*/
|
||||
export type PublicBackground = {
|
||||
backgroundColor?: string;
|
||||
color?: string;
|
||||
};
|
||||
|
||||
const HEX_RE = /^#?(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
|
||||
// 允许的非 hex 颜色:rgb()/rgba()/hsl()/hsla() 与简单命名色。限定安全字符集,
|
||||
// 既能覆盖常见写法,又能挡掉任何想塞进内联样式的奇怪内容。
|
||||
const SAFE_COLOR_RE = /^[a-zA-Z]+$|^(?:rgb|rgba|hsl|hsla)\(\s*[0-9.,%\s/]+\)$/;
|
||||
|
||||
/** 把外部传入的颜色串规整成可用的 CSS 颜色;非法/为空时返回 undefined。 */
|
||||
export function normalizeCssColor(raw: string | null | undefined): string | undefined {
|
||||
if (!raw) return undefined;
|
||||
const value = raw.trim();
|
||||
if (!value) return undefined;
|
||||
if (HEX_RE.test(value)) return value.startsWith("#") ? value : `#${value}`;
|
||||
if (SAFE_COLOR_RE.test(value)) return value;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function readFromSearch(search: string): PublicBackground {
|
||||
const params = new URLSearchParams(search.startsWith("?") ? search : `?${search}`);
|
||||
const backgroundColor = normalizeCssColor(params.get("bg") ?? params.get("background"));
|
||||
const color = normalizeCssColor(params.get("text") ?? params.get("fg"));
|
||||
const result: PublicBackground = {};
|
||||
if (backgroundColor) result.backgroundColor = backgroundColor;
|
||||
if (color) result.color = color;
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取公开页背景配置,可直接 `style={...}` 展开到页面根容器。
|
||||
*
|
||||
* 合并两处来源:HashRouter 路由内的查询串(`?bg=` 跟在 `#/路由` 后面)以及
|
||||
* `window.location.search`(`?bg=` 在 `#` 前面);路由内的更贴近当前页,优先级更高。
|
||||
* 同时监听 `postMessage` 以支持嵌套后动态改色。
|
||||
*/
|
||||
/**
|
||||
* 把外部传入的主题标识规整成 light/dark;不认识或为空返回 undefined(沿用站内主题)。
|
||||
* 兼容嵌入聊天页已有的取值习惯:`dark-blue`/深蓝 → 深色,`red`/红白 → 浅色。
|
||||
*/
|
||||
export function normalizePublicTheme(
|
||||
raw: string | null | undefined,
|
||||
): "dark" | "light" | undefined {
|
||||
const value = raw?.trim().toLowerCase();
|
||||
if (!value) return undefined;
|
||||
if (value === "dark" || value === "dark-blue" || value === "深蓝" || value === "深色") {
|
||||
return "dark";
|
||||
}
|
||||
if (value === "light" || value === "red" || value === "红白" || value === "浅色") {
|
||||
return "light";
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function readThemeFromSearch(search: string): "dark" | "light" | undefined {
|
||||
const params = new URLSearchParams(search.startsWith("?") ? search : `?${search}`);
|
||||
return normalizePublicTheme(params.get("theme"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取公开页的外部主题(`?theme=` 或 `deerflow:set-theme` postMessage)。
|
||||
*
|
||||
* 与 `usePublicBackground` 同样合并两处查询串(hash 路由内优先),
|
||||
* postMessage 的动态值优先级最高。返回 undefined 表示外部未指定。
|
||||
*/
|
||||
export function usePublicEmbedTheme(): "dark" | "light" | undefined {
|
||||
const location = useLocation();
|
||||
|
||||
const fromUrl = useMemo(() => {
|
||||
const outer = readThemeFromSearch(
|
||||
typeof window !== "undefined" ? window.location.search : "",
|
||||
);
|
||||
const inner = readThemeFromSearch(location.search);
|
||||
return inner ?? outer;
|
||||
}, [location.search]);
|
||||
|
||||
const [override, setOverride] = useState<"dark" | "light" | undefined>(undefined);
|
||||
|
||||
useEffect(() => {
|
||||
function onMessage(event: MessageEvent) {
|
||||
const data = event.data as { type?: string; theme?: string } | null;
|
||||
if (!data || typeof data !== "object") return;
|
||||
if (data.type !== "deerflow:set-theme") return;
|
||||
const theme = normalizePublicTheme(data.theme);
|
||||
if (theme) setOverride(theme);
|
||||
}
|
||||
window.addEventListener("message", onMessage);
|
||||
return () => window.removeEventListener("message", onMessage);
|
||||
}, []);
|
||||
|
||||
return override ?? fromUrl;
|
||||
}
|
||||
|
||||
export function usePublicBackground(): PublicBackground {
|
||||
const location = useLocation();
|
||||
|
||||
const fromUrl = useMemo<PublicBackground>(() => {
|
||||
const outer = readFromSearch(typeof window !== "undefined" ? window.location.search : "");
|
||||
const inner = readFromSearch(location.search);
|
||||
return { ...outer, ...inner };
|
||||
}, [location.search]);
|
||||
|
||||
const [override, setOverride] = useState<PublicBackground>({});
|
||||
|
||||
useEffect(() => {
|
||||
function onMessage(event: MessageEvent) {
|
||||
const data = event.data as
|
||||
| { type?: string; bg?: string; background?: string; text?: string; fg?: string }
|
||||
| null;
|
||||
if (!data || typeof data !== "object") return;
|
||||
if (data.type !== "deerflow:set-bg" && data.type !== "deerflow:set-background") return;
|
||||
setOverride((prev) => {
|
||||
const next: PublicBackground = { ...prev };
|
||||
const bg = normalizeCssColor(data.bg ?? data.background);
|
||||
const text = normalizeCssColor(data.text ?? data.fg);
|
||||
if (bg) next.backgroundColor = bg;
|
||||
if (text) next.color = text;
|
||||
return next;
|
||||
});
|
||||
}
|
||||
window.addEventListener("message", onMessage);
|
||||
return () => window.removeEventListener("message", onMessage);
|
||||
}, []);
|
||||
|
||||
return useMemo(() => ({ ...fromUrl, ...override }), [fromUrl, override]);
|
||||
}
|
||||
@@ -44,3 +44,14 @@ export function resolveEmbedChatParams(search: string): EmbedChatParams {
|
||||
export function resolveEmbedTheme(themeParam: string): "dark" | "light" {
|
||||
return resolveThemeFromQuery(themeParam || null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 把宿主传入的主题标识映射成 light/dark。**默认深蓝(dark)**:
|
||||
* 只有明确传 light/红白 才走浅色,其余(dark / dark-blue / 深蓝 / 空)一律深蓝。
|
||||
* 不复用 `resolveEmbedTheme`(它只认严格的 "dark-blue",传 "dark" 会被判成浅色)。
|
||||
*/
|
||||
export function resolveEmbedRoundtableTheme(raw: string): "dark" | "light" {
|
||||
const v = raw.trim().toLowerCase();
|
||||
if (v === "light" || v === "red" || v === "红白") return "light";
|
||||
return "dark";
|
||||
}
|
||||
@@ -482,6 +482,8 @@ export const enUS: Translations = {
|
||||
badgeFromOthersTitle: "Owned by user {user_id}",
|
||||
badgePublished: "Published",
|
||||
badgePublishedTitle: "Visible to all users",
|
||||
badgeUnpublished: "Unpublished",
|
||||
badgeUnpublishedTitle: "Not published yet — only visible to its owner",
|
||||
badgeStale: "Stale",
|
||||
badgeStaleTitle: "Idle for a long time — flagged by the curator",
|
||||
badgeArchived: "Archived",
|
||||
|
||||
@@ -415,6 +415,8 @@ export interface Translations {
|
||||
badgeFromOthersTitle: string;
|
||||
badgePublished: string;
|
||||
badgePublishedTitle: string;
|
||||
badgeUnpublished: string;
|
||||
badgeUnpublishedTitle: string;
|
||||
badgeStale: string;
|
||||
badgeStaleTitle: string;
|
||||
badgeArchived: string;
|
||||
|
||||
@@ -462,6 +462,8 @@ export const zhCN: Translations = {
|
||||
badgeFromOthersTitle: "来自用户 {user_id}",
|
||||
badgePublished: "已发布",
|
||||
badgePublishedTitle: "该技能已对所有用户可见",
|
||||
badgeUnpublished: "未发布",
|
||||
badgeUnpublishedTitle: "该技能尚未发布,仅所有者可见",
|
||||
badgeStale: "过时",
|
||||
badgeStaleTitle: "长期未使用,已被策展程序标记",
|
||||
badgeArchived: "归档",
|
||||
|
||||
@@ -32,6 +32,7 @@ export async function listKnowledgeNotes(params: KnowledgeListParams = {}) {
|
||||
const qs = new URLSearchParams();
|
||||
if (params.keyword) qs.set("keyword", params.keyword);
|
||||
if (params.tag) qs.set("tag", params.tag);
|
||||
if (params.entity) qs.set("entity", params.entity);
|
||||
if (params.source_type) qs.set("source_type", params.source_type);
|
||||
if (params.status) qs.set("status", params.status);
|
||||
qs.set("limit", String(params.limit ?? 20));
|
||||
|
||||
@@ -54,6 +54,8 @@ export interface KnowledgeListResponse {
|
||||
export interface KnowledgeListParams {
|
||||
keyword?: string;
|
||||
tag?: string;
|
||||
/** Exact entity-name filter (matched via the knowledge relation graph). */
|
||||
entity?: string;
|
||||
source_type?: string;
|
||||
status?: string;
|
||||
limit?: number;
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import {
|
||||
isChatsIframeWorkspacePath,
|
||||
resolveForcedThemeForPath,
|
||||
} from "./chats-iframe-route.ts";
|
||||
|
||||
test("matches only workspace chats_iframe routes", () => {
|
||||
assert.equal(
|
||||
isChatsIframeWorkspacePath("/page/workspace/chats_iframe/new"),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isChatsIframeWorkspacePath("/page/workspace/chats_iframe/thread-123"),
|
||||
true,
|
||||
);
|
||||
assert.equal(isChatsIframeWorkspacePath("/page/workspace/chats/new"), false);
|
||||
assert.equal(isChatsIframeWorkspacePath("/landing"), false);
|
||||
});
|
||||
|
||||
test("forces light theme for landing and chats_iframe routes only", () => {
|
||||
assert.equal(resolveForcedThemeForPath("/landing"), "light");
|
||||
assert.equal(
|
||||
resolveForcedThemeForPath("/page/workspace/chats_iframe/new"),
|
||||
"light",
|
||||
);
|
||||
assert.equal(
|
||||
resolveForcedThemeForPath("/page/workspace/chats_iframe/thread-123"),
|
||||
"light",
|
||||
);
|
||||
assert.equal(resolveForcedThemeForPath("/page/workspace/chats/new"), undefined);
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
export function isChatsIframeWorkspacePath(pathname: string): boolean {
|
||||
return (
|
||||
pathname === "/page/workspace/chats_iframe/new" ||
|
||||
pathname.startsWith("/page/workspace/chats_iframe/")
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveForcedThemeForPath(
|
||||
pathname: string,
|
||||
): "light" | undefined {
|
||||
if (pathname === "/landing" || isChatsIframeWorkspacePath(pathname)) {
|
||||
return "light";
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
/**
|
||||
* 全局侧边栏菜单数据与权限过滤逻辑。
|
||||
* ?????????????????
|
||||
*
|
||||
* 浅色 ``PageSidebar`` 和深色 ``PageSidebarDark`` 共用这份数据 —— 菜单结构与
|
||||
* adminOnly 权限策略对两种皮肤完全一致;UI 渲染(icon 显示/折叠样式/hover flyout)
|
||||
* 在各自组件里实现。
|
||||
* ?? ``PageSidebar`` ??? ``PageSidebarDark`` ?????? ?? ?????
|
||||
* adminOnly ??????????????UI ???icon ??/????/hover flyout?
|
||||
* ?????????
|
||||
*
|
||||
* 修改菜单只需改这一处,两个 sidebar 自动同步。
|
||||
* ????????????? sidebar ?????
|
||||
*/
|
||||
import type { ElementType } from "react";
|
||||
import {
|
||||
@@ -24,11 +24,13 @@ import {
|
||||
History,
|
||||
Layers,
|
||||
Layout,
|
||||
Library,
|
||||
List,
|
||||
ListChecks,
|
||||
ListTodo,
|
||||
MessageSquareCode,
|
||||
Network,
|
||||
NotebookPen,
|
||||
Plus,
|
||||
Settings,
|
||||
Sparkles,
|
||||
Target,
|
||||
@@ -48,46 +50,80 @@ export type MenuItem = {
|
||||
export const sidebarMenuItems: MenuItem[] = [
|
||||
{
|
||||
id: "qa-center",
|
||||
label: "问答中心",
|
||||
label: "????",
|
||||
icon: HelpCircle,
|
||||
children: [
|
||||
{ id: "general-qa", label: "通用问答", icon: CircleHelp, path: "/page/workspace/chats/new" },
|
||||
{ id: "general-qa", label: "????", icon: CircleHelp, path: "/page/workspace/chats/new" },
|
||||
{
|
||||
id: "multi-agent-roundtable",
|
||||
label: "多智能体会商",
|
||||
label: "??????",
|
||||
icon: Users,
|
||||
path: "/page/strategy/qa/multi-agent-roundtable",
|
||||
},
|
||||
// { id: "expert-qa", label: "专家问答", icon: Brain, path: "/page/strategy/qa/expert-qa" },
|
||||
// { id: "expert-qa", label: "????", icon: Brain, path: "/page/strategy/qa/expert-qa" },
|
||||
{
|
||||
id: "qa-zzjc",
|
||||
label: "zzJC支持",
|
||||
icon: Bot,
|
||||
path: "/page/strategy/agents/6bf/chats/new",
|
||||
},
|
||||
{ id: "qa-zzxd", label: "zzXD应用", icon: Layout, path: "/page/strategy/agents/10d69686718349688e58a8790cb61024/chats/new", },
|
||||
{ id: "qa-research", label: "课题研究", icon: FileText, path: "/page/canvas/ai-writing" },
|
||||
{ id: "qa-zzxd", label: "zzXD??", icon: Layout, path: "/page/strategy/agents/10d69686718349688e58a8790cb61024/chats/new", },
|
||||
{ id: "qa-research", label: "????", icon: FileText, path: "/page/canvas/ai-writing" },
|
||||
],
|
||||
},
|
||||
// {
|
||||
// id: "light-app-center",
|
||||
// label: "???",
|
||||
// icon: Grid3X3,
|
||||
// children: [
|
||||
// {
|
||||
// id: "light-app-note-management",
|
||||
// label: "????",
|
||||
// icon: NotebookPen,
|
||||
// children: [
|
||||
// {
|
||||
// id: "light-app-new-note",
|
||||
// label: "????",
|
||||
// icon: Plus,
|
||||
// path: "/page/strategy/light-app/new-note",
|
||||
// },
|
||||
// {
|
||||
// id: "light-app-note-list",
|
||||
// label: "????",
|
||||
// icon: List,
|
||||
// path: "/page/strategy/light-app/notes",
|
||||
// },
|
||||
// {
|
||||
// id: "light-app-note-qa",
|
||||
// label: "????",
|
||||
// icon: MessageSquareCode,
|
||||
// path: "/page/strategy/light-app/note-qa",
|
||||
// },
|
||||
// ],
|
||||
// },
|
||||
// { id: "light-app-square", label: "????", icon: Layout },
|
||||
// { id: "light-app-records", label: "????", icon: History },
|
||||
// ],
|
||||
// },
|
||||
{
|
||||
id: "task-management",
|
||||
label: "任务管理",
|
||||
label: "????",
|
||||
icon: Target,
|
||||
children: [
|
||||
{
|
||||
id: "xk-center-task",
|
||||
label: "XK中任务",
|
||||
label: "XK???",
|
||||
icon: Folder,
|
||||
children: [
|
||||
{
|
||||
id: "xk-task-jc",
|
||||
label: "任务JC",
|
||||
label: "??JC",
|
||||
icon: ListTodo,
|
||||
path: "/page/strategy/task-management/xk-task-jc",
|
||||
},
|
||||
{
|
||||
id: "xk-task-dispatch",
|
||||
label: "任务调度",
|
||||
label: "????",
|
||||
icon: ListTodo,
|
||||
path: "/page/strategy/task-management/xk-task-dispatch",
|
||||
},
|
||||
@@ -95,7 +131,7 @@ export const sidebarMenuItems: MenuItem[] = [
|
||||
},
|
||||
{
|
||||
id: "coh-center-task",
|
||||
label: "COH中任务",
|
||||
label: "COH???",
|
||||
icon: Folder,
|
||||
children: [
|
||||
{
|
||||
@@ -106,7 +142,7 @@ export const sidebarMenuItems: MenuItem[] = [
|
||||
},
|
||||
{
|
||||
id: "coh-task-fx",
|
||||
label: "任务FX",
|
||||
label: "??FX",
|
||||
icon: ListTodo,
|
||||
path: "/page/strategy/task-management/plan-task/plan-task-fx",
|
||||
},
|
||||
@@ -120,12 +156,12 @@ export const sidebarMenuItems: MenuItem[] = [
|
||||
},
|
||||
{
|
||||
id: "pg-center-task",
|
||||
label: "PG中任务",
|
||||
label: "PG???",
|
||||
icon: Folder,
|
||||
children: [
|
||||
{
|
||||
id: "pg-task-pg",
|
||||
label: "任务PG",
|
||||
label: "??PG",
|
||||
icon: ListTodo,
|
||||
path: "/page/strategy/task-management/effect-task-pg",
|
||||
},
|
||||
@@ -137,7 +173,7 @@ export const sidebarMenuItems: MenuItem[] = [
|
||||
},
|
||||
{
|
||||
id: "pg-task-info-pg",
|
||||
label: "信息PG",
|
||||
label: "??PG",
|
||||
icon: ListTodo,
|
||||
path: "/page/strategy/task-management/effect-info-pg",
|
||||
},
|
||||
@@ -145,24 +181,24 @@ export const sidebarMenuItems: MenuItem[] = [
|
||||
},
|
||||
{
|
||||
id: "ty-center-task",
|
||||
label: "TY中任务",
|
||||
label: "TY???",
|
||||
icon: Folder,
|
||||
children: [
|
||||
{
|
||||
id: "ty-task-xdty",
|
||||
label: "XDTY任务",
|
||||
label: "XDTY??",
|
||||
icon: ListTodo,
|
||||
path: "/page/strategy/task-management/mnty-task-mechanism",
|
||||
},
|
||||
{
|
||||
id: "ty-task-plan",
|
||||
label: "方案TY任务",
|
||||
label: "??TY??",
|
||||
icon: ListTodo,
|
||||
path: "/page/strategy/task-management/mnty-task-plan",
|
||||
},
|
||||
{
|
||||
id: "ty-task-xxty",
|
||||
label: "XXTY任务",
|
||||
label: "XXTY??",
|
||||
icon: ListTodo,
|
||||
path: "/page/strategy/task-management/mnty-task-zsty",
|
||||
},
|
||||
@@ -170,83 +206,63 @@ export const sidebarMenuItems: MenuItem[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "light-app-center",
|
||||
label: "应用中心",
|
||||
icon: Grid3X3,
|
||||
children: [
|
||||
{
|
||||
id: "light-app-management",
|
||||
label: "应用管理",
|
||||
icon: Layout,
|
||||
path: "/page/strategy/light-app/management",
|
||||
adminOnly: true,
|
||||
},
|
||||
{
|
||||
id: "light-app-apps",
|
||||
label: "应用列表",
|
||||
icon: List,
|
||||
path: "/page/strategy/light-app/apps",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "comprehensive-management",
|
||||
label: "综合管理",
|
||||
label: "????",
|
||||
icon: Settings,
|
||||
children: [
|
||||
{ id: "mgmt-agents", label: "智能体管理", icon: Bot, path: "/page/strategy/agents" },
|
||||
{ id: "mgmt-agents", label: "?????", icon: Bot, path: "/page/strategy/agents" },
|
||||
{
|
||||
id: "mgmt-business-chain-mapping",
|
||||
label: "配置管理",
|
||||
label: "????",
|
||||
icon: Network,
|
||||
path: "/page/strategy/business-chain-mapping",
|
||||
},
|
||||
{
|
||||
id: "mgmt-business-chains",
|
||||
label: "业务链条配置",
|
||||
label: "??????",
|
||||
icon: Layers,
|
||||
path: "/page/strategy/business-chains",
|
||||
},
|
||||
{ id: "mgmt-skills", label: "技能管理", icon: Sparkles, path: "/page/strategy/skills" },
|
||||
{ id: "mgmt-memory", label: "记忆管理", icon: Brain, path: "/page/strategy/memory" },
|
||||
{ id: "mgmt-skills", label: "????", icon: Sparkles, path: "/page/strategy/skills" },
|
||||
{ id: "mgmt-memory", label: "????", icon: Brain, path: "/page/strategy/memory" },
|
||||
{
|
||||
id: "mgmt-tasks",
|
||||
label: "定时任务",
|
||||
label: "????",
|
||||
icon: ListChecks,
|
||||
path: "/page/strategy/scheduled/tasks",
|
||||
},
|
||||
{
|
||||
id: "mgmt-llm-metrics",
|
||||
label: "大模型调用统计",
|
||||
label: "???????",
|
||||
icon: Gauge,
|
||||
path: "/page/strategy/settings/llm-metrics",
|
||||
adminOnly: true,
|
||||
},
|
||||
{
|
||||
id: "mgmt-users",
|
||||
label: "用户管理",
|
||||
label: "????",
|
||||
icon: Users,
|
||||
path: "/page/strategy/admin/users",
|
||||
adminOnly: true,
|
||||
},
|
||||
{
|
||||
id: "mgmt-user-leaderboard",
|
||||
label: "用户排行榜",
|
||||
label: "?????",
|
||||
icon: Trophy,
|
||||
path: "/page/strategy/admin/user-leaderboard",
|
||||
adminOnly: true,
|
||||
},
|
||||
{
|
||||
id: "mgmt-admin-scheduled-tasks",
|
||||
label: "定时任务管理",
|
||||
label: "??????",
|
||||
icon: CalendarClock,
|
||||
path: "/page/strategy/admin/scheduled-tasks",
|
||||
adminOnly: true,
|
||||
},
|
||||
{
|
||||
id: "mgmt-user-activity",
|
||||
label: "用户活动审计",
|
||||
label: "??????",
|
||||
icon: History,
|
||||
path: "/page/strategy/admin/user-activity",
|
||||
adminOnly: true,
|
||||
@@ -255,30 +271,24 @@ export const sidebarMenuItems: MenuItem[] = [
|
||||
},
|
||||
{
|
||||
id: "resource-management",
|
||||
label: "资源管理",
|
||||
label: "????",
|
||||
icon: Database,
|
||||
children: [
|
||||
{
|
||||
id: "resource-network-xwt",
|
||||
label: "网络xwt资源管理",
|
||||
label: "??xwt????",
|
||||
icon: Network,
|
||||
path: "/page/strategy/resource-management/resource-network-actor",
|
||||
},
|
||||
{
|
||||
id: "resource-knowledge-native",
|
||||
label: "问答梳理",
|
||||
label: "????",
|
||||
icon: BookOpen,
|
||||
path: "/page/workspace/knowledge",
|
||||
},
|
||||
{
|
||||
id: "resource-knowledge-base",
|
||||
label: "知识库资源管理",
|
||||
icon: Library,
|
||||
path: "/page/strategy/resource-management/resource-knowledge-base",
|
||||
},
|
||||
{
|
||||
id: "resource-evaluation-index",
|
||||
label: "作战资源管理",
|
||||
label: "??????",
|
||||
icon: FileBox,
|
||||
path: "/page/strategy/resource-management/resource-evaluation-index",
|
||||
},
|
||||
@@ -286,7 +296,7 @@ export const sidebarMenuItems: MenuItem[] = [
|
||||
},
|
||||
];
|
||||
|
||||
/** 默认展开的菜单 id 集合(浅色版可折叠交互的初始状态) */
|
||||
/** ??????? id ????????????????? */
|
||||
export const defaultExpandedIds: ReadonlySet<string> = new Set([
|
||||
"qa-center",
|
||||
"light-app-center",
|
||||
@@ -296,7 +306,7 @@ export const defaultExpandedIds: ReadonlySet<string> = new Set([
|
||||
"comprehensive-management",
|
||||
]);
|
||||
|
||||
/** 按 admin 角色过滤菜单:非 admin 不展示 ``adminOnly: true`` 的项及其子项 */
|
||||
/** ? admin ???????? admin ??? ``adminOnly: true`` ?????? */
|
||||
export function filterMenuItemsByRole(items: MenuItem[], isAdmin: boolean): MenuItem[] {
|
||||
return items
|
||||
.filter((item) => !item.adminOnly || isAdmin)
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
export { useLocalSettings, useThreadSettings } from "./hooks";
|
||||
export {
|
||||
getKnowledgeRagEnabled,
|
||||
setKnowledgeRagEnabled,
|
||||
useKnowledgeRagEnabled,
|
||||
} from "./knowledge-rag";
|
||||
export {
|
||||
getLastAgentId,
|
||||
isThreadRagModeLocked,
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { useCallback, useSyncExternalStore } from "react";
|
||||
|
||||
/**
|
||||
* Session-wide switch for knowledge-base RAG injection, toggled from the
|
||||
* workspace sidebar. Deliberately kept in memory only (NOT localStorage):
|
||||
* the product decision is "turn it on for this session and every chat sent
|
||||
* while it is on defaults to enabled" — a page reload resets it to off.
|
||||
*/
|
||||
let knowledgeRagEnabled = false;
|
||||
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function emitChange() {
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
|
||||
export function subscribeKnowledgeRag(listener: () => void): () => void {
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
export function getKnowledgeRagEnabled(): boolean {
|
||||
return knowledgeRagEnabled;
|
||||
}
|
||||
|
||||
export function setKnowledgeRagEnabled(value: boolean) {
|
||||
if (knowledgeRagEnabled === value) {
|
||||
return;
|
||||
}
|
||||
knowledgeRagEnabled = value;
|
||||
emitChange();
|
||||
}
|
||||
|
||||
export function useKnowledgeRagEnabled(): [boolean, (value: boolean) => void] {
|
||||
const enabled = useSyncExternalStore(
|
||||
subscribeKnowledgeRag,
|
||||
getKnowledgeRagEnabled,
|
||||
() => false,
|
||||
);
|
||||
const setEnabled = useCallback((value: boolean) => {
|
||||
setKnowledgeRagEnabled(value);
|
||||
}, []);
|
||||
return [enabled, setEnabled];
|
||||
}
|
||||
@@ -71,6 +71,9 @@ export interface LocalSettings {
|
||||
| "subagent_enabled"
|
||||
| "model_name"
|
||||
| "reasoning_effort"
|
||||
// Session-only sidebar switch (core/settings/knowledge-rag.ts) — must not
|
||||
// round-trip through localStorage.
|
||||
| "knowledge_rag_enabled"
|
||||
> & {
|
||||
model_name?: string | undefined;
|
||||
mode: "flash" | "thinking" | "pro" | "ultra" | undefined;
|
||||
@@ -79,12 +82,16 @@ export interface LocalSettings {
|
||||
}
|
||||
|
||||
function mergeLocalSettings(settings?: Partial<LocalSettings>): LocalSettings {
|
||||
const context = {
|
||||
...DEFAULT_LOCAL_SETTINGS.context,
|
||||
...settings?.context,
|
||||
};
|
||||
// Drop the value persisted by the retired per-thread header toggle; the
|
||||
// knowledge-RAG switch now lives in the sidebar and is session-only.
|
||||
delete (context as Record<string, unknown>).knowledge_rag_enabled;
|
||||
return {
|
||||
...DEFAULT_LOCAL_SETTINGS,
|
||||
context: {
|
||||
...DEFAULT_LOCAL_SETTINGS.context,
|
||||
...settings?.context,
|
||||
},
|
||||
context,
|
||||
notification: {
|
||||
...DEFAULT_LOCAL_SETTINGS.notification,
|
||||
...settings?.notification,
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
export * from "./api";
|
||||
export * from "./type";
|
||||
export * from "./utils";
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { Skill } from "./type";
|
||||
|
||||
/**
|
||||
* 智能体技能白名单的候选池过滤。
|
||||
*
|
||||
* 编辑智能体时,普通用户只能从「内置技能 + 自己的技能 + 已发布到广场的
|
||||
* 技能」里挑选,其他用户未发布的自定义技能不可选;管理员仍可使用全部
|
||||
* 已启用技能。
|
||||
*/
|
||||
export function isAgentSkillCandidate(
|
||||
skill: Skill,
|
||||
currentUserId: string | null,
|
||||
isAdmin = false,
|
||||
): boolean {
|
||||
if (!skill.enabled) return false;
|
||||
if (isAdmin) return true;
|
||||
if ((skill.state ?? "active") !== "active") return false;
|
||||
const builtin = skill.builtin ?? !skill.owner_user_id;
|
||||
const ownedByMe =
|
||||
!!skill.owner_user_id && skill.owner_user_id === currentUserId;
|
||||
return builtin || ownedByMe || !!skill.published;
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import type { AIMessage, Message } from "@langchain/langgraph-sdk";
|
||||
import type { ThreadsClient } from "@langchain/langgraph-sdk/client";
|
||||
import { useStream } from "@langchain/langgraph-sdk/react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import type { QueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { toast } from "sonner";
|
||||
@@ -152,7 +153,10 @@ function getStreamErrorMessage(error: unknown): string {
|
||||
*/
|
||||
function isThreadNotAccessibleError(message: string): boolean {
|
||||
const lowered = message.toLowerCase();
|
||||
if (/thread\s+[\w-]{8,}\s+not\s+found/i.test(message)) {
|
||||
// Backend now returns "not found" (no row + no checkpoint) and
|
||||
// "not accessible" (row owned by another user / stale login session) as
|
||||
// distinct details — both mean the current user can't use this thread.
|
||||
if (/thread\s+[\w-]{8,}\s+not\s+(found|accessible)/i.test(message)) {
|
||||
return true;
|
||||
}
|
||||
// Fallback: a bare 404/403 from the threads endpoint when the SDK has
|
||||
@@ -163,6 +167,21 @@ function isThreadNotAccessibleError(message: string): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect a "Run <id> not found" 404 from the LangGraph SDK.
|
||||
*
|
||||
* The SDK persists the in-flight run id under ``lg:stream:{threadId}`` in
|
||||
* sessionStorage and, on mount, auto-``joinStream``s it to resume a dropped
|
||||
* SSE. After a backend restart the in-memory run registry is gone, so the join
|
||||
* 404s — and the SDK only clears that key on reconnect *success*, never on
|
||||
* failure. So every switch back into the conversation re-fires the same 404.
|
||||
* We detect it here to clear the stale key ourselves and stay silent (the
|
||||
* conversation renders from history; there is nothing live to reconnect to).
|
||||
*/
|
||||
function isRunNotFoundError(message: string): boolean {
|
||||
return /run\s+[\w-]{8,}\s+not\s+found/i.test(message);
|
||||
}
|
||||
|
||||
function buildCurrentUserLabel(): string {
|
||||
const auth = getStoredAuth();
|
||||
if (!auth) {
|
||||
@@ -280,25 +299,19 @@ export function useThreadStream({
|
||||
);
|
||||
for (const update of updates) {
|
||||
if (update && "title" in update && update.title) {
|
||||
void queryClient.setQueriesData(
|
||||
{
|
||||
queryKey: ["threads", "search"],
|
||||
exact: false,
|
||||
},
|
||||
(oldData: Array<AgentThread> | undefined) => {
|
||||
return oldData?.map((t) => {
|
||||
if (t.thread_id === threadIdRef.current) {
|
||||
return {
|
||||
const nextTitle = update.title;
|
||||
updateCachedThreadLists(queryClient, (threads) =>
|
||||
threads.map((t) =>
|
||||
t.thread_id === threadIdRef.current
|
||||
? {
|
||||
...t,
|
||||
values: {
|
||||
...t.values,
|
||||
title: update.title,
|
||||
title: nextTitle,
|
||||
},
|
||||
};
|
||||
}
|
||||
return t;
|
||||
});
|
||||
},
|
||||
}
|
||||
: t,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -335,6 +348,19 @@ export function useThreadStream({
|
||||
onError(error) {
|
||||
setOptimisticMessages([]);
|
||||
const message = getStreamErrorMessage(error);
|
||||
// A stale auto-reconnect ("Run <id> not found") after a backend restart:
|
||||
// drop the dirty ``lg:stream:{threadId}`` key so switching back into this
|
||||
// conversation stops re-firing the same 404, and render from history
|
||||
// silently — there is no live run to rejoin.
|
||||
if (isRunNotFoundError(message)) {
|
||||
const staleThreadId = threadIdRef.current ?? onStreamThreadId ?? null;
|
||||
if (staleThreadId && runMetadataStorageRef.current) {
|
||||
runMetadataStorageRef.current.removeItem(
|
||||
`lg:stream:${staleThreadId}`,
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// A "thread not found" 404 almost always means the URL points at a
|
||||
// thread from a previous login session — either this tab outlived a
|
||||
// logout/re-login or the thread genuinely belongs to a different user.
|
||||
@@ -784,6 +810,31 @@ export interface ThreadsPageResult {
|
||||
hasMore: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply ``transform`` to the thread array inside every cached
|
||||
* ``["threads", "search"]`` entry. The sidebar queries cache a plain
|
||||
* ``AgentThread[]`` while the paged chats list (`useThreadsPage`) caches a
|
||||
* ``ThreadsPageResult`` object under the same key prefix, so fuzzy
|
||||
* ``setQueriesData`` updaters must handle both shapes.
|
||||
*/
|
||||
function updateCachedThreadLists(
|
||||
queryClient: QueryClient,
|
||||
transform: (threads: AgentThread[]) => AgentThread[],
|
||||
) {
|
||||
queryClient.setQueriesData<AgentThread[] | ThreadsPageResult | undefined>(
|
||||
{ queryKey: ["threads", "search"], exact: false },
|
||||
(oldData) => {
|
||||
if (Array.isArray(oldData)) {
|
||||
return transform(oldData);
|
||||
}
|
||||
if (oldData && Array.isArray(oldData.threads)) {
|
||||
return { ...oldData, threads: transform(oldData.threads) };
|
||||
}
|
||||
return oldData;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Server-side paginated conversation list for the chats page. Unlike
|
||||
* `useThreads` (which loads a bounded recent window for the sidebar), this
|
||||
@@ -904,17 +955,8 @@ export function useDeleteThread() {
|
||||
}
|
||||
},
|
||||
onSuccess(_, { threadId }) {
|
||||
queryClient.setQueriesData(
|
||||
{
|
||||
queryKey: ["threads", "search"],
|
||||
exact: false,
|
||||
},
|
||||
(oldData: Array<AgentThread> | undefined) => {
|
||||
if (oldData == null) {
|
||||
return oldData;
|
||||
}
|
||||
return oldData.filter((t) => t.thread_id !== threadId);
|
||||
},
|
||||
updateCachedThreadLists(queryClient, (threads) =>
|
||||
threads.filter((t) => t.thread_id !== threadId),
|
||||
);
|
||||
},
|
||||
onSettled() {
|
||||
@@ -1000,27 +1042,18 @@ export function useUpdateThreadMetadata() {
|
||||
}
|
||||
},
|
||||
onSuccess(_, { threadId, metadata }) {
|
||||
queryClient.setQueriesData(
|
||||
{
|
||||
queryKey: ["threads", "search"],
|
||||
exact: false,
|
||||
},
|
||||
(oldData: Array<AgentThread> | undefined) => {
|
||||
if (oldData == null) {
|
||||
return oldData;
|
||||
}
|
||||
return oldData.map((t) =>
|
||||
t.thread_id === threadId
|
||||
? {
|
||||
...t,
|
||||
metadata: {
|
||||
...(t.metadata as Record<string, unknown> | null),
|
||||
...metadata,
|
||||
},
|
||||
}
|
||||
: t,
|
||||
);
|
||||
},
|
||||
updateCachedThreadLists(queryClient, (threads) =>
|
||||
threads.map((t) =>
|
||||
t.thread_id === threadId
|
||||
? {
|
||||
...t,
|
||||
metadata: {
|
||||
...(t.metadata as Record<string, unknown> | null),
|
||||
...metadata,
|
||||
},
|
||||
}
|
||||
: t,
|
||||
),
|
||||
);
|
||||
},
|
||||
});
|
||||
@@ -1062,25 +1095,18 @@ export function useRenameThread() {
|
||||
});
|
||||
},
|
||||
onSuccess(_, { threadId, title }) {
|
||||
queryClient.setQueriesData(
|
||||
{
|
||||
queryKey: ["threads", "search"],
|
||||
exact: false,
|
||||
},
|
||||
(oldData: Array<AgentThread>) => {
|
||||
return oldData.map((t) => {
|
||||
if (t.thread_id === threadId) {
|
||||
return {
|
||||
updateCachedThreadLists(queryClient, (threads) =>
|
||||
threads.map((t) =>
|
||||
t.thread_id === threadId
|
||||
? {
|
||||
...t,
|
||||
values: {
|
||||
...t.values,
|
||||
title,
|
||||
},
|
||||
};
|
||||
}
|
||||
return t;
|
||||
});
|
||||
},
|
||||
}
|
||||
: t,
|
||||
),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -8,6 +8,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { PromptInputMessage } from "@/components/ai-elements/prompt-input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { AgentDetailPanel } from "@/components/workspace/agents/agent-detail-panel";
|
||||
import { AgentQuestionChips } from "@/components/workspace/agents/agent-question-chips";
|
||||
import { AgentWelcome } from "@/components/workspace/agent-welcome";
|
||||
import { ArtifactTrigger } from "@/components/workspace/artifacts";
|
||||
import { ChatBox, useThreadChat } from "@/components/workspace/chats";
|
||||
@@ -15,6 +16,7 @@ import { ExportTrigger } from "@/components/workspace/export-trigger";
|
||||
import { InputBox } from "@/components/workspace/input-box";
|
||||
import { MessageList } from "@/components/workspace/messages";
|
||||
import { ThreadContext } from "@/components/workspace/messages/context";
|
||||
import { QuestionNavigator } from "@/components/workspace/question-navigator";
|
||||
import { ThreadTitle } from "@/components/workspace/thread-title";
|
||||
import { TodoList } from "@/components/workspace/todo-list";
|
||||
import { TokenUsageIndicator } from "@/components/workspace/token-usage-indicator";
|
||||
@@ -28,7 +30,6 @@ import { useThreadStream } from "@/core/threads/hooks";
|
||||
import { textOfMessage } from "@/core/threads/utils";
|
||||
import { env } from "@/env";
|
||||
import { desensitize } from "@/lib/desensitize";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export default function AgentChatPage() {
|
||||
const routeBase = useRouteBase();
|
||||
@@ -182,8 +183,9 @@ export default function AgentChatPage() {
|
||||
<div className="flex size-full min-h-0 overflow-hidden">
|
||||
<div className="min-h-0 min-w-0 flex-1">
|
||||
<ChatBox threadId={threadId}>
|
||||
{/* Main conversation column */}
|
||||
<main className="flex size-full min-h-0 min-w-0 flex-col">
|
||||
{/* Main conversation column. `relative` hosts the floating
|
||||
question navigator overlay. */}
|
||||
<main className="relative flex size-full min-h-0 min-w-0 flex-col">
|
||||
{/* Header in normal flow, fixed height. */}
|
||||
<header className="bg-card/90 border-border/70 flex h-12 shrink-0 items-center gap-2 border-b px-4 backdrop-blur-md">
|
||||
<div className="flex shrink-0 items-center gap-1.5 rounded-md border px-2 py-1">
|
||||
@@ -235,29 +237,12 @@ export default function AgentChatPage() {
|
||||
className="mb-7"
|
||||
/>
|
||||
<div className="w-full max-w-(--container-width-md)">
|
||||
{commonQuestions.length > 0 && (
|
||||
<div className="mb-2 flex max-h-20 flex-wrap items-start justify-start gap-2 overflow-y-auto px-1">
|
||||
{commonQuestions.map((question, index) => (
|
||||
<button
|
||||
key={index}
|
||||
type="button"
|
||||
disabled={isDemoMode}
|
||||
onClick={() =>
|
||||
handleSubmit({ text: question.prompt, files: [] })
|
||||
}
|
||||
title={desensitize(question.prompt)}
|
||||
className={cn(
|
||||
"border-border/70 bg-background/85 hover:bg-accent hover:border-border max-w-full rounded-full border px-3 py-1.5 text-left text-sm leading-5 shadow-sm transition-colors",
|
||||
"disabled:cursor-not-allowed disabled:opacity-50",
|
||||
)}
|
||||
>
|
||||
<span className="block max-w-[220px] truncate">
|
||||
{desensitize(question.title)}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<AgentQuestionChips
|
||||
className="mb-3"
|
||||
questions={commonQuestions}
|
||||
disabled={isDemoMode}
|
||||
onAsk={(text) => handleSubmit({ text, files: [] })}
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<InputBox
|
||||
className="w-full"
|
||||
@@ -288,6 +273,12 @@ export default function AgentChatPage() {
|
||||
/* Conversation: messages scroll, input
|
||||
docked at the bottom of the main column only. */
|
||||
<div className="flex min-h-0 flex-1 flex-col">
|
||||
{/* Question index pinned to this conversation column; the
|
||||
bottom inset keeps it clear of the docked input box. */}
|
||||
<QuestionNavigator
|
||||
messages={thread.messages}
|
||||
className="top-14 right-0 bottom-40 left-0"
|
||||
/>
|
||||
<MessageList
|
||||
className="min-h-0 flex-1"
|
||||
threadId={threadId}
|
||||
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
} from "@/components/workspace/chats";
|
||||
import { ExportTrigger } from "@/components/workspace/export-trigger";
|
||||
import { KnowledgeSaveTrigger } from "@/components/workspace/knowledge-save-trigger";
|
||||
import { KnowledgeRagToggle } from "@/components/workspace/knowledge-rag-toggle";
|
||||
import { InputBox } from "@/components/workspace/input-box";
|
||||
import {
|
||||
MessageList,
|
||||
@@ -24,6 +23,7 @@ import {
|
||||
MESSAGE_LIST_FOLLOWUPS_EXTRA_PADDING_BOTTOM,
|
||||
} from "@/components/workspace/messages";
|
||||
import { ThreadContext } from "@/components/workspace/messages/context";
|
||||
import { QuestionNavigator } from "@/components/workspace/question-navigator";
|
||||
import { ThreadTitle } from "@/components/workspace/thread-title";
|
||||
import { TodoList } from "@/components/workspace/todo-list";
|
||||
import { TokenUsageIndicator } from "@/components/workspace/token-usage-indicator";
|
||||
@@ -35,6 +35,7 @@ import { useNotification } from "@/core/notification/hooks";
|
||||
import {
|
||||
getLastAgentId,
|
||||
saveLastAgentId,
|
||||
useKnowledgeRagEnabled,
|
||||
useThreadSettings,
|
||||
} from "@/core/settings";
|
||||
import { useThreadStream } from "@/core/threads/hooks";
|
||||
@@ -90,6 +91,18 @@ export default function ChatPage() {
|
||||
const { threadId, setThreadId, isNewThread, setIsNewThread, isMock } =
|
||||
useThreadChat();
|
||||
const [settings, setSettings] = useThreadSettings(threadId);
|
||||
// Sidebar session toggle: while on, every message in every chat carries
|
||||
// knowledge_rag_enabled so the backend injects knowledge-base recall.
|
||||
// In-memory only — explicitly overrides any value persisted by the old
|
||||
// per-thread header toggle so stale localStorage can't re-enable it.
|
||||
const [knowledgeRagEnabled] = useKnowledgeRagEnabled();
|
||||
const streamContext = useMemo(
|
||||
() => ({
|
||||
...settings.context,
|
||||
knowledge_rag_enabled: knowledgeRagEnabled,
|
||||
}),
|
||||
[settings.context, knowledgeRagEnabled],
|
||||
);
|
||||
const [mounted, setMounted] = useState(false);
|
||||
const { tokenUsageEnabled } = useModels();
|
||||
const { data: promptPrefixSettings } = usePromptPrefixSettings();
|
||||
@@ -136,7 +149,7 @@ export default function ChatPage() {
|
||||
|
||||
const [thread, sendMessage, isUploading] = useThreadStream({
|
||||
threadId: isNewThread ? undefined : threadId,
|
||||
context: settings.context,
|
||||
context: streamContext,
|
||||
isMock,
|
||||
onStart: (createdThreadId) => {
|
||||
setThreadId(createdThreadId);
|
||||
@@ -410,7 +423,6 @@ export default function ChatPage() {
|
||||
enabled={tokenUsageEnabled}
|
||||
messages={thread.messages}
|
||||
/>
|
||||
<KnowledgeRagToggle threadId={threadId} />
|
||||
<ExportTrigger threadId={threadId} />
|
||||
<KnowledgeSaveTrigger threadId={threadId} />
|
||||
<ArtifactTrigger />
|
||||
@@ -521,6 +533,19 @@ export default function ChatPage() {
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
{/*
|
||||
ChatGPT-style question index. Anchored to the chat column (this
|
||||
relative wrapper), not the browser edge; insets keep it below the
|
||||
overlay header (h-12) and above the docked input box, and it is
|
||||
pointer-events-none outside its own cards so it never blocks the
|
||||
header buttons or input.
|
||||
*/}
|
||||
{!isLandingState && (
|
||||
<QuestionNavigator
|
||||
messages={thread.messages}
|
||||
className="top-16 right-0 bottom-48 left-0"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</ChatBox>
|
||||
</ThreadContext.Provider>
|
||||
|
||||
@@ -4,13 +4,9 @@ import { useSearchParams } from "next/navigation";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useParams } from "react-router-dom";
|
||||
|
||||
import { useTheme } from "@/contexts/ThemeContext";
|
||||
import { loginByUsername } from "@/core/auth/api";
|
||||
import { setStoredAuth } from "@/core/auth";
|
||||
import {
|
||||
resolveEmbedChatParams,
|
||||
resolveEmbedTheme,
|
||||
} from "@/core/embed/params";
|
||||
import { resolveEmbedChatParams } from "@/core/embed/params";
|
||||
import { registerEmbedSession } from "@/core/embed/status-api";
|
||||
import { useThreadSettings } from "@/core/settings";
|
||||
import { useThreadStream } from "@/core/threads/hooks";
|
||||
@@ -29,7 +25,8 @@ const EMBED_ROUTE_BASE = "/embed/chats";
|
||||
export default function EmbedChatPage() {
|
||||
const { thread_id: threadIdFromPath } = useParams<{ thread_id: string }>();
|
||||
const searchParams = useSearchParams();
|
||||
const { setTheme } = useTheme();
|
||||
// 主题不在这里处理 —— ?theme= 由 AppProviders 通过 forcedTheme 强制
|
||||
// (不落 localStorage),避免污染主站用户自己选的主题。
|
||||
const embedParams = resolveEmbedChatParams(searchParams.toString());
|
||||
const [authReady, setAuthReady] = useState(false);
|
||||
const [authError, setAuthError] = useState<string | null>(null);
|
||||
@@ -51,12 +48,6 @@ export default function EmbedChatPage() {
|
||||
const [settings] = useThreadSettings(threadId);
|
||||
const { tokenUsageEnabled } = useModels();
|
||||
|
||||
useEffect(() => {
|
||||
if (embedParams.theme) {
|
||||
setTheme(resolveEmbedTheme(embedParams.theme));
|
||||
}
|
||||
}, [embedParams.theme, setTheme]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
async function runLogin() {
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
|
||||
import { useTheme } from "@/contexts/ThemeContext";
|
||||
import { loginByUsername } from "@/core/auth/api";
|
||||
import { setStoredAuth } from "@/core/auth";
|
||||
import { readWujieProps, isWujieEnv } from "@/core/embed/wujie";
|
||||
@@ -13,17 +12,6 @@ import "@/roundtable-planning/styles/roundtable-planning.css";
|
||||
|
||||
const DEFAULT_USERNAME = "guest";
|
||||
|
||||
/**
|
||||
* 把宿主传入的主题标识映射成 light/dark。**默认深蓝(dark)**:
|
||||
* 只有明确传 light/红白 才走浅色,其余(dark / dark-blue / 深蓝 / 空)一律深蓝。
|
||||
* 不复用 `resolveEmbedTheme`(它只认严格的 "dark-blue",传 "dark" 会被判成浅色)。
|
||||
*/
|
||||
function resolveEmbedRoundtableTheme(raw: string): "dark" | "light" {
|
||||
const v = raw.trim().toLowerCase();
|
||||
if (v === "light" || v === "red" || v === "红白") return "light";
|
||||
return "dark";
|
||||
}
|
||||
|
||||
/**
|
||||
* 圆桌规划嵌入页(独立入口,**与现有 wujie ticket 登录无关**)。
|
||||
*
|
||||
@@ -37,9 +25,10 @@ function resolveEmbedRoundtableTheme(raw: string): "dark" | "light" {
|
||||
*/
|
||||
export default function EmbedRoundtablePage() {
|
||||
const searchParams = useSearchParams();
|
||||
const { setTheme } = useTheme();
|
||||
|
||||
// username / password / theme:wujie props 优先,URL query 兜底。
|
||||
// username / password:wujie props 优先,URL query 兜底。
|
||||
// 主题不在这里处理 —— 嵌入路由的主题由 AppProviders 通过 forcedTheme
|
||||
// 强制(不落 localStorage),避免污染主站用户自己选的主题。
|
||||
const wp = readWujieProps();
|
||||
const username =
|
||||
(typeof wp.username === "string" && wp.username.trim()) ||
|
||||
@@ -53,19 +42,10 @@ export default function EmbedRoundtablePage() {
|
||||
(typeof wp.password === "string" && wp.password) ||
|
||||
searchParams.get("password") ||
|
||||
undefined;
|
||||
// 主题色:宿主传入优先;默认「深蓝」= dark 主题(其主色为蓝,oklch hue 259)。
|
||||
const themeParam =
|
||||
(typeof wp.theme === "string" && wp.theme.trim()) ||
|
||||
searchParams.get("theme")?.trim() ||
|
||||
"dark";
|
||||
|
||||
const [authReady, setAuthReady] = useState(false);
|
||||
const [authError, setAuthError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setTheme(resolveEmbedRoundtableTheme(themeParam));
|
||||
}, [themeParam, setTheme]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isWujieEnv()) return;
|
||||
document.documentElement.classList.add("wujie-embed");
|
||||
|
||||
@@ -468,6 +468,8 @@ export default function KnowledgeBasePage() {
|
||||
const [status, setStatus] = useState("all");
|
||||
const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());
|
||||
const treeInitializedRef = useRef(false);
|
||||
// Auto-open a default note once on entry so the reading pane is never blank.
|
||||
const defaultNoteShownRef = useRef(false);
|
||||
const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
|
||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(readSidebarCollapsed);
|
||||
|
||||
@@ -495,6 +497,15 @@ export default function KnowledgeBasePage() {
|
||||
const { data: note, isLoading: noteLoading } = useKnowledgeNote(noteId);
|
||||
const { data: wikiLinks } = useNoteWikilinks(noteId);
|
||||
|
||||
// On first entry without an explicit note, open the most recent one so the
|
||||
// reading pane shows real content instead of the empty placeholder.
|
||||
useEffect(() => {
|
||||
if (defaultNoteShownRef.current || noteId || isLoading) return;
|
||||
if (notes.length === 0) return;
|
||||
defaultNoteShownRef.current = true;
|
||||
navigate(`/page/workspace/knowledge/${notes[0].id}`, { replace: true });
|
||||
}, [noteId, isLoading, notes, navigate]);
|
||||
|
||||
// First load: expand the root-level folders so the tree reads as a directory.
|
||||
useEffect(() => {
|
||||
if (treeInitializedRef.current || tree.length === 0) return;
|
||||
|
||||
@@ -47,9 +47,10 @@ import {
|
||||
createAgent,
|
||||
updateAgent,
|
||||
} from "@/core/agents/api";
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
import { useI18n } from "@/core/i18n/hooks";
|
||||
import { useModels } from "@/core/models/hooks";
|
||||
import type { Skill } from "@/core/skills";
|
||||
import { isAgentSkillCandidate, type Skill } from "@/core/skills";
|
||||
import { useSkills } from "@/core/skills/hooks";
|
||||
import { useThreadStream } from "@/core/threads/hooks";
|
||||
import { uuid } from "@/core/utils/uuid";
|
||||
@@ -81,6 +82,7 @@ export default function NewAgentPage() {
|
||||
const [soulInput, setSoulInput] = useState("");
|
||||
const [modelInput, setModelInput] = useState<string>("");
|
||||
const [chatModelInput, setChatModelInput] = useState<string>("");
|
||||
const [templateNameInput, setTemplateNameInput] = useState("");
|
||||
const [formError, setFormError] = useState("");
|
||||
const [agentId, setAgentId] = useState("");
|
||||
const [agent, setAgent] = useState<Agent | null>(null);
|
||||
@@ -94,9 +96,19 @@ export default function NewAgentPage() {
|
||||
const { skills, isLoading: isSkillsLoading } = useSkills();
|
||||
const { models, isLoading: isModelsLoading } = useModels();
|
||||
|
||||
// 可配置的技能限定为「内置 + 自己的 + 已发布到广场的」,
|
||||
// 其他用户未发布的自定义技能不可选。
|
||||
const storedAuth = useMemo(() => getStoredAuth(), []);
|
||||
const enabledSkills = useMemo(
|
||||
() => skills.filter((skill) => skill.enabled),
|
||||
[skills],
|
||||
() =>
|
||||
skills.filter((skill) =>
|
||||
isAgentSkillCandidate(
|
||||
skill,
|
||||
storedAuth?.user_id ?? null,
|
||||
storedAuth?.system_role === "admin",
|
||||
),
|
||||
),
|
||||
[skills, storedAuth],
|
||||
);
|
||||
|
||||
const filteredSkills = useMemo(() => {
|
||||
@@ -184,13 +196,11 @@ export default function NewAgentPage() {
|
||||
// Name is intentionally NOT required here so the user can start chatting
|
||||
// immediately. If they leave it blank, ensureAgent() generates a placeholder
|
||||
// and writes it back into the input so they can rename it later.
|
||||
if (enabledSkills.length > 0 && selectedSkills.length === 0) {
|
||||
setFormError("请至少选择一个技能");
|
||||
return null;
|
||||
}
|
||||
// Zero skills is a valid choice: the backend treats an empty/omitted skill
|
||||
// list as "no skills" for custom agents (never "all skills").
|
||||
setFormError("");
|
||||
return nameInput.trim();
|
||||
}, [enabledSkills.length, nameInput, selectedSkills.length]);
|
||||
}, [nameInput]);
|
||||
|
||||
const ensureAgent = useCallback(async () => {
|
||||
const provided = validateForm();
|
||||
@@ -219,6 +229,7 @@ export default function NewAgentPage() {
|
||||
soul: soulInput,
|
||||
skills: selectedSkills,
|
||||
model: modelOverride,
|
||||
template_name: templateNameInput.trim(),
|
||||
});
|
||||
setAgent(updated);
|
||||
return updated;
|
||||
@@ -239,6 +250,7 @@ export default function NewAgentPage() {
|
||||
soul: soulInput,
|
||||
skills: selectedSkills,
|
||||
model: modelOverride,
|
||||
template_name: templateNameInput.trim(),
|
||||
});
|
||||
setAgentId(created.id);
|
||||
setAgent(created);
|
||||
@@ -268,6 +280,7 @@ export default function NewAgentPage() {
|
||||
modelInput,
|
||||
selectedSkills,
|
||||
soulInput,
|
||||
templateNameInput,
|
||||
t.agents.nameStepCheckError,
|
||||
t.agents.nameStepNetworkError,
|
||||
validateForm,
|
||||
@@ -540,6 +553,21 @@ export default function NewAgentPage() {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">入库模板名</label>
|
||||
<Input
|
||||
placeholder="例如:临时策略库(留空表示不支持入库)"
|
||||
value={templateNameInput}
|
||||
onChange={(event) =>
|
||||
setTemplateNameInput(event.currentTarget.value)
|
||||
}
|
||||
/>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
配置后,该智能体对话中生成的 Markdown
|
||||
文件右上角会出现"发布入库"按钮,可一键发送到知识入库接口。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">SOUL.md</label>
|
||||
<Textarea
|
||||
|
||||
@@ -3,8 +3,10 @@ import { Navigate, Route, Routes } from "react-router-dom";
|
||||
|
||||
import { PageSidebar } from "@/components/page-sidebar";
|
||||
import { PageSidebarDark } from "@/components/page-sidebar-dark";
|
||||
import { isChatsIframeWorkspacePath } from "@/core/page-layout/chats-iframe-route";
|
||||
import { readSidebarEnabled } from "@/core/page-layout/sidebar-enabled";
|
||||
import { useTheme } from "@/contexts/ThemeContext";
|
||||
import { useLocation } from "react-router-dom";
|
||||
|
||||
import WorkspaceRoutes from "./WorkspaceRoutes";
|
||||
import StrategyRoutes from "./StrategyRoutes";
|
||||
@@ -16,17 +18,20 @@ import NotebookRoutes from "./NotebookRoutes";
|
||||
function PageLayout() {
|
||||
const [collapsed, setCollapsed] = useState(false);
|
||||
const sidebarEnabled = useMemo(() => readSidebarEnabled(), []);
|
||||
const location = useLocation();
|
||||
const { theme } = useTheme();
|
||||
const isDark = theme === "dark";
|
||||
const pageSidebarAllowed =
|
||||
sidebarEnabled && !isChatsIframeWorkspacePath(location.pathname);
|
||||
|
||||
// h-full(100%)而非 h-screen(100vh):配合 globals.css 的 html/body/#root height:100%
|
||||
// 高度链,根布局跟随容器高度。全屏下 100% 解析到视口,与 h-screen 等价;无界等嵌套
|
||||
// 下容器不占满整屏时,高度才能正确收缩而非锁死整屏。
|
||||
return (
|
||||
<div className="h-full flex flex-col bg-muted/20">
|
||||
{sidebarEnabled && <Header collapsed={collapsed} />}
|
||||
{pageSidebarAllowed && <Header collapsed={collapsed} />}
|
||||
<div className="flex flex-1 overflow-hidden">
|
||||
{sidebarEnabled && (
|
||||
{pageSidebarAllowed && (
|
||||
isDark ? (
|
||||
<PageSidebarDark
|
||||
collapsed={collapsed}
|
||||
@@ -41,7 +46,7 @@ function PageLayout() {
|
||||
)}
|
||||
<main
|
||||
className={`flex-1 overflow-hidden ${
|
||||
!sidebarEnabled
|
||||
!pageSidebarAllowed
|
||||
? ""
|
||||
: isDark
|
||||
// 深色 sidebar:展开 118px(10 + 98 + 10 gap),收起 = 0 sidebar 完全消失,
|
||||
@@ -59,9 +64,9 @@ function PageLayout() {
|
||||
element={
|
||||
<WorkspaceRoutes
|
||||
pageSidebarCollapsed={collapsed}
|
||||
pageSidebarHidden={!sidebarEnabled}
|
||||
headerHidden={!sidebarEnabled}
|
||||
compactWorkspaceSidebar={sidebarEnabled}
|
||||
pageSidebarHidden={!pageSidebarAllowed}
|
||||
headerHidden={!pageSidebarAllowed}
|
||||
compactWorkspaceSidebar={pageSidebarAllowed}
|
||||
pageSidebarDark={isDark}
|
||||
/>
|
||||
}
|
||||
|
||||
@@ -44,6 +44,7 @@ import type {
|
||||
AdminLeaderboardUser,
|
||||
} from "@/core/admin/api";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
import { usePublicBackground } from "@/core/embed/background";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type UserRankTab = "activity" | "questions" | "tokens" | "skills" | "efficiency";
|
||||
@@ -151,6 +152,8 @@ export default function PublicLeaderboardPage() {
|
||||
const [query, setQuery] = useState("");
|
||||
const [userPage, setUserPage] = useState(1);
|
||||
const days = RANGE_DAYS;
|
||||
// 被第三方 iframe 嵌套时,允许嵌套方通过 ?bg=/?text= 或 postMessage 改背景/文字色。
|
||||
const pageBg = usePublicBackground();
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
@@ -222,7 +225,7 @@ export default function PublicLeaderboardPage() {
|
||||
}, [userPageCount]);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen w-full bg-[#FFF7F7] text-[#231815] dark:bg-[#011226] dark:text-white">
|
||||
<div className="min-h-screen w-full bg-[#FFF7F7] text-[#231815] dark:bg-[#011226] dark:text-white" style={pageBg}>
|
||||
<div className="mx-auto w-full max-w-6xl px-4 py-8 sm:px-6 sm:py-10">
|
||||
{/* 标题区:仅展示,不含任何操作按钮 */}
|
||||
<header className="mb-6">
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
getPublicDraftShareSnapshot,
|
||||
type PublicDraftSeatDelivery,
|
||||
} from "@/core/roundtable-draft-shares/api";
|
||||
import { usePublicBackground } from "@/core/embed/background";
|
||||
import { markdownComponents } from "@/roundtable-planning/components/markdown-components";
|
||||
|
||||
/** 各席位最终交付 —— 折叠手风琴(仿 HighFidelityReport 第二区块)。 */
|
||||
@@ -96,6 +97,8 @@ export default function PublicRoundtableSharePage({
|
||||
report?: boolean;
|
||||
}) {
|
||||
const { shareCode } = useParams<{ shareCode: string }>();
|
||||
// 嵌套方可用 ?bg=/?text= 或 postMessage 覆盖背景/文字色。
|
||||
const pageBg = usePublicBackground();
|
||||
|
||||
const { data, isLoading, isError } = useQuery({
|
||||
queryKey: ["public-roundtable-share", shareCode],
|
||||
@@ -107,7 +110,7 @@ export default function PublicRoundtableSharePage({
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="bg-background text-muted-foreground flex h-screen items-center justify-center gap-2 text-sm">
|
||||
<div className="bg-background text-muted-foreground flex h-screen items-center justify-center gap-2 text-sm" style={pageBg}>
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
正在加载分享内容…
|
||||
</div>
|
||||
@@ -116,7 +119,7 @@ export default function PublicRoundtableSharePage({
|
||||
|
||||
if (isError || !data) {
|
||||
return (
|
||||
<div className="bg-background flex h-screen flex-col items-center justify-center gap-2 px-6 text-center">
|
||||
<div className="bg-background flex h-screen flex-col items-center justify-center gap-2 px-6 text-center" style={pageBg}>
|
||||
<p className="text-lg font-medium">分享不可用</p>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
该分享链接不存在、已被撤销,或不是只读分享。
|
||||
@@ -128,7 +131,7 @@ export default function PublicRoundtableSharePage({
|
||||
// ── 报告页:整页沙箱 iframe 展示第 3 步结果绘制 ──────────────────────────────
|
||||
if (report) {
|
||||
return (
|
||||
<div className="bg-background flex h-screen flex-col">
|
||||
<div className="bg-background flex h-screen flex-col" style={pageBg}>
|
||||
<header className="flex shrink-0 items-center gap-2 border-b px-6 py-3">
|
||||
<h1 className="truncate text-base font-semibold">
|
||||
{data.title || "未命名会商"}
|
||||
@@ -162,7 +165,7 @@ export default function PublicRoundtableSharePage({
|
||||
const reportUrl = `${window.location.origin}${window.location.pathname}#/roundtable-share/${shareCode}/report`;
|
||||
|
||||
return (
|
||||
<div className="bg-[#fef6f6] flex h-screen flex-col text-slate-800">
|
||||
<div className="bg-[#fef6f6] flex h-screen flex-col text-slate-800" style={pageBg}>
|
||||
<header className="flex shrink-0 flex-col gap-1 border-b border-slate-100 bg-white px-6 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<h1 className="truncate text-base font-semibold">
|
||||
|
||||
@@ -43,6 +43,7 @@ import {
|
||||
import { MarkdownContent } from "@/components/workspace/messages/markdown-content";
|
||||
import { HtmlPreviewFrame } from "@/components/html-preview-frame";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
import { usePublicBackground } from "@/core/embed/background";
|
||||
import { downloadMarkdownAsDocx } from "@/core/scheduled-tasks/markdown-docx";
|
||||
import { reasoningPlugins } from "@/core/streamdown";
|
||||
import { cn } from "@/lib/utils";
|
||||
@@ -289,6 +290,8 @@ export default function PublicScheduledTaskPage() {
|
||||
const [runListWidth, setRunListWidth] = useState(RUN_LIST_DEFAULT_WIDTH);
|
||||
const dragStateRef = useRef<{ startX: number; startWidth: number } | null>(null);
|
||||
const queryClient = useQueryClient();
|
||||
// 嵌套方可用 ?bg=/?text= 或 postMessage 覆盖背景/文字色。
|
||||
const pageBg = usePublicBackground();
|
||||
|
||||
const { data, isLoading, isError, error } = useQuery({
|
||||
queryKey: ["public-scheduled-task", taskId],
|
||||
@@ -405,7 +408,7 @@ export default function PublicScheduledTaskPage() {
|
||||
|
||||
if (!taskId) {
|
||||
return (
|
||||
<div className="text-muted-foreground flex h-screen items-center justify-center text-sm">
|
||||
<div className="text-muted-foreground flex h-screen items-center justify-center text-sm" style={pageBg}>
|
||||
缺少任务 ID。请使用 <code className="mx-1">/public/scheduled-tasks/<task_id></code>。
|
||||
</div>
|
||||
);
|
||||
@@ -413,7 +416,7 @@ export default function PublicScheduledTaskPage() {
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="text-muted-foreground flex h-screen items-center justify-center gap-2 text-sm">
|
||||
<div className="text-muted-foreground flex h-screen items-center justify-center gap-2 text-sm" style={pageBg}>
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
正在加载任务记录...
|
||||
</div>
|
||||
@@ -422,7 +425,7 @@ export default function PublicScheduledTaskPage() {
|
||||
|
||||
if (isError) {
|
||||
return (
|
||||
<div className="text-destructive flex h-screen items-center justify-center text-sm">
|
||||
<div className="text-destructive flex h-screen items-center justify-center text-sm" style={pageBg}>
|
||||
加载失败:{error instanceof Error ? error.message : "未知错误"}
|
||||
</div>
|
||||
);
|
||||
@@ -430,7 +433,7 @@ export default function PublicScheduledTaskPage() {
|
||||
|
||||
return (
|
||||
<TooltipProvider delayDuration={150}>
|
||||
<div className="bg-muted/20 flex h-screen min-h-0 overflow-hidden p-4">
|
||||
<div className="bg-muted/20 flex h-screen min-h-0 overflow-hidden p-4" style={pageBg}>
|
||||
<div
|
||||
className="relative flex min-h-0 shrink-0 transition-[width] duration-200 ease-out"
|
||||
style={{ width: visibleRunListWidth }}
|
||||
@@ -1139,6 +1142,8 @@ function RunDetailPane({ run, taskId }: { run: PublicRun; taskId: string }) {
|
||||
|
||||
export function PublicScheduledTaskFullscreenPage() {
|
||||
const { taskId, runId } = useParams<{ taskId: string; runId: string }>();
|
||||
// 嵌套方可用 ?bg=/?text= 或 postMessage 覆盖背景/文字色。
|
||||
const pageBg = usePublicBackground();
|
||||
const [searchParams] = useSearchParams();
|
||||
const requestedTab = searchParams.get("tab");
|
||||
const tabKind: ContentTab["kind"] =
|
||||
@@ -1194,7 +1199,7 @@ export function PublicScheduledTaskFullscreenPage() {
|
||||
|
||||
return (
|
||||
<TooltipProvider delayDuration={150}>
|
||||
<div className="bg-background flex h-screen min-h-0 flex-col">
|
||||
<div className="bg-background flex h-screen min-h-0 flex-col" style={pageBg}>
|
||||
<div className="flex h-12 shrink-0 items-center gap-2 border-b px-3">
|
||||
<Button asChild variant="ghost" size="sm" className="h-8 px-2 text-xs">
|
||||
<a href={backHref}>
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
import { MessageList } from "@/components/workspace/messages";
|
||||
import { ThreadContext } from "@/components/workspace/messages/context";
|
||||
import { SubtasksProvider } from "@/core/tasks/context";
|
||||
import { usePublicBackground } from "@/core/embed/background";
|
||||
import { getPublicShareSnapshot } from "@/core/thread-shares/api";
|
||||
import type { AgentThreadState } from "@/core/threads";
|
||||
|
||||
@@ -71,6 +72,8 @@ function PublicShareBody({
|
||||
*/
|
||||
export default function PublicSharePage() {
|
||||
const { shareCode } = useParams<{ shareCode: string }>();
|
||||
// 嵌套方可用 ?bg=/?text= 或 postMessage 覆盖背景/文字色。
|
||||
const pageBg = usePublicBackground();
|
||||
|
||||
const { data, isLoading, isError } = useQuery({
|
||||
queryKey: ["public-share", shareCode],
|
||||
@@ -101,7 +104,7 @@ export default function PublicSharePage() {
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="bg-background text-muted-foreground flex h-screen items-center justify-center gap-2 text-sm">
|
||||
<div className="bg-background text-muted-foreground flex h-screen items-center justify-center gap-2 text-sm" style={pageBg}>
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
正在加载分享内容…
|
||||
</div>
|
||||
@@ -110,7 +113,7 @@ export default function PublicSharePage() {
|
||||
|
||||
if (isError || !data) {
|
||||
return (
|
||||
<div className="bg-background flex h-screen flex-col items-center justify-center gap-2 px-6 text-center">
|
||||
<div className="bg-background flex h-screen flex-col items-center justify-center gap-2 px-6 text-center" style={pageBg}>
|
||||
<p className="text-lg font-medium">分享不可用</p>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
该分享链接不存在、已被撤销,或不是只读分享。
|
||||
@@ -120,7 +123,7 @@ export default function PublicSharePage() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-background flex h-screen flex-col">
|
||||
<div className="bg-background flex h-screen flex-col" style={pageBg}>
|
||||
<header className="flex shrink-0 flex-col gap-1 border-b px-6 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<h1 className="truncate text-base font-semibold">
|
||||
|
||||
@@ -455,6 +455,11 @@ export default function StudioNotebookDetailPage() {
|
||||
return (
|
||||
<DocumentUploadDialogProvider
|
||||
searchSpace={{ id: notebook.id }}
|
||||
onClose={() => {
|
||||
// 关闭上传弹窗时刷新来源列表与 source_count(覆盖文件上传 / A·B·Y 导入等所有路径)
|
||||
void queryClient.invalidateQueries({ queryKey: ["studio", "sources"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["studio", "notebooks", studioToken] });
|
||||
}}
|
||||
onUploadSuccess={() => {
|
||||
void queryClient.invalidateQueries({ queryKey: ["studio", "sources"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["studio", "notebooks", studioToken] });
|
||||
|
||||
@@ -67,6 +67,7 @@ export function WorkspaceLayout({
|
||||
children,
|
||||
pageSidebarCollapsed,
|
||||
pageSidebarHidden = false,
|
||||
workspaceSidebarHidden = false,
|
||||
headerHidden = false,
|
||||
compactWorkspaceSidebar = false,
|
||||
wrapperOverflowHidden = false,
|
||||
@@ -76,6 +77,7 @@ export function WorkspaceLayout({
|
||||
children: ReactNode;
|
||||
pageSidebarCollapsed: boolean;
|
||||
pageSidebarHidden?: boolean;
|
||||
workspaceSidebarHidden?: boolean;
|
||||
headerHidden?: boolean;
|
||||
compactWorkspaceSidebar?: boolean;
|
||||
wrapperOverflowHidden?: boolean;
|
||||
@@ -109,7 +111,9 @@ export function WorkspaceLayout({
|
||||
data-page-sidebar-collapsed={pageSidebarCollapsed}
|
||||
defaultOpen
|
||||
>
|
||||
<WorkspaceSidebar compactChrome={compactWorkspaceSidebar} />
|
||||
{!workspaceSidebarHidden && (
|
||||
<WorkspaceSidebar compactChrome={compactWorkspaceSidebar} />
|
||||
)}
|
||||
<SidebarInset
|
||||
className={cn('min-w-0', insetOverflowHidden && 'overflow-hidden')}
|
||||
>
|
||||
@@ -205,7 +209,11 @@ export default function WorkspaceRoutes({
|
||||
<Route
|
||||
path="chats_iframe/new"
|
||||
element={
|
||||
<WorkspaceLayout {...layoutProps}>
|
||||
<WorkspaceLayout
|
||||
{...layoutProps}
|
||||
pageSidebarHidden
|
||||
workspaceSidebarHidden
|
||||
>
|
||||
<ChatRuntime>
|
||||
<IframeChatPage />
|
||||
</ChatRuntime>
|
||||
@@ -217,6 +225,8 @@ export default function WorkspaceRoutes({
|
||||
element={
|
||||
<WorkspaceLayout
|
||||
{...layoutProps}
|
||||
pageSidebarHidden
|
||||
workspaceSidebarHidden
|
||||
wrapperOverflowHidden
|
||||
insetOverflowHidden
|
||||
>
|
||||
|
||||
@@ -131,17 +131,6 @@ export function AgentDetailSheet({
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* 人设(SOUL.md) */}
|
||||
{agent.soul?.trim() && (
|
||||
<section className="space-y-1.5">
|
||||
<h4 className="text-[11px] font-bold uppercase tracking-wide text-muted-foreground">
|
||||
人设
|
||||
</h4>
|
||||
<pre className="whitespace-pre-wrap break-words rounded-md border border-border bg-muted/30 p-3 text-[12px] leading-relaxed text-foreground">
|
||||
{agent.soul}
|
||||
</pre>
|
||||
</section>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user