feat: 新增表格文件预览,优化知识图谱与 Agent 详情交互

- 新增 spreadsheet-preview 组件及 xlsx 解析工具,支持产物中的表格文件预览
- 优化知识图谱画布、详情面板及样式
- 调整 Agent 详情面板、聊天与消息列表交互

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
吉鑫升andClaude Opus 4.8 committed 2026-06-11 17:43:09 +08:00
1 parent 5daa4b3e20
commit 7d61bc09bc
18 files changed
+1092 -208

No files matched your search

@@ -2,6 +2,7 @@
import {
BotIcon,
CheckIcon,
GlobeIcon,
InfoIcon,
Loader2Icon,
@@ -15,6 +16,7 @@ import {
SquarePenIcon,
Trash2Icon,
UserRoundIcon,
XIcon,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { useMemo, useState, type ReactNode } from "react";
@@ -156,6 +158,13 @@ export function AgentDetailPanel({
const [mobileOpen, setMobileOpen] = useState(false);
const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState<AgentDraft | null>(null);
const [editingQuestionIndex, setEditingQuestionIndex] = useState<
number | null
>(null);
const [questionDraft, setQuestionDraft] = useState<AgentQuestion>({
title: "",
prompt: "",
});
const [pickerOpen, setPickerOpen] = useState(false);
const [deleteOpen, setDeleteOpen] = useState(false);
const [publishPickerOpen, setPublishPickerOpen] = useState(false);
@@ -200,6 +209,7 @@ export function AgentDetailPanel({
function beginEdit() {
if (!agent || !canEdit) return;
cancelQuestionEdit();
setDraft(draftFromAgent(agent));
setEditing(true);
}
@@ -210,6 +220,42 @@ export function AgentDetailPanel({
setPickerOpen(false);
}
function beginQuestionEdit(index: number, question: AgentQuestion) {
if (!canEdit) return;
setEditingQuestionIndex(index);
setQuestionDraft(question);
}
function cancelQuestionEdit() {
setEditingQuestionIndex(null);
setQuestionDraft({ title: "", prompt: "" });
}
async function saveQuestionEdit(index: number) {
if (!agent) return;
const nextQuestions = questions.map((question, questionIndex) =>
questionIndex === index
? {
title: questionDraft.title.trim() || questionDraft.prompt.trim(),
prompt: questionDraft.prompt.trim() || questionDraft.title.trim(),
}
: question,
);
const cleanedQuestions = nextQuestions.filter(
(question) => question.prompt.trim().length > 0,
);
try {
await updateAgent.mutateAsync({
id: agent.id,
request: { common_questions: cleanedQuestions },
});
toast.success("Updated");
cancelQuestionEdit();
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
}
}
async function saveEdit() {
if (!agent || !draft) return;
const trimmedName = draft.name.trim();
@@ -367,7 +413,14 @@ export function AgentDetailPanel({
</div>
) : (
<div className="flex items-center gap-1">
<Button size="sm" variant="outline" onClick={beginEdit}>
<Button
size="sm"
variant="outline"
className="hidden"
onClick={beginEdit}
aria-hidden="true"
tabIndex={-1}
>
<SquarePenIcon className="size-3.5" />
编辑
</Button>
@@ -544,21 +597,98 @@ export function AgentDetailPanel({
/>
) : (
<div className="flex flex-col gap-2">
{questions.map((question, index) => (
<button
key={index}
type="button"
disabled={disabled}
onClick={() => onAskQuestion(question.prompt)}
title={desensitize(question.prompt)}
className={cn(
"border-border/60 bg-background/60 hover:bg-accent hover:border-border w-full rounded-xl border px-3 py-2.5 text-left text-sm leading-relaxed transition-colors",
"disabled:cursor-not-allowed disabled:opacity-50",
)}
>
{desensitize(question.title)}
</button>
))}
{questions.map((question, index) => {
const isEditingThis = editingQuestionIndex === index;
return (
<div
key={index}
className="border-border/60 bg-background/60 rounded-xl border p-2"
>
{isEditingThis ? (
<div className="space-y-2">
<Input
value={questionDraft.title}
disabled={isSaving}
placeholder="Title"
onChange={(e) =>
setQuestionDraft({
...questionDraft,
title: e.currentTarget.value,
})
}
className="h-8 text-sm font-medium"
/>
<Textarea
value={questionDraft.prompt}
disabled={isSaving}
placeholder="Prompt"
onChange={(e) =>
setQuestionDraft({
...questionDraft,
prompt: e.currentTarget.value,
})
}
className="min-h-16 resize-none text-sm"
/>
<div className="flex justify-end gap-1.5">
<Button
type="button"
size="sm"
variant="outline"
onClick={cancelQuestionEdit}
disabled={isSaving}
>
<XIcon className="size-3.5" />
Cancel
</Button>
<Button
type="button"
size="sm"
onClick={() => void saveQuestionEdit(index)}
disabled={isSaving}
>
{isSaving ? (
<Loader2Icon className="size-3.5 animate-spin" />
) : (
<CheckIcon className="size-3.5" />
)}
Save
</Button>
</div>
</div>
) : (
<div className="flex items-center gap-2">
<button
type="button"
disabled={disabled}
onClick={() => onAskQuestion(question.prompt)}
title={desensitize(question.prompt)}
className={cn(
"hover:bg-accent min-w-0 flex-1 rounded-lg px-2 py-1.5 text-left text-sm leading-relaxed transition-colors",
"disabled:cursor-not-allowed disabled:opacity-50",
)}
>
<span className="block truncate">
{desensitize(question.title)}
</span>
</button>
{canEdit && (
<Button
type="button"
size="icon-sm"
variant="ghost"
onClick={() => beginQuestionEdit(index, question)}
disabled={isSaving}
aria-label="Edit question"
>
<SquarePenIcon className="size-3.5" />
</Button>
)}
</div>
)}
</div>
);
})}
</div>
)}
</Section>
@@ -76,6 +76,7 @@ import { useThread } from "../messages/context";
import { Tooltip } from "../tooltip";
import { useArtifacts } from "./context";
import { SpreadsheetPreview } from "./spreadsheet-preview";
const SANDBOX_RESUME_EVENT = "workspace:sandbox-resume-autoscroll";
@@ -137,6 +138,11 @@ export function ArtifactFileDetail({
const isSkillFile = useMemo(() => {
return filepath.endsWith(".skill");
}, [filepath]);
// .xlsx is a ZIP archive — the generic binary iframe preview renders its
// raw bytes as mojibake, so it gets a dedicated table preview instead.
const isSpreadsheetFile = useMemo(() => {
return /\.xlsx$/i.test(filepath);
}, [filepath]);
const { isCodeFile, language } = useMemo(() => {
if (useWriteFileStreaming) {
let nextLanguage = checkCodeFile(filepath).language;
@@ -174,13 +180,14 @@ export function ArtifactFileDetail({
const hasMultipleArtifacts = (artifacts?.length ?? 0) > 1;
const fileTypeLabel = useMemo(() => {
if (isImageFile(filepath)) return "IMG";
if (isSpreadsheetFile) return "XLSX";
if (isMermaidFile(filepath) || language === "mermaid") return "MMD";
if (language === "html") return "HTML";
if (language === "markdown") return "MD";
if (isSkillFile) return "SKILL";
if (language) return language.toUpperCase();
return "FILE";
}, [filepath, isSkillFile, language]);
}, [filepath, isSkillFile, isSpreadsheetFile, language]);
const [viewMode, setViewMode] = useState<"code" | "preview">("code");
const [allowAutoViewSwitch, setAllowAutoViewSwitch] = useState(true);
@@ -191,6 +198,9 @@ export function ArtifactFileDetail({
const [binaryPreviewUrl, setBinaryPreviewUrl] = useState<string | null>(
null,
);
const [spreadsheetData, setSpreadsheetData] = useState<ArrayBuffer | null>(
null,
);
const artifactContentRef = useRef<HTMLDivElement | null>(null);
const resumeButtonTimeoutRef = useRef<number | null>(null);
@@ -310,6 +320,7 @@ export function ArtifactFileDetail({
useEffect(() => {
if (isCodeFile) {
setSpreadsheetData(null);
setBinaryPreviewUrl((prev) => {
if (prev) URL.revokeObjectURL(prev);
return null;
@@ -325,6 +336,13 @@ export function ArtifactFileDetail({
urlOfArtifact({ filepath, threadId, isMock, publicShareCode }),
);
if (cancelled || !res.ok) return;
if (isSpreadsheetFile) {
const buffer = await res.arrayBuffer();
if (!cancelled) {
setSpreadsheetData(buffer);
}
return;
}
const blob = await res.blob();
if (cancelled) return;
const u = URL.createObjectURL(blob);
@@ -342,12 +360,13 @@ export function ArtifactFileDetail({
return () => {
cancelled = true;
setSpreadsheetData(null);
setBinaryPreviewUrl((prev) => {
if (prev) URL.revokeObjectURL(prev);
return null;
});
};
}, [filepath, threadId, isMock, isCodeFile, publicShareCode]);
}, [filepath, threadId, isMock, isCodeFile, isSpreadsheetFile, publicShareCode]);
const handlePauseAutoScroll = useCallback(() => {
if (!thread.isLoading || !autoScrollEnabled) {
@@ -766,7 +785,18 @@ export function ArtifactFileDetail({
/>
</div>
)}
{!isCodeFile && isSpreadsheetFile && (
spreadsheetData ? (
<SpreadsheetPreview data={spreadsheetData} />
) : (
<div className="text-muted-foreground flex size-full items-center justify-center gap-2 text-sm">
<LoaderIcon className="size-5 animate-spin" />
{t.common.loading}
</div>
)
)}
{!isCodeFile &&
!isSpreadsheetFile &&
(binaryPreviewUrl ? (
<iframe className="size-full bg-white" src={binaryPreviewUrl} />
) : (
@@ -0,0 +1,151 @@
"use client";
import { LoaderIcon, TriangleAlertIcon } from "lucide-react";
import { useEffect, useState } from "react";
import { parseXlsx, type ParsedWorksheet } from "@/core/utils/xlsx";
import { desensitize } from "@/lib/desensitize";
import { cn } from "@/lib/utils";
/**
* Renders an .xlsx ArrayBuffer as sheet tabs + an HTML table, replacing the
* old binary-blob iframe preview that showed the raw ZIP bytes as mojibake.
*/
export function SpreadsheetPreview({
data,
className,
}: {
data: ArrayBuffer;
className?: string;
}) {
const [sheets, setSheets] = useState<ParsedWorksheet[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [activeSheetIndex, setActiveSheetIndex] = useState(0);
useEffect(() => {
let cancelled = false;
setSheets(null);
setError(null);
setActiveSheetIndex(0);
parseXlsx(data)
.then((parsed) => {
if (!cancelled) {
setSheets(parsed);
}
})
.catch((err) => {
console.error("xlsx preview parse failed:", err);
if (!cancelled) {
setError(err instanceof Error ? err.message : "解析失败");
}
});
return () => {
cancelled = true;
};
}, [data]);
if (error) {
return (
<div
className={cn(
"text-muted-foreground flex size-full flex-col items-center justify-center gap-2 p-6 text-sm",
className,
)}
>
<TriangleAlertIcon className="size-5" />
<div>无法预览此表格文件:{error}</div>
<div className="text-xs">可点击右上角下载后用本地软件打开。</div>
</div>
);
}
if (!sheets) {
return (
<div
className={cn(
"text-muted-foreground flex size-full items-center justify-center gap-2 text-sm",
className,
)}
>
<LoaderIcon className="size-5 animate-spin" />
正在解析表格…
</div>
);
}
const activeSheet = sheets[activeSheetIndex] ?? sheets[0]!;
const [headerRow, ...bodyRows] = activeSheet.rows;
const columnCount = Math.max(
headerRow?.length ?? 0,
...activeSheet.rows.map((row) => row.length),
1,
);
return (
<div
data-artifact-preview-scroll
className={cn("flex size-full flex-col overflow-hidden", className)}
>
{sheets.length > 1 && (
<div className="border-border/70 flex shrink-0 items-center gap-1 overflow-x-auto border-b px-3 py-2">
{sheets.map((sheet, index) => (
<button
key={`${sheet.name}-${index}`}
type="button"
onClick={() => setActiveSheetIndex(index)}
className={cn(
"shrink-0 rounded-md px-2.5 py-1 text-xs transition-colors",
index === activeSheetIndex
? "bg-primary/10 text-primary font-medium"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
{desensitize(sheet.name)}
</button>
))}
</div>
)}
<div className="min-h-0 flex-1 overflow-auto p-3">
{activeSheet.rows.length === 0 ? (
<div className="text-muted-foreground flex h-full items-center justify-center text-sm">
(空工作表)
</div>
) : (
<table className="border-border w-max min-w-full border-collapse text-sm">
<thead>
<tr>
{Array.from({ length: columnCount }, (_, columnIndex) => (
<th
key={columnIndex}
className="border-border bg-muted/60 text-foreground sticky top-0 border px-3 py-1.5 text-left font-medium whitespace-pre-wrap"
>
{desensitize(headerRow?.[columnIndex] ?? "")}
</th>
))}
</tr>
</thead>
<tbody>
{bodyRows.map((row, rowIndex) => (
<tr key={rowIndex} className="even:bg-muted/30">
{Array.from({ length: columnCount }, (_, columnIndex) => (
<td
key={columnIndex}
className="border-border border px-3 py-1.5 align-top whitespace-pre-wrap"
>
{desensitize(row[columnIndex] ?? "")}
</td>
))}
</tr>
))}
</tbody>
</table>
)}
{activeSheet.truncated && (
<div className="text-muted-foreground py-2 text-center text-xs">
表格过大,仅预览部分内容;完整数据请下载文件查看。
</div>
)}
</div>
</div>
);
}
@@ -33,7 +33,7 @@ import {
ArtifactFileList,
useArtifacts,
} from "../artifacts";
import { useThread } from "../messages/context";
import { ReferenceBatchesContext, useThread } from "../messages/context";
import { SkillDisplaySources } from "../skill-display-sources";
const CLOSE_MODE = { chat: 100, artifacts: 0 };
@@ -362,10 +362,15 @@ const ChatBox: React.FC<{
}, [sidePanelOpen]);
if (disableArtifacts) {
return <>{children}</>;
return (
<ReferenceBatchesContext.Provider value={referenceBatches}>
{children}
</ReferenceBatchesContext.Provider>
);
}
return (
<ReferenceBatchesContext.Provider value={referenceBatches}>
<ResizablePanelGroup
id={`${resizableIdBase}-panels`}
orientation="horizontal"
@@ -490,6 +495,7 @@ const ChatBox: React.FC<{
</div>
</ResizablePanel>
</ResizablePanelGroup>
</ReferenceBatchesContext.Provider>
);
};
@@ -1,6 +1,7 @@
import type { BaseStream } from "@langchain/langgraph-sdk/react";
import { createContext, useContext } from "react";
import type { RuntimeDisplaySource } from "@/core/skill-display/runtime";
import type { AgentThreadState } from "@/core/threads";
export interface ThreadContextType {
@@ -26,3 +27,18 @@ export function useThread() {
}
return context;
}
/**
* One turn's reference sources, keyed to the assistant message that answered
* the turn. Provided by ChatBox so inline citation rendering and the
* right-side reference panel always resolve `[n]` against the SAME sources
* (the panel prefers backend reference batches, which the per-message
* frontend collection in MessageList knows nothing about).
*/
export interface ReferenceBatch {
id: string;
assistant_message_id?: string;
sources: RuntimeDisplaySource[];
}
export const ReferenceBatchesContext = createContext<ReferenceBatch[]>([]);
@@ -37,7 +37,7 @@ import { resolveAllowMultiple } from "@/roundtable-planning/lib/clarification";
import { ArtifactFileList } from "../artifacts/artifact-file-list";
import { StreamingIndicator } from "../streaming-indicator";
import { ThreadContext } from "./context";
import { ReferenceBatchesContext, ThreadContext } from "./context";
import { MarkdownContent } from "./markdown-content";
import { MessageGroup } from "./message-group";
import { MessageListItem } from "./message-list-item";
@@ -146,6 +146,11 @@ export function MessageList({
() => (ragModeEnabled ? buildSkillDisplayMap(skills) : new Map()),
[ragModeEnabled, skills],
);
// Same per-turn reference batches the right-side panel renders (backend
// batches preferred). Inline [n] tokens must resolve against these so badge
// numbering matches the panel, and so citations still render when the
// frontend tool-message scan below comes up empty (e.g. after a reload).
const referenceBatches = useContext(ReferenceBatchesContext);
// Track which clarification messages are still awaiting an answer.
// Pending = clarification tool messages that appear after the last human message
@@ -270,16 +275,24 @@ export function MessageList({
{groupMessages(messages, (group) => {
if (group.type === "human" || group.type === "assistant") {
return group.messages.map((msg) => {
const displaySources =
const isAssistantMessage =
ragModeEnabled &&
group.type === "assistant" &&
msg.type === "ai"
? collectRuntimeDisplaySources(messages, skillDisplayMap, {
msg.type === "ai";
const batchSources = isAssistantMessage
? referenceBatches.find(
(batch) => batch.assistant_message_id === msg.id,
)?.sources ?? []
: [];
const displaySources = isAssistantMessage
? batchSources.length > 0
? batchSources
: collectRuntimeDisplaySources(messages, skillDisplayMap, {
afterMessageId: findPreviousHumanMessageId(messages, msg.id),
beforeMessageId: msg.id,
includeBeforeMessage: true,
})
: [];
: [];
return (
<MessageListItem
key={`${group.id}/${msg.id}`}
@@ -169,7 +169,7 @@ export function WorkspaceNavChatList({
>
<Link href="/page/workspace/knowledge">
<BookOpen />
<span>知识库</span>
<span>问答梳理</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>