Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat(web): reuse the assistant session menu on infographic notes

tianma-if89660919200b
diff --git a/apps/web/src/components/InfographicEditorPane.test.mjs b/apps/web/src/components/InfographicEditorPane.test.mjs
index 392fe508..58a9b661 100644
--- a/apps/web/src/components/InfographicEditorPane.test.mjs
+++ b/apps/web/src/components/InfographicEditorPane.test.mjs
@@ -36,6 +36,9 @@ describe("infographic editor header", () => {
expect(source).toContain("<AiSidebar");
expect(source).toContain("infographic={infographicAssistant}");
expect(source).toContain("nextInfographicNoteTitle");
+ expect(source).toContain("infographicSessionHistory");
+ expect(source).toContain("onCreateSession");
+ expect(source).toContain("activeSessionId");
expect(source).toContain("edgeever-infographic-preview");
});
});
diff --git a/apps/web/src/components/InfographicEditorPane.tsx b/apps/web/src/components/InfographicEditorPane.tsx
index f1380e03..e38c0e3c 100644
--- a/apps/web/src/components/InfographicEditorPane.tsx
+++ b/apps/web/src/components/InfographicEditorPane.tsx
@@ -25,6 +25,8 @@ import { readAiSidebarAdapter, readAiSidebarSource } from "@/lib/desktop-acp";
import { buildInfographicLocalAgentContext, collectInfographicLocalAgentText, infographicLocalAgentErrorKey, parseInfographicLocalReply } from "@/lib/infographic-local-agent";
import { formatShortcutBinding, getNotebookMoveOptions, type ShortcutSettings } from "@/lib/app-helpers";
import { createLocalEditSession, requiresLocalEditSession } from "@/components/editor/editor-pane-helpers";
+import { createClientUuid } from "@/lib/client-id";
+import { infographicSessionHistory, infographicSessionStamp, infographicSessionThreads, infographicTurnSessionId, resolveInfographicSessionId } from "@/lib/infographic-sessions";
import { canvasToPngBlob, downloadBlob, frameInfographicExportSvg, infographicExportBasename, rasterizeInfographicSvg, readInfographicSheetColor } from "@/lib/infographic-image-export";
import { buildInfographicSyntax, buildOfficialInfographicSyntax, infographicAgentCandidates, infographicNoteTitleIsAutomatic, infographicSyntaxTitle, INFOGRAPHIC_TEMPLATES, nextInfographicNoteTitle, parseGeneratedOfficialData, type InfographicItem } from "@/lib/infographic-generation";
import { statusSettleMotion } from "@/lib/motion";
@@ -43,6 +45,9 @@ type Props = {
onToggleDesktopFocusMode: () => void;
aiAssistantOpenToken: number;
shortcutSettings: ShortcutSettings;
+ companionAvailable?: boolean;
+ beforeCompanionApply?: () => Promise<void>;
+ onCompanionNotesChanged?: () => Promise<void>;
onOpenCompanionNote?: (id: string, notebookId: string) => void;
};
@@ -199,6 +204,9 @@ export default function InfographicEditorPane({
onToggleDesktopFocusMode,
aiAssistantOpenToken,
shortcutSettings,
+ companionAvailable = false,
+ beforeCompanionApply,
+ onCompanionNotesChanged,
onOpenCompanionNote,
}: Props) {
const { t, i18n } = useTranslation();
@@ -214,6 +222,7 @@ export default function InfographicEditorPane({
const [tagsText, setTagsText] = useState(initialTags);
const [syntax, setSyntax] = useState(parsed?.syntax ?? "");
const [history, setHistory] = useState<InfographicConversationTurn[]>(parsed?.history ?? []);
+ const [activeSessionId, setActiveSessionId] = useState<string | null>(parsed?.activeSessionId ?? null);
const [activeTurn, setActiveTurn] = useState<{ prompt: string; response: string; template?: string; decision?: string; question?: string } | null>(null);
const [aiAssistantOpen, setAiAssistantOpenState] = useState(readAiSidebarOpen);
const [previousGeneration, setPreviousGeneration] = useState<{ title: string; syntax: string; turnId: string } | null>(null);
@@ -223,7 +232,7 @@ export default function InfographicEditorPane({
const [renderError, setRenderError] = useState<string | null>(null);
const [previewReady, setPreviewReady] = useState(false);
const [ready, setReady] = useState(false);
- const [savedSnapshot, setSavedSnapshot] = useState(JSON.stringify([memo.title ?? "", parsed?.syntax ?? "", parsed?.history ?? [], initialTags]));
+ const [savedSnapshot, setSavedSnapshot] = useState(JSON.stringify([memo.title ?? "", parsed?.syntax ?? "", parsed?.history ?? [], initialTags, parsed?.activeSessionId ?? null]));
const [savedHistorySnapshot, setSavedHistorySnapshot] = useState(JSON.stringify(parsed?.history ?? []));
const [galleryDialogOpen, setGalleryDialogOpen] = useState(false);
const [mobileNotebookSheetOpen, setMobileNotebookSheetOpen] = useState(false);
@@ -239,7 +248,8 @@ export default function InfographicEditorPane({
const memoRef = useRef(memo);
const tagsRef = useRef(initialTags);
const saveRef = useRef<() => boolean | Promise<boolean>>(() => false);
- const snapshot = JSON.stringify([title, syntax, history, tagsText]);
+ const snapshotSessionId = readOnly ? (parsed?.activeSessionId ?? null) : activeSessionId;
+ const snapshot = JSON.stringify([title, syntax, history, tagsText, snapshotSessionId]);
const notebookOptions = useMemo(() => getNotebookMoveOptions(notebooks), [notebooks]);
const dirty = snapshot !== savedSnapshot;
const historyDirty = JSON.stringify(history) !== savedHistorySnapshot;
@@ -395,7 +405,7 @@ export default function InfographicEditorPane({
}
const currentMemo = memoRef.current;
const currentSnapshot = snapshot;
- const document: InfographicDocument = { schemaVersion: 1, syntax, ...(history.length ? { history } : {}) };
+ const document: InfographicDocument = { schemaVersion: 1, syntax, ...(history.length ? { history } : {}), ...(activeSessionId ? { activeSessionId } : {}) };
setSaving(true); setError(null);
try {
const result = await repository.updateMemo(currentMemo, {
@@ -483,6 +493,8 @@ export default function InfographicEditorPane({
let response = "";
let proposal: { template: string; data: Record<string, unknown>; explanation: string } | null = null;
let question = "";
+ const viewingSessionId = resolveInfographicSessionId(history, activeSessionId);
+ const sessionStamp = infographicSessionStamp(viewingSessionId);
try {
const { parseSyntax, getTemplate, getTemplates } = await import("@antv/infographic");
const existingOptions = parseSyntax(syntax).options;
@@ -492,8 +504,8 @@ export default function InfographicEditorPane({
if (currentContent.length > INFOGRAPHIC_AGENT_SOURCE_MAX_LENGTH) throw new Error(t("infographic.contentTooLarge"));
const candidates = infographicAgentCandidates(promptText, getTemplates(), existingTemplate);
if (!candidates.length) throw new Error(t("infographic.aiInvalidResponse"));
- const agentHistory = history.filter((turn) => !turn.undoneAt && turn.kind !== "failed")
- .slice(-12).map((turn) => ({ prompt: turn.prompt, response: `${turn.kind === "clarified" ? "No infographic change was applied. Clarification: " : ""}${turn.response || turn.resultTitle}${turn.decision ? `\nDecision: ${turn.decision}` : ""}`.slice(0, 2000) }));
+ const agentHistory = infographicSessionHistory(history, viewingSessionId)
+ .map((turn) => ({ prompt: turn.prompt, response: `${turn.kind === "clarified" ? "No infographic change was applied. Clarification: " : ""}${turn.response || turn.resultTitle}${turn.decision ? `\nDecision: ${turn.decision}` : ""}`.slice(0, 2000) }));
if (readAiSidebarSource() === "local") {
const adapter = readAiSidebarAdapter();
if (!adapter) throw new Error(t("aiAssistant.sidebar.localMissing"));
@@ -580,17 +592,18 @@ export default function InfographicEditorPane({
id: turnId, prompt: promptText, createdAt: new Date().toISOString(),
kind: syntax.trim() ? "refined" : "generated", resultTitle: generatedTitle,
response: (response.trim() || selected.explanation).slice(0, 4000), decision: selected.explanation.slice(0, 500), template: selected.template,
+ ...sessionStamp,
}]);
setSyntax(candidate);
if (nextTitle !== title) setTitle(nextTitle);
} else if (question) {
- setHistory((turns) => [...turns, { id: crypto.randomUUID(), prompt: promptText, createdAt: new Date().toISOString(), kind: "clarified", resultTitle: "", response: (response.trim() || question).slice(0, 4000) }]);
+ setHistory((turns) => [...turns, { id: crypto.randomUUID(), prompt: promptText, createdAt: new Date().toISOString(), kind: "clarified", resultTitle: "", response: (response.trim() || question).slice(0, 4000), ...sessionStamp }]);
} else throw new Error(t("infographic.aiInvalidResponse"));
} catch (caught) {
if (controller.signal.aborted) throw caught;
const messageText = caught instanceof Error ? caught.message : t("infographic.aiError");
setError(messageText);
- setHistory((turns) => [...turns, { id: crypto.randomUUID(), prompt: promptText, createdAt: new Date().toISOString(), kind: "failed", resultTitle: "", response: response.slice(0, 4000), error: messageText.slice(0, 1000) }]);
+ setHistory((turns) => [...turns, { id: crypto.randomUUID(), prompt: promptText, createdAt: new Date().toISOString(), kind: "failed", resultTitle: "", response: response.slice(0, 4000), error: messageText.slice(0, 1000), ...sessionStamp }]);
throw caught instanceof Error ? caught : new Error(messageText);
} finally { if (generationControllerRef.current === controller) generationControllerRef.current = null; setActiveTurn(null); setGenerating(false); }
};
@@ -618,16 +631,27 @@ export default function InfographicEditorPane({
const saveStatus = saving ? "saving" : dirty ? "unsaved" : "saved";
const saveLabel = t(`editor.saveState.${saveStatus}`);
const saveStatusClassName = saveStatus === "saved" ? "text-slate-400" : "bg-slate-100 text-slate-700";
+ const viewingSessionId = resolveInfographicSessionId(history, activeSessionId);
const infographicAssistant: InfographicSidebarController = {
turns: history,
activeTurn,
generating,
readOnly,
- canUndo: Boolean(previousGeneration),
+ canUndo: Boolean(previousGeneration && history.some((turn) => turn.id === previousGeneration.turnId && infographicTurnSessionId(turn) === viewingSessionId && !turn.undoneAt)),
hasGraphic: Boolean(syntax.trim()),
+ activeSessionId,
onSubmit: generate,
onUndo: undoGeneration,
onStop: () => generationControllerRef.current?.abort(),
+ onSelectSession: (sessionId) => {
+ if (generating) return;
+ setActiveSessionId(sessionId);
+ },
+ onCreateSession: () => {
+ if (generating || readOnly) return;
+ if (!infographicSessionThreads(history).some((thread) => thread.id === viewingSessionId)) return;
+ setActiveSessionId(createClientUuid());
+ },
};
return <div className="relative flex h-full min-h-0 min-w-0 bg-card text-foreground">
@@ -782,7 +806,9 @@ export default function InfographicEditorPane({
<AiSidebar
open={aiAssistantOpen}
onOpenChange={setAiSidebarOpen}
- companionAvailable={false}
+ companionAvailable={companionAvailable}
+ beforeCompanionApply={beforeCompanionApply}
+ onCompanionNotesChanged={onCompanionNotesChanged}
contentMarkdown={syntax}
memoId={memo.id}
notebookId={memo.notebookId}
diff --git a/apps/web/src/components/WorkspaceApp.tsx b/apps/web/src/components/WorkspaceApp.tsx
index 8a95b9be..c5937b00 100644
--- a/apps/web/src/components/WorkspaceApp.tsx
+++ b/apps/web/src/components/WorkspaceApp.tsx
@@ -3676,6 +3676,15 @@ export const WorkspaceApp = ({
onToggleDesktopFocusMode={toggleDesktopFocusMode}
aiAssistantOpenToken={noteAiAssistantOpenToken}
shortcutSettings={shortcutSettings}
+ companionAvailable={authRequired && Boolean(user) && !demoMode}
+ beforeCompanionApply={async () => {
+ const { assertCompanionChangesSynced } = await import("@/lib/companion-actions");
+ await assertCompanionChangesSynced(localDataScope);
+ }}
+ onCompanionNotesChanged={async () => {
+ const result = await refreshWorkspaceFromServer("manual");
+ if ("skipped" in result && result.skipped) throw new Error("Workspace refresh was skipped.");
+ }}
onOpenCompanionNote={handleOpenPluginNote}
onSaved={async (memo) => {
await putLocalMemo(localDataScope, memo);
diff --git a/apps/web/src/components/ai-sidebar/AiSidebar.tsx b/apps/web/src/components/ai-sidebar/AiSidebar.tsx
index 42b101c9..36fe10c3 100644
--- a/apps/web/src/components/ai-sidebar/AiSidebar.tsx
+++ b/apps/web/src/components/ai-sidebar/AiSidebar.tsx
@@ -2,17 +2,10 @@ import { useCallback, useEffect, useMemo, useRef, useState, type ClipboardEvent,
import { AnimatePresence } from "motion/react";
import * as m from "motion/react-m";
import { useTranslation } from "react-i18next";
-import { ArrowUp, Check, ChevronDown, Download, FileText, Loader2, PanelRightClose, Plus, Search, Sparkles, X } from "lucide-react";
+import { ArrowUp, Download, FileText, Loader2, PanelRightClose, Plus, Sparkles, X } from "lucide-react";
import type { CompanionAction, CompanionAnswer, CompanionEvent, CompanionFailureDiagnostics, CompanionTurn, CompanionTurnInput } from "@edgeever/shared";
import { buildRevisionDiffRows, companionFailureDiagnostics, createMemoLinkHref } from "@edgeever/shared";
import { Button } from "@/components/ui/button";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import {
Attachment,
@@ -70,7 +63,6 @@ import {
parseLocalAgentTurns,
resolveLocalAgentThreadId,
saveLocalAgentTurns,
- type ChatThreadSummary,
} from "@/lib/local-agent-threads";
import { LocalAgentImageStore } from "@/lib/local-agent-images";
import { appendLocalAgentText } from "@/lib/local-agent-response";
@@ -89,6 +81,7 @@ import { CompanionCreatedNoteLinks } from "../CompanionCreatedNoteLinks";
import { AiSidebarMessage } from "./AiSidebarMessage";
import { AiSidebarLocalProcess } from "./AiSidebarLocalProcess";
import { AiAgentSelector } from "./AiAgentSelector";
+import { AiSidebarThreadMenu } from "./AiSidebarThreadMenu";
import { InfographicSidebarSession, type InfographicSidebarController } from "./InfographicSidebarSession";
import { memoIdFromSidebarLinkEvent } from "./sidebar-note-links";
@@ -239,7 +232,6 @@ export const readAiSidebarWidth = () => {
};
const THREAD_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
-const THREAD_RECENCY_MS = 30 * 24 * 60 * 60 * 1000;
const readAiSidebarThread = () => {
const value = readStorage(AI_SIDEBAR_THREAD_KEY);
@@ -250,108 +242,6 @@ const writeAiSidebarThread = (threadId: string) => {
writeStorage(AI_SIDEBAR_THREAD_KEY, threadId);
};
-const sidebarThreadLabel = (title: string) => {
- const clause = title.split(/[,。!?!?;;::\n]/)[0]?.trim() || title;
- return clause.length >= 2 ? clause : title;
-};
-
-function AiSidebarThreadMenu({
- threads,
- threadId,
- title,
- onSelect,
- onCreate,
-}: {
- threads: ChatThreadSummary[];
- threadId: string;
- title: string;
- onSelect: (threadId: string) => void;
- onCreate: () => void;
-}) {
- const { t } = useTranslation();
- const [query, setQuery] = useState("");
- const [searching, setSearching] = useState(false);
- const normalized = query.trim().toLocaleLowerCase();
- const visible = threads.filter((thread) => !normalized || thread.title.toLocaleLowerCase().includes(normalized));
- const cutoff = Date.now() - THREAD_RECENCY_MS;
- const recent = visible.filter((thread) => Date.parse(thread.updatedAt) >= cutoff);
- const older = visible.filter((thread) => Date.parse(thread.updatedAt) < cutoff);
- const searchOnRecent = recent.length > 0 || older.length === 0;
-
- const renderGroup = (label: string, items: ChatThreadSummary[], withSearch: boolean) => {
- if (!items.length) return null;
- return (
- <div>
- {searching ? null : (
- <div className="flex items-center gap-2 px-2 py-1.5 text-xs text-slate-500">
- <span className="min-w-0 flex-1">{label}</span>
- {withSearch ? (
- <button
- type="button"
- className="rounded-sm p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-700"
- aria-label={t("aiAssistant.sidebar.historySearch")}
- onClick={() => setSearching(true)}
- >
- <Search className="size-3.5" aria-hidden="true" />
- </button>
- ) : null}
- </div>
- )}
- {items.map((thread) => (
- <DropdownMenuItem
- key={thread.id}
- className="justify-between gap-3 py-2 text-sm"
- onSelect={() => onSelect(thread.id)}
- >
- <span className="truncate">{thread.title}</span>
- {thread.id === threadId ? <Check className="size-4 shrink-0 text-slate-700" aria-hidden="true" /> : <span className="size-4 shrink-0" aria-hidden="true" />}
- </DropdownMenuItem>
- ))}
- </div>
- );
- };
-
- return (
- <DropdownMenu onOpenChange={(open) => { if (!open) { setQuery(""); setSearching(false); } }}>
- <DropdownMenuTrigger asChild>
- <button
- type="button"
- className="flex h-8 min-w-0 max-w-52 items-center gap-1 rounded-full px-2 text-left text-[13px] font-medium text-slate-700 hover:bg-slate-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400"
- data-ai-thread-menu=""
- aria-label={`${title} · ${t("aiAssistant.sidebar.history")}`}
- >
- <Sparkles className="size-3.5 shrink-0 text-slate-500" aria-hidden="true" />
- <span className="min-w-0 truncate">{sidebarThreadLabel(title)}</span>
- <ChevronDown className="size-3.5 shrink-0 text-slate-400" aria-hidden="true" />
- </button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="start" className="z-[60] max-h-80 w-72 overflow-y-auto p-1.5">
- {searching ? (
- <input
- autoFocus
- value={query}
- placeholder={t("aiAssistant.sidebar.historySearch")}
- className="mb-1 h-8 w-full rounded-md border border-slate-200 bg-card px-2 text-sm text-slate-950 outline-none placeholder:text-slate-400"
- aria-label={t("aiAssistant.sidebar.historySearch")}
- onChange={(event) => setQuery(event.target.value)}
- onKeyDown={(event) => event.stopPropagation()}
- />
- ) : null}
- <DropdownMenuItem className="gap-2 py-2 text-sm" onSelect={onCreate}>
- <Plus className="size-3.5 shrink-0" aria-hidden="true" />
- {t("aiAssistant.sidebar.newThread")}
- </DropdownMenuItem>
- {threads.length ? <DropdownMenuSeparator /> : null}
- {renderGroup(t("aiAssistant.sidebar.historyRecent"), recent, searchOnRecent && !searching)}
- {renderGroup(t("aiAssistant.sidebar.historyOlder"), older, !searchOnRecent && !searching)}
- {normalized && !visible.length ? (
- <p className="px-2 py-3 text-sm text-slate-500">{t("aiAssistant.sidebar.historyEmpty")}</p>
- ) : null}
- </DropdownMenuContent>
- </DropdownMenu>
- );
-}
-
const readLocalAdapter = readAiSidebarAdapter;
const attachmentServerCode = (code: string | undefined) => (
@@ -760,6 +650,7 @@ function AiSidebarSession({
beforeCompanionApply,
onCompanionNotesChanged,
onOpenCompanionNote,
+ infographic,
addFilesRef,
onStopReady,
}: AiSidebarProps & {
@@ -782,6 +673,8 @@ function AiSidebarSession({
) ?? createClientUuid()
));
const [threadId, setThreadId] = useState<string>(() => readAiSidebarThread() ?? createClientUuid());
+ const graphicAvailable = Boolean(infographic);
+ const [graphicOpen, setGraphicOpen] = useState(graphicAvailable);
const [attachments, setAttachments] = useState<PendingAttachment[]>([]);
const [attachmentError, setAttachmentError] = useState<string | null>(null);
const [conflicts, setConflicts] = useState<Record<string, string>>({});
@@ -816,7 +709,8 @@ function AiSidebarSession({
useEffect(() => {
setIncludeCurrentNote(false);
- }, [memoId]);
+ setGraphicOpen(graphicAvailable);
+ }, [graphicAvailable, memoId]);
const explainDiagnostics = useCallback((diagnostics?: CompanionFailureDiagnostics) => {
if (!diagnostics) return "";
@@ -1530,6 +1424,7 @@ function AiSidebarSession({
const menuThreads = source === "builtin" ? companionThreads : localThreadList;
const menuThreadId = source === "builtin" ? threadId : localThreadId;
const threadTitle = menuThreads.find((thread) => thread.id === menuThreadId)?.title || t("aiAssistant.sidebar.newThread");
+ const graphicTitle = t("aiAssistant.sidebar.currentInfographic");
const rememberThread = (id: string) => {
threadPinned.current = true;
setThreadId(id);
@@ -1541,6 +1436,19 @@ function AiSidebarSession({
setError(null);
writeStorage(AI_SIDEBAR_LOCAL_THREAD_KEY, id);
};
+ const openAssistantThread = (id: string) => {
+ setGraphicOpen(false);
+ if (source === "local") selectLocalThread(id);
+ else rememberThread(id);
+ };
+ const createAssistantThread = () => {
+ setGraphicOpen(false);
+ if (source === "local") {
+ if (localTurns.some((turn) => turn.threadId === localThreadId)) selectLocalThread(createClientUuid());
+ return;
+ }
+ if (companionThreads.some((thread) => thread.id === threadId)) rememberThread(createClientUuid());
+ };
const threadTurns = turns.filter((turn) => turn.threadId === threadId).slice().reverse();
const localThreadTurns = localTurns.filter((turn) => turn.threadId === localThreadId);
const visibleCompanion = source === "builtin";
@@ -1588,16 +1496,13 @@ function AiSidebarSession({
<div className="flex h-12 shrink-0 items-center gap-2 border-b border-slate-200 px-2">
<AiSidebarThreadMenu
threads={menuThreads}
- threadId={menuThreadId}
- title={threadTitle}
- onSelect={source === "builtin" ? rememberThread : selectLocalThread}
- onCreate={() => {
- if (source === "local") {
- if (localTurns.some((turn) => turn.threadId === localThreadId)) selectLocalThread(createClientUuid());
- return;
- }
- if (companionThreads.some((thread) => thread.id === threadId)) rememberThread(createClientUuid());
- }}
+ threadId={graphicOpen ? "" : menuThreadId}
+ title={graphicOpen ? (noteTitle?.trim() || graphicTitle) : threadTitle}
+ pinned={graphicAvailable ? { id: "infographic", title: graphicTitle } : null}
+ pinnedActive={graphicOpen}
+ onSelectPinned={() => setGraphicOpen(true)}
+ onSelect={openAssistantThread}
+ onCreate={createAssistantThread}
/>
<Button
type="button"
@@ -1611,6 +1516,13 @@ function AiSidebarSession({
<PanelRightClose className="h-4 w-4" />
</Button>
</div>
+ {graphicOpen && infographic ? (
+ <InfographicSidebarSession
+ session={infographic}
+ onOpenNote={onOpenCompanionNote}
+ />
+ ) : (
+ <>
{error ? <p role="alert" className="shrink-0 px-3 pt-2 text-xs leading-5 text-rose-700">{error}</p> : null}
<Conversation key={menuThreadId} className="min-h-0 flex-1">
<ConversationContent className={sidebarThreadClassName}>
@@ -1805,6 +1717,8 @@ function AiSidebarSession({
/>
</PromptInputProvider>
</div>
+ </>
+ )}
</div>
);
}
@@ -1926,16 +1840,7 @@ export function AiSidebar(props: AiSidebarProps) {
</Tooltip>
</TooltipProvider>
) : null}
- {props.infographic ? (
- <InfographicSidebarSession
- session={props.infographic}
- noteTitle={props.noteTitle}
- onOpenChange={onOpenChange}
- onOpenNote={props.onOpenCompanionNote}
- />
- ) : (
- <AiSidebarSession {...props} addFilesRef={addFilesRef} onStopReady={onStopReady} />
- )}
+ <AiSidebarSession {...props} addFilesRef={addFilesRef} onStopReady={onStopReady} />
</div>
</m.aside>
</>
diff --git a/apps/web/src/components/ai-sidebar/AiSidebarThreadMenu.tsx b/apps/web/src/components/ai-sidebar/AiSidebarThreadMenu.tsx
new file mode 100644
index 00000000..c265e80a
--- /dev/null
+++ b/apps/web/src/components/ai-sidebar/AiSidebarThreadMenu.tsx
@@ -0,0 +1,122 @@
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Check, ChevronDown, Plus, Search, Sparkles } from "lucide-react";
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
+import type { ChatThreadSummary } from "@/lib/local-agent-threads";
+
+const THREAD_RECENCY_MS = 30 * 24 * 60 * 60 * 1000;
+
+const sidebarThreadLabel = (title: string) => {
+ const clause = title.split(/[,。!?!?;;::\n]/)[0]?.trim() || title;
+ return clause.length >= 2 ? clause : title;
+};
+
+export function AiSidebarThreadMenu({
+ threads,
+ threadId,
+ title,
+ onSelect,
+ onCreate,
+ pinned,
+ pinnedActive = false,
+ onSelectPinned,
+}: {
+ threads: ChatThreadSummary[];
+ threadId: string;
+ title: string;
+ onSelect: (threadId: string) => void;
+ onCreate: () => void;
+ pinned?: { id: string; title: string } | null;
+ pinnedActive?: boolean;
+ onSelectPinned?: () => void;
+}) {
+ const { t } = useTranslation();
+ const [query, setQuery] = useState("");
+ const [searching, setSearching] = useState(false);
+ const normalized = query.trim().toLocaleLowerCase();
+ const visible = threads.filter((thread) => !normalized || thread.title.toLocaleLowerCase().includes(normalized));
+ const cutoff = Date.now() - THREAD_RECENCY_MS;
+ const recent = visible.filter((thread) => Date.parse(thread.updatedAt) >= cutoff);
+ const older = visible.filter((thread) => Date.parse(thread.updatedAt) < cutoff);
+ const searchOnRecent = recent.length > 0 || older.length === 0;
+ const pinnedVisible = Boolean(pinned && (!normalized || pinned.title.toLocaleLowerCase().includes(normalized)));
+
+ const renderGroup = (label: string, items: ChatThreadSummary[], withSearch: boolean) => {
+ if (!items.length) return null;
+ return (
+ <div>
+ {searching ? null : (
+ <div className="flex items-center gap-2 px-2 py-1.5 text-xs text-slate-500">
+ <span className="min-w-0 flex-1">{label}</span>
+ {withSearch ? (
+ <button
+ type="button"
+ className="rounded-sm p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-700"
+ aria-label={t("aiAssistant.sidebar.historySearch")}
+ onClick={() => setSearching(true)}
+ >
+ <Search className="size-3.5" aria-hidden="true" />
+ </button>
+ ) : null}
+ </div>
+ )}
+ {items.map((thread) => (
+ <DropdownMenuItem
+ key={thread.id}
+ className="justify-between gap-3 py-2 text-sm"
+ onSelect={() => onSelect(thread.id)}
+ >
+ <span className="truncate">{thread.title}</span>
+ {thread.id === threadId ? <Check className="size-4 shrink-0 text-slate-700" aria-hidden="true" /> : <span className="size-4 shrink-0" aria-hidden="true" />}
+ </DropdownMenuItem>
+ ))}
+ </div>
+ );
+ };
+
+ return (
+ <DropdownMenu onOpenChange={(open) => { if (!open) { setQuery(""); setSearching(false); } }}>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ className="flex h-8 min-w-0 max-w-52 items-center gap-1 rounded-full px-2 text-left text-[13px] font-medium text-slate-700 hover:bg-slate-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400"
+ data-ai-thread-menu=""
+ aria-label={`${title} · ${t("aiAssistant.sidebar.history")}`}
+ >
+ <Sparkles className="size-3.5 shrink-0 text-slate-500" aria-hidden="true" />
+ <span className="min-w-0 truncate">{sidebarThreadLabel(title)}</span>
+ <ChevronDown className="size-3.5 shrink-0 text-slate-400" aria-hidden="true" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="z-[60] max-h-80 w-72 overflow-y-auto p-1.5">
+ {searching ? (
+ <input
+ autoFocus
+ value={query}
+ placeholder={t("aiAssistant.sidebar.historySearch")}
+ className="mb-1 h-8 w-full rounded-md border border-slate-200 bg-card px-2 text-sm text-slate-950 outline-none placeholder:text-slate-400"
+ aria-label={t("aiAssistant.sidebar.historySearch")}
+ onChange={(event) => setQuery(event.target.value)}
+ onKeyDown={(event) => event.stopPropagation()}
+ />
+ ) : null}
+ <DropdownMenuItem className="gap-2 py-2 text-sm" onSelect={onCreate}>
+ <Plus className="size-3.5 shrink-0" aria-hidden="true" />
+ {t("aiAssistant.sidebar.newThread")}
+ </DropdownMenuItem>
+ {pinned && pinnedVisible ? (
+ <DropdownMenuItem className="justify-between gap-3 py-2 text-sm" onSelect={onSelectPinned}>
+ <span className="truncate">{pinned.title}</span>
+ {pinnedActive ? <Check className="size-4 shrink-0 text-slate-700" aria-hidden="true" /> : <span className="size-4 shrink-0" aria-hidden="true" />}
+ </DropdownMenuItem>
+ ) : null}
+ {threads.length || pinnedVisible ? <DropdownMenuSeparator /> : null}
+ {renderGroup(t("aiAssistant.sidebar.historyRecent"), recent, searchOnRecent && !searching)}
+ {renderGroup(t("aiAssistant.sidebar.historyOlder"), older, !searchOnRecent && !searching)}
+ {normalized && !visible.length ? (
+ <p className="px-2 py-3 text-sm text-slate-500">{t("aiAssistant.sidebar.historyEmpty")}</p>
+ ) : null}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/apps/web/src/components/ai-sidebar/InfographicSidebarSession.test.mjs b/apps/web/src/components/ai-sidebar/InfographicSidebarSession.test.mjs
index d84e8ef5..66f7ac75 100644
--- a/apps/web/src/components/ai-sidebar/InfographicSidebarSession.test.mjs
+++ b/apps/web/src/components/ai-sidebar/InfographicSidebarSession.test.mjs
@@ -25,12 +25,15 @@ const session = {
response: "见 [流程图](#memo=memo_03de025fc0134b7da0d155c2c1686b92)",
},
generating: false,
- readOnly: true,
+ readOnly: false,
canUndo: false,
hasGraphic: true,
+ activeSessionId: null,
async onSubmit() {},
onUndo() {},
onStop() {},
+ onSelectSession() {},
+ onCreateSession() {},
};
describe("infographic sidebar note links", () => {
@@ -45,8 +48,6 @@ describe("infographic sidebar note links", () => {
{ i18n },
createElement(InfographicSidebarSession, {
session,
- noteTitle: "演进里程碑",
- onOpenChange() {},
onOpenNote() {},
}),
),
diff --git a/apps/web/src/components/ai-sidebar/InfographicSidebarSession.tsx b/apps/web/src/components/ai-sidebar/InfographicSidebarSession.tsx
index c3a2de0c..587e0777 100644
--- a/apps/web/src/components/ai-sidebar/InfographicSidebarSession.tsx
+++ b/apps/web/src/components/ai-sidebar/InfographicSidebarSession.tsx
@@ -1,5 +1,5 @@
import { useTranslation } from "react-i18next";
-import { ArrowUp, PanelRightClose, Sparkles, Undo2 } from "lucide-react";
+import { ArrowUp, Sparkles, Undo2 } from "lucide-react";
import { useState, type MouseEvent } from "react";
import type { InfographicConversationTurn } from "@edgeever/shared";
import { Button } from "@/components/ui/button";
@@ -15,6 +15,7 @@ import {
usePromptInputController,
} from "@/components/ai-elements/prompt-input";
import { cn } from "@/lib/utils";
+import { infographicTurnSessionId, resolveInfographicSessionId } from "@/lib/infographic-sessions";
import { SidebarAgentModeStatus } from "./SidebarAgentModeStatus";
import { memoIdFromSidebarLinkEvent, rewriteSidebarNoteLinks, sidebarNoteLinkAllowedTags, sidebarNoteLinkComponents } from "./sidebar-note-links";
@@ -42,9 +43,12 @@ export type InfographicSidebarController = {
readOnly: boolean;
canUndo: boolean;
hasGraphic: boolean;
+ activeSessionId: string | null;
onSubmit: (prompt: string) => Promise<void>;
onUndo: () => void;
onStop: () => void;
+ onSelectSession: (sessionId: string) => void;
+ onCreateSession: () => void;
};
function InfographicSidebarComposer({ session, selectionPending, onPendingChange }: { session: InfographicSidebarController; selectionPending: boolean; onPendingChange: (pending: boolean) => void }) {
@@ -112,18 +116,15 @@ function InfographicReply({ children, isAnimating }: { children: string; isAnima
export function InfographicSidebarSession({
session,
- noteTitle,
- onOpenChange,
onOpenNote,
}: {
session: InfographicSidebarController;
- noteTitle?: string;
- onOpenChange: (open: boolean) => void;
onOpenNote?: (memoId: string, notebookId: string) => void;
}) {
const { t, i18n } = useTranslation();
const [selectionPending, setSelectionPending] = useState(false);
- const title = noteTitle?.trim() || t("infographic.name");
+ const viewingId = resolveInfographicSessionId(session.turns, session.activeSessionId);
+ const visibleTurns = session.turns.filter((turn) => infographicTurnSessionId(turn) === viewingId);
const openLinkedNote = (event: MouseEvent<HTMLElement>) => {
const linkedId = memoIdFromSidebarLinkEvent(event);
if (!linkedId || !onOpenNote) return;
@@ -137,33 +138,17 @@ export function InfographicSidebarSession({
: t(turn.kind === "generated" ? "infographic.historyGenerated" : "infographic.historyRefined", { title: turn.resultTitle || t("infographic.name") }));
return (
- <div className="flex h-full min-h-0 min-w-0 flex-col bg-card" data-infographic-ai-sidebar="">
- <div className="flex h-12 shrink-0 items-center gap-2 border-b border-slate-200 px-2">
- <span className="flex min-w-0 flex-1 items-center gap-1.5 px-1.5 text-[13px] text-slate-800">
- <Sparkles className="size-3.5 shrink-0" aria-hidden="true" />
- <span className="truncate">{title}</span>
- </span>
- <Button
- type="button"
- size="icon-sm"
- variant="ghost"
- title={t("aiAssistant.sidebar.close")}
- aria-label={t("aiAssistant.sidebar.close")}
- onClick={() => onOpenChange(false)}
- >
- <PanelRightClose className="h-4 w-4" />
- </Button>
- </div>
- <Conversation className="min-h-0 flex-1" aria-label={t("infographic.historyTitle")}>
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-card" data-infographic-ai-sidebar="">
+ <Conversation key={viewingId} className="min-h-0 flex-1" aria-label={t("infographic.historyTitle")}>
<ConversationContent className={threadClassName} onClick={openLinkedNote}>
- {!session.turns.length && !session.activeTurn ? (
+ {!visibleTurns.length && !session.activeTurn ? (
<ConversationEmptyState
icon={<Sparkles className="h-6 w-6" />}
title={t(session.hasGraphic ? "infographic.refine" : "infographic.describe")}
description={t(session.hasGraphic ? "infographic.refinePrompt" : "infographic.prompt")}
/>
) : null}
- {session.turns.map((turn) => (
+ {visibleTurns.map((turn) => (
<div key={turn.id} data-infographic-turn={turn.id} className="space-y-2">
<Message from="user">
<MessageContent className={userMessageClassName}>{turn.prompt}</MessageContent>
diff --git a/apps/web/src/components/dialogs/AiAssistantDialog.test.mjs b/apps/web/src/components/dialogs/AiAssistantDialog.test.mjs
index a7ae13af..13d6c5d5 100644
--- a/apps/web/src/components/dialogs/AiAssistantDialog.test.mjs
+++ b/apps/web/src/components/dialogs/AiAssistantDialog.test.mjs
@@ -14,14 +14,18 @@ describe("AI assistant modes", () => {
expect(sidebar).toContain("sidebarRevealTransition");
expect(sidebar).not.toContain("{open && <AiSidebarSession");
expect(sidebar).not.toContain("hidden w-0");
- expect(sidebar).toContain("props.infographic ? (");
+ expect(sidebar).toContain("<AiSidebarSession");
+ expect(sidebar).not.toContain("props.infographic ? (");
expect(sidebar).toContain("<InfographicSidebarSession");
+ expect(sidebar).toContain("aiAssistant.sidebar.currentInfographic");
expect(sidebar).toContain("<AiAgentSelector");
const infographic = readFileSync(new URL("../ai-sidebar/InfographicSidebarSession.tsx", import.meta.url), "utf8");
const mode = readFileSync(new URL("../ai-sidebar/SidebarAgentModeStatus.tsx", import.meta.url), "utf8");
const status = readFileSync(new URL("../ai-sidebar/BuiltinAgentStatus.tsx", import.meta.url), "utf8");
const pane = readFileSync(new URL("../InfographicEditorPane.tsx", import.meta.url), "utf8");
expect(infographic).toContain("<SidebarAgentModeStatus");
+ expect(infographic).not.toContain("<AiSidebarThreadMenu");
+ expect(sidebar).toContain("<AiSidebarThreadMenu");
expect(mode).toContain("readAiSidebarSource");
expect(mode).toContain("<AiAgentSelector");
expect(pane).toContain('readAiSidebarSource() === "local"');
diff --git a/apps/web/src/lib/infographic-sessions.test.mjs b/apps/web/src/lib/infographic-sessions.test.mjs
new file mode 100644
index 00000000..3246345a
--- /dev/null
+++ b/apps/web/src/lib/infographic-sessions.test.mjs
@@ -0,0 +1,36 @@
+import { describe, expect, test } from "bun:test";
+import {
+ INFOGRAPHIC_LEGACY_SESSION_ID,
+ infographicSessionHistory,
+ infographicSessionStamp,
+ infographicSessionThreads,
+ resolveInfographicSessionId,
+} from "./infographic-sessions.ts";
+
+const turn = (id, createdAt, prompt, extra = {}) => ({
+ id,
+ prompt,
+ createdAt,
+ kind: "refined",
+ resultTitle: "",
+ ...extra,
+});
+
+describe("infographic sidebar sessions", () => {
+ test("keeps older turns in one session and starts a new one without that context", () => {
+ const history = [
+ turn("one", "2026-10-01T00:00:00.000Z", "做成里程碑"),
+ turn("two", "2026-10-02T00:00:00.000Z", "把第二项改成用户增长", { undoneAt: "2026-10-02T01:00:00.000Z" }),
+ turn("three", "2026-10-24T00:00:00.000Z", "改成技术演进", { sessionId: "session-new", kind: "failed" }),
+ ];
+ expect(resolveInfographicSessionId(history, null)).toBe("session-new");
+ expect(resolveInfographicSessionId(history.slice(0, 2), null)).toBe(INFOGRAPHIC_LEGACY_SESSION_ID);
+ expect(infographicSessionThreads(history).map((thread) => thread.title)).toEqual(["改成技术演进", "做成里程碑"]);
+ expect(infographicSessionHistory(history, INFOGRAPHIC_LEGACY_SESSION_ID).map((item) => item.id)).toEqual(["one"]);
+ expect(infographicSessionHistory(history, "session-new")).toEqual([]);
+ expect(infographicSessionStamp(INFOGRAPHIC_LEGACY_SESSION_ID)).toEqual({});
+ expect(infographicSessionStamp("session-new")).toEqual({ sessionId: "session-new" });
+ expect(resolveInfographicSessionId([], "session-empty")).toBe("session-empty");
+ expect(infographicSessionThreads([])).toEqual([]);
+ });
+});
diff --git a/apps/web/src/lib/infographic-sessions.ts b/apps/web/src/lib/infographic-sessions.ts
new file mode 100644
index 00000000..5dea6d5f
--- /dev/null
+++ b/apps/web/src/lib/infographic-sessions.ts
@@ -0,0 +1,53 @@
+import type { ChatThreadSummary } from "@/lib/local-agent-threads";
+
+// Turns saved before sessions have no sessionId and stay in one note-local chat.
+export const INFOGRAPHIC_LEGACY_SESSION_ID = "legacy";
+
+type SessionTurn = {
+ sessionId?: string;
+ prompt: string;
+ createdAt: string;
+ kind: string;
+ undoneAt?: string;
+};
+
+export const infographicTurnSessionId = (turn: { sessionId?: string }) => turn.sessionId?.trim() || INFOGRAPHIC_LEGACY_SESSION_ID;
+
+export const resolveInfographicSessionId = (
+ turns: readonly { sessionId?: string; createdAt: string }[],
+ activeSessionId: string | null | undefined,
+) => {
+ if (activeSessionId) return activeSessionId;
+ let latest: { sessionId?: string; createdAt: string } | null = null;
+ for (const turn of turns) {
+ if (!latest || turn.createdAt > latest.createdAt) latest = turn;
+ }
+ return latest ? infographicTurnSessionId(latest) : INFOGRAPHIC_LEGACY_SESSION_ID;
+};
+
+export const infographicSessionThreads = (turns: readonly SessionTurn[]): ChatThreadSummary[] => {
+ const byId = new Map<string, ChatThreadSummary & { oldestAt: string }>();
+ for (const turn of turns) {
+ const id = infographicTurnSessionId(turn);
+ const title = turn.prompt.replace(/\s+/g, " ").trim();
+ const current = byId.get(id);
+ if (!current) {
+ byId.set(id, { id, title, updatedAt: turn.createdAt, oldestAt: turn.createdAt });
+ continue;
+ }
+ if (turn.createdAt > current.updatedAt) current.updatedAt = turn.createdAt;
+ if (turn.createdAt < current.oldestAt && title) {
+ current.oldestAt = turn.createdAt;
+ current.title = title;
+ }
+ }
+ return [...byId.values()]
+ .sort((left, right) => (left.updatedAt < right.updatedAt ? 1 : left.updatedAt > right.updatedAt ? -1 : 0))
+ .map(({ oldestAt: _oldestAt, ...thread }) => thread);
+};
+
+export const infographicSessionHistory = <T extends SessionTurn>(turns: readonly T[], sessionId: string) =>
+ turns.filter((turn) => infographicTurnSessionId(turn) === sessionId && !turn.undoneAt && turn.kind !== "failed").slice(-12);
+
+export const infographicSessionStamp = (sessionId: string): { sessionId?: string } =>
+ sessionId === INFOGRAPHIC_LEGACY_SESSION_ID ? {} : { sessionId };
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index 68ce2d8f..05dcc4bc 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -1652,6 +1652,7 @@ export const enUS = {
close: "Collapse assistant",
history: "Chat history",
newThread: "New chat",
+ currentInfographic: "This infographic",
historyRecent: "Past 30 days",
historyOlder: "Earlier",
historySearch: "Search chats",
diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.ts
index c05bd7e4..a0b19c2e 100644
--- a/packages/shared/src/i18n/ja.ts
+++ b/packages/shared/src/i18n/ja.ts
@@ -1641,6 +1641,7 @@ export const ja = {
close: "アシスタントをしまう",
history: "チャット履歴",
newThread: "新しいチャット",
+ currentInfographic: "この情報図",
historyRecent: "過去 30 日",
historyOlder: "それ以前",
historySearch: "チャットを検索",
diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.ts
index 2f4b6188..e271a655 100644
--- a/packages/shared/src/i18n/pl.ts
+++ b/packages/shared/src/i18n/pl.ts
@@ -1641,6 +1641,7 @@ export const pl = {
close: "Zwiń asystenta",
history: "Historia czatów",
newThread: "Nowy czat",
+ currentInfographic: "Ta infografika",
historyRecent: "Ostatnie 30 dni",
historyOlder: "Wcześniej",
historySearch: "Szukaj czatów",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index 41990e3b..eb415c66 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -1652,6 +1652,7 @@ export const zhCN = {
close: "收起助手",
history: "会话记录",
newThread: "新对话",
+ currentInfographic: "当前信息图",
historyRecent: "过去 30 天",
historyOlder: "更早",
historySearch: "搜索会话",
diff --git a/packages/shared/src/infographic.test.mjs b/packages/shared/src/infographic.test.mjs
index b6950c22..cc7d9c29 100644
--- a/packages/shared/src/infographic.test.mjs
+++ b/packages/shared/src/infographic.test.mjs
@@ -46,6 +46,18 @@ describe("infographic note format", () => {
{ id: "edit", prompt: "阿里巴巴", response: "已替换对比对象。", decision: "对比关系未变,因此沿用原模板。", kind: "refined", resultTitle: "腾讯 vs 阿里巴巴", template: "compare-binary-horizontal-badge-card-vs", createdAt: "2026-09-24T10:01:00.000Z" },
] };
expect(parseInfographicDocument(serializeInfographicDocument(document))).toEqual(document);
+ const sessioned = {
+ schemaVersion: 1,
+ syntax: "infographic sequence-steps-simple\ndata\n title 发布流程",
+ activeSessionId: "session-new",
+ history: [
+ { id: "old", prompt: "做成发布流程", createdAt: "2026-10-01T00:00:00.000Z", kind: "generated", resultTitle: "发布流程" },
+ { id: "new", prompt: "换成里程碑", createdAt: "2026-10-24T00:00:00.000Z", kind: "refined", resultTitle: "里程碑", sessionId: "session-new" },
+ ],
+ };
+ expect(parseInfographicDocument(serializeInfographicDocument(sessioned))).toEqual(sessioned);
+ expect(parseInfographicDocument(serializeInfographicDocument({ schemaVersion: 1, syntax: "", activeSessionId: "session empty" }))).toBeNull();
+ expect(parseInfographicDocument(serializeInfographicDocument({ ...sessioned, history: [{ ...sessioned.history[1], sessionId: "bad id" }] }))).toBeNull();
expect(InfographicAgentRequestSchema.safeParse({ prompt: "修改", currentContent: "", candidates: ["compare-binary-horizontal-badge-card-vs"], history: [{ prompt: "原请求", response: "原回复" }] }).success).toBe(true);
expect(InfographicAgentRequestSchema.safeParse({ prompt: "修改", currentContent: "", candidates: [], history: [] }).success).toBe(false);
});
diff --git a/packages/shared/src/infographic.ts b/packages/shared/src/infographic.ts
index ebfe66f6..25cad301 100644
--- a/packages/shared/src/infographic.ts
+++ b/packages/shared/src/infographic.ts
@@ -5,12 +5,14 @@ export const INFOGRAPHIC_SCHEMA_VERSION = 1 as const;
export const INFOGRAPHIC_AGENT_SOURCE_MAX_LENGTH = 100_000;
const MARKER = "edgeever-infographic-v1";
const COMMENT = /<!--\s*edgeever-infographic-v1:([A-Za-z0-9_-]+)\s*-->/;
+const SESSION_ID = /^[A-Za-z0-9_-]{1,80}$/;
export type InfographicDocument = {
schemaVersion: typeof INFOGRAPHIC_SCHEMA_VERSION;
// AntV Infographic's native source, separate from the visual diagram IR.
syntax: string;
history?: InfographicConversationTurn[];
+ activeSessionId?: string;
};
export type InfographicConversationTurn = {
@@ -24,6 +26,7 @@ export type InfographicConversationTurn = {
template?: string;
error?: string;
undoneAt?: string;
+ sessionId?: string;
};
export const InfographicAgentRequestSchema = z.object({
@@ -90,9 +93,17 @@ export const parseInfographicDocument = (markdown: string | null | undefined): I
&& (value.decision === undefined || typeof value.decision === "string" && value.decision.length <= 500)
&& (value.template === undefined || typeof value.template === "string")
&& (value.error === undefined || typeof value.error === "string")
- && (value.undoneAt === undefined || typeof value.undoneAt === "string");
+ && (value.undoneAt === undefined || typeof value.undoneAt === "string")
+ && (value.sessionId === undefined || typeof value.sessionId === "string" && SESSION_ID.test(value.sessionId));
}))) return null;
- return { schemaVersion: INFOGRAPHIC_SCHEMA_VERSION, syntax: document.syntax, ...(history ? { history: history as InfographicConversationTurn[] } : {}) };
+ const activeSessionId = document.activeSessionId;
+ if (activeSessionId !== undefined && (typeof activeSessionId !== "string" || !SESSION_ID.test(activeSessionId))) return null;
+ return {
+ schemaVersion: INFOGRAPHIC_SCHEMA_VERSION,
+ syntax: document.syntax,
+ ...(history ? { history: history as InfographicConversationTurn[] } : {}),
+ ...(typeof activeSessionId === "string" ? { activeSessionId } : {}),
+ };
} catch {
return null;
}