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
feat(mobile): add SQLite mirror and incremental sync
tianma-ifeeb694d45d87
diff --git a/README.md b/README.mdindex c5a34d1c..5022a45a 100644--- a/README.md+++ b/README.md@@ -97,7 +97,7 @@ The Chrome/Edge web clipper is complete and pending store publication.## Native Clients-The Android app is built with Expo and React Native as a true native client. It connects directly to a self-hosted EdgeEver API and implements the mobile workspace with native views instead of embedding the PWA, prioritizing fast startup, smooth lists, instant cached content, offline drafts, and background synchronization while keeping the PWA's features and visual language aligned.+The Android app is built with Expo and React Native as a true native client. It connects directly to a self-hosted EdgeEver API and implements the mobile workspace with native views instead of embedding the PWA. A SQLite local mirror serves notebooks, note lists, search, and note details immediately; cursor-based delta sync and an offline create/edit queue reconcile changes in the background while keeping the PWA's features and visual language aligned.The desktop app remains on the roadmap and is planned to use Tauri.diff --git a/README.zh-CN.md b/README.zh-CN.mdindex b840bd01..487dd171 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -96,7 +96,7 @@ Chrome/Edge 网页裁剪插件已开发完成,待上架。## 关于客户端-Android App 基于 Expo 与 React Native 构建为真正的原生客户端,直接连接自托管 EdgeEver API,不再把 PWA 嵌入 App。移动工作区使用原生视图实现,优先保障快速启动、流畅列表、缓存内容即时显示、离线草稿和后台同步,同时持续对齐移动 PWA 的功能与视觉语言。+Android App 基于 Expo 与 React Native 构建为真正的原生客户端,直接连接自托管 EdgeEver API,不再把 PWA 嵌入 App。SQLite 本地镜像会即时提供笔记本、笔记列表、搜索和笔记详情;基于游标的增量同步与离线新建/编辑队列在后台完成云端对账,同时持续对齐移动 PWA 的功能与视觉语言。桌面端 App 仍在规划中,计划基于 Tauri 构建。diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex 10742229..e5ce62c4 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -116,6 +116,13 @@ type MemoSummaryRow = {type MemoListSortMode = "updated-desc" | "created-desc" | "title-asc";type MemoListFilterMode = "all" | "tagged" | "untagged" | "pinned";+type MobileSyncChangeRow = {+ id: number;+ entity_type: "notebook" | "memo";+ entity_id: string;+ operation: "upsert" | "delete";+};+type MemoListCursor = {sort: MemoListSortMode;id: string;@@ -788,6 +795,117 @@ app.get("/api/v1/notebooks", async (c) => {return c.json({ notebooks: rows.results.map(mapNotebook) });});+app.get("/api/v1/sync/bootstrap", async (c) => {+ const denied = requireScopes(c, "read:notebooks", "read:memos");++ if (denied) {+ return denied;+ }++ const workspaceId = getWorkspaceId(c);+ const limit = clampNumber(Number(c.req.query("limit") ?? 100), 1, 200);+ const afterId = c.req.query("afterId")?.trim() ?? "";+ const [notebookRows, memoRows, totalRow, cursorRow] = await Promise.all([+ c.env.DB.prepare(+ `SELECT n.id, n.parent_id, n.name, n.slug, n.icon, n.color, n.sort_order,+ n.created_at, n.updated_at, COUNT(m.id) AS memo_count, MAX(m.updated_at) AS last_memo_updated_at+ FROM notebooks n+ LEFT JOIN memos m ON m.notebook_id = n.id AND m.workspace_id = n.workspace_id AND m.is_deleted = 0+ WHERE n.workspace_id = ? AND n.is_deleted = 0+ GROUP BY n.id, n.parent_id, n.name, n.slug, n.icon, n.color, n.sort_order, n.created_at, n.updated_at+ ORDER BY n.sort_order ASC, n.name ASC`+ ).bind(workspaceId).all<NotebookRow>(),+ c.env.DB.prepare(+ `SELECT m.id, m.notebook_id, m.title, m.excerpt, m.tags_json, m.is_pinned,+ m.is_archived, m.is_deleted, m.created_at, m.updated_at, m.deleted_at, mc.revision,+ mc.content_json, mc.content_markdown, mc.content_text, mc.content_hash,+ m.source_memo_ids, m.merge_source_count, m.merged_into_memo_id+ FROM memos m+ INNER JOIN memo_contents mc ON mc.memo_id = m.id+ WHERE m.workspace_id = ? AND m.id > ?+ ORDER BY m.id ASC+ LIMIT ?`+ ).bind(workspaceId, afterId, limit + 1).all<MemoDetailRow>(),+ c.env.DB.prepare(`SELECT COUNT(*) AS count FROM memos WHERE workspace_id = ?`).bind(workspaceId).first<{ count: number }>(),+ c.env.DB.prepare(`SELECT COALESCE(MAX(id), 0) AS cursor FROM mobile_sync_changes WHERE workspace_id = ?`).bind(workspaceId).first<{ cursor: number }>(),+ ]);+ const page = memoRows.results.slice(0, limit);+ const totalCount = totalRow?.count ?? page.length;+ const nextAfterId = memoRows.results.length > limit ? page.at(-1)?.id ?? null : null;++ return c.json({+ notebooks: notebookRows.results.map(mapNotebook),+ memos: page.map(mapMemoDetail),+ snapshotCursor: cursorRow?.cursor ?? 0,+ totalCount,+ nextAfterId,+ });+});++app.get("/api/v1/sync/changes", async (c) => {+ const denied = requireScopes(c, "read:notebooks", "read:memos");++ if (denied) {+ return denied;+ }++ const workspaceId = getWorkspaceId(c);+ const cursor = clampNumber(Number(c.req.query("cursor") ?? 0), 0, Number.MAX_SAFE_INTEGER);+ const limit = clampNumber(Number(c.req.query("limit") ?? 100), 1, 200);+ const rows = await c.env.DB.prepare(+ `SELECT id, entity_type, entity_id, operation+ FROM mobile_sync_changes+ WHERE workspace_id = ? AND id > ?+ ORDER BY id ASC+ LIMIT ?`+ ).bind(workspaceId, cursor, limit + 1).all<MobileSyncChangeRow>();+ const page = rows.results.slice(0, limit);+ const memoIds = Array.from(new Set(page.filter((change) => change.entity_type === "memo" && change.operation === "upsert").map((change) => change.entity_id)));+ const notebookIds = Array.from(new Set(page.filter((change) => change.entity_type === "notebook" && change.operation === "upsert").map((change) => change.entity_id)));+ const memoPlaceholders = memoIds.map(() => "?").join(", ");+ const notebookPlaceholders = notebookIds.map(() => "?").join(", ");+ const [memoRows, notebookRows] = await Promise.all([+ memoIds.length > 0+ ? c.env.DB.prepare(+ `SELECT m.id, m.notebook_id, m.title, m.excerpt, m.tags_json, m.is_pinned,+ m.is_archived, m.is_deleted, m.created_at, m.updated_at, m.deleted_at, mc.revision,+ mc.content_json, mc.content_markdown, mc.content_text, mc.content_hash,+ m.source_memo_ids, m.merge_source_count, m.merged_into_memo_id+ FROM memos m+ INNER JOIN memo_contents mc ON mc.memo_id = m.id+ WHERE m.workspace_id = ? AND m.id IN (${memoPlaceholders})`+ ).bind(workspaceId, ...memoIds).all<MemoDetailRow>()+ : Promise.resolve({ results: [] as MemoDetailRow[] }),+ notebookIds.length > 0+ ? c.env.DB.prepare(+ `SELECT n.id, n.parent_id, n.name, n.slug, n.icon, n.color, n.sort_order,+ n.created_at, n.updated_at, COUNT(m.id) AS memo_count, MAX(m.updated_at) AS last_memo_updated_at+ FROM notebooks n+ LEFT JOIN memos m ON m.notebook_id = n.id AND m.workspace_id = n.workspace_id AND m.is_deleted = 0+ WHERE n.workspace_id = ? AND n.is_deleted = 0 AND n.id IN (${notebookPlaceholders})+ GROUP BY n.id, n.parent_id, n.name, n.slug, n.icon, n.color, n.sort_order, n.created_at, n.updated_at`+ ).bind(workspaceId, ...notebookIds).all<NotebookRow>()+ : Promise.resolve({ results: [] as NotebookRow[] }),+ ]);+ const memosById = new Map(memoRows.results.map((row) => [row.id, mapMemoDetail(row)]));+ const notebooksById = new Map(notebookRows.results.map((row) => [row.id, mapNotebook(row)]));+ const changes = page.map((change) => {+ if (change.entity_type === "memo") {+ const memo = change.operation === "upsert" ? memosById.get(change.entity_id) ?? null : null;+ return { cursor: change.id, entityType: change.entity_type, entityId: change.entity_id, operation: memo ? "upsert" as const : "delete" as const, notebook: null, memo };+ }++ const notebook = change.operation === "upsert" ? notebooksById.get(change.entity_id) ?? null : null;+ return { cursor: change.id, entityType: change.entity_type, entityId: change.entity_id, operation: notebook ? "upsert" as const : "delete" as const, notebook, memo: null };+ });++ return c.json({+ changes,+ cursor: page.at(-1)?.id ?? cursor,+ hasMore: rows.results.length > limit,+ });+});+app.post("/api/v1/notebooks", zValidator("json", NotebookCreateSchema), async (c) => {const denied = requireScopes(c, "write:notebooks");diff --git a/apps/mobile/app.json b/apps/mobile/app.jsonindex 30d24872..aad119fa 100644--- a/apps/mobile/app.json+++ b/apps/mobile/app.json@@ -3,7 +3,7 @@"name": "EdgeEver","slug": "edgeever","scheme": "edgeever",- "version": "0.3.2",+ "version": "0.4.0","orientation": "portrait","userInterfaceStyle": "light","newArchEnabled": true,@@ -13,7 +13,7 @@},"android": {"package": "org.edgeever.mobile",- "versionCode": 5,+ "versionCode": 6,"adaptiveIcon": {"backgroundColor": "#f8fafc"}diff --git a/apps/mobile/package.json b/apps/mobile/package.jsonindex 9f3699bf..35e3a614 100644--- a/apps/mobile/package.json+++ b/apps/mobile/package.json@@ -1,6 +1,6 @@{"name": "@edgeever/mobile",- "version": "0.3.2",+ "version": "0.4.0","private": true,"type": "module","main": "expo-router/entry",@@ -28,6 +28,7 @@"expo-image-manipulator": "~57.0.5","expo-router": "latest","expo-secure-store": "latest",+ "expo-sqlite": "~57.0.1","expo-splash-screen": "^57.0.4","expo-status-bar": "latest","react": "19.2.3",diff --git a/apps/mobile/src/lib/local-mirror.ts b/apps/mobile/src/lib/local-mirror.tsnew file mode 100644index 00000000..6be8bb65--- /dev/null+++ b/apps/mobile/src/lib/local-mirror.ts@@ -0,0 +1,306 @@+import type { createEdgeEverClient, ListMemosResponse, MemoFilterMode, MemoSortMode } from "@edgeever/client";+import type { MemoDetail, MemoSummary, Notebook } from "@edgeever/shared";+import * as SQLite from "expo-sqlite";++const DATABASE_NAME = "edgeever-mobile.db";+const BOOTSTRAP_PAGE_SIZE = 200;+const CHANGE_PAGE_SIZE = 200;++let databasePromise: Promise<SQLite.SQLiteDatabase> | null = null;+const syncPromises = new Map<string, Promise<number>>();++type StoredMemoRow = { data_json: string };+type StoredNotebookRow = { data_json: string; memo_count: number; last_memo_updated_at: string | null };+type CursorRow = { value: string };+type IdMappingRow = { remote_id: string };++export type LocalMemoListParams = {+ notebookId?: string | null;+ q?: string;+ trash?: boolean;+ sort?: MemoSortMode;+ filter?: MemoFilterMode;+ limit?: number;+};++export const createMobileDataScope = (baseUrl: string, userId?: string | null) =>+ `${baseUrl.trim().toLowerCase()}|${userId ?? "anonymous"}`;++export const listLocalNotebooks = async (scope: string): Promise<{ notebooks: Notebook[] }> => {+ const db = await getDatabase();+ const rows = await db.getAllAsync<StoredNotebookRow>(+ `SELECT n.data_json,+ COUNT(CASE WHEN m.is_deleted = 0 THEN 1 END) AS memo_count,+ MAX(CASE WHEN m.is_deleted = 0 THEN m.updated_at END) AS last_memo_updated_at+ FROM mobile_notebooks n+ LEFT JOIN mobile_memos m ON m.scope = n.scope AND m.notebook_id = n.id+ WHERE n.scope = ?+ GROUP BY n.id, n.data_json+ ORDER BY n.sort_order ASC, n.name COLLATE NOCASE ASC`,+ scope+ );++ return {+ notebooks: rows.map((row) => ({+ ...(JSON.parse(row.data_json) as Notebook),+ memoCount: row.memo_count,+ lastMemoUpdatedAt: row.last_memo_updated_at,+ })),+ };+};++export const listLocalMemos = async (scope: string, params: LocalMemoListParams): Promise<ListMemosResponse> => {+ const db = await getDatabase();+ const conditions = ["scope = ?", "is_deleted = ?"];+ const binds: (string | number)[] = [scope, params.trash ? 1 : 0];++ if (params.notebookId) {+ conditions.push("notebook_id = ?");+ binds.push(params.notebookId);+ }+ if (params.q?.trim()) {+ conditions.push("(title LIKE ? OR content_text LIKE ? OR tags_text LIKE ?)");+ const q = `%${params.q.trim()}%`;+ binds.push(q, q, q);+ }+ if (params.filter === "tagged") {+ conditions.push("tags_text <> ''");+ } else if (params.filter === "untagged") {+ conditions.push("tags_text = ''");+ } else if (params.filter === "pinned") {+ conditions.push("is_pinned = 1");+ }++ const orderBy = params.trash+ ? "deleted_at DESC, id DESC"+ : params.sort === "created-desc"+ ? "is_pinned DESC, created_at DESC, id DESC"+ : params.sort === "title-asc"+ ? "is_pinned DESC, title COLLATE NOCASE ASC, updated_at DESC, id DESC"+ : "is_pinned DESC, updated_at DESC, id DESC";+ const countRow = await db.getFirstAsync<{ count: number }>(+ `SELECT COUNT(*) AS count FROM mobile_memos WHERE ${conditions.join(" AND ")}`,+ ...binds+ );+ const rows = await db.getAllAsync<StoredMemoRow>(+ `SELECT data_json FROM mobile_memos WHERE ${conditions.join(" AND ")} ORDER BY ${orderBy} LIMIT ?`,+ ...binds,+ params.limit ?? 50+ );++ return {+ memos: rows.map((row) => toMemoSummary(JSON.parse(row.data_json) as MemoDetail)),+ totalCount: countRow?.count ?? rows.length,+ nextCursor: null,+ };+};++export const getLocalMemo = async (scope: string, memoId: string): Promise<MemoDetail | null> => {+ const db = await getDatabase();+ const row = await db.getFirstAsync<StoredMemoRow>(+ `SELECT data_json FROM mobile_memos WHERE scope = ? AND id = ?`,+ scope,+ memoId+ );+ return row ? JSON.parse(row.data_json) as MemoDetail : null;+};++export const resolveLocalMemo = async (scope: string, memoId: string): Promise<MemoDetail | null> => {+ const direct = await getLocalMemo(scope, memoId);+ if (direct) {+ return direct;+ }+ const db = await getDatabase();+ const mapping = await db.getFirstAsync<IdMappingRow>(+ `SELECT remote_id FROM mobile_id_mappings WHERE scope = ? AND temporary_id = ?`,+ scope,+ memoId+ );+ return mapping ? getLocalMemo(scope, mapping.remote_id) : null;+};++export const upsertLocalMemo = async (scope: string, memo: MemoDetail) => {+ const db = await getDatabase();+ await upsertMemo(db, scope, memo);+};++export const deleteLocalMemo = async (scope: string, memoId: string) => {+ const db = await getDatabase();+ await db.runAsync(`DELETE FROM mobile_memos WHERE scope = ? AND id = ?`, scope, memoId);+};++export const replaceLocalMemoId = async (scope: string, temporaryId: string, memo: MemoDetail) => {+ const db = await getDatabase();+ await db.withExclusiveTransactionAsync(async (tx) => {+ await upsertMemo(tx, scope, memo);+ await tx.runAsync(`DELETE FROM mobile_memos WHERE scope = ? AND id = ?`, scope, temporaryId);+ await tx.runAsync(+ `INSERT OR REPLACE INTO mobile_id_mappings (scope, temporary_id, remote_id, created_at) VALUES (?, ?, ?, ?)`,+ scope,+ temporaryId,+ memo.id,+ new Date().toISOString()+ );+ });+};++export const syncMobileLocalMirror = async (+ client: ReturnType<typeof createEdgeEverClient>,+ scope: string+) => {+ const existing = syncPromises.get(scope);+ if (existing) {+ return existing;+ }+ const operation = performMobileLocalMirrorSync(client, scope).finally(() => {+ syncPromises.delete(scope);+ });+ syncPromises.set(scope, operation);+ return operation;+};++const performMobileLocalMirrorSync = async (+ client: ReturnType<typeof createEdgeEverClient>,+ scope: string+) => {+ const db = await getDatabase();+ const cursorRow = await db.getFirstAsync<CursorRow>(+ `SELECT value FROM mobile_sync_meta WHERE scope = ? AND key = 'cursor'`,+ scope+ );+ let cursor = cursorRow ? Number(cursorRow.value) : null;++ if (cursor === null || !Number.isFinite(cursor)) {+ let afterId: string | null = null;+ let snapshotCursor = 0;+ await db.withExclusiveTransactionAsync(async (tx) => {+ await tx.runAsync(`DELETE FROM mobile_notebooks WHERE scope = ?`, scope);+ await tx.runAsync(`DELETE FROM mobile_memos WHERE scope = ?`, scope);+ });++ while (true) {+ const page = await client.getMobileSyncBootstrapPage(afterId, BOOTSTRAP_PAGE_SIZE);+ if (afterId === null) {+ snapshotCursor = page.snapshotCursor;+ }+ 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);+ }+ });+ if (page.nextAfterId === null) {+ break;+ }+ afterId = page.nextAfterId;+ }+ cursor = snapshotCursor;+ await setCursor(db, scope, cursor);+ }++ while (true) {+ const page = await client.getMobileSyncChanges(cursor, CHANGE_PAGE_SIZE);+ await db.withExclusiveTransactionAsync(async (tx) => {+ for (const change of page.changes) {+ if (change.entityType === "memo") {+ if (change.memo) {+ await upsertMemo(tx, scope, change.memo);+ } else {+ await tx.runAsync(`DELETE FROM mobile_memos WHERE scope = ? AND id = ?`, scope, change.entityId);+ }+ } else if (change.notebook) {+ await upsertNotebook(tx, scope, change.notebook);+ } else {+ await tx.runAsync(`DELETE FROM mobile_notebooks WHERE scope = ? AND id = ?`, scope, change.entityId);+ }+ }+ await setCursor(tx, scope, page.cursor);+ });+ cursor = page.cursor;+ if (!page.hasMore) {+ return cursor;+ }+ }+};++const getDatabase = async () => {+ databasePromise ??= SQLite.openDatabaseAsync(DATABASE_NAME).then(async (db) => {+ await db.execAsync(`+ PRAGMA journal_mode = WAL;+ CREATE TABLE IF NOT EXISTS mobile_notebooks (+ scope TEXT NOT NULL, id TEXT NOT NULL, name TEXT NOT NULL, sort_order INTEGER NOT NULL,+ data_json TEXT NOT NULL, PRIMARY KEY (scope, id)+ );+ CREATE TABLE IF NOT EXISTS mobile_memos (+ scope TEXT NOT NULL, id TEXT NOT NULL, notebook_id TEXT NOT NULL, title TEXT NOT NULL,+ content_text TEXT NOT NULL, tags_text TEXT NOT NULL, is_pinned INTEGER NOT NULL,+ is_deleted INTEGER NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL,+ deleted_at TEXT, data_json TEXT NOT NULL, PRIMARY KEY (scope, id)+ );+ CREATE INDEX IF NOT EXISTS idx_mobile_memos_feed ON mobile_memos(scope, is_deleted, updated_at DESC);+ CREATE INDEX IF NOT EXISTS idx_mobile_memos_notebook ON mobile_memos(scope, notebook_id, is_deleted, updated_at DESC);+ CREATE TABLE IF NOT EXISTS mobile_sync_meta (+ scope TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY (scope, key)+ );+ CREATE TABLE IF NOT EXISTS mobile_id_mappings (+ scope TEXT NOT NULL, temporary_id TEXT NOT NULL, remote_id TEXT NOT NULL, created_at TEXT NOT NULL,+ PRIMARY KEY (scope, temporary_id)+ );+ `);+ return db;+ });+ return databasePromise;+};++const upsertNotebook = (db: SQLite.SQLiteDatabase, scope: string, notebook: Notebook) =>+ db.runAsync(+ `INSERT OR REPLACE INTO mobile_notebooks (scope, id, name, sort_order, data_json) VALUES (?, ?, ?, ?, ?)`,+ scope,+ notebook.id,+ notebook.name,+ notebook.sortOrder,+ JSON.stringify(notebook)+ );++const upsertMemo = (db: SQLite.SQLiteDatabase, scope: string, memo: MemoDetail) =>+ db.runAsync(+ `INSERT OR REPLACE INTO mobile_memos+ (scope, id, notebook_id, title, content_text, tags_text, is_pinned, is_deleted, created_at, updated_at, deleted_at, data_json)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,+ scope,+ memo.id,+ memo.notebookId,+ memo.title ?? "",+ memo.contentText,+ memo.tags.join(" "),+ memo.isPinned ? 1 : 0,+ memo.isDeleted ? 1 : 0,+ memo.createdAt,+ memo.updatedAt,+ memo.deletedAt,+ JSON.stringify(memo)+ );++const setCursor = (db: SQLite.SQLiteDatabase, scope: string, cursor: number) =>+ db.runAsync(+ `INSERT OR REPLACE INTO mobile_sync_meta (scope, key, value) VALUES (?, 'cursor', ?)`,+ scope,+ String(cursor)+ );++const toMemoSummary = (memo: MemoDetail): MemoSummary => ({+ id: memo.id,+ notebookId: memo.notebookId,+ title: memo.title,+ excerpt: memo.excerpt,+ tags: memo.tags,+ isPinned: memo.isPinned,+ isArchived: memo.isArchived,+ isDeleted: memo.isDeleted,+ revision: memo.revision,+ createdAt: memo.createdAt,+ updatedAt: memo.updatedAt,+ deletedAt: memo.deletedAt,+});diff --git a/apps/mobile/src/lib/sync-queue.test.ts b/apps/mobile/src/lib/sync-queue.test.tsindex b8b8c3ad..c6aab5f5 100644--- a/apps/mobile/src/lib/sync-queue.test.ts+++ b/apps/mobile/src/lib/sync-queue.test.ts@@ -15,7 +15,7 @@ mock.module("@react-native-async-storage/async-storage", () => ({},}));-const { listMobileSyncQueueItems, queueMobileMemoUpdate, syncMobileQueuedChanges } = await import("./sync-queue");+const { listMobileSyncQueueItems, queueMobileMemoCreate, queueMobileMemoUpdate, syncMobileQueuedChanges } = await import("./sync-queue");const basePayload = {memoId: "memo-1",@@ -75,6 +75,70 @@ test("rebases a newer local save when an older save finishes syncing", async ()expect(queued?.payload.expectedContentHash).toBe("hash-2");});+test("syncs an offline create and reports its temporary id", async () => {+ await queueMobileMemoCreate("https://one.example", {+ memoId: "local:one",+ title: "Offline",+ contentMarkdown: "offline body",+ notebookId: "notebook-1",+ tags: ["offline"],+ createdAt: "2026-01-01T00:00:00.000Z",+ });+ const remoteMemo = createMemo({ id: "memo-remote", title: "Offline", contentMarkdown: "offline body" });+ let syncedTemporaryId = "";++ await syncMobileQueuedChanges({ createMemo: async () => ({ memo: remoteMemo }) } as never, "https://one.example", {+ onSynced: (_memo, item) => {+ syncedTemporaryId = item.memoId;+ },+ });++ expect(syncedTemporaryId).toBe("local:one");+ expect(await listMobileSyncQueueItems("https://one.example")).toHaveLength(0);+});++test("promotes an edit made while an offline create is syncing", async () => {+ const scope = "https://one.example";+ await queueMobileMemoCreate(scope, {+ memoId: "local:one",+ title: "Offline",+ contentMarkdown: "first",+ notebookId: "notebook-1",+ tags: [],+ createdAt: "2026-01-01T00:00:00.000Z",+ });+ let markCreateStarted: (() => void) | undefined;+ const createStarted = new Promise<void>((resolve) => {+ markCreateStarted = resolve;+ });+ let resolveCreate: ((memo: MemoDetail) => void) | undefined;+ const createResponse = new Promise<MemoDetail>((resolve) => {+ resolveCreate = resolve;+ });+ const client = {+ createMemo: async () => {+ markCreateStarted?.();+ return createResponse.then((memo) => ({ memo }));+ },+ };+ const sync = syncMobileQueuedChanges(client as never, scope);+ await createStarted;+ await queueMobileMemoUpdate(scope, {+ ...basePayload,+ memoId: "local:one",+ title: "Newest",+ contentMarkdown: "newest",+ });+ resolveCreate?.(createMemo({ id: "memo-remote", revision: 0, contentHash: "hash-remote" }));+ await sync;++ const queued = (await listMobileSyncQueueItems(scope))[0];+ expect(queued?.kind).toBe("memo.update");+ expect(queued?.memoId).toBe("memo-remote");+ expect(queued?.payload.title).toBe("Newest");+ expect(queued?.payload.expectedContentHash).toBe("hash-remote");+});+const createMemo = (overrides: Partial<MemoDetail> = {}): MemoDetail => ({id: "memo-1",notebookId: "notebook-1",diff --git a/apps/mobile/src/lib/sync-queue.ts b/apps/mobile/src/lib/sync-queue.tsindex 84f84aca..078601b3 100644--- a/apps/mobile/src/lib/sync-queue.ts+++ b/apps/mobile/src/lib/sync-queue.ts@@ -15,12 +15,19 @@ export type MobileMemoUpdateSyncPayload = {tags: string[];};-export type MobileSyncQueueItem = {+export type MobileMemoCreateSyncPayload = {+ memoId: string;+ title: string;+ contentMarkdown: string;+ notebookId: string;+ tags: string[];+ createdAt: string;+};++type MobileSyncQueueItemBase = {id: string;- kind: "memo.update";memoId: string;status: "pending" | "syncing" | "conflict" | "error";- payload: MobileMemoUpdateSyncPayload;attemptCount: number;lastError: string | null;nextAttemptAt: string | null;@@ -29,6 +36,18 @@ export type MobileSyncQueueItem = {version: number;};+export type MobileMemoUpdateSyncQueueItem = MobileSyncQueueItemBase & {+ kind: "memo.update";+ payload: MobileMemoUpdateSyncPayload;+};++export type MobileMemoCreateSyncQueueItem = MobileSyncQueueItemBase & {+ kind: "memo.create";+ payload: MobileMemoCreateSyncPayload;+};++export type MobileSyncQueueItem = MobileMemoUpdateSyncQueueItem | MobileMemoCreateSyncQueueItem;+let syncQueueWriteChain: Promise<void> = Promise.resolve();export type MobileSyncQueueSummary = {@@ -55,13 +74,55 @@ export const emptyMobileSyncQueueSummary = (): MobileSyncQueueSummary => ({});export const getMobileMemoUpdateQueueId = (memoId: string) => `memo.update:${memoId}`;+export const getMobileMemoCreateQueueId = (memoId: string) => `memo.create:${memoId}`;++export const queueMobileMemoCreate = async (scope: string, payload: MobileMemoCreateSyncPayload) => {+ const now = new Date().toISOString();+ const id = getMobileMemoCreateQueueId(payload.memoId);+ await mutateMobileSyncQueue(scope, (items) => {+ const existing = items.find((item) => item.id === id);+ const nextItem: MobileMemoCreateSyncQueueItem = {+ id,+ kind: "memo.create",+ memoId: payload.memoId,+ status: "pending",+ payload,+ attemptCount: existing?.attemptCount ?? 0,+ lastError: null,+ nextAttemptAt: null,+ createdAt: existing?.createdAt ?? now,+ updatedAt: now,+ version: (existing?.version ?? 0) + 1,+ };+ return [nextItem, ...items.filter((item) => item.id !== id)];+ });+ return summarizeMobileSyncQueue(await readMobileSyncQueue(scope));+};export const queueMobileMemoUpdate = async (scope: string, payload: MobileMemoUpdateSyncPayload) => {const now = new Date().toISOString();const id = getMobileMemoUpdateQueueId(payload.memoId);await mutateMobileSyncQueue(scope, (items) => {+ const pendingCreate = items.find((item): item is MobileMemoCreateSyncQueueItem => item.kind === "memo.create" && item.memoId === payload.memoId);+ if (pendingCreate) {+ return items.map((item) => item.id === pendingCreate.id ? {+ ...pendingCreate,+ status: "pending",+ payload: {+ ...pendingCreate.payload,+ title: payload.title,+ contentMarkdown: payload.contentMarkdown,+ notebookId: payload.notebookId,+ tags: payload.tags,+ },+ lastError: null,+ nextAttemptAt: null,+ updatedAt: now,+ version: pendingCreate.version + 1,+ } : item);+ }const existing = items.find((item) => item.id === id);- const nextItem: MobileSyncQueueItem = {+ const nextItem: MobileMemoUpdateSyncQueueItem = {id,kind: "memo.update",memoId: payload.memoId,@@ -108,7 +169,7 @@ export const syncMobileQueuedChanges = async (client: ReturnType<typeof createEdgeEverClient>,scope: string,options: {- onSynced?: (memo: MemoDetail) => void | Promise<void>;+ onSynced?: (memo: MemoDetail, item: MobileSyncQueueItem) => void | Promise<void>;} = {}): Promise<MobileSyncRunResult> => {const result: MobileSyncRunResult = {@@ -136,7 +197,10 @@ export const syncMobileQueuedChanges = async (const removed = await removeMobileSyncQueueItem(scope, item.id, itemVersion);if (removed) {- await options.onSynced?.(memo);+ await options.onSynced?.(memo, item);+ } else if (item.kind === "memo.create") {+ await promoteQueuedMemoCreate(scope, item.id, itemVersion, memo);+ await options.onSynced?.(memo, item);} else {await rebaseQueuedMemoUpdate(scope, item.id, itemVersion, memo);}@@ -173,6 +237,18 @@ export const shouldQueueMobileMemoSaveError = (error: unknown) => {};const syncMobileQueueItem = async (client: ReturnType<typeof createEdgeEverClient>, item: MobileSyncQueueItem) => {+ if (item.kind === "memo.create") {+ const response = await client.createMemo({+ notebookId: item.payload.notebookId,+ title: item.payload.title,+ contentMarkdown: item.payload.contentMarkdown,+ tags: item.payload.tags,+ createdAt: item.payload.createdAt,+ updatedAt: item.updatedAt,+ });+ return response.memo;+ }+const { editSession } = await client.createMemoEditSession(item.memoId);if (@@ -223,7 +299,7 @@ const readMobileSyncQueue = async (scope: string): Promise<MobileSyncQueueItem[]const writeMobileSyncQueue = (scope: string, items: MobileSyncQueueItem[]) =>AsyncStorage.setItem(getSyncQueueStorageKey(scope), JSON.stringify(items));-const updateMobileSyncQueueItem = async (scope: string, id: string, patch: Partial<MobileSyncQueueItem>, expectedVersion?: number) => {+const updateMobileSyncQueueItem = async (scope: string, id: string, patch: Partial<MobileSyncQueueItemBase>, expectedVersion?: number) => {let updated = false;await mutateMobileSyncQueue(scope, (items) =>items.map((item) => {@@ -256,7 +332,7 @@ const removeMobileSyncQueueItem = async (scope: string, id: string, expectedVersconst rebaseQueuedMemoUpdate = async (scope: string, id: string, syncedVersion: number, memo: MemoDetail) => {await mutateMobileSyncQueue(scope, (items) =>items.map((item) => {- if (item.id !== id || (item.version ?? 1) <= syncedVersion) {+ if (item.id !== id || item.kind !== "memo.update" || (item.version ?? 1) <= syncedVersion) {return item;}@@ -276,6 +352,38 @@ const rebaseQueuedMemoUpdate = async (scope: string, id: string, syncedVersion:);};+const promoteQueuedMemoCreate = async (scope: string, id: string, syncedVersion: number, memo: MemoDetail) => {+ await mutateMobileSyncQueue(scope, (items) => {+ const current = items.find((item) => item.id === id);+ if (!current || current.kind !== "memo.create" || current.version <= syncedVersion) {+ return items;+ }+ const now = new Date().toISOString();+ const promoted: MobileMemoUpdateSyncQueueItem = {+ id: getMobileMemoUpdateQueueId(memo.id),+ kind: "memo.update",+ memoId: memo.id,+ status: "pending",+ payload: {+ memoId: memo.id,+ expectedRevision: memo.revision,+ expectedContentHash: memo.contentHash,+ title: current.payload.title,+ contentMarkdown: current.payload.contentMarkdown,+ notebookId: current.payload.notebookId,+ tags: current.payload.tags,+ },+ attemptCount: 0,+ lastError: null,+ nextAttemptAt: null,+ createdAt: current.createdAt,+ updatedAt: now,+ version: 1,+ };+ return [promoted, ...items.filter((item) => item.id !== id && item.id !== promoted.id)];+ });+};+const mutateMobileSyncQueue = async (scope: string, mutate: (items: MobileSyncQueueItem[]) => MobileSyncQueueItem[]) => {const operation = syncQueueWriteChain.then(async () => {const items = await readMobileSyncQueue(scope);@@ -301,7 +409,7 @@ const isMobileSyncQueueItem = (value: unknown): value is MobileSyncQueueItem =>}const item = value as Partial<MobileSyncQueueItem>;- return item.kind === "memo.update" && typeof item.id === "string" && typeof item.memoId === "string" && Boolean(item.payload);+ return (item.kind === "memo.update" || item.kind === "memo.create") && typeof item.id === "string" && typeof item.memoId === "string" && Boolean(item.payload);};const isRevisionConflict = (error: unknown) => error instanceof ApiRequestError && error.code === "revision_conflict";diff --git a/apps/mobile/src/screens/WorkspaceScreen.tsx b/apps/mobile/src/screens/WorkspaceScreen.tsxindex d96ef950..cf9f6269 100644--- a/apps/mobile/src/screens/WorkspaceScreen.tsx+++ b/apps/mobile/src/screens/WorkspaceScreen.tsx@@ -73,7 +73,7 @@ import {View,} from "react-native";import { SafeAreaView } from "react-native-safe-area-context";-import type { ApiToken, MemoDetail, MemoRevision, MemoSummary, Notebook, ResourceListItem, TagSummary } from "@edgeever/shared";+import { createExcerpt, docToText, markdownToDoc, type ApiToken, type MemoDetail, type MemoRevision, type MemoSummary, type Notebook, type ResourceListItem, type TagSummary } from "@edgeever/shared";import { clearMobileMemoDraft, readMobileMemoDraft, writeMobileMemoDraft } from "../lib/mobile-drafts";import {readMobileImageCompressionEnabled,@@ -98,11 +98,22 @@ import {getMobileSyncRetryDelay,listMobileSyncQueueItems,loadMobileSyncQueueSummary,+ queueMobileMemoCreate,queueMobileMemoUpdate,syncMobileQueuedChanges,type MobileSyncQueueItem,type MobileSyncQueueSummary,} from "../lib/sync-queue";+import {+ createMobileDataScope,+ getLocalMemo,+ listLocalMemos,+ listLocalNotebooks,+ replaceLocalMemoId,+ resolveLocalMemo,+ syncMobileLocalMirror,+ upsertLocalMemo,+} from "../lib/local-mirror";import { AccountSecurityModal } from "./AccountSecurityModal";import { getStartupPerformanceItems, markStartup } from "../lib/startup-performance";@@ -298,6 +309,7 @@ export const WorkspaceScreen = () => {const { client, session, signOut } = useSession();const queryClient = useQueryClient();const syncQueueScope = session?.baseUrl ?? "";+ const dataScope = createMobileDataScope(session?.baseUrl ?? "", session?.user?.id);const [activeView, setActiveView] = useState<MobileView>("notes");const [activeNotebookId, setActiveNotebookId] = useState<string>(ALL_NOTES_ID);const [memoView, setMemoView] = useState<MemoView>("notebook");@@ -344,7 +356,12 @@ export const WorkspaceScreen = () => {throw new Error("Client is not ready");}- return client.listNotebooks();+ let local = await listLocalNotebooks(dataScope);+ if (local.notebooks.length === 0) {+ await syncMobileLocalMirror(client, dataScope);+ local = await listLocalNotebooks(dataScope);+ }+ return local;},enabled: Boolean(client),});@@ -359,7 +376,7 @@ export const WorkspaceScreen = () => {throw new Error("Client is not ready");}- return client.listMemos({+ return listLocalMemos(dataScope, {notebookId: activeNotebookId === ALL_NOTES_ID ? null : activeNotebookId,filter: memoFilterMode,limit: 50,@@ -378,7 +395,7 @@ export const WorkspaceScreen = () => {throw new Error("Client is not ready");}- return client.listMemos({+ return listLocalMemos(dataScope, {q: debouncedSearchText,limit: 50,sort: "updated-desc",@@ -395,7 +412,13 @@ export const WorkspaceScreen = () => {throw new Error("Memo is not selected");}- return client.getMemo(selectedMemoId, { includeDeleted: memoView === "trash" });+ const local = await getLocalMemo(dataScope, selectedMemoId);+ if (local) {+ return { memo: local };+ }+ const response = await client.getMemo(selectedMemoId, { includeDeleted: memoView === "trash" });+ await upsertLocalMemo(dataScope, response.memo);+ return response;},enabled: Boolean(client && selectedMemoId),});@@ -413,6 +436,9 @@ export const WorkspaceScreen = () => {}, [memosQuery.data, notebooksQuery.data]);const refresh = async () => {+ if (client) {+ await syncMobileLocalMirror(client, dataScope);+ }await Promise.all([queryClient.invalidateQueries({ queryKey: ["mobile", "notebooks"] }),queryClient.invalidateQueries({ queryKey: ["mobile", "memos"] }),@@ -621,6 +647,9 @@ export const WorkspaceScreen = () => {};const invalidateWorkspace = async () => {+ if (client) {+ await syncMobileLocalMirror(client, dataScope);+ }await Promise.all([queryClient.invalidateQueries({ queryKey: ["mobile", "notebooks"] }),queryClient.invalidateQueries({ queryKey: ["mobile", "memos"] }),@@ -659,12 +688,13 @@ export const WorkspaceScreen = () => {const localUpdateMemoMutation = useMutation({mutationFn: async ({ memo, payload }: { memo: MemoDetail; payload: { title?: string; contentMarkdown?: string; isPinned?: boolean; notebookId?: string; tags?: string[] } }) => {- const optimisticMemo = createOptimisticMemo(memo, payload);+ const syncBaseMemo = await resolveLocalMemo(dataScope, memo.id) ?? memo;+ const optimisticMemo = createOptimisticMemo(syncBaseMemo, payload);await queueMobileMemoUpdate(syncQueueScope, {- memoId: memo.id,- expectedRevision: memo.revision,- expectedContentHash: memo.contentHash,+ memoId: syncBaseMemo.id,+ expectedRevision: syncBaseMemo.revision,+ expectedContentHash: syncBaseMemo.contentHash,title: optimisticMemo.title?.trim() || DEFAULT_MEMO_TITLE,contentMarkdown: optimisticMemo.contentMarkdown,notebookId: optimisticMemo.notebookId,@@ -674,6 +704,7 @@ export const WorkspaceScreen = () => {return optimisticMemo;},onSuccess: async (memo, variables) => {+ await upsertLocalMemo(dataScope, memo);applyOptimisticMemoToCache(queryClient, variables.memo, memo);setSyncQueueSummary(await loadMobileSyncQueueSummary(syncQueueScope));setSyncQueueMessage("已保存到本地,正在后台同步");@@ -888,7 +919,14 @@ export const WorkspaceScreen = () => {try {const result = await syncMobileQueuedChanges(client, syncQueueScope, {- onSynced: async (memo) => {+ onSynced: async (memo, item) => {+ if (item.kind === "memo.create") {+ await replaceLocalMemoId(dataScope, item.memoId, memo);+ setSelectedMemoId((current) => current === item.memoId ? memo.id : current);+ setEditingMemo((current) => current?.id === item.memoId ? memo : current);+ } else {+ await upsertLocalMemo(dataScope, memo);+ }queryClient.setQueryData(["mobile", "memo", "notebook", memo.id], { memo });queryClient.setQueryData(["mobile", "memo", "trash", memo.id], { memo });},@@ -937,7 +975,14 @@ export const WorkspaceScreen = () => {try {const result = await syncMobileQueuedChanges(client, syncQueueScope, {- onSynced: async (memo) => {+ onSynced: async (memo, item) => {+ if (item.kind === "memo.create") {+ await replaceLocalMemoId(dataScope, item.memoId, memo);+ setSelectedMemoId((current) => current === item.memoId ? memo.id : current);+ setEditingMemo((current) => current?.id === item.memoId ? memo : current);+ } else {+ await upsertLocalMemo(dataScope, memo);+ }queryClient.setQueryData(["mobile", "memo", "notebook", memo.id], { memo });queryClient.setQueryData(["mobile", "memo", "trash", memo.id], { memo });},@@ -991,6 +1036,37 @@ export const WorkspaceScreen = () => {};}, [client, syncQueueScope]);+ useEffect(() => {+ if (!client) {+ return;+ }+ let active = true;+ const syncMirror = async () => {+ try {+ await syncMobileLocalMirror(client, dataScope);+ if (active) {+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: ["mobile", "notebooks"] }),+ queryClient.invalidateQueries({ queryKey: ["mobile", "memos"] }),+ queryClient.invalidateQueries({ queryKey: ["mobile", "search"] }),+ ]);+ }+ } catch {+ // The local mirror remains readable while the device is offline.+ }+ };+ void syncMirror();+ const subscription = AppState.addEventListener("change", (nextState: AppStateStatus) => {+ if (nextState === "active") {+ void syncMirror();+ }+ });+ return () => {+ active = false;+ subscription.remove();+ };+ }, [client, dataScope, queryClient]);+return (<MobileLocaleContext.Provider value={localePreference}><SafeAreaView style={styles.safeArea}>@@ -1155,6 +1231,7 @@ export const WorkspaceScreen = () => {{createOpen ? <CreateMemoModalactiveNotebookId={activeNotebookId}+ dataScope={dataScope}notebooks={notebooks}onClose={() => setCreateOpen(false)}onCreated={(memo) => {@@ -1162,9 +1239,17 @@ export const WorkspaceScreen = () => {setActiveView("notes");setMemoView("notebook");setActiveNotebookId(memo.notebookId);- setSelectedMemoId(null);- setRichEditingMemo(memo);+ setSelectedMemoId(memo.id);+ if (!memo.id.startsWith("local:")) {+ setRichEditingMemo(memo);+ }}}+ onQueued={async () => {+ setSyncQueueSummary(await loadMobileSyncQueueSummary(syncQueueScope));+ setSyncQueueMessage("已保存到本地,正在后台同步");+ void runAutomaticSync();+ }}+ syncQueueScope={syncQueueScope}visible/> : null}@@ -2021,18 +2106,23 @@ const SettingsView = ({const CreateMemoModal = ({activeNotebookId,+ dataScope,notebooks,onClose,onCreated,+ onQueued,+ syncQueueScope,visible,}: {activeNotebookId: string;+ dataScope: string;notebooks: Notebook[];onClose: () => void;onCreated: (memo: MemoDetail) => void;+ onQueued: () => void | Promise<void>;+ syncQueueScope: string;visible: boolean;}) => {- const { client } = useSession();const queryClient = useQueryClient();const fallbackNotebookId = activeNotebookId !== ALL_NOTES_ID ? activeNotebookId : notebooks[0]?.id ?? "";const [notebookId, setNotebookId] = useState(fallbackNotebookId);@@ -2051,22 +2141,45 @@ const CreateMemoModal = ({const createMutation = useMutation({mutationFn: async () => {- if (!client) {- throw new Error("Client is not ready");- }-if (!targetNotebookId) {throw new Error("请先创建一个笔记本");}-- const response = await client.createMemo({+ const now = new Date().toISOString();+ const temporaryId = `local:${Date.now().toString(36)}:${Math.random().toString(36).slice(2, 10)}`;+ const markdown = contentMarkdown.trim();+ const contentJson = markdownToDoc(markdown);+ const contentText = docToText(contentJson);+ const memo: MemoDetail = {+ id: temporaryId,notebookId: targetNotebookId,title: title.trim() || DEFAULT_MEMO_TITLE,+ excerpt: createExcerpt(contentText),tags: parseTags(tagsText),- contentMarkdown: contentMarkdown.trim(),+ isPinned: false,+ isArchived: false,+ isDeleted: false,+ revision: 0,+ createdAt: now,+ updatedAt: now,+ deletedAt: null,+ contentJson,+ contentMarkdown: markdown,+ contentText,+ contentHash: `local:${temporaryId}`,+ sourceMemoIds: [],+ mergeSourceCount: 0,+ mergedIntoMemoId: null,+ };+ await upsertLocalMemo(dataScope, memo);+ await queueMobileMemoCreate(syncQueueScope, {+ memoId: temporaryId,+ notebookId: memo.notebookId,+ title: memo.title ?? DEFAULT_MEMO_TITLE,+ contentMarkdown: memo.contentMarkdown,+ tags: memo.tags,+ createdAt: now,});-- return response.memo;+ return memo;},onSuccess: async (memo) => {await Promise.all([@@ -2076,6 +2189,7 @@ const CreateMemoModal = ({setTitle("");setTagsText("");setContentMarkdown("");+ await onQueued();onCreated(memo);},});@@ -5654,7 +5768,7 @@ const applyOptimisticMemoToCache = (queryClient: QueryClient, previousMemo: Memofor (const query of detailQueries) {const data = query.state.data as { memo?: MemoDetail } | undefined;- if (data?.memo?.id === nextMemo.id) {+ if (data?.memo?.id === nextMemo.id || data?.memo?.id === previousMemo.id) {queryClient.setQueryData(query.queryKey, { ...data, memo: nextMemo });}}@@ -5669,7 +5783,7 @@ const applyOptimisticMemoToCache = (queryClient: QueryClient, previousMemo: Memoconst previouslyMatched = memoMatchesListQuery(previousMemo, query.queryKey);const nextMatches = memoMatchesListQuery(nextMemo, query.queryKey);- const withoutMemo = data.memos.filter((memo) => memo.id !== nextMemo.id);+ const withoutMemo = data.memos.filter((memo) => memo.id !== nextMemo.id && memo.id !== previousMemo.id);const memos = nextMatches ? sortMemoSummaries([nextMemo, ...withoutMemo], query.queryKey[5]).slice(0, 50) : withoutMemo;const totalCount = Math.max(0, (data.totalCount ?? data.memos.length) + (nextMatches ? 1 : 0) - (previouslyMatched ? 1 : 0));@@ -5679,10 +5793,10 @@ const applyOptimisticMemoToCache = (queryClient: QueryClient, previousMemo: Memoconst searchQueries = queryClient.getQueryCache().findAll({ queryKey: ["mobile", "search"] });for (const query of searchQueries) {const data = query.state.data as { memos?: MemoSummary[] } | undefined;- if (data?.memos?.some((memo) => memo.id === nextMemo.id)) {+ if (data?.memos?.some((memo) => memo.id === nextMemo.id || memo.id === previousMemo.id)) {queryClient.setQueryData(query.queryKey, {...data,- memos: data.memos.map((memo) => (memo.id === nextMemo.id ? nextMemo : memo)),+ memos: data.memos.map((memo) => (memo.id === nextMemo.id || memo.id === previousMemo.id ? nextMemo : memo)),});}}diff --git a/bun.lock b/bun.lockindex de0d387b..efad52d9 100644--- a/bun.lock+++ b/bun.lock@@ -98,6 +98,7 @@"expo-router": "latest","expo-secure-store": "latest","expo-splash-screen": "^57.0.4",+ "expo-sqlite": "~57.0.1","expo-status-bar": "latest","react": "19.2.3","react-native": "latest",@@ -1262,6 +1263,8 @@"available-typed-arrays": ["[email protected]", "", { "dependencies": { "possible-typed-array-names": "^1.0.0" } }, "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ=="],+ "await-lock": ["[email protected]", "", {}, "sha512-aDczADvlvTGajTDjcjpJMqRkOF6Qdz3YbPZm/PyW6tKPkx2hlYBzxMhEywM/tU72HrVZjgl5VCdRuMlA7pZ8Gw=="],+"axobject-query": ["[email protected]", "", {}, "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ=="],"babel-plugin-polyfill-corejs2": ["[email protected]", "", { "dependencies": { "@babel/compat-data": "^7.28.6", "@babel/helper-define-polyfill-provider": "^0.6.8", "semver": "^6.3.1" }, "peerDependencies": { "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" } }, "sha512-aTyf30K/rqAsNwN76zYrdtx8obu0E4KoUME29B1xj+B3WxgvWkp943vYQ+z8Mv3lw9xHXMHpvSPOBxzAkIa94w=="],@@ -1618,6 +1621,8 @@"expo-splash-screen": ["[email protected]", "", { "dependencies": { "@expo/config-plugins": "~57.0.5", "@expo/image-utils": "^0.11.3", "xml2js": "0.6.0" }, "peerDependencies": { "expo": "*" } }, "sha512-AspaOA5VZUl8yXb/BQORrRdOs0f7F/IgmvKNdCFaUDuz4X+j/4bPkkyssARFKwC5A5IQ3g7QS/Ve1XxDiDZ38Q=="],+ "expo-sqlite": ["[email protected]", "", { "dependencies": { "await-lock": "^2.2.2" }, "peerDependencies": { "expo": "*", "react": "*", "react-native": "*" } }, "sha512-I6KoUvfGIiROTKxr5D3H+jRIGA/iEvWEtqHK4XMukAA7tVTinz/YdS8zOz6/DdG6vgrNmvF7gyOcbhLinlfxzQ=="],+"expo-status-bar": ["[email protected]", "", { "peerDependencies": { "expo": "*", "react": "*", "react-native": "*" } }, "sha512-Xwaq1gAoVRWx5dPG5VhT5RSbnI9OilhZnO5qoPBnUaBAa5VzRzfdS8q0/bsPt0jR2DKLtGuP0bQ6efMJ4RIMDg=="],"expo-symbols": ["[email protected]", "", { "dependencies": { "@expo-google-fonts/material-symbols": "^0.4.1", "sf-symbols-typescript": "^2.0.0" }, "peerDependencies": { "expo": "*", "expo-font": "*", "react": "*", "react-native": "*" } }, "sha512-8Zf+a83OywV0vf1NUtSKpNqKcULmO0GTI+zfFnGYl7SLDH9FjL5RcEZoy6CHvCgq2KDrQF21pl3r7Tb4ItPscw=="],diff --git a/migrations/0013_mobile_sync_changes.sql b/migrations/0013_mobile_sync_changes.sqlnew file mode 100644index 00000000..0c6a9f9f--- /dev/null+++ b/migrations/0013_mobile_sync_changes.sql@@ -0,0 +1,55 @@+PRAGMA foreign_keys = ON;++CREATE TABLE mobile_sync_changes (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ workspace_id TEXT NOT NULL,+ entity_type TEXT NOT NULL CHECK (entity_type IN ('notebook', 'memo')),+ entity_id TEXT NOT NULL,+ operation TEXT NOT NULL CHECK (operation IN ('upsert', 'delete')),+ changed_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))+);++CREATE INDEX idx_mobile_sync_changes_workspace_cursor+ ON mobile_sync_changes(workspace_id, id);++CREATE TRIGGER trg_mobile_sync_notebooks_insert+AFTER INSERT ON notebooks+BEGIN+ INSERT INTO mobile_sync_changes (workspace_id, entity_type, entity_id, operation)+ VALUES (NEW.workspace_id, 'notebook', NEW.id, 'upsert');+END;++CREATE TRIGGER trg_mobile_sync_notebooks_update+AFTER UPDATE ON notebooks+BEGIN+ INSERT INTO mobile_sync_changes (workspace_id, entity_type, entity_id, operation)+ VALUES (NEW.workspace_id, 'notebook', NEW.id, CASE WHEN NEW.is_deleted = 1 THEN 'delete' ELSE 'upsert' END);+END;++CREATE TRIGGER trg_mobile_sync_notebooks_delete+AFTER DELETE ON notebooks+BEGIN+ INSERT INTO mobile_sync_changes (workspace_id, entity_type, entity_id, operation)+ VALUES (OLD.workspace_id, 'notebook', OLD.id, 'delete');+END;++CREATE TRIGGER trg_mobile_sync_memos_insert+AFTER INSERT ON memos+BEGIN+ INSERT INTO mobile_sync_changes (workspace_id, entity_type, entity_id, operation)+ VALUES (NEW.workspace_id, 'memo', NEW.id, 'upsert');+END;++CREATE TRIGGER trg_mobile_sync_memos_update+AFTER UPDATE ON memos+BEGIN+ INSERT INTO mobile_sync_changes (workspace_id, entity_type, entity_id, operation)+ VALUES (NEW.workspace_id, 'memo', NEW.id, 'upsert');+END;++CREATE TRIGGER trg_mobile_sync_memos_delete+AFTER DELETE ON memos+BEGIN+ INSERT INTO mobile_sync_changes (workspace_id, entity_type, entity_id, operation)+ VALUES (OLD.workspace_id, 'memo', OLD.id, 'delete');+END;diff --git a/packages/client/src/index.ts b/packages/client/src/index.tsindex 41964939..ba2f8817 100644--- a/packages/client/src/index.ts+++ b/packages/client/src/index.ts@@ -87,6 +87,29 @@ export type JsonBackupPage = MarkdownExportPage & {revisions: JsonBackupRevision[];};+export type MobileSyncBootstrapPage = {+ notebooks: Notebook[];+ memos: MemoDetail[];+ snapshotCursor: number;+ totalCount: number;+ nextAfterId: string | null;+};++export type MobileSyncChange = {+ cursor: number;+ entityType: "notebook" | "memo";+ entityId: string;+ operation: "upsert" | "delete";+ notebook: Notebook | null;+ memo: MemoDetail | null;+};++export type MobileSyncChangesPage = {+ changes: MobileSyncChange[];+ cursor: number;+ hasMore: boolean;+};+export class ApiRequestError extends Error {status: number;code?: string;@@ -175,6 +198,17 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {listNotebooks: () => request<ListNotebooksResponse>("/api/v1/notebooks"),+ getMobileSyncBootstrapPage: (afterId: string | null = null, limit = 100) => {+ const search = new URLSearchParams({ limit: String(limit) });+ if (afterId) {+ search.set("afterId", afterId);+ }+ return request<MobileSyncBootstrapPage>(`/api/v1/sync/bootstrap?${search.toString()}`);+ },++ getMobileSyncChanges: (cursor: number, limit = 100) =>+ request<MobileSyncChangesPage>(`/api/v1/sync/changes?cursor=${cursor}&limit=${limit}`),+createNotebook: (payload: { name: string; parentId?: string | null }) =>request<NotebookResponse>("/api/v1/notebooks", {method: "POST",