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 notebook selection after create sync
tianma-ifbd3c1807767d
diff --git a/apps/web/src/components/WorkspaceApp.create-memo.test.mjs b/apps/web/src/components/WorkspaceApp.create-memo.test.mjsindex b01f6bab..584381a4 100644--- a/apps/web/src/components/WorkspaceApp.create-memo.test.mjs+++ b/apps/web/src/components/WorkspaceApp.create-memo.test.mjs@@ -5,6 +5,7 @@ const workspaceSource = readFileSync(new URL("./WorkspaceApp.tsx", import.meta.uconst editorSource = readFileSync(new URL("./EditorPane.tsx", import.meta.url), "utf8");const searchControllerSource = readFileSync(new URL("./editor/useEditorNoteSearchController.ts", import.meta.url), "utf8");const queuedSyncSource = readFileSync(new URL("../hooks/useWorkspaceQueuedSync.ts", import.meta.url), "utf8");+const desktopSyncSource = readFileSync(new URL("../lib/desktop-sync.ts", import.meta.url), "utf8");describe("desktop create-note wiring", () => {test("ignores a second new-note request while the first create is still in flight", () => {@@ -18,6 +19,15 @@ describe("desktop create-note wiring", () => {expect(queuedSyncSource).toContain("MEMO_ID_REMAPPED_EVENT");});+ test("remaps a newly selected notebook before creating notes in it", () => {+ expect(queuedSyncSource).toContain("setSelectedNotebookId((current) => current === temporaryId ? remoteId : current)");+ expect(queuedSyncSource).toContain("notifyNotebookIdRemapped(temporaryId, (result as Notebook).id)");+ expect(desktopSyncSource).toContain("notifyNotebookIdRemapped(item.entityId, result.id)");+ expect(workspaceSource.indexOf("setSelectedNotebookId(data.notebook.id)")).toBeLessThan(+ workspaceSource.indexOf("await queryClient.invalidateQueries({ queryKey: [\"notebooks\"] });")+ );+ });+test("resets in-note search on editor instance changes, not local-to-remote id remaps", () => {expect(searchControllerSource).toContain("editorInstanceKey");expect(searchControllerSource).toContain("shouldResetNoteSearchForMemoChange(previousEditorInstanceKeyRef.current, editorInstanceKey)");diff --git a/apps/web/src/components/WorkspaceApp.tsx b/apps/web/src/components/WorkspaceApp.tsxindex 8da6de73..275a163b 100644--- a/apps/web/src/components/WorkspaceApp.tsx+++ b/apps/web/src/components/WorkspaceApp.tsx@@ -76,6 +76,7 @@ import {getNotebookDropSortOrder,getNotebookMoveOptions,getMemoIdsNeedingMove,+ getCreateMemoNotebookId,resolveSelectionMoveTargetNotebookId,} from "@/lib/app-helpers";import { useBrowserBackLayer } from "@/lib/app-hooks";@@ -576,6 +577,7 @@ export const WorkspaceApp = ({setCreatedMemoEditId,setOnline: setIsOnline,setSelectedMemoId,+ setSelectedNotebookId,});const invalidateWorkspaceQueries = useCallback(async () => {@@ -678,9 +680,7 @@ export const WorkspaceApp = ({notebooks.find((notebook) => notebook.id === "nb_inbox" || notebook.slug === "inbox" || notebook.name === "等待分类")?.id ?? null;- const createMemoNotebookId =- (selectedNotebookId && notebooks.some((notebook) => notebook.id === selectedNotebookId) ? selectedNotebookId : null) ??- defaultMemoNotebookId;+ const createMemoNotebookId = getCreateMemoNotebookId(selectedNotebookId, notebooks, defaultMemoNotebookId);const canCreateMemo = Boolean(createMemoNotebookId && memoView !== "trash");const memoSelectionModeActive = memoSelectionMode || selectedMemoIds.size > 0;const mobileSearchActive = mobileBottomNavActive === "search";@@ -1186,11 +1186,11 @@ export const WorkspaceApp = ({const createNotebookMutation = useMutation({mutationFn: repository.createNotebook,onSuccess: async (data) => {- await putLocalNotebook(localDataScope, data.notebook);- await queryClient.invalidateQueries({ queryKey: ["notebooks"] });setSelectedTag(null);setSelectedNotebookId(data.notebook.id);setActivePane("memos");+ await putLocalNotebook(localDataScope, data.notebook);+ await queryClient.invalidateQueries({ queryKey: ["notebooks"] });},});diff --git a/apps/web/src/hooks/useWorkspaceQueuedSync.ts b/apps/web/src/hooks/useWorkspaceQueuedSync.tsindex cf59cb37..69806117 100644--- a/apps/web/src/hooks/useWorkspaceQueuedSync.ts+++ b/apps/web/src/hooks/useWorkspaceQueuedSync.ts@@ -3,7 +3,7 @@ import type { QueryClient } from "@tanstack/react-query";import type { MemoDetail, MemoTemplate, Notebook, Resource } from "@edgeever/shared";import { isBrowserOffline } from "@/lib/network-status";import { emptySyncQueueSummary, type SyncQueueSummary } from "@/lib/sync-queue";-import { MEMO_ID_REMAPPED_EVENT, notifyMemoIdRemapped, notifyMemoSyncAcknowledged } from "@/lib/sync-events";+import { MEMO_ID_REMAPPED_EVENT, NOTEBOOK_ID_REMAPPED_EVENT, notifyMemoIdRemapped, notifyMemoSyncAcknowledged, notifyNotebookIdRemapped } from "@/lib/sync-events";import { observeLocalMemoIdMappings, putLocalMemo, replaceLocalMemoId } from "@/lib/local-mirror";import { remapMemoIdsInLists } from "@/lib/memo-list-cache";import { preserveRemappedMemoDetailQueries, resolveSyncedMemoId } from "@/lib/workspace-refresh";@@ -17,6 +17,7 @@ type UseWorkspaceQueuedSyncOptions = {setCreatedMemoEditId: Dispatch<SetStateAction<string | null>>;setOnline: Dispatch<SetStateAction<boolean>>;setSelectedMemoId: Dispatch<SetStateAction<string | null>>;+ setSelectedNotebookId: Dispatch<SetStateAction<string | null>>;};export const useWorkspaceQueuedSync = ({@@ -28,6 +29,7 @@ export const useWorkspaceQueuedSync = ({setCreatedMemoEditId,setOnline,setSelectedMemoId,+ setSelectedNotebookId,}: UseWorkspaceQueuedSyncOptions) => {const [syncSummary, setSyncSummary] = useState<SyncQueueSummary>(emptySyncQueueSummary);const [isSyncingQueuedChanges, setIsSyncingQueuedChanges] = useState(false);@@ -73,6 +75,25 @@ export const useWorkspaceQueuedSync = ({return () => window.removeEventListener(MEMO_ID_REMAPPED_EVENT, handleMemoIdRemapped);}, [queryClient]);+ useEffect(() => {+ const handleNotebookIdRemapped = (event: Event) => {+ const { temporaryId, remoteId } = (event as CustomEvent<{ temporaryId: string; remoteId: string }>).detail;+ queryClient.setQueryData<{ notebooks: Notebook[] }>(["notebooks"], (current) => {+ if (!current) return current;+ const hasRemote = current.notebooks.some((notebook) => notebook.id === remoteId);+ return {+ ...current,+ notebooks: hasRemote+ ? current.notebooks.filter((notebook) => notebook.id !== temporaryId)+ : current.notebooks.map((notebook) => notebook.id === temporaryId ? { ...notebook, id: remoteId } : notebook),+ };+ });+ setSelectedNotebookId((current) => current === temporaryId ? remoteId : current);+ };+ window.addEventListener(NOTEBOOK_ID_REMAPPED_EVENT, handleNotebookIdRemapped);+ return () => window.removeEventListener(NOTEBOOK_ID_REMAPPED_EVENT, handleNotebookIdRemapped);+ }, [queryClient, setSelectedNotebookId]);+const invalidateSyncQueries = useCallback(() => Promise.all([queryClient.invalidateQueries({ queryKey: ["memos"] }),queryClient.invalidateQueries({ queryKey: ["memo"] }),@@ -149,6 +170,7 @@ export const useWorkspaceQueuedSync = ({} else if (item.kind === "notebook.create" && "name" in result && temporaryId) {await deleteLocalNotebook(localDataScope, temporaryId);await putLocalNotebook(localDataScope, result as Notebook);+ notifyNotebookIdRemapped(temporaryId, (result as Notebook).id);} else if (item.kind === "notebook.update" && "name" in result) {await putLocalNotebook(localDataScope, result as Notebook);} else if (item.kind === "template.create" && "contentMarkdown" in result && temporaryId) {diff --git a/apps/web/src/lib/app-helpers.test.mjs b/apps/web/src/lib/app-helpers.test.mjsindex 9506a990..7e935509 100644--- a/apps/web/src/lib/app-helpers.test.mjs+++ b/apps/web/src/lib/app-helpers.test.mjs@@ -14,6 +14,7 @@ import {NOTEBOOK_TREE_COLLAPSED_IDS_STORAGE_KEY,SHORTCUT_SETTINGS_STORAGE_KEY,getSearchShortcutScope,+ getCreateMemoNotebookId,getShortcutActionForEvent,canToggleNotebookSidebar,getNotebookSortComparator,@@ -46,6 +47,13 @@ import {const originalWindow = globalThis.window;+test("a stale selected notebook cannot send a new note to the inbox", () => {+ const notebooks = [{ id: "nb_inbox" }, { id: "nb_remote" }];+ expect(getCreateMemoNotebookId("nb_local", notebooks, "nb_inbox")).toBeNull();+ expect(getCreateMemoNotebookId("nb_remote", notebooks, "nb_inbox")).toBe("nb_remote");+ expect(getCreateMemoNotebookId(null, notebooks, "nb_inbox")).toBe("nb_inbox");+});+const installLocalStorage = (initialValue = null) => {const values = new Map();if (initialValue !== null) {diff --git a/apps/web/src/lib/app-helpers.ts b/apps/web/src/lib/app-helpers.tsindex 3f6a3d9b..dea28645 100644--- a/apps/web/src/lib/app-helpers.ts+++ b/apps/web/src/lib/app-helpers.ts@@ -69,6 +69,14 @@ export const isTextEntryTarget = (target: EventTarget | null) =>export const getSearchShortcutScope = (selectedMemoId: string | null): "note" | "memo-list" =>selectedMemoId ? "note" : "memo-list";+export const getCreateMemoNotebookId = (+ selectedNotebookId: string | null,+ notebooks: ReadonlyArray<Pick<Notebook, "id">>,+ defaultNotebookId: string | null,+) => selectedNotebookId+ ? notebooks.some((notebook) => notebook.id === selectedNotebookId) ? selectedNotebookId : null+ : defaultNotebookId;+export const getNotebookAncestorIds = (nodes: NotebookNode[], targetNotebookId: string) => {const walk = (items: NotebookNode[], ancestors: string[]): string[] | null => {for (const node of items) {diff --git a/apps/web/src/lib/desktop-sync.test.mjs b/apps/web/src/lib/desktop-sync.test.mjsindex 45c0d941..f3173e0d 100644--- a/apps/web/src/lib/desktop-sync.test.mjs+++ b/apps/web/src/lib/desktop-sync.test.mjs@@ -25,6 +25,51 @@ const {} = await import("./desktop-sync.ts");const { api, ApiRequestError } = await import("./api.ts");+test("desktop notebook create announces its durable id after sidecar acknowledgment", async () => {+ const previousWindow = globalThis.window;+ const previousNavigator = globalThis.navigator;+ const originalCreateNotebook = api.createNotebook;+ const events = [];+ const calls = [];+ let outboxReads = 0;+ const item = { id: 4, version: 1, kind: "notebook.create", entityId: "nb_local_1", payload: { name: "测试" } };+ globalThis.window = {+ dispatchEvent: (event) => { events.push(event); return true; },+ edgeeverDesktop: {+ isAvailable: true,+ listStagedResources: async () => [],+ listStagedResourceAliases: async () => [],+ sidecarRequest: async (method, params) => {+ calls.push(method);+ if (method === "sync.outbox.list") {+ if (params.limit === 200) return { items: [] };+ outboxReads += 1;+ return { items: outboxReads === 1 ? [] : [item] };+ }+ if (method === "sync.status") return { pending: 1, syncing: 0 };+ return { ok: true };+ },+ },+ };+ globalThis.navigator = { onLine: true };+ api.createNotebook = async () => ({ notebook: { id: "nb_remote_1", name: "测试", parentId: null } });+ try {+ const result = await syncDesktopData();+ expect(result.failed).toBe(0);+ expect(calls).toContain("sync.outbox.ack");+ expect(events.find((event) => event.type === "edgeever:notebook-id-remapped")?.detail).toEqual({+ temporaryId: "nb_local_1",+ remoteId: "nb_remote_1",+ });+ expect(calls.indexOf("sync.outbox.ack")).toBeLessThan(calls.indexOf("sync.status"));+ } finally {+ api.createNotebook = originalCreateNotebook;+ globalThis.navigator = previousNavigator;+ if (previousWindow === undefined) delete globalThis.window;+ else globalThis.window = previousWindow;+ }+});+test("desktop explicit discard clears a conflict whose cloud note is gone", async () => {const previousWindow = globalThis.window;const originalGetMemo = api.getMemo;diff --git a/apps/web/src/lib/desktop-sync.ts b/apps/web/src/lib/desktop-sync.tsindex df950c4d..a09b29cc 100644--- a/apps/web/src/lib/desktop-sync.ts+++ b/apps/web/src/lib/desktop-sync.ts@@ -19,7 +19,7 @@ import { api, ApiRequestError } from "@/lib/api";import { isDesktopResourceRuntime, mapMarkdownResourceUrls, mapTiptapResourceUrls, toApiResourceUrl } from "@/lib/desktop-resources";import { readEmergencyDraft } from "@/lib/emergency-draft";import { notebookDeleteIdsFromPayload } from "@/lib/notebook-delete";-import { notifyMemoIdRemapped, notifyMemoSyncAcknowledged, notifySyncQueueChanged } from "@/lib/sync-events";+import { notifyMemoIdRemapped, notifyMemoSyncAcknowledged, notifyNotebookIdRemapped, notifySyncQueueChanged } from "@/lib/sync-events";type StagedResourceRewrite = { memoId: string; placeholder: string; url: string };@@ -476,7 +476,7 @@ const syncOutboxItem = async (item: DesktopOutboxItem, stagedRewrites: StagedResif (item.kind === "notebook.create") {const data = await api.createNotebook({ name: String(payload.name ?? ""), parentId: typeof payload.parentId === "string" ? payload.parentId : null });await acknowledge(item, undefined, data.notebook);- return null;+ return data.notebook;}if (item.kind === "notebook.update") {@@ -581,6 +581,9 @@ const syncOutbox = async (stagedRewrites: StagedResourceRewrite[], onlyKinds?: S// leaves a window where the next autosave still sends revision 0.notifyMemoIdRemapped(new Map([[item.entityId, result.id]]));}+ if (item.kind === "notebook.create" && result && typeof result === "object" && "id" in result && typeof result.id === "string") {+ notifyNotebookIdRemapped(item.entityId, result.id);+ }if (result && typeof result === "object" && "id" in result && typeof result.id === "string" && "contentJson" in result) {const syncedMemo = result as DesktopRpcResponses["memo.get"]["memo"];syncedMemos.set(result.id, syncedMemo);diff --git a/apps/web/src/lib/sync-events.ts b/apps/web/src/lib/sync-events.tsindex 77bf143f..4a997ce8 100644--- a/apps/web/src/lib/sync-events.ts+++ b/apps/web/src/lib/sync-events.ts@@ -3,6 +3,7 @@ import type { MemoDetail } from "@edgeever/shared";export const SYNC_QUEUE_CHANGED_EVENT = "edgeever:sync-queue-changed";export const SYNC_QUEUE_DEFERRED_EVENT = "edgeever:sync-queue-deferred";export const MEMO_ID_REMAPPED_EVENT = "edgeever:memo-id-remapped";+export const NOTEBOOK_ID_REMAPPED_EVENT = "edgeever:notebook-id-remapped";export const MEMO_SYNC_ACKNOWLEDGED_EVENT = "edgeever:memo-sync-acknowledged";export const notifySyncQueueChanged = () => {@@ -18,6 +19,11 @@ export const notifyMemoIdRemapped = (memoIdMappings: ReadonlyMap<string, string>window.dispatchEvent(new CustomEvent(MEMO_ID_REMAPPED_EVENT, { detail: memoIdMappings }));};+export const notifyNotebookIdRemapped = (temporaryId: string, remoteId: string) => {+ if (temporaryId === remoteId) return;+ window.dispatchEvent(new CustomEvent(NOTEBOOK_ID_REMAPPED_EVENT, { detail: { temporaryId, remoteId } }));+};+export const notifyMemoSyncAcknowledged = (memo: MemoDetail) => {window.dispatchEvent(new CustomEvent(MEMO_SYNC_ACKNOWLEDGED_EVENT, { detail: memo }));};