Skip to content

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

fix(sync): resolve memo conflicts with adopt-cloud and copy-draft actions

tianma-if72b479155741
diff --git a/apps/mobile/src/lib/mobile-locale.tsx b/apps/mobile/src/lib/mobile-locale.tsx
index bb6bf321..67abe597 100644
--- a/apps/mobile/src/lib/mobile-locale.tsx
+++ b/apps/mobile/src/lib/mobile-locale.tsx
@@ -40,9 +40,17 @@ const mobileOnlyTranslations = new Map<string, string>([
["待同步", "Pending sync"],
["已同步", "Synced"],
["查看并处理同步冲突", "Review and resolve the sync conflict"],
- ["云端笔记已在其他设备更新,本地修改没有覆盖云端。你可以查看版本历史,或放弃本地修改并使用云端版本。", "The cloud note was updated on another device. Your local changes did not overwrite it. View version history, or discard the local changes and use the cloud version."],
+ ["云端笔记已在其他标签页、设备,或离线期间被更新,本地草稿无法直接覆盖。可先复制本地草稿,再采用云端版本后继续编辑。", "The cloud note was updated in another tab, on another device, or while you were offline. Copy your local draft, then use the cloud version before editing again."],
+ ["云端笔记已在其他标签页、设备,或离线期间被更新。可先复制本地草稿,再采用云端版本后继续编辑。", "The cloud note was updated in another tab, on another device, or while you were offline. Copy your local draft, then use the cloud version before editing again."],
["查看历史", "View history"],
["使用云端版本", "Use cloud version"],
+ ["采用云端并重新加载", "Use cloud and reload"],
+ ["采用云端版本失败", "Could not use the cloud version"],
+ ["复制本地草稿", "Copy local draft"],
+ ["本地草稿已复制到剪贴板。", "Local draft copied to the clipboard."],
+ ["没有可复制的本地草稿。", "There is no local draft to copy."],
+ ["已复制", "Copied"],
+ ["更多", "More"],
["加载失败", "Failed to load"],
["请稍后重试", "Please try again later"],
["重试", "Retry"],
diff --git a/apps/mobile/src/lib/sync-queue.test.ts b/apps/mobile/src/lib/sync-queue.test.ts
index f3c48537..5e46c4b7 100644
--- a/apps/mobile/src/lib/sync-queue.test.ts
+++ b/apps/mobile/src/lib/sync-queue.test.ts
@@ -16,7 +16,15 @@ mock.module("@react-native-async-storage/async-storage", () => ({
},
}));
-const { listMobileSyncQueueItems, queueMobileMemoCreate, queueMobileMemoUpdate, syncMobileQueuedChanges } = await import("./sync-queue");
+const {
+ discardMobileMemoConflict,
+ getMobileConflictDraftClipboardText,
+ listMobileSyncQueueItems,
+ queueMobileMemoCreate,
+ queueMobileMemoUpdate,
+ syncMobileQueuedChanges,
+} = await import("./sync-queue");
+const { writeMobileMemoDraft, clearMobileMemoDraft } = await import("./mobile-drafts");
const basePayload = {
memoId: "memo-1",
@@ -63,6 +71,51 @@ test("keeps a stale mobile edit as an explicit conflict without overwriting the
expect(queued?.payload.contentMarkdown).toBe("first");
});
+test("discardMobileMemoConflict clears the local conflict and returns the cloud memo", async () => {
+ const scope = "https://one.example";
+ await queueMobileMemoUpdate(scope, basePayload);
+ await syncMobileQueuedChanges({
+ createMemoEditSession: async () => ({
+ editSession: { id: "edit-2", baseRevision: 2, baseContentHash: "hash-2" },
+ }),
+ updateMemo: async () => {
+ throw new Error("should not update");
+ },
+ } as never, scope);
+
+ const cloud = createMemo({ revision: 3, contentHash: "hash-3", contentMarkdown: "cloud wins", title: "Cloud" });
+ const client = {
+ getMemo: async () => ({ memo: cloud }),
+ };
+
+ const adopted = await discardMobileMemoConflict(client as never, scope, "memo-1");
+ expect(adopted).toEqual(cloud);
+ expect(await listMobileSyncQueueItems(scope)).toEqual([]);
+});
+
+test("getMobileConflictDraftClipboardText prefers the queued update payload", async () => {
+ const scope = "https://one.example";
+ await queueMobileMemoUpdate(scope, {
+ ...basePayload,
+ title: "Queued title",
+ contentMarkdown: "queued body",
+ tags: ["demo"],
+ });
+ await writeMobileMemoDraft({
+ memoId: "memo-1",
+ expectedRevision: 1,
+ title: "Draft title",
+ contentMarkdown: "draft body",
+ notebookId: "notebook-1",
+ tagsText: "other",
+ updatedAt: "2026-07-15T00:00:00.000Z",
+ });
+
+ const text = await getMobileConflictDraftClipboardText(scope, "memo-1");
+ expect(text).toBe("# Queued title\n#demo\n\nqueued body");
+ await clearMobileMemoDraft("memo-1");
+});
+
test("rebases a newer local save when an older save finishes syncing", async () => {
await queueMobileMemoUpdate("https://one.example", basePayload);
diff --git a/apps/mobile/src/lib/sync-queue.ts b/apps/mobile/src/lib/sync-queue.ts
index c9b23998..1909181b 100644
--- a/apps/mobile/src/lib/sync-queue.ts
+++ b/apps/mobile/src/lib/sync-queue.ts
@@ -3,6 +3,7 @@ import { ApiRequestError, type createEdgeEverClient } from "@edgeever/client";
import {
createEmptySyncQueueSummary,
createEmptySyncRunResult,
+ formatLocalDraftClipboardText,
getNextSyncQueueRetryDelay,
getSyncRetryAt,
summarizeSyncQueue,
@@ -10,6 +11,7 @@ import {
type SyncQueueSummary,
type SyncRunResult,
} from "@edgeever/shared";
+import { readMobileMemoDraft } from "./mobile-drafts";
const LEGACY_SYNC_QUEUE_KEY = "edgeever.mobile.syncQueue.v1";
const SYNC_QUEUE_KEY_PREFIX = "edgeever.mobile.syncQueue.v2";
@@ -145,6 +147,62 @@ export const deleteMobileSyncQueueItem = async (scope: string, id: string) => {
return loadMobileSyncQueueSummary(scope);
};
+/**
+ * Discard a single note's conflicted local queue item and return the
+ * authoritative cloud memo so the UI can rehydrate cleanly.
+ */
+export const discardMobileMemoConflict = async (
+ client: ReturnType<typeof createEdgeEverClient>,
+ scope: string,
+ memoId: string,
+) => {
+ const remote = await client.getMemo(memoId, { includeDeleted: true });
+ const queueId = getMobileMemoUpdateQueueId(memoId);
+ const items = await readMobileSyncQueue(scope);
+
+ for (const item of items) {
+ if (item.memoId !== memoId) {
+ continue;
+ }
+ if (item.id === queueId || item.status === "conflict") {
+ await removeMobileSyncQueueItem(scope, item.id);
+ }
+ }
+
+ return remote.memo;
+};
+
+/** Resolve the best local draft snapshot to copy when a conflict is shown. */
+export const getMobileConflictDraftClipboardText = async (scope: string, memoId: string) => {
+ const [queued, draft] = await Promise.all([
+ readMobileSyncQueue(scope).then((items) =>
+ items.find((item) => item.memoId === memoId && item.kind === "memo.update")
+ ),
+ readMobileMemoDraft(memoId),
+ ]);
+
+ if (queued && queued.kind === "memo.update") {
+ return formatLocalDraftClipboardText({
+ title: queued.payload.title,
+ tags: queued.payload.tags,
+ contentMarkdown: queued.payload.contentMarkdown,
+ });
+ }
+
+ if (draft) {
+ return formatLocalDraftClipboardText({
+ title: draft.title,
+ tags: draft.tagsText
+ .split(/[,,]/u)
+ .map((tag) => tag.trim())
+ .filter(Boolean),
+ contentMarkdown: draft.contentMarkdown,
+ });
+ }
+
+ return null;
+};
+
export const syncMobileQueuedChanges = async (
client: ReturnType<typeof createEdgeEverClient>,
scope: string,
diff --git a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx b/apps/mobile/src/screens/WorkspaceMemoDetail.tsx
index 46d54304..1bb5d6ea 100644
--- a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx
+++ b/apps/mobile/src/screens/WorkspaceMemoDetail.tsx
@@ -294,7 +294,9 @@ export const MemoDetailModal = ({
isSharing,
memo,
notebookName,
+ onAdoptCloudVersion,
onClose,
+ onCopyLocalDraft,
onDelete,
onDeleteResource,
onRichEdit,
@@ -313,7 +315,9 @@ export const MemoDetailModal = ({
isSharing: boolean;
memo: MemoDetail | null;
notebookName: string;
+ onAdoptCloudVersion: (memo: MemoDetail) => void;
onClose: () => void;
+ onCopyLocalDraft: (memo: MemoDetail) => void;
onDelete: (memo: MemoDetail) => void;
onDeleteResource: (memo: MemoDetail, target: MobileResourceTarget) => Promise<void>;
onRichEdit: (memo: MemoDetail) => void;
@@ -506,6 +510,40 @@ export const MemoDetailModal = ({
</View>
</View>
+ {syncStatus === "conflict" && memo ? (
+ <View style={styles.conflictBanner}>
+ <Text style={styles.conflictBannerText}>
+ 云端笔记已在其他标签页、设备,或离线期间被更新。可先复制本地草稿,再采用云端版本后继续编辑。
+ </Text>
+ <View style={styles.conflictBannerActions}>
+ <Pressable
+ accessibilityLabel="采用云端并重新加载"
+ accessibilityRole="button"
+ onPress={() => onAdoptCloudVersion(memo)}
+ style={styles.conflictBannerPrimaryButton}
+ >
+ <Text style={styles.conflictBannerPrimaryButtonText}>采用云端并重新加载</Text>
+ </Pressable>
+ <Pressable
+ accessibilityLabel="复制本地草稿"
+ accessibilityRole="button"
+ onPress={() => onCopyLocalDraft(memo)}
+ style={styles.conflictBannerSecondaryButton}
+ >
+ <Text style={styles.conflictBannerSecondaryButtonText}>复制本地草稿</Text>
+ </Pressable>
+ <Pressable
+ accessibilityLabel="查看并处理同步冲突"
+ accessibilityRole="button"
+ onPress={() => onResolveSyncConflict(memo)}
+ style={styles.conflictBannerSecondaryButton}
+ >
+ <Text style={styles.conflictBannerSecondaryButtonText}>更多</Text>
+ </Pressable>
+ </View>
+ </View>
+ ) : null}
+
{isLoading ? (
<View style={styles.centerState}>
<ActivityIndicator color="#0f172a" />
diff --git a/apps/mobile/src/screens/WorkspaceScreen.tsx b/apps/mobile/src/screens/WorkspaceScreen.tsx
index 9ed3c195..b66c63ad 100644
--- a/apps/mobile/src/screens/WorkspaceScreen.tsx
+++ b/apps/mobile/src/screens/WorkspaceScreen.tsx
@@ -83,6 +83,8 @@ import { useMobileLocale } from "../lib/mobile-locale";
import { useSession } from "../lib/session";
import {
deleteMobileSyncQueueItem,
+ discardMobileMemoConflict,
+ getMobileConflictDraftClipboardText,
listMobileSyncQueueItems,
queueMobileMemoCreate,
queueMobileMemoUpdate,
@@ -928,49 +930,68 @@ export const WorkspaceScreen = ({
});
};
- const handleMemoSyncConflict = (memo: MemoDetail) => {
+ const handleCopyConflictDraft = useCallback(async (memo: MemoDetail) => {
+ try {
+ const text = await getMobileConflictDraftClipboardText(syncQueueScope, memo.id);
+ if (!text?.trim()) {
+ Alert.alert("复制失败", "没有可复制的本地草稿。");
+ return;
+ }
+ await Clipboard.setStringAsync(text);
+ Alert.alert("已复制", "本地草稿已复制到剪贴板。");
+ } catch (error) {
+ Alert.alert("复制失败", error instanceof Error ? error.message : "请重试");
+ }
+ }, [syncQueueScope]);
+
+ const handleAdoptCloudVersion = useCallback(async (memo: MemoDetail) => {
+ if (!client) {
+ return;
+ }
+
+ try {
+ const remoteMemo = await discardMobileMemoConflict(client, syncQueueScope, memo.id);
+ await Promise.all([
+ clearMobileMemoDraft(memo.id),
+ upsertLocalMemo(dataScope, remoteMemo),
+ ]);
+ queryClient.setQueryData(["mobile", "memo", "notebook", memo.id], { memo: remoteMemo });
+ queryClient.setQueryData(["mobile", "memo", "trash", memo.id], { memo: remoteMemo });
+ await Promise.all([
+ refreshSyncQueueItems(),
+ queryClient.invalidateQueries({ queryKey: ["mobile", "memos"] }),
+ queryClient.invalidateQueries({ queryKey: ["mobile", "search"] }),
+ queryClient.invalidateQueries({ queryKey: ["mobile", "memo", "notebook", memo.id] }),
+ queryClient.invalidateQueries({ queryKey: ["mobile", "memo", "trash", memo.id] }),
+ ]);
+ } catch (error) {
+ Alert.alert("采用云端版本失败", error instanceof Error ? error.message : "请检查网络后重试");
+ }
+ }, [client, dataScope, queryClient, refreshSyncQueueItems, syncQueueScope]);
+
+ const handleMemoSyncConflict = useCallback((memo: MemoDetail) => {
Alert.alert(
"同步冲突",
- "云端笔记已在其他设备更新,本地修改没有覆盖云端。你可以查看版本历史,或放弃本地修改并使用云端版本。",
+ "云端笔记已在其他标签页、设备,或离线期间被更新,本地草稿无法直接覆盖。可先复制本地草稿,再采用云端版本后继续编辑。",
[
{ text: "取消", style: "cancel" },
+ {
+ text: "复制本地草稿",
+ onPress: () => {
+ void handleCopyConflictDraft(memo);
+ },
+ },
{ text: "查看历史", onPress: () => setRevisionMemo(memo) },
{
- text: "使用云端版本",
+ text: "采用云端并重新加载",
style: "destructive",
onPress: () => {
- void (async () => {
- if (!client) {
- return;
- }
-
- try {
- const conflict = (await listMobileSyncQueueItems(syncQueueScope))
- .find((item) => item.memoId === memo.id && item.status === "conflict");
- const response = await client.getMemo(memo.id);
- if (conflict) {
- await deleteMobileSyncQueueItem(syncQueueScope, conflict.id);
- }
- await Promise.all([
- clearMobileMemoDraft(memo.id),
- upsertLocalMemo(dataScope, response.memo),
- ]);
- queryClient.setQueryData(["mobile", "memo", "notebook", memo.id], response);
- queryClient.setQueryData(["mobile", "memo", "trash", memo.id], response);
- await Promise.all([
- refreshSyncQueueItems(),
- queryClient.invalidateQueries({ queryKey: ["mobile", "memos"] }),
- queryClient.invalidateQueries({ queryKey: ["mobile", "search"] }),
- ]);
- } catch (error) {
- Alert.alert("加载失败", error instanceof Error ? error.message : "请稍后重试");
- }
- })();
+ void handleAdoptCloudVersion(memo);
},
},
]
);
- };
+ }, [handleAdoptCloudVersion, handleCopyConflictDraft]);
const handleDeleteSelection = () => {
const permanent = memoView === "trash";
@@ -1078,6 +1099,8 @@ export const WorkspaceScreen = ({
onRichEdit={(memo) => void openRichEditor(memo)}
onOpenRevisions={setRevisionMemo}
onRenameResource={handleRenameResource}
+ onAdoptCloudVersion={(memo) => void handleAdoptCloudVersion(memo)}
+ onCopyLocalDraft={(memo) => void handleCopyConflictDraft(memo)}
onResolveSyncConflict={handleMemoSyncConflict}
onRestore={(memo) => restoreMemoMutation.mutate(memo)}
onShare={(memo) => shareMemoMutation.mutate(memo)}
diff --git a/apps/mobile/src/screens/workspace-styles.ts b/apps/mobile/src/screens/workspace-styles.ts
index d7261914..9c2bf34f 100644
--- a/apps/mobile/src/screens/workspace-styles.ts
+++ b/apps/mobile/src/screens/workspace-styles.ts
@@ -1490,6 +1490,48 @@ const baseWorkspaceStyles = StyleSheet.create({
color: "#c2410c",
fontWeight: "700",
},
+ conflictBanner: {
+ backgroundColor: "#fff1f2",
+ borderBottomColor: "#fecdd3",
+ borderBottomWidth: StyleSheet.hairlineWidth,
+ gap: 10,
+ paddingHorizontal: 14,
+ paddingVertical: 12,
+ },
+ conflictBannerText: {
+ color: "#9f1239",
+ fontSize: 12,
+ lineHeight: 18,
+ },
+ conflictBannerActions: {
+ flexDirection: "row",
+ flexWrap: "wrap",
+ gap: 8,
+ },
+ conflictBannerPrimaryButton: {
+ backgroundColor: "#be123c",
+ borderRadius: 8,
+ paddingHorizontal: 10,
+ paddingVertical: 8,
+ },
+ conflictBannerPrimaryButtonText: {
+ color: "#fff",
+ fontSize: 12,
+ fontWeight: "700",
+ },
+ conflictBannerSecondaryButton: {
+ backgroundColor: "#fff",
+ borderColor: "#fecdd3",
+ borderRadius: 8,
+ borderWidth: 1,
+ paddingHorizontal: 10,
+ paddingVertical: 8,
+ },
+ conflictBannerSecondaryButtonText: {
+ color: "#9f1239",
+ fontSize: 12,
+ fontWeight: "600",
+ },
detailMetaRow: {
alignItems: "center",
flexDirection: "row",
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsx
index 20f45bec..ab54d1a1 100644
--- a/apps/web/src/components/EditorPane.tsx
+++ b/apps/web/src/components/EditorPane.tsx
@@ -111,11 +111,13 @@ import { compressImageForUpload } from "@/lib/image-compression";
import { localDb, type MemoUpdateSyncPayload } from "@/lib/local-db";
import { getMemoUpdateQueueId, isMemoUpdateAlreadyApplied, queueMemoUpdate, shouldQueueMemoSaveError } from "@/lib/sync-queue";
import {
+ formatLocalDraftClipboardText,
formatMemoSaveConflictReason,
getMemoSaveConflictInfo,
getMemoSaveConflictInfoFromQueueItem,
type MemoSaveConflictInfo,
} from "@/lib/memo-save-conflict";
+import { copyTextToClipboard } from "@/lib/clipboard";
import { isLocalMemoId } from "@/lib/local-mirror";
import { shouldAcceptRemoteMemoDetail } from "@/lib/memo-detail-freshness";
import type { EdgeEverRepository } from "@/lib/repository";
@@ -864,6 +866,8 @@ const RichEditorPane = ({
const [tagsText, setTagsText] = useState("");
const [saveState, setSaveState] = useState<"idle" | "saving" | "saved" | "queued" | "error" | "conflict">("idle");
const [saveConflictInfo, setSaveConflictInfo] = useState<MemoSaveConflictInfo | null>(null);
+ const [conflictActionPending, setConflictActionPending] = useState<"adopt" | "copy" | null>(null);
+ const [conflictActionMessage, setConflictActionMessage] = useState<string | null>(null);
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
const [hydratedEditorMemoId, setHydratedEditorMemoId] = useState<string | null>(null);
const [dirtyVersion, setDirtyVersion] = useState(0);
@@ -2754,6 +2758,135 @@ const RichEditorPane = ({
[saveConflictInfo, saveState, t],
);
+ useEffect(() => {
+ if (saveState !== "conflict") {
+ setConflictActionPending(null);
+ setConflictActionMessage(null);
+ }
+ }, [saveState]);
+
+ const getLocalDraftMarkdown = useCallback(() => {
+ if (useMobilePlainTextEditor) {
+ return getMobilePlainTextValue();
+ }
+ if (useMarkdownSourceEditor) {
+ return markdownSource;
+ }
+ const contentJson = getCurrentContentJson();
+ if (contentJson) {
+ return docToMarkdown(contentJson);
+ }
+ return memo?.contentMarkdown ?? "";
+ }, [
+ getCurrentContentJson,
+ getMobilePlainTextValue,
+ markdownSource,
+ memo?.contentMarkdown,
+ useMarkdownSourceEditor,
+ useMobilePlainTextEditor,
+ ]);
+
+ const handleCopyLocalDraft = useCallback(async () => {
+ if (conflictActionPending) {
+ return;
+ }
+
+ setConflictActionPending("copy");
+ setConflictActionMessage(null);
+ try {
+ const text = formatLocalDraftClipboardText({
+ title,
+ tags: parseTagsText(tagsText),
+ contentMarkdown: getLocalDraftMarkdown(),
+ });
+ const copied = await copyTextToClipboard(text);
+ if (!copied) {
+ setConflictActionMessage(t("editor.saveState.conflictCopyDraftFailed"));
+ return;
+ }
+ setConflictActionMessage(t("editor.saveState.conflictCopyDraftDone"));
+ window.setTimeout(() => {
+ setConflictActionMessage((current) =>
+ current === t("editor.saveState.conflictCopyDraftDone") ? null : current
+ );
+ }, 2000);
+ } catch {
+ setConflictActionMessage(t("editor.saveState.conflictCopyDraftFailed"));
+ } finally {
+ setConflictActionPending(null);
+ }
+ }, [conflictActionPending, getLocalDraftMarkdown, t, tagsText, title]);
+
+ const handleAdoptCloudAndReload = useCallback(async () => {
+ const currentMemo = memoRef.current;
+ if (!currentMemo || conflictActionPending === "adopt") {
+ return;
+ }
+
+ setConflictActionPending("adopt");
+ setConflictActionMessage(null);
+ try {
+ const { memo: remoteMemo } = await repository.adoptCloudMemo(currentMemo.id);
+ await onSaved(remoteMemo);
+
+ hasUnsavedChangesRef.current = false;
+ setHasUnsavedChanges(false);
+ setSaveConflictInfo(null);
+ setSaveState("idle");
+ setConflictActionMessage(null);
+
+ const nextTitle = getEditableMemoTitle(remoteMemo.title);
+ const nextTagsText = remoteMemo.tags.join(", ");
+ const nextContent = resolveMemoContentDoc(remoteMemo.contentJson, remoteMemo.contentMarkdown);
+ const nextMarkdown = remoteMemo.contentMarkdown || docToMarkdown(nextContent);
+
+ memoRef.current = remoteMemo;
+ editSessionRef.current = null;
+ hydratedMemoIdRef.current = remoteMemo.id;
+ setHydratedEditorMemoId(remoteMemo.id);
+ editingMemoIdRef.current = remoteMemo.id;
+ appliedEditorSourceKeyRef.current = `memo:${remoteMemo.id}:${remoteMemo.revision}:${remoteMemo.updatedAt}:${remoteMemo.contentHash}:${nextTitle}:${nextTagsText}:${nextMarkdown}`;
+
+ setTitle(nextTitle);
+ setTagsText(nextTagsText);
+ setMobilePlainText(nextMarkdown);
+ setMarkdownSource(nextMarkdown);
+ setMobilePlainTextElementValue(mobileTextAreaRef.current, nextMarkdown);
+
+ const currentEditor = editorRef.current;
+ if (isEditorReady(currentEditor)) {
+ hydratingRef.current = true;
+ try {
+ currentEditor.commands.setContent(nextContent);
+ } catch (err) {
+ console.error("Failed to apply cloud memo after conflict resolve:", err);
+ currentEditor.commands.setContent(markdownToDoc(nextMarkdown));
+ }
+ window.setTimeout(() => {
+ hydratingRef.current = false;
+ }, 0);
+ }
+
+ if (requiresLocalEditSession(remoteMemo)) {
+ editSessionRef.current = createLocalEditSession(remoteMemo);
+ } else {
+ void api.createMemoEditSession(remoteMemo.id).then((response) => {
+ if (editingMemoIdRef.current !== remoteMemo.id) return;
+ editSessionRef.current = response.editSession;
+ }).catch(() => {
+ if (editingMemoIdRef.current !== remoteMemo.id) return;
+ editSessionRef.current = createLocalEditSession(remoteMemo);
+ });
+ }
+
+ await queryClient.invalidateQueries({ queryKey: ["memo", remoteMemo.id] });
+ } catch {
+ setConflictActionMessage(t("editor.saveState.conflictAdoptFailed"));
+ } finally {
+ setConflictActionPending(null);
+ }
+ }, [conflictActionPending, onSaved, queryClient, repository, t]);
+
if (isSelectionMode) {
return (
<div className="flex h-full min-w-0 flex-col bg-white">
@@ -3565,11 +3698,40 @@ const RichEditorPane = ({
)}
{saveState === "conflict" && saveConflictReason ? (
<div
- className="flex items-start gap-2 border-t border-rose-100 bg-rose-50 px-3 py-2 text-xs leading-relaxed text-rose-800 sm:px-5"
+ className="flex flex-col gap-2 border-t border-rose-100 bg-rose-50 px-3 py-2 text-xs leading-relaxed text-rose-800 sm:px-5"
role="alert"
>
- <CircleAlert className="mt-0.5 h-3.5 w-3.5 shrink-0" aria-hidden="true" />
- <span>{saveConflictReason}</span>
+ <div className="flex items-start gap-2">
+ <CircleAlert className="mt-0.5 h-3.5 w-3.5 shrink-0" aria-hidden="true" />
+ <span className="min-w-0 flex-1">{saveConflictReason}</span>
+ </div>
+ <div className="flex flex-wrap items-center gap-2 pl-5">
+ <Button
+ size="sm"
+ variant="solid"
+ className="h-7 bg-rose-700 px-2.5 text-[11px] text-white hover:bg-rose-800"
+ disabled={conflictActionPending !== null}
+ onClick={() => void handleAdoptCloudAndReload()}
+ >
+ {conflictActionPending === "adopt"
+ ? t("editor.saveState.conflictAdopting")
+ : t("editor.saveState.conflictAdoptCloud")}
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ className="h-7 px-2.5 text-[11px] text-rose-800 hover:bg-rose-100"
+ disabled={conflictActionPending !== null}
+ onClick={() => void handleCopyLocalDraft()}
+ >
+ {t("editor.saveState.conflictCopyDraft")}
+ </Button>
+ {conflictActionMessage ? (
+ <span className="text-[11px] font-medium text-rose-700" role="status" aria-live="polite">
+ {conflictActionMessage}
+ </span>
+ ) : null}
+ </div>
</div>
) : null}
</header>
diff --git a/apps/web/src/lib/desktop-repository.ts b/apps/web/src/lib/desktop-repository.ts
index 246e277f..0fbae905 100644
--- a/apps/web/src/lib/desktop-repository.ts
+++ b/apps/web/src/lib/desktop-repository.ts
@@ -243,6 +243,12 @@ export const createDesktopRepository = (): EdgeEverRepository => ({
return { memo: toDisplayMemo(result.memo), queued: true as const };
},
+ adoptCloudMemo: async (memoId) => {
+ const { discardDesktopMemoConflict } = await import("@/lib/desktop-sync");
+ const memo = await discardDesktopMemoConflict(memoId);
+ return { memo: toDisplayMemo(memo) };
+ },
+
deleteMemo: (memoId, permanent = false) => request("memo.delete", { memoId, permanent }).then((result) => {
window.dispatchEvent(new CustomEvent("edgeever:sync-queue-changed"));
return result;
diff --git a/apps/web/src/lib/desktop-sync.ts b/apps/web/src/lib/desktop-sync.ts
index 9243c247..f88fe414 100644
--- a/apps/web/src/lib/desktop-sync.ts
+++ b/apps/web/src/lib/desktop-sync.ts
@@ -505,3 +505,31 @@ export const discardDesktopConflicts = async () => {
return discarded;
};
+
+/**
+ * Discard a single note's conflicted desktop outbox item and replace the local
+ * store with the authoritative cloud memo.
+ */
+export const discardDesktopMemoConflict = async (memoId: string) => {
+ const remote = await api.getMemo(memoId, { includeDeleted: true });
+ await request("sync.apply", {
+ changes: [{ entityType: "memo", operation: "upsert", entityId: remote.memo.id, memo: remote.memo, notebook: null }],
+ });
+
+ const response = await request("sync.outbox.list", { limit: 200 });
+ for (const item of response.items) {
+ if (item.entityId !== memoId || item.status !== "conflict") {
+ continue;
+ }
+ if (item.kind === "memo.update") {
+ await request("sync.outbox.ack", { id: item.id, remoteMemo: remote.memo });
+ } else {
+ await request("sync.outbox.discard", { id: item.id });
+ }
+ }
+
+ if (typeof window !== "undefined") {
+ window.dispatchEvent(new CustomEvent("edgeever:sync-queue-changed"));
+ }
+ return remote.memo;
+};
diff --git a/apps/web/src/lib/memo-save-conflict.ts b/apps/web/src/lib/memo-save-conflict.ts
index 99761bc6..2ad92ad0 100644
--- a/apps/web/src/lib/memo-save-conflict.ts
+++ b/apps/web/src/lib/memo-save-conflict.ts
@@ -116,3 +116,5 @@ export const formatMemoSaveConflictReason = (t: Translate, info: MemoSaveConflic
return t("editor.saveState.conflictReason.revision");
};
+
+export { formatLocalDraftClipboardText } from "@edgeever/shared";
diff --git a/apps/web/src/lib/repository.ts b/apps/web/src/lib/repository.ts
index 63caec85..b9680a65 100644
--- a/apps/web/src/lib/repository.ts
+++ b/apps/web/src/lib/repository.ts
@@ -39,7 +39,7 @@ import {
type LocalMemoListParams,
type LocalMemoListResponse,
} from "@/lib/local-mirror";
-import { getMemoUpdateQueueId, queueLocalAction, queueMemoCreate, queueMemoDelete, queueMemoRestore, queueMemoUpdate } from "@/lib/sync-queue";
+import { discardWebMemoConflict, getMemoUpdateQueueId, queueLocalAction, queueMemoCreate, queueMemoDelete, queueMemoRestore, queueMemoUpdate } from "@/lib/sync-queue";
import { localDb, type MemoUpdateSyncPayload } from "@/lib/local-db";
import { createDesktopRepository } from "@/lib/desktop-repository";
import { isBrowserOffline } from "@/lib/network-status";
@@ -73,6 +73,11 @@ export type EdgeEverRepository = {
getMemo(memoId: string, includeDeleted?: boolean): Promise<{ memo: MemoDetail }>;
createMemo(input: { notebookId: string; title?: string; contentMarkdown?: string; tags?: string[] }): Promise<{ memo: MemoDetail }>;
updateMemo(memo: MemoDetail, input: Omit<MemoUpdateSyncPayload, "memoId">): Promise<{ memo: MemoDetail; queued: true }>;
+ /**
+ * Drop the local conflicted draft for a note and replace the local copy with
+ * the authoritative cloud memo so the editor can rehydrate cleanly.
+ */
+ adoptCloudMemo(memoId: string): Promise<{ memo: MemoDetail }>;
deleteMemo(memoId: string, permanent?: boolean): Promise<{ ok: true }>;
restoreMemo(memoId: string): Promise<{ memo: MemoDetail; queued: true }>;
listMemoRevisions(memoId: string): Promise<{ revisions: MemoRevision[] }>;
@@ -434,6 +439,11 @@ export const createWebRepository = (scope: string): EdgeEverRepository => {
return { memo: updated, queued: true };
},
+ async adoptCloudMemo(memoId) {
+ const memo = await discardWebMemoConflict(scope, memoId);
+ return { memo };
+ },
+
async deleteMemo(memoId, permanent = false) {
const { deleteLocalMemo } = await import("@/lib/local-mirror");
await deleteLocalMemo(scope, memoId, permanent);
diff --git a/apps/web/src/lib/sync-queue.ts b/apps/web/src/lib/sync-queue.ts
index 4390b94b..9d14db1f 100644
--- a/apps/web/src/lib/sync-queue.ts
+++ b/apps/web/src/lib/sync-queue.ts
@@ -207,6 +207,37 @@ export const discardWebConflicts = async (scope: string) => {
return discarded;
};
+/**
+ * Discard a single note's local conflict/draft and replace the local mirror
+ * with the authoritative cloud memo so the editor can rehydrate cleanly.
+ */
+export const discardWebMemoConflict = async (scope: string, memoId: string) => {
+ const remote = await api.getMemo(memoId, { includeDeleted: true });
+ const { putLocalMemo } = await import("@/lib/local-mirror");
+ await putLocalMemo(scope, remote.memo);
+ await localDb.drafts.delete(memoId);
+
+ const queueId = getMemoUpdateQueueId(memoId);
+ const queued = await localDb.syncQueue.get(queueId);
+ if (queued) {
+ await localDb.syncQueue.delete(queueId);
+ }
+
+ // Older clients could leave unscoped conflict rows; clear any leftover
+ // conflict update for this memo under the current scope as well.
+ for (const item of await localDb.syncQueue.where("status").equals("conflict").toArray()) {
+ if (item.memoId !== memoId) continue;
+ if (item.scope && item.scope !== scope) continue;
+ if (item.id === queueId) continue;
+ await localDb.syncQueue.delete(item.id);
+ }
+
+ if (typeof window !== "undefined") {
+ window.dispatchEvent(new CustomEvent("edgeever:sync-queue-changed"));
+ }
+ return remote.memo;
+};
+
export const isMemoUpdateAlreadyApplied = (memo: MemoDetail, item: SyncQueueItem) => {
if (item.kind !== "memo.update") {
return false;
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index 9dc391e4..987fd43d 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -653,13 +653,19 @@ export const enUS = {
error: "Save failed",
unsaved: "Unsaved",
conflictReason: {
- revisionWithVersions: "The cloud note was updated (local base revision {{expected}}, cloud is {{current}}). Common causes: another tab/device, or someone else editing the same note on Demo. Reload before editing again.",
- revision: "The cloud note was updated elsewhere. Common causes: another tab/device, or concurrent editing. Reload before editing again.",
- content: "The cloud content changed after this note was opened. Reload before saving.",
- editSession: "This edit session is stale or expired. Reopen the note before saving.",
- offlineStale: "While offline or queued, the cloud note was updated, so the local draft cannot overwrite it. Copy local content, then reload—or use the cloud version.",
- generic: "A version conflict was detected while saving. Reload the note, or use the cloud version before editing again.",
+ revisionWithVersions: "The cloud note was updated (local base revision {{expected}}, cloud is {{current}}). Common causes: another browser tab, another device, or a cloud change while you were offline. Copy your local draft, then use the cloud version before editing again.",
+ revision: "The cloud note was updated elsewhere. Common causes: another browser tab, another device, or a cloud change while you were offline. Copy your local draft, then use the cloud version before editing again.",
+ content: "The cloud content changed after this note was opened. Copy your local draft, then use the cloud version before saving.",
+ editSession: "This edit session is stale or expired. Copy your local draft, then use the cloud version before editing again.",
+ offlineStale: "While offline or queued, the cloud note was updated, so the local draft cannot overwrite it. Copy your local draft, then use the cloud version.",
+ generic: "A version conflict was detected while saving. Copy your local draft, then use the cloud version before editing again.",
},
+ conflictAdoptCloud: "Use cloud and reload",
+ conflictAdopting: "Using cloud…",
+ conflictAdoptFailed: "Could not use the cloud version. Check your connection and try again.",
+ conflictCopyDraft: "Copy local draft",
+ conflictCopyDraftDone: "Copied",
+ conflictCopyDraftFailed: "Copy failed. Please try again.",
},
uploadState: {
failed: "Upload failed",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index 2e568ad3..ccbb8f98 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -653,13 +653,19 @@ export const zhCN = {
error: "保存失败",
unsaved: "未保存",
conflictReason: {
- revisionWithVersions: "云端笔记已更新(本地基于版本 {{expected}},云端已是 {{current}})。常见原因:其他标签页/设备,或 Demo 上其他人修改了同一条笔记。请重新加载后再编辑。",
- revision: "云端笔记已在其他位置被更新。常见原因:其他标签页/设备,或多人同时编辑。请重新加载后再编辑。",
- content: "打开笔记后,云端内容已变化。请重新加载后再保存。",
- editSession: "当前编辑会话已失效或过期。请重新打开笔记后再保存。",
- offlineStale: "离线或待同步期间,云端笔记已被更新,本地草稿无法直接覆盖。可复制本地内容后重新加载,或采用云端版本。",
- generic: "保存时版本不一致。请重新加载笔记,或采用云端版本后再编辑。",
+ revisionWithVersions: "云端笔记已更新(本地基于版本 {{expected}},云端已是 {{current}})。常见原因:其他标签页、其他设备,或离线期间云端被改过。可先复制本地草稿,再采用云端版本后继续编辑。",
+ revision: "云端笔记已在其他位置被更新。常见原因:其他标签页、其他设备,或离线期间云端被改过。可先复制本地草稿,再采用云端版本后继续编辑。",
+ content: "打开笔记后,云端内容已变化。可先复制本地草稿,再采用云端版本后保存。",
+ editSession: "当前编辑会话已失效或过期。可先复制本地草稿,再采用云端版本后继续编辑。",
+ offlineStale: "离线或待同步期间,云端笔记已被更新,本地草稿无法直接覆盖。可先复制本地草稿,再采用云端版本。",
+ generic: "保存时版本不一致。可先复制本地草稿,再采用云端版本后继续编辑。",
},
+ conflictAdoptCloud: "采用云端并重新加载",
+ conflictAdopting: "正在采用云端…",
+ conflictAdoptFailed: "采用云端版本失败,请检查网络后重试。",
+ conflictCopyDraft: "复制本地草稿",
+ conflictCopyDraftDone: "已复制",
+ conflictCopyDraftFailed: "复制失败,请重试。",
},
uploadState: {
failed: "上传失败",
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 411b304b..f0af63cb 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -4,6 +4,7 @@ export * from "./github-feedback";
export * from "./image-display";
export * from "./image-referrer";
export * from "./memo-safety";
+export * from "./memo-conflict";
export * from "./memo-content-style";
export * from "./note-links";
export * from "./notebooks";
diff --git a/packages/shared/src/memo-conflict.ts b/packages/shared/src/memo-conflict.ts
new file mode 100644
index 00000000..aaa8ae98
--- /dev/null
+++ b/packages/shared/src/memo-conflict.ts
@@ -0,0 +1,23 @@
+/** Format a conflicted local draft for clipboard recovery (title, tags, body). */
+export const formatLocalDraftClipboardText = (input: {
+ title: string;
+ tags: string[];
+ contentMarkdown: string;
+}) => {
+ const parts: string[] = [];
+ const title = input.title.trim();
+ if (title) {
+ parts.push(`# ${title}`);
+ }
+ if (input.tags.length > 0) {
+ parts.push(input.tags.map((tag) => `#${tag}`).join(" "));
+ }
+ const body = input.contentMarkdown.replace(/\s+$/u, "");
+ if (body) {
+ if (parts.length > 0) {
+ parts.push("");
+ }
+ parts.push(body);
+ }
+ return parts.join("\n");
+};
diff --git a/tests/web-sync-queue.test.ts b/tests/web-sync-queue.test.ts
index 145e434d..fb97beae 100644
--- a/tests/web-sync-queue.test.ts
+++ b/tests/web-sync-queue.test.ts
@@ -4,7 +4,14 @@ import type { MemoDetail, MemoEditSession } from "@edgeever/shared";
import type { MemoUpdateSyncPayload } from "../apps/web/src/lib/local-db";
const { localDb } = await import("../apps/web/src/lib/local-db");
-const { getMemoUpdateQueueId, isMemoUpdateAlreadyApplied, queueMemoUpdate, syncQueuedChanges } = await import("../apps/web/src/lib/sync-queue");
+const {
+ discardWebMemoConflict,
+ getMemoUpdateQueueId,
+ isMemoUpdateAlreadyApplied,
+ queueMemoUpdate,
+ syncQueuedChanges,
+} = await import("../apps/web/src/lib/sync-queue");
+const { formatLocalDraftClipboardText } = await import("../apps/web/src/lib/memo-save-conflict");
const originalFetch = globalThis.fetch;
const payload = (title: string, revision = 0): MemoUpdateSyncPayload => ({
@@ -58,9 +65,10 @@ beforeEach(async () => {
configurable: true,
value: { onLine: true },
});
- await localDb.transaction("rw", localDb.drafts, localDb.syncQueue, async () => {
+ await localDb.transaction("rw", localDb.drafts, localDb.syncQueue, localDb.memos, async () => {
await localDb.drafts.clear();
await localDb.syncQueue.clear();
+ await localDb.memos.clear();
});
});
@@ -142,4 +150,43 @@ describe("web sync queue concurrency", () => {
expect(queued?.status).toBe("conflict");
expect(queued?.payload.title).toBe("offline edit");
});
+
+ test("discardWebMemoConflict replaces local draft with the cloud memo", async () => {
+ const scope = "test-scope";
+ await queueMemoUpdate(payload("local conflicted edit"), scope);
+ await localDb.syncQueue.update(getMemoUpdateQueueId("memo_sync_test"), { status: "conflict" });
+ await localDb.drafts.put({
+ memoId: "memo_sync_test",
+ title: "local conflicted edit",
+ tagsText: "",
+ contentJson: payload("local conflicted edit").contentJson,
+ updatedAt: "2026-07-15T00:00:02.000Z",
+ });
+
+ const cloud = memo("cloud wins", 3);
+ globalThis.fetch = (async () => jsonResponse({ memo: cloud })) as typeof fetch;
+
+ const adopted = await discardWebMemoConflict(scope, "memo_sync_test");
+
+ expect(adopted).toEqual(cloud);
+ expect(await localDb.syncQueue.get(getMemoUpdateQueueId("memo_sync_test"))).toBeUndefined();
+ expect(await localDb.drafts.get("memo_sync_test")).toBeUndefined();
+ expect(await localDb.memos.get([scope, "memo_sync_test"])).toMatchObject({
+ title: "cloud wins",
+ revision: 3,
+ scope,
+ });
+ });
+});
+
+describe("local draft clipboard formatting", () => {
+ test("includes title, tags, and body", () => {
+ expect(
+ formatLocalDraftClipboardText({
+ title: "Welcome",
+ tags: ["overview", "demo"],
+ contentMarkdown: "Hello world\n",
+ }),
+ ).toBe("# Welcome\n#overview #demo\n\nHello world");
+ });
});