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(mobile): show notes during initial sync
tianma-if6bc95d961d1d
diff --git a/apps/mobile/app.json b/apps/mobile/app.jsonindex d32f8ac7..6bb42e85 100644--- a/apps/mobile/app.json+++ b/apps/mobile/app.json@@ -3,7 +3,7 @@"name": "EdgeEver","slug": "edgeever","scheme": "edgeever",- "version": "0.4.13",+ "version": "0.4.14","runtimeVersion": {"policy": "appVersion"},@@ -25,7 +25,7 @@},"android": {"package": "org.edgeever.mobile",- "versionCode": 19,+ "versionCode": 20,"adaptiveIcon": {"backgroundColor": "#d1fae5","backgroundImage": "./assets/icon.png",diff --git a/apps/mobile/package.json b/apps/mobile/package.jsonindex 31e51720..e6172661 100644--- a/apps/mobile/package.json+++ b/apps/mobile/package.json@@ -1,6 +1,6 @@{"name": "@edgeever/mobile",- "version": "0.4.13",+ "version": "0.4.14","private": true,"type": "module","main": "expo-router/entry",diff --git a/apps/mobile/src/lib/local-mirror.test.ts b/apps/mobile/src/lib/local-mirror.test.tsindex bc7a15a0..ec4f7db5 100644--- a/apps/mobile/src/lib/local-mirror.test.ts+++ b/apps/mobile/src/lib/local-mirror.test.ts@@ -1,5 +1,5 @@import { expect, test } from "bun:test";-import { hasMobileSyncCursorRewound, hasMobileSyncIdentityChanged, isMobileSyncMetadataInitialized } from "./mobile-sync-protocol";+import { hasMobileSyncCursorRewound, hasMobileSyncIdentityChanged, isMobileSyncMetadataInitialized, splitMobileBootstrapWriteBatches } from "./mobile-sync-protocol";test("rebuilds the mobile mirror when the server change cursor rewinds", () => {expect(hasMobileSyncCursorRewound(42, 7)).toBe(true);@@ -26,3 +26,9 @@ test("waits for a complete local mirror before rendering an empty notebook", ()expect(isMobileSyncMetadataInitialized("42", null)).toBe(false);expect(isMobileSyncMetadataInitialized("not-a-number", "workspace-a")).toBe(false);});++test("splits the initial mirror into progressive write batches", () => {+ const items = Array.from({ length: 123 }, (_, index) => index);+ expect(splitMobileBootstrapWriteBatches(items, 50).map((batch) => batch.length)).toEqual([50, 50, 23]);+ expect(splitMobileBootstrapWriteBatches([], 50)).toEqual([[]]);+});diff --git a/apps/mobile/src/lib/local-mirror.ts b/apps/mobile/src/lib/local-mirror.tsindex 7be6b016..8a080b1a 100644--- a/apps/mobile/src/lib/local-mirror.ts+++ b/apps/mobile/src/lib/local-mirror.ts@@ -1,10 +1,11 @@import type { createEdgeEverClient, ListMemosResponse, MemoFilterMode, MemoSortMode } from "@edgeever/client";import type { MemoDetail, MemoSummary, Notebook } from "@edgeever/shared";import * as SQLite from "expo-sqlite";-import { hasMobileSyncCursorRewound, hasMobileSyncIdentityChanged, isMobileSyncMetadataInitialized } from "./mobile-sync-protocol";+import { hasMobileSyncCursorRewound, hasMobileSyncIdentityChanged, isMobileSyncMetadataInitialized, splitMobileBootstrapWriteBatches } from "./mobile-sync-protocol";const DATABASE_NAME = "edgeever-mobile.db";const BOOTSTRAP_PAGE_SIZE = 200;+const BOOTSTRAP_WRITE_BATCH_SIZE = 50;const CHANGE_PAGE_SIZE = 200;let databasePromise: Promise<SQLite.SQLiteDatabase> | null = null;@@ -27,6 +28,15 @@ export type LocalMemoListParams = {offset?: number;};+export type MobileBootstrapProgress = {+ loadedCount: number;+ totalCount: number;+};++type MobileLocalMirrorSyncOptions = {+ onBootstrapProgress?: (progress: MobileBootstrapProgress) => void | Promise<void>;+};+export const createMobileDataScope = (baseUrl: string, userId?: string | null) =>`${baseUrl.trim().toLowerCase()}|${userId ?? "anonymous"}`;@@ -170,13 +180,14 @@ export const replaceLocalMemoId = async (scope: string, temporaryId: string, memexport const syncMobileLocalMirror = async (client: ReturnType<typeof createEdgeEverClient>,- scope: string+ scope: string,+ options: MobileLocalMirrorSyncOptions = {}) => {const existing = syncPromises.get(scope);if (existing) {return existing;}- const operation = performMobileLocalMirrorSync(client, scope).finally(() => {+ const operation = performMobileLocalMirrorSync(client, scope, options).finally(() => {syncPromises.delete(scope);});syncPromises.set(scope, operation);@@ -185,7 +196,8 @@ export const syncMobileLocalMirror = async (const performMobileLocalMirrorSync = async (client: ReturnType<typeof createEdgeEverClient>,- scope: string+ scope: string,+ options: MobileLocalMirrorSyncOptions = {}) => {const db = await getDatabase();const cursorRow = await db.getFirstAsync<CursorRow>(@@ -201,6 +213,7 @@ const performMobileLocalMirrorSync = async (if (cursor === null || !Number.isFinite(cursor) || syncIdentity === null) {let afterId: string | null = null;+ let loadedCount = 0;let snapshotCursor = 0;let snapshotIdentity = "legacy";await db.withExclusiveTransactionAsync(async (tx) => {@@ -216,14 +229,21 @@ const performMobileLocalMirrorSync = async (snapshotCursor = page.snapshotCursor;snapshotIdentity = page.syncIdentity || "legacy";}- await db.withExclusiveTransactionAsync(async (tx) => {- for (const notebook of page.notebooks) {- await upsertNotebook(tx, scope, notebook);- }- for (const memo of page.memos) {- await upsertMemo(tx, scope, memo);- }- });+ const writeBatches = splitMobileBootstrapWriteBatches(page.memos, BOOTSTRAP_WRITE_BATCH_SIZE);+ for (const [batchIndex, memos] of writeBatches.entries()) {+ await db.withExclusiveTransactionAsync(async (tx) => {+ if (batchIndex === 0) {+ for (const notebook of page.notebooks) {+ await upsertNotebook(tx, scope, notebook);+ }+ }+ for (const memo of memos) {+ await upsertMemo(tx, scope, memo);+ }+ });+ loadedCount += memos.length;+ await options.onBootstrapProgress?.({ loadedCount, totalCount: page.totalCount });+ }if (page.nextAfterId === null) {break;}@@ -242,7 +262,7 @@ const performMobileLocalMirrorSync = async (// change sequence. Rebuild the mirror instead of treating the stale// local cursor as proof that no remote notes exist.await db.runAsync(`DELETE FROM mobile_sync_meta WHERE scope = ? AND key IN ('cursor', 'identity')`, scope);- return performMobileLocalMirrorSync(client, scope);+ return performMobileLocalMirrorSync(client, scope, options);}await db.withExclusiveTransactionAsync(async (tx) => {for (const change of page.changes) {diff --git a/apps/mobile/src/lib/mobile-sync-protocol.ts b/apps/mobile/src/lib/mobile-sync-protocol.tsindex 13856284..1b4eae20 100644--- a/apps/mobile/src/lib/mobile-sync-protocol.ts+++ b/apps/mobile/src/lib/mobile-sync-protocol.ts@@ -8,3 +8,14 @@ export const isMobileSyncMetadataInitialized = (cursorValue: string | null | undefined,identityValue: string | null | undefined) => Boolean(identityValue?.trim()) && typeof cursorValue === "string" && cursorValue.trim().length > 0 && Number.isFinite(Number(cursorValue));++export const splitMobileBootstrapWriteBatches = <T>(items: T[], batchSize: number): T[][] => {+ const normalizedBatchSize = Math.max(1, Math.floor(batchSize));+ if (items.length === 0) {+ return [[]];+ }+ return Array.from(+ { length: Math.ceil(items.length / normalizedBatchSize) },+ (_, index) => items.slice(index * normalizedBatchSize, (index + 1) * normalizedBatchSize)+ );+};diff --git a/apps/mobile/src/lib/mobile-theme.tsx b/apps/mobile/src/lib/mobile-theme.tsxindex 631f11cb..f3f45d55 100644--- a/apps/mobile/src/lib/mobile-theme.tsx+++ b/apps/mobile/src/lib/mobile-theme.tsx@@ -38,6 +38,7 @@ const backgroundDarkMap: Record<string, string> = {"#f1f5f9": "#1e293b","#ecfdf5": "#064e3b","#ecfdf3": "#064e3b",+ "#d1fae5": "#065f46","#f0fdf4": "#052e16","#fef2f2": "#450a0a","#fff1f2": "#4c0519",diff --git a/apps/mobile/src/screens/WorkspaceScreen.tsx b/apps/mobile/src/screens/WorkspaceScreen.tsxindex a298ff41..de2dfddb 100644--- a/apps/mobile/src/screens/WorkspaceScreen.tsx+++ b/apps/mobile/src/screens/WorkspaceScreen.tsx@@ -112,6 +112,7 @@ import {resolveLocalMemo,syncMobileLocalMirror,upsertLocalMemo,+ type MobileBootstrapProgress,} from "../lib/local-mirror";import { AccountSecurityPanel } from "./AccountSecurityModal";import { beginEditorStartup, markStartup, recordEditorStartup } from "../lib/startup-performance";@@ -259,6 +260,10 @@ export const WorkspaceScreen = () => {const [selectedMemoIds, setSelectedMemoIds] = useState<Set<string>>(() => new Set());const [selectionMoveOpen, setSelectionMoveOpen] = useState(false);const [selectionMoreOpen, setSelectionMoreOpen] = useState(false);+ const [isInitialMirrorStatusPending, setIsInitialMirrorStatusPending] = useState(true);+ const [initialMirrorSyncProgress, setInitialMirrorSyncProgress] = useState<MobileBootstrapProgress | null>(null);+ const [initialMirrorSyncError, setInitialMirrorSyncError] = useState<unknown>(null);+ const [mirrorSyncAttempt, setMirrorSyncAttempt] = useState(0);const autoSyncRunningRef = useRef(false);const autoSyncRequestedRef = useRef(false);const autoSyncRetryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);@@ -272,9 +277,6 @@ export const WorkspaceScreen = () => {throw new Error("Client is not ready");}- if (!(await isMobileLocalMirrorInitialized(dataScope))) {- await syncMobileLocalMirror(client, dataScope);- }return listLocalNotebooks(dataScope);},enabled: Boolean(client),@@ -295,10 +297,6 @@ export const WorkspaceScreen = () => {throw new Error("Client is not ready");}- if (pageParam === 0 && !(await isMobileLocalMirrorInitialized(dataScope))) {- await syncMobileLocalMirror(client, dataScope);- }-return listLocalMemos(dataScope, {notebookIds: activeNotebookDescendantIds,filter: memoFilterMode,@@ -960,17 +958,46 @@ export const WorkspaceScreen = () => {}let active = true;const syncMirror = async () => {+ let isInitialSync = false;+ let refreshedNotebooksDuringBootstrap = false;try {- await syncMobileLocalMirror(client, dataScope);+ isInitialSync = !(await isMobileLocalMirrorInitialized(dataScope));+ if (active) {+ setIsInitialMirrorStatusPending(false);+ setInitialMirrorSyncError(null);+ setInitialMirrorSyncProgress(isInitialSync ? { loadedCount: 0, totalCount: 0 } : null);+ }+ await syncMobileLocalMirror(client, dataScope, {+ onBootstrapProgress: isInitialSync ? async (progress) => {+ if (!active) {+ return;+ }+ setInitialMirrorSyncProgress(progress);+ const invalidations = [+ queryClient.invalidateQueries({ queryKey: ["mobile", "memos"] }),+ queryClient.invalidateQueries({ queryKey: ["mobile", "search"] }),+ ];+ if (!refreshedNotebooksDuringBootstrap) {+ refreshedNotebooksDuringBootstrap = true;+ invalidations.push(queryClient.invalidateQueries({ queryKey: ["mobile", "notebooks"] }));+ }+ await Promise.all(invalidations);+ } : undefined,+ });if (active) {await Promise.all([queryClient.invalidateQueries({ queryKey: ["mobile", "notebooks"] }),queryClient.invalidateQueries({ queryKey: ["mobile", "memos"] }),queryClient.invalidateQueries({ queryKey: ["mobile", "search"] }),]);+ setInitialMirrorSyncProgress(null);}- } catch {- // The local mirror remains readable while the device is offline.+ } catch (error) {+ if (active && isInitialSync) {+ setInitialMirrorSyncProgress(null);+ setInitialMirrorSyncError(error);+ }+ // An initialized local mirror remains readable while the device is offline.}};void syncMirror();@@ -983,7 +1010,7 @@ export const WorkspaceScreen = () => {active = false;subscription.remove();};- }, [client, dataScope, queryClient]);+ }, [client, dataScope, mirrorSyncAttempt, queryClient]);if (richEditingSession) {return <RichEditorModal@@ -1003,7 +1030,8 @@ export const WorkspaceScreen = () => {{activeView === "notes" ? (<NotesViewactiveNotebook={activeNotebook}- isLoading={notebooksQuery.isLoading || (searchActive ? searchQuery.isLoading : memosQuery.isLoading)}+ initialSyncProgress={initialMirrorSyncProgress}+ isLoading={notebooksQuery.isLoading || (searchActive ? searchQuery.isLoading : memosQuery.isLoading) || (isInitialMirrorStatusPending && visibleMemos.length === 0)}isLoadingMore={searchActive ? searchQuery.isFetchingNextPage : memosQuery.isFetchingNextPage}isRefreshing={isRefreshing}memoFilterMode={memoFilterMode}@@ -1036,8 +1064,13 @@ export const WorkspaceScreen = () => {: memosQuery.data?.pages[0]?.totalCount ?? memos.length}selectionMode={selectionMode}selectedMemoIds={selectedMemoIds}- error={notebooksQuery.error ?? (searchActive ? searchQuery.error : memosQuery.error)}- isError={notebooksQuery.isError || (searchActive ? searchQuery.isError : memosQuery.isError)}+ error={initialMirrorSyncError ?? notebooksQuery.error ?? (searchActive ? searchQuery.error : memosQuery.error)}+ isError={Boolean(initialMirrorSyncError) || notebooksQuery.isError || (searchActive ? searchQuery.isError : memosQuery.isError)}+ onRetry={() => {+ setIsInitialMirrorStatusPending(true);+ setInitialMirrorSyncError(null);+ setMirrorSyncAttempt((attempt) => attempt + 1);+ }}/>) : null}@@ -1233,6 +1266,7 @@ export const WorkspaceScreen = () => {const NotesView = ({activeNotebook,error,+ initialSyncProgress,isError,isLoading,isLoadingMore,@@ -1251,6 +1285,7 @@ const NotesView = ({onMemoPress,onLoadMore,onRefresh,+ onRetry,onSearchTextChange,onSetMemoView,searchText,@@ -1260,6 +1295,7 @@ const NotesView = ({}: {activeNotebook: Notebook | null;error: unknown;+ initialSyncProgress: MobileBootstrapProgress | null;isError: boolean;isLoading: boolean;isLoadingMore: boolean;@@ -1278,6 +1314,7 @@ const NotesView = ({onMemoPress: (memoId: string) => void;onLoadMore: () => void;onRefresh: () => void;+ onRetry: () => void;onSearchTextChange: (value: string) => void;onSetMemoView: (memoView: MemoView) => void;searchText: string;@@ -1403,6 +1440,7 @@ const NotesView = ({emptyDescription={searchActive ? "换个关键词再试" : memoFilterMode !== "all" ? "试试切换筛选条件,或调整搜索关键词。" : memoView === "trash" ? "删除的笔记会显示在这里。" : "先创建一条笔记,之后可以在这里快速预览、搜索和批量整理。"}emptyTitle={searchActive ? "没有找到匹配笔记" : memoFilterMode !== "all" ? "没有符合筛选的笔记" : memoView === "trash" ? "回收站为空" : "暂无笔记"}error={error}+ initialSyncProgress={initialSyncProgress}isError={isError}isLoading={isLoading}isLoadingMore={isLoadingMore}@@ -1413,7 +1451,7 @@ const NotesView = ({onMemoPress={onMemoPress}onLoadMore={onLoadMore}onRefresh={onRefresh}- onRetry={onRefresh}+ onRetry={onRetry}selectionMode={selectionMode}selectedMemoIds={selectedMemoIds}/>@@ -4573,6 +4611,7 @@ const MemoList = ({emptyTitle,error,isError,+ initialSyncProgress,isLoading,isLoadingMore = false,isRefreshing,@@ -4591,6 +4630,7 @@ const MemoList = ({emptyTitle: string;error?: unknown;isError: boolean;+ initialSyncProgress: MobileBootstrapProgress | null;isLoading: boolean;isLoadingMore?: boolean;isRefreshing: boolean;@@ -4604,13 +4644,33 @@ const MemoList = ({selectionMode?: boolean;selectedMemoIds?: Set<string>;}) => {- if (isLoading) {+ const localePreference = useMobileLocalePreference();+ const englishLocale = isEnglishMobileLocale(localePreference);+ const hasInitialSyncProgress = initialSyncProgress !== null;+ const loadedCount = initialSyncProgress?.loadedCount ?? 0;+ const totalCount = initialSyncProgress?.totalCount ?? 0;+ const progressPercent = totalCount > 0 ? Math.min(100, Math.round((loadedCount / totalCount) * 100)) : 0;+ const progressTitle = englishLocale ? "Syncing your notes" : "正在同步笔记";+ const progressDescription = totalCount > 0+ ? (englishLocale ? `${loadedCount} of ${totalCount} notes loaded` : `已加载 ${loadedCount} / ${totalCount} 条笔记`)+ : (englishLocale ? "Preparing your notes for the first sync…" : "正在准备首次同步…");+ const loadingTitle = hasInitialSyncProgress ? progressTitle : (englishLocale ? "Loading notes" : "正在加载笔记");+ const loadingDescription = hasInitialSyncProgress+ ? progressDescription+ : (englishLocale ? "Loading notebooks and notes…" : "正在加载笔记本和笔记…");++ if ((isLoading || hasInitialSyncProgress) && memos.length === 0) {return (- <View accessibilityLabel="正在加载笔记" accessibilityLiveRegion="polite" style={styles.memoListStateWrap}>+ <View accessibilityLabel={loadingTitle} accessibilityLiveRegion="polite" style={styles.memoListStateWrap}><View style={styles.memoListLoadingCard}><ActivityIndicator color="#059669" size="large" />- <Text style={styles.memoListLoadingTitle}>正在加载笔记</Text>- <Text style={styles.memoListLoadingDescription}>正在同步笔记本和笔记,首次登录可能需要一点时间。</Text>+ <Text style={styles.memoListLoadingTitle}>{loadingTitle}</Text>+ <Text style={styles.memoListLoadingDescription}>{loadingDescription}</Text>+ {totalCount > 0 ? (+ <View style={styles.memoSyncProgressTrack}>+ <View style={[styles.memoSyncProgressFill, { width: `${progressPercent}%` }]} />+ </View>+ ) : null}</View></View>);@@ -4667,6 +4727,33 @@ const MemoList = ({) : null}</View>}+ ListHeaderComponent={hasInitialSyncProgress ? (+ <View accessibilityLiveRegion="polite" style={styles.memoSyncBanner}>+ <ActivityIndicator color="#059669" size="small" />+ <View style={styles.memoSyncBannerContent}>+ <Text style={styles.memoSyncBannerTitle}>{progressTitle}</Text>+ <Text style={styles.memoSyncBannerDescription}>{progressDescription}</Text>+ <View style={styles.memoSyncProgressTrack}>+ <View style={[styles.memoSyncProgressFill, { width: `${progressPercent}%` }]} />+ </View>+ </View>+ </View>+ ) : isError ? (+ <View accessibilityLiveRegion="polite" style={styles.memoSyncErrorBanner}>+ <View style={styles.memoSyncBannerContent}>+ <Text style={styles.memoSyncErrorBannerTitle}>{englishLocale ? "Sync paused" : "同步已暂停"}</Text>+ <Text style={styles.memoSyncErrorBannerDescription}>+ {englishLocale ? "Loaded notes remain available. Check your connection and retry." : "已加载的笔记仍可使用,请检查网络后重试。"}+ </Text>+ </View>+ {onRetry ? (+ <Pressable accessibilityRole="button" onPress={onRetry} style={styles.memoSyncErrorRetryButton}>+ <RotateCcw color="#92400e" size={15} />+ <Text style={styles.memoListRetryText}>{englishLocale ? "Retry" : "重试"}</Text>+ </Pressable>+ ) : null}+ </View>+ ) : null}ListFooterComponent={isLoadingMore ? <ActivityIndicator color="#0f172a" style={styles.listLoadingFooter} /> : null}updateCellsBatchingPeriod={32}windowSize={7}@@ -6539,6 +6626,74 @@ const baseWorkspaceStyles = StyleSheet.create({maxWidth: 300,textAlign: "center",},+ memoSyncBanner: {+ alignItems: "center",+ backgroundColor: "#ecfdf5",+ borderColor: "#a7f3d0",+ borderRadius: 8,+ borderWidth: 1,+ flexDirection: "row",+ gap: 12,+ marginBottom: 10,+ paddingHorizontal: 14,+ paddingVertical: 12,+ },+ memoSyncBannerContent: {+ flex: 1,+ },+ memoSyncBannerTitle: {+ color: "#065f46",+ fontSize: 13,+ fontWeight: "800",+ },+ memoSyncBannerDescription: {+ color: "#047857",+ fontSize: 12,+ marginTop: 2,+ },+ memoSyncProgressTrack: {+ backgroundColor: "#d1fae5",+ borderRadius: 999,+ height: 4,+ marginTop: 10,+ overflow: "hidden",+ width: "100%",+ },+ memoSyncProgressFill: {+ backgroundColor: "#059669",+ borderRadius: 999,+ height: "100%",+ },+ memoSyncErrorBanner: {+ alignItems: "center",+ backgroundColor: "#fffbeb",+ borderColor: "#fcd34d",+ borderRadius: 8,+ borderWidth: 1,+ flexDirection: "row",+ gap: 10,+ marginBottom: 10,+ paddingHorizontal: 14,+ paddingVertical: 12,+ },+ memoSyncErrorBannerTitle: {+ color: "#451a03",+ fontSize: 13,+ fontWeight: "800",+ },+ memoSyncErrorBannerDescription: {+ color: "#92400e",+ fontSize: 12,+ lineHeight: 18,+ marginTop: 2,+ },+ memoSyncErrorRetryButton: {+ alignItems: "center",+ flexDirection: "row",+ gap: 5,+ paddingHorizontal: 4,+ paddingVertical: 8,+ },memoListErrorCard: {alignItems: "center",backgroundColor: "#fffbeb",