AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
fix(web): bind editor metadata to memo identity (#460)
tianma-if33ace487fb19
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsxindex cacec367..ef92563a 100644--- a/apps/web/src/components/EditorPane.tsx+++ b/apps/web/src/components/EditorPane.tsx@@ -265,8 +265,10 @@ import {type NoteLinkHintPosition,} from "./editor/EditorPaneChrome";import {+ getWritableEditorMemoFields,resolveEditorDraftState,shouldReplaceEditorDocument,+ type EditorMemoFields,} from "./editor/editor-draft-state";import {pendingEditorInsertMatchesMemo,@@ -436,8 +438,10 @@ const RichEditorPane = ({const queryClient = useQueryClient();const resourceInsertionLimit = useMemo(createFileBatchQueue, []);const isSelectionMode = Boolean(selectionActionBar);- const [title, setTitle] = useState("");- const [tagsText, setTagsText] = useState("");+ // Keep field ownership and values in one React state update. memoRef changes+ // synchronously during hydration, before a new title/tags render can commit.+ const [memoFields, setMemoFields] = useState<EditorMemoFields>({ memoId: null, title: "", tagsText: "" });+ const { memoId: fieldsMemoId, title, tagsText } = memoFields;const {dirtyVersion,hasUnsavedChanges,@@ -823,6 +827,9 @@ const RichEditorPane = ({mappings,);memoRef.current = { ...currentMemo, id: nextMemoId };+ setMemoFields((fields) => fields.memoId === previousMemoId+ ? { ...fields, memoId: nextMemoId }+ : fields);if (editingMemoIdRef.current === previousMemoId) editingMemoIdRef.current = nextMemoId;if (hydratedMemoIdRef.current === previousMemoId) {hydratedMemoIdRef.current = nextMemoId;@@ -1945,7 +1952,7 @@ const RichEditorPane = ({if (!currentMemo ||currentMemo.isDeleted ||- hydratedMemoIdRef.current !== currentMemo.id ||+ !getWritableEditorMemoFields(memoFields, currentMemo.id, hydratedMemoIdRef.current, hydratingRef.current) ||(!useMobilePlainTextEditor && !isEditorReady(currentEditor))) {return Promise.resolve();@@ -1967,7 +1974,7 @@ const RichEditorPane = ({updatedAt: new Date().toISOString(),});},- [getMobilePlainTextValue, markdownSource, tagsText, title, useMarkdownSourceEditor, useMobilePlainTextEditor]+ [getMobilePlainTextValue, markdownSource, memoFields, tagsText, title, useMarkdownSourceEditor, useMobilePlainTextEditor]);const markDirty = useCallback(() => {@@ -1976,13 +1983,13 @@ const RichEditorPane = ({hydratingRef.current ||currentMemo?.isDeleted ||!currentMemo ||- hydratedMemoIdRef.current !== currentMemo.id+ !getWritableEditorMemoFields(memoFields, currentMemo.id, hydratedMemoIdRef.current, hydratingRef.current)) {return;}markDirtyStatus();- }, [markDirtyStatus]);+ }, [markDirtyStatus, memoFields]);const getCurrentMarkdownForAi = useCallback(() => {if (useMobilePlainTextEditor) return getMobilePlainTextValue();@@ -2189,17 +2196,19 @@ const RichEditorPane = ({}return JSON.stringify({+ memoId: fieldsMemoId,title,tagsText,contentJson,});- }, [getCurrentContentJson, tagsText, title]);+ }, [fieldsMemoId, getCurrentContentJson, tagsText, title]);useEffect(() => {const handleLocalDatabaseInterrupted = () => {const currentMemo = memoRef.current;const contentJson = getCurrentContentJson();- if (currentMemo && contentJson && !currentMemo.isDeleted) {+ if (currentMemo && contentJson && !currentMemo.isDeleted &&+ getWritableEditorMemoFields(memoFields, currentMemo.id, hydratedMemoIdRef.current, hydratingRef.current)) {persistEmergencyDraft({memoId: currentMemo.id,expectedRevision: currentMemo.revision,@@ -2217,7 +2226,7 @@ const RichEditorPane = ({window.addEventListener(LOCAL_DATABASE_INTERRUPTED_EVENT, handleLocalDatabaseInterrupted);return () => window.removeEventListener(LOCAL_DATABASE_INTERRUPTED_EVENT, handleLocalDatabaseInterrupted);- }, [getCurrentContentJson, setHasUnsavedChanges, setSaveConflictInfo, setSaveState, tagsText, title]);+ }, [getCurrentContentJson, memoFields, setHasUnsavedChanges, setSaveConflictInfo, setSaveState, tagsText, title]);useEffect(() => {const currentEditor = editorRef.current;@@ -2232,8 +2241,7 @@ const RichEditorPane = ({setHydratedEditorMemoId(null);editingMemoIdRef.current = null;setHasUnsavedChanges(false);- setTitle("");- setTagsText("");+ setMemoFields({ memoId: null, title: "", tagsText: "" });setMobilePlainText("");setMobilePlainTextElementValue(mobileTextAreaRef.current, "");setSaveState("idle");@@ -2250,6 +2258,7 @@ const RichEditorPane = ({if (!sameMemo) {hydratedMemoIdRef.current = null;+ editSessionRef.current = null;appliedEditorSourceKeyRef.current = null;clearMarkdownSnapshot();const immediateDraft = resolveEditorDraftState({ memo, draft: null, queuedUpdate: null });@@ -2258,8 +2267,7 @@ const RichEditorPane = ({setHasUnsavedChanges(false);setSaveState("idle");setSaveConflictInfo(null);- setTitle(immediateDraft.title);- setTagsText(immediateDraft.tagsText);+ setMemoFields({ memoId: memo.id, title: immediateDraft.title, tagsText: immediateDraft.tagsText });setMobilePlainText(immediateDraft.contentMarkdown);setMobilePlainTextElementValue(mobileTextAreaRef.current, immediateDraft.contentMarkdown);hydrateMarkdownSource(memo.id, immediateDraft.contentJson, immediateDraft.contentMarkdown);@@ -2395,6 +2403,8 @@ const RichEditorPane = ({await localDb.drafts.delete(memo.id);removeEmergencyDraft(memo.id);}+ // Draft cleanup is async; the selected memo may have changed meanwhile.+ if (cancelled || editingMemoIdRef.current !== memo.id) return;const {title: nextTitle,tagsText: nextTagsText,@@ -2466,8 +2476,7 @@ const RichEditorPane = ({setSaveState("idle");setSaveConflictInfo(null);}- setTitle(nextTitle);- setTagsText(nextTagsText);+ setMemoFields({ memoId: memo.id, title: nextTitle, tagsText: nextTagsText });setMobilePlainText(nextMarkdown);const keptLiveMarkdown = hydrateMarkdownSource(memo.id, nextContent, nextMarkdown);setMobilePlainTextElementValue(mobileTextAreaRef.current, nextMarkdown);@@ -2737,8 +2746,15 @@ const RichEditorPane = ({const currentMemo = memoRef.current;const contentJson = getCurrentContentJson();const editSession = editSessionRef.current;+ const writableFields = getWritableEditorMemoFields(+ memoFields,+ currentMemo?.id ?? null,+ hydratedMemoIdRef.current,+ hydratingRef.current,+ );- if (!currentMemo || !contentJson || !editSession || hydratedMemoIdRef.current !== currentMemo.id) {+ if (!currentMemo || !contentJson || !editSession || editSession.memoId !== currentMemo.id ||+ !writableFields) {throw new Error("No memo selected");}@@ -2756,16 +2772,16 @@ const RichEditorPane = ({expectedRevision: currentMemo.revision,expectedContentHash: currentMemo.contentHash,editSessionId: editSession.id,- title,+ title: writableFields.title,contentJson,contentMarkdown: useMarkdownSourceEditor ? markdownSource : undefined,- tags: parseTagsText(tagsText),+ tags: parseTagsText(writableFields.tagsText),};persistEmergencyDraft({memoId: currentMemo.id,expectedRevision: currentMemo.revision,- title,- tagsText,+ title: writableFields.title,+ tagsText: writableFields.tagsText,contentJson,updatedAt: new Date().toISOString(),});@@ -2777,11 +2793,17 @@ const RichEditorPane = ({setSaveState("saving");},onSuccess: async ({ memo: savedMemo, snapshot, queued }) => {- setStorageSaveError(false);removeEmergencyDraft(savedMemo.id);+ // A previous note's save may finish after the user switches notes.+ // Update its cache, but leave the active editor and save state alone.+ if (memoRef.current?.id !== savedMemo.id) {+ await onSaved(savedMemo);+ return;+ }+ setStorageSaveError(false);memoRef.current = savedMemo;const currentEditSession = editSessionRef.current;- if (currentEditSession) {+ if (currentEditSession?.memoId === savedMemo.id) {editSessionRef.current = {...currentEditSession,baseRevision: savedMemo.revision,@@ -2803,6 +2825,7 @@ const RichEditorPane = ({}await onSaved(savedMemo);+ if (memoRef.current?.id !== savedMemo.id) return;if (currentSnapshot() === snapshot) {setMobilePlainText(docToMarkdown(savedMemo.contentJson));@@ -3156,7 +3179,8 @@ const RichEditorPane = ({const markMobilePlainTextDirty = useCallback(() => {const currentMemo = memoRef.current;- if (hydratingRef.current || currentMemo?.isDeleted) {+ if (hydratingRef.current || currentMemo?.isDeleted ||+ !getWritableEditorMemoFields(memoFields, currentMemo?.id ?? null, hydratedMemoIdRef.current, hydratingRef.current)) {return;}@@ -3193,7 +3217,7 @@ const RichEditorPane = ({mutateSave();}, EDITOR_LOCAL_SAVE_DELAY_MS);- }, [getMobilePlainTextValue, mutateSave, persistCurrentDraft, saveMutationPending, saveState, tagsText, title]);+ }, [getMobilePlainTextValue, memoFields, mutateSave, persistCurrentDraft, saveMutationPending, saveState, tagsText, title]);useEffect(() => {if (!useMobilePlainTextEditor) {@@ -3271,6 +3295,7 @@ const RichEditorPane = ({const { memo: remoteMemo } = await repository.adoptCloudMemo(currentMemo.id);await onSaved(remoteMemo);+ if (memoRef.current?.id !== remoteMemo.id) return;setHasUnsavedChanges(false);setSaveConflictInfo(null);@@ -3288,8 +3313,7 @@ const RichEditorPane = ({editingMemoIdRef.current = remoteMemo.id;appliedEditorSourceKeyRef.current = `memo:${remoteMemo.id}:${remoteMemo.revision}:${remoteMemo.updatedAt}:${remoteMemo.contentHash}:${nextTitle}:${nextTagsText}:${nextMarkdown}`;- setTitle(nextTitle);- setTagsText(nextTagsText);+ setMemoFields({ memoId: remoteMemo.id, title: nextTitle, tagsText: nextTagsText });setMobilePlainText(nextMarkdown);hydrateMarkdownSource(remoteMemo.id, nextContent, nextMarkdown, { force: true });setMobilePlainTextElementValue(mobileTextAreaRef.current, nextMarkdown);@@ -3476,15 +3500,20 @@ const RichEditorPane = ({notebookId,}).then(async (data) => {- memoRef.current = data.memo;+ if (memoRef.current?.id === data.memo.id) memoRef.current = data.memo;await onSaved(data.memo);+ if (memoRef.current?.id !== data.memo.id) return;setSaveState("saved");- window.setTimeout(() => setSaveState("idle"), 1200);+ window.setTimeout(() => {+ if (memoRef.current?.id === data.memo.id) setSaveState("idle");+ }, 1200);+ })+ .catch(() => {+ if (memoRef.current?.id === sourceMemo.id) setSaveState("error");})- .catch(() => setSaveState("error")).finally(() => {setNotebookUpdatePending(false);- setMobileNotebookSheetOpen(false);+ if (memoRef.current?.id === sourceMemo.id) setMobileNotebookSheetOpen(false);});};@@ -3691,7 +3720,9 @@ const RichEditorPane = ({value={title}readOnly={effectiveReadOnly}onValueChange={(nextTitle) => {- setTitle(nextTitle);+ setMemoFields((fields) => fields.memoId === memo.id+ ? { ...fields, title: nextTitle }+ : fields);persistCurrentDraft(nextTitle, tagsText, getMobilePlainTextValue());markDirty();}}@@ -3713,7 +3744,9 @@ const RichEditorPane = ({onMobileNotebookPickerOpenChange={setMobileNotebookSheetOpen}onNotebookChange={handleNotebookChange}onTagsChange={(nextTagsText) => {- setTagsText(nextTagsText);+ setMemoFields((fields) => fields.memoId === memo.id+ ? { ...fields, tagsText: nextTagsText }+ : fields);persistCurrentDraft(title, nextTagsText, getMobilePlainTextValue());markDirty();}}diff --git a/apps/web/src/components/editor/editor-draft-state.test.mjs b/apps/web/src/components/editor/editor-draft-state.test.mjsindex 08c4cea9..a8742f06 100644--- a/apps/web/src/components/editor/editor-draft-state.test.mjs+++ b/apps/web/src/components/editor/editor-draft-state.test.mjs@@ -1,6 +1,7 @@import { describe, expect, test } from "bun:test";import { markdownToDoc } from "@edgeever/shared";import {+ getWritableEditorMemoFields,resolveEditorDraftState,shouldReplaceEditorDocument,} from "./editor-draft-state.ts";@@ -226,3 +227,31 @@ describe("editor document hydration", () => {expect(shouldReplaceEditorDocument(null, doc("remote body"))).toBe(true);});});++describe("editor write ownership", () => {+ test("rejects the previous note's title and tags while the editor switches notes", () => {+ const previousFields = { memoId: "memo-a", title: "Title A", tagsText: "tag-a" };++ expect(getWritableEditorMemoFields(previousFields, "memo-b", "memo-b", false)).toBeNull();+ expect(getWritableEditorMemoFields(previousFields, "memo-b", "memo-a", false)).toBeNull();+ expect(getWritableEditorMemoFields(previousFields, "memo-a", "memo-a", true)).toBeNull();+ });++ test("accepts a recovered old-format draft once all fields belong to its note", () => {+ const recoveredMemo = { ...memo, id: "memo-b" };+ const recovered = resolveEditorDraftState({+ memo: recoveredMemo,+ draft: {+ memoId: recoveredMemo.id,+ title: "Recovered B",+ tagsText: "tag-b",+ contentJson: doc("recovered body"),+ updatedAt: "2026-01-04T00:00:00.000Z",+ },+ });+ const fields = { memoId: recoveredMemo.id, title: recovered.title, tagsText: recovered.tagsText };++ expect(getWritableEditorMemoFields(fields, recoveredMemo.id, recoveredMemo.id, false)).toEqual(fields);+ expect(recovered.contentMarkdown).toBe("recovered body");+ });+});diff --git a/apps/web/src/components/editor/editor-draft-state.ts b/apps/web/src/components/editor/editor-draft-state.tsindex 69aeda27..bdc766fd 100644--- a/apps/web/src/components/editor/editor-draft-state.ts+++ b/apps/web/src/components/editor/editor-draft-state.ts@@ -15,6 +15,23 @@ import { parseTagsText } from "@/lib/utils";export type EditorDraftSource = "draft" | "queue" | "memo";+export type EditorMemoFields = {+ memoId: string | null;+ title: string;+ tagsText: string;+};++export const getWritableEditorMemoFields = (+ fields: EditorMemoFields,+ memoId: string | null,+ hydratedMemoId: string | null,+ hydrating: boolean,+): EditorMemoFields | null => (+ !hydrating && memoId && fields.memoId === memoId && hydratedMemoId === memoId+ ? fields+ : null+);+export type EditorDraftState = {source: EditorDraftSource;sourceKey: string;