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
Add mobile offline sync queue
yomacba7dd5f886b
diff --git a/apps/mobile/package.json b/apps/mobile/package.jsonindex 5cd837ac..2c463048 100644--- a/apps/mobile/package.json+++ b/apps/mobile/package.json@@ -15,6 +15,7 @@"@edgeever/client": "workspace:*","@edgeever/shared": "workspace:*","@gorhom/bottom-sheet": "latest",+ "@react-native-async-storage/async-storage": "2.2.0","@tanstack/react-query": "latest","expo": "latest","expo-clipboard": "~57.0.0",diff --git a/apps/mobile/src/lib/sync-queue.ts b/apps/mobile/src/lib/sync-queue.tsnew file mode 100644index 00000000..6faa51c7--- /dev/null+++ b/apps/mobile/src/lib/sync-queue.ts@@ -0,0 +1,201 @@+import AsyncStorage from "@react-native-async-storage/async-storage";+import { ApiRequestError, type createEdgeEverClient } from "@edgeever/client";+import type { MemoDetail } from "@edgeever/shared";++const SYNC_QUEUE_KEY = "edgeever.mobile.syncQueue.v1";++export type MobileMemoUpdateSyncPayload = {+ memoId: string;+ expectedRevision: number;+ title: string;+ contentMarkdown: string;+ notebookId: string;+ tags: string[];+};++export type MobileSyncQueueItem = {+ id: string;+ kind: "memo.update";+ memoId: string;+ status: "pending" | "syncing" | "conflict" | "error";+ payload: MobileMemoUpdateSyncPayload;+ attemptCount: number;+ lastError: string | null;+ nextAttemptAt: string | null;+ createdAt: string;+ updatedAt: string;+};++export type MobileSyncQueueSummary = {+ total: number;+ pending: number;+ syncing: number;+ conflict: number;+ error: number;+};++export type MobileSyncRunResult = {+ attempted: number;+ synced: number;+ failed: number;+ conflicted: number;+};++export const emptyMobileSyncQueueSummary = (): MobileSyncQueueSummary => ({+ total: 0,+ pending: 0,+ syncing: 0,+ conflict: 0,+ error: 0,+});++export const getMobileMemoUpdateQueueId = (memoId: string) => `memo.update:${memoId}`;++export const queueMobileMemoUpdate = async (payload: MobileMemoUpdateSyncPayload) => {+ const now = new Date().toISOString();+ const items = await readMobileSyncQueue();+ const id = getMobileMemoUpdateQueueId(payload.memoId);+ const existing = items.find((item) => item.id === id);+ const nextItem: MobileSyncQueueItem = {+ id,+ kind: "memo.update",+ memoId: payload.memoId,+ status: "pending",+ payload,+ attemptCount: existing?.attemptCount ?? 0,+ lastError: null,+ nextAttemptAt: null,+ createdAt: existing?.createdAt ?? now,+ updatedAt: now,+ };++ await writeMobileSyncQueue([nextItem, ...items.filter((item) => item.id !== id)]);+ return summarizeMobileSyncQueue(await readMobileSyncQueue());+};++export const loadMobileSyncQueueSummary = async () => summarizeMobileSyncQueue(await readMobileSyncQueue());++export const syncMobileQueuedChanges = async (+ client: ReturnType<typeof createEdgeEverClient>,+ options: {+ onSynced?: (memo: MemoDetail) => void | Promise<void>;+ } = {}+): Promise<MobileSyncRunResult> => {+ const result: MobileSyncRunResult = {+ attempted: 0,+ synced: 0,+ failed: 0,+ conflicted: 0,+ };+ const now = new Date();+ const items = (await readMobileSyncQueue())+ .filter((item) => item.status === "pending" || item.status === "error" || item.status === "syncing")+ .filter((item) => !item.nextAttemptAt || new Date(item.nextAttemptAt) <= now)+ .sort((left, right) => left.createdAt.localeCompare(right.createdAt));++ for (const item of items) {+ result.attempted += 1;+ await updateMobileSyncQueueItem(item.id, {+ status: "syncing",+ updatedAt: new Date().toISOString(),+ });++ try {+ const memo = await syncMobileQueueItem(client, item);+ await removeMobileSyncQueueItem(item.id);+ await options.onSynced?.(memo);+ result.synced += 1;+ } catch (error) {+ const status = isRevisionConflict(error) ? "conflict" : "error";+ const attemptCount = item.attemptCount + 1;++ await updateMobileSyncQueueItem(item.id, {+ status,+ attemptCount,+ lastError: getErrorMessage(error),+ nextAttemptAt: status === "error" ? nextRetryAt(attemptCount) : null,+ updatedAt: new Date().toISOString(),+ });++ if (status === "conflict") {+ result.conflicted += 1;+ } else {+ result.failed += 1;+ }+ }+ }++ return result;+};++export const shouldQueueMobileMemoSaveError = (error: unknown) => {+ if (error instanceof ApiRequestError) {+ return error.status === 408 || error.status === 429 || error.status >= 500;+ }++ return error instanceof TypeError || getErrorMessage(error).toLowerCase().includes("network");+};++const syncMobileQueueItem = async (client: ReturnType<typeof createEdgeEverClient>, item: MobileSyncQueueItem) => {+ const response = await client.updateMemo(item.memoId, {+ expectedRevision: item.payload.expectedRevision,+ title: item.payload.title,+ contentMarkdown: item.payload.contentMarkdown,+ notebookId: item.payload.notebookId,+ tags: item.payload.tags,+ });++ return response.memo;+};++const readMobileSyncQueue = async (): Promise<MobileSyncQueueItem[]> => {+ const rawValue = await AsyncStorage.getItem(SYNC_QUEUE_KEY);++ if (!rawValue) {+ return [];+ }++ try {+ const parsed = JSON.parse(rawValue);+ return Array.isArray(parsed) ? parsed.filter(isMobileSyncQueueItem) : [];+ } catch {+ return [];+ }+};++const writeMobileSyncQueue = (items: MobileSyncQueueItem[]) => AsyncStorage.setItem(SYNC_QUEUE_KEY, JSON.stringify(items));++const updateMobileSyncQueueItem = async (id: string, patch: Partial<MobileSyncQueueItem>) => {+ const items = await readMobileSyncQueue();+ await writeMobileSyncQueue(items.map((item) => (item.id === id ? { ...item, ...patch } : item)));+};++const removeMobileSyncQueueItem = async (id: string) => {+ const items = await readMobileSyncQueue();+ await writeMobileSyncQueue(items.filter((item) => item.id !== id));+};++const summarizeMobileSyncQueue = (items: MobileSyncQueueItem[]) =>+ items.reduce((summary, item) => {+ summary.total += 1;+ summary[item.status] += 1;+ return summary;+ }, emptyMobileSyncQueueSummary());++const isMobileSyncQueueItem = (value: unknown): value is MobileSyncQueueItem => {+ if (!value || typeof value !== "object") {+ return false;+ }++ const item = value as Partial<MobileSyncQueueItem>;+ return item.kind === "memo.update" && typeof item.id === "string" && typeof item.memoId === "string" && Boolean(item.payload);+};++const isRevisionConflict = (error: unknown) => error instanceof ApiRequestError && error.code === "revision_conflict";++const getErrorMessage = (error: unknown) => (error instanceof Error ? error.message : "Sync failed");++const nextRetryAt = (attemptCount: number) => {+ const delayMs = Math.min(5 * 60_000, 2 ** Math.min(attemptCount, 6) * 1000);+ return new Date(Date.now() + delayMs).toISOString();+};diff --git a/apps/mobile/src/screens/WorkspaceScreen.tsx b/apps/mobile/src/screens/WorkspaceScreen.tsxindex 006717b1..5198c995 100644--- a/apps/mobile/src/screens/WorkspaceScreen.tsx+++ b/apps/mobile/src/screens/WorkspaceScreen.tsx@@ -59,6 +59,14 @@ import {import { SafeAreaView } from "react-native-safe-area-context";import type { ApiToken, MemoDetail, MemoRevision, MemoSummary, Notebook, ResourceListItem, TagSummary } from "@edgeever/shared";import { useSession } from "../lib/session";+import {+ emptyMobileSyncQueueSummary,+ loadMobileSyncQueueSummary,+ queueMobileMemoUpdate,+ shouldQueueMobileMemoSaveError,+ syncMobileQueuedChanges,+ type MobileSyncQueueSummary,+} from "../lib/sync-queue";const ALL_NOTES_ID = "all";const DEFAULT_MEMO_TITLE = "无标题笔记";@@ -153,6 +161,9 @@ export const WorkspaceScreen = () => {const [revisionMemo, setRevisionMemo] = useState<MemoDetail | null>(null);const [selectedMemoIds, setSelectedMemoIds] = useState<Set<string>>(() => new Set());const [selectionMoveOpen, setSelectionMoveOpen] = useState(false);+ const [syncQueueSummary, setSyncQueueSummary] = useState<MobileSyncQueueSummary>(() => emptyMobileSyncQueueSummary());+ const [syncQueueMessage, setSyncQueueMessage] = useState("");+ const [isSyncingQueue, setIsSyncingQueue] = useState(false);const notebooksQuery = useQuery({queryKey: ["mobile", "notebooks"],@@ -222,6 +233,7 @@ export const WorkspaceScreen = () => {queryClient.invalidateQueries({ queryKey: ["mobile", "search"] }),queryClient.invalidateQueries({ queryKey: ["mobile", "memo"] }),]);+ setSyncQueueSummary(await loadMobileSyncQueueSummary());};const handleMemoPress = (memoId: string) => {@@ -269,6 +281,20 @@ export const WorkspaceScreen = () => {clearSelection();}, [activeNotebookId, memoFilterMode, memoSortMode, memoView]);+ useEffect(() => {+ let mounted = true;++ loadMobileSyncQueueSummary().then((summary) => {+ if (mounted) {+ setSyncQueueSummary(summary);+ }+ });++ return () => {+ mounted = false;+ };+ }, []);+const invalidateWorkspace = async () => {await Promise.all([queryClient.invalidateQueries({ queryKey: ["mobile", "notebooks"] }),@@ -456,6 +482,32 @@ export const WorkspaceScreen = () => {]);};+ const handleSyncQueuedChanges = async () => {+ if (!client || isSyncingQueue) {+ return;+ }++ setIsSyncingQueue(true);+ setSyncQueueMessage("");++ try {+ const result = await syncMobileQueuedChanges(client, {+ onSynced: async (memo) => {+ queryClient.setQueryData(["mobile", "memo", "notebook", memo.id], { memo });+ queryClient.setQueryData(["mobile", "memo", "trash", memo.id], { memo });+ },+ });+ await invalidateWorkspace();+ setSyncQueueSummary(await loadMobileSyncQueueSummary());+ setSyncQueueMessage(result.attempted === 0 ? "没有可同步的变更" : `已同步 ${result.synced} 条,失败 ${result.failed + result.conflicted} 条`);+ } catch (error) {+ setSyncQueueSummary(await loadMobileSyncQueueSummary());+ setSyncQueueMessage(error instanceof Error ? error.message : "同步失败");+ } finally {+ setIsSyncingQueue(false);+ }+ };+return (<SafeAreaView style={styles.safeArea}><AppHeader instance={session?.baseUrl ?? ""} onRefresh={refresh} onSignOut={signOut} />@@ -515,6 +567,10 @@ export const WorkspaceScreen = () => {onOpenSystemInfo={() => setSystemInfoOpen(true)}onOpenTagsManager={() => setTagsManagerOpen(true)}onOpenTemplates={() => setTemplatesOpen(true)}+ onSyncQueuedChanges={handleSyncQueuedChanges}+ syncQueueMessage={syncQueueMessage}+ syncQueueSummary={syncQueueSummary}+ isSyncingQueue={isSyncingQueue}/>) : null}@@ -538,6 +594,11 @@ export const WorkspaceScreen = () => {memo={editingMemo}notebooks={notebooks}onClose={() => setEditingMemo(null)}+ onQueued={async () => {+ setEditingMemo(null);+ setSyncQueueSummary(await loadMobileSyncQueueSummary());+ setSyncQueueMessage("变更已保存到本地队列");+ }}onSaved={(memo) => {setEditingMemo(null);setSelectedMemoId(memo.id);@@ -870,6 +931,7 @@ const AccountView = ({ instance, userName, onSignOut }: { instance: string; user);const SettingsView = ({+ isSyncingQueue,memoCount,notebookCount,onOpenApiTokens,@@ -879,7 +941,11 @@ const SettingsView = ({onOpenSystemInfo,onOpenTagsManager,onOpenTemplates,+ onSyncQueuedChanges,+ syncQueueMessage,+ syncQueueSummary,}: {+ isSyncingQueue: boolean;memoCount: number;notebookCount: number;onOpenApiTokens: () => void;@@ -889,6 +955,9 @@ const SettingsView = ({onOpenSystemInfo: () => void;onOpenTagsManager: () => void;onOpenTemplates: () => void;+ onSyncQueuedChanges: () => void;+ syncQueueMessage: string;+ syncQueueSummary: MobileSyncQueueSummary;}) => (<ScrollView contentContainerStyle={styles.panelList} style={styles.viewBody}><Text style={styles.sectionTitle}>设置</Text>@@ -916,7 +985,7 @@ const SettingsView = ({<PanelRow label="移动端形态" value="React Native" /><PanelRow label="笔记本数量" value={String(notebookCount)} /><PanelRow label="笔记总数" value={String(memoCount)} />- <PanelRow label="离线同步" value="待接入" />+ <SyncQueuePanel isSyncing={isSyncingQueue} message={syncQueueMessage} onSync={onSyncQueuedChanges} summary={syncQueueSummary} /><PanelRow label="富文本编辑器" value="待接入 WebView TipTap" /></ScrollView>);@@ -2396,12 +2465,14 @@ const EditMemoModal = ({memo,notebooks,onClose,+ onQueued,onSaved,updateMutation,}: {memo: MemoDetail | null;notebooks: Notebook[];onClose: () => void;+ onQueued: () => void | Promise<void>;onSaved: (memo: MemoDetail) => void;updateMutation: UseMutationResult<MemoDetail,@@ -2451,6 +2522,22 @@ const EditMemoModal = ({},{onSuccess: onSaved,+ onError: async (error) => {+ if (!shouldQueueMobileMemoSaveError(error)) {+ return;+ }++ await queueMobileMemoUpdate({+ memoId: memo.id,+ expectedRevision: memo.revision,+ title: title.trim() || DEFAULT_MEMO_TITLE,+ contentMarkdown,+ notebookId,+ tags: parseTags(tagsText),+ });+ await onQueued();+ Alert.alert("已保存到本地队列", "网络恢复后可在设置页手动同步。");+ },});};@@ -2802,6 +2889,33 @@ const PanelRow = ({ label, value }: { label: string; value: string }) => (</View>);+const SyncQueuePanel = ({+ isSyncing,+ message,+ onSync,+ summary,+}: {+ isSyncing: boolean;+ message: string;+ onSync: () => void;+ summary: MobileSyncQueueSummary;+}) => {+ const hasQueuedChanges = summary.total > 0;+ const value = hasQueuedChanges ? `${summary.pending} 待同步 · ${summary.syncing} 同步中 · ${summary.error} 失败 · ${summary.conflict} 冲突` : "无待同步变更";++ return (+ <View style={styles.panelRow}>+ <Text style={styles.panelLabel}>离线同步</Text>+ <Text style={styles.panelValue}>{value}</Text>+ {message ? <Text style={styles.panelHint}>{message}</Text> : null}+ <Pressable disabled={isSyncing || !hasQueuedChanges} onPress={onSync} style={[styles.syncButton, (isSyncing || !hasQueuedChanges) && styles.buttonDisabled]}>+ {isSyncing ? <ActivityIndicator color="#ffffff" /> : <RefreshCw color="#ffffff" size={16} />}+ <Text style={styles.syncButtonText}>{isSyncing ? "同步中" : "立即同步"}</Text>+ </Pressable>+ </View>+ );+};+const IconButton = ({ children, onPress }: { children: ReactNode; onPress: () => void }) => (<Pressable accessibilityRole="button" onPress={onPress} style={styles.iconButton}>{children}@@ -3514,6 +3628,27 @@ const styles = StyleSheet.create({fontSize: 15,fontWeight: "700",},+ panelHint: {+ color: "#64748b",+ fontSize: 12,+ fontWeight: "700",+ lineHeight: 18,+ },+ syncButton: {+ alignItems: "center",+ alignSelf: "flex-start",+ backgroundColor: "#0f172a",+ borderRadius: 8,+ flexDirection: "row",+ gap: 8,+ minHeight: 38,+ paddingHorizontal: 12,+ },+ syncButtonText: {+ color: "#ffffff",+ fontSize: 13,+ fontWeight: "800",+ },dangerButton: {alignItems: "center",backgroundColor: "#fef2f2",diff --git a/bun.lock b/bun.lockindex 1053b240..3d9b840a 100644--- a/bun.lock+++ b/bun.lock@@ -74,6 +74,7 @@"@edgeever/client": "workspace:*","@edgeever/shared": "workspace:*","@gorhom/bottom-sheet": "latest",+ "@react-native-async-storage/async-storage": "2.2.0","@tanstack/react-query": "latest","expo": "latest","expo-clipboard": "~57.0.0",@@ -799,6 +800,8 @@"@radix-ui/rect": ["@radix-ui/[email protected]", "", {}, "sha512-xnXE7wG13PI+cxieVssYXlQJuYVRhH9NBoxt3KNwzghDIA69GMm7d4wXRouHIYjE+KvS6U/MsMO73NdS2MH9ZA=="],+ "@react-native-async-storage/async-storage": ["@react-native-async-storage/[email protected]", "", { "dependencies": { "merge-options": "^3.0.4" }, "peerDependencies": { "react-native": "^0.0.0-0 || >=0.65 <1.0" } }, "sha512-gvRvjR5JAaUZF8tv2Kcq/Gbt3JHwbKFYfmb445rhOj6NUMx3qPLixmDx5pZAyb9at1bYvJ4/eTUipU5aki45xw=="],+"@react-native-masked-view/masked-view": ["@react-native-masked-view/[email protected]", "", { "peerDependencies": { "react": ">=16", "react-native": ">=0.57" } }, "sha512-XwuQoW7/GEgWRMovOQtX3A4PrXhyaZm0lVUiY8qJDvdngjLms9Cpdck6SmGAUNqQwcj2EadHC1HwL0bEyoa/SQ=="],"@react-native/assets-registry": ["@react-native/[email protected]", "", {}, "sha512-nIaXbm2jX1OTYp0qbviJ3O6KZivoE8z3BnhUQ2LsqfZSWRoOK/n1qsiAr6oALiNKWnXY3j2KPwtYORnZzp8xew=="],@@ -1839,7 +1842,7 @@"is-obj": ["[email protected]", "", {}, "sha512-l4RyHgRqGN4Y3+9JHVrNqO+tN0rV5My76uW5/nuO4K1b6vw5G8d/cmFjP9tRfEsdhZNt0IFdZuK/c2Vr4Nb+Qg=="],- "is-plain-obj": ["[email protected]", "", {}, "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg=="],+ "is-plain-obj": ["[email protected]", "", {}, "sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA=="],"is-plain-object": ["[email protected]", "", { "dependencies": { "isobject": "^3.0.1" } }, "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og=="],@@ -2033,6 +2036,8 @@"memoize-one": ["[email protected]", "", {}, "sha512-zYiwtZUcYyXKo/np96AGZAckk+FWWsUdJ3cHGGmld7+AhvcWmQyGCYUh1hc4Q/pkOhb65dQR/pqCyK0cOaHz4Q=="],+ "merge-options": ["[email protected]", "", { "dependencies": { "is-plain-obj": "^2.1.0" } }, "sha512-2Sug1+knBjkaMsMgf1ctR1Ujx+Ayku4EdJN4Z+C2+JzoeF7A3OZ9KM2GY0CpQS51NR61LTurMJrRKPhSs3ZRTQ=="],+"merge-stream": ["[email protected]", "", {}, "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w=="],"merge2": ["[email protected]", "", {}, "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg=="],@@ -3297,6 +3302,8 @@"terser/commander": ["[email protected]", "", {}, "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ=="],+ "unified/is-plain-obj": ["[email protected]", "", {}, "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg=="],+"unifont/css-tree": ["[email protected]", "", { "dependencies": { "mdn-data": "2.27.1", "source-map-js": "^1.2.1" } }, "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA=="],"unstorage/chokidar": ["[email protected]", "", { "dependencies": { "readdirp": "^5.0.0" } }, "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw=="],