Skip to content

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

fix(web): show the AI assistant on diagram and table notes

tianma-if8d81218ff468
diff --git a/apps/api/src/companion-agent-tools.ts b/apps/api/src/companion-agent-tools.ts
index dbae12bf..60767323 100644
--- a/apps/api/src/companion-agent-tools.ts
+++ b/apps/api/src/companion-agent-tools.ts
@@ -1,4 +1,4 @@
-import { COMPANION_NOTE_EDIT_MAX_CHARS, parseDiagramDocument, type CompanionSource, type CompanionTodo, type CompanionToolCall, type CompanionToolDefinition, type CompanionTurnInput, type MemoDetail, type MemoSummary } from "@edgeever/shared";
+import { COMPANION_NOTE_EDIT_MAX_CHARS, parseDiagramDocument, parseTableDocument, type CompanionSource, type CompanionTodo, type CompanionToolCall, type CompanionToolDefinition, type CompanionTurnInput, type MemoDetail, type MemoSummary } from "@edgeever/shared";
import type { DatabaseAdapter } from "./storage-contract";
import type { AppContext } from "./api-context";
import type { CompanionScope } from "./companion-service";
@@ -318,6 +318,9 @@ export function createCompanionTools(args: { db: DatabaseAdapter; scope: Compani
if (parseDiagramDocument(memo.contentMarkdown)) {
throw new AppError("invalid_params", "This is an editable diagram. Change it with update_diagram, not update_memo.", 400);
}
+ if (parseTableDocument(memo.contentMarkdown)) {
+ throw new AppError("invalid_params", "This is a structured table. Do not replace it with update_memo.", 400);
+ }
if (memo.contentMarkdown.length > COMPANION_NOTE_EDIT_MAX_CHARS || parameters_.contentMarkdown.length > COMPANION_NOTE_EDIT_MAX_CHARS) {
throw new AppError("invalid_params", "This note edit is too large to review. Split it into a smaller change.", 400);
}
@@ -409,7 +412,7 @@ export function createCompanionTools(args: { db: DatabaseAdapter; scope: Compani
return done(payload);
}
if (definition.name === "get_memo") {
- const payload = result as { memo: MemoDetail; diagram?: { kind?: string } };
+ const payload = result as { memo: MemoDetail; diagram?: { kind?: string }; structuredTable?: unknown };
const memo = payload.memo;
remember(memo);
if (payload.diagram) {
@@ -424,7 +427,12 @@ export function createCompanionTools(args: { db: DatabaseAdapter; scope: Compani
if (content.length === memo.contentMarkdown.length) inspected.set(memo.id, memo.revision); else inspected.delete(memo.id);
return done({ id: memo.id, title: memo.title, notebookId: memo.notebookId, tags: memo.tags, revision: memo.revision,
createdAt: memo.createdAt, updatedAt: memo.updatedAt,
- content, truncated: content.length !== memo.contentMarkdown.length });
+ content, truncated: content.length !== memo.contentMarkdown.length,
+ ...(payload.structuredTable ? {
+ structuredTable: payload.structuredTable,
+ message: "This is a structured table. Answer from this content. Do not replace it with update_memo.",
+ } : {}),
+ });
}
if (definition.name === "search_memos" || definition.name === "list_memos") {
const listed = result as { memos: MemoSummary[]; hasMore?: boolean };
diff --git a/apps/api/src/companion-prepare.ts b/apps/api/src/companion-prepare.ts
index 1be0dff9..4eb08660 100644
--- a/apps/api/src/companion-prepare.ts
+++ b/apps/api/src/companion-prepare.ts
@@ -45,6 +45,7 @@ If list_memos or search_memos sets hasMore, say the list is incomplete instead o
When the user refers to this note, 这篇, 当前, or the open note, use the Open note body in Focus DATA. If that body is truncated, call get_memo. If Focus DATA says the open note is a diagram, call get_diagram. Do not invent structure from the title alone.
When the user asks for a mind map, 思维导图, flowchart, 流程图, architecture diagram, or 架构图 of the open note, build it from that body (or get_memo/get_diagram first). To create a new diagram note, call create_diagram_memo. Do not use create_memo, Markdown outlines, or Mermaid. Preserve an explicitly requested type exactly: 思维导图/mind map means kind=mind-map, 流程图/flowchart means kind=flowchart, and 架构图/architecture diagram means kind=architecture. For mind maps, supply a root node and children with parentId; omit node type. If the user did not name a notebook, omit notebookId so it is saved in the inbox notebook (等待分类). Do not ask which notebook, and do not use the open notebook unless the user named it. Reply with the new note link.
To change an existing diagram, call get_diagram then update_diagram. Do not create a second diagram unless the user asked for a new note. Do not use update_memo or Mermaid for diagrams.
+A structured table cannot be replaced with update_memo. Answer from the open note body or get_memo, and do not rewrite its Markdown.
You can list, create, update, use, and delete note templates, and list, create, update, and delete AI instructions. use_note_template creates a memo immediately. You cannot empty the trash, share notes, or upload files. Do not claim those tools exist.
Call get_memo only when you must quote, summarize, or edit one specific note; even then quote at most a short phrase and always include the link.
Say when evidence is missing or truncated.
diff --git a/apps/api/src/companion-tool-actions.test.mjs b/apps/api/src/companion-tool-actions.test.mjs
index 73e9988f..6fbf5c04 100644
--- a/apps/api/src/companion-tool-actions.test.mjs
+++ b/apps/api/src/companion-tool-actions.test.mjs
@@ -5,7 +5,7 @@ import { Hono } from "hono";
import { createSelfHostedStorageAdapter } from "./self-hosted-storage-adapter.ts";
import { registerCompanionRoutes } from "./companion-routes.ts";
import { beginCompanionTurn, checkpointCompanionTurn, clearCompanionHistory, saveCompanionMemory } from "./companion-service.ts";
-import { parseDiagramDocument } from "@edgeever/shared";
+import { createDefaultTableDocument, parseDiagramDocument, serializeTableDocument } from "@edgeever/shared";
import { createMemoRecord, getMemoDetail, normalizeSearchTimeBound, updateMemoRecord } from "./memo-service.ts";
import { companionWorkspaceCursor, proposeCompanionToolAction } from "./companion-tool-actions.ts";
import { getCompanionAction, applyCompanionAction, dismissCompanionAction } from "./companion-actions.ts";
@@ -239,6 +239,24 @@ describe("shared companion MCP adapter", () => {
.toContain("eval");
expect(f.sqlite.query("SELECT COUNT(*) AS n FROM companion_actions").get().n).toBe(0);
});
+ test("refuses to replace a structured table with update_memo", async () => {
+ const f = await setup();
+ const table = await createMemoRecord(f.db, scope.workspaceId, {
+ notebookId: "ideas",
+ title: "Tasks",
+ contentMarkdown: serializeTableDocument(createDefaultTableDocument()),
+ }, actor, "owner");
+ const tools = createCompanionTools({ ...f, scope, signal: new AbortController().signal, assertActive: async () => {}, sources: [] });
+ const read = await tools.get_memo.execute({ memoId: table.id });
+ expect(read.message).toContain("structured table");
+ expect(read.structuredTable).toBeTruthy();
+ expect(read.content).toContain("|");
+ expect(read.content).not.toContain("edgeever-table-v1");
+ await expect(tools.update_memo.execute({ memoId: table.id, contentMarkdown: "# no" })).rejects.toThrow(
+ "This is a structured table. Do not replace it with update_memo.",
+ );
+ expect((await getMemoDetail(f.db, scope.workspaceId, table.id)).contentMarkdown).toContain("edgeever-table-v1");
+ });
test("create_diagram_memo keeps generated edge IDs out of Agent input", async () => {
const f = await setup();
const tools = createCompanionTools({ ...f, scope, signal: new AbortController().signal, assertActive: async () => {}, sources: [] });
diff --git a/apps/web/src/components/DiagramEditorPane.test.mjs b/apps/web/src/components/DiagramEditorPane.test.mjs
index fdefd73d..20a1178b 100644
--- a/apps/web/src/components/DiagramEditorPane.test.mjs
+++ b/apps/web/src/components/DiagramEditorPane.test.mjs
@@ -454,7 +454,8 @@ describe("diagram editor canvas surface", () => {
});
test("paints diagram chrome from theme tokens instead of literal white", () => {
- expect(source).toContain('className="flex h-full min-h-0 flex-col bg-card"');
+ expect(source).toContain('className="relative flex h-full min-h-0 min-w-0 bg-card"');
+ expect(source).toContain('className="relative flex h-full min-h-0 min-w-0 flex-1 flex-col"');
expect(source).toContain('className="shrink-0 border-b border-slate-200 bg-card"');
expect(source).not.toContain("flex-col bg-white");
expect(source).not.toContain("border-slate-200 bg-white");
diff --git a/apps/web/src/components/DiagramEditorPane.tsx b/apps/web/src/components/DiagramEditorPane.tsx
index bc09e38a..9e623479 100644
--- a/apps/web/src/components/DiagramEditorPane.tsx
+++ b/apps/web/src/components/DiagramEditorPane.tsx
@@ -142,6 +142,9 @@ import {
type MemoEditSession,
type Notebook,
} from "@edgeever/shared";
+import { AiSidebar, readAiSidebarOpen, writeAiSidebarOpen } from "@/components/ai-sidebar/AiSidebar";
+import { AiSidebarErrorBoundary } from "@/components/ai-sidebar/AiSidebarErrorBoundary";
+import { IconTooltip } from "@/components/editor/EditorPaneChrome";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { AppConfirmDialog } from "@/components/dialogs/ConfirmDialogs";
@@ -164,7 +167,7 @@ import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSepara
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { useAppearanceTheme } from "@/components/ThemeProvider";
import { api } from "@/lib/api";
-import { EDITOR_LOCAL_SAVE_DELAY_MS, getNotebookMoveOptions } from "@/lib/app-helpers";
+import { EDITOR_LOCAL_SAVE_DELAY_MS, formatShortcutBinding, getNotebookMoveOptions, type ShortcutSettings } from "@/lib/app-helpers";
import { copyTextToClipboard } from "@/lib/clipboard";
import {
compactArchitectureNodeSize,
@@ -200,6 +203,12 @@ type DiagramEditorPaneProps = {
onSaveAsTemplate: (memo: MemoDetail, name: string) => Promise<void>;
onToggleDesktopFocusMode: () => void;
onOpenExecutionCenter: () => void;
+ aiAssistantOpenToken: number;
+ shortcutSettings: ShortcutSettings;
+ companionAvailable: boolean;
+ beforeCompanionApply?: () => Promise<void>;
+ onCompanionNotesChanged?: () => Promise<void>;
+ onOpenCompanionNote?: (id: string, notebookId: string) => void;
};
type NodeData = { label: string; shape: DiagramNodeShape; parentId?: string; resourceIcon?: ArchitectureResourceIcon };
@@ -1635,6 +1644,12 @@ export const DiagramEditorPane = ({
onSaveAsTemplate,
onToggleDesktopFocusMode,
onOpenExecutionCenter,
+ aiAssistantOpenToken,
+ shortcutSettings,
+ companionAvailable,
+ beforeCompanionApply,
+ onCompanionNotesChanged,
+ onOpenCompanionNote,
}: DiagramEditorPaneProps) => {
const { t } = useTranslation();
const { resolvedTheme } = useAppearanceTheme();
@@ -1680,6 +1695,12 @@ export const DiagramEditorPane = ({
const [saveFailed, setSaveFailed] = useState(false);
const [historyOpen, setHistoryOpen] = useState(false);
const [shareOpen, setShareOpen] = useState(false);
+ const [aiAssistantOpen, setAiAssistantOpenState] = useState(readAiSidebarOpen);
+ const setAiSidebarOpen = useCallback((open: boolean) => {
+ setAiAssistantOpenState(open);
+ writeAiSidebarOpen(open);
+ }, []);
+ const handledAiAssistantOpenTokenRef = useRef(aiAssistantOpenToken);
const [memoIdCopyNotice, setMemoIdCopyNotice] = useState<"copied" | "error" | null>(null);
const memoIdCopyTimerRef = useRef<number | null>(null);
const [confirmDiscardOpen, setConfirmDiscardOpen] = useState(false);
@@ -1850,6 +1871,14 @@ export const DiagramEditorPane = ({
return () => { cancelled = true; };
}, [memo.id, memo.contentHash, memo.revision, readOnly, t]);
+ useEffect(() => {
+ if (handledAiAssistantOpenTokenRef.current === aiAssistantOpenToken) return;
+ handledAiAssistantOpenTokenRef.current = aiAssistantOpenToken;
+ if (readOnly || historyOpen || shareOpen || confirmDiscardOpen || mobileNotebookSheetOpen) return;
+ setAiSidebarOpen(true);
+ if (editorDirty) saveRef.current();
+ }, [aiAssistantOpenToken, confirmDiscardOpen, editorDirty, historyOpen, mobileNotebookSheetOpen, readOnly, setAiSidebarOpen, shareOpen]);
+
useEffect(() => {
appearanceRef.current = resolvedTheme;
const graph = graphRef.current;
@@ -3058,6 +3087,9 @@ export const DiagramEditorPane = ({
if (!document) return null;
const kindLabel = document.kind === "mind-map" ? t("diagram.mindMap") : document.kind === "architecture" ? t("diagram.architecture") : t("diagram.flowchart");
+ const assistantMarkdown = graphRef.current
+ ? serializeDiagramDocument(graphToDocument(graphRef.current, document.kind, themeRef.current, structureRef.current))
+ : memo.contentMarkdown;
const currentMarkdown = historyOpen && dirty
? serializeDiagramDocument(graphRef.current ? graphToDocument(graphRef.current, document.kind, themeRef.current, structureRef.current) : document)
: memo.contentMarkdown;
@@ -3077,7 +3109,8 @@ export const DiagramEditorPane = ({
return (
<TooltipProvider>
- <div className="flex h-full min-h-0 flex-col bg-card">
+ <div className="relative flex h-full min-h-0 min-w-0 bg-card">
+ <div className="relative flex h-full min-h-0 min-w-0 flex-1 flex-col">
<header className="shrink-0 border-b border-slate-200 bg-card">
<div className={cn(MEMO_EDITOR_TOP_ROW_CLASS_NAME, "border-b-0")}>
<div
@@ -3389,7 +3422,7 @@ export const DiagramEditorPane = ({
/>
{!readOnly && (
<div
- className="pointer-events-none absolute bottom-3 left-3 z-10 flex select-none items-center gap-1.5 rounded-full border border-slate-200/80 bg-white/90 px-3 py-1 text-xs text-slate-500 shadow-xs backdrop-blur-sm dark:border-slate-800 dark:bg-slate-900/90 dark:text-slate-400"
+ className="pointer-events-none absolute bottom-3 left-3 z-10 flex max-w-[calc(100%-6.5rem)] flex-wrap select-none items-center gap-1.5 rounded-full border border-slate-200/80 bg-white/90 px-3 py-1 text-xs text-slate-500 shadow-xs backdrop-blur-sm dark:border-slate-800 dark:bg-slate-900/90 dark:text-slate-400"
role="status"
aria-live="polite"
>
@@ -3533,6 +3566,46 @@ export const DiagramEditorPane = ({
{t(memoIdCopyNotice === "copied" ? "editor.noteIdCopied" : "editor.noteIdCopyFailed", { id: memo.id })}
</ClipboardCopyNotice>
) : null}
+ {!readOnly && !aiAssistantOpen ? (
+ <IconTooltip
+ side="left"
+ label={`${t("aiAssistant.open")} (${formatShortcutBinding(shortcutSettings.openAiAssistant)})`}
+ >
+ <Button
+ type="button"
+ variant="outline"
+ size="icon"
+ data-ai-assistant-launcher=""
+ className="absolute bottom-[calc(1.25rem+env(safe-area-inset-bottom))] right-5 z-30 size-11 rounded-full border-slate-200 bg-card text-slate-950 shadow-[0_8px_24px_rgba(15,23,42,0.14)] hover:bg-card hover:text-slate-950"
+ aria-label={t("aiAssistant.open")}
+ onClick={() => {
+ setAiSidebarOpen(true);
+ if (editorDirty) saveRef.current();
+ }}
+ >
+ <Sparkles className="size-5" strokeWidth={1.75} />
+ </Button>
+ </IconTooltip>
+ ) : null}
+ </div>
+ <AiSidebarErrorBoundary open={aiAssistantOpen} onOpenChange={setAiSidebarOpen}>
+ <AiSidebar
+ open={aiAssistantOpen}
+ onOpenChange={setAiSidebarOpen}
+ companionAvailable={companionAvailable}
+ contentMarkdown={assistantMarkdown}
+ memoId={memo.id}
+ notebookId={memo.notebookId}
+ notebookTitle={notebookOptions.find((notebook) => notebook.id === memo.notebookId)?.name}
+ noteTitle={title}
+ beforeCompanionApply={async () => {
+ if (editorDirty && !(await save())) throw new Error("save failed");
+ await beforeCompanionApply?.();
+ }}
+ onCompanionNotesChanged={onCompanionNotesChanged}
+ onOpenCompanionNote={onOpenCompanionNote}
+ />
+ </AiSidebarErrorBoundary>
</div>
</TooltipProvider>
);
diff --git a/apps/web/src/components/MemoEditorHeaderActions.test.mjs b/apps/web/src/components/MemoEditorHeaderActions.test.mjs
index a1f42cfc..6ca29c42 100644
--- a/apps/web/src/components/MemoEditorHeaderActions.test.mjs
+++ b/apps/web/src/components/MemoEditorHeaderActions.test.mjs
@@ -4,6 +4,8 @@ import { readFileSync } from "node:fs";
const actionsSource = readFileSync(new URL("./MemoEditorHeaderActions.tsx", import.meta.url), "utf8");
const editorSource = readFileSync(new URL("./EditorPane.tsx", import.meta.url), "utf8");
const diagramSource = readFileSync(new URL("./DiagramEditorPane.tsx", import.meta.url), "utf8");
+const tableSource = readFileSync(new URL("./TableEditorPane.tsx", import.meta.url), "utf8");
+const workspaceSource = readFileSync(new URL("./WorkspaceApp.tsx", import.meta.url), "utf8");
const densitySource = readFileSync(new URL("./MemoEditorChromeDensity.ts", import.meta.url), "utf8");
const editorToolbarSource = readFileSync(new URL("./EditorToolbar.tsx", import.meta.url), "utf8");
const diagramToolbarSource = readFileSync(new URL("./DiagramToolbar.tsx", import.meta.url), "utf8");
@@ -30,7 +32,8 @@ describe("shared memo editor header actions", () => {
expect(editorSource).toContain("data-ai-assistant-launcher");
expect(editorSource).not.toContain("textNoteActions=");
expect(diagramSource).not.toContain("textNoteActions=");
- expect(diagramSource).not.toContain("data-ai-assistant-launcher");
+ expect(diagramSource).toContain("data-ai-assistant-launcher");
+ expect(diagramSource).toContain("<AiSidebar");
expect(diagramSource).not.toContain("<WeChatIcon");
});
@@ -51,6 +54,20 @@ describe("shared memo editor header actions", () => {
expect(metadataRowSource).not.toContain("<Maximize2");
});
+ test("opens the same assistant on diagram and table notes", () => {
+ expect(tableSource).toContain("data-ai-assistant-launcher");
+ expect(tableSource).toContain("<AiSidebar");
+ expect(tableSource).not.toContain("infographic=");
+ expect(diagramSource).not.toContain("infographic=");
+ const diagramPane = workspaceSource.slice(workspaceSource.indexOf("<DiagramEditorPane"), workspaceSource.indexOf("<InfographicEditorPane"));
+ const tablePane = workspaceSource.slice(workspaceSource.indexOf("<TableEditorPane"), workspaceSource.indexOf("<EditorPane\n"));
+ expect(diagramPane).toContain("aiAssistantOpenToken={noteAiAssistantOpenToken}");
+ expect(diagramPane).toContain("companionAvailable={authRequired && Boolean(user) && !demoMode}");
+ expect(tablePane).toContain("aiAssistantOpenToken={noteAiAssistantOpenToken}");
+ expect(tablePane).toContain("notebooks={notebooks}");
+ expect(tablePane).toContain("companionAvailable={authRequired && Boolean(user) && !demoMode}");
+ });
+
test("leaves sequential note navigation to the memo list", () => {
expect(editorSource).not.toContain("onOpenPreviousMemo");
expect(editorSource).not.toContain("onOpenNextMemo");
diff --git a/apps/web/src/components/TableEditorPane.tsx b/apps/web/src/components/TableEditorPane.tsx
index fb07447e..df7af7b0 100644
--- a/apps/web/src/components/TableEditorPane.tsx
+++ b/apps/web/src/components/TableEditorPane.tsx
@@ -1,7 +1,7 @@
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { flexRender, getCoreRowModel, useReactTable, type ColumnDef } from "@tanstack/react-table";
-import { Check, ChevronLeft, Copy, Download, Form, Paperclip, Plus, RefreshCw, Table2, Trash2, X } from "lucide-react";
+import { Check, ChevronLeft, Copy, Download, Form, Paperclip, Plus, RefreshCw, Sparkles, Table2, Trash2, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import {
addTableField,
@@ -27,6 +27,7 @@ import {
updateTableCell,
updateTableField,
type MemoDetail,
+ type Notebook,
type TableAttachment,
type TableCellValue,
type TableDocument,
@@ -36,6 +37,9 @@ import {
type TableFilterOperator,
type TableRecord,
} from "@edgeever/shared";
+import { AiSidebar, readAiSidebarOpen, writeAiSidebarOpen } from "@/components/ai-sidebar/AiSidebar";
+import { AiSidebarErrorBoundary } from "@/components/ai-sidebar/AiSidebarErrorBoundary";
+import { IconTooltip } from "@/components/editor/EditorPaneChrome";
import { MemoTitleInput } from "@/components/MemoTitleInput";
import { TableFormDialog } from "@/components/dialogs/TableFormDialog";
import { Button } from "@/components/ui/button";
@@ -51,7 +55,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip
import { api } from "@/lib/api";
import { copyImageUrlToClipboard } from "@/lib/clipboard";
import { toDesktopResourceDownloadUrl, toDesktopResourceUrl } from "@/lib/desktop-resources";
-import { EDITOR_LOCAL_SAVE_DELAY_MS } from "@/lib/app-helpers";
+import { EDITOR_LOCAL_SAVE_DELAY_MS, formatShortcutBinding, getNotebookMoveOptions, type ShortcutSettings } from "@/lib/app-helpers";
import { createLocalEditSession } from "@/components/editor/editor-pane-helpers";
import { isLocalMemoId } from "@/lib/local-mirror";
import { isBrowserOffline } from "@/lib/network-status";
@@ -60,10 +64,17 @@ import type { MemoEditSession } from "@edgeever/shared";
type TableEditorPaneProps = {
memo: MemoDetail;
+ notebooks: Notebook[];
repository: EdgeEverRepository;
readOnly: boolean;
onBackToList: () => void;
onSaved: (memo: MemoDetail) => Promise<void>;
+ aiAssistantOpenToken: number;
+ shortcutSettings: ShortcutSettings;
+ companionAvailable: boolean;
+ beforeCompanionApply?: () => Promise<void>;
+ onCompanionNotesChanged?: () => Promise<void>;
+ onOpenCompanionNote?: (id: string, notebookId: string) => void;
};
type EditingCell = { recordId: string; fieldId: string };
@@ -467,10 +478,17 @@ const RecordCell = ({
export const TableEditorPane = ({
memo,
+ notebooks,
repository,
readOnly,
onBackToList,
onSaved,
+ aiAssistantOpenToken,
+ shortcutSettings,
+ companionAvailable,
+ beforeCompanionApply,
+ onCompanionNotesChanged,
+ onOpenCompanionNote,
}: TableEditorPaneProps) => {
const { t } = useTranslation();
const parsed = useMemo(() => parseTableDocument(memo.contentMarkdown), [memo.contentMarkdown]);
@@ -483,6 +501,13 @@ export const TableEditorPane = ({
const [saveError, setSaveError] = useState<string | null>(null);
const [saveFailed, setSaveFailed] = useState(false);
const [formOpen, setFormOpen] = useState(false);
+ const [aiAssistantOpen, setAiAssistantOpenState] = useState(readAiSidebarOpen);
+ const setAiSidebarOpen = useCallback((open: boolean) => {
+ setAiAssistantOpenState(open);
+ writeAiSidebarOpen(open);
+ }, []);
+ const handledAiAssistantOpenTokenRef = useRef(aiAssistantOpenToken);
+ const notebookOptions = useMemo(() => getNotebookMoveOptions(notebooks), [notebooks]);
const [refreshing, setRefreshing] = useState(false);
const refreshingRef = useRef(false);
const formQuery = useQuery({
@@ -530,6 +555,14 @@ export const TableEditorPane = ({
return () => { cancelled = true; };
}, [memo.id, memo.contentHash, memo.revision, parsed, readOnly, t]);
+ useEffect(() => {
+ if (handledAiAssistantOpenTokenRef.current === aiAssistantOpenToken) return;
+ handledAiAssistantOpenTokenRef.current = aiAssistantOpenToken;
+ if (readOnly || formOpen) return;
+ setAiSidebarOpen(true);
+ if (dirty) saveRef.current();
+ }, [aiAssistantOpenToken, dirty, formOpen, readOnly, setAiSidebarOpen]);
+
const changeDocument = (next: TableDocument) => {
setDocument(next);
documentRef.current = next;
@@ -673,16 +706,63 @@ export const TableEditorPane = ({
const table = useReactTable({ data: visibleRecords, columns, getCoreRowModel: getCoreRowModel(), getRowId: (row) => row.id });
+ const assistantMarkdown = document ? serializeTableDocument(document) : memo.contentMarkdown;
+ const assistantLauncher = !readOnly && !aiAssistantOpen ? (
+ <IconTooltip
+ side="left"
+ label={`${t("aiAssistant.open")} (${formatShortcutBinding(shortcutSettings.openAiAssistant)})`}
+ >
+ <Button
+ type="button"
+ variant="outline"
+ size="icon"
+ data-ai-assistant-launcher=""
+ className="absolute bottom-[calc(1.25rem+env(safe-area-inset-bottom))] right-5 z-30 size-11 rounded-full border-slate-200 bg-card text-slate-950 shadow-[0_8px_24px_rgba(15,23,42,0.14)] hover:bg-card hover:text-slate-950"
+ aria-label={t("aiAssistant.open")}
+ onClick={() => {
+ setAiSidebarOpen(true);
+ if (dirty) saveRef.current();
+ }}
+ >
+ <Sparkles className="size-5" strokeWidth={1.75} />
+ </Button>
+ </IconTooltip>
+ ) : null;
+ const assistantSidebar = (
+ <AiSidebarErrorBoundary open={aiAssistantOpen} onOpenChange={setAiSidebarOpen}>
+ <AiSidebar
+ open={aiAssistantOpen}
+ onOpenChange={setAiSidebarOpen}
+ companionAvailable={companionAvailable}
+ contentMarkdown={assistantMarkdown}
+ memoId={memo.id}
+ notebookId={memo.notebookId}
+ notebookTitle={notebookOptions.find((notebook) => notebook.id === memo.notebookId)?.name}
+ noteTitle={title}
+ beforeCompanionApply={async () => {
+ if (dirty && !(await save())) throw new Error("save failed");
+ await beforeCompanionApply?.();
+ }}
+ onCompanionNotesChanged={onCompanionNotesChanged}
+ onOpenCompanionNote={onOpenCompanionNote}
+ />
+ </AiSidebarErrorBoundary>
+ );
+
if (!document) {
return (
- <div className="flex h-full min-h-0 flex-col bg-card">
- <div className="flex items-center gap-2 border-b border-slate-200 px-3 py-2">
- <Button type="button" variant="ghost" size="sm" onClick={onBackToList}>
- <ChevronLeft className="h-4 w-4" />
- {t("structuredTable.back")}
- </Button>
+ <div className="relative flex h-full min-h-0 min-w-0 bg-card">
+ <div className="relative flex h-full min-h-0 min-w-0 flex-1 flex-col">
+ <div className="flex items-center gap-2 border-b border-slate-200 px-3 py-2">
+ <Button type="button" variant="ghost" size="sm" onClick={onBackToList}>
+ <ChevronLeft className="h-4 w-4" />
+ {t("structuredTable.back")}
+ </Button>
+ </div>
+ <p className="p-6 text-sm text-slate-500">{t("structuredTable.unreadable")}</p>
+ {assistantLauncher}
</div>
- <p className="p-6 text-sm text-slate-500">{t("structuredTable.unreadable")}</p>
+ {assistantSidebar}
</div>
);
}
@@ -746,7 +826,8 @@ export const TableEditorPane = ({
};
return (
- <div className="flex h-full min-h-0 flex-col bg-card">
+ <div className="relative flex h-full min-h-0 min-w-0 bg-card">
+ <div className="relative flex h-full min-h-0 min-w-0 flex-1 flex-col">
<div className="flex flex-wrap items-center gap-2 border-b border-slate-200 px-3 py-2">
<Tooltip>
<TooltipTrigger asChild>
@@ -983,6 +1064,9 @@ export const TableEditorPane = ({
<p className="px-4 py-8 text-sm text-slate-500">{filtered ? t("structuredTable.noMatches") : t("structuredTable.empty")}</p>
) : null}
</div>
+ {assistantLauncher}
+ </div>
+ {assistantSidebar}
</div>
);
};
diff --git a/apps/web/src/components/WorkspaceApp.tsx b/apps/web/src/components/WorkspaceApp.tsx
index f3d7d1d3..725b9653 100644
--- a/apps/web/src/components/WorkspaceApp.tsx
+++ b/apps/web/src/components/WorkspaceApp.tsx
@@ -3547,7 +3547,18 @@ export const WorkspaceApp = ({
onSaveAsTemplate={handleSaveAsTemplate}
onToggleDesktopFocusMode={toggleDesktopFocusMode}
onOpenExecutionCenter={handleOpenExecutionCenter}
-
+ 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}
/>
) : selectedMemo && selectedInfographicNote ? (
<InfographicEditorPane
@@ -3579,8 +3590,21 @@ export const WorkspaceApp = ({
<TableEditorPane
key={selectedMemo.id}
memo={selectedMemo}
+ notebooks={notebooks}
repository={repository}
readOnly={memoView === "trash" || selectedMemo.isDeleted}
+ 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}
onBackToList={() => {
clearPendingCreatedMemo();
setActivePane("memos");