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
refactor: decompose core runtime modules
tianma-if4eda31ca3075
diff --git a/apps/api/src/api-context.ts b/apps/api/src/api-context.tsindex 07116726..4410f2ff 100644--- a/apps/api/src/api-context.ts+++ b/apps/api/src/api-context.ts@@ -1,7 +1,8 @@import type { Context } from "hono";-import type { CloudflareStorageBindings, StorageAdapter } from "./storage-contract";+import type { CloudflareStorageBindings } from "./cloudflare-storage-adapter";+import type { StorageAdapter } from "./storage-contract";-export type Bindings = CloudflareStorageBindings & {+export type Bindings = {/** The only persistence dependency exposed to application code. */storage: StorageAdapter;EDGE_EVER_AUTH_USERNAME?: string;@@ -22,7 +23,7 @@ export type Bindings = CloudflareStorageBindings & {EDGE_EVER_ALLOW_UNAUTHENTICATED?: string;};-export type WorkerBindings = Omit<Bindings, "storage">;+export type WorkerBindings = Omit<Bindings, "storage"> & CloudflareStorageBindings;export type AuthContext = {kind: "user" | "agent";diff --git a/apps/api/src/auth-service.ts b/apps/api/src/auth-service.tsnew file mode 100644index 00000000..1ea8f08c--- /dev/null+++ b/apps/api/src/auth-service.ts@@ -0,0 +1,375 @@+import type { Context } from "hono";+import { getCookie, setCookie } from "hono/cookie";+import { hasBootstrapCredential, isSupportedPasswordHash, verifyBootstrapPassword } from "./auth-bootstrap";+import { hashPassword, randomToken, SESSION_TOKEN_BYTES, verifyPassword } from "./auth-crypto";+import type { LoginAttemptKey } from "./auth-login-limiter";+import { resolveSessionDeviceId } from "./auth-session-devices";+import {+ isDatabaseNotReadyError,+ isUnauthenticatedAccessEnabled,+ resolveInstanceAuthMode,+ type InstanceAuthMode,+} from "./auth-state";+import type { ApiTokenRow } from "./api-token-routes";+import type { AppContext, AuthContext, Bindings } from "./api-context";+import { AppError } from "./app-error";+import type { UserRow } from "./auth-routes";+import { createId, isoNow, parseJsonArray } from "./entity-utils";+import { sha256 } from "./hash-utils";+import { apiError } from "./http-errors";+import type { DatabaseAdapter } from "./storage-contract";+import type { InstanceUserRow } from "./user-routes";+import { ensureUserWorkspace } from "./workspace-provisioning";++type SessionRow = {+ id: string;+ user_id: string;+ username: string;+ display_name: string | null;+ expires_at: string;+ last_seen_at: string | null;+ workspace_id: string | null;+ role: "owner" | "member" | null;+};++const SESSION_COOKIE = "edgeever_session";+const DEFAULT_SESSION_TTL_DAYS = 400;+const MAX_SESSION_TTL_DAYS = 400;+const SESSION_LAST_SEEN_UPDATE_INTERVAL_MS = 60 * 60 * 1000;+const API_TOKEN_LAST_USED_UPDATE_INTERVAL_MS = 60 * 60 * 1000;+const clampNumber = (value: number, min: number, max: number) =>+ Number.isNaN(value) ? min : Math.min(Math.max(value, min), max);++export const getInstanceAuthMode = async (+ env: Bindings,+ verifyDatabase = false,+): Promise<InstanceAuthMode> => {+ if (!env.storage.db || typeof env.storage.db.prepare !== "function") {+ throw new AppError(+ "database_not_ready",+ "Database is not ready. Bind the D1 database as DB and apply the remote migrations.",+ 503,+ );+ }++ const allowUnauthenticated = isUnauthenticatedAccessEnabled(env.EDGE_EVER_ALLOW_UNAUTHENTICATED);+ const bootstrapCredentialConfigured = hasBootstrapCredential(+ env.EDGE_EVER_AUTH_PASSWORD,+ env.EDGE_EVER_AUTH_PASSWORD_HASH,+ );++ if (!verifyDatabase) {+ if (allowUnauthenticated) return "disabled";+ if (bootstrapCredentialConfigured) return "required";+ }++ let user: { id: string } | null;+ try {+ user = await env.storage.db.prepare(`SELECT id FROM users WHERE is_disabled = 0 LIMIT 1`).first<{ id: string }>();+ } catch (error) {+ if (isDatabaseNotReadyError(error)) {+ throw new AppError(+ "database_not_ready",+ "Database is not ready. Bind the D1 database as DB and apply the remote migrations.",+ 503,+ );+ }+ throw error;+ }++ return resolveInstanceAuthMode({+ allowUnauthenticated,+ hasBootstrapCredential: bootstrapCredentialConfigured,+ hasEnabledUser: Boolean(user),+ });+};++export const getLoginAttemptKeys = async (c: AppContext, username: string): Promise<LoginAttemptKey[]> => {+ const keys: LoginAttemptKey[] = [{ scope: "username", key: await sha256(username.trim()) }];+ const clientIp = getClientIp(c);++ if (clientIp) {+ keys.push({ scope: "ip", key: await sha256(clientIp) });+ }++ return keys;+};++const getClientIp = (c: Context) => {+ const cloudflareIp = c.req.header("CF-Connecting-IP")?.trim();+ if (cloudflareIp) return cloudflareIp;++ const realIp = c.req.header("X-Real-IP")?.trim();+ if (realIp) return realIp;++ const forwardedIp = c.req.header("X-Forwarded-For")?.split(",", 1)[0]?.trim();+ return forwardedIp || null;+};++export const tooManyLoginAttempts = (c: Context, retryAfterSeconds: number) => {+ c.header("Retry-After", String(retryAfterSeconds));+ return apiError(c, "login_rate_limited", "Too many login attempts. Try again later.", 429);+};++export const verifyLogin = async (env: Bindings, username: string, password: string): Promise<UserRow | null> => {+ const normalizedUsername = username.trim();+ const existingUser = await getUserByUsername(env.storage.db, normalizedUsername);++ if (existingUser) {+ if (await verifyPassword(password, existingUser.password_hash)) {+ return existingUser;+ }++ if (!isSupportedPasswordHash(existingUser.password_hash)) {+ throw new AppError(+ "password_hash_invalid",+ "This account has an invalid password hash. Reset it with the EdgeEver password reset command.",+ 503,+ );+ }++ return null;+ }++ const configuredHash = env.EDGE_EVER_AUTH_PASSWORD_HASH?.trim();+ const configuredPassword = env.EDGE_EVER_AUTH_PASSWORD;++ if (!configuredHash && !configuredPassword) {+ return null;+ }++ const configuredUsername = env.EDGE_EVER_AUTH_USERNAME?.trim() || "admin";++ if (normalizedUsername !== configuredUsername) {+ return null;+ }++ const passwordMatches = await verifyBootstrapPassword(+ password,+ configuredPassword,+ configuredHash,+ verifyPassword,+ );++ if (!passwordMatches) {+ return null;+ }++ const now = isoNow();+ const userId = createId("usr");+ const passwordHash = await hashPassword(password);++ await env.storage.db.prepare(+ `INSERT OR IGNORE INTO users (id, username, password_hash, display_name, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?)`+ )+ .bind(userId, normalizedUsername, passwordHash, normalizedUsername, now, now)+ .run();++ return getUserByUsername(env.storage.db, normalizedUsername);+};++const getUserByUsername = async (db: DatabaseAdapter, username: string) =>+ db+ .prepare(+ `SELECT id, username, password_hash, display_name, is_disabled+ FROM users+ WHERE username = ? AND is_disabled = 0`+ )+ .bind(username)+ .first<UserRow>();++export const getInstanceUser = (db: DatabaseAdapter, userId: string) =>+ db.prepare(+ `SELECT u.id, u.username, u.password_hash, u.display_name, u.is_disabled,+ u.last_login_at, u.created_at, wm.role+ FROM users u+ INNER JOIN workspace_members wm ON wm.user_id = u.id+ WHERE u.id = ?`+ ).bind(userId).first<InstanceUserRow>();++export const createSession = async (c: AppContext, user: UserRow, requestedDeviceId?: string) => {+ const token = randomToken(SESSION_TOKEN_BYTES);+ const id = createId("sess");+ const now = isoNow();+ const maxAge = getSessionMaxAge(c.env);+ const expiresAt = new Date(Date.now() + maxAge * 1000).toISOString();+ const userAgent = c.req.header("User-Agent") ?? null;+ const deviceId = resolveSessionDeviceId(requestedDeviceId, userAgent, id);+ const ip = c.req.header("CF-Connecting-IP");+ const ipHash = ip ? await sha256(ip) : null;+ const cf = c.req.raw.cf as { country?: string; region?: string } | undefined;+ const ipCountry = c.req.header("CF-IPCountry") ?? cf?.country ?? null;+ const ipRegion = cf?.region ?? null;++ await c.env.storage.db.batch([+ c.env.storage.db.prepare(+ `UPDATE sessions SET revoked_at = ?+ WHERE user_id = ? AND device_id = ? AND revoked_at IS NULL`+ ).bind(now, user.id, deviceId),+ c.env.storage.db.prepare(+ `INSERT INTO sessions (+ id, user_id, token_hash, device_id, user_agent, ip_hash, device_label, ip_address, ip_country, ip_region, expires_at, created_at, last_seen_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`+ ).bind(id, user.id, await sha256(token), deviceId, userAgent, ipHash, null, ip ?? null, ipCountry, ipRegion, expiresAt, now, now),+ ]);++ return { id, token, maxAge };+};++export const setSessionCookie = (c: AppContext, token: string, maxAge: number) => {+ setCookie(c, SESSION_COOKIE, token, {+ httpOnly: true,+ secure: new URL(c.req.url).protocol === "https:",+ sameSite: "Lax",+ path: "/",+ maxAge,+ });+};++export const revokeSession = async (db: DatabaseAdapter, token: string) => {+ await db+ .prepare(`UPDATE sessions SET revoked_at = ? WHERE token_hash = ? AND revoked_at IS NULL`)+ .bind(isoNow(), await sha256(token))+ .run();+};++export const authenticateRequest = async (c: AppContext, touch: boolean): Promise<AuthContext | null> => {+ const bearerAuth = await authenticateBearerToken(c, touch);++ if (bearerAuth) {+ return bearerAuth;+ }++ return authenticateSession(c, touch);+};++const authenticateBearerToken = async (c: AppContext, touch: boolean): Promise<AuthContext | null> => {+ const token = getBearerToken(c);++ if (!token) {+ return null;+ }++ const sessionAuth = await authenticateSessionToken(c, token, touch);++ if (sessionAuth) {+ return sessionAuth;+ }++ const row = await c.env.storage.db.prepare(+ `SELECT id, name, token_value, scopes_json, last_used_at, expires_at, is_revoked, created_at, workspace_id+ FROM api_tokens+ WHERE token_hash = ?+ AND is_revoked = 0+ AND (expires_at IS NULL OR expires_at > ?)`+ )+ .bind(await sha256(token), isoNow())+ .first<ApiTokenRow>();++ if (!row) {+ return null;+ }++ const lastUsedAt = row.last_used_at ? Date.parse(row.last_used_at) : Number.NaN;+ if (+ touch+ && (!Number.isFinite(lastUsedAt) || lastUsedAt <= Date.now() - API_TOKEN_LAST_USED_UPDATE_INTERVAL_MS)+ ) {+ const now = isoNow();+ const cutoff = new Date(Date.now() - API_TOKEN_LAST_USED_UPDATE_INTERVAL_MS).toISOString();+ await c.env.storage.db.prepare(+ `UPDATE api_tokens+ SET last_used_at = ?+ WHERE id = ? AND (last_used_at IS NULL OR last_used_at <= ?)`,+ ).bind(now, row.id, cutoff).run();+ }++ return {+ kind: "agent",+ actorType: "agent",+ actorId: row.id,+ username: row.name,+ displayName: row.name,+ scopes: parseJsonArray(row.scopes_json),+ workspaceId: row.workspace_id,+ role: "member",+ tokenId: row.id,+ };+};++const authenticateSessionToken = async (c: AppContext, token: string, touch: boolean): Promise<AuthContext | null> => {+ const now = isoNow();+ const row = await c.env.storage.db.prepare(+ `SELECT s.id, s.user_id, u.username, u.display_name, s.expires_at, s.last_seen_at,+ wm.workspace_id, wm.role+ FROM sessions s+ INNER JOIN users u ON u.id = s.user_id+ LEFT JOIN workspace_members wm ON wm.user_id = s.user_id+ WHERE s.token_hash = ?+ AND s.revoked_at IS NULL+ AND s.expires_at > ?+ AND u.is_disabled = 0`+ )+ .bind(await sha256(token), now)+ .first<SessionRow>();++ if (!row) {+ return null;+ }++ const lastSeenAt = row.last_seen_at ? Date.parse(row.last_seen_at) : Number.NaN;+ if (+ touch+ && (!Number.isFinite(lastSeenAt) || lastSeenAt <= Date.now() - SESSION_LAST_SEEN_UPDATE_INTERVAL_MS)+ ) {+ const cutoff = new Date(Date.now() - SESSION_LAST_SEEN_UPDATE_INTERVAL_MS).toISOString();+ await c.env.storage.db.prepare(+ `UPDATE sessions+ SET last_seen_at = ?+ WHERE id = ? AND (last_seen_at IS NULL OR last_seen_at <= ?)`,+ ).bind(now, row.id, cutoff).run();+ }++ const workspace = row.workspace_id && row.role+ ? { workspaceId: row.workspace_id, role: row.role }+ : await ensureUserWorkspace(c.env.storage.db, row.user_id, row.username, c.req.header("accept-language"));++ return {+ kind: "user",+ actorType: "user",+ actorId: row.user_id,+ username: row.username,+ displayName: row.display_name,+ scopes: [],+ workspaceId: workspace.workspaceId,+ role: workspace.role,+ sessionId: row.id,+ };+};++export const authenticateSession = async (c: AppContext, touch: boolean): Promise<AuthContext | null> => {+ const token = getCookie(c, SESSION_COOKIE);++ if (!token) {+ return null;+ }++ return authenticateSessionToken(c, token, touch);+};++export const getBearerToken = (c: AppContext) => {+ const authorization = c.req.header("Authorization");++ if (!authorization) {+ return null;+ }++ const [scheme, token] = authorization.split(/\s+/, 2);+ return scheme.toLowerCase() === "bearer" && token ? token : null;+};++const getSessionMaxAge = (env: Bindings) => {+ const days = clampNumber(Number(env.EDGE_EVER_SESSION_TTL_DAYS ?? DEFAULT_SESSION_TTL_DAYS), 1, MAX_SESSION_TTL_DAYS);+ return days * 24 * 60 * 60;+};diff --git a/apps/api/src/backup-service.ts b/apps/api/src/backup-service.tsnew file mode 100644index 00000000..7cdaa57d--- /dev/null+++ b/apps/api/src/backup-service.ts@@ -0,0 +1,228 @@+import {+ createExcerpt,+ DEFAULT_MEMO_TITLE,+ docToMarkdown,+ docToText,+ emptyDoc,+ normalizeTags,+ type JsonBackupMemo,+ type JsonBackupNotebook,+ type TiptapDoc,+} from "@edgeever/shared";+import { AppError } from "./app-error";+import { audit } from "./audit";+import { createId } from "./entity-utils";+import { sha256 } from "./hash-utils";+import { upsertMemoSearchDocumentStatement } from "./memo-search-index";+import type { DatabaseAdapter } from "./storage-contract";++const parseBackupDoc = (value: unknown): TiptapDoc => {+ try {+ const parsed = JSON.parse(JSON.stringify(value));+ return parsed && typeof parsed === "object" ? parsed as TiptapDoc : emptyDoc();+ } catch {+ return emptyDoc();+ }+};++const normalizeMemoTitle = (value: string | null | undefined) => {+ const title = value?.trim();+ return title || DEFAULT_MEMO_TITLE;+};++const assertIdsAvailableInWorkspace = async (+ db: DatabaseAdapter,+ table: "notebooks" | "memos",+ workspaceId: string,+ ids: string[],+) => {+ if (ids.length === 0) return;+ const placeholders = ids.map(() => "?").join(", ");+ const collision = await db.prepare(+ `SELECT id FROM ${table} WHERE workspace_id <> ? AND id IN (${placeholders}) LIMIT 1`,+ ).bind(workspaceId, ...ids).first<{ id: string }>();+ if (collision) {+ throw new AppError("cross_workspace_id_conflict", "Backup contains an ID already used by another user.", 409);+ }+};++const assertNotebookIdsInWorkspace = async (+ db: DatabaseAdapter,+ workspaceId: string,+ ids: string[],+) => {+ const uniqueIds = Array.from(new Set(ids));+ if (uniqueIds.length === 0) return;+ const placeholders = uniqueIds.map(() => "?").join(", ");+ const rows = await db.prepare(+ `SELECT id FROM notebooks WHERE workspace_id = ? AND id IN (${placeholders})`,+ ).bind(workspaceId, ...uniqueIds).all<{ id: string }>();+ if (rows.results.length !== uniqueIds.length) {+ throw new AppError("invalid_backup_workspace", "Backup references a notebook outside the current workspace.", 400);+ }+};++export const restoreJsonNotebooks = async (+ db: DatabaseAdapter,+ workspaceId: string,+ notebooks: JsonBackupNotebook[],+) => {+ await assertIdsAvailableInWorkspace(db, "notebooks", workspaceId, notebooks.map((notebook) => notebook.id));+ const importedIds = new Set(notebooks.map((notebook) => notebook.id));+ const externalParentIds = notebooks+ .map((notebook) => notebook.parentId)+ .filter((id): id is string => Boolean(id) && !importedIds.has(id as string));+ await assertNotebookIdsInWorkspace(db, workspaceId, externalParentIds);++ await db.batch(notebooks.map((notebook) => db.prepare(+ `INSERT INTO notebooks (+ id, workspace_id, parent_id, name, slug, icon, color, sort_order, is_deleted, created_at, updated_at, deleted_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, NULL)+ ON CONFLICT(id) DO UPDATE SET+ parent_id = excluded.parent_id,+ name = excluded.name,+ slug = excluded.slug,+ icon = excluded.icon,+ color = excluded.color,+ sort_order = excluded.sort_order,+ is_deleted = 0,+ updated_at = excluded.updated_at,+ deleted_at = NULL`,+ ).bind(+ notebook.id,+ workspaceId,+ notebook.parentId,+ notebook.name,+ notebook.slug,+ notebook.icon,+ notebook.color,+ notebook.sortOrder,+ notebook.createdAt,+ notebook.updatedAt,+ )));+};++export const restoreJsonMemos = async (+ db: DatabaseAdapter,+ workspaceId: string,+ backups: JsonBackupMemo[],+) => {+ await assertIdsAvailableInWorkspace(db, "memos", workspaceId, backups.map((backup) => backup.memo.id));+ await assertNotebookIdsInWorkspace(db, workspaceId, backups.map((backup) => backup.memo.notebookId));++ for (const backup of backups) {+ const memo = backup.memo;+ const contentJson = parseBackupDoc(memo.contentJson);+ const contentMarkdown = memo.contentMarkdown || docToMarkdown(contentJson);+ const contentText = docToText(contentJson);+ const contentHash = await sha256(contentMarkdown + JSON.stringify(contentJson));+ const title = normalizeMemoTitle(memo.title);+ const tags = normalizeTags(memo.tags);++ if (backup.revisions.some((revision) => revision.memoId !== memo.id)) {+ throw new AppError("invalid_backup", "A backup revision belongs to a different memo.", 400);+ }++ await db.batch([+ db.prepare(+ `INSERT INTO memos (+ id, workspace_id, notebook_id, title, excerpt, tags_json, is_pinned, is_archived, is_deleted,+ source_memo_ids, merge_source_count, merged_into_memo_id,+ created_by, updated_by, created_at, updated_at, deleted_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, NULL, 'restore', 'restore', ?, ?, NULL)+ ON CONFLICT(id) DO UPDATE SET+ notebook_id = excluded.notebook_id,+ title = excluded.title,+ excerpt = excluded.excerpt,+ tags_json = excluded.tags_json,+ is_pinned = excluded.is_pinned,+ is_archived = excluded.is_archived,+ is_deleted = 0,+ source_memo_ids = excluded.source_memo_ids,+ merge_source_count = excluded.merge_source_count,+ merged_into_memo_id = NULL,+ updated_by = 'restore',+ updated_at = excluded.updated_at,+ deleted_at = NULL`,+ ).bind(+ memo.id,+ workspaceId,+ memo.notebookId,+ title,+ createExcerpt(contentText),+ JSON.stringify(tags),+ memo.isPinned ? 1 : 0,+ memo.isArchived ? 1 : 0,+ JSON.stringify(memo.sourceMemoIds),+ memo.mergeSourceCount,+ memo.createdAt,+ memo.updatedAt,+ ),+ db.prepare(+ `INSERT INTO memo_contents (+ memo_id, content_json, content_markdown, content_text, content_hash, revision, created_at, updated_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT(memo_id) DO UPDATE SET+ content_json = excluded.content_json,+ content_markdown = excluded.content_markdown,+ content_text = excluded.content_text,+ content_hash = excluded.content_hash,+ revision = excluded.revision,+ updated_at = excluded.updated_at`,+ ).bind(+ memo.id,+ JSON.stringify(contentJson),+ contentMarkdown,+ contentText,+ contentHash,+ memo.revision,+ memo.createdAt,+ memo.updatedAt,+ ),+ upsertMemoSearchDocumentStatement(db, memo.id, title, contentText, tags.join(" ")),+ db.prepare("DELETE FROM memo_revisions WHERE memo_id = ?").bind(memo.id),+ ]);++ for (let index = 0; index < backup.revisions.length; index += 50) {+ const statements = backup.revisions.slice(index, index + 50).map((revision) => {+ const revisionJson = parseBackupDoc(revision.contentJson);+ const revisionMarkdown = revision.contentMarkdown || docToMarkdown(revisionJson);+ const revisionText = docToText(revisionJson);+ return db.prepare(+ `INSERT INTO memo_revisions (+ id, memo_id, revision, title, content_json, content_markdown,+ content_hash, created_by, created_at, tags_json, content_text+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT(id) DO UPDATE SET+ memo_id = excluded.memo_id,+ revision = excluded.revision,+ title = excluded.title,+ content_json = excluded.content_json,+ content_markdown = excluded.content_markdown,+ content_hash = excluded.content_hash,+ created_by = excluded.created_by,+ created_at = excluded.created_at,+ tags_json = excluded.tags_json,+ content_text = excluded.content_text`,+ ).bind(+ revision.id,+ memo.id,+ revision.revision,+ normalizeMemoTitle(revision.title),+ JSON.stringify(revisionJson),+ revisionMarkdown,+ revision.contentHash || "",+ revision.createdBy,+ revision.createdAt,+ JSON.stringify(normalizeTags(revision.tags)),+ revisionText,+ );+ });+ await db.batch(statements);+ }+ }++ await audit(db, "user", null, "backup.restore", "backup", createId("restore"), {+ memoCount: backups.length,+ });+};diff --git a/apps/api/src/cloudflare-storage-adapter.ts b/apps/api/src/cloudflare-storage-adapter.tsindex 9739fc39..a5e81504 100644--- a/apps/api/src/cloudflare-storage-adapter.ts+++ b/apps/api/src/cloudflare-storage-adapter.ts@@ -1,8 +1,15 @@import type {- CloudflareStorageBindings,+ BlobStoreAdapter,+ DatabaseAdapter,StorageAdapter,} from "./storage-contract";+/** Native Worker bindings are mentioned only at this platform boundary. */+export type CloudflareStorageBindings = {+ DB: DatabaseAdapter;+ RESOURCES: BlobStoreAdapter;+};+/*** Adapts native Cloudflare bindings to the storage surface consumed by the* application. No route or service should construct this shape directly.diff --git a/apps/api/src/hash-utils.ts b/apps/api/src/hash-utils.tsnew file mode 100644index 00000000..f05ee6b2--- /dev/null+++ b/apps/api/src/hash-utils.ts@@ -0,0 +1,9 @@+export const sha256 = async (value: string) => {+ const bytes = new TextEncoder().encode(value);+ return sha256Bytes(bytes);+};++export const sha256Bytes = async (bytes: Uint8Array) => {+ const digest = await crypto.subtle.digest("SHA-256", bytes.slice());+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");+};diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex 536d7f58..ab57c735 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -1,54 +1,34 @@import {createExcerpt,- DEFAULT_MEMO_TITLE,- docToMarkdown,docToText,- emptyDoc,markdownToDoc,- mergeMemoDocs,- resolveMemoContentDoc,- resolveMergedMemoTitle,- isSuspiciousMemoOverwrite,- isMemoEditBindingValid,normalizeTags,- AiPromptTemplateCreateSchema,- AiPromptTemplateUpdateSchema,- TemplateCreateSchema,- TemplateUpdateSchema,- type MemoDetail,- type MemoEditSession,- type MemoRevision,- type MemoSummary,- type MemoUpdateInput,- type JsonBackupMemo,- type JsonBackupNotebook,- type Resource,- type TiptapDoc,} from "@edgeever/shared";-import type { Context } from "hono";import { Hono } from "hono";-import { getCookie, setCookie } from "hono/cookie";import { cors } from "hono/cors";import openApiSpec from "../../../docs/openapi.json";import releaseSummary from "../../../release-summary.json";-import { hasBootstrapCredential, isSupportedPasswordHash, verifyBootstrapPassword } from "./auth-bootstrap";+import {+ authenticateRequest,+ authenticateSession,+ createSession,+ getBearerToken,+ getInstanceAuthMode,+ getInstanceUser,+ getLoginAttemptKeys,+ revokeSession,+ setSessionCookie,+ tooManyLoginAttempts,+ verifyLogin,+} from "./auth-service";import {isDatabaseNotReadyError,- isUnauthenticatedAccessEnabled,- resolveInstanceAuthMode,- type InstanceAuthMode,} from "./auth-state";import {isDemoModeEnabled,resolveDemoPasswordHash,shouldUpsertDemoSeedRecord,} from "./demo-mode";-import {- resolveSessionDeviceId,-} from "./auth-session-devices";-import {- type LoginAttemptKey,-} from "./auth-login-limiter";import {decodeDemoAttachment,DEMO_SEED_ATTACHMENT_RESOURCES,@@ -59,120 +39,89 @@ import {DEMO_SEED_REVISIONS,} from "./demo-seed-data";import { createCloudflareStorageAdapter } from "./cloudflare-storage-adapter";+import {+ restoreJsonMemos as restoreJsonMemosService,+ restoreJsonNotebooks as restoreJsonNotebooksService,+} from "./backup-service";+import { sha256, sha256Bytes } from "./hash-utils";import { INSTANCE_BUILD_ID } from "./instance-build";import type {DatabaseAdapter,PreparedStatementAdapter,} from "./storage-contract";-import type { AppContext, AppEnv, AuditActor, AuthContext, Bindings, WorkerBindings } from "./api-context";+import type { AppContext, AppEnv, AuthContext, Bindings, WorkerBindings } from "./api-context";import { AppError } from "./app-error";-import { hashPassword, randomToken, SESSION_TOKEN_BYTES, verifyPassword } from "./auth-crypto";+import { hashPassword } from "./auth-crypto";import {apiError,authNotConfigured,databaseNotReady,- forbidden,- notFound,unauthorized,} from "./http-errors";+import { audit } from "./audit";+import { createId, isoNow } from "./entity-utils";import {- decodeBase64Data,- escapeMarkdownImageAlt,- escapeMarkdownLinkLabel,- getOptionalString,- getOptionalStringArray,- getRequiredString,- getRequiredStringArray,-} from "./mcp-json-rpc";-import { audit, auditStatement } from "./audit";-import { createId, isoNow, parseJsonArray } from "./entity-utils";-import {- deleteMemoSearchDocumentsStatement,upsertMemoSearchDocumentStatement,} from "./memo-search-index";import {- createNotebookRecord,- findNotebooks,- getNotebook,- listNotebooks,- mapNotebook,- notebookSelectSql,- resolveNotebookPath,- updateNotebookRecord,- type NotebookRow,-} from "./notebook-service";-import {- listTagSummaries,- previewTagRename,- updateTagAcrossMemos,- updateTagsForMemos,-} from "./tag-service";-import {- assertScope,- getActorLabel,- getAuditActor,- getWorkspaceId,- hasScopes,- requireOwner,- requireScopes,- requireUser,- type TokenScope,-} from "./request-auth";+ listMemoRevisions as listMemoRevisionsService,+ restoreMemoRevision as restoreMemoRevisionService,+} from "./memo-revision-service";import { registerTagRoutes } from "./tag-routes";-import { getMemoTemplate, listMemoTemplates, registerTemplateRoutes } from "./template-routes";-import { registerAuthRoutes, type UserRow } from "./auth-routes";-import { registerApiTokenRoutes, type ApiTokenRow } from "./api-token-routes";+import { registerTemplateRoutes } from "./template-routes";+import { registerAuthRoutes } from "./auth-routes";+import { registerApiTokenRoutes } from "./api-token-routes";import { registerObjectStorageRoutes } from "./object-storage-routes";import { registerAiRoutes } from "./ai-routes";import { registerAiPromptRoutes } from "./ai-prompt-routes";-import {- getAiPromptTemplateRow,- listAiPromptTemplates,- mapAiPromptTemplateRow,-} from "./ai-prompt-service";-import { restoreMissingDefaultAiPrompts } from "./ai-prompt-seed";import { registerResourceRoutes } from "./resource-routes";import { registerPluginDistributionRoutes } from "./plugin-distribution-routes";import { registerSyncRoutes } from "./sync-routes";import { registerMemoRoutes } from "./memo-routes";import { registerBackupRoutes } from "./backup-routes";import { registerMcpRoutes } from "./mcp-routes";+import { callMcpTool as callMcpToolService } from "./mcp-tool-service";import {- escapeLike,- listMemos,- mapMemoSummary,- toFtsQuery,- type MemoSummaryRow,-} from "./memo-list-service";+ createMemoEditSession,+ createMemoRecord,+ deleteMemoRecord,+ deleteMemosRecord,+ emptyTrashMemosRecord,+ getCurrentWorkspaceIdentity,+ getMemoDetail,+ getMemoDetailRow,+ getMemosForBulkAction,+ importMemosRecord,+ listMemosForMcp,+ mapMemoDetail,+ mergeMemosRecord,+ moveMemosRecord,+ moveMemosToNotebook,+ restoreMemoRecord,+ restoreMemosRecord,+ searchMemoSummaries,+ updateMemoRecord,+} from "./memo-service";++export { createMemoEditSession, mergeMemosRecord, updateMemoRecord };+import { listMemos } from "./memo-list-service";import {registerUserRoutes,- type InstanceUserRow,} from "./user-routes";import { registerNotebookRoutes } from "./notebook-routes";import { registerMemoShareRoutes, registerPublicShareRoutes } from "./share-routes";import {deleteStoredObjects,getActiveObjectStorageConfig,- resolveObjectStorage,} from "./object-storage";import {DEFAULT_WORKSPACE_ID,ensureUserWorkspace,} from "./workspace-provisioning";import {- MAX_ATTACHMENT_UPLOAD_BYTES,- MAX_IMAGE_UPLOAD_BYTES,- inferImageExtension,- mapResource,- mapResourceListItem,- mapResourceStorageSummary,- normalizeFilename,- prepareImageForStorage,- validateAttachmentUpload,- validateImageUpload,- type ResourceListRow,- type ResourceRow,- type ResourceStatsRow,+ createAttachmentResource,+ createImageResource,+ getResourceRow,} from "./resource-service";// Compatibility aliases keep the existing SQL-heavy implementation small@@ -181,76 +130,9 @@ import {type D1Database = DatabaseAdapter;type D1PreparedStatement = PreparedStatementAdapter;-type MemoDetailRow = MemoSummaryRow & {- content_json: string;- content_markdown: string;- content_text: string;- source_memo_ids: string;- merge_source_count: number;- merged_into_memo_id: string | null;- content_hash: string;-};--type MemoRevisionRow = {- id: string;- memo_id: string;- revision: number;- title: string | null;- tags_json: string;- content_json: string;- content_markdown: string;- content_text: string;- content_hash: string;- created_by: string;- created_at: string;-};--type MemoEditSessionRow = {- id: string;- memo_id: string;- actor_type: "user" | "agent";- actor_id: string | null;- base_revision: number;- base_content_hash: string;- expires_at: string;-};--type SessionRow = {- id: string;- user_id: string;- username: string;- display_name: string | null;- expires_at: string;- last_seen_at: string | null;- workspace_id: string | null;- role: "owner" | "member" | null;-};--type WorkspaceIdentityRow = {- workspace_id: string;- workspace_name: string;- is_personal: number;- user_id: string;- username: string;- display_name: string | null;- role: "owner" | "member";-};--type MemoImportSourceRow = {- external_id: string;- memo_id: string;- source_updated_at: string | null;-};--const SESSION_COOKIE = "edgeever_session";-const DEFAULT_SESSION_TTL_DAYS = 400;-const MAX_SESSION_TTL_DAYS = 400;-const SESSION_LAST_SEEN_UPDATE_INTERVAL_MS = 60 * 60 * 1000;-const API_TOKEN_LAST_USED_UPDATE_INTERVAL_MS = 60 * 60 * 1000;const DEMO_RESET_LEASE_MS = 5 * 60 * 1000;const DEMO_RESET_COOLDOWN_MS = 60 * 1000;const DEFAULT_R2_BUCKET_NAME = "edgeever-resources";-const REVISION_SNAPSHOT_INTERVAL_MS = 5 * 60 * 1000;const app = new Hono<AppEnv>();app.use(@@ -430,11 +312,11 @@ registerMemoRoutes(app, {emptyTrash: (...args) => emptyTrashMemosRecord(...args),getMemoDetail: (...args) => getMemoDetail(...args),listMemos: (...args) => listMemos(...args),- listMemoRevisions: (...args) => listMemoRevisions(...args, false),+ listMemoRevisions: (...args) => listMemoRevisionsService(...args, getMemoDetail, false),mergeMemos: (...args) => mergeMemosRecord(...args),moveMemos: (...args) => moveMemosRecord(...args),restoreMemo: (...args) => restoreMemoRecord(...args),- restoreMemoRevision: (...args) => restoreMemoRevisionRecord(...args),+ restoreMemoRevision: (...args) => restoreMemoRevisionService(...args, { getMemoDetail, getMemoDetailRow }),updateMemo: (...args) => updateMemoRecord(...args),});@@ -442,9 +324,9 @@ registerBackupRoutes(app, {clampNumber: (...args) => clampNumber(...args),getMemoDetail: (...args) => getMemoDetail(...args),mapMemoDetail: (...args) => mapMemoDetail(...args),- restoreJsonMemos: (...args) => restoreJsonMemos(...args),- restoreJsonNotebooks: (...args) => restoreJsonNotebooks(...args),- sha256Bytes: (...args) => sha256Bytes(...args),+ restoreJsonMemos: restoreJsonMemosService,+ restoreJsonNotebooks: restoreJsonNotebooksService,+ sha256Bytes,});registerMcpRoutes(app, {@@ -461,160 +343,6 @@ registerResourceRoutes(app, {getResourceRow: (...args) => getResourceRow(...args),});-const createImageResource = async (- c: AppContext,- input: {- memoId: string;- filename: string;- mimeType: string;- bytes: Uint8Array;- actor: AuditActor;- source: "upload" | "mcp";- }-) => {- validateImageUpload(input.mimeType, input.bytes.byteLength);-- const resourceId = createId("res");- const now = isoNow();- const processed = prepareImageForStorage({- bytes: input.bytes,- filename: input.filename,- mimeType: input.mimeType,- source: input.source,- });- const objectKey = `workspaces/${getWorkspaceId(c)}/memos/${input.memoId}/${resourceId}${inferImageExtension(processed.filename, processed.mimeType)}`;- const destination = await resolveObjectStorage(c.env);- const filename = normalizeFilename(processed.filename) || `${resourceId}${inferImageExtension(processed.filename, processed.mimeType)}`;- const checksum = await sha256Bytes(processed.bytes);-- await destination.store.put(objectKey, processed.bytes, {- httpMetadata: {- contentType: processed.mimeType,- cacheControl: "private, max-age=3600",- },- customMetadata: {- memoId: input.memoId,- resourceId,- filename,- },- });-- try {- await c.env.storage.db.batch([- c.env.storage.db.prepare(- `INSERT INTO resources (- id, memo_id, bucket_name, object_key, storage_config_id, kind, mime_type, filename,- byte_size, sha256, width, height, metadata_json, created_at, updated_at- ) VALUES (?, ?, ?, ?, ?, 'image', ?, ?, ?, ?, ?, ?, ?, ?, ?)`- ).bind(- resourceId,- input.memoId,- destination.bucketName,- objectKey,- destination.configId,- processed.mimeType,- filename,- processed.bytes.byteLength,- checksum,- processed.width,- processed.height,- JSON.stringify(processed.metadata),- now,- now- ),- auditStatement(c.env.storage.db, input.actor.actorType, input.actor.actorId, "resource.create", "resource", resourceId, {- memoId: input.memoId,- mimeType: processed.mimeType,- byteSize: processed.bytes.byteLength,- compressed: processed.compressed,- }),- ]);- } catch (error) {- await destination.store.delete(objectKey);- throw error;- }-- const resource = await getResourceRow(c.env.storage.db, getWorkspaceId(c), resourceId);-- if (!resource) {- throw new AppError("not_found", "Resource not found", 404);- }-- return mapResource(resource);-};--const createAttachmentResource = async (- c: AppContext,- input: {- memoId: string;- filename: string;- mimeType: string;- bytes: Uint8Array;- actor: AuditActor;- }-) => {- validateAttachmentUpload(input.bytes.byteLength);-- const resourceId = createId("res");- const now = isoNow();- const filename = normalizeFilename(input.filename) || resourceId;- const objectKey = `workspaces/${getWorkspaceId(c)}/memos/${input.memoId}/${resourceId}`;- const destination = await resolveObjectStorage(c.env);- const checksum = await sha256Bytes(input.bytes);-- await destination.store.put(objectKey, input.bytes, {- httpMetadata: {- contentType: input.mimeType,- cacheControl: "private, max-age=3600",- },- customMetadata: {- memoId: input.memoId,- resourceId,- filename,- },- });-- try {- await c.env.storage.db.batch([- c.env.storage.db.prepare(- `INSERT INTO resources (- id, memo_id, bucket_name, object_key, storage_config_id, kind, mime_type, filename,- byte_size, sha256, width, height, metadata_json, created_at, updated_at- ) VALUES (?, ?, ?, ?, ?, 'attachment', ?, ?, ?, ?, NULL, NULL, ?, ?, ?)`- ).bind(- resourceId,- input.memoId,- destination.bucketName,- objectKey,- destination.configId,- input.mimeType,- filename,- input.bytes.byteLength,- checksum,- JSON.stringify({ originalFilename: filename }),- now,- now- ),- auditStatement(c.env.storage.db, input.actor.actorType, input.actor.actorId, "resource.create", "resource", resourceId, {- memoId: input.memoId,- mimeType: input.mimeType,- byteSize: input.bytes.byteLength,- }),- ]);- } catch (error) {- await destination.store.delete(objectKey);- throw error;- }-- const resource = await getResourceRow(c.env.storage.db, getWorkspaceId(c), resourceId);-- if (!resource) {- throw new AppError("not_found", "Resource not found", 404);- }-- return mapResource(resource);-};-app.post("/api/v1/demo/reset", async (c) => {if (!isDemoMode(c.env) && !isLocalDemoSeedEnabled(c.env)) {return c.json(@@ -650,1876 +378,91 @@ app.post("/api/v1/demo/reset", async (c) => {/*** Executes the platform-neutral EdgeEver application with an injected storage- * adapter. Runtime entrypoints must remain thin and call this function rather- * than introducing platform-specific route or service implementations.- */-export const fetchEdgeEverApp = async (- request: Request,- runtimeEnv: Bindings,- ctx: ExecutionContext,-) => {- if (isLocalDemoSeedEnabled(runtimeEnv)) {- await ensureLocalDemoSeed(runtimeEnv);- }-- return app.fetch(request, runtimeEnv, ctx);-};--const worker = {- async fetch(request: Request, env: WorkerBindings, ctx: ExecutionContext) {- return fetchEdgeEverApp(request, {- ...env,- storage: createCloudflareStorageAdapter(env),- }, ctx);- },- async scheduled(controller: ScheduledController, env: WorkerBindings, ctx: ExecutionContext) {- const runtimeEnv = {- ...env,- storage: createCloudflareStorageAdapter(env),- } as Bindings;-- if (!isDemoMode(runtimeEnv)) {- return;- }-- ctx.waitUntil(resetDemoData(runtimeEnv, controller.scheduledTime, { resetCredentials: true }));- },-};--app.notFound((c) =>- c.json(- {- error: {- code: "not_found",- message: "Route not found",- },- },- 404- )-);--app.onError((error, c) => {- if (error instanceof AppError) {- return apiError(c, error.code, error.message, error.status);- }-- if (isDatabaseNotReadyError(error)) {- console.error("EdgeEver database readiness check failed", error);- return databaseNotReady(c);- }-- console.error("Unhandled EdgeEver API error", error);- return apiError(c, "internal_error", "An unexpected server error occurred.", 500);-});--export default worker;--type McpInputSchema<T> = {- safeParse: (input: unknown) =>- | { success: true; data: T }- | { success: false; error: { issues: Array<{ path: PropertyKey[]; message: string }> } };-};--const parseMcpInput = <T>(schema: McpInputSchema<T>, input: unknown): T => {- const result = schema.safeParse(input);- if (result.success) return result.data;- const message = result.error.issues- .map((issue) => `${issue.path.join(".") || "arguments"}: ${issue.message}`)- .join("; ");- throw new AppError("invalid_params", message, 400);-};--const assertMcpMutationAllowed = (environment: Bindings) => {- if (isDemoMode(environment)) {- throw new AppError("forbidden", "Templates and AI instructions cannot be changed in demo mode.", 403);- }-};--export const callMcpTool = async (- c: AppContext,- auth: AuthContext,- name: string,- args: Record<string, unknown>-) => {- switch (name) {- case "get_current_user": {- return await getCurrentWorkspaceIdentity(c.env.storage.db, auth);- }- case "search_memos": {- assertScope(auth, "read:memos");- return {- memos: await searchMemoSummaries(c.env.storage.db, {- workspaceId: auth.workspaceId,- query: getOptionalString(args.query),- notebookId: getOptionalString(args.notebookId),- tags: getOptionalStringArray(args.tags),- createdAfter: getOptionalString(args.createdAfter),- createdBefore: getOptionalString(args.createdBefore),- updatedAfter: getOptionalString(args.updatedAfter),- updatedBefore: getOptionalString(args.updatedBefore),- isPinned: typeof args.isPinned === "boolean" ? args.isPinned : null,- hasResources: typeof args.hasResources === "boolean" ? args.hasResources : null,- limit: clampNumber(Number(args.limit ?? 20), 1, 50),- }),- };- }- case "list_memos": {- assertScope(auth, "read:memos");- return await listMemosForMcp(c.env.storage.db, {- workspaceId: auth.workspaceId,- notebookId: getOptionalString(args.notebookId),- limit: clampNumber(Number(args.limit ?? 50), 1, 100),- offset: clampNumber(Number(args.offset ?? 0), 0, 100_000),- includeContent: args.includeContent === true,- includeDeleted: args.includeDeleted === true,- });- }- case "get_memo": {- assertScope(auth, "read:memos");- const memoId = getRequiredString(args.memoId, "memoId");- const memo = await getMemoDetail(c.env.storage.db, auth.workspaceId, memoId, args.includeDeleted === true);-- if (!memo) {- throw new Error("Memo not found");- }-- return { memo };- }- case "create_memo": {- assertScope(auth, "write:memos");- const notebookId = getRequiredString(args.notebookId, "notebookId");- const actor = getAuditActor(c);- const actorLabel = getActorLabel(c);- const memo = await createMemoRecord(c.env.storage.db, auth.workspaceId, {- notebookId,- title: getOptionalString(args.title) ?? undefined,- contentMarkdown: getOptionalString(args.contentMarkdown) ?? "",- tags: getOptionalStringArray(args.tags),- createdAt: getOptionalString(args.createdAt) ?? undefined,- updatedAt: getOptionalString(args.updatedAt) ?? undefined,- }, actor, actorLabel);-- return { memo };- }- case "import_memos": {- assertScope(auth, "write:memos");- return await importMemosRecord(c.env.storage.db, auth.workspaceId, {- source: getRequiredString(args.source, "source"),- notebookId: getRequiredString(args.notebookId, "notebookId"),- items: args.items,- dryRun: args.dryRun === true,- actor: getAuditActor(c),- actorLabel: getActorLabel(c),- });- }- case "update_memo": {- assertScope(auth, "write:memos");- const memoId = getRequiredString(args.memoId, "memoId");- const actor = getAuditActor(c);- const actorLabel = getActorLabel(c);- const result = await updateMemoRecord(- c.env.storage.db,- auth.workspaceId,- memoId,- {- expectedRevision:- typeof args.expectedRevision === "number" && Number.isInteger(args.expectedRevision)- ? args.expectedRevision- : undefined,- notebookId: getOptionalString(args.notebookId) ?? undefined,- title: getOptionalString(args.title) ?? undefined,- isPinned: typeof args.isPinned === "boolean" ? args.isPinned : undefined,- contentMarkdown: getOptionalString(args.contentMarkdown) ?? undefined,- tags: Array.isArray(args.tags) ? getOptionalStringArray(args.tags) : undefined,- createdAt: getOptionalString(args.createdAt) ?? undefined,- updatedAt: getOptionalString(args.updatedAt) ?? undefined,- },- actor,- actorLabel- );-- if ("error" in result) {- throw new Error(result.message);- }-- return { memo: result.memo };- }- case "trash_memos": {- assertScope(auth, "write:memos");- const memoIds = getRequiredStringArray(args.memoIds, "memoIds");-- if (args.dryRun === true) {- return { dryRun: true, memos: await getMemosForBulkAction(c.env.storage.db, auth.workspaceId, memoIds, 0) };- }-- const deleted = await deleteMemosRecord(c.env, auth.workspaceId, memoIds, false, getAuditActor(c));- return { ok: true, deleted };- }- case "restore_memos": {- assertScope(auth, "write:memos");- const memoIds = getRequiredStringArray(args.memoIds, "memoIds");-- if (args.dryRun === true) {- return { dryRun: true, memos: await getMemosForBulkAction(c.env.storage.db, auth.workspaceId, memoIds, 1) };- }-- const restored = await restoreMemosRecord(c.env.storage.db, auth.workspaceId, memoIds, getAuditActor(c));- return { ok: true, restored };- }- case "upload_memo_image": {- assertScope(auth, "write:resources");- const memoId = getRequiredString(args.memoId, "memoId");- const memo = await getMemoDetail(c.env.storage.db, auth.workspaceId, memoId);-- if (!memo) {- throw new AppError("not_found", "Memo not found", 404);- }-- const mimeType = getRequiredString(args.mimeType, "mimeType");- const filename = getOptionalString(args.filename) ?? `image${inferImageExtension("", mimeType)}`;- const bytes = await decodeBase64Data(getRequiredString(args.dataBase64, "dataBase64"));- const resource = await createImageResource(c, {- memoId,- filename,- mimeType,- bytes,- actor: getAuditActor(c),- source: "mcp",- });- const alt = getOptionalString(args.alt) ?? normalizeFilename(filename) ?? "image";-- return {- resource,- markdownImage: ``,- };- }- case "move_memos": {- assertScope(auth, "write:memos");- const notebookId = getRequiredString(args.notebookId, "notebookId");- const memoIds = getRequiredStringArray(args.memoIds, "memoIds");- const target = await getNotebook(c.env.storage.db, auth.workspaceId, notebookId);-- if (!target) {- throw new AppError("not_found", "Target notebook not found", 404);- }-- if (args.dryRun === true) {- return { dryRun: true, targetNotebook: target, memos: await getMemosForBulkAction(c.env.storage.db, auth.workspaceId, memoIds, 0) };- }-- const actor = getAuditActor(c);- const actorLabel = getActorLabel(c);- const moved = await moveMemosToNotebook(c.env.storage.db, auth.workspaceId, memoIds, notebookId, actor, actorLabel);-- return { ok: true, moved };- }- case "add_tags_to_memos": {- assertScope(auth, "write:tags");- return await updateTagsForMemos(c.env.storage.db, {- workspaceId: auth.workspaceId,- memoIds: getRequiredStringArray(args.memoIds, "memoIds"),- tags: getRequiredStringArray(args.tags, "tags"),- mode: "add",- dryRun: args.dryRun === true,- actor: getAuditActor(c),- actorLabel: getActorLabel(c),- });- }- case "remove_tags_from_memos": {- assertScope(auth, "write:tags");- return await updateTagsForMemos(c.env.storage.db, {- workspaceId: auth.workspaceId,- memoIds: getRequiredStringArray(args.memoIds, "memoIds"),- tags: getRequiredStringArray(args.tags, "tags"),- mode: "remove",- dryRun: args.dryRun === true,- actor: getAuditActor(c),- actorLabel: getActorLabel(c),- });- }- case "rename_tag": {- assertScope(auth, "write:tags");- const from = getRequiredString(args.from, "from");- const to = getRequiredString(args.to, "to");-- if (args.dryRun === true) {- return await previewTagRename(c.env.storage.db, auth.workspaceId, from, to);- }-- const updated = await updateTagAcrossMemos(c.env.storage.db, auth.workspaceId, from, to, getAuditActor(c), getActorLabel(c));- return { ok: true, updated };- }- case "delete_tag": {- assertScope(auth, "write:tags");- const tag = getRequiredString(args.tag, "tag");-- if (args.dryRun === true) {- return await previewTagRename(c.env.storage.db, auth.workspaceId, tag, null);- }-- const updated = await updateTagAcrossMemos(c.env.storage.db, auth.workspaceId, tag, null, getAuditActor(c), getActorLabel(c));- return { ok: true, updated };- }- case "merge_memos": {- assertScope(auth, "write:memos");- const actor = getAuditActor(c);- const actorLabel = getActorLabel(c);- const memo = await mergeMemosRecord(- c.env.storage.db,- auth.workspaceId,- {- memoIds: getRequiredStringArray(args.memoIds, "memoIds"),- notebookId: getOptionalString(args.notebookId) ?? undefined,- title: getOptionalString(args.title) ?? undefined,- },- actor,- actorLabel- );-- return { memo };- }- case "upload_memo_attachment": {- assertScope(auth, "write:resources");- const memoId = getRequiredString(args.memoId, "memoId");- const memo = await getMemoDetail(c.env.storage.db, auth.workspaceId, memoId);-- if (!memo) {- throw new AppError("not_found", "Memo not found", 404);- }-- const filename = getRequiredString(args.filename, "filename");- const bytes = await decodeBase64Data(getRequiredString(args.dataBase64, "dataBase64"));- const resource = await createAttachmentResource(c, {- memoId,- filename,- mimeType: getRequiredString(args.mimeType, "mimeType"),- bytes,- actor: getAuditActor(c),- });- const label = getOptionalString(args.label) ?? normalizeFilename(filename) ?? "attachment";-- return {- resource,- markdownLink: `[${escapeMarkdownLinkLabel(label)}](${resource.url})`,- };- }- case "list_memo_resources": {- assertScope(auth, "read:resources");- const memoId = getRequiredString(args.memoId, "memoId");- const memo = await getMemoDetail(c.env.storage.db, auth.workspaceId, memoId, true);-- if (!memo) {- throw new AppError("not_found", "Memo not found", 404);- }-- return { resources: await listResourcesForMemo(c.env.storage.db, auth.workspaceId, memoId) };- }- case "list_resources": {- assertScope(auth, "read:resources");- return await listResourcesForMcp(c.env.storage.db, auth.workspaceId, clampNumber(Number(args.limit ?? 100), 1, 500));- }- case "list_memo_revisions": {- assertScope(auth, "read:memos");- return {- revisions: await listMemoRevisions(- c.env.storage.db,- auth.workspaceId,- getRequiredString(args.memoId, "memoId"),- clampNumber(Number(args.limit ?? 50), 1, 100)- ),- };- }- case "restore_memo_revision": {- assertScope(auth, "write:memos");- const memoId = getRequiredString(args.memoId, "memoId");- const revisionId = getRequiredString(args.revisionId, "revisionId");- const revision = await getMemoRevisionRow(c.env.storage.db, auth.workspaceId, memoId, revisionId);-- if (!revision) {- throw new AppError("not_found", "Memo revision not found", 404);- }-- if (args.dryRun === true) {- return { dryRun: true, revision: mapMemoRevision(revision) };- }-- return { memo: await restoreMemoRevisionRecord(c.env.storage.db, auth.workspaceId, memoId, revisionId, getAuditActor(c), getActorLabel(c)) };- }- case "move_notebook": {- assertScope(auth, "write:notebooks");- const actor = getAuditActor(c);- const notebook = await updateNotebookRecord(- c.env.storage.db,- auth.workspaceId,- getRequiredString(args.notebookId, "notebookId"),- {- parentId: args.parentId === null ? null : getOptionalString(args.parentId) ?? undefined,- sortOrder: typeof args.sortOrder === "number" && Number.isInteger(args.sortOrder) ? args.sortOrder : undefined,- },- actor- );-- return { notebook };- }- case "create_notebook": {- assertScope(auth, "write:notebooks");- const actor = getAuditActor(c);- const name = getRequiredString(args.name, "name");-- if (name.length > 80) {- throw new AppError("invalid_params", "name must be at most 80 characters", 400);- }-- const notebook = await createNotebookRecord(- c.env.storage.db,- auth.workspaceId,- {- name,- parentId: args.parentId === null ? null : getOptionalString(args.parentId) ?? undefined,- sortOrder: typeof args.sortOrder === "number" && Number.isInteger(args.sortOrder) ? args.sortOrder : undefined,- },- actor- );-- return { notebook };- }- case "rename_notebook": {- assertScope(auth, "write:notebooks");- const name = getRequiredString(args.name, "name");-- if (name.length > 80) {- throw new AppError("invalid_params", "name must be at most 80 characters", 400);- }-- const notebook = await updateNotebookRecord(- c.env.storage.db,- auth.workspaceId,- getRequiredString(args.notebookId, "notebookId"),- { name },- getAuditActor(c)- );-- return { notebook };- }- case "get_notebook": {- assertScope(auth, "read:notebooks");- const notebook = await getNotebook(c.env.storage.db, auth.workspaceId, getRequiredString(args.notebookId, "notebookId"));- if (!notebook) {- throw new AppError("not_found", "Notebook not found in the authenticated user's workspace.", 404);- }- return { notebook };- }- case "find_notebooks": {- assertScope(auth, "read:notebooks");- return {- notebooks: await findNotebooks(c.env.storage.db, auth.workspaceId, {- name: getRequiredString(args.name, "name"),- parentId: Object.hasOwn(args, "parentId")- ? args.parentId === null- ? null- : getRequiredString(args.parentId, "parentId")- : undefined,- exact: args.exact === true,- limit: clampNumber(Number(args.limit ?? 20), 1, 50),- }),- };- }- case "resolve_notebook_path": {- assertScope(auth, "read:notebooks");- return await resolveNotebookPath(c.env.storage.db, auth.workspaceId, getRequiredString(args.path, "path"));- }- case "list_notebooks": {- assertScope(auth, "read:notebooks");- return { notebooks: await listNotebooks(c.env.storage.db, auth.workspaceId) };- }- case "list_tags": {- assertScope(auth, "read:tags");- return { tags: await listTagSummaries(c.env.storage.db, auth.workspaceId) };- }- case "get_workspace_stats": {- assertScope(auth, "read:memos");- return await getWorkspaceStats(c.env.storage.db, auth.workspaceId);- }- case "list_note_templates": {- assertScope(auth, "read:memos");- return { templates: await listMemoTemplates(c.env.storage.db, auth.workspaceId) };- }- case "get_note_template": {- assertScope(auth, "read:memos");- const template = await getMemoTemplate(- c.env.storage.db,- auth.workspaceId,- getRequiredString(args.templateId, "templateId"),- );- if (!template) throw new AppError("not_found", "Template not found", 404);- return { template };- }- case "create_note_template": {- assertScope(auth, "write:memos");- assertMcpMutationAllowed(c.env);- const input = parseMcpInput(TemplateCreateSchema, args);- const memo = input.memoId- ? await getMemoDetail(c.env.storage.db, auth.workspaceId, input.memoId)- : null;- if (input.memoId && !memo) throw new AppError("not_found", "Memo not found", 404);-- const id = createId("template");- const now = isoNow();- const title = memo?.title ?? (input.title?.trim() || null);- const contentMarkdown = memo?.contentMarkdown ?? input.contentMarkdown ?? "";- const tags = memo?.tags ?? input.tags ?? [];- const contentJson = memo?.contentJson ?? markdownToDoc(contentMarkdown);- await c.env.storage.db.prepare(- `INSERT INTO memo_templates (- id, workspace_id, name, description, title, content_json, content_markdown, tags_json, created_at, updated_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,- ).bind(- id,- auth.workspaceId,- input.name.trim(),- input.description?.trim() || null,- title,- JSON.stringify(contentJson),- contentMarkdown,- JSON.stringify(tags),- now,- now,- ).run();- const actor = getAuditActor(c);- await audit(c.env.storage.db, actor.actorType, actor.actorId, "template.create", "template", id, {- memoId: input.memoId ?? null,- });- return { template: await getMemoTemplate(c.env.storage.db, auth.workspaceId, id) };- }- case "update_note_template": {- assertScope(auth, "write:memos");- assertMcpMutationAllowed(c.env);- const templateId = getRequiredString(args.templateId, "templateId");- const input = parseMcpInput(TemplateUpdateSchema, args);- if (Object.keys(input).length === 0) {- throw new AppError("invalid_params", "At least one template field is required.", 400);- }- const current = await getMemoTemplate(c.env.storage.db, auth.workspaceId, templateId);- if (!current) throw new AppError("not_found", "Template not found", 404);-- const contentMarkdown = input.contentMarkdown ?? current.contentMarkdown;- const contentJson = input.contentMarkdown !== undefined- ? markdownToDoc(contentMarkdown)- : current.contentJson;- const now = isoNow();- await c.env.storage.db.prepare(- `UPDATE memo_templates- SET name = ?, description = ?, title = ?, content_json = ?, content_markdown = ?, tags_json = ?, updated_at = ?- WHERE id = ? AND workspace_id = ?`,- ).bind(- input.name ?? current.name,- input.description !== undefined ? input.description?.trim() || null : current.description,- input.title !== undefined ? input.title?.trim() || null : current.title,- JSON.stringify(contentJson),- contentMarkdown,- JSON.stringify(input.tags ?? current.tags),- now,- templateId,- auth.workspaceId,- ).run();- const actor = getAuditActor(c);- await audit(c.env.storage.db, actor.actorType, actor.actorId, "template.update", "template", templateId, {});- return { template: await getMemoTemplate(c.env.storage.db, auth.workspaceId, templateId) };- }- case "delete_note_template": {- assertScope(auth, "write:memos");- assertMcpMutationAllowed(c.env);- const templateId = getRequiredString(args.templateId, "templateId");- const current = await getMemoTemplate(c.env.storage.db, auth.workspaceId, templateId);- if (!current) throw new AppError("not_found", "Template not found", 404);- await c.env.storage.db.prepare(- `DELETE FROM memo_templates WHERE id = ? AND workspace_id = ?`,- ).bind(templateId, auth.workspaceId).run();- const actor = getAuditActor(c);- await audit(c.env.storage.db, actor.actorType, actor.actorId, "template.delete", "template", templateId, {});- return { ok: true };- }- case "use_note_template": {- assertScope(auth, "write:memos");- assertMcpMutationAllowed(c.env);- const templateId = getRequiredString(args.templateId, "templateId");- const template = await getMemoTemplate(c.env.storage.db, auth.workspaceId, templateId);- if (!template) throw new AppError("not_found", "Template not found", 404);- const memo = await createMemoRecord(c.env.storage.db, auth.workspaceId, {- notebookId: getRequiredString(args.notebookId, "notebookId"),- title: template.title ?? undefined,- contentMarkdown: template.contentMarkdown,- tags: template.tags,- }, getAuditActor(c), getActorLabel(c));- const actor = getAuditActor(c);- await audit(c.env.storage.db, actor.actorType, actor.actorId, "template.use", "template", templateId, { memoId: memo.id });- return { memo };- }- case "list_ai_instructions": {- assertScope(auth, "read:memos");- return {- instructions: await listAiPromptTemplates(- c.env.storage.db,- auth.workspaceId,- getOptionalString(args.locale),- ),- };- }- case "get_ai_instruction": {- assertScope(auth, "read:memos");- const row = await getAiPromptTemplateRow(- c.env.storage.db,- auth.workspaceId,- getRequiredString(args.instructionId, "instructionId"),- );- if (!row) throw new AppError("not_found", "AI instruction not found", 404);- return { instruction: mapAiPromptTemplateRow(row, getOptionalString(args.locale)) };- }- case "create_ai_instruction": {- assertScope(auth, "write:memos");- assertMcpMutationAllowed(c.env);- const input = parseMcpInput(AiPromptTemplateCreateSchema, args);- const id = createId("aiprompt");- const now = isoNow();- const actor = getAuditActor(c);- await c.env.storage.db.batch([- c.env.storage.db.prepare(- `INSERT INTO ai_prompt_templates (- id, workspace_id, seed_key, action, parameter_kind, result_mode,- name, description, instruction,- name_customized, description_customized, instruction_customized,- created_at, updated_at- ) VALUES (?, ?, NULL, 'custom', ?, ?, ?, ?, ?, 1, 1, 1, ?, ?)`,- ).bind(- id,- auth.workspaceId,- input.parameterKind,- input.resultMode,- input.name.trim(),- input.description?.trim() || null,- input.instruction.trim(),- now,- now,- ),- auditStatement(c.env.storage.db, actor.actorType, actor.actorId, "ai_prompt.create", "ai_prompt", id, {}),- ]);- const row = await getAiPromptTemplateRow(c.env.storage.db, auth.workspaceId, id);- return { instruction: mapAiPromptTemplateRow(row!, getOptionalString(args.locale)) };- }- case "update_ai_instruction": {- assertScope(auth, "write:memos");- assertMcpMutationAllowed(c.env);- const instructionId = getRequiredString(args.instructionId, "instructionId");- const input = parseMcpInput(AiPromptTemplateUpdateSchema, args);- const current = await getAiPromptTemplateRow(c.env.storage.db, auth.workspaceId, instructionId);- if (!current) throw new AppError("not_found", "AI instruction not found", 404);-- const now = isoNow();- const actor = getAuditActor(c);- await c.env.storage.db.batch([- c.env.storage.db.prepare(- `UPDATE ai_prompt_templates- SET name = ?, description = ?, instruction = ?,- parameter_kind = ?, result_mode = ?,- name_customized = ?, description_customized = ?, instruction_customized = ?,- updated_at = ?- WHERE id = ? AND workspace_id = ?`,- ).bind(- input.name?.trim() ?? current.name,- input.description !== undefined ? input.description?.trim() || null : current.description,- input.instruction?.trim() ?? current.instruction,- input.parameterKind ?? current.parameter_kind,- input.resultMode ?? current.result_mode,- input.name !== undefined ? 1 : current.name_customized,- input.description !== undefined ? 1 : current.description_customized,- input.instruction !== undefined ? 1 : current.instruction_customized,- now,- instructionId,- auth.workspaceId,- ),- auditStatement(c.env.storage.db, actor.actorType, actor.actorId, "ai_prompt.update", "ai_prompt", instructionId, {}),- ]);- const row = await getAiPromptTemplateRow(c.env.storage.db, auth.workspaceId, instructionId);- return { instruction: mapAiPromptTemplateRow(row!, getOptionalString(args.locale)) };- }- case "delete_ai_instruction": {- assertScope(auth, "write:memos");- assertMcpMutationAllowed(c.env);- const instructionId = getRequiredString(args.instructionId, "instructionId");- const current = await getAiPromptTemplateRow(c.env.storage.db, auth.workspaceId, instructionId);- if (!current) throw new AppError("not_found", "AI instruction not found", 404);- const actor = getAuditActor(c);- await c.env.storage.db.batch([- c.env.storage.db.prepare(- `DELETE FROM ai_prompt_templates WHERE id = ? AND workspace_id = ?`,- ).bind(instructionId, auth.workspaceId),- auditStatement(c.env.storage.db, actor.actorType, actor.actorId, "ai_prompt.delete", "ai_prompt", instructionId, {}),- ]);- return { ok: true };- }- case "restore_default_ai_instructions": {- assertScope(auth, "write:memos");- assertMcpMutationAllowed(c.env);- const result = await restoreMissingDefaultAiPrompts(c.env.storage.db, auth.workspaceId);- if (result.restoredCount > 0) {- const actor = getAuditActor(c);- await audit(c.env.storage.db, actor.actorType, actor.actorId, "ai_prompt.restore_defaults", "workspace", auth.workspaceId, result);- }- return {- ...result,- instructions: await listAiPromptTemplates(- c.env.storage.db,- auth.workspaceId,- getOptionalString(args.locale),- ),- };- }- default:- throw new Error(`Unknown tool: ${name}`);- }-};--const getInstanceAuthMode = async (- env: Bindings,- verifyDatabase = false,-): Promise<InstanceAuthMode> => {- if (!env.storage.db || typeof env.storage.db.prepare !== "function") {- throw new AppError(- "database_not_ready",- "Database is not ready. Bind the D1 database as DB and apply the remote migrations.",- 503,- );- }-- const allowUnauthenticated = isUnauthenticatedAccessEnabled(env.EDGE_EVER_ALLOW_UNAUTHENTICATED);- const bootstrapCredentialConfigured = hasBootstrapCredential(- env.EDGE_EVER_AUTH_PASSWORD,- env.EDGE_EVER_AUTH_PASSWORD_HASH,- );-- if (!verifyDatabase) {- if (allowUnauthenticated) return "disabled";- if (bootstrapCredentialConfigured) return "required";- }-- let user: { id: string } | null;- try {- user = await env.storage.db.prepare(`SELECT id FROM users WHERE is_disabled = 0 LIMIT 1`).first<{ id: string }>();- } catch (error) {- if (isDatabaseNotReadyError(error)) {- throw new AppError(- "database_not_ready",- "Database is not ready. Bind the D1 database as DB and apply the remote migrations.",- 503,- );- }- throw error;- }-- return resolveInstanceAuthMode({- allowUnauthenticated,- hasBootstrapCredential: bootstrapCredentialConfigured,- hasEnabledUser: Boolean(user),- });-};--const getLoginAttemptKeys = async (c: AppContext, username: string): Promise<LoginAttemptKey[]> => {- const keys: LoginAttemptKey[] = [{ scope: "username", key: await sha256(username.trim()) }];- const clientIp = getClientIp(c);-- if (clientIp) {- keys.push({ scope: "ip", key: await sha256(clientIp) });- }-- return keys;-};--const getClientIp = (c: Context) => {- const cloudflareIp = c.req.header("CF-Connecting-IP")?.trim();- if (cloudflareIp) return cloudflareIp;-- const realIp = c.req.header("X-Real-IP")?.trim();- if (realIp) return realIp;-- const forwardedIp = c.req.header("X-Forwarded-For")?.split(",", 1)[0]?.trim();- return forwardedIp || null;-};--const tooManyLoginAttempts = (c: Context, retryAfterSeconds: number) => {- c.header("Retry-After", String(retryAfterSeconds));- return apiError(c, "login_rate_limited", "Too many login attempts. Try again later.", 429);-};--const verifyLogin = async (env: Bindings, username: string, password: string): Promise<UserRow | null> => {- const normalizedUsername = username.trim();- const existingUser = await getUserByUsername(env.storage.db, normalizedUsername);-- if (existingUser) {- if (await verifyPassword(password, existingUser.password_hash)) {- return existingUser;- }-- if (!isSupportedPasswordHash(existingUser.password_hash)) {- throw new AppError(- "password_hash_invalid",- "This account has an invalid password hash. Reset it with the EdgeEver password reset command.",- 503,- );- }-- return null;- }-- const configuredHash = env.EDGE_EVER_AUTH_PASSWORD_HASH?.trim();- const configuredPassword = env.EDGE_EVER_AUTH_PASSWORD;-- if (!configuredHash && !configuredPassword) {- return null;- }-- const configuredUsername = env.EDGE_EVER_AUTH_USERNAME?.trim() || "admin";-- if (normalizedUsername !== configuredUsername) {- return null;- }-- const passwordMatches = await verifyBootstrapPassword(- password,- configuredPassword,- configuredHash,- verifyPassword,- );-- if (!passwordMatches) {- return null;- }-- const now = isoNow();- const userId = createId("usr");- const passwordHash = await hashPassword(password);-- await env.storage.db.prepare(- `INSERT OR IGNORE INTO users (id, username, password_hash, display_name, created_at, updated_at)- VALUES (?, ?, ?, ?, ?, ?)`- )- .bind(userId, normalizedUsername, passwordHash, normalizedUsername, now, now)- .run();-- return getUserByUsername(env.storage.db, normalizedUsername);-};--const getUserByUsername = async (db: DatabaseAdapter, username: string) =>- db- .prepare(- `SELECT id, username, password_hash, display_name, is_disabled- FROM users- WHERE username = ? AND is_disabled = 0`- )- .bind(username)- .first<UserRow>();--const getInstanceUser = (db: D1Database, userId: string) =>- db.prepare(- `SELECT u.id, u.username, u.password_hash, u.display_name, u.is_disabled,- u.last_login_at, u.created_at, wm.role- FROM users u- INNER JOIN workspace_members wm ON wm.user_id = u.id- WHERE u.id = ?`- ).bind(userId).first<InstanceUserRow>();--const createSession = async (c: AppContext, user: UserRow, requestedDeviceId?: string) => {- const token = randomToken(SESSION_TOKEN_BYTES);- const id = createId("sess");- const now = isoNow();- const maxAge = getSessionMaxAge(c.env);- const expiresAt = new Date(Date.now() + maxAge * 1000).toISOString();- const userAgent = c.req.header("User-Agent") ?? null;- const deviceId = resolveSessionDeviceId(requestedDeviceId, userAgent, id);- const ip = c.req.header("CF-Connecting-IP");- const ipHash = ip ? await sha256(ip) : null;- const cf = c.req.raw.cf as { country?: string; region?: string } | undefined;- const ipCountry = c.req.header("CF-IPCountry") ?? cf?.country ?? null;- const ipRegion = cf?.region ?? null;-- await c.env.storage.db.batch([- c.env.storage.db.prepare(- `UPDATE sessions SET revoked_at = ?- WHERE user_id = ? AND device_id = ? AND revoked_at IS NULL`- ).bind(now, user.id, deviceId),- c.env.storage.db.prepare(- `INSERT INTO sessions (- id, user_id, token_hash, device_id, user_agent, ip_hash, device_label, ip_address, ip_country, ip_region, expires_at, created_at, last_seen_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`- ).bind(id, user.id, await sha256(token), deviceId, userAgent, ipHash, null, ip ?? null, ipCountry, ipRegion, expiresAt, now, now),- ]);-- return { id, token, maxAge };-};--const setSessionCookie = (c: AppContext, token: string, maxAge: number) => {- setCookie(c, SESSION_COOKIE, token, {- httpOnly: true,- secure: new URL(c.req.url).protocol === "https:",- sameSite: "Lax",- path: "/",- maxAge,- });-};--const revokeSession = async (db: D1Database, token: string) => {- await db- .prepare(`UPDATE sessions SET revoked_at = ? WHERE token_hash = ? AND revoked_at IS NULL`)- .bind(isoNow(), await sha256(token))- .run();-};--const authenticateRequest = async (c: AppContext, touch: boolean): Promise<AuthContext | null> => {- const bearerAuth = await authenticateBearerToken(c, touch);-- if (bearerAuth) {- return bearerAuth;- }-- return authenticateSession(c, touch);-};--const authenticateBearerToken = async (c: AppContext, touch: boolean): Promise<AuthContext | null> => {- const token = getBearerToken(c);-- if (!token) {- return null;- }-- const sessionAuth = await authenticateSessionToken(c, token, touch);-- if (sessionAuth) {- return sessionAuth;- }-- const row = await c.env.storage.db.prepare(- `SELECT id, name, token_value, scopes_json, last_used_at, expires_at, is_revoked, created_at, workspace_id- FROM api_tokens- WHERE token_hash = ?- AND is_revoked = 0- AND (expires_at IS NULL OR expires_at > ?)`- )- .bind(await sha256(token), isoNow())- .first<ApiTokenRow>();-- if (!row) {- return null;- }-- const lastUsedAt = row.last_used_at ? Date.parse(row.last_used_at) : Number.NaN;- if (- touch- && (!Number.isFinite(lastUsedAt) || lastUsedAt <= Date.now() - API_TOKEN_LAST_USED_UPDATE_INTERVAL_MS)- ) {- const now = isoNow();- const cutoff = new Date(Date.now() - API_TOKEN_LAST_USED_UPDATE_INTERVAL_MS).toISOString();- await c.env.storage.db.prepare(- `UPDATE api_tokens- SET last_used_at = ?- WHERE id = ? AND (last_used_at IS NULL OR last_used_at <= ?)`,- ).bind(now, row.id, cutoff).run();- }-- return {- kind: "agent",- actorType: "agent",- actorId: row.id,- username: row.name,- displayName: row.name,- scopes: parseJsonArray(row.scopes_json),- workspaceId: row.workspace_id,- role: "member",- tokenId: row.id,- };-};--const authenticateSessionToken = async (c: AppContext, token: string, touch: boolean): Promise<AuthContext | null> => {- const now = isoNow();- const row = await c.env.storage.db.prepare(- `SELECT s.id, s.user_id, u.username, u.display_name, s.expires_at, s.last_seen_at,- wm.workspace_id, wm.role- FROM sessions s- INNER JOIN users u ON u.id = s.user_id- LEFT JOIN workspace_members wm ON wm.user_id = s.user_id- WHERE s.token_hash = ?- AND s.revoked_at IS NULL- AND s.expires_at > ?- AND u.is_disabled = 0`- )- .bind(await sha256(token), now)- .first<SessionRow>();-- if (!row) {- return null;- }-- const lastSeenAt = row.last_seen_at ? Date.parse(row.last_seen_at) : Number.NaN;- if (- touch- && (!Number.isFinite(lastSeenAt) || lastSeenAt <= Date.now() - SESSION_LAST_SEEN_UPDATE_INTERVAL_MS)- ) {- const cutoff = new Date(Date.now() - SESSION_LAST_SEEN_UPDATE_INTERVAL_MS).toISOString();- await c.env.storage.db.prepare(- `UPDATE sessions- SET last_seen_at = ?- WHERE id = ? AND (last_seen_at IS NULL OR last_seen_at <= ?)`,- ).bind(now, row.id, cutoff).run();- }-- const workspace = row.workspace_id && row.role- ? { workspaceId: row.workspace_id, role: row.role }- : await ensureUserWorkspace(c.env.storage.db, row.user_id, row.username, c.req.header("accept-language"));-- return {- kind: "user",- actorType: "user",- actorId: row.user_id,- username: row.username,- displayName: row.display_name,- scopes: [],- workspaceId: workspace.workspaceId,- role: workspace.role,- sessionId: row.id,- };-};--const authenticateSession = async (c: AppContext, touch: boolean): Promise<AuthContext | null> => {- const token = getCookie(c, SESSION_COOKIE);-- if (!token) {- return null;- }-- return authenticateSessionToken(c, token, touch);-};--const getBearerToken = (c: AppContext) => {- const authorization = c.req.header("Authorization");-- if (!authorization) {- return null;- }-- const [scheme, token] = authorization.split(/\s+/, 2);- return scheme.toLowerCase() === "bearer" && token ? token : null;-};--const getSessionMaxAge = (env: Bindings) => {- const days = clampNumber(Number(env.EDGE_EVER_SESSION_TTL_DAYS ?? DEFAULT_SESSION_TTL_DAYS), 1, MAX_SESSION_TTL_DAYS);- return days * 24 * 60 * 60;-};--const mapMemoDetail = (row: MemoDetailRow): MemoDetail => ({- ...mapMemoSummary(row),- contentJson: parseDoc(row.content_json),- contentMarkdown: row.content_markdown,- contentText: row.content_text,- contentHash: row.content_hash,- sourceMemoIds: parseJsonArray(row.source_memo_ids),- mergeSourceCount: row.merge_source_count,- mergedIntoMemoId: row.merged_into_memo_id,-});--const mapMemoRevision = (row: MemoRevisionRow): MemoRevision => ({- id: row.id,- memoId: row.memo_id,- revision: row.revision,- title: row.title,- tags: parseJsonArray(row.tags_json),- contentMarkdown: row.content_markdown,- contentText: row.content_text,- contentHash: row.content_hash,- createdBy: row.created_by,- createdAt: row.created_at,-});--const restoreJsonNotebooks = async (db: D1Database, workspaceId: string, notebooks: JsonBackupNotebook[]) => {- await assertIdsAvailableInWorkspace(db, "notebooks", workspaceId, notebooks.map((notebook) => notebook.id));- const importedIds = new Set(notebooks.map((notebook) => notebook.id));- const externalParentIds = notebooks- .map((notebook) => notebook.parentId)- .filter((id): id is string => Boolean(id) && !importedIds.has(id as string));- await assertNotebookIdsInWorkspace(db, workspaceId, externalParentIds);- const statements = notebooks.map((notebook) =>- db.prepare(- `INSERT INTO notebooks (- id, workspace_id, parent_id, name, slug, icon, color, sort_order, is_deleted, created_at, updated_at, deleted_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, NULL)- ON CONFLICT(id) DO UPDATE SET- parent_id = excluded.parent_id,- name = excluded.name,- slug = excluded.slug,- icon = excluded.icon,- color = excluded.color,- sort_order = excluded.sort_order,- is_deleted = 0,- updated_at = excluded.updated_at,- deleted_at = NULL`- ).bind(- notebook.id,- workspaceId,- notebook.parentId,- notebook.name,- notebook.slug,- notebook.icon,- notebook.color,- notebook.sortOrder,- notebook.createdAt,- notebook.updatedAt- )- );-- await db.batch(statements);-};--const restoreJsonMemos = async (db: D1Database, workspaceId: string, backups: JsonBackupMemo[]) => {- await assertIdsAvailableInWorkspace(db, "memos", workspaceId, backups.map((backup) => backup.memo.id));- await assertNotebookIdsInWorkspace(db, workspaceId, backups.map((backup) => backup.memo.notebookId));- for (const backup of backups) {- const memo = backup.memo;- const contentJson = parseDoc(JSON.stringify(memo.contentJson));- const contentMarkdown = memo.contentMarkdown || docToMarkdown(contentJson);- const contentText = docToText(contentJson);- const contentHash = await sha256(contentMarkdown + JSON.stringify(contentJson));- const title = normalizeMemoTitle(memo.title);- const tags = normalizeTags(memo.tags);-- if (backup.revisions.some((revision) => revision.memoId !== memo.id)) {- throw new AppError("invalid_backup", "A backup revision belongs to a different memo.", 400);- }-- await db.batch([- db.prepare(- `INSERT INTO memos (- id, workspace_id, notebook_id, title, excerpt, tags_json, is_pinned, is_archived, is_deleted,- source_memo_ids, merge_source_count, merged_into_memo_id,- created_by, updated_by, created_at, updated_at, deleted_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, NULL, 'restore', 'restore', ?, ?, NULL)- ON CONFLICT(id) DO UPDATE SET- notebook_id = excluded.notebook_id,- title = excluded.title,- excerpt = excluded.excerpt,- tags_json = excluded.tags_json,- is_pinned = excluded.is_pinned,- is_archived = excluded.is_archived,- is_deleted = 0,- source_memo_ids = excluded.source_memo_ids,- merge_source_count = excluded.merge_source_count,- merged_into_memo_id = NULL,- updated_by = 'restore',- updated_at = excluded.updated_at,- deleted_at = NULL`- ).bind(- memo.id,- workspaceId,- memo.notebookId,- title,- createExcerpt(contentText),- JSON.stringify(tags),- memo.isPinned ? 1 : 0,- memo.isArchived ? 1 : 0,- JSON.stringify(memo.sourceMemoIds),- memo.mergeSourceCount,- memo.createdAt,- memo.updatedAt- ),- db.prepare(- `INSERT INTO memo_contents (- memo_id, content_json, content_markdown, content_text, content_hash, revision, created_at, updated_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)- ON CONFLICT(memo_id) DO UPDATE SET- content_json = excluded.content_json,- content_markdown = excluded.content_markdown,- content_text = excluded.content_text,- content_hash = excluded.content_hash,- revision = excluded.revision,- updated_at = excluded.updated_at`- ).bind(- memo.id,- JSON.stringify(contentJson),- contentMarkdown,- contentText,- contentHash,- memo.revision,- memo.createdAt,- memo.updatedAt- ),- upsertMemoSearchDocumentStatement(db, memo.id, title, contentText, tags.join(" ")),- db.prepare(`DELETE FROM memo_revisions WHERE memo_id = ?`).bind(memo.id),- ]);-- for (let index = 0; index < backup.revisions.length; index += 50) {- const statements = backup.revisions.slice(index, index + 50).map((revision) => {- const revisionJson = parseDoc(JSON.stringify(revision.contentJson));- const revisionMarkdown = revision.contentMarkdown || docToMarkdown(revisionJson);- const revisionText = docToText(revisionJson);- return db.prepare(- `INSERT INTO memo_revisions (- id, memo_id, revision, title, content_json, content_markdown,- content_hash, created_by, created_at, tags_json, content_text- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)- ON CONFLICT(id) DO UPDATE SET- memo_id = excluded.memo_id,- revision = excluded.revision,- title = excluded.title,- content_json = excluded.content_json,- content_markdown = excluded.content_markdown,- content_hash = excluded.content_hash,- created_by = excluded.created_by,- created_at = excluded.created_at,- tags_json = excluded.tags_json,- content_text = excluded.content_text`- ).bind(- revision.id,- memo.id,- revision.revision,- normalizeMemoTitle(revision.title),- JSON.stringify(revisionJson),- revisionMarkdown,- revision.contentHash || "",- revision.createdBy,- revision.createdAt,- JSON.stringify(normalizeTags(revision.tags)),- revisionText- );- });- await db.batch(statements);- }- }-- await audit(db, "user", null, "backup.restore", "backup", createId("restore"), {- memoCount: backups.length,- });-};--const assertIdsAvailableInWorkspace = async (- db: D1Database,- table: "notebooks" | "memos",- workspaceId: string,- ids: string[],-) => {- if (ids.length === 0) return;- const placeholders = ids.map(() => "?").join(", ");- const collision = await db.prepare(- `SELECT id FROM ${table} WHERE workspace_id <> ? AND id IN (${placeholders}) LIMIT 1`- ).bind(workspaceId, ...ids).first<{ id: string }>();- if (collision) {- throw new AppError("cross_workspace_id_conflict", "Backup contains an ID already used by another user.", 409);- }-};--const assertNotebookIdsInWorkspace = async (db: D1Database, workspaceId: string, ids: string[]) => {- const uniqueIds = Array.from(new Set(ids));- if (uniqueIds.length === 0) return;- const placeholders = uniqueIds.map(() => "?").join(", ");- const rows = await db.prepare(- `SELECT id FROM notebooks WHERE workspace_id = ? AND id IN (${placeholders})`- ).bind(workspaceId, ...uniqueIds).all<{ id: string }>();- if (rows.results.length !== uniqueIds.length) {- throw new AppError("invalid_backup_workspace", "Backup references a notebook outside the current workspace.", 400);- }-};--const getCurrentWorkspaceIdentity = async (db: D1Database, auth: AuthContext) => {- const row = await db.prepare(- `SELECT w.id AS workspace_id, w.name AS workspace_name, w.is_personal,- u.id AS user_id, u.username, u.display_name, wm.role- FROM workspaces w- INNER JOIN workspace_members wm ON wm.workspace_id = w.id- INNER JOIN users u ON u.id = wm.user_id- WHERE w.id = ?- ORDER BY CASE WHEN u.id = ? THEN 0 ELSE 1 END, wm.created_at ASC- LIMIT 1`- ).bind(auth.workspaceId, auth.kind === "user" ? auth.actorId : null).first<WorkspaceIdentityRow>();-- if (!row) {- throw new AppError("workspace_identity_not_found", "The authenticated workspace has no associated user.", 404);- }-- return {- user: {- id: row.user_id,- username: row.username,- displayName: row.display_name,- role: row.role,- },- workspace: {- id: row.workspace_id,- name: row.workspace_name,- isPersonal: row.is_personal === 1,- },- authorization: {- kind: auth.kind === "agent" ? "api_token" : "user_session",- ...(auth.kind === "agent" ? { tokenName: auth.username, scopes: auth.scopes } : {}),- },- dataIsolation: {- workspaceScoped: true,- statement:- "Every notebook and memo returned by this MCP server belongs to this workspace; data from other users is excluded.",- },- };-};--const searchMemoSummaries = async (- db: D1Database,- options: {- workspaceId: string;- query?: string | null;- notebookId?: string | null;- tags?: string[];- createdAfter?: string | null;- createdBefore?: string | null;- updatedAfter?: string | null;- updatedBefore?: string | null;- isPinned?: boolean | null;- hasResources?: boolean | null;- limit: number;- }-): Promise<MemoSummary[]> => {- const q = options.query?.trim();- const notebookId = options.notebookId?.trim() || null;- const tags = normalizeTags(options.tags ?? []);- const limit = clampNumber(options.limit, 1, 100);- const filters = ["m.workspace_id = ?", "m.is_deleted = 0"];- const binds: unknown[] = [options.workspaceId];-- if (notebookId) {- filters.push("m.notebook_id = ?");- binds.push(notebookId);- }-- for (const tag of tags) {- filters.push("EXISTS (SELECT 1 FROM memo_tags mt WHERE mt.memo_id = m.id AND mt.workspace_id = ? AND mt.name = ?)");- binds.push(options.workspaceId, tag);- }-- if (options.createdAfter) {- filters.push("m.created_at >= ?");- binds.push(options.createdAfter);- }-- if (options.createdBefore) {- filters.push("m.created_at <= ?");- binds.push(options.createdBefore);- }-- if (options.updatedAfter) {- filters.push("m.updated_at >= ?");- binds.push(options.updatedAfter);- }-- if (options.updatedBefore) {- filters.push("m.updated_at <= ?");- binds.push(options.updatedBefore);- }-- if (options.isPinned !== null && options.isPinned !== undefined) {- filters.push("m.is_pinned = ?");- binds.push(options.isPinned ? 1 : 0);- }-- if (options.hasResources !== null && options.hasResources !== undefined) {- filters.push(- options.hasResources- ? "EXISTS (SELECT 1 FROM resources r WHERE r.memo_id = m.id AND r.is_deleted = 0)"- : "NOT EXISTS (SELECT 1 FROM resources r WHERE r.memo_id = m.id AND r.is_deleted = 0)"- );- }-- if (q) {- const ftsQuery = toFtsQuery(q);- const likeQuery = `%${escapeLike(q)}%`;-- if (ftsQuery) {- const rows = await db- .prepare(- `WITH raw_matches(memo_id, rank) AS (- SELECT memo_id, bm25(memos_fts)- FROM memos_fts- WHERE memos_fts MATCH ?-- UNION ALL-- SELECT m.id, 100.0- FROM memos m- INNER JOIN memo_contents c ON c.memo_id = m.id- WHERE m.title LIKE ? ESCAPE '\\'- OR c.content_text LIKE ? ESCAPE '\\'- OR m.tags_json LIKE ? ESCAPE '\\'- ),- search_matches AS (- SELECT memo_id, MIN(rank) AS rank- FROM raw_matches- GROUP BY memo_id- )- 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, c.revision,- c.content_text- FROM search_matches s- INNER JOIN memos m ON m.id = s.memo_id- INNER JOIN memo_contents c ON c.memo_id = m.id- WHERE ${filters.join(" AND ")}- ORDER BY s.rank ASC, m.is_pinned DESC, m.updated_at DESC- LIMIT ?`- )- .bind(ftsQuery, likeQuery, likeQuery, likeQuery, ...binds, limit)- .all<MemoSummaryRow>();-- return rows.results.map(mapMemoSummary);- }- }-- const rows = await 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, c.revision,- c.content_text- FROM memos m- INNER JOIN memo_contents c ON c.memo_id = m.id- WHERE ${filters.join(" AND ")}- ORDER BY m.is_pinned DESC, m.updated_at DESC- LIMIT ?`- )- .bind(...binds, limit)- .all<MemoSummaryRow>();-- return rows.results.map(mapMemoSummary);-};--const listMemosForMcp = async (- db: D1Database,- options: { workspaceId: string; notebookId?: string | null; limit: number; offset: number; includeContent: boolean; includeDeleted: boolean }-) => {- const notebookId = options.notebookId?.trim() || null;- const limit = clampNumber(options.limit, 1, 100);- const offset = clampNumber(options.offset, 0, 100_000);- const pageSize = limit + 1;- const deletedFilter = options.includeDeleted ? "1 = 1" : "m.is_deleted = 0";-- if (options.includeContent) {- const rows = await 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, c.revision,- c.content_json, c.content_markdown, c.content_text, c.content_hash,- m.source_memo_ids, m.merge_source_count, m.merged_into_memo_id- FROM memos m- INNER JOIN memo_contents c ON c.memo_id = m.id- WHERE m.workspace_id = ? AND ${deletedFilter}- AND (? IS NULL OR m.notebook_id = ?)- ORDER BY m.updated_at DESC, m.id ASC- LIMIT ? OFFSET ?`- )- .bind(options.workspaceId, notebookId, notebookId, pageSize, offset)- .all<MemoDetailRow>();- const page = rows.results.slice(0, limit).map(mapMemoDetail);-- return {- memos: page,- limit,- offset,- nextOffset: rows.results.length > limit ? offset + limit : null,- hasMore: rows.results.length > limit,- };- }-- const rows = await 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, c.revision,- c.content_text- FROM memos m- INNER JOIN memo_contents c ON c.memo_id = m.id- WHERE m.workspace_id = ? AND ${deletedFilter}- AND (? IS NULL OR m.notebook_id = ?)- ORDER BY m.updated_at DESC, m.id ASC- LIMIT ? OFFSET ?`- )- .bind(options.workspaceId, notebookId, notebookId, pageSize, offset)- .all<MemoSummaryRow>();- const page = rows.results.slice(0, limit).map(mapMemoSummary);-- return {- memos: page,- limit,- offset,- nextOffset: rows.results.length > limit ? offset + limit : null,- hasMore: rows.results.length > limit,- };-};--const getMemoDetailRow = async (- db: D1Database,- workspaceId: string,- id: string,- includeDeleted = false-): Promise<MemoDetailRow | null> =>- 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, c.revision,- c.content_json, c.content_markdown, c.content_text, c.content_hash,- m.source_memo_ids, m.merge_source_count, m.merged_into_memo_id- FROM memos m- INNER JOIN memo_contents c ON c.memo_id = m.id- WHERE m.id = ? AND m.workspace_id = ? AND (? = 1 OR m.is_deleted = 0)`- )- .bind(id, workspaceId, includeDeleted ? 1 : 0)- .first<MemoDetailRow>();--const getMemoDetail = async (db: D1Database, workspaceId: string, id: string, includeDeleted = false): Promise<MemoDetail | null> => {- const row = await getMemoDetailRow(db, workspaceId, id, includeDeleted);- return row ? mapMemoDetail(row) : null;-};--export const createMemoEditSession = async (c: AppContext, memoId: string): Promise<MemoEditSession | null> => {- const current = await getMemoDetailRow(c.env.storage.db, getWorkspaceId(c), memoId);- if (!current) return null;-- const actor = getAuditActor(c);- const now = isoNow();- const existing = await c.env.storage.db.prepare(- `SELECT id, memo_id, base_revision, base_content_hash, expires_at- FROM memo_edit_sessions- WHERE memo_id = ? AND actor_type = ? AND actor_id IS ?- AND base_revision = ? AND base_content_hash = ? AND expires_at > ?- ORDER BY updated_at DESC- LIMIT 1`,- ).bind(- memoId,- actor.actorType,- actor.actorId,- current.revision,- current.content_hash,- now,- ).first<{- id: string;- memo_id: string;- base_revision: number;- base_content_hash: string;- expires_at: string;- }>();-- if (existing) {- return {- id: existing.id,- memoId: existing.memo_id,- baseRevision: existing.base_revision,- baseContentHash: existing.base_content_hash,- expiresAt: existing.expires_at,- };- }-- const session: MemoEditSession = {- id: createId("edit"),- memoId,- baseRevision: current.revision,- baseContentHash: current.content_hash,- expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60_000).toISOString(),- };-- await c.env.storage.db.batch([- c.env.storage.db.prepare(`DELETE FROM memo_edit_sessions WHERE expires_at <= ?`).bind(now),- c.env.storage.db.prepare(- `INSERT INTO memo_edit_sessions (- id, memo_id, actor_type, actor_id, base_revision, base_content_hash,- expires_at, created_at, updated_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,- ).bind(- session.id,- memoId,- actor.actorType,- actor.actorId,- session.baseRevision,- session.baseContentHash,- session.expiresAt,- now,- now,- ),- ]);-- return session;-};--const deleteMemosRecord = async (- env: Bindings,- workspaceId: string,- memoIds: string[],- permanent: boolean,- actor: { actorType: "user" | "agent"; actorId: string | null }-) => {- const db = env.storage.db;- const uniqueMemoIds = Array.from(new Set(memoIds));-- if (uniqueMemoIds.length === 0) {- return 0;- }-- const placeholders = uniqueMemoIds.map(() => "?").join(", ");- const expectedDeletedState = permanent ? 1 : 0;- const rows = await db- .prepare(- `SELECT id- FROM memos- WHERE workspace_id = ? AND is_deleted = ? AND id IN (${placeholders})`- )- .bind(workspaceId, expectedDeletedState, ...uniqueMemoIds)- .all<{ id: string }>();-- if (rows.results.length !== uniqueMemoIds.length) {- throw new AppError(- "missing_memos",- permanent ? "One or more memos cannot be permanently deleted." : "One or more memos cannot be deleted.",- 400- );- }-- const now = isoNow();- const statements: D1PreparedStatement[] = [];-- if (permanent) {- const resourceRows = await db- .prepare(- `SELECT object_key, storage_config_id- FROM resources- WHERE memo_id IN (${placeholders})`- )- .bind(...uniqueMemoIds)- .all<{ object_key: string; storage_config_id: string }>();-- if (resourceRows.results.length > 0) {- await deleteStoredObjects(env, resourceRows.results);- }-- statements.push(- db.prepare(`DELETE FROM resources WHERE memo_id IN (${placeholders})`).bind(...uniqueMemoIds),- db.prepare(`DELETE FROM memo_revisions WHERE memo_id IN (${placeholders})`).bind(...uniqueMemoIds),- db.prepare(`DELETE FROM memo_contents WHERE memo_id IN (${placeholders})`).bind(...uniqueMemoIds),- db.prepare(`DELETE FROM memos WHERE workspace_id = ? AND is_deleted = 1 AND id IN (${placeholders})`).bind(workspaceId, ...uniqueMemoIds)- );-- for (const memoId of uniqueMemoIds) {- statements.push(auditStatement(db, actor.actorType, actor.actorId, "memo.delete_permanent", "memo", memoId, {}));- }- } else {- statements.push(- db.prepare(`DELETE FROM memo_shares WHERE workspace_id = ? AND memo_id IN (${placeholders})`).bind(workspaceId, ...uniqueMemoIds),- db- .prepare(- `UPDATE memos- SET is_deleted = 1, deleted_at = ?, updated_at = ?- WHERE workspace_id = ? AND is_deleted = 0 AND id IN (${placeholders})`- )- .bind(now, now, workspaceId, ...uniqueMemoIds),- db- .prepare(- `UPDATE resources- SET is_deleted = 1, deleted_at = ?, updated_at = ?- WHERE is_deleted = 0 AND memo_id IN (${placeholders})`- )- .bind(now, now, ...uniqueMemoIds),- deleteMemoSearchDocumentsStatement(db, uniqueMemoIds)- );-- for (const memoId of uniqueMemoIds) {- statements.push(auditStatement(db, actor.actorType, actor.actorId, "memo.delete", "memo", memoId, {}));- }- }-- await db.batch(statements);- return uniqueMemoIds.length;-};--const deleteMemoRecord = async (- env: Bindings,- workspaceId: string,- memoId: string,- permanent: boolean,- actor: AuditActor,-) => {- const current = await getMemoDetailRow(env.storage.db, workspaceId, memoId, permanent);-- if (permanent && (!current || current.is_deleted === 0)) {- throw new AppError("not_found", "Memo not found in trash", 404);- }-- // Soft deletion historically treats an unknown/already-deleted memo as an idempotent no-op.- if (!permanent && !current) return;-- await deleteMemosRecord(env, workspaceId, [memoId], permanent, actor);-};--const getMemosForBulkAction = async (db: D1Database, workspaceId: string, memoIds: string[], deletedState: 0 | 1) => {- const uniqueMemoIds = Array.from(new Set(memoIds));-- if (uniqueMemoIds.length === 0) {- return [];- }-- const placeholders = uniqueMemoIds.map(() => "?").join(", ");- const rows = await 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, c.revision,- c.content_text- FROM memos m- INNER JOIN memo_contents c ON c.memo_id = m.id- WHERE m.workspace_id = ? AND m.is_deleted = ?- AND m.id IN (${placeholders})- ORDER BY m.updated_at DESC, m.id ASC`- )- .bind(workspaceId, deletedState, ...uniqueMemoIds)- .all<MemoSummaryRow>();-- if (rows.results.length !== uniqueMemoIds.length) {- throw new AppError("missing_memos", "One or more memos cannot be found for this action in the expected state.", 400);- }-- return rows.results.map(mapMemoSummary);-};--const restoreMemosRecord = async (- db: D1Database,- workspaceId: string,- memoIds: string[],- actor: { actorType: "user" | "agent"; actorId: string | null }-) => {- const uniqueMemoIds = Array.from(new Set(memoIds));-- if (uniqueMemoIds.length === 0) {- return 0;- }-- const placeholders = uniqueMemoIds.map(() => "?").join(", ");- const rows = await db- .prepare(- `SELECT m.id, m.notebook_id, m.title, m.tags_json, c.content_text- FROM memos m- INNER JOIN memo_contents c ON c.memo_id = m.id- WHERE m.workspace_id = ? AND m.is_deleted = 1 AND m.id IN (${placeholders})`- )- .bind(workspaceId, ...uniqueMemoIds)- .all<{ id: string; notebook_id: string; title: string | null; tags_json: string; content_text: string }>();-- if (rows.results.length !== uniqueMemoIds.length) {- throw new AppError("missing_memos", "One or more memos cannot be restored.", 400);- }-- const notebookIds = Array.from(new Set(rows.results.map((row) => row.notebook_id)));- const notebookPlaceholders = notebookIds.map(() => "?").join(", ");- const notebookRows = await db- .prepare(`SELECT id FROM notebooks WHERE workspace_id = ? AND is_deleted = 0 AND id IN (${notebookPlaceholders})`)- .bind(workspaceId, ...notebookIds)- .all<{ id: string }>();- const activeNotebookIds = new Set(notebookRows.results.map((row) => row.id));-- const needsInbox = rows.results.some((row) => !activeNotebookIds.has(row.notebook_id));-- const inbox = needsInbox- ? await db.prepare(`SELECT id FROM notebooks WHERE workspace_id = ? AND slug = 'inbox' AND is_deleted = 0 LIMIT 1`).bind(workspaceId).first<{ id: string }>()- : null;- if (needsInbox && !inbox) {- throw new AppError("restore_notebook_missing", "Original notebooks were deleted and the default inbox is unavailable.", 409);- }-- const now = isoNow();- const statements: D1PreparedStatement[] = [];-- for (const row of rows.results) {- const restoreNotebookId = activeNotebookIds.has(row.notebook_id) ? row.notebook_id : inbox!.id;- const tags = parseJsonArray(row.tags_json);-- statements.push(- db- .prepare(- `UPDATE memos- SET notebook_id = ?, is_deleted = 0, deleted_at = NULL, updated_at = ?- WHERE id = ? AND workspace_id = ? AND is_deleted = 1`- )- .bind(restoreNotebookId, now, row.id, workspaceId),- db- .prepare(- `UPDATE resources- SET is_deleted = 0, deleted_at = NULL, updated_at = ?- WHERE memo_id = ? AND is_deleted = 1`- )- .bind(now, row.id),- upsertMemoSearchDocumentStatement(db, row.id, row.title, row.content_text, tags.join(" ")),- auditStatement(db, actor.actorType, actor.actorId, "memo.restore", "memo", row.id, {- fromNotebookId: row.notebook_id,- toNotebookId: restoreNotebookId,- })- );- }+ * adapter. Runtime entrypoints must remain thin and call this function rather+ * than introducing platform-specific route or service implementations.+ */+export const fetchEdgeEverApp = async (+ request: Request,+ runtimeEnv: Bindings,+ ctx: ExecutionContext,+) => {+ if (isLocalDemoSeedEnabled(runtimeEnv)) {+ await ensureLocalDemoSeed(runtimeEnv);+ }- await db.batch(statements);- return uniqueMemoIds.length;+ return app.fetch(request, runtimeEnv, ctx);};-const restoreMemoRecord = async (- db: D1Database,- workspaceId: string,- memoId: string,- actor: AuditActor,-): Promise<MemoDetail> => {- const current = await getMemoDetailRow(db, workspaceId, memoId, true);- if (!current || current.is_deleted === 0) {- throw new AppError("not_found", "Memo not found in trash", 404);- }+const worker = {+ async fetch(request: Request, env: WorkerBindings, ctx: ExecutionContext) {+ return fetchEdgeEverApp(request, {+ ...env,+ storage: createCloudflareStorageAdapter(env),+ }, ctx);+ },+ async scheduled(controller: ScheduledController, env: WorkerBindings, ctx: ExecutionContext) {+ const runtimeEnv = {+ ...env,+ storage: createCloudflareStorageAdapter(env),+ } as Bindings;++ if (!isDemoMode(runtimeEnv)) {+ return;+ }- await restoreMemosRecord(db, workspaceId, [memoId], actor);- const memo = await getMemoDetail(db, workspaceId, memoId);- if (!memo) throw new AppError("not_found", "Memo not found after restore", 404);- return memo;+ ctx.waitUntil(resetDemoData(runtimeEnv, controller.scheduledTime, { resetCredentials: true }));+ },};-const emptyTrashMemosRecord = async (- env: Bindings,- workspaceId: string,- actor: { actorType: "user" | "agent"; actorId: string | null }-) => {- const db = env.storage.db;- const countRow = await db- .prepare(- `SELECT COUNT(*) AS count- FROM memos- WHERE workspace_id = ? AND is_deleted = 1`- )- .bind(workspaceId).first<{ count: number }>();- const deleted = countRow?.count ?? 0;-- if (deleted === 0) {- return 0;- }+app.notFound((c) =>+ c.json(+ {+ error: {+ code: "not_found",+ message: "Route not found",+ },+ },+ 404+ )+);- const resourceRows = await db- .prepare(- `SELECT r.object_key, r.storage_config_id- FROM resources r- INNER JOIN memos m ON m.id = r.memo_id- WHERE m.workspace_id = ? AND m.is_deleted = 1`- )- .bind(workspaceId).all<{ object_key: string; storage_config_id: string }>();+app.onError((error, c) => {+ if (error instanceof AppError) {+ return apiError(c, error.code, error.message, error.status);+ }- if (resourceRows.results.length > 0) {- await deleteStoredObjects(env, resourceRows.results);+ if (isDatabaseNotReadyError(error)) {+ console.error("EdgeEver database readiness check failed", error);+ return databaseNotReady(c);}- await db.batch([- db.prepare(`UPDATE resources SET original_memo_id = NULL WHERE original_memo_id IN (SELECT id FROM memos WHERE workspace_id = ? AND is_deleted = 1)`).bind(workspaceId),- db.prepare(`DELETE FROM resources WHERE memo_id IN (SELECT id FROM memos WHERE workspace_id = ? AND is_deleted = 1)`).bind(workspaceId),- db.prepare(`DELETE FROM memo_revisions WHERE memo_id IN (SELECT id FROM memos WHERE workspace_id = ? AND is_deleted = 1)`).bind(workspaceId),- db.prepare(`DELETE FROM memo_contents WHERE memo_id IN (SELECT id FROM memos WHERE workspace_id = ? AND is_deleted = 1)`).bind(workspaceId),- db.prepare(`DELETE FROM memos WHERE workspace_id = ? AND is_deleted = 1`).bind(workspaceId),- auditStatement(db, actor.actorType, actor.actorId, "memo.trash_empty", "trash", "memos", { deleted }),- ]);+ console.error("Unhandled EdgeEver API error", error);+ return apiError(c, "internal_error", "An unexpected server error occurred.", 500);+});++export default worker;- return deleted;-};+export const callMcpTool = (+ context: AppContext,+ auth: AuthContext,+ name: string,+ args: Record<string, unknown>,+) => callMcpToolService(context, auth, name, args, {+ clampNumber,+ createMemoRecord,+ deleteMemosRecord,+ getCurrentWorkspaceIdentity,+ getMemoDetail,+ getMemoDetailRow,+ getMemosForBulkAction,+ importMemosRecord,+ listMemosForMcp,+ mergeMemosRecord,+ moveMemosToNotebook,+ restoreMemosRecord,+ searchMemoSummaries,+ updateMemoRecord,+});const isDemoMode = (env: Bindings) => isDemoModeEnabled(env.EDGE_EVER_DEMO_MODE);const isLocalDemoSeedEnabled = (env: Bindings) =>@@ -2900,1022 +843,6 @@ const resetDemoData = async (}};-const moveMemosToNotebook = async (- db: D1Database,- workspaceId: string,- memoIds: string[],- notebookId: string,- actor: { actorType: "user" | "agent"; actorId: string | null },- actorLabel: string-) => {- const uniqueMemoIds = Array.from(new Set(memoIds));-- if (uniqueMemoIds.length === 0) {- return 0;- }-- const placeholders = uniqueMemoIds.map(() => "?").join(", ");- const rows = await db- .prepare(- `SELECT id, notebook_id- FROM memos- WHERE workspace_id = ? AND is_deleted = 0 AND id IN (${placeholders})`- )- .bind(workspaceId, ...uniqueMemoIds)- .all<{ id: string; notebook_id: string }>();-- if (rows.results.length !== uniqueMemoIds.length) {- throw new AppError("missing_memos", "One or more memos cannot be moved.", 400);- }-- const now = isoNow();- const statements: D1PreparedStatement[] = [- db- .prepare(- `UPDATE memos- SET notebook_id = ?, updated_by = ?, updated_at = ?- WHERE workspace_id = ? AND is_deleted = 0 AND id IN (${placeholders})`- )- .bind(notebookId, actorLabel, now, workspaceId, ...uniqueMemoIds),- ];-- for (const row of rows.results) {- statements.push(- auditStatement(db, actor.actorType, actor.actorId, "memo.move", "memo", row.id, {- fromNotebookId: row.notebook_id,- toNotebookId: notebookId,- })- );- }-- await db.batch(statements);- return uniqueMemoIds.length;-};--const moveMemosRecord = async (- db: D1Database,- workspaceId: string,- memoIds: string[],- notebookId: string,- actor: AuditActor,- actorLabel: string,-) => {- if (!(await getNotebook(db, workspaceId, notebookId))) {- throw new AppError("not_found", "Target notebook not found", 404);- }- return moveMemosToNotebook(db, workspaceId, memoIds, notebookId, actor, actorLabel);-};--export const mergeMemosRecord = async (- db: D1Database,- workspaceId: string,- input: { memoIds: string[]; notebookId?: string; title?: string },- actor: { actorType: "user" | "agent"; actorId: string | null },- actorLabel: string-) => {- const uniqueMemoIds = Array.from(new Set(input.memoIds));-- if (uniqueMemoIds.length < 2) {- throw new AppError("bad_request", "At least two memos are required to merge.", 400);- }-- const placeholders = uniqueMemoIds.map(() => "?").join(", ");- const rows = await 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, c.revision,- c.content_json, c.content_markdown, c.content_text, c.content_hash,- m.source_memo_ids, m.merge_source_count, m.merged_into_memo_id- FROM memos m- INNER JOIN memo_contents c ON c.memo_id = m.id- WHERE m.workspace_id = ? AND m.id IN (${placeholders})`- )- .bind(workspaceId, ...uniqueMemoIds)- .all<MemoDetailRow>();-- if (rows.results.length !== uniqueMemoIds.length) {- throw new AppError("missing_memos", "One or more memos cannot be merged.", 400);- }-- const activeRows = rows.results.filter((row) => !row.is_deleted);- if (activeRows.length !== uniqueMemoIds.length) {- // A desktop outbox retry can arrive after the first merge committed but- // before the client acknowledged its local placeholder. When every source- // now points at the same live merge result, return that result instead of- // treating the retry as a new merge. This makes the operation recoverable- // after a lost response without ever creating a second server-side memo.- const mergedTargetIds = new Set(- rows.results- .filter((row) => row.is_deleted && row.merged_into_memo_id)- .map((row) => row.merged_into_memo_id as string),- );- if (activeRows.length === 0 && mergedTargetIds.size === 1) {- const [mergedTargetId] = mergedTargetIds;- const completedMerge = await getMemoDetail(db, workspaceId, mergedTargetId);- const completedSourceIds = new Set(completedMerge?.sourceMemoIds ?? []);- if (- completedMerge- && completedMerge.sourceMemoIds.length === uniqueMemoIds.length- && uniqueMemoIds.every((memoId) => completedSourceIds.has(memoId))- ) {- return completedMerge;- }- }- throw new AppError("missing_memos", "One or more memos cannot be merged.", 400);- }-- if (input.notebookId && !(await getNotebook(db, workspaceId, input.notebookId))) {- throw new AppError("not_found", "Target notebook not found", 404);- }-- const ordered = uniqueMemoIds- .map((memoId) => rows.results.find((row) => row.id === memoId))- .filter((row): row is MemoDetailRow => Boolean(row));- const notebookId = input.notebookId ?? ordered[0].notebook_id;- const title = resolveMergedMemoTitle(input.title, ordered);- const sourceDocs = ordered.map((memo) => {- const contentJson = parseDoc(memo.content_json);- const doc = resolveMemoContentDoc(contentJson, memo.content_markdown);- if (!docToText(doc).trim() && memo.content_text.trim()) {- throw new AppError("merge_content_unavailable", "One or more memo bodies could not be recovered safely.", 409);- }- return doc;- });- const contentJson = mergeMemoDocs(sourceDocs);- const mergedMarkdown = docToMarkdown(contentJson);- const contentText = docToText(contentJson);- const tags = Array.from(new Set(ordered.flatMap((memo) => parseJsonArray(memo.tags_json))));- const excerpt = createExcerpt(contentText || title);- const contentHash = await sha256(mergedMarkdown + JSON.stringify(contentJson));- const newMemoId = createId("memo");- const now = isoNow();-- await db.batch([- db- .prepare(- `INSERT INTO memos (- id, workspace_id, notebook_id, title, excerpt, tags_json, source_memo_ids, merge_source_count,- created_by, updated_by, created_at, updated_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`- )- .bind(- newMemoId,- workspaceId,- notebookId,- title,- excerpt,- JSON.stringify(tags),- JSON.stringify(uniqueMemoIds),- uniqueMemoIds.length,- actorLabel,- actorLabel,- now,- now- ),- db- .prepare(- `INSERT INTO memo_contents (- memo_id, content_json, content_markdown, content_text, content_hash, revision, created_at, updated_at- ) VALUES (?, ?, ?, ?, ?, 0, ?, ?)`- )- .bind(newMemoId, JSON.stringify(contentJson), mergedMarkdown, contentText, contentHash, now, now),- upsertMemoSearchDocumentStatement(db, newMemoId, title, contentText, tags.join(" ")),- db- .prepare(- `UPDATE memos- SET is_deleted = 1, deleted_at = ?, merged_into_memo_id = ?, merged_at = ?, updated_at = ?- WHERE workspace_id = ? AND id IN (${placeholders})`- )- .bind(now, newMemoId, now, now, workspaceId, ...uniqueMemoIds),- db.prepare(`DELETE FROM memo_shares WHERE workspace_id = ? AND memo_id IN (${placeholders})`).bind(workspaceId, ...uniqueMemoIds),- deleteMemoSearchDocumentsStatement(db, uniqueMemoIds),- db- .prepare(- `UPDATE resources- SET original_memo_id = COALESCE(original_memo_id, memo_id),- memo_id = ?,- updated_at = ?- WHERE memo_id IN (${placeholders})`- )- .bind(newMemoId, now, ...uniqueMemoIds),- auditStatement(db, actor.actorType, actor.actorId, "memo.merge", "memo", newMemoId, {- sourceMemoIds: uniqueMemoIds,- }),- ]);-- const memo = await getMemoDetail(db, workspaceId, newMemoId);-- if (!memo) {- throw new AppError("not_found", "Merged memo not found after create.", 404);- }-- return memo;-};--const createMemoRecord = async (- db: D1Database,- workspaceId: string,- input: { notebookId: string; title?: string; contentMarkdown?: string; tags?: string[]; createdAt?: string; updatedAt?: string },- actor: { actorType: "user" | "agent"; actorId: string | null },- actorLabel: string-): Promise<MemoDetail> => {- const tags = normalizeTags(input.tags);- const contentMarkdown = input.contentMarkdown ?? "";- const contentJson = markdownToDoc(contentMarkdown);- const contentText = docToText(contentJson);- const title = normalizeMemoTitle(input.title);- const excerpt = createExcerpt(contentText);- const contentHash = await sha256(contentMarkdown + JSON.stringify(contentJson));- const id = createId("memo");- const now = isoNow();- const createdAt = input.createdAt ?? now;- const updatedAt = input.updatedAt ?? now;-- await db.batch([- db- .prepare(- `INSERT INTO memos (- id, workspace_id, notebook_id, title, excerpt, tags_json, created_by, updated_by, created_at, updated_at- ) SELECT ?, ?, id, ?, ?, ?, ?, ?, ?, ? FROM notebooks WHERE id = ? AND workspace_id = ? AND is_deleted = 0`- )- .bind(id, workspaceId, title, excerpt, JSON.stringify(tags), actorLabel, actorLabel, createdAt, updatedAt, input.notebookId, workspaceId),- db- .prepare(- `INSERT INTO memo_contents (- memo_id, content_json, content_markdown, content_text, content_hash, revision, created_at, updated_at- ) VALUES (?, ?, ?, ?, ?, 0, ?, ?)`- )- .bind(id, JSON.stringify(contentJson), contentMarkdown, contentText, contentHash, createdAt, updatedAt),- upsertMemoSearchDocumentStatement(db, id, title, contentText, tags.join(" ")),- auditStatement(db, actor.actorType, actor.actorId, "memo.create", "memo", id, {- notebookId: input.notebookId,- }),- ]);-- const memo = await getMemoDetail(db, workspaceId, id);-- if (!memo) {- throw new Error("Memo was created but could not be read.");- }-- return memo;-};--const normalizeImportSource = (value: string) => {- const source = value.trim().toLocaleLowerCase("en-US");- if (source.length > 80 || !/^[a-z0-9._-]+$/.test(source)) {- throw new AppError(- "invalid_import_source",- "source must contain only letters, numbers, dots, underscores, or hyphens and be at most 80 characters",- 400,- );- }- return source;-};--const parseImportDateTime = (value: unknown, field: string) => {- if (value === undefined) {- return undefined;- }- if (typeof value !== "string" || !value.trim() || Number.isNaN(Date.parse(value))) {- throw new Error(`${field} must be a valid ISO 8601 date-time`);- }- return value.trim();-};--const parseMemoImportItem = (value: unknown, index: number) => {- if (!value || typeof value !== "object" || Array.isArray(value)) {- throw new Error(`items[${index}] must be an object`);- }-- const item = value as Record<string, unknown>;- const externalId = getRequiredString(item.externalId, `items[${index}].externalId`);- if (externalId.length > 512) {- throw new Error(`items[${index}].externalId must be at most 512 characters`);- }- if (item.title !== undefined && typeof item.title !== "string") {- throw new Error(`items[${index}].title must be a string`);- }- const title = typeof item.title === "string" ? item.title.trim() : undefined;- if (title && title.length > 160) {- throw new Error(`items[${index}].title must be at most 160 characters`);- }- if (item.contentMarkdown !== undefined && typeof item.contentMarkdown !== "string") {- throw new Error(`items[${index}].contentMarkdown must be a string`);- }- if (item.tags !== undefined && (!Array.isArray(item.tags) || item.tags.some((tag) => typeof tag !== "string"))) {- throw new Error(`items[${index}].tags must be an array of strings`);- }- if (Array.isArray(item.tags) && item.tags.length > 100) {- throw new Error(`items[${index}].tags must contain at most 100 items`);- }-- return {- externalId,- title: title || undefined,- contentMarkdown: typeof item.contentMarkdown === "string" ? item.contentMarkdown : "",- tags: Array.isArray(item.tags) ? (item.tags as string[]) : [],- createdAt: parseImportDateTime(item.createdAt, `items[${index}].createdAt`),- updatedAt: parseImportDateTime(item.updatedAt, `items[${index}].updatedAt`),- };-};--const getMemoImportSource = async (db: D1Database, workspaceId: string, source: string, externalId: string) =>- db.prepare(- `SELECT external_id, memo_id, source_updated_at- FROM memo_import_sources- WHERE workspace_id = ? AND source = ? AND external_id = ?`- ).bind(workspaceId, source, externalId).first<MemoImportSourceRow>();--const discardUnlinkedImportedMemo = async (db: D1Database, workspaceId: string, memoId: string) => {- await db.batch([- db.prepare(`DELETE FROM memo_revisions WHERE memo_id = ?`).bind(memoId),- db.prepare(`DELETE FROM memo_contents WHERE memo_id = ?`).bind(memoId),- db.prepare(`DELETE FROM memos WHERE id = ? AND workspace_id = ?`).bind(memoId, workspaceId),- ]);-};--const importMemosRecord = async (- db: D1Database,- workspaceId: string,- input: {- source: string;- notebookId: string;- items: unknown;- dryRun: boolean;- actor: { actorType: "user" | "agent"; actorId: string | null };- actorLabel: string;- },-) => {- const source = normalizeImportSource(input.source);- if (!Array.isArray(input.items) || input.items.length === 0 || input.items.length > 25) {- throw new AppError("invalid_import_items", "items must contain between 1 and 25 memos", 400);- }- const notebook = await getNotebook(db, workspaceId, input.notebookId);- if (!notebook) {- throw new AppError("not_found", "Import destination notebook not found in the authenticated user's workspace.", 404);- }-- const results: Array<Record<string, unknown>> = [];-- for (const [index, rawItem] of input.items.entries()) {- let externalId: string | null = null;- let createdMemoId: string | null = null;-- try {- const item = parseMemoImportItem(rawItem, index);- externalId = item.externalId;- const existing = await getMemoImportSource(db, workspaceId, source, externalId);- if (existing) {- results.push({- index,- externalId,- status: "skipped",- reason: "already_imported",- memo: await getMemoDetail(db, workspaceId, existing.memo_id, true),- sourceUpdatedAt: existing.source_updated_at,- });- continue;- }-- if (input.dryRun) {- results.push({ index, externalId, status: "would_create" });- continue;- }-- const memo = await createMemoRecord(db, workspaceId, {- notebookId: notebook.id,- title: item.title,- contentMarkdown: item.contentMarkdown,- tags: item.tags,- createdAt: item.createdAt,- updatedAt: item.updatedAt,- }, input.actor, input.actorLabel);- createdMemoId = memo.id;- const now = isoNow();- await db.batch([- db.prepare(- `INSERT INTO memo_import_sources (- workspace_id, source, external_id, memo_id, source_updated_at, content_hash, created_at, updated_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`- ).bind(workspaceId, source, externalId, memo.id, item.updatedAt ?? null, memo.contentHash, now, now),- auditStatement(db, input.actor.actorType, input.actor.actorId, "memo.import", "memo", memo.id, {- source,- externalId,- notebookId: notebook.id,- }),- ]);- results.push({ index, externalId, status: "created", memo });- } catch (error) {- if (createdMemoId) {- await discardUnlinkedImportedMemo(db, workspaceId, createdMemoId);- const winner = externalId ? await getMemoImportSource(db, workspaceId, source, externalId) : null;- if (winner) {- results.push({- index,- externalId,- status: "skipped",- reason: "already_imported",- memo: await getMemoDetail(db, workspaceId, winner.memo_id, true),- sourceUpdatedAt: winner.source_updated_at,- });- continue;- }- }-- results.push({- index,- externalId,- status: "failed",- error: error instanceof Error ? error.message : "Import failed",- });- }- }-- const count = (status: string) => results.filter((result) => result.status === status).length;- return {- dryRun: input.dryRun,- source,- notebookId: notebook.id,- total: results.length,- created: count("created"),- skipped: count("skipped"),- failed: count("failed"),- wouldCreate: count("would_create"),- results,- };-};--export const updateMemoRecord = async (- db: D1Database,- workspaceId: string,- id: string,- input: MemoUpdateInput,- actor: { actorType: "user" | "agent"; actorId: string | null },- actorLabel: string,- requireEditSession = false,-): Promise<- | { memo: MemoDetail; error?: never; message?: never; status?: never; details?: never }- | { error: string; message: string; status?: number; details?: Record<string, unknown> }-> => {- const current = await getMemoDetailRow(db, workspaceId, id);-- if (!current) {- return { error: "not_found", message: "Memo not found" };- }-- if (input.expectedRevision !== undefined && input.expectedRevision !== current.revision) {- return {- error: "revision_conflict",- message: "Memo was updated elsewhere. Reload before saving.",- status: 409,- details: {- expectedRevision: input.expectedRevision,- currentRevision: current.revision,- },- };- }-- const hasDocumentUpdate = input.contentJson !== undefined || input.contentMarkdown !== undefined;- let editSession: MemoEditSessionRow | null = null;-- if (requireEditSession && hasDocumentUpdate) {- if (!input.editSessionId || !input.expectedContentHash || input.expectedRevision === undefined) {- return {- error: "edit_session_required",- message: "A bound edit session is required to save note content.",- status: 428,- };- }-- if (input.expectedContentHash !== current.content_hash) {- return {- error: "content_conflict",- message: "Note content changed after this edit session started.",- status: 409,- };- }-- editSession = await db.prepare(- `SELECT id, memo_id, actor_type, actor_id, base_revision, base_content_hash, expires_at- FROM memo_edit_sessions- WHERE id = ? AND memo_id = ? AND actor_type = ? AND actor_id IS ? AND expires_at > ?`,- )- .bind(input.editSessionId, id, actor.actorType, actor.actorId, isoNow())- .first<MemoEditSessionRow>();-- if (- !editSession ||- !isMemoEditBindingValid(- { memoId: id, revision: current.revision, contentHash: current.content_hash },- {- id: editSession.id,- memoId: editSession.memo_id,- baseRevision: editSession.base_revision,- baseContentHash: editSession.base_content_hash,- },- {- editSessionId: input.editSessionId,- memoId: id,- expectedRevision: input.expectedRevision,- expectedContentHash: input.expectedContentHash,- },- )- ) {- return {- error: "edit_session_conflict",- message: "The edit session is stale or belongs to another note.",- status: 409,- };- }- }-- const isPinned = input.isPinned ?? Boolean(current.is_pinned);- const hasContentUpdate =- input.notebookId !== undefined ||- input.title !== undefined ||- input.contentJson !== undefined ||- input.contentMarkdown !== undefined ||- input.tags !== undefined ||- input.createdAt !== undefined ||- input.updatedAt !== undefined;- const now = isoNow();- const updatedAt = input.updatedAt ?? now;-- if (!hasContentUpdate) {- if (input.isPinned === undefined || isPinned === Boolean(current.is_pinned)) {- const memo = await getMemoDetail(db, workspaceId, id);-- if (!memo) {- return { error: "not_found", message: "Memo not found after update" };- }-- return { memo };- }-- await db.batch([- db- .prepare(- `UPDATE memos- SET is_pinned = ?, updated_by = ?, updated_at = ?, created_at = COALESCE(?, created_at)- WHERE id = ? AND workspace_id = ? AND is_deleted = 0`- )- .bind(isPinned ? 1 : 0, actorLabel, updatedAt, input.createdAt ?? null, id, workspaceId),- auditStatement(db, actor.actorType, actor.actorId, isPinned ? "memo.pin" : "memo.unpin", "memo", id, {}),- ]);-- const memo = await getMemoDetail(db, workspaceId, id);-- if (!memo) {- return { error: "not_found", message: "Memo not found after update" };- }-- return { memo };- }-- const currentContentJson = parseDoc(current.content_json);- const contentJson =- input.contentJson !== undefined- ? input.contentJson- : input.contentMarkdown !== undefined- ? markdownToDoc(input.contentMarkdown)- : currentContentJson;- const contentMarkdown =- input.contentMarkdown !== undefined- ? input.contentMarkdown- : input.contentJson !== undefined- ? docToMarkdown(contentJson)- : current.content_markdown;- const contentText = hasDocumentUpdate ? docToText(contentJson) : current.content_text;- const title =- input.title !== undefined ? normalizeMemoTitle(input.title) : normalizeMemoTitle(current.title);- if (- !input.allowDestructiveOverwrite &&- isSuspiciousMemoOverwrite(current.title, current.content_text, title, contentText)- ) {- return {- error: "suspicious_memo_overwrite",- message: "Save blocked because the title changed while most of the note content disappeared.",- };- }- const tags = input.tags === undefined ? parseJsonArray(current.tags_json) : normalizeTags(input.tags);- const excerpt = createExcerpt(contentText);- const notebookId = input.notebookId ?? current.notebook_id;- const contentHash = await sha256(contentMarkdown + JSON.stringify(contentJson));- const unchanged =- notebookId === current.notebook_id- && title === normalizeMemoTitle(current.title)- && JSON.stringify(tags) === current.tags_json- && isPinned === Boolean(current.is_pinned)- && contentHash === current.content_hash- && input.createdAt === undefined- && input.updatedAt === undefined;-- if (unchanged) {- return { memo: mapMemoDetail(current) };- }-- const nextRevision = current.revision + 1;- const revisionStatements = (await shouldSnapshotMemoRevision(db, current, title, JSON.stringify(tags), contentHash, updatedAt))- ? [createMemoRevisionStatement(db, current, actorLabel, updatedAt)]- : [];- const editSessionStatements = editSession- ? [- db.prepare(- `UPDATE memo_edit_sessions- SET base_revision = ?, base_content_hash = ?, updated_at = ?- WHERE id = ? AND memo_id = ? AND base_revision = ? AND base_content_hash = ?`,- ).bind(nextRevision, contentHash, updatedAt, editSession.id, id, current.revision, current.content_hash),- ]- : requireEditSession- ? [- db.prepare(- `UPDATE memo_edit_sessions- SET base_revision = ?, base_content_hash = ?, updated_at = ?- WHERE memo_id = ? AND actor_type = ? AND actor_id IS ?- AND base_revision = ? AND base_content_hash = ? AND expires_at > ?`,- ).bind(- nextRevision,- contentHash,- updatedAt,- id,- actor.actorType,- actor.actorId,- current.revision,- current.content_hash,- updatedAt,- ),- ]- : [];-- await db.batch([- ...revisionStatements,- db- .prepare(- `UPDATE memos- SET notebook_id = ?, title = ?, excerpt = ?, tags_json = ?, is_pinned = ?, updated_by = ?, updated_at = ?, created_at = COALESCE(?, created_at)- WHERE id = ? AND workspace_id = ? AND is_deleted = 0- AND EXISTS (SELECT 1 FROM notebooks n WHERE n.id = ? AND n.workspace_id = ? AND n.is_deleted = 0)`- )- .bind(notebookId, title, excerpt, JSON.stringify(tags), isPinned ? 1 : 0, actorLabel, updatedAt, input.createdAt ?? null, id, workspaceId, notebookId, workspaceId),- db- .prepare(- `UPDATE memo_contents- SET content_json = ?, content_markdown = ?, content_text = ?, content_hash = ?,- revision = ?, updated_at = ?, created_at = COALESCE(?, created_at)- WHERE memo_id = ?`- )- .bind(JSON.stringify(contentJson), contentMarkdown, contentText, contentHash, nextRevision, updatedAt, input.createdAt ?? null, id),- upsertMemoSearchDocumentStatement(db, id, title, contentText, tags.join(" ")),- ...editSessionStatements,- auditStatement(db, actor.actorType, actor.actorId, "memo.update", "memo", id, {- revision: nextRevision,- }),- ]);-- const memo = await getMemoDetail(db, workspaceId, id);-- if (!memo) {- return { error: "not_found", message: "Memo not found after update" };- }-- return { memo };-};--const getMemoRevisionRow = async (- db: D1Database,- workspaceId: string,- memoId: string,- revisionId: string-): Promise<MemoRevisionRow | null> =>- db- .prepare(- `SELECT mr.id, mr.memo_id, mr.revision, mr.title, mr.tags_json, mr.content_json, mr.content_markdown,- mr.content_text, mr.content_hash, mr.created_by, mr.created_at- FROM memo_revisions mr- INNER JOIN memos m ON m.id = mr.memo_id- WHERE mr.id = ? AND mr.memo_id = ? AND m.workspace_id = ?`- )- .bind(revisionId, memoId, workspaceId)- .first<MemoRevisionRow>();--const listMemoRevisions = async (- db: D1Database,- workspaceId: string,- memoId: string,- limit: number,- includeDeleted = true,-): Promise<MemoRevision[]> => {- const memo = await getMemoDetail(db, workspaceId, memoId, includeDeleted);-- if (!memo) {- throw new AppError("not_found", "Memo not found", 404);- }-- const rows = await db- .prepare(- `SELECT id, memo_id, revision, title, tags_json, content_json, content_markdown,- content_text, content_hash, created_by, created_at- FROM memo_revisions- WHERE memo_id = ?- ORDER BY revision DESC, created_at DESC- LIMIT ?`- )- .bind(memoId, limit)- .all<MemoRevisionRow>();-- return rows.results.map(mapMemoRevision);-};--const restoreMemoRevisionRecord = async (- db: D1Database,- workspaceId: string,- memoId: string,- revisionId: string,- actor: { actorType: "user" | "agent"; actorId: string | null },- actorLabel: string-) => {- const current = await getMemoDetailRow(db, workspaceId, memoId);-- if (!current) {- throw new AppError("not_found", "Memo not found", 404);- }-- const revision = await getMemoRevisionRow(db, workspaceId, memoId, revisionId);-- if (!revision) {- throw new AppError("not_found", "Memo revision not found", 404);- }-- const tags = parseJsonArray(revision.tags_json);- const contentJson = parseDoc(revision.content_json);- const contentMarkdown = revision.content_markdown || docToMarkdown(contentJson);- const contentText = revision.content_text || docToText(contentJson);- const title = normalizeMemoTitle(revision.title);- const excerpt = createExcerpt(contentText);- const contentHash = await sha256(contentMarkdown + JSON.stringify(contentJson));- const nextRevision = current.revision + 1;- const now = isoNow();-- await db.batch([- createMemoRevisionStatement(db, current, actorLabel, now),- db- .prepare(- `UPDATE memos- SET title = ?, excerpt = ?, tags_json = ?, updated_by = ?, updated_at = ?- WHERE id = ? AND workspace_id = ? AND is_deleted = 0`- )- .bind(title, excerpt, JSON.stringify(tags), actorLabel, now, memoId, workspaceId),- db- .prepare(- `UPDATE memo_contents- SET content_json = ?, content_markdown = ?, content_text = ?, content_hash = ?,- revision = ?, updated_at = ?- WHERE memo_id = ?`- )- .bind(JSON.stringify(contentJson), contentMarkdown, contentText, contentHash, nextRevision, now, memoId),- upsertMemoSearchDocumentStatement(db, memoId, title, contentText, tags.join(" ")),- auditStatement(db, actor.actorType, actor.actorId, "memo.revision_restore", "memo", memoId, {- revisionId,- restoredRevision: revision.revision,- revision: nextRevision,- }),- ]);-- const memo = await getMemoDetail(db, workspaceId, memoId);-- if (!memo) {- throw new AppError("not_found", "Memo not found after revision restore", 404);- }-- return memo;-};--const getLatestMemoRevisionRow = async (db: D1Database, memoId: string): Promise<MemoRevisionRow | null> =>- db- .prepare(- `SELECT id, memo_id, revision, title, tags_json, content_json, content_markdown,- content_text, content_hash, created_by, created_at- FROM memo_revisions- WHERE memo_id = ?- ORDER BY created_at DESC, revision DESC- LIMIT 1`- )- .bind(memoId)- .first<MemoRevisionRow>();--const createMemoRevisionStatement = (- db: D1Database,- current: MemoDetailRow,- actorLabel: string,- createdAt: string-) =>- db- .prepare(- `INSERT INTO memo_revisions (- id, memo_id, revision, title, content_json, content_markdown,- content_hash, created_by, created_at, tags_json, content_text- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`- )- .bind(- createId("rev"),- current.id,- current.revision,- current.title,- current.content_json,- current.content_markdown,- current.content_hash,- actorLabel,- createdAt,- current.tags_json,- current.content_text- );--const shouldSnapshotMemoRevision = async (- db: D1Database,- current: MemoDetailRow,- nextTitle: string | null,- nextTagsJson: string,- nextContentHash: string,- now: string-) => {- const changed =- (current.title ?? "") !== (nextTitle ?? "") ||- current.tags_json !== nextTagsJson ||- current.content_hash !== nextContentHash;-- if (!changed) {- return false;- }-- const latest = await getLatestMemoRevisionRow(db, current.id);-- if (!latest) {- return true;- }-- const alreadyCapturedCurrent =- (latest.title ?? "") === (current.title ?? "") &&- latest.tags_json === current.tags_json &&- latest.content_hash === current.content_hash;-- if (alreadyCapturedCurrent) {- return false;- }-- return Date.parse(now) - Date.parse(latest.created_at) >= REVISION_SNAPSHOT_INTERVAL_MS;-};--const getResourceRow = async (- db: D1Database,- workspaceId: string,- id: string,- includeDeleted = false,-): Promise<ResourceRow | null> =>- db- .prepare(- `SELECT r.id, r.memo_id, r.original_memo_id, r.bucket_name, r.object_key, r.storage_config_id, r.kind, r.mime_type,- r.filename, r.byte_size, r.sha256, r.width, r.height, r.created_at, r.updated_at, r.is_deleted- FROM resources r- INNER JOIN memos m ON m.id = r.memo_id- WHERE r.id = ? AND m.workspace_id = ?${includeDeleted ? "" : " AND r.is_deleted = 0"}`- )- .bind(id, workspaceId)- .first<ResourceRow>();--const getResourceRowsForMemo = async (db: D1Database, workspaceId: string, memoId: string): Promise<ResourceRow[]> => {- const rows = await db- .prepare(- `SELECT r.id, r.memo_id, r.original_memo_id, r.bucket_name, r.object_key, r.storage_config_id, r.kind, r.mime_type,- r.filename, r.byte_size, r.sha256, r.width, r.height, r.created_at, r.updated_at- FROM resources r- INNER JOIN memos m ON m.id = r.memo_id- WHERE r.memo_id = ? AND m.workspace_id = ?`- )- .bind(memoId, workspaceId)- .all<ResourceRow>();-- return rows.results;-};--const listResourcesForMemo = async (db: D1Database, workspaceId: string, memoId: string): Promise<Resource[]> => {- const rows = await db- .prepare(- `SELECT r.id, r.memo_id, r.original_memo_id, r.bucket_name, r.object_key, r.storage_config_id, r.kind, r.mime_type,- r.filename, r.byte_size, r.sha256, r.width, r.height, r.created_at, r.updated_at- FROM resources r- INNER JOIN memos m ON m.id = r.memo_id- WHERE r.memo_id = ? AND m.workspace_id = ? AND r.is_deleted = 0- ORDER BY r.created_at ASC, r.id ASC`- )- .bind(memoId, workspaceId)- .all<ResourceRow>();-- return rows.results.map(mapResource);-};--const listResourcesForMcp = async (db: D1Database, workspaceId: string, limit: number) => {- const [rows, stats] = await Promise.all([- db- .prepare(- `SELECT r.id, r.memo_id, r.original_memo_id, r.bucket_name, r.object_key, r.storage_config_id, r.kind,- r.mime_type, r.filename, r.byte_size, r.sha256, r.width, r.height,- r.created_at, r.updated_at, m.title AS memo_title, m.excerpt AS memo_excerpt,- m.is_deleted AS memo_is_deleted- FROM resources r- INNER JOIN memos m ON m.id = r.memo_id- WHERE m.workspace_id = ? AND r.is_deleted = 0- ORDER BY r.created_at DESC- LIMIT ?`- )- .bind(workspaceId, limit)- .all<ResourceListRow>(),- db- .prepare(- `SELECT COUNT(*) AS total_count,- COALESCE(SUM(byte_size), 0) AS total_bytes,- COALESCE(SUM(CASE WHEN kind = 'image' THEN 1 ELSE 0 END), 0) AS image_count,- COALESCE(SUM(CASE WHEN kind = 'attachment' THEN 1 ELSE 0 END), 0) AS attachment_count- FROM resources r- INNER JOIN memos m ON m.id = r.memo_id- WHERE m.workspace_id = ? AND r.is_deleted = 0`- )- .bind(workspaceId).first<ResourceStatsRow>(),- ]);-- return {- resources: rows.results.map(mapResourceListItem),- summary: mapResourceStorageSummary(stats),- };-};--const getWorkspaceStats = async (db: D1Database, workspaceId: string) => {- const [memoCounts, notebookCount, tagCount, resourceStats] = await Promise.all([- db- .prepare(- `SELECT- COUNT(*) AS total,- COALESCE(SUM(CASE WHEN is_deleted = 0 THEN 1 ELSE 0 END), 0) AS active,- COALESCE(SUM(CASE WHEN is_deleted = 1 THEN 1 ELSE 0 END), 0) AS trashed,- COALESCE(SUM(CASE WHEN is_deleted = 0 AND is_pinned = 1 THEN 1 ELSE 0 END), 0) AS pinned,- COALESCE(SUM(CASE WHEN is_deleted = 0 AND tags_json = '[]' THEN 1 ELSE 0 END), 0) AS untagged- FROM memos WHERE workspace_id = ?`- )- .bind(workspaceId).first<{ total: number; active: number; trashed: number; pinned: number; untagged: number }>(),- db.prepare(`SELECT COUNT(*) AS count FROM notebooks WHERE workspace_id = ? AND is_deleted = 0`).bind(workspaceId).first<{ count: number }>(),- db- .prepare(- `SELECT COUNT(DISTINCT mt.name) AS count- FROM memo_tags mt- INNER JOIN memos m ON m.id = mt.memo_id AND m.workspace_id = mt.workspace_id- WHERE mt.workspace_id = ? AND m.is_deleted = 0`- )- .bind(workspaceId).first<{ count: number }>(),- db- .prepare(- `SELECT COUNT(*) AS total_count,- COALESCE(SUM(byte_size), 0) AS total_bytes,- COALESCE(SUM(CASE WHEN kind = 'image' THEN 1 ELSE 0 END), 0) AS image_count,- COALESCE(SUM(CASE WHEN kind = 'attachment' THEN 1 ELSE 0 END), 0) AS attachment_count- FROM resources r- INNER JOIN memos m ON m.id = r.memo_id- WHERE m.workspace_id = ? AND r.is_deleted = 0`- )- .bind(workspaceId).first<ResourceStatsRow>(),- ]);-- return {- memos: {- total: memoCounts?.total ?? 0,- active: memoCounts?.active ?? 0,- trashed: memoCounts?.trashed ?? 0,- pinned: memoCounts?.pinned ?? 0,- untagged: memoCounts?.untagged ?? 0,- },- notebooks: {- active: notebookCount?.count ?? 0,- },- tags: {- active: tagCount?.count ?? 0,- },- resources: mapResourceStorageSummary(resourceStats),- };-};--const parseDoc = (json: string): TiptapDoc => {- try {- const value = JSON.parse(json);- return value && typeof value === "object" ? (value as TiptapDoc) : emptyDoc();- } catch {- return emptyDoc();- }-};--const normalizeMemoTitle = (value: string | null | undefined) => {- const title = value?.trim();- return title || DEFAULT_MEMO_TITLE;-};-const clampNumber = (value: number, min: number, max: number) => {if (Number.isNaN(value)) {return min;@@ -3923,19 +850,3 @@ const clampNumber = (value: number, min: number, max: number) => {return Math.min(Math.max(value, min), max);};--const sha256 = async (value: string) => {- const bytes = new TextEncoder().encode(value);- return sha256Bytes(bytes);-};--const sha256Bytes = async (bytes: Uint8Array) => {- const digest = await crypto.subtle.digest("SHA-256", bytes.slice());- const hashArray = new Uint8Array(digest);- let hexString = "";- for (let i = 0; i < hashArray.length; i++) {- const hex = hashArray[i].toString(16);- hexString += hex.length === 1 ? "0" + hex : hex;- }- return hexString;-};diff --git a/apps/api/src/mcp-tool-service.ts b/apps/api/src/mcp-tool-service.tsnew file mode 100644index 00000000..e8a3a2c5--- /dev/null+++ b/apps/api/src/mcp-tool-service.ts@@ -0,0 +1,866 @@+import {+ AiPromptTemplateCreateSchema,+ AiPromptTemplateUpdateSchema,+ TemplateCreateSchema,+ TemplateUpdateSchema,+ markdownToDoc,+ type MemoDetail,+ type MemoSummary,+ type MemoUpdateInput,+} from "@edgeever/shared";+import { audit, auditStatement } from "./audit";+import type { AppContext, AuditActor, AuthContext, Bindings } from "./api-context";+import { AppError } from "./app-error";+import { isDemoModeEnabled } from "./demo-mode";+import { createId, isoNow } from "./entity-utils";+import {+ decodeBase64Data,+ escapeMarkdownImageAlt,+ escapeMarkdownLinkLabel,+ getOptionalString,+ getOptionalStringArray,+ getRequiredString,+ getRequiredStringArray,+} from "./mcp-json-rpc";+import {+ getMemoRevisionRow as getMemoRevisionRowService,+ listMemoRevisions as listMemoRevisionsService,+ mapMemoRevision as mapMemoRevisionService,+ restoreMemoRevision as restoreMemoRevisionService,+ type MemoRevisionSourceRow,+} from "./memo-revision-service";+import {+ createNotebookRecord,+ findNotebooks,+ getNotebook,+ listNotebooks,+ resolveNotebookPath,+ updateNotebookRecord,+} from "./notebook-service";+import {+ createAttachmentResource,+ createImageResource,+ inferImageExtension,+ listResourcesForMcp,+ listResourcesForMemo,+ normalizeFilename,+ } from "./resource-service";+import { assertScope, getActorLabel, getAuditActor } from "./request-auth";+import { restoreMissingDefaultAiPrompts } from "./ai-prompt-seed";+import {+ getAiPromptTemplateRow,+ listAiPromptTemplates,+ mapAiPromptTemplateRow,+} from "./ai-prompt-service";+import { getMemoTemplate, listMemoTemplates } from "./template-routes";+import {+ listTagSummaries,+ previewTagRename,+ updateTagAcrossMemos,+ updateTagsForMemos,+} from "./tag-service";+ import type { DatabaseAdapter } from "./storage-contract";+ import { getWorkspaceStats } from "./workspace-stats-service";++type MemoUpdateResult =+ | { memo: MemoDetail; error?: never; message?: never; status?: never; details?: never }+ | { error: string; message: string; status?: number; details?: Record<string, unknown> };++export type McpToolDependencies = {+ clampNumber: (value: number, min: number, max: number) => number;+ createMemoRecord: (+ database: DatabaseAdapter,+ workspaceId: string,+ input: { notebookId: string; title?: string; contentMarkdown?: string; tags?: string[]; createdAt?: string; updatedAt?: string },+ actor: AuditActor,+ actorLabel: string,+ ) => Promise<MemoDetail>;+ deleteMemosRecord: (+ environment: Bindings,+ workspaceId: string,+ memoIds: string[],+ permanent: boolean,+ actor: AuditActor,+ ) => Promise<number>;+ getCurrentWorkspaceIdentity: (database: DatabaseAdapter, auth: AuthContext) => Promise<unknown>;+ getMemoDetail: (+ database: DatabaseAdapter,+ workspaceId: string,+ memoId: string,+ includeDeleted?: boolean,+ ) => Promise<MemoDetail | null>;+ getMemoDetailRow: (+ database: DatabaseAdapter,+ workspaceId: string,+ memoId: string,+ ) => Promise<MemoRevisionSourceRow | null>;+ getMemosForBulkAction: (+ database: DatabaseAdapter,+ workspaceId: string,+ memoIds: string[],+ deletedState: 0 | 1,+ ) => Promise<unknown[]>;+ importMemosRecord: (+ database: DatabaseAdapter,+ workspaceId: string,+ input: {+ source: string;+ notebookId: string;+ items: unknown;+ dryRun: boolean;+ actor: AuditActor;+ actorLabel: string;+ },+ ) => Promise<unknown>;+ listMemosForMcp: (+ database: DatabaseAdapter,+ options: {+ workspaceId: string;+ notebookId?: string | null;+ limit: number;+ offset: number;+ includeContent: boolean;+ includeDeleted: boolean;+ },+ ) => Promise<unknown>;+ mergeMemosRecord: (+ database: DatabaseAdapter,+ workspaceId: string,+ input: { memoIds: string[]; notebookId?: string; title?: string },+ actor: AuditActor,+ actorLabel: string,+ ) => Promise<MemoDetail>;+ moveMemosToNotebook: (+ database: DatabaseAdapter,+ workspaceId: string,+ memoIds: string[],+ notebookId: string,+ actor: AuditActor,+ actorLabel: string,+ ) => Promise<number>;+ restoreMemosRecord: (+ database: DatabaseAdapter,+ workspaceId: string,+ memoIds: string[],+ actor: AuditActor,+ ) => Promise<number>;+ searchMemoSummaries: (+ database: DatabaseAdapter,+ options: {+ workspaceId: string;+ query?: string | null;+ notebookId?: string | null;+ tags?: string[];+ createdAfter?: string | null;+ createdBefore?: string | null;+ updatedAfter?: string | null;+ updatedBefore?: string | null;+ isPinned?: boolean | null;+ hasResources?: boolean | null;+ limit: number;+ },+ ) => Promise<MemoSummary[]>;+ updateMemoRecord: (+ database: DatabaseAdapter,+ workspaceId: string,+ memoId: string,+ input: MemoUpdateInput,+ actor: AuditActor,+ actorLabel: string,+ requireEditSession?: boolean,+ ) => Promise<MemoUpdateResult>;+};++type McpInputSchema<T> = {+ safeParse: (input: unknown) =>+ | { success: true; data: T }+ | { success: false; error: { issues: Array<{ path: PropertyKey[]; message: string }> } };+};++const parseMcpInput = <T>(schema: McpInputSchema<T>, input: unknown): T => {+ const result = schema.safeParse(input);+ if (result.success) return result.data;+ const message = result.error.issues+ .map((issue) => `${issue.path.join(".") || "arguments"}: ${issue.message}`)+ .join("; ");+ throw new AppError("invalid_params", message, 400);+};++const assertMcpMutationAllowed = (environment: Bindings) => {+ if (isDemoModeEnabled(environment.EDGE_EVER_DEMO_MODE)) {+ throw new AppError("forbidden", "Templates and AI instructions cannot be changed in demo mode.", 403);+ }+};++export const callMcpTool = async (+ c: AppContext,+ auth: AuthContext,+ name: string,+ args: Record<string, unknown>,+ dependencies: McpToolDependencies,+) => {+ const {+ clampNumber,+ createMemoRecord,+ deleteMemosRecord,+ getCurrentWorkspaceIdentity,+ getMemoDetail,+ getMemoDetailRow,+ getMemosForBulkAction,+ importMemosRecord,+ listMemosForMcp,+ mergeMemosRecord,+ moveMemosToNotebook,+ restoreMemosRecord,+ searchMemoSummaries,+ updateMemoRecord,+ } = dependencies;++ switch (name) {+ case "get_current_user": {+ return await getCurrentWorkspaceIdentity(c.env.storage.db, auth);+ }+ case "search_memos": {+ assertScope(auth, "read:memos");+ return {+ memos: await searchMemoSummaries(c.env.storage.db, {+ workspaceId: auth.workspaceId,+ query: getOptionalString(args.query),+ notebookId: getOptionalString(args.notebookId),+ tags: getOptionalStringArray(args.tags),+ createdAfter: getOptionalString(args.createdAfter),+ createdBefore: getOptionalString(args.createdBefore),+ updatedAfter: getOptionalString(args.updatedAfter),+ updatedBefore: getOptionalString(args.updatedBefore),+ isPinned: typeof args.isPinned === "boolean" ? args.isPinned : null,+ hasResources: typeof args.hasResources === "boolean" ? args.hasResources : null,+ limit: clampNumber(Number(args.limit ?? 20), 1, 50),+ }),+ };+ }+ case "list_memos": {+ assertScope(auth, "read:memos");+ return await listMemosForMcp(c.env.storage.db, {+ workspaceId: auth.workspaceId,+ notebookId: getOptionalString(args.notebookId),+ limit: clampNumber(Number(args.limit ?? 50), 1, 100),+ offset: clampNumber(Number(args.offset ?? 0), 0, 100_000),+ includeContent: args.includeContent === true,+ includeDeleted: args.includeDeleted === true,+ });+ }+ case "get_memo": {+ assertScope(auth, "read:memos");+ const memoId = getRequiredString(args.memoId, "memoId");+ const memo = await getMemoDetail(c.env.storage.db, auth.workspaceId, memoId, args.includeDeleted === true);++ if (!memo) {+ throw new Error("Memo not found");+ }++ return { memo };+ }+ case "create_memo": {+ assertScope(auth, "write:memos");+ const notebookId = getRequiredString(args.notebookId, "notebookId");+ const actor = getAuditActor(c);+ const actorLabel = getActorLabel(c);+ const memo = await createMemoRecord(c.env.storage.db, auth.workspaceId, {+ notebookId,+ title: getOptionalString(args.title) ?? undefined,+ contentMarkdown: getOptionalString(args.contentMarkdown) ?? "",+ tags: getOptionalStringArray(args.tags),+ createdAt: getOptionalString(args.createdAt) ?? undefined,+ updatedAt: getOptionalString(args.updatedAt) ?? undefined,+ }, actor, actorLabel);++ return { memo };+ }+ case "import_memos": {+ assertScope(auth, "write:memos");+ return await importMemosRecord(c.env.storage.db, auth.workspaceId, {+ source: getRequiredString(args.source, "source"),+ notebookId: getRequiredString(args.notebookId, "notebookId"),+ items: args.items,+ dryRun: args.dryRun === true,+ actor: getAuditActor(c),+ actorLabel: getActorLabel(c),+ });+ }+ case "update_memo": {+ assertScope(auth, "write:memos");+ const memoId = getRequiredString(args.memoId, "memoId");+ const actor = getAuditActor(c);+ const actorLabel = getActorLabel(c);+ const result = await updateMemoRecord(+ c.env.storage.db,+ auth.workspaceId,+ memoId,+ {+ expectedRevision:+ typeof args.expectedRevision === "number" && Number.isInteger(args.expectedRevision)+ ? args.expectedRevision+ : undefined,+ notebookId: getOptionalString(args.notebookId) ?? undefined,+ title: getOptionalString(args.title) ?? undefined,+ isPinned: typeof args.isPinned === "boolean" ? args.isPinned : undefined,+ contentMarkdown: getOptionalString(args.contentMarkdown) ?? undefined,+ tags: Array.isArray(args.tags) ? getOptionalStringArray(args.tags) : undefined,+ createdAt: getOptionalString(args.createdAt) ?? undefined,+ updatedAt: getOptionalString(args.updatedAt) ?? undefined,+ },+ actor,+ actorLabel+ );++ if ("error" in result) {+ throw new Error(result.message);+ }++ return { memo: result.memo };+ }+ case "trash_memos": {+ assertScope(auth, "write:memos");+ const memoIds = getRequiredStringArray(args.memoIds, "memoIds");++ if (args.dryRun === true) {+ return { dryRun: true, memos: await getMemosForBulkAction(c.env.storage.db, auth.workspaceId, memoIds, 0) };+ }++ const deleted = await deleteMemosRecord(c.env, auth.workspaceId, memoIds, false, getAuditActor(c));+ return { ok: true, deleted };+ }+ case "restore_memos": {+ assertScope(auth, "write:memos");+ const memoIds = getRequiredStringArray(args.memoIds, "memoIds");++ if (args.dryRun === true) {+ return { dryRun: true, memos: await getMemosForBulkAction(c.env.storage.db, auth.workspaceId, memoIds, 1) };+ }++ const restored = await restoreMemosRecord(c.env.storage.db, auth.workspaceId, memoIds, getAuditActor(c));+ return { ok: true, restored };+ }+ case "upload_memo_image": {+ assertScope(auth, "write:resources");+ const memoId = getRequiredString(args.memoId, "memoId");+ const memo = await getMemoDetail(c.env.storage.db, auth.workspaceId, memoId);++ if (!memo) {+ throw new AppError("not_found", "Memo not found", 404);+ }++ const mimeType = getRequiredString(args.mimeType, "mimeType");+ const filename = getOptionalString(args.filename) ?? `image${inferImageExtension("", mimeType)}`;+ const bytes = await decodeBase64Data(getRequiredString(args.dataBase64, "dataBase64"));+ const resource = await createImageResource(c, {+ memoId,+ filename,+ mimeType,+ bytes,+ actor: getAuditActor(c),+ source: "mcp",+ });+ const alt = getOptionalString(args.alt) ?? normalizeFilename(filename) ?? "image";++ return {+ resource,+ markdownImage: ``,+ };+ }+ case "move_memos": {+ assertScope(auth, "write:memos");+ const notebookId = getRequiredString(args.notebookId, "notebookId");+ const memoIds = getRequiredStringArray(args.memoIds, "memoIds");+ const target = await getNotebook(c.env.storage.db, auth.workspaceId, notebookId);++ if (!target) {+ throw new AppError("not_found", "Target notebook not found", 404);+ }++ if (args.dryRun === true) {+ return { dryRun: true, targetNotebook: target, memos: await getMemosForBulkAction(c.env.storage.db, auth.workspaceId, memoIds, 0) };+ }++ const actor = getAuditActor(c);+ const actorLabel = getActorLabel(c);+ const moved = await moveMemosToNotebook(c.env.storage.db, auth.workspaceId, memoIds, notebookId, actor, actorLabel);++ return { ok: true, moved };+ }+ case "add_tags_to_memos": {+ assertScope(auth, "write:tags");+ return await updateTagsForMemos(c.env.storage.db, {+ workspaceId: auth.workspaceId,+ memoIds: getRequiredStringArray(args.memoIds, "memoIds"),+ tags: getRequiredStringArray(args.tags, "tags"),+ mode: "add",+ dryRun: args.dryRun === true,+ actor: getAuditActor(c),+ actorLabel: getActorLabel(c),+ });+ }+ case "remove_tags_from_memos": {+ assertScope(auth, "write:tags");+ return await updateTagsForMemos(c.env.storage.db, {+ workspaceId: auth.workspaceId,+ memoIds: getRequiredStringArray(args.memoIds, "memoIds"),+ tags: getRequiredStringArray(args.tags, "tags"),+ mode: "remove",+ dryRun: args.dryRun === true,+ actor: getAuditActor(c),+ actorLabel: getActorLabel(c),+ });+ }+ case "rename_tag": {+ assertScope(auth, "write:tags");+ const from = getRequiredString(args.from, "from");+ const to = getRequiredString(args.to, "to");++ if (args.dryRun === true) {+ return await previewTagRename(c.env.storage.db, auth.workspaceId, from, to);+ }++ const updated = await updateTagAcrossMemos(c.env.storage.db, auth.workspaceId, from, to, getAuditActor(c), getActorLabel(c));+ return { ok: true, updated };+ }+ case "delete_tag": {+ assertScope(auth, "write:tags");+ const tag = getRequiredString(args.tag, "tag");++ if (args.dryRun === true) {+ return await previewTagRename(c.env.storage.db, auth.workspaceId, tag, null);+ }++ const updated = await updateTagAcrossMemos(c.env.storage.db, auth.workspaceId, tag, null, getAuditActor(c), getActorLabel(c));+ return { ok: true, updated };+ }+ case "merge_memos": {+ assertScope(auth, "write:memos");+ const actor = getAuditActor(c);+ const actorLabel = getActorLabel(c);+ const memo = await mergeMemosRecord(+ c.env.storage.db,+ auth.workspaceId,+ {+ memoIds: getRequiredStringArray(args.memoIds, "memoIds"),+ notebookId: getOptionalString(args.notebookId) ?? undefined,+ title: getOptionalString(args.title) ?? undefined,+ },+ actor,+ actorLabel+ );++ return { memo };+ }+ case "upload_memo_attachment": {+ assertScope(auth, "write:resources");+ const memoId = getRequiredString(args.memoId, "memoId");+ const memo = await getMemoDetail(c.env.storage.db, auth.workspaceId, memoId);++ if (!memo) {+ throw new AppError("not_found", "Memo not found", 404);+ }++ const filename = getRequiredString(args.filename, "filename");+ const bytes = await decodeBase64Data(getRequiredString(args.dataBase64, "dataBase64"));+ const resource = await createAttachmentResource(c, {+ memoId,+ filename,+ mimeType: getRequiredString(args.mimeType, "mimeType"),+ bytes,+ actor: getAuditActor(c),+ });+ const label = getOptionalString(args.label) ?? normalizeFilename(filename) ?? "attachment";++ return {+ resource,+ markdownLink: `[${escapeMarkdownLinkLabel(label)}](${resource.url})`,+ };+ }+ case "list_memo_resources": {+ assertScope(auth, "read:resources");+ const memoId = getRequiredString(args.memoId, "memoId");+ const memo = await getMemoDetail(c.env.storage.db, auth.workspaceId, memoId, true);++ if (!memo) {+ throw new AppError("not_found", "Memo not found", 404);+ }++ return { resources: await listResourcesForMemo(c.env.storage.db, auth.workspaceId, memoId) };+ }+ case "list_resources": {+ assertScope(auth, "read:resources");+ return await listResourcesForMcp(c.env.storage.db, auth.workspaceId, clampNumber(Number(args.limit ?? 100), 1, 500));+ }+ case "list_memo_revisions": {+ assertScope(auth, "read:memos");+ return {+ revisions: await listMemoRevisionsService(+ c.env.storage.db,+ auth.workspaceId,+ getRequiredString(args.memoId, "memoId"),+ clampNumber(Number(args.limit ?? 50), 1, 100),+ getMemoDetail,+ ),+ };+ }+ case "restore_memo_revision": {+ assertScope(auth, "write:memos");+ const memoId = getRequiredString(args.memoId, "memoId");+ const revisionId = getRequiredString(args.revisionId, "revisionId");+ const revision = await getMemoRevisionRowService(c.env.storage.db, auth.workspaceId, memoId, revisionId);++ if (!revision) {+ throw new AppError("not_found", "Memo revision not found", 404);+ }++ if (args.dryRun === true) {+ return { dryRun: true, revision: mapMemoRevisionService(revision) };+ }++ return {+ memo: await restoreMemoRevisionService(+ c.env.storage.db,+ auth.workspaceId,+ memoId,+ revisionId,+ getAuditActor(c),+ getActorLabel(c),+ { getMemoDetail, getMemoDetailRow },+ ),+ };+ }+ case "move_notebook": {+ assertScope(auth, "write:notebooks");+ const actor = getAuditActor(c);+ const notebook = await updateNotebookRecord(+ c.env.storage.db,+ auth.workspaceId,+ getRequiredString(args.notebookId, "notebookId"),+ {+ parentId: args.parentId === null ? null : getOptionalString(args.parentId) ?? undefined,+ sortOrder: typeof args.sortOrder === "number" && Number.isInteger(args.sortOrder) ? args.sortOrder : undefined,+ },+ actor+ );++ return { notebook };+ }+ case "create_notebook": {+ assertScope(auth, "write:notebooks");+ const actor = getAuditActor(c);+ const name = getRequiredString(args.name, "name");++ if (name.length > 80) {+ throw new AppError("invalid_params", "name must be at most 80 characters", 400);+ }++ const notebook = await createNotebookRecord(+ c.env.storage.db,+ auth.workspaceId,+ {+ name,+ parentId: args.parentId === null ? null : getOptionalString(args.parentId) ?? undefined,+ sortOrder: typeof args.sortOrder === "number" && Number.isInteger(args.sortOrder) ? args.sortOrder : undefined,+ },+ actor+ );++ return { notebook };+ }+ case "rename_notebook": {+ assertScope(auth, "write:notebooks");+ const name = getRequiredString(args.name, "name");++ if (name.length > 80) {+ throw new AppError("invalid_params", "name must be at most 80 characters", 400);+ }++ const notebook = await updateNotebookRecord(+ c.env.storage.db,+ auth.workspaceId,+ getRequiredString(args.notebookId, "notebookId"),+ { name },+ getAuditActor(c)+ );++ return { notebook };+ }+ case "get_notebook": {+ assertScope(auth, "read:notebooks");+ const notebook = await getNotebook(c.env.storage.db, auth.workspaceId, getRequiredString(args.notebookId, "notebookId"));+ if (!notebook) {+ throw new AppError("not_found", "Notebook not found in the authenticated user's workspace.", 404);+ }+ return { notebook };+ }+ case "find_notebooks": {+ assertScope(auth, "read:notebooks");+ return {+ notebooks: await findNotebooks(c.env.storage.db, auth.workspaceId, {+ name: getRequiredString(args.name, "name"),+ parentId: Object.hasOwn(args, "parentId")+ ? args.parentId === null+ ? null+ : getRequiredString(args.parentId, "parentId")+ : undefined,+ exact: args.exact === true,+ limit: clampNumber(Number(args.limit ?? 20), 1, 50),+ }),+ };+ }+ case "resolve_notebook_path": {+ assertScope(auth, "read:notebooks");+ return await resolveNotebookPath(c.env.storage.db, auth.workspaceId, getRequiredString(args.path, "path"));+ }+ case "list_notebooks": {+ assertScope(auth, "read:notebooks");+ return { notebooks: await listNotebooks(c.env.storage.db, auth.workspaceId) };+ }+ case "list_tags": {+ assertScope(auth, "read:tags");+ return { tags: await listTagSummaries(c.env.storage.db, auth.workspaceId) };+ }+ case "get_workspace_stats": {+ assertScope(auth, "read:memos");+ return await getWorkspaceStats(c.env.storage.db, auth.workspaceId);+ }+ case "list_note_templates": {+ assertScope(auth, "read:memos");+ return { templates: await listMemoTemplates(c.env.storage.db, auth.workspaceId) };+ }+ case "get_note_template": {+ assertScope(auth, "read:memos");+ const template = await getMemoTemplate(+ c.env.storage.db,+ auth.workspaceId,+ getRequiredString(args.templateId, "templateId"),+ );+ if (!template) throw new AppError("not_found", "Template not found", 404);+ return { template };+ }+ case "create_note_template": {+ assertScope(auth, "write:memos");+ assertMcpMutationAllowed(c.env);+ const input = parseMcpInput(TemplateCreateSchema, args);+ const memo = input.memoId+ ? await getMemoDetail(c.env.storage.db, auth.workspaceId, input.memoId)+ : null;+ if (input.memoId && !memo) throw new AppError("not_found", "Memo not found", 404);++ const id = createId("template");+ const now = isoNow();+ const title = memo?.title ?? (input.title?.trim() || null);+ const contentMarkdown = memo?.contentMarkdown ?? input.contentMarkdown ?? "";+ const tags = memo?.tags ?? input.tags ?? [];+ const contentJson = memo?.contentJson ?? markdownToDoc(contentMarkdown);+ await c.env.storage.db.prepare(+ `INSERT INTO memo_templates (+ id, workspace_id, name, description, title, content_json, content_markdown, tags_json, created_at, updated_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,+ ).bind(+ id,+ auth.workspaceId,+ input.name.trim(),+ input.description?.trim() || null,+ title,+ JSON.stringify(contentJson),+ contentMarkdown,+ JSON.stringify(tags),+ now,+ now,+ ).run();+ const actor = getAuditActor(c);+ await audit(c.env.storage.db, actor.actorType, actor.actorId, "template.create", "template", id, {+ memoId: input.memoId ?? null,+ });+ return { template: await getMemoTemplate(c.env.storage.db, auth.workspaceId, id) };+ }+ case "update_note_template": {+ assertScope(auth, "write:memos");+ assertMcpMutationAllowed(c.env);+ const templateId = getRequiredString(args.templateId, "templateId");+ const input = parseMcpInput(TemplateUpdateSchema, args);+ if (Object.keys(input).length === 0) {+ throw new AppError("invalid_params", "At least one template field is required.", 400);+ }+ const current = await getMemoTemplate(c.env.storage.db, auth.workspaceId, templateId);+ if (!current) throw new AppError("not_found", "Template not found", 404);++ const contentMarkdown = input.contentMarkdown ?? current.contentMarkdown;+ const contentJson = input.contentMarkdown !== undefined+ ? markdownToDoc(contentMarkdown)+ : current.contentJson;+ const now = isoNow();+ await c.env.storage.db.prepare(+ `UPDATE memo_templates+ SET name = ?, description = ?, title = ?, content_json = ?, content_markdown = ?, tags_json = ?, updated_at = ?+ WHERE id = ? AND workspace_id = ?`,+ ).bind(+ input.name ?? current.name,+ input.description !== undefined ? input.description?.trim() || null : current.description,+ input.title !== undefined ? input.title?.trim() || null : current.title,+ JSON.stringify(contentJson),+ contentMarkdown,+ JSON.stringify(input.tags ?? current.tags),+ now,+ templateId,+ auth.workspaceId,+ ).run();+ const actor = getAuditActor(c);+ await audit(c.env.storage.db, actor.actorType, actor.actorId, "template.update", "template", templateId, {});+ return { template: await getMemoTemplate(c.env.storage.db, auth.workspaceId, templateId) };+ }+ case "delete_note_template": {+ assertScope(auth, "write:memos");+ assertMcpMutationAllowed(c.env);+ const templateId = getRequiredString(args.templateId, "templateId");+ const current = await getMemoTemplate(c.env.storage.db, auth.workspaceId, templateId);+ if (!current) throw new AppError("not_found", "Template not found", 404);+ await c.env.storage.db.prepare(+ `DELETE FROM memo_templates WHERE id = ? AND workspace_id = ?`,+ ).bind(templateId, auth.workspaceId).run();+ const actor = getAuditActor(c);+ await audit(c.env.storage.db, actor.actorType, actor.actorId, "template.delete", "template", templateId, {});+ return { ok: true };+ }+ case "use_note_template": {+ assertScope(auth, "write:memos");+ assertMcpMutationAllowed(c.env);+ const templateId = getRequiredString(args.templateId, "templateId");+ const template = await getMemoTemplate(c.env.storage.db, auth.workspaceId, templateId);+ if (!template) throw new AppError("not_found", "Template not found", 404);+ const memo = await createMemoRecord(c.env.storage.db, auth.workspaceId, {+ notebookId: getRequiredString(args.notebookId, "notebookId"),+ title: template.title ?? undefined,+ contentMarkdown: template.contentMarkdown,+ tags: template.tags,+ }, getAuditActor(c), getActorLabel(c));+ const actor = getAuditActor(c);+ await audit(c.env.storage.db, actor.actorType, actor.actorId, "template.use", "template", templateId, { memoId: memo.id });+ return { memo };+ }+ case "list_ai_instructions": {+ assertScope(auth, "read:memos");+ return {+ instructions: await listAiPromptTemplates(+ c.env.storage.db,+ auth.workspaceId,+ getOptionalString(args.locale),+ ),+ };+ }+ case "get_ai_instruction": {+ assertScope(auth, "read:memos");+ const row = await getAiPromptTemplateRow(+ c.env.storage.db,+ auth.workspaceId,+ getRequiredString(args.instructionId, "instructionId"),+ );+ if (!row) throw new AppError("not_found", "AI instruction not found", 404);+ return { instruction: mapAiPromptTemplateRow(row, getOptionalString(args.locale)) };+ }+ case "create_ai_instruction": {+ assertScope(auth, "write:memos");+ assertMcpMutationAllowed(c.env);+ const input = parseMcpInput(AiPromptTemplateCreateSchema, args);+ const id = createId("aiprompt");+ const now = isoNow();+ const actor = getAuditActor(c);+ await c.env.storage.db.batch([+ c.env.storage.db.prepare(+ `INSERT INTO ai_prompt_templates (+ id, workspace_id, seed_key, action, parameter_kind, result_mode,+ name, description, instruction,+ name_customized, description_customized, instruction_customized,+ created_at, updated_at+ ) VALUES (?, ?, NULL, 'custom', ?, ?, ?, ?, ?, 1, 1, 1, ?, ?)`,+ ).bind(+ id,+ auth.workspaceId,+ input.parameterKind,+ input.resultMode,+ input.name.trim(),+ input.description?.trim() || null,+ input.instruction.trim(),+ now,+ now,+ ),+ auditStatement(c.env.storage.db, actor.actorType, actor.actorId, "ai_prompt.create", "ai_prompt", id, {}),+ ]);+ const row = await getAiPromptTemplateRow(c.env.storage.db, auth.workspaceId, id);+ return { instruction: mapAiPromptTemplateRow(row!, getOptionalString(args.locale)) };+ }+ case "update_ai_instruction": {+ assertScope(auth, "write:memos");+ assertMcpMutationAllowed(c.env);+ const instructionId = getRequiredString(args.instructionId, "instructionId");+ const input = parseMcpInput(AiPromptTemplateUpdateSchema, args);+ const current = await getAiPromptTemplateRow(c.env.storage.db, auth.workspaceId, instructionId);+ if (!current) throw new AppError("not_found", "AI instruction not found", 404);++ const now = isoNow();+ const actor = getAuditActor(c);+ await c.env.storage.db.batch([+ c.env.storage.db.prepare(+ `UPDATE ai_prompt_templates+ SET name = ?, description = ?, instruction = ?,+ parameter_kind = ?, result_mode = ?,+ name_customized = ?, description_customized = ?, instruction_customized = ?,+ updated_at = ?+ WHERE id = ? AND workspace_id = ?`,+ ).bind(+ input.name?.trim() ?? current.name,+ input.description !== undefined ? input.description?.trim() || null : current.description,+ input.instruction?.trim() ?? current.instruction,+ input.parameterKind ?? current.parameter_kind,+ input.resultMode ?? current.result_mode,+ input.name !== undefined ? 1 : current.name_customized,+ input.description !== undefined ? 1 : current.description_customized,+ input.instruction !== undefined ? 1 : current.instruction_customized,+ now,+ instructionId,+ auth.workspaceId,+ ),+ auditStatement(c.env.storage.db, actor.actorType, actor.actorId, "ai_prompt.update", "ai_prompt", instructionId, {}),+ ]);+ const row = await getAiPromptTemplateRow(c.env.storage.db, auth.workspaceId, instructionId);+ return { instruction: mapAiPromptTemplateRow(row!, getOptionalString(args.locale)) };+ }+ case "delete_ai_instruction": {+ assertScope(auth, "write:memos");+ assertMcpMutationAllowed(c.env);+ const instructionId = getRequiredString(args.instructionId, "instructionId");+ const current = await getAiPromptTemplateRow(c.env.storage.db, auth.workspaceId, instructionId);+ if (!current) throw new AppError("not_found", "AI instruction not found", 404);+ const actor = getAuditActor(c);+ await c.env.storage.db.batch([+ c.env.storage.db.prepare(+ `DELETE FROM ai_prompt_templates WHERE id = ? AND workspace_id = ?`,+ ).bind(instructionId, auth.workspaceId),+ auditStatement(c.env.storage.db, actor.actorType, actor.actorId, "ai_prompt.delete", "ai_prompt", instructionId, {}),+ ]);+ return { ok: true };+ }+ case "restore_default_ai_instructions": {+ assertScope(auth, "write:memos");+ assertMcpMutationAllowed(c.env);+ const result = await restoreMissingDefaultAiPrompts(c.env.storage.db, auth.workspaceId);+ if (result.restoredCount > 0) {+ const actor = getAuditActor(c);+ await audit(c.env.storage.db, actor.actorType, actor.actorId, "ai_prompt.restore_defaults", "workspace", auth.workspaceId, result);+ }+ return {+ ...result,+ instructions: await listAiPromptTemplates(+ c.env.storage.db,+ auth.workspaceId,+ getOptionalString(args.locale),+ ),+ };+ }+ default:+ throw new Error(`Unknown tool: ${name}`);+ }+};diff --git a/apps/api/src/memo-revision-service.test.mjs b/apps/api/src/memo-revision-service.test.mjsnew file mode 100644index 00000000..79c7c7c1--- /dev/null+++ b/apps/api/src/memo-revision-service.test.mjs@@ -0,0 +1,145 @@+import { describe, expect, test } from "bun:test";+import {+ listMemoRevisions,+ mapMemoRevision,+ restoreMemoRevision,+ shouldSnapshotMemoRevision,+} from "./memo-revision-service.ts";++const current = {+ id: "memo_1",+ revision: 3,+ title: "Current",+ tags_json: '["tag"]',+ content_json: '{"type":"doc","content":[]}',+ content_markdown: "Current body",+ content_text: "Current body",+ content_hash: "current-hash",+};++const revision = {+ id: "revision_1",+ memo_id: "memo_1",+ revision: 2,+ title: "Previous",+ tags_json: '["old"]',+ content_json: '{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Previous body"}]}]}',+ content_markdown: "Previous body",+ content_text: "Previous body",+ content_hash: "previous-hash",+ created_by: "Owner",+ created_at: "2026-08-29T00:00:00.000Z",+};++const createStatement = (sql, firstValue = null, allResults = []) => ({+ sql,+ bindings: [],+ bind(...bindings) {+ this.bindings = bindings;+ return this;+ },+ async first() {+ return firstValue;+ },+ async all() {+ return { success: true, meta: {}, results: allResults };+ },+ async run() {+ return { success: true, meta: {}, results: [] };+ },+});++describe("memo revision service", () => {+ test("maps stored revision rows into the public contract", () => {+ expect(mapMemoRevision(revision)).toEqual({+ id: "revision_1",+ memoId: "memo_1",+ revision: 2,+ title: "Previous",+ tags: ["old"],+ contentMarkdown: "Previous body",+ contentText: "Previous body",+ contentHash: "previous-hash",+ createdBy: "Owner",+ createdAt: "2026-08-29T00:00:00.000Z",+ });+ });++ test("does not query revision history when the memo is unchanged", async () => {+ const database = {+ prepare: () => {+ throw new Error("Revision history should not be queried");+ },+ };++ await expect(shouldSnapshotMemoRevision(+ database,+ current,+ current.title,+ current.tags_json,+ current.content_hash,+ "2026-08-29T01:00:00.000Z",+ )).resolves.toBe(false);+ });++ test("lists revisions only after confirming memo visibility", async () => {+ const statement = createStatement("SELECT revisions", null, [revision]);+ const database = { prepare: () => statement };+ const visibilityChecks = [];++ const result = await listMemoRevisions(+ database,+ "workspace_1",+ "memo_1",+ 25,+ async (_db, workspaceId, memoId, includeDeleted) => {+ visibilityChecks.push({ workspaceId, memoId, includeDeleted });+ return { id: memoId };+ },+ false,+ );++ expect(result).toEqual([mapMemoRevision(revision)]);+ expect(visibilityChecks).toEqual([{+ workspaceId: "workspace_1",+ memoId: "memo_1",+ includeDeleted: false,+ }]);+ expect(statement.bindings).toEqual(["memo_1", 25]);+ });++ test("restores a revision through one service-owned batch", async () => {+ const prepared = [];+ let batch = [];+ const database = {+ prepare: (sql) => {+ const statement = createStatement(sql, sql.includes("FROM memo_revisions mr") ? revision : null);+ prepared.push(statement);+ return statement;+ },+ batch: async (statements) => {+ batch = statements;+ return statements.map(() => ({ success: true, meta: {}, results: [] }));+ },+ };+ const restoredMemo = { id: "memo_1", revision: 4, title: "Previous" };++ const result = await restoreMemoRevision(+ database,+ "workspace_1",+ "memo_1",+ "revision_1",+ { actorType: "user", actorId: "user_1" },+ "Owner",+ {+ getMemoDetailRow: async () => current,+ getMemoDetail: async () => restoredMemo,+ },+ );++ expect(result).toBe(restoredMemo);+ expect(batch).toHaveLength(5);+ expect(prepared.some(({ sql }) => sql.includes("INSERT INTO memo_revisions"))).toBe(true);+ expect(prepared.some(({ sql }) => sql.includes("UPDATE memo_contents"))).toBe(true);+ });+});diff --git a/apps/api/src/memo-revision-service.ts b/apps/api/src/memo-revision-service.tsnew file mode 100644index 00000000..b9864365--- /dev/null+++ b/apps/api/src/memo-revision-service.ts@@ -0,0 +1,231 @@+import {+ createExcerpt,+ DEFAULT_MEMO_TITLE,+ docToMarkdown,+ docToText,+ emptyDoc,+ type MemoDetail,+ type MemoRevision,+ type TiptapDoc,+} from "@edgeever/shared";+import type { AuditActor } from "./api-context";+import { AppError } from "./app-error";+import { auditStatement } from "./audit";+import { createId, isoNow, parseJsonArray } from "./entity-utils";+import { sha256 } from "./hash-utils";+import { upsertMemoSearchDocumentStatement } from "./memo-search-index";+import type { DatabaseAdapter, PreparedStatementAdapter } from "./storage-contract";++const REVISION_SNAPSHOT_INTERVAL_MS = 5 * 60 * 1000;++export type MemoRevisionRow = {+ id: string;+ memo_id: string;+ revision: number;+ title: string | null;+ tags_json: string;+ content_json: string;+ content_markdown: string;+ content_text: string;+ content_hash: string;+ created_by: string;+ created_at: string;+};++export type MemoRevisionSourceRow = {+ id: string;+ revision: number;+ title: string | null;+ tags_json: string;+ content_json: string;+ content_markdown: string;+ content_text: string;+ content_hash: string;+};++type MemoRevisionDependencies = {+ getMemoDetail: (+ db: DatabaseAdapter,+ workspaceId: string,+ memoId: string,+ includeDeleted?: boolean,+ ) => Promise<MemoDetail | null>;+ getMemoDetailRow: (+ db: DatabaseAdapter,+ workspaceId: string,+ memoId: string,+ ) => Promise<MemoRevisionSourceRow | null>;+};++const parseDoc = (json: string): TiptapDoc => {+ try {+ const value = JSON.parse(json);+ return value && typeof value === "object" ? value as TiptapDoc : emptyDoc();+ } catch {+ return emptyDoc();+ }+};++const normalizeMemoTitle = (value: string | null | undefined) => {+ const title = value?.trim();+ return title || DEFAULT_MEMO_TITLE;+};++export const mapMemoRevision = (row: MemoRevisionRow): MemoRevision => ({+ id: row.id,+ memoId: row.memo_id,+ revision: row.revision,+ title: row.title,+ tags: parseJsonArray(row.tags_json),+ contentMarkdown: row.content_markdown,+ contentText: row.content_text,+ contentHash: row.content_hash,+ createdBy: row.created_by,+ createdAt: row.created_at,+});++export const getMemoRevisionRow = async (+ db: DatabaseAdapter,+ workspaceId: string,+ memoId: string,+ revisionId: string,+): Promise<MemoRevisionRow | null> => db.prepare(+ `SELECT mr.id, mr.memo_id, mr.revision, mr.title, mr.tags_json, mr.content_json, mr.content_markdown,+ mr.content_text, mr.content_hash, mr.created_by, mr.created_at+ FROM memo_revisions mr+ INNER JOIN memos m ON m.id = mr.memo_id+ WHERE mr.id = ? AND mr.memo_id = ? AND m.workspace_id = ?`,+).bind(revisionId, memoId, workspaceId).first<MemoRevisionRow>();++export const listMemoRevisions = async (+ db: DatabaseAdapter,+ workspaceId: string,+ memoId: string,+ limit: number,+ getMemoDetail: MemoRevisionDependencies["getMemoDetail"],+ includeDeleted = true,+): Promise<MemoRevision[]> => {+ const memo = await getMemoDetail(db, workspaceId, memoId, includeDeleted);+ if (!memo) throw new AppError("not_found", "Memo not found", 404);++ const rows = await db.prepare(+ `SELECT id, memo_id, revision, title, tags_json, content_json, content_markdown,+ content_text, content_hash, created_by, created_at+ FROM memo_revisions+ WHERE memo_id = ?+ ORDER BY revision DESC, created_at DESC+ LIMIT ?`,+ ).bind(memoId, limit).all<MemoRevisionRow>();++ return rows.results.map(mapMemoRevision);+};++export const createMemoRevisionStatement = (+ db: DatabaseAdapter,+ current: MemoRevisionSourceRow,+ actorLabel: string,+ createdAt: string,+): PreparedStatementAdapter => db.prepare(+ `INSERT INTO memo_revisions (+ id, memo_id, revision, title, content_json, content_markdown,+ content_hash, created_by, created_at, tags_json, content_text+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,+).bind(+ createId("rev"),+ current.id,+ current.revision,+ current.title,+ current.content_json,+ current.content_markdown,+ current.content_hash,+ actorLabel,+ createdAt,+ current.tags_json,+ current.content_text,+);++const getLatestMemoRevisionRow = (+ db: DatabaseAdapter,+ memoId: string,+) => db.prepare(+ `SELECT id, memo_id, revision, title, tags_json, content_json, content_markdown,+ content_text, content_hash, created_by, created_at+ FROM memo_revisions+ WHERE memo_id = ?+ ORDER BY created_at DESC, revision DESC+ LIMIT 1`,+).bind(memoId).first<MemoRevisionRow>();++export const shouldSnapshotMemoRevision = async (+ db: DatabaseAdapter,+ current: MemoRevisionSourceRow,+ nextTitle: string | null,+ nextTagsJson: string,+ nextContentHash: string,+ now: string,+) => {+ const changed = (current.title ?? "") !== (nextTitle ?? "")+ || current.tags_json !== nextTagsJson+ || current.content_hash !== nextContentHash;+ if (!changed) return false;++ const latest = await getLatestMemoRevisionRow(db, current.id);+ if (!latest) return true;++ const alreadyCapturedCurrent = (latest.title ?? "") === (current.title ?? "")+ && latest.tags_json === current.tags_json+ && latest.content_hash === current.content_hash;+ if (alreadyCapturedCurrent) return false;++ return Date.parse(now) - Date.parse(latest.created_at) >= REVISION_SNAPSHOT_INTERVAL_MS;+};++export const restoreMemoRevision = async (+ db: DatabaseAdapter,+ workspaceId: string,+ memoId: string,+ revisionId: string,+ actor: AuditActor,+ actorLabel: string,+ dependencies: Pick<MemoRevisionDependencies, "getMemoDetail" | "getMemoDetailRow">,+) => {+ const current = await dependencies.getMemoDetailRow(db, workspaceId, memoId);+ if (!current) throw new AppError("not_found", "Memo not found", 404);++ const revision = await getMemoRevisionRow(db, workspaceId, memoId, revisionId);+ if (!revision) throw new AppError("not_found", "Memo revision not found", 404);++ const tags = parseJsonArray(revision.tags_json);+ const contentJson = parseDoc(revision.content_json);+ const contentMarkdown = revision.content_markdown || docToMarkdown(contentJson);+ const contentText = revision.content_text || docToText(contentJson);+ const title = normalizeMemoTitle(revision.title);+ const contentHash = await sha256(contentMarkdown + JSON.stringify(contentJson));+ const nextRevision = current.revision + 1;+ const now = isoNow();++ await db.batch([+ createMemoRevisionStatement(db, current, actorLabel, now),+ db.prepare(+ `UPDATE memos+ SET title = ?, excerpt = ?, tags_json = ?, updated_by = ?, updated_at = ?+ WHERE id = ? AND workspace_id = ? AND is_deleted = 0`,+ ).bind(title, createExcerpt(contentText), JSON.stringify(tags), actorLabel, now, memoId, workspaceId),+ db.prepare(+ `UPDATE memo_contents+ SET content_json = ?, content_markdown = ?, content_text = ?, content_hash = ?,+ revision = ?, updated_at = ?+ WHERE memo_id = ?`,+ ).bind(JSON.stringify(contentJson), contentMarkdown, contentText, contentHash, nextRevision, now, memoId),+ upsertMemoSearchDocumentStatement(db, memoId, title, contentText, tags.join(" ")),+ auditStatement(db, actor.actorType, actor.actorId, "memo.revision_restore", "memo", memoId, {+ revisionId,+ restoredRevision: revision.revision,+ revision: nextRevision,+ }),+ ]);++ const memo = await dependencies.getMemoDetail(db, workspaceId, memoId);+ if (!memo) throw new AppError("not_found", "Memo not found after revision restore", 404);+ return memo;+};diff --git a/apps/api/src/memo-service.ts b/apps/api/src/memo-service.tsnew file mode 100644index 00000000..f00893ad--- /dev/null+++ b/apps/api/src/memo-service.ts@@ -0,0 +1,1387 @@+import {+ createExcerpt,+ DEFAULT_MEMO_TITLE,+ docToMarkdown,+ docToText,+ emptyDoc,+ markdownToDoc,+ mergeMemoDocs,+ resolveMemoContentDoc,+ resolveMergedMemoTitle,+ isSuspiciousMemoOverwrite,+ isMemoEditBindingValid,+ normalizeTags,+ type MemoDetail,+ type MemoEditSession,+ type MemoSummary,+ type MemoUpdateInput,+ type TiptapDoc,+} from "@edgeever/shared";+import { auditStatement } from "./audit";+import type { AppContext, AuditActor, AuthContext, Bindings } from "./api-context";+import { AppError } from "./app-error";+import { createId, isoNow, parseJsonArray } from "./entity-utils";+import { sha256 } from "./hash-utils";+import { getRequiredString } from "./mcp-json-rpc";+import {+ escapeLike,+ listMemos,+ mapMemoSummary,+ toFtsQuery,+ type MemoSummaryRow,+} from "./memo-list-service";+import {+ deleteMemoSearchDocumentsStatement,+ upsertMemoSearchDocumentStatement,+} from "./memo-search-index";+import {+ createMemoRevisionStatement as createMemoRevisionStatementService,+ shouldSnapshotMemoRevision as shouldSnapshotMemoRevisionService,+} from "./memo-revision-service";+import { getNotebook } from "./notebook-service";+import { deleteStoredObjects } from "./object-storage";+import { getAuditActor, getWorkspaceId } from "./request-auth";+import type { DatabaseAdapter, PreparedStatementAdapter } from "./storage-contract";++const clampNumber = (value: number, min: number, max: number) =>+ Number.isNaN(value) ? min : Math.min(Math.max(value, min), max);++export type MemoDetailRow = MemoSummaryRow & {+ content_json: string;+ content_markdown: string;+ content_text: string;+ source_memo_ids: string;+ merge_source_count: number;+ merged_into_memo_id: string | null;+ content_hash: string;+};++type MemoEditSessionRow = {+ id: string;+ memo_id: string;+ actor_type: "user" | "agent";+ actor_id: string | null;+ base_revision: number;+ base_content_hash: string;+ expires_at: string;+};++type WorkspaceIdentityRow = {+ workspace_id: string;+ workspace_name: string;+ is_personal: number;+ user_id: string;+ username: string;+ display_name: string | null;+ role: "owner" | "member";+};++type MemoImportSourceRow = {+ external_id: string;+ memo_id: string;+ source_updated_at: string | null;+};++export const mapMemoDetail = (row: MemoDetailRow): MemoDetail => ({+ ...mapMemoSummary(row),+ contentJson: parseDoc(row.content_json),+ contentMarkdown: row.content_markdown,+ contentText: row.content_text,+ contentHash: row.content_hash,+ sourceMemoIds: parseJsonArray(row.source_memo_ids),+ mergeSourceCount: row.merge_source_count,+ mergedIntoMemoId: row.merged_into_memo_id,+});++export const getCurrentWorkspaceIdentity = async (db: DatabaseAdapter, auth: AuthContext) => {+ const row = await db.prepare(+ `SELECT w.id AS workspace_id, w.name AS workspace_name, w.is_personal,+ u.id AS user_id, u.username, u.display_name, wm.role+ FROM workspaces w+ INNER JOIN workspace_members wm ON wm.workspace_id = w.id+ INNER JOIN users u ON u.id = wm.user_id+ WHERE w.id = ?+ ORDER BY CASE WHEN u.id = ? THEN 0 ELSE 1 END, wm.created_at ASC+ LIMIT 1`+ ).bind(auth.workspaceId, auth.kind === "user" ? auth.actorId : null).first<WorkspaceIdentityRow>();++ if (!row) {+ throw new AppError("workspace_identity_not_found", "The authenticated workspace has no associated user.", 404);+ }++ return {+ user: {+ id: row.user_id,+ username: row.username,+ displayName: row.display_name,+ role: row.role,+ },+ workspace: {+ id: row.workspace_id,+ name: row.workspace_name,+ isPersonal: row.is_personal === 1,+ },+ authorization: {+ kind: auth.kind === "agent" ? "api_token" : "user_session",+ ...(auth.kind === "agent" ? { tokenName: auth.username, scopes: auth.scopes } : {}),+ },+ dataIsolation: {+ workspaceScoped: true,+ statement:+ "Every notebook and memo returned by this MCP server belongs to this workspace; data from other users is excluded.",+ },+ };+};++export const searchMemoSummaries = async (+ db: DatabaseAdapter,+ options: {+ workspaceId: string;+ query?: string | null;+ notebookId?: string | null;+ tags?: string[];+ createdAfter?: string | null;+ createdBefore?: string | null;+ updatedAfter?: string | null;+ updatedBefore?: string | null;+ isPinned?: boolean | null;+ hasResources?: boolean | null;+ limit: number;+ }+): Promise<MemoSummary[]> => {+ const q = options.query?.trim();+ const notebookId = options.notebookId?.trim() || null;+ const tags = normalizeTags(options.tags ?? []);+ const limit = clampNumber(options.limit, 1, 100);+ const filters = ["m.workspace_id = ?", "m.is_deleted = 0"];+ const binds: unknown[] = [options.workspaceId];++ if (notebookId) {+ filters.push("m.notebook_id = ?");+ binds.push(notebookId);+ }++ for (const tag of tags) {+ filters.push("EXISTS (SELECT 1 FROM memo_tags mt WHERE mt.memo_id = m.id AND mt.workspace_id = ? AND mt.name = ?)");+ binds.push(options.workspaceId, tag);+ }++ if (options.createdAfter) {+ filters.push("m.created_at >= ?");+ binds.push(options.createdAfter);+ }++ if (options.createdBefore) {+ filters.push("m.created_at <= ?");+ binds.push(options.createdBefore);+ }++ if (options.updatedAfter) {+ filters.push("m.updated_at >= ?");+ binds.push(options.updatedAfter);+ }++ if (options.updatedBefore) {+ filters.push("m.updated_at <= ?");+ binds.push(options.updatedBefore);+ }++ if (options.isPinned !== null && options.isPinned !== undefined) {+ filters.push("m.is_pinned = ?");+ binds.push(options.isPinned ? 1 : 0);+ }++ if (options.hasResources !== null && options.hasResources !== undefined) {+ filters.push(+ options.hasResources+ ? "EXISTS (SELECT 1 FROM resources r WHERE r.memo_id = m.id AND r.is_deleted = 0)"+ : "NOT EXISTS (SELECT 1 FROM resources r WHERE r.memo_id = m.id AND r.is_deleted = 0)"+ );+ }++ if (q) {+ const ftsQuery = toFtsQuery(q);+ const likeQuery = `%${escapeLike(q)}%`;++ if (ftsQuery) {+ const rows = await db+ .prepare(+ `WITH raw_matches(memo_id, rank) AS (+ SELECT memo_id, bm25(memos_fts)+ FROM memos_fts+ WHERE memos_fts MATCH ?++ UNION ALL++ SELECT m.id, 100.0+ FROM memos m+ INNER JOIN memo_contents c ON c.memo_id = m.id+ WHERE m.title LIKE ? ESCAPE '\\'+ OR c.content_text LIKE ? ESCAPE '\\'+ OR m.tags_json LIKE ? ESCAPE '\\'+ ),+ search_matches AS (+ SELECT memo_id, MIN(rank) AS rank+ FROM raw_matches+ GROUP BY memo_id+ )+ 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, c.revision,+ c.content_text+ FROM search_matches s+ INNER JOIN memos m ON m.id = s.memo_id+ INNER JOIN memo_contents c ON c.memo_id = m.id+ WHERE ${filters.join(" AND ")}+ ORDER BY s.rank ASC, m.is_pinned DESC, m.updated_at DESC+ LIMIT ?`+ )+ .bind(ftsQuery, likeQuery, likeQuery, likeQuery, ...binds, limit)+ .all<MemoSummaryRow>();++ return rows.results.map(mapMemoSummary);+ }+ }++ const rows = await 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, c.revision,+ c.content_text+ FROM memos m+ INNER JOIN memo_contents c ON c.memo_id = m.id+ WHERE ${filters.join(" AND ")}+ ORDER BY m.is_pinned DESC, m.updated_at DESC+ LIMIT ?`+ )+ .bind(...binds, limit)+ .all<MemoSummaryRow>();++ return rows.results.map(mapMemoSummary);+};++export const listMemosForMcp = async (+ db: DatabaseAdapter,+ options: { workspaceId: string; notebookId?: string | null; limit: number; offset: number; includeContent: boolean; includeDeleted: boolean }+) => {+ const notebookId = options.notebookId?.trim() || null;+ const limit = clampNumber(options.limit, 1, 100);+ const offset = clampNumber(options.offset, 0, 100_000);+ const pageSize = limit + 1;+ const deletedFilter = options.includeDeleted ? "1 = 1" : "m.is_deleted = 0";++ if (options.includeContent) {+ const rows = await 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, c.revision,+ c.content_json, c.content_markdown, c.content_text, c.content_hash,+ m.source_memo_ids, m.merge_source_count, m.merged_into_memo_id+ FROM memos m+ INNER JOIN memo_contents c ON c.memo_id = m.id+ WHERE m.workspace_id = ? AND ${deletedFilter}+ AND (? IS NULL OR m.notebook_id = ?)+ ORDER BY m.updated_at DESC, m.id ASC+ LIMIT ? OFFSET ?`+ )+ .bind(options.workspaceId, notebookId, notebookId, pageSize, offset)+ .all<MemoDetailRow>();+ const page = rows.results.slice(0, limit).map(mapMemoDetail);++ return {+ memos: page,+ limit,+ offset,+ nextOffset: rows.results.length > limit ? offset + limit : null,+ hasMore: rows.results.length > limit,+ };+ }++ const rows = await 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, c.revision,+ c.content_text+ FROM memos m+ INNER JOIN memo_contents c ON c.memo_id = m.id+ WHERE m.workspace_id = ? AND ${deletedFilter}+ AND (? IS NULL OR m.notebook_id = ?)+ ORDER BY m.updated_at DESC, m.id ASC+ LIMIT ? OFFSET ?`+ )+ .bind(options.workspaceId, notebookId, notebookId, pageSize, offset)+ .all<MemoSummaryRow>();+ const page = rows.results.slice(0, limit).map(mapMemoSummary);++ return {+ memos: page,+ limit,+ offset,+ nextOffset: rows.results.length > limit ? offset + limit : null,+ hasMore: rows.results.length > limit,+ };+};++export const getMemoDetailRow = async (+ db: DatabaseAdapter,+ workspaceId: string,+ id: string,+ includeDeleted = false+): Promise<MemoDetailRow | null> =>+ 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, c.revision,+ c.content_json, c.content_markdown, c.content_text, c.content_hash,+ m.source_memo_ids, m.merge_source_count, m.merged_into_memo_id+ FROM memos m+ INNER JOIN memo_contents c ON c.memo_id = m.id+ WHERE m.id = ? AND m.workspace_id = ? AND (? = 1 OR m.is_deleted = 0)`+ )+ .bind(id, workspaceId, includeDeleted ? 1 : 0)+ .first<MemoDetailRow>();++export const getMemoDetail = async (db: DatabaseAdapter, workspaceId: string, id: string, includeDeleted = false): Promise<MemoDetail | null> => {+ const row = await getMemoDetailRow(db, workspaceId, id, includeDeleted);+ return row ? mapMemoDetail(row) : null;+};++export const createMemoEditSession = async (c: AppContext, memoId: string): Promise<MemoEditSession | null> => {+ const current = await getMemoDetailRow(c.env.storage.db, getWorkspaceId(c), memoId);+ if (!current) return null;++ const actor = getAuditActor(c);+ const now = isoNow();+ const existing = await c.env.storage.db.prepare(+ `SELECT id, memo_id, base_revision, base_content_hash, expires_at+ FROM memo_edit_sessions+ WHERE memo_id = ? AND actor_type = ? AND actor_id IS ?+ AND base_revision = ? AND base_content_hash = ? AND expires_at > ?+ ORDER BY updated_at DESC+ LIMIT 1`,+ ).bind(+ memoId,+ actor.actorType,+ actor.actorId,+ current.revision,+ current.content_hash,+ now,+ ).first<{+ id: string;+ memo_id: string;+ base_revision: number;+ base_content_hash: string;+ expires_at: string;+ }>();++ if (existing) {+ return {+ id: existing.id,+ memoId: existing.memo_id,+ baseRevision: existing.base_revision,+ baseContentHash: existing.base_content_hash,+ expiresAt: existing.expires_at,+ };+ }++ const session: MemoEditSession = {+ id: createId("edit"),+ memoId,+ baseRevision: current.revision,+ baseContentHash: current.content_hash,+ expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60_000).toISOString(),+ };++ await c.env.storage.db.batch([+ c.env.storage.db.prepare(`DELETE FROM memo_edit_sessions WHERE expires_at <= ?`).bind(now),+ c.env.storage.db.prepare(+ `INSERT INTO memo_edit_sessions (+ id, memo_id, actor_type, actor_id, base_revision, base_content_hash,+ expires_at, created_at, updated_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,+ ).bind(+ session.id,+ memoId,+ actor.actorType,+ actor.actorId,+ session.baseRevision,+ session.baseContentHash,+ session.expiresAt,+ now,+ now,+ ),+ ]);++ return session;+};++export const deleteMemosRecord = async (+ env: Bindings,+ workspaceId: string,+ memoIds: string[],+ permanent: boolean,+ actor: { actorType: "user" | "agent"; actorId: string | null }+) => {+ const db = env.storage.db;+ const uniqueMemoIds = Array.from(new Set(memoIds));++ if (uniqueMemoIds.length === 0) {+ return 0;+ }++ const placeholders = uniqueMemoIds.map(() => "?").join(", ");+ const expectedDeletedState = permanent ? 1 : 0;+ const rows = await db+ .prepare(+ `SELECT id+ FROM memos+ WHERE workspace_id = ? AND is_deleted = ? AND id IN (${placeholders})`+ )+ .bind(workspaceId, expectedDeletedState, ...uniqueMemoIds)+ .all<{ id: string }>();++ if (rows.results.length !== uniqueMemoIds.length) {+ throw new AppError(+ "missing_memos",+ permanent ? "One or more memos cannot be permanently deleted." : "One or more memos cannot be deleted.",+ 400+ );+ }++ const now = isoNow();+ const statements: PreparedStatementAdapter[] = [];++ if (permanent) {+ const resourceRows = await db+ .prepare(+ `SELECT object_key, storage_config_id+ FROM resources+ WHERE memo_id IN (${placeholders})`+ )+ .bind(...uniqueMemoIds)+ .all<{ object_key: string; storage_config_id: string }>();++ if (resourceRows.results.length > 0) {+ await deleteStoredObjects(env, resourceRows.results);+ }++ statements.push(+ db.prepare(`DELETE FROM resources WHERE memo_id IN (${placeholders})`).bind(...uniqueMemoIds),+ db.prepare(`DELETE FROM memo_revisions WHERE memo_id IN (${placeholders})`).bind(...uniqueMemoIds),+ db.prepare(`DELETE FROM memo_contents WHERE memo_id IN (${placeholders})`).bind(...uniqueMemoIds),+ db.prepare(`DELETE FROM memos WHERE workspace_id = ? AND is_deleted = 1 AND id IN (${placeholders})`).bind(workspaceId, ...uniqueMemoIds)+ );++ for (const memoId of uniqueMemoIds) {+ statements.push(auditStatement(db, actor.actorType, actor.actorId, "memo.delete_permanent", "memo", memoId, {}));+ }+ } else {+ statements.push(+ db.prepare(`DELETE FROM memo_shares WHERE workspace_id = ? AND memo_id IN (${placeholders})`).bind(workspaceId, ...uniqueMemoIds),+ db+ .prepare(+ `UPDATE memos+ SET is_deleted = 1, deleted_at = ?, updated_at = ?+ WHERE workspace_id = ? AND is_deleted = 0 AND id IN (${placeholders})`+ )+ .bind(now, now, workspaceId, ...uniqueMemoIds),+ db+ .prepare(+ `UPDATE resources+ SET is_deleted = 1, deleted_at = ?, updated_at = ?+ WHERE is_deleted = 0 AND memo_id IN (${placeholders})`+ )+ .bind(now, now, ...uniqueMemoIds),+ deleteMemoSearchDocumentsStatement(db, uniqueMemoIds)+ );++ for (const memoId of uniqueMemoIds) {+ statements.push(auditStatement(db, actor.actorType, actor.actorId, "memo.delete", "memo", memoId, {}));+ }+ }++ await db.batch(statements);+ return uniqueMemoIds.length;+};++export const deleteMemoRecord = async (+ env: Bindings,+ workspaceId: string,+ memoId: string,+ permanent: boolean,+ actor: AuditActor,+) => {+ const current = await getMemoDetailRow(env.storage.db, workspaceId, memoId, permanent);++ if (permanent && (!current || current.is_deleted === 0)) {+ throw new AppError("not_found", "Memo not found in trash", 404);+ }++ // Soft deletion historically treats an unknown/already-deleted memo as an idempotent no-op.+ if (!permanent && !current) return;++ await deleteMemosRecord(env, workspaceId, [memoId], permanent, actor);+};++export const getMemosForBulkAction = async (db: DatabaseAdapter, workspaceId: string, memoIds: string[], deletedState: 0 | 1) => {+ const uniqueMemoIds = Array.from(new Set(memoIds));++ if (uniqueMemoIds.length === 0) {+ return [];+ }++ const placeholders = uniqueMemoIds.map(() => "?").join(", ");+ const rows = await 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, c.revision,+ c.content_text+ FROM memos m+ INNER JOIN memo_contents c ON c.memo_id = m.id+ WHERE m.workspace_id = ? AND m.is_deleted = ?+ AND m.id IN (${placeholders})+ ORDER BY m.updated_at DESC, m.id ASC`+ )+ .bind(workspaceId, deletedState, ...uniqueMemoIds)+ .all<MemoSummaryRow>();++ if (rows.results.length !== uniqueMemoIds.length) {+ throw new AppError("missing_memos", "One or more memos cannot be found for this action in the expected state.", 400);+ }++ return rows.results.map(mapMemoSummary);+};++export const restoreMemosRecord = async (+ db: DatabaseAdapter,+ workspaceId: string,+ memoIds: string[],+ actor: { actorType: "user" | "agent"; actorId: string | null }+) => {+ const uniqueMemoIds = Array.from(new Set(memoIds));++ if (uniqueMemoIds.length === 0) {+ return 0;+ }++ const placeholders = uniqueMemoIds.map(() => "?").join(", ");+ const rows = await db+ .prepare(+ `SELECT m.id, m.notebook_id, m.title, m.tags_json, c.content_text+ FROM memos m+ INNER JOIN memo_contents c ON c.memo_id = m.id+ WHERE m.workspace_id = ? AND m.is_deleted = 1 AND m.id IN (${placeholders})`+ )+ .bind(workspaceId, ...uniqueMemoIds)+ .all<{ id: string; notebook_id: string; title: string | null; tags_json: string; content_text: string }>();++ if (rows.results.length !== uniqueMemoIds.length) {+ throw new AppError("missing_memos", "One or more memos cannot be restored.", 400);+ }++ const notebookIds = Array.from(new Set(rows.results.map((row) => row.notebook_id)));+ const notebookPlaceholders = notebookIds.map(() => "?").join(", ");+ const notebookRows = await db+ .prepare(`SELECT id FROM notebooks WHERE workspace_id = ? AND is_deleted = 0 AND id IN (${notebookPlaceholders})`)+ .bind(workspaceId, ...notebookIds)+ .all<{ id: string }>();+ const activeNotebookIds = new Set(notebookRows.results.map((row) => row.id));++ const needsInbox = rows.results.some((row) => !activeNotebookIds.has(row.notebook_id));++ const inbox = needsInbox+ ? await db.prepare(`SELECT id FROM notebooks WHERE workspace_id = ? AND slug = 'inbox' AND is_deleted = 0 LIMIT 1`).bind(workspaceId).first<{ id: string }>()+ : null;+ if (needsInbox && !inbox) {+ throw new AppError("restore_notebook_missing", "Original notebooks were deleted and the default inbox is unavailable.", 409);+ }++ const now = isoNow();+ const statements: PreparedStatementAdapter[] = [];++ for (const row of rows.results) {+ const restoreNotebookId = activeNotebookIds.has(row.notebook_id) ? row.notebook_id : inbox!.id;+ const tags = parseJsonArray(row.tags_json);++ statements.push(+ db+ .prepare(+ `UPDATE memos+ SET notebook_id = ?, is_deleted = 0, deleted_at = NULL, updated_at = ?+ WHERE id = ? AND workspace_id = ? AND is_deleted = 1`+ )+ .bind(restoreNotebookId, now, row.id, workspaceId),+ db+ .prepare(+ `UPDATE resources+ SET is_deleted = 0, deleted_at = NULL, updated_at = ?+ WHERE memo_id = ? AND is_deleted = 1`+ )+ .bind(now, row.id),+ upsertMemoSearchDocumentStatement(db, row.id, row.title, row.content_text, tags.join(" ")),+ auditStatement(db, actor.actorType, actor.actorId, "memo.restore", "memo", row.id, {+ fromNotebookId: row.notebook_id,+ toNotebookId: restoreNotebookId,+ })+ );+ }++ await db.batch(statements);+ return uniqueMemoIds.length;+};++export const restoreMemoRecord = async (+ db: DatabaseAdapter,+ workspaceId: string,+ memoId: string,+ actor: AuditActor,+): Promise<MemoDetail> => {+ const current = await getMemoDetailRow(db, workspaceId, memoId, true);+ if (!current || current.is_deleted === 0) {+ throw new AppError("not_found", "Memo not found in trash", 404);+ }++ await restoreMemosRecord(db, workspaceId, [memoId], actor);+ const memo = await getMemoDetail(db, workspaceId, memoId);+ if (!memo) throw new AppError("not_found", "Memo not found after restore", 404);+ return memo;+};++export const emptyTrashMemosRecord = async (+ env: Bindings,+ workspaceId: string,+ actor: { actorType: "user" | "agent"; actorId: string | null }+) => {+ const db = env.storage.db;+ const countRow = await db+ .prepare(+ `SELECT COUNT(*) AS count+ FROM memos+ WHERE workspace_id = ? AND is_deleted = 1`+ )+ .bind(workspaceId).first<{ count: number }>();+ const deleted = countRow?.count ?? 0;++ if (deleted === 0) {+ return 0;+ }++ const resourceRows = await db+ .prepare(+ `SELECT r.object_key, r.storage_config_id+ FROM resources r+ INNER JOIN memos m ON m.id = r.memo_id+ WHERE m.workspace_id = ? AND m.is_deleted = 1`+ )+ .bind(workspaceId).all<{ object_key: string; storage_config_id: string }>();++ if (resourceRows.results.length > 0) {+ await deleteStoredObjects(env, resourceRows.results);+ }++ await db.batch([+ db.prepare(`UPDATE resources SET original_memo_id = NULL WHERE original_memo_id IN (SELECT id FROM memos WHERE workspace_id = ? AND is_deleted = 1)`).bind(workspaceId),+ db.prepare(`DELETE FROM resources WHERE memo_id IN (SELECT id FROM memos WHERE workspace_id = ? AND is_deleted = 1)`).bind(workspaceId),+ db.prepare(`DELETE FROM memo_revisions WHERE memo_id IN (SELECT id FROM memos WHERE workspace_id = ? AND is_deleted = 1)`).bind(workspaceId),+ db.prepare(`DELETE FROM memo_contents WHERE memo_id IN (SELECT id FROM memos WHERE workspace_id = ? AND is_deleted = 1)`).bind(workspaceId),+ db.prepare(`DELETE FROM memos WHERE workspace_id = ? AND is_deleted = 1`).bind(workspaceId),+ auditStatement(db, actor.actorType, actor.actorId, "memo.trash_empty", "trash", "memos", { deleted }),+ ]);++ return deleted;+};++export const moveMemosToNotebook = async (+ db: DatabaseAdapter,+ workspaceId: string,+ memoIds: string[],+ notebookId: string,+ actor: { actorType: "user" | "agent"; actorId: string | null },+ actorLabel: string+) => {+ const uniqueMemoIds = Array.from(new Set(memoIds));++ if (uniqueMemoIds.length === 0) {+ return 0;+ }++ const placeholders = uniqueMemoIds.map(() => "?").join(", ");+ const rows = await db+ .prepare(+ `SELECT id, notebook_id+ FROM memos+ WHERE workspace_id = ? AND is_deleted = 0 AND id IN (${placeholders})`+ )+ .bind(workspaceId, ...uniqueMemoIds)+ .all<{ id: string; notebook_id: string }>();++ if (rows.results.length !== uniqueMemoIds.length) {+ throw new AppError("missing_memos", "One or more memos cannot be moved.", 400);+ }++ const now = isoNow();+ const statements: PreparedStatementAdapter[] = [+ db+ .prepare(+ `UPDATE memos+ SET notebook_id = ?, updated_by = ?, updated_at = ?+ WHERE workspace_id = ? AND is_deleted = 0 AND id IN (${placeholders})`+ )+ .bind(notebookId, actorLabel, now, workspaceId, ...uniqueMemoIds),+ ];++ for (const row of rows.results) {+ statements.push(+ auditStatement(db, actor.actorType, actor.actorId, "memo.move", "memo", row.id, {+ fromNotebookId: row.notebook_id,+ toNotebookId: notebookId,+ })+ );+ }++ await db.batch(statements);+ return uniqueMemoIds.length;+};++export const moveMemosRecord = async (+ db: DatabaseAdapter,+ workspaceId: string,+ memoIds: string[],+ notebookId: string,+ actor: AuditActor,+ actorLabel: string,+) => {+ if (!(await getNotebook(db, workspaceId, notebookId))) {+ throw new AppError("not_found", "Target notebook not found", 404);+ }+ return moveMemosToNotebook(db, workspaceId, memoIds, notebookId, actor, actorLabel);+};++export const mergeMemosRecord = async (+ db: DatabaseAdapter,+ workspaceId: string,+ input: { memoIds: string[]; notebookId?: string; title?: string },+ actor: { actorType: "user" | "agent"; actorId: string | null },+ actorLabel: string+) => {+ const uniqueMemoIds = Array.from(new Set(input.memoIds));++ if (uniqueMemoIds.length < 2) {+ throw new AppError("bad_request", "At least two memos are required to merge.", 400);+ }++ const placeholders = uniqueMemoIds.map(() => "?").join(", ");+ const rows = await 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, c.revision,+ c.content_json, c.content_markdown, c.content_text, c.content_hash,+ m.source_memo_ids, m.merge_source_count, m.merged_into_memo_id+ FROM memos m+ INNER JOIN memo_contents c ON c.memo_id = m.id+ WHERE m.workspace_id = ? AND m.id IN (${placeholders})`+ )+ .bind(workspaceId, ...uniqueMemoIds)+ .all<MemoDetailRow>();++ if (rows.results.length !== uniqueMemoIds.length) {+ throw new AppError("missing_memos", "One or more memos cannot be merged.", 400);+ }++ const activeRows = rows.results.filter((row) => !row.is_deleted);+ if (activeRows.length !== uniqueMemoIds.length) {+ // A desktop outbox retry can arrive after the first merge committed but+ // before the client acknowledged its local placeholder. When every source+ // now points at the same live merge result, return that result instead of+ // treating the retry as a new merge. This makes the operation recoverable+ // after a lost response without ever creating a second server-side memo.+ const mergedTargetIds = new Set(+ rows.results+ .filter((row) => row.is_deleted && row.merged_into_memo_id)+ .map((row) => row.merged_into_memo_id as string),+ );+ if (activeRows.length === 0 && mergedTargetIds.size === 1) {+ const [mergedTargetId] = mergedTargetIds;+ const completedMerge = await getMemoDetail(db, workspaceId, mergedTargetId);+ const completedSourceIds = new Set(completedMerge?.sourceMemoIds ?? []);+ if (+ completedMerge+ && completedMerge.sourceMemoIds.length === uniqueMemoIds.length+ && uniqueMemoIds.every((memoId) => completedSourceIds.has(memoId))+ ) {+ return completedMerge;+ }+ }+ throw new AppError("missing_memos", "One or more memos cannot be merged.", 400);+ }++ if (input.notebookId && !(await getNotebook(db, workspaceId, input.notebookId))) {+ throw new AppError("not_found", "Target notebook not found", 404);+ }++ const ordered = uniqueMemoIds+ .map((memoId) => rows.results.find((row) => row.id === memoId))+ .filter((row): row is MemoDetailRow => Boolean(row));+ const notebookId = input.notebookId ?? ordered[0].notebook_id;+ const title = resolveMergedMemoTitle(input.title, ordered);+ const sourceDocs = ordered.map((memo) => {+ const contentJson = parseDoc(memo.content_json);+ const doc = resolveMemoContentDoc(contentJson, memo.content_markdown);+ if (!docToText(doc).trim() && memo.content_text.trim()) {+ throw new AppError("merge_content_unavailable", "One or more memo bodies could not be recovered safely.", 409);+ }+ return doc;+ });+ const contentJson = mergeMemoDocs(sourceDocs);+ const mergedMarkdown = docToMarkdown(contentJson);+ const contentText = docToText(contentJson);+ const tags = Array.from(new Set(ordered.flatMap((memo) => parseJsonArray(memo.tags_json))));+ const excerpt = createExcerpt(contentText || title);+ const contentHash = await sha256(mergedMarkdown + JSON.stringify(contentJson));+ const newMemoId = createId("memo");+ const now = isoNow();++ await db.batch([+ db+ .prepare(+ `INSERT INTO memos (+ id, workspace_id, notebook_id, title, excerpt, tags_json, source_memo_ids, merge_source_count,+ created_by, updated_by, created_at, updated_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`+ )+ .bind(+ newMemoId,+ workspaceId,+ notebookId,+ title,+ excerpt,+ JSON.stringify(tags),+ JSON.stringify(uniqueMemoIds),+ uniqueMemoIds.length,+ actorLabel,+ actorLabel,+ now,+ now+ ),+ db+ .prepare(+ `INSERT INTO memo_contents (+ memo_id, content_json, content_markdown, content_text, content_hash, revision, created_at, updated_at+ ) VALUES (?, ?, ?, ?, ?, 0, ?, ?)`+ )+ .bind(newMemoId, JSON.stringify(contentJson), mergedMarkdown, contentText, contentHash, now, now),+ upsertMemoSearchDocumentStatement(db, newMemoId, title, contentText, tags.join(" ")),+ db+ .prepare(+ `UPDATE memos+ SET is_deleted = 1, deleted_at = ?, merged_into_memo_id = ?, merged_at = ?, updated_at = ?+ WHERE workspace_id = ? AND id IN (${placeholders})`+ )+ .bind(now, newMemoId, now, now, workspaceId, ...uniqueMemoIds),+ db.prepare(`DELETE FROM memo_shares WHERE workspace_id = ? AND memo_id IN (${placeholders})`).bind(workspaceId, ...uniqueMemoIds),+ deleteMemoSearchDocumentsStatement(db, uniqueMemoIds),+ db+ .prepare(+ `UPDATE resources+ SET original_memo_id = COALESCE(original_memo_id, memo_id),+ memo_id = ?,+ updated_at = ?+ WHERE memo_id IN (${placeholders})`+ )+ .bind(newMemoId, now, ...uniqueMemoIds),+ auditStatement(db, actor.actorType, actor.actorId, "memo.merge", "memo", newMemoId, {+ sourceMemoIds: uniqueMemoIds,+ }),+ ]);++ const memo = await getMemoDetail(db, workspaceId, newMemoId);++ if (!memo) {+ throw new AppError("not_found", "Merged memo not found after create.", 404);+ }++ return memo;+};++export const createMemoRecord = async (+ db: DatabaseAdapter,+ workspaceId: string,+ input: { notebookId: string; title?: string; contentMarkdown?: string; tags?: string[]; createdAt?: string; updatedAt?: string },+ actor: { actorType: "user" | "agent"; actorId: string | null },+ actorLabel: string+): Promise<MemoDetail> => {+ const tags = normalizeTags(input.tags);+ const contentMarkdown = input.contentMarkdown ?? "";+ const contentJson = markdownToDoc(contentMarkdown);+ const contentText = docToText(contentJson);+ const title = normalizeMemoTitle(input.title);+ const excerpt = createExcerpt(contentText);+ const contentHash = await sha256(contentMarkdown + JSON.stringify(contentJson));+ const id = createId("memo");+ const now = isoNow();+ const createdAt = input.createdAt ?? now;+ const updatedAt = input.updatedAt ?? now;++ await db.batch([+ db+ .prepare(+ `INSERT INTO memos (+ id, workspace_id, notebook_id, title, excerpt, tags_json, created_by, updated_by, created_at, updated_at+ ) SELECT ?, ?, id, ?, ?, ?, ?, ?, ?, ? FROM notebooks WHERE id = ? AND workspace_id = ? AND is_deleted = 0`+ )+ .bind(id, workspaceId, title, excerpt, JSON.stringify(tags), actorLabel, actorLabel, createdAt, updatedAt, input.notebookId, workspaceId),+ db+ .prepare(+ `INSERT INTO memo_contents (+ memo_id, content_json, content_markdown, content_text, content_hash, revision, created_at, updated_at+ ) VALUES (?, ?, ?, ?, ?, 0, ?, ?)`+ )+ .bind(id, JSON.stringify(contentJson), contentMarkdown, contentText, contentHash, createdAt, updatedAt),+ upsertMemoSearchDocumentStatement(db, id, title, contentText, tags.join(" ")),+ auditStatement(db, actor.actorType, actor.actorId, "memo.create", "memo", id, {+ notebookId: input.notebookId,+ }),+ ]);++ const memo = await getMemoDetail(db, workspaceId, id);++ if (!memo) {+ throw new Error("Memo was created but could not be read.");+ }++ return memo;+};++const normalizeImportSource = (value: string) => {+ const source = value.trim().toLocaleLowerCase("en-US");+ if (source.length > 80 || !/^[a-z0-9._-]+$/.test(source)) {+ throw new AppError(+ "invalid_import_source",+ "source must contain only letters, numbers, dots, underscores, or hyphens and be at most 80 characters",+ 400,+ );+ }+ return source;+};++const parseImportDateTime = (value: unknown, field: string) => {+ if (value === undefined) {+ return undefined;+ }+ if (typeof value !== "string" || !value.trim() || Number.isNaN(Date.parse(value))) {+ throw new Error(`${field} must be a valid ISO 8601 date-time`);+ }+ return value.trim();+};++const parseMemoImportItem = (value: unknown, index: number) => {+ if (!value || typeof value !== "object" || Array.isArray(value)) {+ throw new Error(`items[${index}] must be an object`);+ }++ const item = value as Record<string, unknown>;+ const externalId = getRequiredString(item.externalId, `items[${index}].externalId`);+ if (externalId.length > 512) {+ throw new Error(`items[${index}].externalId must be at most 512 characters`);+ }+ if (item.title !== undefined && typeof item.title !== "string") {+ throw new Error(`items[${index}].title must be a string`);+ }+ const title = typeof item.title === "string" ? item.title.trim() : undefined;+ if (title && title.length > 160) {+ throw new Error(`items[${index}].title must be at most 160 characters`);+ }+ if (item.contentMarkdown !== undefined && typeof item.contentMarkdown !== "string") {+ throw new Error(`items[${index}].contentMarkdown must be a string`);+ }+ if (item.tags !== undefined && (!Array.isArray(item.tags) || item.tags.some((tag) => typeof tag !== "string"))) {+ throw new Error(`items[${index}].tags must be an array of strings`);+ }+ if (Array.isArray(item.tags) && item.tags.length > 100) {+ throw new Error(`items[${index}].tags must contain at most 100 items`);+ }++ return {+ externalId,+ title: title || undefined,+ contentMarkdown: typeof item.contentMarkdown === "string" ? item.contentMarkdown : "",+ tags: Array.isArray(item.tags) ? (item.tags as string[]) : [],+ createdAt: parseImportDateTime(item.createdAt, `items[${index}].createdAt`),+ updatedAt: parseImportDateTime(item.updatedAt, `items[${index}].updatedAt`),+ };+};++const getMemoImportSource = async (db: DatabaseAdapter, workspaceId: string, source: string, externalId: string) =>+ db.prepare(+ `SELECT external_id, memo_id, source_updated_at+ FROM memo_import_sources+ WHERE workspace_id = ? AND source = ? AND external_id = ?`+ ).bind(workspaceId, source, externalId).first<MemoImportSourceRow>();++const discardUnlinkedImportedMemo = async (db: DatabaseAdapter, workspaceId: string, memoId: string) => {+ await db.batch([+ db.prepare(`DELETE FROM memo_revisions WHERE memo_id = ?`).bind(memoId),+ db.prepare(`DELETE FROM memo_contents WHERE memo_id = ?`).bind(memoId),+ db.prepare(`DELETE FROM memos WHERE id = ? AND workspace_id = ?`).bind(memoId, workspaceId),+ ]);+};++export const importMemosRecord = async (+ db: DatabaseAdapter,+ workspaceId: string,+ input: {+ source: string;+ notebookId: string;+ items: unknown;+ dryRun: boolean;+ actor: { actorType: "user" | "agent"; actorId: string | null };+ actorLabel: string;+ },+) => {+ const source = normalizeImportSource(input.source);+ if (!Array.isArray(input.items) || input.items.length === 0 || input.items.length > 25) {+ throw new AppError("invalid_import_items", "items must contain between 1 and 25 memos", 400);+ }+ const notebook = await getNotebook(db, workspaceId, input.notebookId);+ if (!notebook) {+ throw new AppError("not_found", "Import destination notebook not found in the authenticated user's workspace.", 404);+ }++ const results: Array<Record<string, unknown>> = [];++ for (const [index, rawItem] of input.items.entries()) {+ let externalId: string | null = null;+ let createdMemoId: string | null = null;++ try {+ const item = parseMemoImportItem(rawItem, index);+ externalId = item.externalId;+ const existing = await getMemoImportSource(db, workspaceId, source, externalId);+ if (existing) {+ results.push({+ index,+ externalId,+ status: "skipped",+ reason: "already_imported",+ memo: await getMemoDetail(db, workspaceId, existing.memo_id, true),+ sourceUpdatedAt: existing.source_updated_at,+ });+ continue;+ }++ if (input.dryRun) {+ results.push({ index, externalId, status: "would_create" });+ continue;+ }++ const memo = await createMemoRecord(db, workspaceId, {+ notebookId: notebook.id,+ title: item.title,+ contentMarkdown: item.contentMarkdown,+ tags: item.tags,+ createdAt: item.createdAt,+ updatedAt: item.updatedAt,+ }, input.actor, input.actorLabel);+ createdMemoId = memo.id;+ const now = isoNow();+ await db.batch([+ db.prepare(+ `INSERT INTO memo_import_sources (+ workspace_id, source, external_id, memo_id, source_updated_at, content_hash, created_at, updated_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`+ ).bind(workspaceId, source, externalId, memo.id, item.updatedAt ?? null, memo.contentHash, now, now),+ auditStatement(db, input.actor.actorType, input.actor.actorId, "memo.import", "memo", memo.id, {+ source,+ externalId,+ notebookId: notebook.id,+ }),+ ]);+ results.push({ index, externalId, status: "created", memo });+ } catch (error) {+ if (createdMemoId) {+ await discardUnlinkedImportedMemo(db, workspaceId, createdMemoId);+ const winner = externalId ? await getMemoImportSource(db, workspaceId, source, externalId) : null;+ if (winner) {+ results.push({+ index,+ externalId,+ status: "skipped",+ reason: "already_imported",+ memo: await getMemoDetail(db, workspaceId, winner.memo_id, true),+ sourceUpdatedAt: winner.source_updated_at,+ });+ continue;+ }+ }++ results.push({+ index,+ externalId,+ status: "failed",+ error: error instanceof Error ? error.message : "Import failed",+ });+ }+ }++ const count = (status: string) => results.filter((result) => result.status === status).length;+ return {+ dryRun: input.dryRun,+ source,+ notebookId: notebook.id,+ total: results.length,+ created: count("created"),+ skipped: count("skipped"),+ failed: count("failed"),+ wouldCreate: count("would_create"),+ results,+ };+};++export const updateMemoRecord = async (+ db: DatabaseAdapter,+ workspaceId: string,+ id: string,+ input: MemoUpdateInput,+ actor: { actorType: "user" | "agent"; actorId: string | null },+ actorLabel: string,+ requireEditSession = false,+): Promise<+ | { memo: MemoDetail; error?: never; message?: never; status?: never; details?: never }+ | { error: string; message: string; status?: number; details?: Record<string, unknown> }+> => {+ const current = await getMemoDetailRow(db, workspaceId, id);++ if (!current) {+ return { error: "not_found", message: "Memo not found" };+ }++ if (input.expectedRevision !== undefined && input.expectedRevision !== current.revision) {+ return {+ error: "revision_conflict",+ message: "Memo was updated elsewhere. Reload before saving.",+ status: 409,+ details: {+ expectedRevision: input.expectedRevision,+ currentRevision: current.revision,+ },+ };+ }++ const hasDocumentUpdate = input.contentJson !== undefined || input.contentMarkdown !== undefined;+ let editSession: MemoEditSessionRow | null = null;++ if (requireEditSession && hasDocumentUpdate) {+ if (!input.editSessionId || !input.expectedContentHash || input.expectedRevision === undefined) {+ return {+ error: "edit_session_required",+ message: "A bound edit session is required to save note content.",+ status: 428,+ };+ }++ if (input.expectedContentHash !== current.content_hash) {+ return {+ error: "content_conflict",+ message: "Note content changed after this edit session started.",+ status: 409,+ };+ }++ editSession = await db.prepare(+ `SELECT id, memo_id, actor_type, actor_id, base_revision, base_content_hash, expires_at+ FROM memo_edit_sessions+ WHERE id = ? AND memo_id = ? AND actor_type = ? AND actor_id IS ? AND expires_at > ?`,+ )+ .bind(input.editSessionId, id, actor.actorType, actor.actorId, isoNow())+ .first<MemoEditSessionRow>();++ if (+ !editSession ||+ !isMemoEditBindingValid(+ { memoId: id, revision: current.revision, contentHash: current.content_hash },+ {+ id: editSession.id,+ memoId: editSession.memo_id,+ baseRevision: editSession.base_revision,+ baseContentHash: editSession.base_content_hash,+ },+ {+ editSessionId: input.editSessionId,+ memoId: id,+ expectedRevision: input.expectedRevision,+ expectedContentHash: input.expectedContentHash,+ },+ )+ ) {+ return {+ error: "edit_session_conflict",+ message: "The edit session is stale or belongs to another note.",+ status: 409,+ };+ }+ }++ const isPinned = input.isPinned ?? Boolean(current.is_pinned);+ const hasContentUpdate =+ input.notebookId !== undefined ||+ input.title !== undefined ||+ input.contentJson !== undefined ||+ input.contentMarkdown !== undefined ||+ input.tags !== undefined ||+ input.createdAt !== undefined ||+ input.updatedAt !== undefined;+ const now = isoNow();+ const updatedAt = input.updatedAt ?? now;++ if (!hasContentUpdate) {+ if (input.isPinned === undefined || isPinned === Boolean(current.is_pinned)) {+ const memo = await getMemoDetail(db, workspaceId, id);++ if (!memo) {+ return { error: "not_found", message: "Memo not found after update" };+ }++ return { memo };+ }++ await db.batch([+ db+ .prepare(+ `UPDATE memos+ SET is_pinned = ?, updated_by = ?, updated_at = ?, created_at = COALESCE(?, created_at)+ WHERE id = ? AND workspace_id = ? AND is_deleted = 0`+ )+ .bind(isPinned ? 1 : 0, actorLabel, updatedAt, input.createdAt ?? null, id, workspaceId),+ auditStatement(db, actor.actorType, actor.actorId, isPinned ? "memo.pin" : "memo.unpin", "memo", id, {}),+ ]);++ const memo = await getMemoDetail(db, workspaceId, id);++ if (!memo) {+ return { error: "not_found", message: "Memo not found after update" };+ }++ return { memo };+ }++ const currentContentJson = parseDoc(current.content_json);+ const contentJson =+ input.contentJson !== undefined+ ? input.contentJson+ : input.contentMarkdown !== undefined+ ? markdownToDoc(input.contentMarkdown)+ : currentContentJson;+ const contentMarkdown =+ input.contentMarkdown !== undefined+ ? input.contentMarkdown+ : input.contentJson !== undefined+ ? docToMarkdown(contentJson)+ : current.content_markdown;+ const contentText = hasDocumentUpdate ? docToText(contentJson) : current.content_text;+ const title =+ input.title !== undefined ? normalizeMemoTitle(input.title) : normalizeMemoTitle(current.title);+ if (+ !input.allowDestructiveOverwrite &&+ isSuspiciousMemoOverwrite(current.title, current.content_text, title, contentText)+ ) {+ return {+ error: "suspicious_memo_overwrite",+ message: "Save blocked because the title changed while most of the note content disappeared.",+ };+ }+ const tags = input.tags === undefined ? parseJsonArray(current.tags_json) : normalizeTags(input.tags);+ const excerpt = createExcerpt(contentText);+ const notebookId = input.notebookId ?? current.notebook_id;+ const contentHash = await sha256(contentMarkdown + JSON.stringify(contentJson));+ const unchanged =+ notebookId === current.notebook_id+ && title === normalizeMemoTitle(current.title)+ && JSON.stringify(tags) === current.tags_json+ && isPinned === Boolean(current.is_pinned)+ && contentHash === current.content_hash+ && input.createdAt === undefined+ && input.updatedAt === undefined;++ if (unchanged) {+ return { memo: mapMemoDetail(current) };+ }++ const nextRevision = current.revision + 1;+ const revisionStatements = (await shouldSnapshotMemoRevisionService(db, current, title, JSON.stringify(tags), contentHash, updatedAt))+ ? [createMemoRevisionStatementService(db, current, actorLabel, updatedAt)]+ : [];+ const editSessionStatements = editSession+ ? [+ db.prepare(+ `UPDATE memo_edit_sessions+ SET base_revision = ?, base_content_hash = ?, updated_at = ?+ WHERE id = ? AND memo_id = ? AND base_revision = ? AND base_content_hash = ?`,+ ).bind(nextRevision, contentHash, updatedAt, editSession.id, id, current.revision, current.content_hash),+ ]+ : requireEditSession+ ? [+ db.prepare(+ `UPDATE memo_edit_sessions+ SET base_revision = ?, base_content_hash = ?, updated_at = ?+ WHERE memo_id = ? AND actor_type = ? AND actor_id IS ?+ AND base_revision = ? AND base_content_hash = ? AND expires_at > ?`,+ ).bind(+ nextRevision,+ contentHash,+ updatedAt,+ id,+ actor.actorType,+ actor.actorId,+ current.revision,+ current.content_hash,+ updatedAt,+ ),+ ]+ : [];++ await db.batch([+ ...revisionStatements,+ db+ .prepare(+ `UPDATE memos+ SET notebook_id = ?, title = ?, excerpt = ?, tags_json = ?, is_pinned = ?, updated_by = ?, updated_at = ?, created_at = COALESCE(?, created_at)+ WHERE id = ? AND workspace_id = ? AND is_deleted = 0+ AND EXISTS (SELECT 1 FROM notebooks n WHERE n.id = ? AND n.workspace_id = ? AND n.is_deleted = 0)`+ )+ .bind(notebookId, title, excerpt, JSON.stringify(tags), isPinned ? 1 : 0, actorLabel, updatedAt, input.createdAt ?? null, id, workspaceId, notebookId, workspaceId),+ db+ .prepare(+ `UPDATE memo_contents+ SET content_json = ?, content_markdown = ?, content_text = ?, content_hash = ?,+ revision = ?, updated_at = ?, created_at = COALESCE(?, created_at)+ WHERE memo_id = ?`+ )+ .bind(JSON.stringify(contentJson), contentMarkdown, contentText, contentHash, nextRevision, updatedAt, input.createdAt ?? null, id),+ upsertMemoSearchDocumentStatement(db, id, title, contentText, tags.join(" ")),+ ...editSessionStatements,+ auditStatement(db, actor.actorType, actor.actorId, "memo.update", "memo", id, {+ revision: nextRevision,+ }),+ ]);++ const memo = await getMemoDetail(db, workspaceId, id);++ if (!memo) {+ return { error: "not_found", message: "Memo not found after update" };+ }++ return { memo };+};++const parseDoc = (json: string): TiptapDoc => {+ try {+ const value = JSON.parse(json);+ return value && typeof value === "object" ? (value as TiptapDoc) : emptyDoc();+ } catch {+ return emptyDoc();+ }+};++const normalizeMemoTitle = (value: string | null | undefined) => {+ const title = value?.trim();+ return title || DEFAULT_MEMO_TITLE;+};diff --git a/apps/api/src/resource-service.ts b/apps/api/src/resource-service.tsindex a6f84be9..d0518b03 100644--- a/apps/api/src/resource-service.ts+++ b/apps/api/src/resource-service.ts@@ -3,7 +3,14 @@ import type {ResourceListItem,ResourceStorageSummary,} from "@edgeever/shared";+import { auditStatement } from "./audit";+import type { AppContext, AuditActor } from "./api-context";import { AppError } from "./app-error";+import { createId, isoNow } from "./entity-utils";+import { sha256Bytes } from "./hash-utils";+import { resolveObjectStorage } from "./object-storage";+import { getWorkspaceId } from "./request-auth";+import type { DatabaseAdapter } from "./storage-contract";export const MAX_IMAGE_UPLOAD_BYTES = 100 * 1024 * 1024;export const MAX_ATTACHMENT_UPLOAD_BYTES = 100 * 1024 * 1024;@@ -150,6 +157,201 @@ export const prepareImageForStorage = (input: {},});+export const getResourceRow = async (+ database: DatabaseAdapter,+ workspaceId: string,+ resourceId: string,+ includeDeleted = false,+): Promise<ResourceRow | null> =>+ database+ .prepare(+ `SELECT r.id, r.memo_id, r.original_memo_id, r.bucket_name, r.object_key, r.storage_config_id, r.kind, r.mime_type,+ r.filename, r.byte_size, r.sha256, r.width, r.height, r.created_at, r.updated_at, r.is_deleted+ FROM resources r+ INNER JOIN memos m ON m.id = r.memo_id+ WHERE r.id = ? AND m.workspace_id = ?${includeDeleted ? "" : " AND r.is_deleted = 0"}`,+ )+ .bind(resourceId, workspaceId)+ .first<ResourceRow>();++export const listResourcesForMemo = async (+ database: DatabaseAdapter,+ workspaceId: string,+ memoId: string,+): Promise<Resource[]> => {+ const rows = await database+ .prepare(+ `SELECT r.id, r.memo_id, r.original_memo_id, r.bucket_name, r.object_key, r.storage_config_id, r.kind, r.mime_type,+ r.filename, r.byte_size, r.sha256, r.width, r.height, r.created_at, r.updated_at+ FROM resources r+ INNER JOIN memos m ON m.id = r.memo_id+ WHERE r.memo_id = ? AND m.workspace_id = ? AND r.is_deleted = 0+ ORDER BY r.created_at ASC, r.id ASC`,+ )+ .bind(memoId, workspaceId)+ .all<ResourceRow>();++ return rows.results.map(mapResource);+};++export const listResourcesForMcp = async (+ database: DatabaseAdapter,+ workspaceId: string,+ limit: number,+) => {+ const [rows, stats] = await Promise.all([+ database.prepare(+ `SELECT r.id, r.memo_id, r.original_memo_id, r.bucket_name, r.object_key, r.storage_config_id, r.kind,+ r.mime_type, r.filename, r.byte_size, r.sha256, r.width, r.height,+ r.created_at, r.updated_at, m.title AS memo_title, m.excerpt AS memo_excerpt,+ m.is_deleted AS memo_is_deleted+ FROM resources r+ INNER JOIN memos m ON m.id = r.memo_id+ WHERE m.workspace_id = ? AND r.is_deleted = 0+ ORDER BY r.created_at DESC+ LIMIT ?`,+ ).bind(workspaceId, limit).all<ResourceListRow>(),+ database.prepare(+ `SELECT COUNT(*) AS total_count,+ COALESCE(SUM(byte_size), 0) AS total_bytes,+ COALESCE(SUM(CASE WHEN kind = 'image' THEN 1 ELSE 0 END), 0) AS image_count,+ COALESCE(SUM(CASE WHEN kind = 'attachment' THEN 1 ELSE 0 END), 0) AS attachment_count+ FROM resources r+ INNER JOIN memos m ON m.id = r.memo_id+ WHERE m.workspace_id = ? AND r.is_deleted = 0`,+ ).bind(workspaceId).first<ResourceStatsRow>(),+ ]);++ return {+ resources: rows.results.map(mapResourceListItem),+ summary: mapResourceStorageSummary(stats),+ };+};++type ResourceCreateInput = {+ memoId: string;+ filename: string;+ mimeType: string;+ bytes: Uint8Array;+ actor: AuditActor;+};++const storeResource = async (+ context: AppContext,+ input: ResourceCreateInput & {+ kind: "image" | "attachment";+ width: number | null;+ height: number | null;+ metadata: Record<string, unknown>;+ auditMetadata: Record<string, unknown>;+ objectKeyExtension?: string;+ },+) => {+ const resourceId = createId("res");+ const now = isoNow();+ const workspaceId = getWorkspaceId(context);+ const filename = normalizeFilename(input.filename) || `${resourceId}${input.objectKeyExtension ?? ""}`;+ const metadata = input.kind === "attachment"+ ? { ...input.metadata, originalFilename: filename }+ : input.metadata;+ const objectKey = `workspaces/${workspaceId}/memos/${input.memoId}/${resourceId}${input.objectKeyExtension ?? ""}`;+ const destination = await resolveObjectStorage(context.env);+ const checksum = await sha256Bytes(input.bytes);++ await destination.store.put(objectKey, input.bytes, {+ httpMetadata: {+ contentType: input.mimeType,+ cacheControl: "private, max-age=3600",+ },+ customMetadata: {+ memoId: input.memoId,+ resourceId,+ filename,+ },+ });++ try {+ await context.env.storage.db.batch([+ context.env.storage.db.prepare(+ `INSERT INTO resources (+ id, memo_id, bucket_name, object_key, storage_config_id, kind, mime_type, filename,+ byte_size, sha256, width, height, metadata_json, created_at, updated_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,+ ).bind(+ resourceId,+ input.memoId,+ destination.bucketName,+ objectKey,+ destination.configId,+ input.kind,+ input.mimeType,+ filename,+ input.bytes.byteLength,+ checksum,+ input.width,+ input.height,+ JSON.stringify(metadata),+ now,+ now,+ ),+ auditStatement(+ context.env.storage.db,+ input.actor.actorType,+ input.actor.actorId,+ "resource.create",+ "resource",+ resourceId,+ { memoId: input.memoId, mimeType: input.mimeType, byteSize: input.bytes.byteLength, ...input.auditMetadata },+ ),+ ]);+ } catch (error) {+ await destination.store.delete(objectKey);+ throw error;+ }++ const resource = await getResourceRow(context.env.storage.db, workspaceId, resourceId);+ if (!resource) {+ throw new AppError("not_found", "Resource not found", 404);+ }+ return mapResource(resource);+};++export const createImageResource = async (+ context: AppContext,+ input: ResourceCreateInput & { source: "upload" | "mcp" },+): Promise<Resource> => {+ validateImageUpload(input.mimeType, input.bytes.byteLength);+ const processed = prepareImageForStorage(input);+ const extension = inferImageExtension(processed.filename, processed.mimeType);+ return storeResource(context, {+ ...input,+ filename: processed.filename,+ mimeType: processed.mimeType,+ bytes: processed.bytes,+ kind: "image",+ width: processed.width,+ height: processed.height,+ metadata: processed.metadata,+ auditMetadata: { compressed: processed.compressed },+ objectKeyExtension: extension,+ });+};++export const createAttachmentResource = async (+ context: AppContext,+ input: ResourceCreateInput,+): Promise<Resource> => {+ validateAttachmentUpload(input.bytes.byteLength);+ return storeResource(context, {+ ...input,+ kind: "attachment",+ width: null,+ height: null,+ metadata: {},+ auditMetadata: {},+ });+};+const encodeRfc5987Value = (value: string) => encodeURIComponent(value.replace(/[\uD800-\uDFFF]/gu, "\uFFFD"),).replace(/['()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);diff --git a/apps/api/src/self-hosted-storage-adapter.ts b/apps/api/src/self-hosted-storage-adapter.tsindex 0c3ddf7d..0e64564b 100644--- a/apps/api/src/self-hosted-storage-adapter.ts+++ b/apps/api/src/self-hosted-storage-adapter.ts@@ -4,6 +4,8 @@ import type {BlobObjectAdapter,BlobStoreAdapter,DatabaseAdapter,+ DatabaseQueryResult,+ PreparedStatementAdapter,RelationalDatabaseDialect,StorageAdapter,} from "./storage-contract";@@ -20,7 +22,10 @@ export type SqliteDatabaseLike = {export const SELF_HOSTED_DATABASE_DIALECT: RelationalDatabaseDialect = "sqlite";-class SqlitePreparedStatement {+const sqliteResultMeta = (result: unknown): Record<string, unknown> =>+ result && typeof result === "object" ? { ...result as Record<string, unknown> } : {};++class SqlitePreparedStatement implements PreparedStatementAdapter {constructor(private readonly sqlite: SqliteDatabaseLike,readonly sql: string,@@ -31,36 +36,48 @@ class SqlitePreparedStatement {return new SqlitePreparedStatement(this.sqlite, this.sql, bindings);}- async all() {+ async all<T = Record<string, unknown>>(): Promise<DatabaseQueryResult<T>> {return {- results: this.sqlite.query(this.sql).all(...this.bindings),+ results: this.sqlite.query(this.sql).all(...this.bindings) as T[],success: true,meta: {},};}- async first<T = Record<string, unknown>>() {- return (this.sqlite.query(this.sql).get(...this.bindings) as T | null | undefined) ?? null;+ async first<T = unknown>(columnName: string): Promise<T | null>;+ async first<T = Record<string, unknown>>(): Promise<T | null>;+ async first<T>(columnName?: string): Promise<T | null> {+ const row = this.sqlite.query(this.sql).get(...this.bindings);+ if (row === null || row === undefined) return null;+ if (columnName === undefined) return row as T;+ if (typeof row !== "object" || !(columnName in row)) return null;+ return (row as Record<string, unknown>)[columnName] as T;}- async run() {- this.sqlite.query(this.sql).run(...this.bindings);- return { success: true, meta: {} };+ async run<T = Record<string, unknown>>(): Promise<DatabaseQueryResult<T>> {+ const result = this.sqlite.query(this.sql).run(...this.bindings);+ return { results: [], success: true, meta: sqliteResultMeta(result) };}}-class SqliteDatabaseAdapter {+class SqliteDatabaseAdapter implements DatabaseAdapter {constructor(private readonly sqlite: SqliteDatabaseLike) {}prepare(sql: string) {return new SqlitePreparedStatement(this.sqlite, sql);}- async batch(statements: SqlitePreparedStatement[]) {- const results: unknown[] = [];+ async batch<T = unknown>(+ statements: PreparedStatementAdapter[],+ ): Promise<DatabaseQueryResult<T>[]> {+ const results: DatabaseQueryResult<T>[] = [];this.sqlite.transaction(() => {for (const statement of statements) {- results.push(this.sqlite.query(statement.sql).run(...statement.bindings));+ if (!(statement instanceof SqlitePreparedStatement)) {+ throw new TypeError("SQLite batches can only execute statements prepared by the same adapter");+ }+ const result = this.sqlite.query(statement.sql).run(...statement.bindings);+ results.push({ results: [], success: true, meta: sqliteResultMeta(result) });}})();return results;@@ -164,7 +181,7 @@ export const createSelfHostedStorageAdapter = (sqlite: SqliteDatabaseLike,resourcesDirectory: string,): StorageAdapter => ({- db: new SqliteDatabaseAdapter(sqlite) as unknown as DatabaseAdapter,+ db: new SqliteDatabaseAdapter(sqlite),resources: createLocalBlobStore(resourcesDirectory),diagnostics: {database: "sqlite",diff --git a/apps/api/src/storage-contract.ts b/apps/api/src/storage-contract.tsindex 8eb169d6..4558e8bc 100644--- a/apps/api/src/storage-contract.ts+++ b/apps/api/src/storage-contract.ts@@ -1,15 +1,33 @@/*** Platform-neutral storage seams used by the API layer.*- * The current production adapter is Cloudflare D1/R2, so these contracts are- * intentionally compatible with the Workers runtime types. A future- * self-hosted adapter can implement the same operations with SQLite and a- * filesystem or S3-compatible object store without changing route logic.+ * These contracts describe only the operations consumed by application code.+ * Runtime adapters translate D1, SQLite, R2, filesystem, or S3 primitives into+ * these shapes without leaking provider SDK types into routes and services.*/-import type { D1Database, D1PreparedStatement } from "@cloudflare/workers-types";+export type DatabaseOperationResult = {+ success: true;+ meta: Record<string, unknown>;+};++export type DatabaseQueryResult<T = unknown> = DatabaseOperationResult & {+ results: T[];+};-export type DatabaseAdapter = Pick<D1Database, "prepare" | "batch">;-export type PreparedStatementAdapter = D1PreparedStatement;+export type PreparedStatementAdapter = {+ bind: (...values: unknown[]) => PreparedStatementAdapter;+ first: {+ <T = unknown>(columnName: string): Promise<T | null>;+ <T = Record<string, unknown>>(): Promise<T | null>;+ };+ run: <T = Record<string, unknown>>() => Promise<DatabaseQueryResult<T>>;+ all: <T = Record<string, unknown>>() => Promise<DatabaseQueryResult<T>>;+};++export type DatabaseAdapter = {+ prepare: (query: string) => PreparedStatementAdapter;+ batch: <T = unknown>(statements: PreparedStatementAdapter[]) => Promise<DatabaseQueryResult<T>[]>;+};export type BlobRange = {offset: number;@@ -55,9 +73,9 @@ export type StorageAdapter = {export type RelationalDatabaseDialect = "sqlite" | "postgresql";/**- * Future driver-neutral relational contract. The current API still consumes- * the D1-compatible DatabaseAdapter above; this contract prevents a future- * PostgreSQL implementation from leaking driver-specific calls into routes.+ * Future transaction-oriented relational contract. The current API consumes+ * the statement-oriented DatabaseAdapter above; this contract prevents a+ * future PostgreSQL implementation from leaking driver calls into routes.*/export type RelationalDatabaseAdapter = {readonly dialect: RelationalDatabaseDialect;@@ -66,12 +84,6 @@ export type RelationalDatabaseAdapter = {transaction<T>(callback: (database: RelationalDatabaseAdapter) => Promise<T>): Promise<T>;};-/** Cloudflare's native Worker bindings, used only by the platform adapter. */-export type CloudflareStorageBindings = {- DB: DatabaseAdapter;- RESOURCES: BlobStoreAdapter;-};-export type StorageAdapterKind = "cloudflare" | "self_hosted";/** Configuration shared by the future SQLite/filesystem implementation. */diff --git a/apps/api/src/workspace-stats-service.ts b/apps/api/src/workspace-stats-service.tsnew file mode 100644index 00000000..57e7c330--- /dev/null+++ b/apps/api/src/workspace-stats-service.ts@@ -0,0 +1,50 @@+import { mapResourceStorageSummary, type ResourceStatsRow } from "./resource-service";+import type { DatabaseAdapter } from "./storage-contract";++export const getWorkspaceStats = async (+ database: DatabaseAdapter,+ workspaceId: string,+) => {+ const [memoCounts, notebookCount, tagCount, resourceStats] = await Promise.all([+ database.prepare(+ `SELECT+ COUNT(*) AS total,+ COALESCE(SUM(CASE WHEN is_deleted = 0 THEN 1 ELSE 0 END), 0) AS active,+ COALESCE(SUM(CASE WHEN is_deleted = 1 THEN 1 ELSE 0 END), 0) AS trashed,+ COALESCE(SUM(CASE WHEN is_deleted = 0 AND is_pinned = 1 THEN 1 ELSE 0 END), 0) AS pinned,+ COALESCE(SUM(CASE WHEN is_deleted = 0 AND tags_json = '[]' THEN 1 ELSE 0 END), 0) AS untagged+ FROM memos WHERE workspace_id = ?`,+ ).bind(workspaceId).first<{ total: number; active: number; trashed: number; pinned: number; untagged: number }>(),+ database.prepare(+ `SELECT COUNT(*) AS count FROM notebooks WHERE workspace_id = ? AND is_deleted = 0`,+ ).bind(workspaceId).first<{ count: number }>(),+ database.prepare(+ `SELECT COUNT(DISTINCT mt.name) AS count+ FROM memo_tags mt+ INNER JOIN memos m ON m.id = mt.memo_id AND m.workspace_id = mt.workspace_id+ WHERE mt.workspace_id = ? AND m.is_deleted = 0`,+ ).bind(workspaceId).first<{ count: number }>(),+ database.prepare(+ `SELECT COUNT(*) AS total_count,+ COALESCE(SUM(byte_size), 0) AS total_bytes,+ COALESCE(SUM(CASE WHEN kind = 'image' THEN 1 ELSE 0 END), 0) AS image_count,+ COALESCE(SUM(CASE WHEN kind = 'attachment' THEN 1 ELSE 0 END), 0) AS attachment_count+ FROM resources r+ INNER JOIN memos m ON m.id = r.memo_id+ WHERE m.workspace_id = ? AND r.is_deleted = 0`,+ ).bind(workspaceId).first<ResourceStatsRow>(),+ ]);++ return {+ memos: {+ total: memoCounts?.total ?? 0,+ active: memoCounts?.active ?? 0,+ trashed: memoCounts?.trashed ?? 0,+ pinned: memoCounts?.pinned ?? 0,+ untagged: memoCounts?.untagged ?? 0,+ },+ notebooks: { active: notebookCount?.count ?? 0 },+ tags: { active: tagCount?.count ?? 0 },+ resources: mapResourceStorageSummary(resourceStats),+ };+};diff --git a/apps/desktop/src/main/rpc.mjs b/apps/desktop/src/main/rpc.mjsindex a6db4ae2..ebe2dbaf 100644--- a/apps/desktop/src/main/rpc.mjs+++ b/apps/desktop/src/main/rpc.mjs@@ -1,11 +1,14 @@import { createInterface } from "node:readline";+export const SIDECAR_PROTOCOL_VERSION = 2;+export class SidecarRpcClient {#child;#nextId = 1;#pending = new Map();#ready = null;#readyMessage = null;+ #readyError = null;constructor(child) {this.#child = child;@@ -29,6 +32,15 @@ export class SidecarRpcClient {}if (message.event === "ready") {+ if (message.protocolVersion !== SIDECAR_PROTOCOL_VERSION) {+ const error = new Error(+ `Unsupported EdgeEver sidecar protocol: expected ${SIDECAR_PROTOCOL_VERSION}, received ${message.protocolVersion ?? "unknown"}`,+ );+ this.#readyError = error;+ this.#ready?.reject(error);+ this.#ready = null;+ return;+ }this.#readyMessage = message;this.#ready?.resolve(message);this.#ready = null;@@ -44,6 +56,7 @@ export class SidecarRpcClient {waitUntilReady(timeoutMs = 5000) {if (this.#readyMessage) return Promise.resolve(this.#readyMessage);+ if (this.#readyError) return Promise.reject(this.#readyError);if (!this.#ready) {this.#ready = {};this.#ready.promise = new Promise((resolve, reject) => {diff --git a/apps/desktop/src/main/rpc.test.mjs b/apps/desktop/src/main/rpc.test.mjsnew file mode 100644index 00000000..795f6d02--- /dev/null+++ b/apps/desktop/src/main/rpc.test.mjs@@ -0,0 +1,30 @@+import assert from "node:assert/strict";+import { EventEmitter } from "node:events";+import { PassThrough } from "node:stream";+import test from "node:test";+import { SidecarRpcClient, SIDECAR_PROTOCOL_VERSION } from "./rpc.mjs";++const createChild = () => {+ const child = new EventEmitter();+ child.stdout = new PassThrough();+ child.stdin = new PassThrough();+ return child;+};++test("sidecar RPC client accepts the supported protocol", async () => {+ const child = createChild();+ const client = new SidecarRpcClient(child);+ const ready = client.waitUntilReady(100);+ child.stdout.write(`${JSON.stringify({ event: "ready", protocolVersion: SIDECAR_PROTOCOL_VERSION })}\n`);+ await assert.doesNotReject(ready);+});++test("sidecar RPC client rejects an incompatible protocol before requests start", async () => {+ const child = createChild();+ const client = new SidecarRpcClient(child);+ child.stdout.write(`${JSON.stringify({ event: "ready", protocolVersion: SIDECAR_PROTOCOL_VERSION + 1 })}\n`);+ await assert.rejects(+ client.waitUntilReady(100),+ /Unsupported EdgeEver sidecar protocol/,+ );+});diff --git a/apps/ios/EdgeEver/Data/Sync/SyncProtocol.swift b/apps/ios/EdgeEver/Data/Sync/SyncProtocol.swiftindex e08b541a..f7dd7ce0 100644--- a/apps/ios/EdgeEver/Data/Sync/SyncProtocol.swift+++ b/apps/ios/EdgeEver/Data/Sync/SyncProtocol.swift@@ -1,6 +1,6 @@import Foundation-/// Port of `apps/mobile/src/lib/mobile-sync-protocol.ts`.+/// Native counterpart of the shared TypeScript sync-state contract in `packages/shared/src/sync.ts`.enum SyncProtocol {static func hasCursorRewound(localCursor: Int, serverCursor: Int?) -> Bool {guard let serverCursor else { return false }diff --git a/apps/mobile/src/hooks/useMobileWorkspaceSelection.test.ts b/apps/mobile/src/hooks/useMobileWorkspaceSelection.test.tsnew file mode 100644index 00000000..9aa93985--- /dev/null+++ b/apps/mobile/src/hooks/useMobileWorkspaceSelection.test.ts@@ -0,0 +1,22 @@+import { expect, test } from "bun:test";+import {+ remapSelectedMemo,+ toggleVisibleMemoSelection,+} from "./useMobileWorkspaceSelection";++test("toggleVisibleMemoSelection selects and clears only visible memos", () => {+ expect([...toggleVisibleMemoSelection(new Set(["hidden"]), ["memo-1", "memo-2"])]).toEqual([+ "hidden",+ "memo-1",+ "memo-2",+ ]);+ expect([...toggleVisibleMemoSelection(new Set(["hidden", "memo-1", "memo-2"]), ["memo-1", "memo-2"])]).toEqual([+ "hidden",+ ]);+});++test("remapSelectedMemo replaces a temporary id without touching unrelated selections", () => {+ const selected = new Set(["local:1", "memo-2"]);+ expect([...remapSelectedMemo(selected, "local:1", "memo-1")]).toEqual(["memo-2", "memo-1"]);+ expect(remapSelectedMemo(selected, "missing", "memo-3")).toBe(selected);+});diff --git a/apps/mobile/src/hooks/useMobileWorkspaceSelection.ts b/apps/mobile/src/hooks/useMobileWorkspaceSelection.tsnew file mode 100644index 00000000..0cdfe952--- /dev/null+++ b/apps/mobile/src/hooks/useMobileWorkspaceSelection.ts@@ -0,0 +1,98 @@+import { useCallback, useState } from "react";+import { toggleMobileMemoSelection } from "@edgeever/shared/mobile-ui";++export const toggleVisibleMemoSelection = (+ current: ReadonlySet<string>,+ visibleMemoIds: readonly string[],+) => {+ const next = new Set(current);+ const allVisibleSelected = visibleMemoIds.length > 0+ && visibleMemoIds.every((memoId) => next.has(memoId));++ for (const memoId of visibleMemoIds) {+ if (allVisibleSelected) {+ next.delete(memoId);+ } else {+ next.add(memoId);+ }+ }++ return next;+};++export const remapSelectedMemo = (+ current: Set<string>,+ temporaryId: string,+ persistedId: string,+) => {+ if (!current.has(temporaryId)) {+ return current;+ }++ const next = new Set(current);+ next.delete(temporaryId);+ next.add(persistedId);+ return next;+};++export const useMobileWorkspaceSelection = () => {+ const [selectionMode, setSelectionMode] = useState(false);+ const [selectedMemoIds, setSelectedMemoIds] = useState<Set<string>>(() => new Set());+ const [selectionMoveOpen, setSelectionMoveOpen] = useState(false);+ const [selectionMoreOpen, setSelectionMoreOpen] = useState(false);++ const clearSelection = useCallback(() => {+ setSelectionMode(false);+ setSelectedMemoIds(new Set());+ setSelectionMoveOpen(false);+ setSelectionMoreOpen(false);+ }, []);++ const enterSelectionMode = useCallback(() => {+ setSelectionMode(true);+ }, []);++ const toggleSelectedMemo = useCallback((memoId: string) => {+ setSelectionMode(true);+ setSelectedMemoIds((current) => toggleMobileMemoSelection(current, memoId));+ }, []);++ const selectSingleMemo = useCallback((memoId: string) => {+ setSelectionMode(true);+ setSelectedMemoIds(new Set([memoId]));+ }, []);++ const toggleVisibleSelection = useCallback((visibleMemoIds: readonly string[]) => {+ if (visibleMemoIds.length === 0) {+ return;+ }++ setSelectionMode(true);+ setSelectedMemoIds((current) => toggleVisibleMemoSelection(current, visibleMemoIds));+ }, []);++ const remapSelectedMemoId = useCallback((temporaryId: string, persistedId: string) => {+ setSelectedMemoIds((current) => remapSelectedMemo(current, temporaryId, persistedId));+ }, []);++ const restoreSelection = useCallback((mode: boolean, memoIds: ReadonlySet<string>) => {+ setSelectionMode(mode);+ setSelectedMemoIds(new Set(memoIds));+ }, []);++ return {+ clearSelection,+ enterSelectionMode,+ remapSelectedMemoId,+ restoreSelection,+ selectedMemoIds,+ selectionMode,+ selectionMoreOpen,+ selectionMoveOpen,+ selectSingleMemo,+ setSelectionMoreOpen,+ setSelectionMoveOpen,+ toggleSelectedMemo,+ toggleVisibleSelection,+ };+};diff --git a/apps/mobile/src/lib/local-mirror.test.ts b/apps/mobile/src/lib/local-mirror.test.tsindex ec4f7db5..b14686df 100644--- a/apps/mobile/src/lib/local-mirror.test.ts+++ b/apps/mobile/src/lib/local-mirror.test.ts@@ -1,34 +1,39 @@import { expect, test } from "bun:test";-import { hasMobileSyncCursorRewound, hasMobileSyncIdentityChanged, isMobileSyncMetadataInitialized, splitMobileBootstrapWriteBatches } from "./mobile-sync-protocol";+import {+ hasSyncCursorRewound,+ hasSyncIdentityChanged,+ isSyncMetadataInitialized,+ splitSyncBootstrapWriteBatches,+} from "@edgeever/shared";test("rebuilds the mobile mirror when the server change cursor rewinds", () => {- expect(hasMobileSyncCursorRewound(42, 7)).toBe(true);- expect(hasMobileSyncCursorRewound(42, 42)).toBe(false);- expect(hasMobileSyncCursorRewound(42, 64)).toBe(false);+ expect(hasSyncCursorRewound(42, 7)).toBe(true);+ expect(hasSyncCursorRewound(42, 42)).toBe(false);+ expect(hasSyncCursorRewound(42, 64)).toBe(false);});test("keeps compatibility with servers that do not report their current cursor", () => {- expect(hasMobileSyncCursorRewound(42)).toBe(false);+ expect(hasSyncCursorRewound(42)).toBe(false);});test("rebuilds the mobile mirror when the server data identity changes", () => {- expect(hasMobileSyncIdentityChanged("workspace-created-at-a", "workspace-created-at-b")).toBe(true);- expect(hasMobileSyncIdentityChanged("workspace-created-at-a", "workspace-created-at-a")).toBe(false);+ expect(hasSyncIdentityChanged("workspace-created-at-a", "workspace-created-at-b")).toBe(true);+ expect(hasSyncIdentityChanged("workspace-created-at-a", "workspace-created-at-a")).toBe(false);});test("keeps compatibility with servers that do not report a data identity", () => {- expect(hasMobileSyncIdentityChanged("legacy")).toBe(false);+ expect(hasSyncIdentityChanged("legacy")).toBe(false);});test("waits for a complete local mirror before rendering an empty notebook", () => {- expect(isMobileSyncMetadataInitialized("42", "workspace-a")).toBe(true);- expect(isMobileSyncMetadataInitialized(null, "workspace-a")).toBe(false);- expect(isMobileSyncMetadataInitialized("42", null)).toBe(false);- expect(isMobileSyncMetadataInitialized("not-a-number", "workspace-a")).toBe(false);+ expect(isSyncMetadataInitialized("42", "workspace-a")).toBe(true);+ expect(isSyncMetadataInitialized(null, "workspace-a")).toBe(false);+ expect(isSyncMetadataInitialized("42", null)).toBe(false);+ expect(isSyncMetadataInitialized("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([[]]);+ expect(splitSyncBootstrapWriteBatches(items, 50).map((batch) => batch.length)).toEqual([50, 50, 23]);+ expect(splitSyncBootstrapWriteBatches([], 50)).toEqual([[]]);});diff --git a/apps/mobile/src/lib/local-mirror.ts b/apps/mobile/src/lib/local-mirror.tsindex cb005805..6477215e 100644--- a/apps/mobile/src/lib/local-mirror.ts+++ b/apps/mobile/src/lib/local-mirror.ts@@ -1,7 +1,14 @@import type { createEdgeEverClient, ListMemosResponse, MemoFilterMode, MemoSortMode } from "@edgeever/client";-import type { MemoDetail, MemoSummary, Notebook, TagSummary } from "@edgeever/shared";+import {+ hasSyncStateReset,+ isSyncMetadataInitialized,+ splitSyncBootstrapWriteBatches,+ type MemoDetail,+ type MemoSummary,+ type Notebook,+ type TagSummary,+} from "@edgeever/shared";import * as SQLite from "expo-sqlite";-import { hasMobileSyncCursorRewound, hasMobileSyncIdentityChanged, isMobileSyncMetadataInitialized, splitMobileBootstrapWriteBatches } from "./mobile-sync-protocol";import { summarizeMobileTags } from "./mobile-tags";const DATABASE_NAME = "edgeever-mobile.db";@@ -50,7 +57,7 @@ export const isMobileLocalMirrorInitialized = async (scope: string) => {const metadata = new Map(rows.map((row) => [row.key, row.value]));const cursorValue = metadata.get("cursor");const identityValue = metadata.get("identity");- return isMobileSyncMetadataInitialized(cursorValue, identityValue);+ return isSyncMetadataInitialized(cursorValue, identityValue);};export const listLocalNotebooks = async (scope: string): Promise<{ notebooks: Notebook[] }> => {@@ -262,7 +269,7 @@ const performMobileLocalMirrorSync = async (snapshotCursor = page.snapshotCursor;snapshotIdentity = page.syncIdentity || "legacy";}- const writeBatches = splitMobileBootstrapWriteBatches(page.memos, BOOTSTRAP_WRITE_BATCH_SIZE);+ const writeBatches = splitSyncBootstrapWriteBatches(page.memos, BOOTSTRAP_WRITE_BATCH_SIZE);for (const [batchIndex, memos] of writeBatches.entries()) {await db.withExclusiveTransactionAsync(async (tx) => {if (batchIndex === 0) {@@ -290,7 +297,10 @@ const performMobileLocalMirrorSync = async (while (true) {const page = await client.getMobileSyncChanges(cursor, CHANGE_PAGE_SIZE);- if (hasMobileSyncCursorRewound(cursor, page.serverCursor) || hasMobileSyncIdentityChanged(syncIdentity, page.syncIdentity)) {+ if (hasSyncStateReset(+ { cursor, syncIdentity },+ { serverCursor: page.serverCursor, syncIdentity: page.syncIdentity },+ )) {// A restored/replaced server database can legitimately restart its// change sequence. Rebuild the mirror instead of treating the stale// local cursor as proof that no remote notes exist.diff --git a/apps/mobile/src/lib/mobile-sync-protocol.ts b/apps/mobile/src/lib/mobile-sync-protocol.tsdeleted file mode 100644index 1b4eae20..00000000--- a/apps/mobile/src/lib/mobile-sync-protocol.ts+++ /dev/null@@ -1,21 +0,0 @@-export const hasMobileSyncCursorRewound = (localCursor: number, serverCursor?: number) =>- typeof serverCursor === "number" && Number.isFinite(serverCursor) && serverCursor < localCursor;--export const hasMobileSyncIdentityChanged = (localIdentity: string, serverIdentity?: string) =>- typeof serverIdentity === "string" && serverIdentity.length > 0 && serverIdentity !== localIdentity;--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/screens/WorkspaceEditors.tsx b/apps/mobile/src/screens/WorkspaceEditors.tsxnew file mode 100644index 00000000..ad2c7245--- /dev/null+++ b/apps/mobile/src/screens/WorkspaceEditors.tsx@@ -0,0 +1,1251 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useMutation, useQueryClient, type UseMutationResult } from "@tanstack/react-query";+import { File as ExpoFile } from "expo-file-system";+import { ActivityIndicator, Check, ChevronDown, ChevronLeft, RotateCcw } from "../components/icons";+import { BackHandler, KeyboardAvoidingView, Platform, View } from "react-native";+import { SafeAreaView } from "react-native-safe-area-context";+import { Alert, Pressable, Text, TextInput } from "../components/LocalizedText";+import {+ createExcerpt,+ DEFAULT_MEMO_TITLE,+ docToMarkdown,+ docToText,+ markdownToDoc,+ resolveMemoContentDoc,+ type MemoDetail,+ type Notebook,+ type TiptapDoc,+} from "@edgeever/shared";+import {+ clearMobileMemoDraft,+ clearMobileNewMemoDraft,+ writeMobileMemoDraft,+ type MobileMemoDraft,+} from "../lib/mobile-drafts";+import { useMobileLocale } from "../lib/mobile-locale";+import { useSession } from "../lib/session";+import { queueMobileMemoCreate, queueMobileMemoUpdate } from "../lib/sync-queue";+import { createMobileDataScope, upsertLocalMemo } from "../lib/local-mirror";+import { recordEditorStartup } from "../lib/startup-performance";+import { prepareUploadAsset, type MobileImageUploadAsset } from "../lib/mobile-image-upload";+import MobileWebClipCapture from "../components/MobileWebClipCapture";+import LocalTiptapEditor, { type LocalTiptapEditorRef } from "../components/LocalTiptapEditor";+import { SAFE_DOM_WEBVIEW_PROPS } from "../lib/mobile-dom";+import { safeDomCall } from "../lib/safe-dom-call";+import { applyMobileEditorUpload, cancelMobileEditorUpload, flushMobileEditor } from "../lib/mobile-editor-controller";+import { showEdgeEverKeyboard } from "../../modules/edgeever-keyboard";+import { MobileResourceActions } from "../components/MobileResourceActions";+import { MobileTemplatePickerModal } from "../components/MobileTemplatePicker";+import { useMobileTheme } from "../lib/mobile-theme";+import { createMemoSeedHasContent, type MobileCreateMemoSeed } from "../lib/mobile-templates";+import { createMobileDraftWriteBarrier } from "../lib/mobile-draft-write-barrier";+import {+ type MobileSharedImage,+ type MobileWebClipDraft,+} from "../lib/mobile-web-clip";+import { useMobileEditorResourceActions } from "../hooks/useMobileEditorResourceActions";+import { useMobileEditorUploadAsset } from "../hooks/useMobileEditorUploadAsset";+import { useMobileSelectionAi } from "../hooks/useMobileSelectionAi";+import { parseTags } from "./workspace-utils";+import { createOptimisticMemo, type MobileMemoUpdatePayload } from "./workspace-memo-cache";+import { styles } from "./workspace-styles";+import { NotebookPickerModal, SmartTagButton, TagPickerModal } from "./WorkspacePickers";+import {+ deleteMobileResourceFromDoc,+ getMobileResourceUpdatePayload,+ renameMobileResourceInDoc,+ type MobileResourceTarget,+} from "../lib/mobile-attachments";+import {+ createOnceProtectedResourceFailureNotifier,+ type ProtectedResourceLoadFailure,+} from "../lib/mobile-protected-resources";++type MobileMemoUpdateMutation = UseMutationResult<MemoDetail, Error, { memo: MemoDetail; payload: MobileMemoUpdatePayload }>;++const MOBILE_EDITOR_STARTUP_TIMEOUT_MS = 10_000;++const useMobileEditorStartupGuard = ({ active, ready }: { active: boolean; ready: boolean }) => {+ const [attempt, setAttempt] = useState(0);+ const [timedOut, setTimedOut] = useState(false);++ useEffect(() => {+ if (!active || ready) {+ setTimedOut(false);+ return;+ }+ const timeout = setTimeout(() => setTimedOut(true), MOBILE_EDITOR_STARTUP_TIMEOUT_MS);+ return () => clearTimeout(timeout);+ }, [active, attempt, ready]);++ const restart = useCallback(() => {+ setTimedOut(false);+ setAttempt((current) => current + 1);+ }, []);++ return { attempt, restart, timedOut };+};++const MobileEditorStartupOverlay = ({+ onRetry,+ timedOut,+}: {+ onRetry: () => void;+ timedOut: boolean;+}) => {+ const { translate } = useMobileLocale();+ return (+ <View accessibilityLiveRegion="polite" style={styles.richEditorLoading}>+ {!timedOut ? <ActivityIndicator color="#16a06e" size="large" /> : null}+ <Text style={styles.richEditorLoadingTitle}>+ {translate(timedOut ? "编辑器启动时间过长" : "正在启动编辑器")}+ </Text>+ <Text style={styles.mutedText}>+ {translate(timedOut+ ? "本地编辑器未能及时启动,可以重试或返回,当前草稿不会丢失。"+ : "正在准备本地编辑器,笔记内容是安全的。")}+ </Text>+ {timedOut ? (+ <Pressable+ accessibilityLabel={translate("重试")}+ accessibilityRole="button"+ onPress={onRetry}+ style={styles.actionButton}+ >+ <RotateCcw color="#0f172a" size={16} />+ <Text style={styles.actionButtonText}>{translate("重试")}</Text>+ </Pressable>+ ) : null}+ </View>+ );+};++const resolveEditableMemoTitle = (title?: string | null) => {+ const trimmedTitle = title?.trim() ?? "";+ return trimmedTitle === DEFAULT_MEMO_TITLE ? "" : trimmedTitle;+};++const alertProtectedImageLoadFailure = (+ locale: "zh-CN" | "en-US",+ failure: ProtectedResourceLoadFailure+) => {+ const statusLabel = failure.status != null+ ? String(failure.status)+ : locale === "en-US"+ ? "network error"+ : "网络错误";+ Alert.alert(+ locale === "en-US" ? "Image failed to load" : "图片加载失败",+ locale === "en-US"+ ? `Could not load a note image (${statusLabel}). Check the network and try again.`+ : `笔记中的图片未能加载(${statusLabel})。请检查网络后重试。`+ );+};++export const CreateMemoModal = ({+ baseUrl,+ client: clientProp,+ dataScope,+ defaultNotebookId,+ imageCompressionEnabled,+ initialDraft,+ initialSharedImages = [],+ notebooks,+ onCreated,+ onDismiss,+ onQueued,+ syncQueueScope,+}: {+ baseUrl: string;+ client?: ReturnType<typeof useSession>["client"];+ dataScope: string;+ defaultNotebookId: string;+ imageCompressionEnabled: boolean;+ initialDraft?: MobileCreateMemoSeed | MobileWebClipDraft | null;+ initialSharedImages?: MobileSharedImage[];+ notebooks: Notebook[];+ onCreated: (memo: MemoDetail) => void;+ onDismiss: () => void;+ onQueued: () => void | Promise<void>;+ syncQueueScope: string;+}) => {+ const sessionState = useSession();+ const client = clientProp ?? sessionState.client;+ const session = sessionState.session;+ const queryClient = useQueryClient();+ const { resolvedLocale, translate } = useMobileLocale();+ const { resolvedTheme } = useMobileTheme();+ const fallbackNotebookId = defaultNotebookId;+ const editorRef = useRef<LocalTiptapEditorRef>(null);+ const resourceDataUrlCacheRef = useRef(new Map<string, Promise<string | null>>());+ const imageLoadFailureNotifier = useMemo(+ () =>+ createOnceProtectedResourceFailureNotifier((failure) => {+ alertProtectedImageLoadFailure(resolvedLocale, failure);+ }),+ [resolvedLocale]+ );+ const contentJsonRef = useRef<TiptapDoc>(markdownToDoc(""));+ const contentMarkdownRef = useRef("");+ const draftVersionRef = useRef(0);+ const draftWriteBarrier = useMemo(createMobileDraftWriteBarrier, []);+ const flushResolverRef = useRef<(() => void) | null>(null);+ const materializedMemoRef = useRef<MemoDetail | null>(null);+ const [notebookId, setNotebookId] = useState(fallbackNotebookId);+ const [title, setTitle] = useState("");+ const [tagsText, setTagsText] = useState("");+ const [contentMarkdown, setContentMarkdown] = useState("");+ const [notebookPickerOpen, setNotebookPickerOpen] = useState(false);+ const [tagPickerOpen, setTagPickerOpen] = useState(false);+ const [templatePickerOpen, setTemplatePickerOpen] = useState(false);+ const [draftLoaded, setDraftLoaded] = useState(false);+ const [dirty, setDirty] = useState(false);+ const [editorReady, setEditorReady] = useState(false);+ const [imageOperation, setImageOperation] = useState<"idle" | "creating" | "uploading">("idle");+ const imageOperationRef = useRef(imageOperation);+ const sharedImagesHandledRef = useRef(false);+ const createPendingRef = useRef(false);+ const submitStartedRef = useRef(false);+ const [submitStarted, setSubmitStarted] = useState(false);+ const [resourceTarget, setResourceTarget] = useState<MobileResourceTarget | null>(null);+ const editorStartup = useMobileEditorStartupGuard({ active: draftLoaded && Boolean(baseUrl), ready: editorReady });+ const { pickUploadAsset, uploadSourcePicker } = useMobileEditorUploadAsset();+ const targetNotebookId = notebookId || fallbackNotebookId;+ const selectedNotebookName = notebooks.find((notebook) => notebook.id === targetNotebookId)?.name ?? "选择笔记本";+ const titleRef = useRef(title);+ const tagsTextRef = useRef(tagsText);+ const targetNotebookIdRef = useRef(targetNotebookId);+ const userEditedSinceOpenRef = useRef(false);+ const notebooksRef = useRef(notebooks);+ notebooksRef.current = notebooks;+ titleRef.current = title;+ tagsTextRef.current = tagsText;+ targetNotebookIdRef.current = targetNotebookId;+ imageOperationRef.current = imageOperation;++ const { aiPromptsJson, cancelSelectionAi, requestSelectionAi } = useMobileSelectionAi({+ client,+ editorRef,+ resolvedLocale,+ titleRef,+ });++ const focusTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const keyboardTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ const pushBodyToEditor = useCallback((doc: TiptapDoc) => {+ safeDomCall(() => editorRef.current?.setContent(JSON.stringify(doc)));+ }, []);++ const clearFocusTimers = useCallback(() => {+ if (focusTimerRef.current !== null) {+ clearTimeout(focusTimerRef.current);+ focusTimerRef.current = null;+ }+ if (keyboardTimerRef.current !== null) {+ clearTimeout(keyboardTimerRef.current);+ keyboardTimerRef.current = null;+ }+ }, []);++ const scheduleBodyKeyboard = useCallback((delayMs = 160, focusEditor = true) => {+ clearFocusTimers();+ // Full-tree create only mounts the editor DomWebView, so native IME show is safe again.+ focusTimerRef.current = setTimeout(() => {+ focusTimerRef.current = null;+ if (focusEditor) {+ safeDomCall(() => editorRef.current?.focusEnd());+ }+ if (Platform.OS === "android") {+ keyboardTimerRef.current = setTimeout(() => {+ keyboardTimerRef.current = null;+ showEdgeEverKeyboard();+ }, focusEditor ? 120 : 0);+ }+ }, delayMs);+ }, [clearFocusTimers]);++ const retryEditorStartup = useCallback(() => {+ clearFocusTimers();+ setEditorReady(false);+ editorStartup.restart();+ }, [clearFocusTimers, editorStartup.restart]);++ // Component is only mounted while create is open — init once on mount.+ useEffect(() => {+ let active = true;+ setDraftLoaded(false);+ setEditorReady(false);+ setTemplatePickerOpen(false);+ userEditedSinceOpenRef.current = false;+ draftVersionRef.current = 0;++ if (initialDraft) {+ const markdown = initialDraft.contentMarkdown;+ contentMarkdownRef.current = markdown;+ contentJsonRef.current = markdownToDoc(markdown);+ setTitle(initialDraft.title);+ setTagsText(initialDraft.tagsText);+ setContentMarkdown(markdown);+ setNotebookId(fallbackNotebookId);+ setDirty(false);+ setDraftLoaded(true);+ return () => {+ active = false;+ };+ }++ contentMarkdownRef.current = "";+ contentJsonRef.current = markdownToDoc("");+ setTitle("");+ setTagsText("");+ setContentMarkdown("");+ setNotebookId(fallbackNotebookId);+ setDirty(false);++ // A regular create session must always start blank. Remove any legacy+ // auto-saved create draft instead of restoring content from the last one.+ void clearMobileNewMemoDraft(dataScope).catch(() => undefined).finally(() => {+ if (active) {+ setDraftLoaded(true);+ }+ });+ return () => {+ active = false;+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps -- mount-only for create screen lifetime+ }, []);++ const isWebClipDraft = Boolean(+ initialDraft && "sourceUrl" in initialDraft && typeof initialDraft.sourceUrl === "string" && initialDraft.sourceUrl.length > 0+ );++ const persistCurrentDraft = useCallback(() => {+ const materializedMemo = materializedMemoRef.current;+ const currentTitle = titleRef.current;+ const currentContentMarkdown = contentMarkdownRef.current;+ const currentNotebookId = targetNotebookIdRef.current;+ const currentTagsText = tagsTextRef.current;+ const updatedAt = new Date().toISOString();++ return draftWriteBarrier.enqueue(() => materializedMemo+ ? writeMobileMemoDraft({+ memoId: materializedMemo.id,+ expectedRevision: materializedMemo.revision,+ title: currentTitle,+ contentMarkdown: currentContentMarkdown,+ notebookId: currentNotebookId,+ tagsText: currentTagsText,+ updatedAt,+ })+ : Promise.resolve());+ }, [draftWriteBarrier]);++ const applyTemplateSeed = useCallback((seed: MobileCreateMemoSeed) => {+ const markdown = seed.contentMarkdown;+ const doc = markdownToDoc(markdown);+ contentMarkdownRef.current = markdown;+ contentJsonRef.current = doc;+ setTitle(seed.title);+ setTagsText(seed.tagsText);+ setContentMarkdown(markdown);+ draftVersionRef.current += 1;+ userEditedSinceOpenRef.current = true;+ setDirty(true);+ // In-place body replace — never remount DomWebView (remount costs ~1s and breaks Android IME).+ pushBodyToEditor(doc);+ scheduleBodyKeyboard(80);+ }, [pushBodyToEditor, scheduleBodyKeyboard]);++ const requestApplyTemplateSeed = useCallback((seed: MobileCreateMemoSeed) => {+ const current = {+ title: titleRef.current,+ contentMarkdown: contentMarkdownRef.current,+ tagsText: tagsTextRef.current,+ };+ if (createMemoSeedHasContent(current)) {+ Alert.alert(translate("应用模板?"), translate("当前内容将被模板内容替换。"), [+ { text: translate("取消"), style: "cancel" },+ { text: translate("替换"), style: "destructive", onPress: () => applyTemplateSeed(seed) },+ ]);+ return;+ }+ applyTemplateSeed(seed);+ }, [applyTemplateSeed, translate]);++ useEffect(() => {+ if (!draftLoaded || !dirty || isWebClipDraft) {+ return;+ }+ const draftVersion = draftVersionRef.current;+ const timeout = setTimeout(() => {+ void persistCurrentDraft().then((written) => {+ if (written && !submitStartedRef.current && draftVersionRef.current === draftVersion) {+ setDirty(false);+ }+ }).catch(() => undefined);+ }, 350);+ return () => clearTimeout(timeout);+ }, [contentMarkdown, dirty, draftLoaded, isWebClipDraft, persistCurrentDraft, tagsText, targetNotebookId, title]);++ const createMutation = useMutation({+ mutationFn: async () => {+ if (!targetNotebookId) {+ throw new Error("请先创建一个笔记本");+ }+ const materializedMemo = materializedMemoRef.current;+ if (materializedMemo) {+ const optimisticMemo = createOptimisticMemo(materializedMemo, {+ title: titleRef.current.trim() || DEFAULT_MEMO_TITLE,+ contentJson: contentJsonRef.current,+ contentMarkdown: contentMarkdownRef.current.trim(),+ notebookId: targetNotebookIdRef.current,+ tags: parseTags(tagsTextRef.current),+ });+ await upsertLocalMemo(dataScope, optimisticMemo);+ await queueMobileMemoUpdate(syncQueueScope, {+ memoId: materializedMemo.id,+ expectedRevision: materializedMemo.revision,+ expectedContentHash: materializedMemo.contentHash,+ title: optimisticMemo.title ?? DEFAULT_MEMO_TITLE,+ contentMarkdown: optimisticMemo.contentMarkdown,+ notebookId: optimisticMemo.notebookId,+ tags: optimisticMemo.tags,+ });+ return optimisticMemo;+ }+ const now = new Date().toISOString();+ const temporaryId = `local:${Date.now().toString(36)}:${Math.random().toString(36).slice(2, 10)}`;+ const markdown = contentMarkdownRef.current.trim();+ const contentJson = contentJsonRef.current;+ const contentText = docToText(contentJson);+ const memo: MemoDetail = {+ id: temporaryId,+ notebookId: targetNotebookId,+ title: title.trim() || DEFAULT_MEMO_TITLE,+ excerpt: createExcerpt(contentText),+ tags: parseTags(tagsText),+ 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 memo;+ },+ onSuccess: async (memo) => {+ const materializedMemoId = materializedMemoRef.current?.id ?? null;+ // Wait for any already-running AsyncStorage write before removing the+ // draft. Nothing queued after submit began is allowed to recreate it.+ await draftWriteBarrier.blockAndDrain();+ if (!isWebClipDraft) {+ await clearMobileNewMemoDraft(dataScope);+ }+ if (materializedMemoId) {+ await clearMobileMemoDraft(materializedMemoId);+ }+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: ["mobile", "notebooks"] }),+ queryClient.invalidateQueries({ queryKey: ["mobile", "memos"] }),+ ]);+ setTitle("");+ setTagsText("");+ setContentMarkdown("");+ contentMarkdownRef.current = "";+ contentJsonRef.current = markdownToDoc("");+ materializedMemoRef.current = null;+ draftVersionRef.current += 1;+ setDirty(false);+ void onQueued();+ onCreated(memo);+ },+ onError: () => {+ submitStartedRef.current = false;+ draftWriteBarrier.unblock();+ setSubmitStarted(false);+ draftVersionRef.current += 1;+ setDirty(true);+ if (!isWebClipDraft) {+ void persistCurrentDraft().catch(() => undefined);+ }+ },+ });+ createPendingRef.current = createMutation.isPending;+ const canSubmitCreateMemo = Boolean(targetNotebookId) && !submitStarted && !createMutation.isPending && imageOperation === "idle";+ const canUseTemplate = editorReady && imageOperation === "idle" && !submitStarted && !createMutation.isPending;++ const materializeMemoForImage = async () => {+ if (materializedMemoRef.current) {+ return materializedMemoRef.current;+ }+ if (!client || !targetNotebookIdRef.current) {+ throw new Error("当前无法连接实例,请稍后重试");+ }+ setImageOperation("creating");+ const response = await client.createMemo({+ notebookId: targetNotebookIdRef.current,+ title: titleRef.current.trim() || DEFAULT_MEMO_TITLE,+ contentMarkdown: contentMarkdownRef.current.trim(),+ tags: parseTags(tagsTextRef.current),+ });+ materializedMemoRef.current = response.memo;+ await upsertLocalMemo(dataScope, response.memo);+ if (!isWebClipDraft) {+ await clearMobileNewMemoDraft(dataScope);+ }+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: ["mobile", "notebooks"] }),+ queryClient.invalidateQueries({ queryKey: ["mobile", "memos"] }),+ ]);+ return response.memo;+ };++ const uploadImageAsset = async (asset: MobileImageUploadAsset | null) => {+ let uploadId: string | null = null;+ try {+ if (!asset) {+ return;+ }+ const isImage = asset.mimeType?.startsWith("image/") ?? false;+ if (isImage) {+ uploadId = createMobileImageUploadId();+ const previewDataUrl = await createLocalImagePreviewDataUrl(asset);+ safeDomCall(() => editorRef.current?.beginImageUpload(uploadId, previewDataUrl));+ }+ const memo = await materializeMemoForImage();+ setImageOperation("uploading");+ const uploadAsset = await prepareUploadAsset(asset, imageCompressionEnabled);+ const form = new FormData();+ form.append("file", new ExpoFile(uploadAsset.uri));+ const { resource } = await client!.uploadMemoResource(memo.id, form);+ applyMobileEditorUpload(editorRef, resource, uploadId, uploadAsset.name || (resource.kind === "image" ? "图片" : "附件"));+ } catch (error) {+ cancelMobileEditorUpload(editorRef, uploadId);+ Alert.alert("附件上传失败", error instanceof Error ? error.message : "请检查网络连接后重试");+ } finally {+ setImageOperation("idle");+ }+ };++ const pickAndUploadImage = async () => {+ const asset = await pickUploadAsset();+ await uploadImageAsset(asset);+ };++ useEffect(() => {+ if (!editorReady || sharedImagesHandledRef.current || initialSharedImages.length === 0) {+ return;+ }+ sharedImagesHandledRef.current = true;+ void (async () => {+ for (const image of initialSharedImages) {+ await uploadImageAsset(image);+ }+ })();+ }, [editorReady, initialSharedImages]);++ const markDirty = () => {+ if (submitStartedRef.current) {+ return;+ }+ userEditedSinceOpenRef.current = true;+ draftVersionRef.current += 1;+ setDirty(true);+ };++ const flushEditor = () => flushMobileEditor(editorRef, flushResolverRef);++ const submitCreateMemo = async () => {+ if (submitStartedRef.current || createPendingRef.current || imageOperationRef.current !== "idle") {+ return;+ }+ submitStartedRef.current = true;+ setSubmitStarted(true);+ const draftsDrained = draftWriteBarrier.blockAndDrain();+ try {+ await flushEditor();+ await draftsDrained;+ createMutation.mutate();+ } catch {+ submitStartedRef.current = false;+ draftWriteBarrier.unblock();+ setSubmitStarted(false);+ }+ };++ const requestClose = () => submitCreateMemo();++ useEffect(() => {+ const subscription = BackHandler.addEventListener("hardwareBackPress", () => {+ void requestClose();+ return true;+ });+ return () => {+ subscription.remove();+ clearFocusTimers();+ };+ }, [clearFocusTimers]);++ const canMutateEditorResource = useCallback(() => Boolean(materializedMemoRef.current), []);+ const {+ deleteResource,+ downloadResource,+ loadEditorResource,+ renameResource,+ saveResourceAs,+ selectResource,+ } = useMobileEditorResourceActions({+ baseUrl,+ canMutate: canMutateEditorResource,+ client,+ editorRef,+ onLoadFailure: imageLoadFailureNotifier,+ onSelect: setResourceTarget,+ resolvedLocale,+ resourceCacheRef: resourceDataUrlCacheRef,+ sessionBaseUrl: session?.baseUrl,+ token: session?.token,+ });++ const editorElement = useMemo(() => draftLoaded && baseUrl ? (+ <LocalTiptapEditor+ autoFocus+ aiPromptsJson={aiPromptsJson}+ baseUrl={baseUrl}+ content={contentJsonRef.current}+ dom={{+ ...SAFE_DOM_WEBVIEW_PROPS,+ bounces: false,+ contentInsetAdjustmentBehavior: "never",+ overScrollMode: "never",+ scrollEnabled: false,+ style: styles.createMemoEditor,+ }}+ onChange={async (contentJson) => {+ contentJsonRef.current = contentJson;+ const markdown = docToMarkdown(contentJson);+ contentMarkdownRef.current = markdown;+ setContentMarkdown(markdown);+ markDirty();+ flushResolverRef.current?.();+ flushResolverRef.current = null;+ }}+ onAiCancel={cancelSelectionAi}+ onAiRequest={requestSelectionAi}+ onResourcePress={selectResource}+ onLoadResource={loadEditorResource}+ onPickImage={pickAndUploadImage}+ onReady={async (elapsedMs) => {+ setEditorReady(true);+ recordEditorStartup(elapsedMs);+ // LocalTiptapEditor owns caret placement; native only reveals the IME after+ // its final focus retry so the two layers cannot race each other.+ scheduleBodyKeyboard(180, false);+ }}+ key={editorStartup.attempt}+ ref={editorRef}+ locale={resolvedLocale}+ theme={resolvedTheme}+ />+ ) : null, [aiPromptsJson, baseUrl, cancelSelectionAi, draftLoaded, editorStartup.attempt, loadEditorResource, pushBodyToEditor, requestSelectionAi, resolvedLocale, resolvedTheme, scheduleBodyKeyboard, selectResource]);++ return (+ <SafeAreaView edges={["top", "left", "right", "bottom"]} style={styles.createMemoSafeArea}>+ <View style={styles.createMemoHeader}>+ <Pressable accessibilityLabel="返回" accessibilityRole="button" disabled={submitStarted || createMutation.isPending || imageOperation !== "idle"} onPress={() => void requestClose()} style={styles.createMemoBackButton}>+ <ChevronLeft color={submitStarted || createMutation.isPending || imageOperation !== "idle" ? "#cbd5e1" : "#0f172a"} size={30} />+ </Pressable>+ <View style={styles.createMemoHeaderActions}>+ <Text style={[styles.createMemoStatus, (submitStarted || createMutation.isPending) && styles.createMemoStatusActive]}>+ {imageOperation === "creating" ? "正在创建" : imageOperation === "uploading" ? "正在上传" : submitStarted || createMutation.isPending || dirty ? "保存中" : editorReady ? "已保存" : "准备中"}+ </Text>+ <Pressable+ accessibilityLabel={translate("模板")}+ accessibilityRole="button"+ disabled={!canUseTemplate}+ onPress={() => setTemplatePickerOpen(true)}+ style={[styles.createMemoTemplateButton, !canUseTemplate && styles.createMemoDoneButtonDisabled]}+ >+ <Text style={[styles.createMemoTemplateButtonText, !canUseTemplate && styles.createMemoDoneTextDisabled]}>{translate("模板")}</Text>+ </Pressable>+ <Pressable+ accessibilityLabel="完成新建笔记"+ disabled={!canSubmitCreateMemo}+ onPress={() => void submitCreateMemo()}+ style={[styles.createMemoDoneButton, !canSubmitCreateMemo && styles.createMemoDoneButtonDisabled]}+ >+ {submitStarted || createMutation.isPending ? <ActivityIndicator color="#64748b" size="small" /> : <Text style={[styles.createMemoDoneText, !canSubmitCreateMemo && styles.createMemoDoneTextDisabled]}>完成</Text>}+ </Pressable>+ </View>+ </View>++ <View style={styles.createMemoMain}>+ <TextInput+ autoCorrect+ accessibilityLabel="笔记标题"+ onChangeText={(value) => {+ setTitle(value);+ markDirty();+ }}+ placeholder={DEFAULT_MEMO_TITLE}+ placeholderTextColor="#94a3b8"+ style={styles.createMemoTitleInput}+ value={title}+ />++ <View style={styles.createMemoMetaRow}>+ <Pressable accessibilityLabel="所在笔记本" accessibilityRole="button" onPress={() => setNotebookPickerOpen(true)} style={styles.createMemoNotebookButton}>+ <Text numberOfLines={1} style={styles.createMemoNotebookText}>{selectedNotebookName}</Text>+ <ChevronDown color="#64748b" size={14} />+ </Pressable>+ <Pressable accessibilityLabel="选择笔记标签" accessibilityRole="button" onPress={() => setTagPickerOpen(true)} style={styles.createMemoTagsButton}>+ <Text numberOfLines={1} style={[styles.createMemoTagsInput, !tagsText && styles.createMemoTagsPlaceholder]}>+ {tagsText || "添加标签"}+ </Text>+ <ChevronDown color="#94a3b8" size={14} />+ </Pressable>+ <SmartTagButton+ client={client}+ contentMarkdown={contentMarkdown}+ onChange={(nextTags) => {+ setTagsText(nextTags.join(", "));+ markDirty();+ }}+ selectedTags={parseTags(tagsText)}+ title={title}+ />+ </View>++ <View style={styles.createMemoEditorFrame}>+ {editorElement}+ {!editorReady ? <MobileEditorStartupOverlay onRetry={retryEditorStartup} timedOut={editorStartup.timedOut} /> : null}+ </View>++ {createMutation.error ? (+ <Text style={styles.errorText}>{createMutation.error instanceof Error ? createMutation.error.message : "创建失败"}</Text>+ ) : null}+ </View>+ <NotebookPickerModal+ activeNotebookId={targetNotebookId}+ notebooks={notebooks}+ onClose={() => setNotebookPickerOpen(false)}+ onSelect={(nextNotebookId) => {+ setNotebookId(nextNotebookId);+ setNotebookPickerOpen(false);+ markDirty();+ }}+ visible={notebookPickerOpen}+ />+ <TagPickerModal+ dataScope={dataScope}+ onChange={(nextTags) => {+ setTagsText(nextTags.join(", "));+ markDirty();+ }}+ onClose={() => setTagPickerOpen(false)}+ selectedTags={parseTags(tagsText)}+ visible={tagPickerOpen}+ />+ <MobileResourceActions+ canMutate={Boolean(materializedMemoRef.current)}+ onClose={() => setResourceTarget(null)}+ onDelete={deleteResource}+ onDownload={downloadResource}+ onRename={renameResource}+ onSaveAs={saveResourceAs}+ target={resourceTarget}+ />+ <MobileTemplatePickerModal+ client={client}+ onClose={() => {+ setTemplatePickerOpen(false);+ scheduleBodyKeyboard(80);+ }}+ onSelect={requestApplyTemplateSeed}+ presentation="overlay"+ visible={templatePickerOpen}+ />+ {uploadSourcePicker}+ </SafeAreaView>+ );+};++export const RichEditorModal = ({+ baseUrl,+ initialDraft,+ imageCompressionEnabled,+ memo,+ notebooks,+ onClose,+ updateMutation,+}: {+ baseUrl: string;+ initialDraft: MobileMemoDraft | null;+ imageCompressionEnabled: boolean;+ memo: MemoDetail | null;+ notebooks: Notebook[];+ onClose: () => void;+ updateMutation: MobileMemoUpdateMutation;+}) => {+ const { client, session } = useSession();+ const { resolvedLocale } = useMobileLocale();+ const { resolvedTheme } = useMobileTheme();+ const restoredDraft = initialDraft?.expectedRevision === memo?.revision ? initialDraft : null;+ const initialContentJson = restoredDraft+ ? markdownToDoc(restoredDraft.contentMarkdown)+ : resolveMemoContentDoc(memo?.contentJson, memo?.contentMarkdown);+ const editorRef = useRef<LocalTiptapEditorRef>(null);+ const resourceDataUrlCacheRef = useRef(new Map<string, Promise<string | null>>());+ const imageLoadFailureNotifier = useMemo(+ () =>+ createOnceProtectedResourceFailureNotifier((failure) => {+ alertProtectedImageLoadFailure(resolvedLocale, failure);+ }),+ [memo?.id, resolvedLocale]+ );+ const initialFocusTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const contentJsonRef = useRef<TiptapDoc>(initialContentJson);+ const contentMarkdownRef = useRef(restoredDraft?.contentMarkdown ?? memo?.contentMarkdown ?? "");+ const contentSnapshotRef = useRef(JSON.stringify(contentJsonRef.current));+ const dirtyRef = useRef(Boolean(restoredDraft));+ const flushResolverRef = useRef<(() => void) | null>(null);+ const savingRef = useRef(false);+ const uploadingRef = useRef(false);+ const memoBaseRef = useRef(memo);+ const [title, setTitle] = useState(resolveEditableMemoTitle(restoredDraft?.title ?? memo?.title));+ const [tagsText, setTagsText] = useState(restoredDraft?.tagsText ?? memo?.tags.join(", ") ?? "");+ const [notebookId, setNotebookId] = useState(restoredDraft?.notebookId ?? memo?.notebookId ?? "");+ const [notebookPickerOpen, setNotebookPickerOpen] = useState(false);+ const [tagPickerOpen, setTagPickerOpen] = useState(false);+ const [draftRestored, setDraftRestored] = useState(Boolean(restoredDraft));+ const [ready, setReady] = useState(false);+ const [dirty, setDirty] = useState(Boolean(restoredDraft));+ const [saving, setSaving] = useState(false);+ const [uploading, setUploading] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [startupMs, setStartupMs] = useState<number | null>(null);+ const [resourceTarget, setResourceTarget] = useState<MobileResourceTarget | null>(null);+ const editorStartup = useMobileEditorStartupGuard({ active: Boolean(memo && baseUrl), ready });+ const { pickUploadAsset, uploadSourcePicker } = useMobileEditorUploadAsset();+ const notebookLabel = notebooks.find((notebook) => notebook.id === notebookId)?.name ?? "未分类";+ const saveLabel = error ? "保存失败" : saving ? "保存中" : uploading ? "上传中" : dirty ? (draftRestored ? "本地草稿" : "未保存") : ready ? "已保存" : "加载中";+ const titleRef = useRef(title);+ const tagsTextRef = useRef(tagsText);+ const notebookIdRef = useRef(notebookId);+ titleRef.current = title;+ tagsTextRef.current = tagsText;+ notebookIdRef.current = notebookId;++ useEffect(() => () => {+ if (initialFocusTimerRef.current !== null) {+ clearTimeout(initialFocusTimerRef.current);+ initialFocusTimerRef.current = null;+ }+ }, []);++ const retryEditorStartup = useCallback(() => {+ if (initialFocusTimerRef.current !== null) {+ clearTimeout(initialFocusTimerRef.current);+ initialFocusTimerRef.current = null;+ }+ setReady(false);+ setStartupMs(null);+ setError(null);+ editorStartup.restart();+ }, [editorStartup.restart]);++ const persistDraft = async (contentJson: TiptapDoc) => {+ const currentMemo = memoBaseRef.current;+ if (!currentMemo) {+ return;+ }+ const contentSnapshot = JSON.stringify(contentJson);+ if (contentSnapshot === contentSnapshotRef.current) {+ flushResolverRef.current?.();+ flushResolverRef.current = null;+ return;+ }+ contentSnapshotRef.current = contentSnapshot;+ contentJsonRef.current = contentJson;+ contentMarkdownRef.current = docToMarkdown(contentJson);+ dirtyRef.current = true;+ setDirty(true);+ setError(null);+ flushResolverRef.current?.();+ flushResolverRef.current = null;+ await writeMobileMemoDraft({+ memoId: currentMemo.id,+ expectedRevision: currentMemo.revision,+ title: titleRef.current.trim(),+ contentMarkdown: contentMarkdownRef.current,+ notebookId: notebookIdRef.current,+ tagsText: tagsTextRef.current,+ updatedAt: new Date().toISOString(),+ });+ };++ const save = async () => {+ const currentMemo = memoBaseRef.current;+ if (!currentMemo || savingRef.current || !notebookIdRef.current) {+ return null;+ }+ if (!dirtyRef.current) {+ return currentMemo;+ }+ // Capture whether the user kept typing while this save is in flight so we+ // do not clear the dirty flag and drop their next autosave.+ const dirtyGenerationAtStart = contentSnapshotRef.current;+ savingRef.current = true;+ setSaving(true);+ setError(null);++ try {+ const savedMemo = await updateMutation.mutateAsync({+ memo: currentMemo,+ payload: {+ title: titleRef.current.trim() || DEFAULT_MEMO_TITLE,+ contentJson: contentJsonRef.current,+ contentMarkdown: contentMarkdownRef.current,+ notebookId: notebookIdRef.current,+ tags: parseTags(tagsTextRef.current),+ },+ });+ memoBaseRef.current = savedMemo;+ await clearMobileMemoDraft(currentMemo.id);+ if (contentSnapshotRef.current === dirtyGenerationAtStart) {+ dirtyRef.current = false;+ setDirty(false);+ } else {+ // Newer local edits arrived during the save; keep dirty so the next pass uploads them.+ dirtyRef.current = true;+ setDirty(true);+ }+ setDraftRestored(false);+ return savedMemo;+ } catch (saveError) {+ setError(saveError instanceof Error ? saveError.message : "保存失败");+ return null;+ } finally {+ savingRef.current = false;+ setSaving(false);+ }+ };++ const flushEditor = () => flushMobileEditor(editorRef, flushResolverRef);+ const { aiPromptsJson, cancelSelectionAi, requestSelectionAi } = useMobileSelectionAi({+ client,+ editorRef,+ resolvedLocale,+ titleRef,+ });++ const requestClose = async () => {+ if (savingRef.current || uploadingRef.current) {+ return;+ }+ if (initialFocusTimerRef.current !== null) {+ clearTimeout(initialFocusTimerRef.current);+ initialFocusTimerRef.current = null;+ }+ await flushEditor();+ const savedMemo = await save();+ if (savedMemo) {+ onClose();+ }+ };++ useEffect(() => {+ const subscription = BackHandler.addEventListener("hardwareBackPress", () => {+ void requestClose();+ return true;+ });+ return () => subscription.remove();+ }, []);++ const pickAndUploadImage = async () => {+ if (!client || !memo || uploadingRef.current) {+ return;+ }+ if (memo.id.startsWith("local:")) {+ Alert.alert("正在同步新笔记", "首次同步完成后即可上传本地图片;图片链接现在就可以直接粘贴到正文。");+ return;+ }+ const asset = await pickUploadAsset();+ if (!asset) {+ return;+ }++ const isImage = asset.mimeType?.startsWith("image/") ?? false;+ const uploadId = isImage ? createMobileImageUploadId() : null;+ uploadingRef.current = true;+ setUploading(true);+ setError(null);+ try {+ if (isImage && uploadId) {+ const previewDataUrl = await createLocalImagePreviewDataUrl(asset);+ safeDomCall(() => editorRef.current?.beginImageUpload(uploadId, previewDataUrl));+ }+ const uploadAsset = await prepareUploadAsset(asset, imageCompressionEnabled);+ const form = new FormData();+ form.append("file", new ExpoFile(uploadAsset.uri));+ const { resource } = await client.uploadMemoResource(memo.id, form);+ applyMobileEditorUpload(editorRef, resource, uploadId, uploadAsset.name || (resource.kind === "image" ? "图片" : "附件"));+ } catch (uploadError) {+ cancelMobileEditorUpload(editorRef, uploadId);+ setError(uploadError instanceof Error ? uploadError.message : "附件上传失败");+ } finally {+ uploadingRef.current = false;+ setUploading(false);+ }+ };++ const canMutateEditorResource = useCallback(() => Boolean(memo && !memo.id.startsWith("local:")), [memo]);+ const {+ deleteResource,+ downloadResource,+ loadEditorResource,+ renameResource,+ saveResourceAs,+ selectResource,+ } = useMobileEditorResourceActions({+ baseUrl,+ canMutate: canMutateEditorResource,+ client,+ editorRef,+ onLoadFailure: imageLoadFailureNotifier,+ onSelect: setResourceTarget,+ resolvedLocale,+ resourceCacheRef: resourceDataUrlCacheRef,+ sessionBaseUrl: session?.baseUrl,+ token: session?.token,+ });++ const editorElement = useMemo(+ () => memo && baseUrl ? (+ <LocalTiptapEditor+ autoFocus+ aiPromptsJson={aiPromptsJson}+ baseUrl={baseUrl}+ content={contentJsonRef.current}+ dom={{+ ...SAFE_DOM_WEBVIEW_PROPS,+ bounces: false,+ contentInsetAdjustmentBehavior: "never",+ overScrollMode: "never",+ scrollEnabled: false,+ style: styles.richEditorWebView,+ }}+ onChange={persistDraft}+ onAiCancel={cancelSelectionAi}+ onAiRequest={requestSelectionAi}+ onResourcePress={selectResource}+ onLoadResource={loadEditorResource}+ onPickImage={pickAndUploadImage}+ onReady={async (elapsedMs) => {+ setStartupMs(elapsedMs);+ setReady(true);+ recordEditorStartup(elapsedMs);+ if (initialFocusTimerRef.current !== null) {+ clearTimeout(initialFocusTimerRef.current);+ }+ // The DOM editor performs its own bounded focus retry. Reveal the Android+ // keyboard only after that retry instead of issuing another competing focus.+ if (Platform.OS === "android") {+ initialFocusTimerRef.current = setTimeout(() => {+ initialFocusTimerRef.current = null;+ showEdgeEverKeyboard();+ }, 180);+ }+ }}+ key={editorStartup.attempt}+ ref={editorRef}+ locale={resolvedLocale}+ theme={resolvedTheme}+ />+ ) : null,+ [aiPromptsJson, baseUrl, cancelSelectionAi, editorStartup.attempt, loadEditorResource, memo?.id, requestSelectionAi, resolvedLocale, resolvedTheme, selectResource]+ );++ useEffect(() => {+ const currentMemo = memoBaseRef.current;+ if (!currentMemo || !dirty) {+ return;+ }+ const timeout = setTimeout(() => {+ void writeMobileMemoDraft({+ memoId: currentMemo.id,+ expectedRevision: currentMemo.revision,+ title: titleRef.current.trim(),+ contentMarkdown: contentMarkdownRef.current,+ notebookId: notebookIdRef.current,+ tagsText: tagsTextRef.current,+ updatedAt: new Date().toISOString(),+ });+ }, 350);+ return () => clearTimeout(timeout);+ }, [dirty, memo, notebookId, tagsText, title]);++ useEffect(() => {+ if (!memoBaseRef.current || !dirty || !ready || savingRef.current || uploadingRef.current) {+ return;+ }+ const timeout = setTimeout(() => {+ void flushEditor().then(save);+ }, 1200);+ return () => clearTimeout(timeout);+ }, [dirty, memo, notebookId, ready, tagsText, title]);++ return (+ <SafeAreaView style={styles.richEditorSafeArea}>+ <KeyboardAvoidingView+ behavior="height"+ enabled={Platform.OS === "android"}+ style={styles.richEditorKeyboardAvoiding}+ >+ <View style={styles.createMemoHeader}>+ <Pressable accessibilityLabel="返回" accessibilityRole="button" disabled={saving || uploading} onPress={() => void requestClose()} style={styles.createMemoBackButton}>+ <ChevronLeft color={saving || uploading ? "#cbd5e1" : "#0f172a"} size={30} />+ </Pressable>+ <View style={styles.createMemoHeaderActions}>+ <Text numberOfLines={1} style={[styles.createMemoStatus, styles.richEditorHeaderStatus, (saving || uploading || dirty) && styles.createMemoStatusActive, error && styles.richEditorStatusError]}>{saveLabel}</Text>+ <Pressable+ accessibilityLabel="完成编辑"+ accessibilityRole="button"+ disabled={saving || uploading || !ready}+ onPress={() => void requestClose()}+ style={[styles.createMemoDoneButton, (saving || uploading || !ready) && styles.createMemoDoneButtonDisabled]}+ >+ {saving ? <ActivityIndicator color="#64748b" size="small" /> : <Text style={[styles.createMemoDoneText, (uploading || !ready) && styles.createMemoDoneTextDisabled]}>完成</Text>}+ </Pressable>+ </View>+ </View>++ {memo && baseUrl ? (+ <View style={styles.richEditorContainer}>+ <TextInput+ onChangeText={(value) => {+ setTitle(value);+ dirtyRef.current = true;+ setDirty(true);+ }}+ placeholder={DEFAULT_MEMO_TITLE}+ placeholderTextColor="#94a3b8"+ style={styles.createMemoTitleInput}+ value={title}+ />+ <View style={[styles.createMemoMetaRow, styles.richStandaloneMetaRow]}>+ <Pressable accessibilityLabel="所在笔记本" accessibilityRole="button" onPress={() => setNotebookPickerOpen(true)} style={styles.createMemoNotebookButton}>+ <Text numberOfLines={1} style={styles.createMemoNotebookText}>{notebookLabel}</Text>+ <ChevronDown color="#64748b" size={14} />+ </Pressable>+ <Pressable accessibilityLabel="选择笔记标签" accessibilityRole="button" onPress={() => setTagPickerOpen(true)} style={[styles.createMemoTagsButton, styles.richStandaloneTagsInput]}>+ <Text numberOfLines={1} style={[styles.createMemoTagsInput, !tagsText && styles.createMemoTagsPlaceholder]}>+ {tagsText || "添加标签"}+ </Text>+ <ChevronDown color="#94a3b8" size={14} />+ </Pressable>+ <SmartTagButton+ client={client}+ contentMarkdown={contentMarkdownRef.current}+ disabled={saving || uploading}+ onChange={(nextTags) => {+ setTagsText(nextTags.join(", "));+ dirtyRef.current = true;+ setDirty(true);+ }}+ selectedTags={parseTags(tagsText)}+ title={title}+ />+ </View>+ {draftRestored ? <Text style={styles.richEditorDraftNotice}>已恢复上次未完成的本地草稿</Text> : null}+ <View style={styles.richEditorFrame}>+ {editorElement}+ {!ready ? <MobileEditorStartupOverlay onRetry={retryEditorStartup} timedOut={editorStartup.timedOut} /> : null}+ </View>+ {error ? <Text style={styles.richEditorInlineError}>{error}</Text> : null}+ {startupMs !== null && __DEV__ ? <Text style={styles.richEditorPerf}>本地编辑器启动:{startupMs}ms</Text> : null}+ </View>+ ) : (+ <View style={styles.centerState}>+ <Text style={styles.errorText}>缺少笔记数据,无法打开富文本编辑器</Text>+ </View>+ )}+ <NotebookPickerModal+ activeNotebookId={notebookId}+ notebooks={notebooks}+ onClose={() => setNotebookPickerOpen(false)}+ onSelect={(nextNotebookId) => {+ setNotebookId(nextNotebookId);+ setNotebookPickerOpen(false);+ dirtyRef.current = true;+ setDirty(true);+ }}+ visible={notebookPickerOpen}+ />+ <TagPickerModal+ dataScope={createMobileDataScope(session?.baseUrl ?? baseUrl, session?.user?.id)}+ onChange={(nextTags) => {+ setTagsText(nextTags.join(", "));+ dirtyRef.current = true;+ setDirty(true);+ }}+ onClose={() => setTagPickerOpen(false)}+ selectedTags={parseTags(tagsText)}+ visible={tagPickerOpen}+ />+ <MobileResourceActions+ canMutate={Boolean(memo && !memo.id.startsWith("local:"))}+ onClose={() => setResourceTarget(null)}+ onDelete={deleteResource}+ onDownload={downloadResource}+ onRename={renameResource}+ onSaveAs={saveResourceAs}+ target={resourceTarget}+ />+ {uploadSourcePicker}+ </KeyboardAvoidingView>+ </SafeAreaView>+ );+};++const createMobileImageUploadId = () =>+ `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;++const createLocalImagePreviewDataUrl = async (asset: { mimeType?: string | null; uri: string }) => {+ const file = new ExpoFile(asset.uri);+ const mimeType = asset.mimeType || file.type || "application/octet-stream";+ return `data:${mimeType};base64,${await file.base64()}`;+};++const appendResourceMarkdown = (+ currentMarkdown: string,+ resource: {+ filename: string;+ kind: "image" | "attachment";+ url: string;+ }+) => {+ const label = resource.filename.replace(/\]/g, "\\]");+ const markdown = resource.kind === "image" ? `` : `附件:[${label}](${resource.url})`;+ const trimmed = currentMarkdown.trimEnd();++ return trimmed ? `${trimmed}\n\n${markdown}\n` : `${markdown}\n`;+};diff --git a/apps/mobile/src/screens/WorkspacePickers.tsx b/apps/mobile/src/screens/WorkspacePickers.tsxnew file mode 100644index 00000000..3a3b117a--- /dev/null+++ b/apps/mobile/src/screens/WorkspacePickers.tsx@@ -0,0 +1,660 @@+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";+import { ApiRequestError } from "@edgeever/client";+import { useQuery } from "@tanstack/react-query";+import type { Notebook } from "@edgeever/shared";+import {+ getMobileCenteredScrollOffset,+ getMobileNotebookSearchVisibleIds,+} from "@edgeever/shared/mobile-ui";+import {+ ActivityIndicator,+ Check,+ ChevronDown,+ ChevronRight,+ Folder,+ Search,+ Tag,+ TagPlus,+ X,+} from "../components/icons";+import {+ type LayoutChangeEvent,+ Modal,+ ScrollView,+ View,+} from "react-native";+import { useSafeAreaInsets } from "react-native-safe-area-context";+import { Alert, Pressable, Text, TextInput } from "../components/LocalizedText";+import { useMobileLocale } from "../lib/mobile-locale";+import { listLocalTags } from "../lib/local-mirror";+import { useSession } from "../lib/session";+import {+ filterCollapsedNotebookOptions,+ filterNotebookOptions,+ filterNotebookOptionsById,+ flattenNotebooks,+ getNotebookAncestorIds,+ getNotebookParentIdSet,+ parseTags,+ type NotebookOption,+} from "./workspace-utils";+import { styles } from "./workspace-styles";++const ALL_NOTES_ID = "all";++const useAutoCenterSelectedScrollRow = (visible: boolean, selectedKey: string) => {+ const scrollRef = useRef<ScrollView>(null);+ const viewportHeightRef = useRef(0);+ const rowLayoutsRef = useRef(new Map<string, { height: number; y: number }>());+ const hasCenteredRef = useRef(false);++ const centerSelectedRow = useCallback(() => {+ const selectedLayout = rowLayoutsRef.current.get(selectedKey);+ const viewportHeight = viewportHeightRef.current;+ if (!visible || hasCenteredRef.current || !selectedLayout || viewportHeight <= 0) {+ return;+ }++ hasCenteredRef.current = true;+ const y = getMobileCenteredScrollOffset(selectedLayout.y, selectedLayout.height, viewportHeight);+ requestAnimationFrame(() => scrollRef.current?.scrollTo({ animated: false, y }));+ }, [selectedKey, visible]);++ useLayoutEffect(() => {+ hasCenteredRef.current = false;+ const frame = requestAnimationFrame(centerSelectedRow);+ return () => cancelAnimationFrame(frame);+ }, [centerSelectedRow]);++ const onViewportLayout = useCallback((event: LayoutChangeEvent) => {+ viewportHeightRef.current = event.nativeEvent.layout.height;+ hasCenteredRef.current = false;+ centerSelectedRow();+ }, [centerSelectedRow]);++ const onRowLayout = useCallback((rowKey: string, event: LayoutChangeEvent) => {+ const { height, y } = event.nativeEvent.layout;+ rowLayoutsRef.current.set(rowKey, { height, y });+ if (rowKey === selectedKey) {+ hasCenteredRef.current = false;+ centerSelectedRow();+ }+ }, [centerSelectedRow, selectedKey]);++ return { onRowLayout, onViewportLayout, scrollRef };+};++export const NotebookPickerModal = ({+ activeNotebookId,+ notebooks,+ onClose,+ onSelect,+ visible,+}: {+ activeNotebookId: string;+ notebooks: Notebook[];+ onClose: () => void;+ onSelect: (notebookId: string) => void;+ visible: boolean;+}) => {+ const { translate } = useMobileLocale();+ const safeAreaInsets = useSafeAreaInsets();+ const [searchText, setSearchText] = useState("");+ const [collapsedNotebookIds, setCollapsedNotebookIds] = useState<Set<string>>(() => new Set());+ const selectedScroll = useAutoCenterSelectedScrollRow(visible, activeNotebookId);+ const notebookOptions = flattenNotebooks(notebooks);+ const searchQuery = searchText.trim();+ const childNotebookIds = getNotebookParentIdSet(notebooks);+ const activeNotebookAncestorIds = getNotebookAncestorIds(notebooks, activeNotebookId);+ const visibleNotebookOptions = searchQuery+ ? filterNotebookOptionsById(notebookOptions, getMobileNotebookSearchVisibleIds(notebooks, searchText))+ : filterCollapsedNotebookOptions(notebookOptions, collapsedNotebookIds);+ const activeNotebookName = activeNotebookId === ALL_NOTES_ID+ ? "全部笔记"+ : notebooks.find((notebook) => notebook.id === activeNotebookId)?.name ?? "全部笔记";+ const allNotebookBranchesExpanded = childNotebookIds.size > 0 && Array.from(childNotebookIds).every((notebookId) => !collapsedNotebookIds.has(notebookId));++ useEffect(() => {+ if (visible) {+ setSearchText("");+ setCollapsedNotebookIds(new Set(Array.from(childNotebookIds).filter((notebookId) => !activeNotebookAncestorIds.has(notebookId))));+ }+ }, [visible, activeNotebookId, notebooks]);++ const toggleNotebookCollapsed = (notebookId: string) => {+ setCollapsedNotebookIds((current) => {+ const next = new Set(current);++ if (next.has(notebookId)) {+ next.delete(notebookId);+ } else {+ next.add(notebookId);+ }++ return next;+ });+ };++ const toggleAllNotebookBranches = () => {+ setCollapsedNotebookIds(allNotebookBranchesExpanded ? new Set(childNotebookIds) : new Set());+ };++ return (+ <Modal animationType="fade" onRequestClose={onClose} transparent visible={visible}>+ <Pressable onPress={onClose} style={styles.actionSheetBackdrop}>+ <Pressable style={[styles.actionSheet, styles.notebookPickerSheet, { paddingBottom: Math.max(8, safeAreaInsets.bottom) }]}>+ <View style={styles.actionSheetHandle} />+ <View style={styles.notebookPickerHeader}>+ <View style={styles.notebookPickerHeaderText}>+ <Text style={styles.actionSheetTitle}>切换笔记本</Text>+ <Text style={styles.panelLabel}>{translate(`当前:${activeNotebookName}`)}</Text>+ </View>+ <Pressable accessibilityLabel="关闭" accessibilityRole="button" onPress={onClose} style={styles.notebookPickerCloseButton}>+ <X color="#0f172a" size={20} />+ </Pressable>+ </View>++ <ScrollView+ contentContainerStyle={styles.notebookPickerContent}+ onLayout={selectedScroll.onViewportLayout}+ ref={selectedScroll.scrollRef}+ style={styles.notebookPickerScroll}+ >+ <View style={styles.notebookPickerSearchBox}>+ <Search color="#64748b" size={18} />+ <TextInput+ accessibilityLabel="搜索笔记本"+ autoCapitalize="none"+ autoCorrect={false}+ onChangeText={setSearchText}+ placeholder="搜索笔记本"+ placeholderTextColor="#94a3b8"+ style={styles.notebookPickerSearchInput}+ value={searchText}+ />+ {searchText ? (+ <Pressable onPress={() => setSearchText("")}>+ <X color="#64748b" size={18} />+ </Pressable>+ ) : null}+ </View>++ <Pressable+ accessibilityLabel={activeNotebookId === ALL_NOTES_ID ? "当前:全部笔记" : "切换到全部笔记"}+ accessibilityRole="button"+ accessibilityState={{ selected: activeNotebookId === ALL_NOTES_ID }}+ onLayout={(event) => selectedScroll.onRowLayout(ALL_NOTES_ID, event)}+ onPress={() => onSelect(ALL_NOTES_ID)}+ style={[styles.notebookPickerRow, styles.notebookPickerAllRow, activeNotebookId === ALL_NOTES_ID && styles.notebookPickerRowActive]}+ >+ <View style={styles.moveNotebookText}>+ <Text numberOfLines={1} style={styles.panelValue}>+ 全部笔记+ </Text>+ </View>+ {activeNotebookId === ALL_NOTES_ID ? <Check color="#0f172a" size={18} /> : null}+ </Pressable>++ <View style={styles.notebookPickerSectionHeader}>+ <Text style={styles.label}>{searchQuery ? "匹配的笔记本" : "笔记本"}</Text>+ {!searchQuery && childNotebookIds.size > 0 ? (+ <Pressable+ accessibilityLabel={allNotebookBranchesExpanded ? "收起全部笔记本" : "展开全部笔记本"}+ accessibilityRole="button"+ onPress={toggleAllNotebookBranches}+ style={styles.notebookPickerToggleAll}+ >+ <Text style={styles.notebookPickerToggleAllText}>{allNotebookBranchesExpanded ? "收起全部" : "展开全部"}</Text>+ </Pressable>+ ) : null}+ </View>+ {visibleNotebookOptions.map(({ depth, notebook }) => (+ <View+ key={notebook.id}+ onLayout={(event) => selectedScroll.onRowLayout(notebook.id, event)}+ style={[styles.notebookPickerRow, activeNotebookId === notebook.id && styles.notebookPickerRowActive, depth > 0 && { marginLeft: Math.min(depth * 18, 54) }]}+ >+ {childNotebookIds.has(notebook.id) && !searchQuery ? (+ <Pressable+ accessibilityLabel={`${collapsedNotebookIds.has(notebook.id) ? "展开" : "收起"} ${notebook.name}`}+ accessibilityRole="button"+ accessibilityState={{ expanded: !collapsedNotebookIds.has(notebook.id) }}+ onPress={() => toggleNotebookCollapsed(notebook.id)}+ style={styles.notebookTreeToggle}+ >+ {collapsedNotebookIds.has(notebook.id) ? <ChevronRight color="#64748b" size={17} /> : <ChevronDown color="#64748b" size={17} />}+ </Pressable>+ ) : (+ <View style={styles.notebookTreeTogglePlaceholder} />+ )}+ <Pressable+ accessibilityLabel={`${activeNotebookId === notebook.id ? "当前" : "切换到"} ${notebook.name}`}+ accessibilityRole="button"+ accessibilityState={{ selected: activeNotebookId === notebook.id }}+ onPress={() => onSelect(notebook.id)}+ style={styles.moveNotebookSelectArea}+ >+ <Text numberOfLines={1} style={styles.panelValue}>+ {notebook.name}+ </Text>+ </Pressable>+ {activeNotebookId === notebook.id ? <Check color="#0f172a" size={18} /> : null}+ </View>+ ))}+ {visibleNotebookOptions.length === 0 ? (+ <View style={styles.emptyInlinePanel}>+ <Folder color="#94a3b8" size={28} />+ <Text style={styles.mutedText}>没有匹配的笔记本</Text>+ </View>+ ) : null}+ </ScrollView>+ </Pressable>+ </Pressable>+ </Modal>+ );+};++export const SmartTagButton = ({+ client,+ contentMarkdown,+ disabled = false,+ onChange,+ selectedTags,+ title,+}: {+ client: ReturnType<typeof useSession>["client"];+ contentMarkdown: string;+ disabled?: boolean;+ onChange: (tags: string[]) => void;+ selectedTags: string[];+ title: string;+}) => {+ const { resolvedLocale, translate } = useMobileLocale();+ const [status, setStatus] = useState<"idle" | "loading" | "success">("idle");+ const controllerRef = useRef<AbortController | null>(null);+ const feedbackTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const unavailable = disabled || !client || selectedTags.length >= 24 || (!title.trim() && !contentMarkdown.trim());++ useEffect(() => () => {+ controllerRef.current?.abort();+ if (feedbackTimerRef.current) clearTimeout(feedbackTimerRef.current);+ }, []);++ const generateAndApplyTags = async () => {+ if (unavailable || !client) return;+ controllerRef.current?.abort();+ if (feedbackTimerRef.current) clearTimeout(feedbackTimerRef.current);+ const controller = new AbortController();+ controllerRef.current = controller;+ setStatus("loading");+ try {+ const selectedTagKeys = new Set(selectedTags.map((tag) => tag.toLocaleLowerCase()));+ const result = await client.suggestAiTags({+ title,+ contentMarkdown,+ currentTags: selectedTags,+ locale: resolvedLocale,+ }, controller.signal);+ const additions = result.suggestions+ .filter((suggestion) => !selectedTagKeys.has(suggestion.name.toLocaleLowerCase()))+ .slice(0, Math.max(0, 24 - selectedTags.length))+ .map((suggestion) => suggestion.name);+ if (additions.length === 0) {+ setStatus("idle");+ Alert.alert(translate("智能标签"), translate("没有找到适合这篇笔记的新标签。"));+ return;+ }+ onChange(Array.from(new Set([...selectedTags, ...additions])).slice(0, 24));+ setStatus("success");+ feedbackTimerRef.current = setTimeout(() => {+ setStatus("idle");+ feedbackTimerRef.current = null;+ }, 4000);+ } catch (error) {+ if (controller.signal.aborted) return;+ setStatus("idle");+ Alert.alert(+ translate("智能标签生成失败"),+ error instanceof ApiRequestError && error.code === "ai_not_configured"+ ? translate("请先在“AI 集成”中配置默认模型。")+ : error instanceof Error+ ? error.message+ : translate("AI 标签建议生成失败。")+ );+ } finally {+ if (controllerRef.current === controller) controllerRef.current = null;+ }+ };++ const accessibilityLabel = status === "loading"+ ? translate("正在生成智能标签")+ : status === "success"+ ? translate("智能标签已添加")+ : translate("智能标签");++ return (+ <Pressable+ accessibilityLabel={accessibilityLabel}+ accessibilityRole="button"+ accessibilityState={{ disabled: unavailable || status === "loading" }}+ disabled={unavailable || status === "loading"}+ onPress={() => void generateAndApplyTags()}+ style={[styles.smartTagButton, status === "success" && styles.smartTagButtonSuccess, unavailable && styles.buttonDisabled]}+ >+ {status === "loading"+ ? <ActivityIndicator color="#047857" size="small" />+ : status === "success"+ ? <Check color="#047857" size={17} />+ : <TagPlus color="#047857" size={18} />}+ </Pressable>+ );+};++export const TagPickerModal = ({+ dataScope,+ onChange,+ onClose,+ selectedTags,+ visible,+}: {+ dataScope: string;+ onChange: (tags: string[]) => void;+ onClose: () => void;+ selectedTags: string[];+ visible: boolean;+}) => {+ const { translate } = useMobileLocale();+ const safeAreaInsets = useSafeAreaInsets();+ const [searchText, setSearchText] = useState("");+ const tagsQuery = useQuery({+ queryKey: ["mobile-tags", dataScope],+ queryFn: () => listLocalTags(dataScope),+ enabled: visible && Boolean(dataScope),+ });+ const normalizedSearch = searchText.trim().replace(/^#/, "");+ const tags = tagsQuery.data?.tags ?? [];+ const visibleTags = tags.filter((tag) => tag.name.toLocaleLowerCase().includes(normalizedSearch.toLocaleLowerCase()));+ const exactMatch = tags.some((tag) => tag.name.toLocaleLowerCase() === normalizedSearch.toLocaleLowerCase());++ useEffect(() => {+ if (visible) {+ setSearchText("");+ }+ }, [visible]);++ const commit = (nextTags: string[]) => onChange(Array.from(new Set(nextTags)).slice(0, 24));+ const toggleTag = (name: string) => commit(+ selectedTags.includes(name) ? selectedTags.filter((tag) => tag !== name) : [...selectedTags, name]+ );+ const createTag = () => {+ const additions = parseTags(normalizedSearch);+ if (additions.length === 0) return;+ commit([...selectedTags, ...additions]);+ setSearchText("");+ };++ return (+ <Modal animationType="fade" onRequestClose={onClose} transparent visible={visible}>+ <Pressable onPress={onClose} style={styles.actionSheetBackdrop}>+ <Pressable style={[styles.actionSheet, styles.notebookPickerSheet, { paddingBottom: Math.max(8, safeAreaInsets.bottom) }]}>+ <View style={styles.actionSheetHandle} />+ <View style={styles.notebookPickerHeader}>+ <View style={styles.notebookPickerHeaderText}>+ <Text style={styles.actionSheetTitle}>{translate("选择标签")}</Text>+ <Text style={styles.panelLabel}>{translate("点选已有标签,或输入名称创建新标签")}</Text>+ </View>+ <Pressable accessibilityLabel="关闭" accessibilityRole="button" onPress={onClose} style={styles.notebookPickerCloseButton}>+ <X color="#0f172a" size={20} />+ </Pressable>+ </View>++ <ScrollView contentContainerStyle={styles.notebookPickerContent} keyboardShouldPersistTaps="handled" style={styles.notebookPickerScroll}>+ {selectedTags.length > 0 ? (+ <View accessibilityLabel="已选标签" style={styles.tagPickerSelectedList}>+ {selectedTags.map((tag) => (+ <Pressable key={tag} accessibilityLabel={`移除标签 ${tag}`} accessibilityRole="button" onPress={() => toggleTag(tag)} style={styles.tagPickerChip}>+ <Text style={styles.tagPickerChipText}>#{tag}</Text>+ <X color="#047857" size={14} />+ </Pressable>+ ))}+ </View>+ ) : null}++ <View style={styles.notebookPickerSearchBox}>+ <Search color="#64748b" size={18} />+ <TextInput+ accessibilityLabel="搜索或输入新标签"+ autoCapitalize="none"+ autoCorrect={false}+ onChangeText={setSearchText}+ onSubmitEditing={createTag}+ placeholder="搜索或输入新标签"+ placeholderTextColor="#94a3b8"+ returnKeyType="done"+ style={styles.notebookPickerSearchInput}+ value={searchText}+ />+ {normalizedSearch && !exactMatch && selectedTags.length < 24 ? (+ <Pressable accessibilityLabel={`新建标签 ${normalizedSearch}`} accessibilityRole="button" onPress={createTag}>+ <Text style={styles.tagPickerCreateText}>{translate("新建")}</Text>+ </Pressable>+ ) : null}+ </View>++ {tagsQuery.isLoading ? (+ <ActivityIndicator color="#16a06e" style={styles.tagPickerLoading} />+ ) : visibleTags.length === 0 ? (+ <View style={styles.emptyInlinePanel}>+ <Tag color="#94a3b8" size={28} />+ <Text style={styles.mutedText}>{translate("没有匹配的现有标签,可直接新建")}</Text>+ </View>+ ) : visibleTags.map((tag) => {+ const selected = selectedTags.includes(tag.name);+ return (+ <Pressable+ key={tag.name}+ accessibilityLabel={`标签 ${tag.name}`}+ accessibilityRole="button"+ accessibilityState={{ selected }}+ onPress={() => toggleTag(tag.name)}+ style={[styles.notebookPickerRow, selected && styles.notebookPickerRowActive]}+ >+ <View style={[styles.tagPickerCheckbox, selected && styles.tagPickerCheckboxSelected]}>+ {selected ? <Check color="#ffffff" size={14} /> : null}+ </View>+ <Text numberOfLines={1} style={styles.tagPickerRowText}>#{tag.name}</Text>+ <Text style={styles.panelLabel}>{translate(`${tag.memoCount} 条笔记`)}</Text>+ </Pressable>+ );+ })}+ </ScrollView>+ </Pressable>+ </Pressable>+ </Modal>+ );+};++export const MoveSelectionModal = ({+ bottomOffset,+ isMoving,+ notebooks,+ onClose,+ onMove,+ selectedCount,+ selectedNotebookId,+ visible,+}: {+ bottomOffset: number;+ isMoving: boolean;+ notebooks: Notebook[];+ onClose: () => void;+ onMove: (notebookId: string) => void;+ selectedCount: number;+ selectedNotebookId: string;+ visible: boolean;+}) => {+ const [searchText, setSearchText] = useState("");+ const notebookOptions = flattenNotebooks(notebooks);+ const selectedScroll = useAutoCenterSelectedScrollRow(visible, selectedNotebookId);++ useEffect(() => {+ if (visible) {+ setSearchText("");+ }+ }, [visible]);++ return (+ <Modal animationType="fade" onRequestClose={onClose} transparent visible={visible}>+ <Pressable onPress={onClose} style={[styles.actionSheetBackdrop, { paddingBottom: bottomOffset }]}>+ <Pressable style={[styles.listActionSheet, styles.moveSelectionSheet]}>+ <View style={styles.actionSheetHandle} />+ <View style={styles.listActionSheetHeader}>+ <View style={styles.listActionSheetHeaderText}>+ <Text style={styles.actionSheetTitle}>移动到笔记本</Text>+ <Text style={styles.actionSheetSubtitle}>{selectedCount > 0 ? `已选择 ${selectedCount} 条` : "选择笔记"}</Text>+ </View>+ <Pressable accessibilityLabel="关闭" accessibilityRole="button" onPress={onClose} style={styles.sheetCloseButton}>+ <X color="#0f172a" size={18} />+ </Pressable>+ </View>+ <View style={styles.moveSelectionSearch}>+ <View style={styles.searchBox}>+ <Search color="#64748b" size={18} />+ <TextInput+ autoCapitalize="none"+ autoCorrect={false}+ onChangeText={setSearchText}+ placeholder="搜索笔记本"+ placeholderTextColor="#94a3b8"+ style={styles.searchInput}+ value={searchText}+ />+ {searchText ? (+ <Pressable onPress={() => setSearchText("")}>+ <X color="#64748b" size={18} />+ </Pressable>+ ) : null}+ </View>+ </View>+ <ScrollView+ contentContainerStyle={styles.moveSelectionList}+ onLayout={selectedScroll.onViewportLayout}+ ref={selectedScroll.scrollRef}+ style={styles.listActionSheetScroll}+ >+ <NotebookTreeOptionRows+ collapsible={false}+ compact+ disabled={isMoving}+ emptyIconSize={28}+ notebooks={notebooks}+ onSelect={onMove}+ options={notebookOptions}+ searchText={searchText}+ showDepthPrefix={false}+ showMemoCount={false}+ selectedNotebookId={selectedNotebookId}+ onRowLayout={selectedScroll.onRowLayout}+ />+ {isMoving ? <ActivityIndicator color="#0f172a" style={styles.listLoadingFooter} /> : null}+ </ScrollView>+ </Pressable>+ </Pressable>+ </Modal>+ );+};++const NotebookTreeOptionRows = ({+ collapsible = true,+ compact = false,+ disabled = false,+ emptyIconSize,+ notebooks,+ onRowLayout,+ onSelect,+ options,+ searchText,+ selectedNotebookId,+ showDepthPrefix = true,+ showMemoCount = true,+}: {+ collapsible?: boolean;+ compact?: boolean;+ disabled?: boolean;+ emptyIconSize: number;+ notebooks: Notebook[];+ onRowLayout?: (notebookId: string, event: LayoutChangeEvent) => void;+ onSelect: (notebookId: string) => void;+ options: NotebookOption[];+ searchText: string;+ selectedNotebookId: string;+ showDepthPrefix?: boolean;+ showMemoCount?: boolean;+}) => {+ const [collapsedNotebookIds, setCollapsedNotebookIds] = useState<Set<string>>(() => new Set());+ const searchQuery = searchText.trim();+ const childNotebookIds = getNotebookParentIdSet(notebooks);+ const visibleNotebookOptions = searchQuery+ ? filterNotebookOptions(options, searchText)+ : filterCollapsedNotebookOptions(options, collapsedNotebookIds);++ const toggleNotebookCollapsed = (notebookId: string) => {+ setCollapsedNotebookIds((current) => {+ const next = new Set(current);++ if (next.has(notebookId)) {+ next.delete(notebookId);+ } else {+ next.add(notebookId);+ }++ return next;+ });+ };++ if (visibleNotebookOptions.length === 0) {+ return (+ <View style={styles.emptyInlinePanel}>+ <Folder color="#94a3b8" size={emptyIconSize} />+ <Text style={styles.mutedText}>没有匹配的笔记本</Text>+ </View>+ );+ }++ return (+ <View style={[styles.notebookTreeRows, compact && styles.notebookTreeRowsCompact]}>+ {visibleNotebookOptions.map(({ depth, notebook }) => (+ <View+ key={notebook.id}+ onLayout={onRowLayout ? (event) => onRowLayout(notebook.id, event) : undefined}+ style={[+ styles.moveNotebookRow,+ compact && styles.moveNotebookRowCompact,+ selectedNotebookId === notebook.id && styles.moveNotebookRowActive,+ compact && selectedNotebookId === notebook.id && styles.moveNotebookRowCompactActive,+ depth > 0 && { marginLeft: Math.min(depth * 14, 42) },+ ]}+ >+ {collapsible && childNotebookIds.has(notebook.id) && !searchQuery ? (+ <Pressable accessibilityRole="button" onPress={() => toggleNotebookCollapsed(notebook.id)} style={styles.notebookTreeToggle}>+ {collapsedNotebookIds.has(notebook.id) ? <ChevronRight color="#64748b" size={17} /> : <ChevronDown color="#64748b" size={17} />}+ </Pressable>+ ) : !collapsible ? (+ <View style={styles.notebookTreeTogglePlaceholder}>+ <Folder color={selectedNotebookId === notebook.id ? "#059669" : "#64748b"} size={17} />+ </View>+ ) : (+ <View style={styles.notebookTreeTogglePlaceholder} />+ )}+ <Pressable disabled={disabled} onPress={() => onSelect(notebook.id)} style={[styles.moveNotebookSelectArea, disabled && styles.buttonDisabled]}>+ <Text numberOfLines={1} style={[styles.panelValue, compact && selectedNotebookId === notebook.id && styles.moveNotebookTextCompactActive]}>+ {showDepthPrefix && depth > 0 ? `${"· ".repeat(depth)}${notebook.name}` : notebook.name}+ </Text>+ {showMemoCount ? <Text style={styles.panelLabel}>{notebook.memoCount} 条笔记</Text> : null}+ </Pressable>+ {selectedNotebookId === notebook.id ? <Check color={compact ? "#059669" : "#0f172a"} size={18} /> : null}+ </View>+ ))}+ </View>+ );+};diff --git a/apps/mobile/src/screens/WorkspaceRevisionHistory.tsx b/apps/mobile/src/screens/WorkspaceRevisionHistory.tsxnew file mode 100644index 00000000..c60f8626--- /dev/null+++ b/apps/mobile/src/screens/WorkspaceRevisionHistory.tsx@@ -0,0 +1,200 @@+import { useEffect, useState, type ReactNode } from "react";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { DEFAULT_MEMO_TITLE, type MemoDetail, type MemoRevision } from "@edgeever/shared";+import { History, RotateCcw, X } from "../components/icons";+import { Modal, ScrollView, View } from "react-native";+import { SafeAreaView } from "react-native-safe-area-context";+import { Alert, Pressable, Text } from "../components/LocalizedText";+import { useMobileLocale } from "../lib/mobile-locale";+import { useSession } from "../lib/session";+import { formatDate, formatRevisionActor } from "./workspace-utils";+import { styles } from "./workspace-styles";++const IconButton = ({+ accessibilityLabel,+ children,+ disabled = false,+ onPress,+}: {+ accessibilityLabel?: string;+ children: ReactNode;+ disabled?: boolean;+ onPress: () => void;+}) => (+ <Pressable accessibilityLabel={accessibilityLabel} accessibilityRole="button" disabled={disabled} onPress={onPress} style={[styles.iconButton, disabled && styles.buttonDisabled]}>+ {children}+ </Pressable>+);++const ActionButton = ({+ children,+ danger = false,+ disabled = false,+ label,+ onPress,+}: {+ children: ReactNode;+ danger?: boolean;+ disabled?: boolean;+ label: string;+ onPress: () => void;+}) => (+ <Pressable disabled={disabled} onPress={onPress} style={[styles.actionButton, danger && styles.actionButtonDanger, disabled && styles.buttonDisabled]}>+ {children}+ <Text style={[styles.actionButtonText, danger && styles.actionButtonTextDanger]}>{label}</Text>+ </Pressable>+);++export const RevisionHistoryModal = ({+ memo,+ onClose,+ onRestored,+}: {+ memo: MemoDetail | null;+ onClose: () => void;+ onRestored: (memo: MemoDetail) => void | Promise<void>;+}) => {+ const { client } = useSession();+ const queryClient = useQueryClient();+ const localePreference = useMobileLocale().preference;+ const [selectedRevisionId, setSelectedRevisionId] = useState<string | null>(null);++ const revisionsQuery = useQuery({+ queryKey: ["mobile", "memo-revisions", memo?.id],+ queryFn: async () => {+ if (!client || !memo) {+ throw new Error("Memo is not selected");+ }++ return client.listMemoRevisions(memo.id);+ },+ enabled: Boolean(client && memo),+ });++ const revisions = revisionsQuery.data?.revisions ?? [];+ const selectedRevision = revisions.find((revision) => revision.id === selectedRevisionId) ?? revisions[0] ?? null;++ useEffect(() => {+ if (memo && revisions.length > 0 && !selectedRevisionId) {+ setSelectedRevisionId(revisions[0].id);+ }+ }, [memo, revisions, selectedRevisionId]);++ useEffect(() => {+ if (!memo) {+ setSelectedRevisionId(null);+ }+ }, [memo]);++ useEffect(() => {+ setSelectedRevisionId(null);+ }, [memo?.id]);++ const restoreRevisionMutation = useMutation({+ mutationFn: async (revision: MemoRevision) => {+ if (!client || !memo) {+ throw new Error("Memo is not selected");+ }++ const response = await client.restoreMemoRevision(memo.id, revision.id);+ return response.memo;+ },+ onSuccess: async (restoredMemo) => {+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: ["mobile", "memos"] }),+ queryClient.invalidateQueries({ queryKey: ["mobile", "search"] }),+ queryClient.invalidateQueries({ queryKey: ["mobile", "memo"] }),+ queryClient.invalidateQueries({ queryKey: ["mobile", "memo-revisions", restoredMemo.id] }),+ ]);+ await onRestored(restoredMemo);+ },+ });++ const requestRestoreRevision = (revision: MemoRevision) => {+ Alert.alert("恢复到这个历史版本", "当前内容会被这个历史版本替换,恢复后仍会产生新的历史记录。", [+ { text: "取消", style: "cancel" },+ {+ text: "恢复",+ onPress: () => restoreRevisionMutation.mutate(revision),+ },+ ]);+ };++ return (+ <Modal animationType="slide" onRequestClose={onClose} presentationStyle="pageSheet" visible={Boolean(memo)}>+ <SafeAreaView style={styles.modalSafeArea}>+ <View style={styles.managementHeader}>+ <View style={styles.managementHeaderText}>+ <View style={styles.managementTitleRow}>+ <History color="#059669" size={19} />+ <Text style={styles.managementTitle}>版本历史</Text>+ </View>+ <Text numberOfLines={1} style={styles.managementSubtitle}>{memo?.title?.trim() || DEFAULT_MEMO_TITLE}</Text>+ </View>+ <IconButton accessibilityLabel="关闭" onPress={onClose}>+ <X color="#0f172a" size={20} />+ </IconButton>+ </View>++ <ScrollView contentContainerStyle={styles.revisionHistoryContent}>+ <View style={styles.revisionSummaryRow}>+ <View style={styles.revisionSummaryText}>+ <Text style={styles.settingsRowTitle}>{selectedRevision ? `版本 ${selectedRevision.revision}` : "未选择历史版本"}</Text>+ <Text style={styles.settingsRowDescription}>选择历史记录后可预览并恢复。</Text>+ </View>+ {selectedRevision ? (+ <ActionButton disabled={restoreRevisionMutation.isPending || Boolean(memo?.isDeleted)} label={restoreRevisionMutation.isPending ? "恢复中" : "恢复该版本"} onPress={() => requestRestoreRevision(selectedRevision)}>+ <RotateCcw color="#0f172a" size={16} />+ </ActionButton>+ ) : null}+ </View>++ <Text style={styles.revisionTimelineLabel}>历史记录</Text>+ {revisionsQuery.isLoading ? (+ <View style={styles.revisionTimelineState}>+ <Text style={styles.mutedText}>加载中</Text>+ </View>+ ) : revisionsQuery.isError ? (+ <View style={styles.revisionTimelineState}>+ <Text style={styles.errorText}>加载失败</Text>+ <Text style={styles.revisionTimelineError}>+ {revisionsQuery.error instanceof Error ? revisionsQuery.error.message : "请稍后重试"}+ </Text>+ <ActionButton label="重试" onPress={() => void revisionsQuery.refetch()}>+ <RotateCcw color="#0f172a" size={16} />+ </ActionButton>+ </View>+ ) : revisions.length === 0 ? (+ <View style={styles.revisionTimelineState}>+ <Text style={styles.mutedText}>暂无历史版本</Text>+ </View>+ ) : (+ <View style={styles.revisionTimeline}>+ {revisions.map((revision) => (+ <Pressable+ key={revision.id}+ onPress={() => setSelectedRevisionId(revision.id)}+ style={[styles.revisionPill, selectedRevision?.id === revision.id && styles.revisionPillActive]}+ >+ <Text style={[styles.revisionPillTitle, selectedRevision?.id === revision.id && styles.revisionPillTitleActive]}>{`版本 ${revision.revision}`}</Text>+ <Text style={[styles.revisionPillMeta, selectedRevision?.id === revision.id && styles.revisionPillTitleActive]}>+ {formatDate(revision.createdAt, localePreference)} · {formatRevisionActor(revision.createdBy)}+ </Text>+ </Pressable>+ ))}+ </View>+ )}++ {selectedRevision ? (+ <View style={styles.revisionPreviewCard}>+ <Text selectable style={styles.revisionPreviewText}>{selectedRevision.contentMarkdown || "空笔记"}</Text>+ </View>+ ) : null}+ {restoreRevisionMutation.error ? (+ <Text style={styles.errorText}>{restoreRevisionMutation.error instanceof Error ? restoreRevisionMutation.error.message : "恢复失败"}</Text>+ ) : null}+ </ScrollView>+ </SafeAreaView>+ </Modal>+ );+};diff --git a/apps/mobile/src/screens/WorkspaceScreen.tsx b/apps/mobile/src/screens/WorkspaceScreen.tsxindex e8f03a6f..318dab84 100644--- a/apps/mobile/src/screens/WorkspaceScreen.tsx+++ b/apps/mobile/src/screens/WorkspaceScreen.tsx@@ -1,78 +1,27 @@-import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";-import { keepPreviousData, useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData, type QueryKey, type UseMutationResult } from "@tanstack/react-query";+import { memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import { keepPreviousData, useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData, type QueryKey } from "@tanstack/react-query";import * as Clipboard from "expo-clipboard";-import Constants from "expo-constants";-import { File as ExpoFile } from "expo-file-system";import type { ListMemosResponse, MemoFilterMode, MemoSortMode } from "@edgeever/client";import {ActivityIndicator,- BookOpen,- Check,- ChevronDown,- ChevronLeft,- ChevronRight,- CheckSquare,- Copy,- ExternalLink,- FileText,- Folder,- History,Home,- Image as ImageIcon,- Info,- List,- LogOut,- MessageSquare,- Moon,- MoreHorizontal,- MoreVertical,- Pencil,Plus,- RefreshCw,- RotateCcw,- Search,- ShieldCheck,- SlidersHorizontal,- Sun,- Tag,- TagPlus,- Trash2,UserRound,- X,} from "../components/icons";import {BackHandler,- FlatList,- Image as RNImage,- type ImageStyle,InteractionManager,- KeyboardAvoidingView,- type LayoutChangeEvent,- Linking,Modal,- Platform,- RefreshControl,Share as NativeShare,- ScrollView,- StyleSheet,- Text as RNText,- type StyleProp,- Switch,- useWindowDimensions,Vibration,View,- type ViewStyle,} from "react-native";-import { Gesture, GestureDetector } from "react-native-gesture-handler";-import Animated, { runOnJS, useAnimatedStyle, useSharedValue, withTiming } from "react-native-reanimated";import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";-import { Alert, Pressable, Text, TextInput } from "../components/LocalizedText";-import Markdown, { type ASTNode, type RenderRules } from "react-native-markdown-display";-import { SvgXml } from "react-native-svg";+import { Alert, Pressable, Text } from "../components/LocalizedText";import { ApiRequestError } from "@edgeever/client";-import { buildGitHubFeedbackUrl, createExcerpt, DEFAULT_MEMO_TITLE, docToMarkdown, docToText, getNotebookDescendantIds, markdownToDoc, resolveMemoContentDoc, type AuthUser, type MemoDetail, type MemoRevision, type MemoSummary, type Notebook, type TiptapDoc } from "@edgeever/shared";-import { MOBILE_UI_METRICS, getMobileCenteredScrollOffset, getMobileNotebookSearchVisibleIds, toggleMobileMemoFilterMode, toggleMobileMemoSelection } from "@edgeever/shared/mobile-ui";-import { clearMobileMemoDraft, clearMobileNewMemoDraft, readMobileMemoDraft, writeMobileMemoDraft, type MobileMemoDraft } from "../lib/mobile-drafts";+import { DEFAULT_MEMO_TITLE, getNotebookDescendantIds, markdownToDoc, type MemoDetail } from "@edgeever/shared";+import { MOBILE_UI_METRICS, toggleMobileMemoFilterMode } from "@edgeever/shared/mobile-ui";+import { clearMobileMemoDraft, readMobileMemoDraft, type MobileMemoDraft } from "../lib/mobile-drafts";import {readMobileImageCompressionEnabled,readMobileMemoListDensity,@@ -93,7 +42,6 @@ import {listMobileSyncQueueItems,markMobileMemoUpdateConflict,markMobileMemoUpdateError,- queueMobileMemoCreate,queueMobileMemoUpdate,shouldQueueMobileMemoSaveError,type MobileSyncQueueItem,@@ -112,22 +60,12 @@ import {type MobileBootstrapProgress,} from "../lib/local-mirror";import { AccountSecurityPanel } from "./AccountSecurityModal";-import { beginEditorStartup, markStartup, recordEditorStartup } from "../lib/startup-performance";-import { prepareUploadAsset, type MobileImageUploadAsset } from "../lib/mobile-image-upload";+import { beginEditorStartup, markStartup } from "../lib/startup-performance";import MobileWebClipCapture from "../components/MobileWebClipCapture";-import LocalTiptapEditor, { type LocalTiptapEditorRef } from "../components/LocalTiptapEditor";-import { SAFE_DOM_WEBVIEW_PROPS } from "../lib/mobile-dom";-import { safeDomCall } from "../lib/safe-dom-call";-import { applyMobileEditorUpload, cancelMobileEditorUpload, flushMobileEditor } from "../lib/mobile-editor-controller";-import { showEdgeEverKeyboard } from "../../modules/edgeever-keyboard";-import { MobileResourceActions } from "../components/MobileResourceActions";import { MobileCreateChoiceModal, MobileTemplatePickerModal } from "../components/MobileTemplatePicker";-import { resolveMobileThemeStyles, useMobileTheme } from "../lib/mobile-theme";+import { useMobileTheme } from "../lib/mobile-theme";import { useMobileUpdateAvailable } from "../lib/mobile-update";-import { createMemoSeedHasContent, type MobileCreateMemoSeed } from "../lib/mobile-templates";-import { createMobileDraftWriteBarrier } from "../lib/mobile-draft-write-barrier";-import { MobileMermaidDiagram, MobileMermaidProvider } from "../components/MobileMermaid";-import { getMobileMarkdownFenceLanguage, trimMobileMarkdownFenceContent } from "../lib/mobile-mermaid";+import { type MobileCreateMemoSeed } from "../lib/mobile-templates";import {buildMobileWebClipDraft,buildMobileWebClipDraftFromRenderedPage,@@ -142,24 +80,14 @@ import {import { useDebouncedValue } from "../hooks/useDebouncedValue";import { useMobileAutomaticSync } from "../hooks/useMobileAutomaticSync";import { useMobileLocalMirrorSync } from "../hooks/useMobileLocalMirrorSync";-import { useMobileEditorResourceActions } from "../hooks/useMobileEditorResourceActions";-import { useMobileEditorUploadAsset } from "../hooks/useMobileEditorUploadAsset";-import { useMobileSelectionAi } from "../hooks/useMobileSelectionAi";+import { useMobileWorkspaceSelection } from "../hooks/useMobileWorkspaceSelection";import {- filterCollapsedNotebookOptions,- filterNotebookOptions,- filterNotebookOptionsById,flattenNotebooks,- formatDate,formatMemoPreviewDate,- formatRevisionActor,- getNotebookAncestorIds,- getNotebookParentIdSet,getResolvedMobileLocale,getTextSearchMatches,isEnglishMobileLocale,parseTags,- type NotebookOption,} from "./workspace-utils";import {applyOptimisticMemoToCache,@@ -171,6 +99,12 @@ import { refreshWorkspaceThemeStyles, styles } from "./workspace-styles";import { NotesView } from "./WorkspaceNotesView";import { SettingsView, type MobileLocaleMode } from "./WorkspaceSettingsView";import { MemoDetailModal } from "./WorkspaceMemoDetail";+import {+ MoveSelectionModal,+ NotebookPickerModal,+} from "./WorkspacePickers";+import { RevisionHistoryModal } from "./WorkspaceRevisionHistory";+import { CreateMemoModal, RichEditorModal } from "./WorkspaceEditors";import {NotesActionsModal,SelectionActionBar,@@ -182,103 +116,14 @@ import {renameMobileResourceInDoc,type MobileResourceTarget,} from "../lib/mobile-attachments";-import {- createOnceProtectedResourceFailureNotifier,- type ProtectedResourceLoadFailure,-} from "../lib/mobile-protected-resources";const ALL_NOTES_ID = "all";-const ANDROID_SYSTEM_NAVIGATION_FALLBACK = 48;-const DETAIL_CONTENT_HORIZONTAL_PADDING = 16;-const DETAIL_TABLE_FIT_COLUMN_COUNT = 3;-const DETAIL_TABLE_MIN_COLUMN_WIDTH = 132;-const MOBILE_EDITOR_STARTUP_TIMEOUT_MS = 10_000;--const useMobileEditorStartupGuard = ({ active, ready }: { active: boolean; ready: boolean }) => {- const [attempt, setAttempt] = useState(0);- const [timedOut, setTimedOut] = useState(false);-- useEffect(() => {- if (!active || ready) {- setTimedOut(false);- return;- }- const timeout = setTimeout(() => setTimedOut(true), MOBILE_EDITOR_STARTUP_TIMEOUT_MS);- return () => clearTimeout(timeout);- }, [active, attempt, ready]);-- const restart = useCallback(() => {- setTimedOut(false);- setAttempt((current) => current + 1);- }, []);-- return { attempt, restart, timedOut };-};--const MobileEditorStartupOverlay = ({- onRetry,- timedOut,-}: {- onRetry: () => void;- timedOut: boolean;-}) => {- const { translate } = useMobileLocale();- return (- <View accessibilityLiveRegion="polite" style={styles.richEditorLoading}>- {!timedOut ? <ActivityIndicator color="#16a06e" size="large" /> : null}- <Text style={styles.richEditorLoadingTitle}>- {translate(timedOut ? "编辑器启动时间过长" : "正在启动编辑器")}- </Text>- <Text style={styles.mutedText}>- {translate(timedOut- ? "本地编辑器未能及时启动,可以重试或返回,当前草稿不会丢失。"- : "正在准备本地编辑器,笔记内容是安全的。")}- </Text>- {timedOut ? (- <Pressable- accessibilityLabel={translate("重试")}- accessibilityRole="button"- onPress={onRetry}- style={styles.actionButton}- >- <RotateCcw color="#0f172a" size={16} />- <Text style={styles.actionButtonText}>{translate("重试")}</Text>- </Pressable>- ) : null}- </View>- );-};--const resolveEditableMemoTitle = (title?: string | null) => {- const trimmedTitle = title?.trim() ?? "";- return trimmedTitle === DEFAULT_MEMO_TITLE ? "" : trimmedTitle;-};--const alertProtectedImageLoadFailure = (- locale: "zh-CN" | "en-US",- failure: ProtectedResourceLoadFailure-) => {- const statusLabel = failure.status != null- ? String(failure.status)- : locale === "en-US"- ? "network error"- : "网络错误";- Alert.alert(- locale === "en-US" ? "Image failed to load" : "图片加载失败",- locale === "en-US"- ? `Could not load a note image (${statusLabel}). Check the network and try again.`- : `笔记中的图片未能加载(${statusLabel})。请检查网络后重试。`- );-};--const useMobileLocalePreference = () => useMobileLocale().preference;type MobileView = "notes" | "settings";type MemoView = "notebook" | "trash";type RichEditingSession = {draft: MobileMemoDraft | null;memo: MemoDetail;};-type MobileMemoUpdateMutation = UseMutationResult<MemoDetail, Error, { memo: MemoDetail; payload: MobileMemoUpdatePayload }>;type MobileMemoListCacheSnapshot = Array<[QueryKey, InfiniteData<ListMemosResponse> | undefined]>;export const WorkspaceScreen = ({@@ -323,10 +168,21 @@ export const WorkspaceScreen = ({const [notebookPickerOpen, setNotebookPickerOpen] = useState(false);const [richEditingSession, setRichEditingSession] = useState<RichEditingSession | null>(null);const [revisionMemo, setRevisionMemo] = useState<MemoDetail | null>(null);- const [selectionMode, setSelectionMode] = useState(false);- const [selectedMemoIds, setSelectedMemoIds] = useState<Set<string>>(() => new Set());- const [selectionMoveOpen, setSelectionMoveOpen] = useState(false);- const [selectionMoreOpen, setSelectionMoreOpen] = useState(false);+ const {+ clearSelection,+ enterSelectionMode,+ remapSelectedMemoId,+ restoreSelection,+ selectedMemoIds,+ selectionMode,+ selectionMoreOpen,+ selectionMoveOpen,+ selectSingleMemo,+ setSelectionMoreOpen,+ setSelectionMoveOpen,+ toggleSelectedMemo,+ toggleVisibleSelection,+ } = useMobileWorkspaceSelection();const memoDraftPrefetchRef = useRef(new Map<string, Promise<MobileMemoDraft | null>>());const processedShareUrlRef = useRef<string | null>(null);const onIncomingShareHandledRef = useRef(onIncomingShareHandled);@@ -336,16 +192,8 @@ export const WorkspaceScreen = ({const sharedImages = useMemo(() => getSharedImages(incomingSharePayloads), [incomingSharePayloads]);const handleMemoIdRemapped = useCallback((temporaryId: string, memo: MemoDetail) => {setSelectedMemoId((current) => current === temporaryId ? memo.id : current);- setSelectedMemoIds((current) => {- if (!current.has(temporaryId)) {- return current;- }- const next = new Set(current);- next.delete(temporaryId);- next.add(memo.id);- return next;- });- }, []);+ remapSelectedMemoId(temporaryId, memo.id);+ }, [remapSelectedMemoId]);const {refreshSyncQueueItems,runForcedSync,@@ -478,10 +326,7 @@ export const WorkspaceScreen = ({return true;}if (selectionMode) {- setSelectionMode(false);- setSelectedMemoIds(new Set());- setSelectionMoveOpen(false);- setSelectionMoreOpen(false);+ clearSelection();return true;}if (searchText.trim()) {@@ -503,7 +348,7 @@ export const WorkspaceScreen = ({return false;});return () => subscription.remove();- }, [activeView, memoView, searchText, selectedMemoId, selectionMode]);+ }, [activeView, clearSelection, memoView, searchText, selectedMemoId, selectionMode]);useEffect(() => {if (notebooksQuery.data && memosQuery.data) {@@ -536,18 +381,6 @@ export const WorkspaceScreen = ({setSelectedMemoId(memoId);};- const toggleSelectedMemo = (memoId: string) => {- setSelectionMode(true);- setSelectedMemoIds((current) => toggleMobileMemoSelection(current, memoId));- };-- const clearSelection = () => {- setSelectionMode(false);- setSelectedMemoIds(new Set());- setSelectionMoveOpen(false);- setSelectionMoreOpen(false);- };-const showAllNotes = () => {setActiveView("notes");setMemoView("notebook");@@ -576,34 +409,6 @@ export const WorkspaceScreen = ({}};- const toggleVisibleSelection = () => {- const visibleMemoIds = visibleMemos.map((memo) => memo.id);-- if (visibleMemoIds.length === 0) {- return;- }-- setSelectionMode(true);- setSelectedMemoIds((current) => {- const next = new Set(current);- const allVisibleSelected = visibleMemoIds.every((memoId) => next.has(memoId));-- for (const memoId of visibleMemoIds) {- if (allVisibleSelected) {- next.delete(memoId);- } else {- next.add(memoId);- }- }-- return next;- });- };-- const enterSelectionMode = () => {- setSelectionMode(true);- };-const closeDetail = () => {setSelectedMemoId(null);};@@ -681,13 +486,12 @@ export const WorkspaceScreen = ({// Drop detail / selection so no other DomWebView stays mounted under the editor.// Multiple WebViews make Android IME attach to the wrong (often read-only) view.setSelectedMemoId(null);- setSelectionMode(false);- setSelectedMemoIds(new Set());+ clearSelection();setIncomingClipDraft(null);setIncomingShareImages([]);setCreateSeed(seed);setCreateOpen(true);- }, []);+ }, [clearSelection]);const openCreateFromTemplate = useCallback(() => {if (!canCreateMemo) {@@ -857,7 +661,7 @@ export const WorkspaceScreen = ({useEffect(() => {clearSelection();- }, [activeNotebookId, memoFilterMode, memoSortMode, memoView]);+ }, [activeNotebookId, clearSelection, memoFilterMode, memoSortMode, memoView]);useEffect(() => {let mounted = true;@@ -1200,8 +1004,10 @@ export const WorkspaceScreen = ({},onError: (error, _variables, context) => {restoreMemoListCache(context?.cacheSnapshot);- setSelectionMode(context?.previousSelectionMode ?? false);- setSelectedMemoIds(context?.previousSelectedMemoIds ?? new Set());+ restoreSelection(+ context?.previousSelectionMode ?? false,+ context?.previousSelectedMemoIds ?? new Set(),+ );Alert.alert("删除失败", error instanceof Error ? error.message : "请检查网络后重试");},});@@ -1330,12 +1136,6 @@ export const WorkspaceScreen = ({]);};- const selectSingleMemo = (memoId: string) => {- Vibration.vibrate(8);- setSelectionMode(true);- setSelectedMemoIds(new Set([memoId]));- };-if (richEditingSession) {return <RichEditorModalbaseUrl={session?.baseUrl ?? ""}@@ -1404,7 +1204,10 @@ export const WorkspaceScreen = ({onOpenActions={() => setNotesActionsOpen(true)}onOpenNotebookPicker={() => setNotebookPickerOpen(true)}onMemoPress={handleMemoPress}- onMemoLongPress={(memo) => selectSingleMemo(memo.id)}+ onMemoLongPress={(memo) => {+ Vibration.vibrate(8);+ selectSingleMemo(memo.id);+ }}onLoadMore={() => {const query = searchActive ? searchQuery : memosQuery;if (query.hasNextPage && !query.isFetchingNextPage) {@@ -1575,7 +1378,7 @@ export const WorkspaceScreen = ({}}onToggleVisibleSelection={() => {setSelectionMoreOpen(false);- toggleVisibleSelection();+ toggleVisibleSelection(visibleMemos.map((memo) => memo.id));}}pinLabel={nextSelectionPinValue ? "置顶" : "取消置顶"}selectedCount={selectedMemoIds.size}@@ -1635,1966 +1438,6 @@ export const WorkspaceScreen = ({);};-const useAutoCenterSelectedScrollRow = (visible: boolean, selectedKey: string) => {- const scrollRef = useRef<ScrollView>(null);- const viewportHeightRef = useRef(0);- const rowLayoutsRef = useRef(new Map<string, { height: number; y: number }>());- const hasCenteredRef = useRef(false);-- const centerSelectedRow = useCallback(() => {- const selectedLayout = rowLayoutsRef.current.get(selectedKey);- const viewportHeight = viewportHeightRef.current;- if (!visible || hasCenteredRef.current || !selectedLayout || viewportHeight <= 0) {- return;- }-- hasCenteredRef.current = true;- const y = getMobileCenteredScrollOffset(selectedLayout.y, selectedLayout.height, viewportHeight);- requestAnimationFrame(() => scrollRef.current?.scrollTo({ animated: false, y }));- }, [selectedKey, visible]);-- useLayoutEffect(() => {- hasCenteredRef.current = false;- const frame = requestAnimationFrame(centerSelectedRow);- return () => cancelAnimationFrame(frame);- }, [centerSelectedRow]);-- const onViewportLayout = useCallback((event: LayoutChangeEvent) => {- viewportHeightRef.current = event.nativeEvent.layout.height;- hasCenteredRef.current = false;- centerSelectedRow();- }, [centerSelectedRow]);-- const onRowLayout = useCallback((rowKey: string, event: LayoutChangeEvent) => {- const { height, y } = event.nativeEvent.layout;- rowLayoutsRef.current.set(rowKey, { height, y });- if (rowKey === selectedKey) {- hasCenteredRef.current = false;- centerSelectedRow();- }- }, [centerSelectedRow, selectedKey]);-- return { onRowLayout, onViewportLayout, scrollRef };-};--const NotebookPickerModal = ({- activeNotebookId,- notebooks,- onClose,- onSelect,- visible,-}: {- activeNotebookId: string;- notebooks: Notebook[];- onClose: () => void;- onSelect: (notebookId: string) => void;- visible: boolean;-}) => {- const { translate } = useMobileLocale();- const safeAreaInsets = useSafeAreaInsets();- const [searchText, setSearchText] = useState("");- const [collapsedNotebookIds, setCollapsedNotebookIds] = useState<Set<string>>(() => new Set());- const selectedScroll = useAutoCenterSelectedScrollRow(visible, activeNotebookId);- const notebookOptions = flattenNotebooks(notebooks);- const searchQuery = searchText.trim();- const childNotebookIds = getNotebookParentIdSet(notebooks);- const activeNotebookAncestorIds = getNotebookAncestorIds(notebooks, activeNotebookId);- const visibleNotebookOptions = searchQuery- ? filterNotebookOptionsById(notebookOptions, getMobileNotebookSearchVisibleIds(notebooks, searchText))- : filterCollapsedNotebookOptions(notebookOptions, collapsedNotebookIds);- const activeNotebookName = activeNotebookId === ALL_NOTES_ID- ? "全部笔记"- : notebooks.find((notebook) => notebook.id === activeNotebookId)?.name ?? "全部笔记";- const allNotebookBranchesExpanded = childNotebookIds.size > 0 && Array.from(childNotebookIds).every((notebookId) => !collapsedNotebookIds.has(notebookId));-- useEffect(() => {- if (visible) {- setSearchText("");- setCollapsedNotebookIds(new Set(Array.from(childNotebookIds).filter((notebookId) => !activeNotebookAncestorIds.has(notebookId))));- }- }, [visible, activeNotebookId, notebooks]);-- const toggleNotebookCollapsed = (notebookId: string) => {- setCollapsedNotebookIds((current) => {- const next = new Set(current);-- if (next.has(notebookId)) {- next.delete(notebookId);- } else {- next.add(notebookId);- }-- return next;- });- };-- const toggleAllNotebookBranches = () => {- setCollapsedNotebookIds(allNotebookBranchesExpanded ? new Set(childNotebookIds) : new Set());- };-- return (- <Modal animationType="fade" onRequestClose={onClose} transparent visible={visible}>- <Pressable onPress={onClose} style={styles.actionSheetBackdrop}>- <Pressable style={[styles.actionSheet, styles.notebookPickerSheet, { paddingBottom: Math.max(8, safeAreaInsets.bottom) }]}>- <View style={styles.actionSheetHandle} />- <View style={styles.notebookPickerHeader}>- <View style={styles.notebookPickerHeaderText}>- <Text style={styles.actionSheetTitle}>切换笔记本</Text>- <Text style={styles.panelLabel}>{translate(`当前:${activeNotebookName}`)}</Text>- </View>- <Pressable accessibilityLabel="关闭" accessibilityRole="button" onPress={onClose} style={styles.notebookPickerCloseButton}>- <X color="#0f172a" size={20} />- </Pressable>- </View>-- <ScrollView- contentContainerStyle={styles.notebookPickerContent}- onLayout={selectedScroll.onViewportLayout}- ref={selectedScroll.scrollRef}- style={styles.notebookPickerScroll}- >- <View style={styles.notebookPickerSearchBox}>- <Search color="#64748b" size={18} />- <TextInput- accessibilityLabel="搜索笔记本"- autoCapitalize="none"- autoCorrect={false}- onChangeText={setSearchText}- placeholder="搜索笔记本"- placeholderTextColor="#94a3b8"- style={styles.notebookPickerSearchInput}- value={searchText}- />- {searchText ? (- <Pressable onPress={() => setSearchText("")}>- <X color="#64748b" size={18} />- </Pressable>- ) : null}- </View>-- <Pressable- accessibilityLabel={activeNotebookId === ALL_NOTES_ID ? "当前:全部笔记" : "切换到全部笔记"}- accessibilityRole="button"- accessibilityState={{ selected: activeNotebookId === ALL_NOTES_ID }}- onLayout={(event) => selectedScroll.onRowLayout(ALL_NOTES_ID, event)}- onPress={() => onSelect(ALL_NOTES_ID)}- style={[styles.notebookPickerRow, styles.notebookPickerAllRow, activeNotebookId === ALL_NOTES_ID && styles.notebookPickerRowActive]}- >- <View style={styles.moveNotebookText}>- <Text numberOfLines={1} style={styles.panelValue}>- 全部笔记- </Text>- </View>- {activeNotebookId === ALL_NOTES_ID ? <Check color="#0f172a" size={18} /> : null}- </Pressable>-- <View style={styles.notebookPickerSectionHeader}>- <Text style={styles.label}>{searchQuery ? "匹配的笔记本" : "笔记本"}</Text>- {!searchQuery && childNotebookIds.size > 0 ? (- <Pressable- accessibilityLabel={allNotebookBranchesExpanded ? "收起全部笔记本" : "展开全部笔记本"}- accessibilityRole="button"- onPress={toggleAllNotebookBranches}- style={styles.notebookPickerToggleAll}- >- <Text style={styles.notebookPickerToggleAllText}>{allNotebookBranchesExpanded ? "收起全部" : "展开全部"}</Text>- </Pressable>- ) : null}- </View>- {visibleNotebookOptions.map(({ depth, notebook }) => (- <View- key={notebook.id}- onLayout={(event) => selectedScroll.onRowLayout(notebook.id, event)}- style={[styles.notebookPickerRow, activeNotebookId === notebook.id && styles.notebookPickerRowActive, depth > 0 && { marginLeft: Math.min(depth * 18, 54) }]}- >- {childNotebookIds.has(notebook.id) && !searchQuery ? (- <Pressable- accessibilityLabel={`${collapsedNotebookIds.has(notebook.id) ? "展开" : "收起"} ${notebook.name}`}- accessibilityRole="button"- accessibilityState={{ expanded: !collapsedNotebookIds.has(notebook.id) }}- onPress={() => toggleNotebookCollapsed(notebook.id)}- style={styles.notebookTreeToggle}- >- {collapsedNotebookIds.has(notebook.id) ? <ChevronRight color="#64748b" size={17} /> : <ChevronDown color="#64748b" size={17} />}- </Pressable>- ) : (- <View style={styles.notebookTreeTogglePlaceholder} />- )}- <Pressable- accessibilityLabel={`${activeNotebookId === notebook.id ? "当前" : "切换到"} ${notebook.name}`}- accessibilityRole="button"- accessibilityState={{ selected: activeNotebookId === notebook.id }}- onPress={() => onSelect(notebook.id)}- style={styles.moveNotebookSelectArea}- >- <Text numberOfLines={1} style={styles.panelValue}>- {notebook.name}- </Text>- </Pressable>- {activeNotebookId === notebook.id ? <Check color="#0f172a" size={18} /> : null}- </View>- ))}- {visibleNotebookOptions.length === 0 ? (- <View style={styles.emptyInlinePanel}>- <Folder color="#94a3b8" size={28} />- <Text style={styles.mutedText}>没有匹配的笔记本</Text>- </View>- ) : null}- </ScrollView>- </Pressable>- </Pressable>- </Modal>- );-};--const SmartTagButton = ({- client,- contentMarkdown,- disabled = false,- onChange,- selectedTags,- title,-}: {- client: ReturnType<typeof useSession>["client"];- contentMarkdown: string;- disabled?: boolean;- onChange: (tags: string[]) => void;- selectedTags: string[];- title: string;-}) => {- const { resolvedLocale, translate } = useMobileLocale();- const [status, setStatus] = useState<"idle" | "loading" | "success">("idle");- const controllerRef = useRef<AbortController | null>(null);- const feedbackTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);- const unavailable = disabled || !client || selectedTags.length >= 24 || (!title.trim() && !contentMarkdown.trim());-- useEffect(() => () => {- controllerRef.current?.abort();- if (feedbackTimerRef.current) clearTimeout(feedbackTimerRef.current);- }, []);-- const generateAndApplyTags = async () => {- if (unavailable || !client) return;- controllerRef.current?.abort();- if (feedbackTimerRef.current) clearTimeout(feedbackTimerRef.current);- const controller = new AbortController();- controllerRef.current = controller;- setStatus("loading");- try {- const selectedTagKeys = new Set(selectedTags.map((tag) => tag.toLocaleLowerCase()));- const result = await client.suggestAiTags({- title,- contentMarkdown,- currentTags: selectedTags,- locale: resolvedLocale,- }, controller.signal);- const additions = result.suggestions- .filter((suggestion) => !selectedTagKeys.has(suggestion.name.toLocaleLowerCase()))- .slice(0, Math.max(0, 24 - selectedTags.length))- .map((suggestion) => suggestion.name);- if (additions.length === 0) {- setStatus("idle");- Alert.alert(translate("智能标签"), translate("没有找到适合这篇笔记的新标签。"));- return;- }- onChange(Array.from(new Set([...selectedTags, ...additions])).slice(0, 24));- setStatus("success");- feedbackTimerRef.current = setTimeout(() => {- setStatus("idle");- feedbackTimerRef.current = null;- }, 4000);- } catch (error) {- if (controller.signal.aborted) return;- setStatus("idle");- Alert.alert(- translate("智能标签生成失败"),- error instanceof ApiRequestError && error.code === "ai_not_configured"- ? translate("请先在“AI 集成”中配置默认模型。")- : error instanceof Error- ? error.message- : translate("AI 标签建议生成失败。")- );- } finally {- if (controllerRef.current === controller) controllerRef.current = null;- }- };-- const accessibilityLabel = status === "loading"- ? translate("正在生成智能标签")- : status === "success"- ? translate("智能标签已添加")- : translate("智能标签");-- return (- <Pressable- accessibilityLabel={accessibilityLabel}- accessibilityRole="button"- accessibilityState={{ disabled: unavailable || status === "loading" }}- disabled={unavailable || status === "loading"}- onPress={() => void generateAndApplyTags()}- style={[styles.smartTagButton, status === "success" && styles.smartTagButtonSuccess, unavailable && styles.buttonDisabled]}- >- {status === "loading"- ? <ActivityIndicator color="#047857" size="small" />- : status === "success"- ? <Check color="#047857" size={17} />- : <TagPlus color="#047857" size={18} />}- </Pressable>- );-};--const TagPickerModal = ({- dataScope,- onChange,- onClose,- selectedTags,- visible,-}: {- dataScope: string;- onChange: (tags: string[]) => void;- onClose: () => void;- selectedTags: string[];- visible: boolean;-}) => {- const { translate } = useMobileLocale();- const safeAreaInsets = useSafeAreaInsets();- const [searchText, setSearchText] = useState("");- const tagsQuery = useQuery({- queryKey: ["mobile-tags", dataScope],- queryFn: () => listLocalTags(dataScope),- enabled: visible && Boolean(dataScope),- });- const normalizedSearch = searchText.trim().replace(/^#/, "");- const tags = tagsQuery.data?.tags ?? [];- const visibleTags = tags.filter((tag) => tag.name.toLocaleLowerCase().includes(normalizedSearch.toLocaleLowerCase()));- const exactMatch = tags.some((tag) => tag.name.toLocaleLowerCase() === normalizedSearch.toLocaleLowerCase());-- useEffect(() => {- if (visible) {- setSearchText("");- }- }, [visible]);-- const commit = (nextTags: string[]) => onChange(Array.from(new Set(nextTags)).slice(0, 24));- const toggleTag = (name: string) => commit(- selectedTags.includes(name) ? selectedTags.filter((tag) => tag !== name) : [...selectedTags, name]- );- const createTag = () => {- const additions = parseTags(normalizedSearch);- if (additions.length === 0) return;- commit([...selectedTags, ...additions]);- setSearchText("");- };-- return (- <Modal animationType="fade" onRequestClose={onClose} transparent visible={visible}>- <Pressable onPress={onClose} style={styles.actionSheetBackdrop}>- <Pressable style={[styles.actionSheet, styles.notebookPickerSheet, { paddingBottom: Math.max(8, safeAreaInsets.bottom) }]}>- <View style={styles.actionSheetHandle} />- <View style={styles.notebookPickerHeader}>- <View style={styles.notebookPickerHeaderText}>- <Text style={styles.actionSheetTitle}>{translate("选择标签")}</Text>- <Text style={styles.panelLabel}>{translate("点选已有标签,或输入名称创建新标签")}</Text>- </View>- <Pressable accessibilityLabel="关闭" accessibilityRole="button" onPress={onClose} style={styles.notebookPickerCloseButton}>- <X color="#0f172a" size={20} />- </Pressable>- </View>-- <ScrollView contentContainerStyle={styles.notebookPickerContent} keyboardShouldPersistTaps="handled" style={styles.notebookPickerScroll}>- {selectedTags.length > 0 ? (- <View accessibilityLabel="已选标签" style={styles.tagPickerSelectedList}>- {selectedTags.map((tag) => (- <Pressable key={tag} accessibilityLabel={`移除标签 ${tag}`} accessibilityRole="button" onPress={() => toggleTag(tag)} style={styles.tagPickerChip}>- <Text style={styles.tagPickerChipText}>#{tag}</Text>- <X color="#047857" size={14} />- </Pressable>- ))}- </View>- ) : null}-- <View style={styles.notebookPickerSearchBox}>- <Search color="#64748b" size={18} />- <TextInput- accessibilityLabel="搜索或输入新标签"- autoCapitalize="none"- autoCorrect={false}- onChangeText={setSearchText}- onSubmitEditing={createTag}- placeholder="搜索或输入新标签"- placeholderTextColor="#94a3b8"- returnKeyType="done"- style={styles.notebookPickerSearchInput}- value={searchText}- />- {normalizedSearch && !exactMatch && selectedTags.length < 24 ? (- <Pressable accessibilityLabel={`新建标签 ${normalizedSearch}`} accessibilityRole="button" onPress={createTag}>- <Text style={styles.tagPickerCreateText}>{translate("新建")}</Text>- </Pressable>- ) : null}- </View>-- {tagsQuery.isLoading ? (- <ActivityIndicator color="#16a06e" style={styles.tagPickerLoading} />- ) : visibleTags.length === 0 ? (- <View style={styles.emptyInlinePanel}>- <Tag color="#94a3b8" size={28} />- <Text style={styles.mutedText}>{translate("没有匹配的现有标签,可直接新建")}</Text>- </View>- ) : visibleTags.map((tag) => {- const selected = selectedTags.includes(tag.name);- return (- <Pressable- key={tag.name}- accessibilityLabel={`标签 ${tag.name}`}- accessibilityRole="button"- accessibilityState={{ selected }}- onPress={() => toggleTag(tag.name)}- style={[styles.notebookPickerRow, selected && styles.notebookPickerRowActive]}- >- <View style={[styles.tagPickerCheckbox, selected && styles.tagPickerCheckboxSelected]}>- {selected ? <Check color="#ffffff" size={14} /> : null}- </View>- <Text numberOfLines={1} style={styles.tagPickerRowText}>#{tag.name}</Text>- <Text style={styles.panelLabel}>{translate(`${tag.memoCount} 条笔记`)}</Text>- </Pressable>- );- })}- </ScrollView>- </Pressable>- </Pressable>- </Modal>- );-};--const CreateMemoModal = ({- baseUrl,- client: clientProp,- dataScope,- defaultNotebookId,- imageCompressionEnabled,- initialDraft,- initialSharedImages = [],- notebooks,- onCreated,- onDismiss,- onQueued,- syncQueueScope,-}: {- baseUrl: string;- client?: ReturnType<typeof useSession>["client"];- dataScope: string;- defaultNotebookId: string;- imageCompressionEnabled: boolean;- initialDraft?: MobileCreateMemoSeed | MobileWebClipDraft | null;- initialSharedImages?: MobileSharedImage[];- notebooks: Notebook[];- onCreated: (memo: MemoDetail) => void;- onDismiss: () => void;- onQueued: () => void | Promise<void>;- syncQueueScope: string;-}) => {- const sessionState = useSession();- const client = clientProp ?? sessionState.client;- const session = sessionState.session;- const queryClient = useQueryClient();- const { resolvedLocale, translate } = useMobileLocale();- const { resolvedTheme } = useMobileTheme();- const fallbackNotebookId = defaultNotebookId;- const editorRef = useRef<LocalTiptapEditorRef>(null);- const resourceDataUrlCacheRef = useRef(new Map<string, Promise<string | null>>());- const imageLoadFailureNotifier = useMemo(- () =>- createOnceProtectedResourceFailureNotifier((failure) => {- alertProtectedImageLoadFailure(resolvedLocale, failure);- }),- [resolvedLocale]- );- const contentJsonRef = useRef<TiptapDoc>(markdownToDoc(""));- const contentMarkdownRef = useRef("");- const draftVersionRef = useRef(0);- const draftWriteBarrier = useMemo(createMobileDraftWriteBarrier, []);- const flushResolverRef = useRef<(() => void) | null>(null);- const materializedMemoRef = useRef<MemoDetail | null>(null);- const [notebookId, setNotebookId] = useState(fallbackNotebookId);- const [title, setTitle] = useState("");- const [tagsText, setTagsText] = useState("");- const [contentMarkdown, setContentMarkdown] = useState("");- const [notebookPickerOpen, setNotebookPickerOpen] = useState(false);- const [tagPickerOpen, setTagPickerOpen] = useState(false);- const [templatePickerOpen, setTemplatePickerOpen] = useState(false);- const [draftLoaded, setDraftLoaded] = useState(false);- const [dirty, setDirty] = useState(false);- const [editorReady, setEditorReady] = useState(false);- const [imageOperation, setImageOperation] = useState<"idle" | "creating" | "uploading">("idle");- const imageOperationRef = useRef(imageOperation);- const sharedImagesHandledRef = useRef(false);- const createPendingRef = useRef(false);- const submitStartedRef = useRef(false);- const [submitStarted, setSubmitStarted] = useState(false);- const [resourceTarget, setResourceTarget] = useState<MobileResourceTarget | null>(null);- const editorStartup = useMobileEditorStartupGuard({ active: draftLoaded && Boolean(baseUrl), ready: editorReady });- const { pickUploadAsset, uploadSourcePicker } = useMobileEditorUploadAsset();- const targetNotebookId = notebookId || fallbackNotebookId;- const selectedNotebookName = notebooks.find((notebook) => notebook.id === targetNotebookId)?.name ?? "选择笔记本";- const titleRef = useRef(title);- const tagsTextRef = useRef(tagsText);- const targetNotebookIdRef = useRef(targetNotebookId);- const userEditedSinceOpenRef = useRef(false);- const notebooksRef = useRef(notebooks);- notebooksRef.current = notebooks;- titleRef.current = title;- tagsTextRef.current = tagsText;- targetNotebookIdRef.current = targetNotebookId;- imageOperationRef.current = imageOperation;-- const { aiPromptsJson, cancelSelectionAi, requestSelectionAi } = useMobileSelectionAi({- client,- editorRef,- resolvedLocale,- titleRef,- });-- const focusTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);- const keyboardTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);-- const pushBodyToEditor = useCallback((doc: TiptapDoc) => {- safeDomCall(() => editorRef.current?.setContent(JSON.stringify(doc)));- }, []);-- const clearFocusTimers = useCallback(() => {- if (focusTimerRef.current !== null) {- clearTimeout(focusTimerRef.current);- focusTimerRef.current = null;- }- if (keyboardTimerRef.current !== null) {- clearTimeout(keyboardTimerRef.current);- keyboardTimerRef.current = null;- }- }, []);-- const scheduleBodyKeyboard = useCallback((delayMs = 160, focusEditor = true) => {- clearFocusTimers();- // Full-tree create only mounts the editor DomWebView, so native IME show is safe again.- focusTimerRef.current = setTimeout(() => {- focusTimerRef.current = null;- if (focusEditor) {- safeDomCall(() => editorRef.current?.focusEnd());- }- if (Platform.OS === "android") {- keyboardTimerRef.current = setTimeout(() => {- keyboardTimerRef.current = null;- showEdgeEverKeyboard();- }, focusEditor ? 120 : 0);- }- }, delayMs);- }, [clearFocusTimers]);-- const retryEditorStartup = useCallback(() => {- clearFocusTimers();- setEditorReady(false);- editorStartup.restart();- }, [clearFocusTimers, editorStartup.restart]);-- // Component is only mounted while create is open — init once on mount.- useEffect(() => {- let active = true;- setDraftLoaded(false);- setEditorReady(false);- setTemplatePickerOpen(false);- userEditedSinceOpenRef.current = false;- draftVersionRef.current = 0;-- if (initialDraft) {- const markdown = initialDraft.contentMarkdown;- contentMarkdownRef.current = markdown;- contentJsonRef.current = markdownToDoc(markdown);- setTitle(initialDraft.title);- setTagsText(initialDraft.tagsText);- setContentMarkdown(markdown);- setNotebookId(fallbackNotebookId);- setDirty(false);- setDraftLoaded(true);- return () => {- active = false;- };- }-- contentMarkdownRef.current = "";- contentJsonRef.current = markdownToDoc("");- setTitle("");- setTagsText("");- setContentMarkdown("");- setNotebookId(fallbackNotebookId);- setDirty(false);-- // A regular create session must always start blank. Remove any legacy- // auto-saved create draft instead of restoring content from the last one.- void clearMobileNewMemoDraft(dataScope).catch(() => undefined).finally(() => {- if (active) {- setDraftLoaded(true);- }- });- return () => {- active = false;- };- // eslint-disable-next-line react-hooks/exhaustive-deps -- mount-only for create screen lifetime- }, []);-- const isWebClipDraft = Boolean(- initialDraft && "sourceUrl" in initialDraft && typeof initialDraft.sourceUrl === "string" && initialDraft.sourceUrl.length > 0- );-- const persistCurrentDraft = useCallback(() => {- const materializedMemo = materializedMemoRef.current;- const currentTitle = titleRef.current;- const currentContentMarkdown = contentMarkdownRef.current;- const currentNotebookId = targetNotebookIdRef.current;- const currentTagsText = tagsTextRef.current;- const updatedAt = new Date().toISOString();-- return draftWriteBarrier.enqueue(() => materializedMemo- ? writeMobileMemoDraft({- memoId: materializedMemo.id,- expectedRevision: materializedMemo.revision,- title: currentTitle,- contentMarkdown: currentContentMarkdown,- notebookId: currentNotebookId,- tagsText: currentTagsText,- updatedAt,- })- : Promise.resolve());- }, [draftWriteBarrier]);-- const applyTemplateSeed = useCallback((seed: MobileCreateMemoSeed) => {- const markdown = seed.contentMarkdown;- const doc = markdownToDoc(markdown);- contentMarkdownRef.current = markdown;- contentJsonRef.current = doc;- setTitle(seed.title);- setTagsText(seed.tagsText);- setContentMarkdown(markdown);- draftVersionRef.current += 1;- userEditedSinceOpenRef.current = true;- setDirty(true);- // In-place body replace — never remount DomWebView (remount costs ~1s and breaks Android IME).- pushBodyToEditor(doc);- scheduleBodyKeyboard(80);- }, [pushBodyToEditor, scheduleBodyKeyboard]);-- const requestApplyTemplateSeed = useCallback((seed: MobileCreateMemoSeed) => {- const current = {- title: titleRef.current,- contentMarkdown: contentMarkdownRef.current,- tagsText: tagsTextRef.current,- };- if (createMemoSeedHasContent(current)) {- Alert.alert(translate("应用模板?"), translate("当前内容将被模板内容替换。"), [- { text: translate("取消"), style: "cancel" },- { text: translate("替换"), style: "destructive", onPress: () => applyTemplateSeed(seed) },- ]);- return;- }- applyTemplateSeed(seed);- }, [applyTemplateSeed, translate]);-- useEffect(() => {- if (!draftLoaded || !dirty || isWebClipDraft) {- return;- }- const draftVersion = draftVersionRef.current;- const timeout = setTimeout(() => {- void persistCurrentDraft().then((written) => {- if (written && !submitStartedRef.current && draftVersionRef.current === draftVersion) {- setDirty(false);- }- }).catch(() => undefined);- }, 350);- return () => clearTimeout(timeout);- }, [contentMarkdown, dirty, draftLoaded, isWebClipDraft, persistCurrentDraft, tagsText, targetNotebookId, title]);-- const createMutation = useMutation({- mutationFn: async () => {- if (!targetNotebookId) {- throw new Error("请先创建一个笔记本");- }- const materializedMemo = materializedMemoRef.current;- if (materializedMemo) {- const optimisticMemo = createOptimisticMemo(materializedMemo, {- title: titleRef.current.trim() || DEFAULT_MEMO_TITLE,- contentJson: contentJsonRef.current,- contentMarkdown: contentMarkdownRef.current.trim(),- notebookId: targetNotebookIdRef.current,- tags: parseTags(tagsTextRef.current),- });- await upsertLocalMemo(dataScope, optimisticMemo);- await queueMobileMemoUpdate(syncQueueScope, {- memoId: materializedMemo.id,- expectedRevision: materializedMemo.revision,- expectedContentHash: materializedMemo.contentHash,- title: optimisticMemo.title ?? DEFAULT_MEMO_TITLE,- contentMarkdown: optimisticMemo.contentMarkdown,- notebookId: optimisticMemo.notebookId,- tags: optimisticMemo.tags,- });- return optimisticMemo;- }- const now = new Date().toISOString();- const temporaryId = `local:${Date.now().toString(36)}:${Math.random().toString(36).slice(2, 10)}`;- const markdown = contentMarkdownRef.current.trim();- const contentJson = contentJsonRef.current;- const contentText = docToText(contentJson);- const memo: MemoDetail = {- id: temporaryId,- notebookId: targetNotebookId,- title: title.trim() || DEFAULT_MEMO_TITLE,- excerpt: createExcerpt(contentText),- tags: parseTags(tagsText),- 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 memo;- },- onSuccess: async (memo) => {- const materializedMemoId = materializedMemoRef.current?.id ?? null;- // Wait for any already-running AsyncStorage write before removing the- // draft. Nothing queued after submit began is allowed to recreate it.- await draftWriteBarrier.blockAndDrain();- if (!isWebClipDraft) {- await clearMobileNewMemoDraft(dataScope);- }- if (materializedMemoId) {- await clearMobileMemoDraft(materializedMemoId);- }- await Promise.all([- queryClient.invalidateQueries({ queryKey: ["mobile", "notebooks"] }),- queryClient.invalidateQueries({ queryKey: ["mobile", "memos"] }),- ]);- setTitle("");- setTagsText("");- setContentMarkdown("");- contentMarkdownRef.current = "";- contentJsonRef.current = markdownToDoc("");- materializedMemoRef.current = null;- draftVersionRef.current += 1;- setDirty(false);- void onQueued();- onCreated(memo);- },- onError: () => {- submitStartedRef.current = false;- draftWriteBarrier.unblock();- setSubmitStarted(false);- draftVersionRef.current += 1;- setDirty(true);- if (!isWebClipDraft) {- void persistCurrentDraft().catch(() => undefined);- }- },- });- createPendingRef.current = createMutation.isPending;- const canSubmitCreateMemo = Boolean(targetNotebookId) && !submitStarted && !createMutation.isPending && imageOperation === "idle";- const canUseTemplate = editorReady && imageOperation === "idle" && !submitStarted && !createMutation.isPending;-- const materializeMemoForImage = async () => {- if (materializedMemoRef.current) {- return materializedMemoRef.current;- }- if (!client || !targetNotebookIdRef.current) {- throw new Error("当前无法连接实例,请稍后重试");- }- setImageOperation("creating");- const response = await client.createMemo({- notebookId: targetNotebookIdRef.current,- title: titleRef.current.trim() || DEFAULT_MEMO_TITLE,- contentMarkdown: contentMarkdownRef.current.trim(),- tags: parseTags(tagsTextRef.current),- });- materializedMemoRef.current = response.memo;- await upsertLocalMemo(dataScope, response.memo);- if (!isWebClipDraft) {- await clearMobileNewMemoDraft(dataScope);- }- await Promise.all([- queryClient.invalidateQueries({ queryKey: ["mobile", "notebooks"] }),- queryClient.invalidateQueries({ queryKey: ["mobile", "memos"] }),- ]);- return response.memo;- };-- const uploadImageAsset = async (asset: MobileImageUploadAsset | null) => {- let uploadId: string | null = null;- try {- if (!asset) {- return;- }- const isImage = asset.mimeType?.startsWith("image/") ?? false;- if (isImage) {- uploadId = createMobileImageUploadId();- const previewDataUrl = await createLocalImagePreviewDataUrl(asset);- safeDomCall(() => editorRef.current?.beginImageUpload(uploadId, previewDataUrl));- }- const memo = await materializeMemoForImage();- setImageOperation("uploading");- const uploadAsset = await prepareUploadAsset(asset, imageCompressionEnabled);- const form = new FormData();- form.append("file", new ExpoFile(uploadAsset.uri));- const { resource } = await client!.uploadMemoResource(memo.id, form);- applyMobileEditorUpload(editorRef, resource, uploadId, uploadAsset.name || (resource.kind === "image" ? "图片" : "附件"));- } catch (error) {- cancelMobileEditorUpload(editorRef, uploadId);- Alert.alert("附件上传失败", error instanceof Error ? error.message : "请检查网络连接后重试");- } finally {- setImageOperation("idle");- }- };-- const pickAndUploadImage = async () => {- const asset = await pickUploadAsset();- await uploadImageAsset(asset);- };-- useEffect(() => {- if (!editorReady || sharedImagesHandledRef.current || initialSharedImages.length === 0) {- return;- }- sharedImagesHandledRef.current = true;- void (async () => {- for (const image of initialSharedImages) {- await uploadImageAsset(image);- }- })();- }, [editorReady, initialSharedImages]);-- const markDirty = () => {- if (submitStartedRef.current) {- return;- }- userEditedSinceOpenRef.current = true;- draftVersionRef.current += 1;- setDirty(true);- };-- const flushEditor = () => flushMobileEditor(editorRef, flushResolverRef);-- const submitCreateMemo = async () => {- if (submitStartedRef.current || createPendingRef.current || imageOperationRef.current !== "idle") {- return;- }- submitStartedRef.current = true;- setSubmitStarted(true);- const draftsDrained = draftWriteBarrier.blockAndDrain();- try {- await flushEditor();- await draftsDrained;- createMutation.mutate();- } catch {- submitStartedRef.current = false;- draftWriteBarrier.unblock();- setSubmitStarted(false);- }- };-- const requestClose = () => submitCreateMemo();-- useEffect(() => {- const subscription = BackHandler.addEventListener("hardwareBackPress", () => {- void requestClose();- return true;- });- return () => {- subscription.remove();- clearFocusTimers();- };- }, [clearFocusTimers]);-- const canMutateEditorResource = useCallback(() => Boolean(materializedMemoRef.current), []);- const {- deleteResource,- downloadResource,- loadEditorResource,- renameResource,- saveResourceAs,- selectResource,- } = useMobileEditorResourceActions({- baseUrl,- canMutate: canMutateEditorResource,- client,- editorRef,- onLoadFailure: imageLoadFailureNotifier,- onSelect: setResourceTarget,- resolvedLocale,- resourceCacheRef: resourceDataUrlCacheRef,- sessionBaseUrl: session?.baseUrl,- token: session?.token,- });-- const editorElement = useMemo(() => draftLoaded && baseUrl ? (- <LocalTiptapEditor- autoFocus- aiPromptsJson={aiPromptsJson}- baseUrl={baseUrl}- content={contentJsonRef.current}- dom={{- ...SAFE_DOM_WEBVIEW_PROPS,- bounces: false,- contentInsetAdjustmentBehavior: "never",- overScrollMode: "never",- scrollEnabled: false,- style: styles.createMemoEditor,- }}- onChange={async (contentJson) => {- contentJsonRef.current = contentJson;- const markdown = docToMarkdown(contentJson);- contentMarkdownRef.current = markdown;- setContentMarkdown(markdown);- markDirty();- flushResolverRef.current?.();- flushResolverRef.current = null;- }}- onAiCancel={cancelSelectionAi}- onAiRequest={requestSelectionAi}- onResourcePress={selectResource}- onLoadResource={loadEditorResource}- onPickImage={pickAndUploadImage}- onReady={async (elapsedMs) => {- setEditorReady(true);- recordEditorStartup(elapsedMs);- // LocalTiptapEditor owns caret placement; native only reveals the IME after- // its final focus retry so the two layers cannot race each other.- scheduleBodyKeyboard(180, false);- }}- key={editorStartup.attempt}- ref={editorRef}- locale={resolvedLocale}- theme={resolvedTheme}- />- ) : null, [aiPromptsJson, baseUrl, cancelSelectionAi, draftLoaded, editorStartup.attempt, loadEditorResource, pushBodyToEditor, requestSelectionAi, resolvedLocale, resolvedTheme, scheduleBodyKeyboard, selectResource]);-- return (- <SafeAreaView edges={["top", "left", "right", "bottom"]} style={styles.createMemoSafeArea}>- <View style={styles.createMemoHeader}>- <Pressable accessibilityLabel="返回" accessibilityRole="button" disabled={submitStarted || createMutation.isPending || imageOperation !== "idle"} onPress={() => void requestClose()} style={styles.createMemoBackButton}>- <ChevronLeft color={submitStarted || createMutation.isPending || imageOperation !== "idle" ? "#cbd5e1" : "#0f172a"} size={30} />- </Pressable>- <View style={styles.createMemoHeaderActions}>- <Text style={[styles.createMemoStatus, (submitStarted || createMutation.isPending) && styles.createMemoStatusActive]}>- {imageOperation === "creating" ? "正在创建" : imageOperation === "uploading" ? "正在上传" : submitStarted || createMutation.isPending || dirty ? "保存中" : editorReady ? "已保存" : "准备中"}- </Text>- <Pressable- accessibilityLabel={translate("模板")}- accessibilityRole="button"- disabled={!canUseTemplate}- onPress={() => setTemplatePickerOpen(true)}- style={[styles.createMemoTemplateButton, !canUseTemplate && styles.createMemoDoneButtonDisabled]}- >- <Text style={[styles.createMemoTemplateButtonText, !canUseTemplate && styles.createMemoDoneTextDisabled]}>{translate("模板")}</Text>- </Pressable>- <Pressable- accessibilityLabel="完成新建笔记"- disabled={!canSubmitCreateMemo}- onPress={() => void submitCreateMemo()}- style={[styles.createMemoDoneButton, !canSubmitCreateMemo && styles.createMemoDoneButtonDisabled]}- >- {submitStarted || createMutation.isPending ? <ActivityIndicator color="#64748b" size="small" /> : <Text style={[styles.createMemoDoneText, !canSubmitCreateMemo && styles.createMemoDoneTextDisabled]}>完成</Text>}- </Pressable>- </View>- </View>-- <View style={styles.createMemoMain}>- <TextInput- autoCorrect- accessibilityLabel="笔记标题"- onChangeText={(value) => {- setTitle(value);- markDirty();- }}- placeholder={DEFAULT_MEMO_TITLE}- placeholderTextColor="#94a3b8"- style={styles.createMemoTitleInput}- value={title}- />-- <View style={styles.createMemoMetaRow}>- <Pressable accessibilityLabel="所在笔记本" accessibilityRole="button" onPress={() => setNotebookPickerOpen(true)} style={styles.createMemoNotebookButton}>- <Text numberOfLines={1} style={styles.createMemoNotebookText}>{selectedNotebookName}</Text>- <ChevronDown color="#64748b" size={14} />- </Pressable>- <Pressable accessibilityLabel="选择笔记标签" accessibilityRole="button" onPress={() => setTagPickerOpen(true)} style={styles.createMemoTagsButton}>- <Text numberOfLines={1} style={[styles.createMemoTagsInput, !tagsText && styles.createMemoTagsPlaceholder]}>- {tagsText || "添加标签"}- </Text>- <ChevronDown color="#94a3b8" size={14} />- </Pressable>- <SmartTagButton- client={client}- contentMarkdown={contentMarkdown}- onChange={(nextTags) => {- setTagsText(nextTags.join(", "));- markDirty();- }}- selectedTags={parseTags(tagsText)}- title={title}- />- </View>-- <View style={styles.createMemoEditorFrame}>- {editorElement}- {!editorReady ? <MobileEditorStartupOverlay onRetry={retryEditorStartup} timedOut={editorStartup.timedOut} /> : null}- </View>-- {createMutation.error ? (- <Text style={styles.errorText}>{createMutation.error instanceof Error ? createMutation.error.message : "创建失败"}</Text>- ) : null}- </View>- <NotebookPickerModal- activeNotebookId={targetNotebookId}- notebooks={notebooks}- onClose={() => setNotebookPickerOpen(false)}- onSelect={(nextNotebookId) => {- setNotebookId(nextNotebookId);- setNotebookPickerOpen(false);- markDirty();- }}- visible={notebookPickerOpen}- />- <TagPickerModal- dataScope={dataScope}- onChange={(nextTags) => {- setTagsText(nextTags.join(", "));- markDirty();- }}- onClose={() => setTagPickerOpen(false)}- selectedTags={parseTags(tagsText)}- visible={tagPickerOpen}- />- <MobileResourceActions- canMutate={Boolean(materializedMemoRef.current)}- onClose={() => setResourceTarget(null)}- onDelete={deleteResource}- onDownload={downloadResource}- onRename={renameResource}- onSaveAs={saveResourceAs}- target={resourceTarget}- />- <MobileTemplatePickerModal- client={client}- onClose={() => {- setTemplatePickerOpen(false);- scheduleBodyKeyboard(80);- }}- onSelect={requestApplyTemplateSeed}- presentation="overlay"- visible={templatePickerOpen}- />- {uploadSourcePicker}- </SafeAreaView>- );-};--const RevisionHistoryModal = ({- memo,- onClose,- onRestored,-}: {- memo: MemoDetail | null;- onClose: () => void;- onRestored: (memo: MemoDetail) => void | Promise<void>;-}) => {- const { client } = useSession();- const queryClient = useQueryClient();- const localePreference = useMobileLocalePreference();- const [selectedRevisionId, setSelectedRevisionId] = useState<string | null>(null);-- const revisionsQuery = useQuery({- queryKey: ["mobile", "memo-revisions", memo?.id],- queryFn: async () => {- if (!client || !memo) {- throw new Error("Memo is not selected");- }-- return client.listMemoRevisions(memo.id);- },- enabled: Boolean(client && memo),- });-- const revisions = revisionsQuery.data?.revisions ?? [];- const selectedRevision = revisions.find((revision) => revision.id === selectedRevisionId) ?? revisions[0] ?? null;-- useEffect(() => {- if (memo && revisions.length > 0 && !selectedRevisionId) {- setSelectedRevisionId(revisions[0].id);- }- }, [memo, revisions, selectedRevisionId]);-- useEffect(() => {- if (!memo) {- setSelectedRevisionId(null);- }- }, [memo]);-- useEffect(() => {- setSelectedRevisionId(null);- }, [memo?.id]);-- const restoreRevisionMutation = useMutation({- mutationFn: async (revision: MemoRevision) => {- if (!client || !memo) {- throw new Error("Memo is not selected");- }-- const response = await client.restoreMemoRevision(memo.id, revision.id);- return response.memo;- },- onSuccess: async (restoredMemo) => {- await Promise.all([- queryClient.invalidateQueries({ queryKey: ["mobile", "memos"] }),- queryClient.invalidateQueries({ queryKey: ["mobile", "search"] }),- queryClient.invalidateQueries({ queryKey: ["mobile", "memo"] }),- queryClient.invalidateQueries({ queryKey: ["mobile", "memo-revisions", restoredMemo.id] }),- ]);- await onRestored(restoredMemo);- },- });-- const requestRestoreRevision = (revision: MemoRevision) => {- Alert.alert("恢复到这个历史版本", "当前内容会被这个历史版本替换,恢复后仍会产生新的历史记录。", [- { text: "取消", style: "cancel" },- {- text: "恢复",- onPress: () => restoreRevisionMutation.mutate(revision),- },- ]);- };-- return (- <Modal animationType="slide" onRequestClose={onClose} presentationStyle="pageSheet" visible={Boolean(memo)}>- <SafeAreaView style={styles.modalSafeArea}>- <View style={styles.managementHeader}>- <View style={styles.managementHeaderText}>- <View style={styles.managementTitleRow}>- <History color="#059669" size={19} />- <Text style={styles.managementTitle}>版本历史</Text>- </View>- <Text numberOfLines={1} style={styles.managementSubtitle}>{memo?.title?.trim() || DEFAULT_MEMO_TITLE}</Text>- </View>- <IconButton accessibilityLabel="关闭" onPress={onClose}>- <X color="#0f172a" size={20} />- </IconButton>- </View>-- <ScrollView contentContainerStyle={styles.revisionHistoryContent}>- <View style={styles.revisionSummaryRow}>- <View style={styles.revisionSummaryText}>- <Text style={styles.settingsRowTitle}>{selectedRevision ? `版本 ${selectedRevision.revision}` : "未选择历史版本"}</Text>- <Text style={styles.settingsRowDescription}>选择历史记录后可预览并恢复。</Text>- </View>- {selectedRevision ? (- <ActionButton disabled={restoreRevisionMutation.isPending || Boolean(memo?.isDeleted)} label={restoreRevisionMutation.isPending ? "恢复中" : "恢复该版本"} onPress={() => requestRestoreRevision(selectedRevision)}>- <RotateCcw color="#0f172a" size={16} />- </ActionButton>- ) : null}- </View>-- <Text style={styles.revisionTimelineLabel}>历史记录</Text>- {revisionsQuery.isLoading ? (- <View style={styles.revisionTimelineState}>- <Text style={styles.mutedText}>加载中</Text>- </View>- ) : revisionsQuery.isError ? (- <View style={styles.revisionTimelineState}>- <Text style={styles.errorText}>加载失败</Text>- <Text style={styles.revisionTimelineError}>- {revisionsQuery.error instanceof Error ? revisionsQuery.error.message : "请稍后重试"}- </Text>- <ActionButton label="重试" onPress={() => void revisionsQuery.refetch()}>- <RotateCcw color="#0f172a" size={16} />- </ActionButton>- </View>- ) : revisions.length === 0 ? (- <View style={styles.revisionTimelineState}>- <Text style={styles.mutedText}>暂无历史版本</Text>- </View>- ) : (- <View style={styles.revisionTimeline}>- {revisions.map((revision) => (- <Pressable- key={revision.id}- onPress={() => setSelectedRevisionId(revision.id)}- style={[styles.revisionPill, selectedRevision?.id === revision.id && styles.revisionPillActive]}- >- <Text style={[styles.revisionPillTitle, selectedRevision?.id === revision.id && styles.revisionPillTitleActive]}>{`版本 ${revision.revision}`}</Text>- <Text style={[styles.revisionPillMeta, selectedRevision?.id === revision.id && styles.revisionPillTitleActive]}>- {formatDate(revision.createdAt, localePreference)} · {formatRevisionActor(revision.createdBy)}- </Text>- </Pressable>- ))}- </View>- )}-- {selectedRevision ? (- <View style={styles.revisionPreviewCard}>- <Text selectable style={styles.revisionPreviewText}>{selectedRevision.contentMarkdown || "空笔记"}</Text>- </View>- ) : null}- {restoreRevisionMutation.error ? (- <Text style={styles.errorText}>{restoreRevisionMutation.error instanceof Error ? restoreRevisionMutation.error.message : "恢复失败"}</Text>- ) : null}- </ScrollView>- </SafeAreaView>- </Modal>- );-};--const RichEditorModal = ({- baseUrl,- initialDraft,- imageCompressionEnabled,- memo,- notebooks,- onClose,- updateMutation,-}: {- baseUrl: string;- initialDraft: MobileMemoDraft | null;- imageCompressionEnabled: boolean;- memo: MemoDetail | null;- notebooks: Notebook[];- onClose: () => void;- updateMutation: MobileMemoUpdateMutation;-}) => {- const { client, session } = useSession();- const { resolvedLocale } = useMobileLocale();- const { resolvedTheme } = useMobileTheme();- const restoredDraft = initialDraft?.expectedRevision === memo?.revision ? initialDraft : null;- const initialContentJson = restoredDraft- ? markdownToDoc(restoredDraft.contentMarkdown)- : resolveMemoContentDoc(memo?.contentJson, memo?.contentMarkdown);- const editorRef = useRef<LocalTiptapEditorRef>(null);- const resourceDataUrlCacheRef = useRef(new Map<string, Promise<string | null>>());- const imageLoadFailureNotifier = useMemo(- () =>- createOnceProtectedResourceFailureNotifier((failure) => {- alertProtectedImageLoadFailure(resolvedLocale, failure);- }),- [memo?.id, resolvedLocale]- );- const initialFocusTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);- const contentJsonRef = useRef<TiptapDoc>(initialContentJson);- const contentMarkdownRef = useRef(restoredDraft?.contentMarkdown ?? memo?.contentMarkdown ?? "");- const contentSnapshotRef = useRef(JSON.stringify(contentJsonRef.current));- const dirtyRef = useRef(Boolean(restoredDraft));- const flushResolverRef = useRef<(() => void) | null>(null);- const savingRef = useRef(false);- const uploadingRef = useRef(false);- const memoBaseRef = useRef(memo);- const [title, setTitle] = useState(resolveEditableMemoTitle(restoredDraft?.title ?? memo?.title));- const [tagsText, setTagsText] = useState(restoredDraft?.tagsText ?? memo?.tags.join(", ") ?? "");- const [notebookId, setNotebookId] = useState(restoredDraft?.notebookId ?? memo?.notebookId ?? "");- const [notebookPickerOpen, setNotebookPickerOpen] = useState(false);- const [tagPickerOpen, setTagPickerOpen] = useState(false);- const [draftRestored, setDraftRestored] = useState(Boolean(restoredDraft));- const [ready, setReady] = useState(false);- const [dirty, setDirty] = useState(Boolean(restoredDraft));- const [saving, setSaving] = useState(false);- const [uploading, setUploading] = useState(false);- const [error, setError] = useState<string | null>(null);- const [startupMs, setStartupMs] = useState<number | null>(null);- const [resourceTarget, setResourceTarget] = useState<MobileResourceTarget | null>(null);- const editorStartup = useMobileEditorStartupGuard({ active: Boolean(memo && baseUrl), ready });- const { pickUploadAsset, uploadSourcePicker } = useMobileEditorUploadAsset();- const notebookLabel = notebooks.find((notebook) => notebook.id === notebookId)?.name ?? "未分类";- const saveLabel = error ? "保存失败" : saving ? "保存中" : uploading ? "上传中" : dirty ? (draftRestored ? "本地草稿" : "未保存") : ready ? "已保存" : "加载中";- const titleRef = useRef(title);- const tagsTextRef = useRef(tagsText);- const notebookIdRef = useRef(notebookId);- titleRef.current = title;- tagsTextRef.current = tagsText;- notebookIdRef.current = notebookId;-- useEffect(() => () => {- if (initialFocusTimerRef.current !== null) {- clearTimeout(initialFocusTimerRef.current);- initialFocusTimerRef.current = null;- }- }, []);-- const retryEditorStartup = useCallback(() => {- if (initialFocusTimerRef.current !== null) {- clearTimeout(initialFocusTimerRef.current);- initialFocusTimerRef.current = null;- }- setReady(false);- setStartupMs(null);- setError(null);- editorStartup.restart();- }, [editorStartup.restart]);-- const persistDraft = async (contentJson: TiptapDoc) => {- const currentMemo = memoBaseRef.current;- if (!currentMemo) {- return;- }- const contentSnapshot = JSON.stringify(contentJson);- if (contentSnapshot === contentSnapshotRef.current) {- flushResolverRef.current?.();- flushResolverRef.current = null;- return;- }- contentSnapshotRef.current = contentSnapshot;- contentJsonRef.current = contentJson;- contentMarkdownRef.current = docToMarkdown(contentJson);- dirtyRef.current = true;- setDirty(true);- setError(null);- flushResolverRef.current?.();- flushResolverRef.current = null;- await writeMobileMemoDraft({- memoId: currentMemo.id,- expectedRevision: currentMemo.revision,- title: titleRef.current.trim(),- contentMarkdown: contentMarkdownRef.current,- notebookId: notebookIdRef.current,- tagsText: tagsTextRef.current,- updatedAt: new Date().toISOString(),- });- };-- const save = async () => {- const currentMemo = memoBaseRef.current;- if (!currentMemo || savingRef.current || !notebookIdRef.current) {- return null;- }- if (!dirtyRef.current) {- return currentMemo;- }- // Capture whether the user kept typing while this save is in flight so we- // do not clear the dirty flag and drop their next autosave.- const dirtyGenerationAtStart = contentSnapshotRef.current;- savingRef.current = true;- setSaving(true);- setError(null);-- try {- const savedMemo = await updateMutation.mutateAsync({- memo: currentMemo,- payload: {- title: titleRef.current.trim() || DEFAULT_MEMO_TITLE,- contentJson: contentJsonRef.current,- contentMarkdown: contentMarkdownRef.current,- notebookId: notebookIdRef.current,- tags: parseTags(tagsTextRef.current),- },- });- memoBaseRef.current = savedMemo;- await clearMobileMemoDraft(currentMemo.id);- if (contentSnapshotRef.current === dirtyGenerationAtStart) {- dirtyRef.current = false;- setDirty(false);- } else {- // Newer local edits arrived during the save; keep dirty so the next pass uploads them.- dirtyRef.current = true;- setDirty(true);- }- setDraftRestored(false);- return savedMemo;- } catch (saveError) {- setError(saveError instanceof Error ? saveError.message : "保存失败");- return null;- } finally {- savingRef.current = false;- setSaving(false);- }- };-- const flushEditor = () => flushMobileEditor(editorRef, flushResolverRef);- const { aiPromptsJson, cancelSelectionAi, requestSelectionAi } = useMobileSelectionAi({- client,- editorRef,- resolvedLocale,- titleRef,- });-- const requestClose = async () => {- if (savingRef.current || uploadingRef.current) {- return;- }- if (initialFocusTimerRef.current !== null) {- clearTimeout(initialFocusTimerRef.current);- initialFocusTimerRef.current = null;- }- await flushEditor();- const savedMemo = await save();- if (savedMemo) {- onClose();- }- };-- useEffect(() => {- const subscription = BackHandler.addEventListener("hardwareBackPress", () => {- void requestClose();- return true;- });- return () => subscription.remove();- }, []);-- const pickAndUploadImage = async () => {- if (!client || !memo || uploadingRef.current) {- return;- }- if (memo.id.startsWith("local:")) {- Alert.alert("正在同步新笔记", "首次同步完成后即可上传本地图片;图片链接现在就可以直接粘贴到正文。");- return;- }- const asset = await pickUploadAsset();- if (!asset) {- return;- }-- const isImage = asset.mimeType?.startsWith("image/") ?? false;- const uploadId = isImage ? createMobileImageUploadId() : null;- uploadingRef.current = true;- setUploading(true);- setError(null);- try {- if (isImage && uploadId) {- const previewDataUrl = await createLocalImagePreviewDataUrl(asset);- safeDomCall(() => editorRef.current?.beginImageUpload(uploadId, previewDataUrl));- }- const uploadAsset = await prepareUploadAsset(asset, imageCompressionEnabled);- const form = new FormData();- form.append("file", new ExpoFile(uploadAsset.uri));- const { resource } = await client.uploadMemoResource(memo.id, form);- applyMobileEditorUpload(editorRef, resource, uploadId, uploadAsset.name || (resource.kind === "image" ? "图片" : "附件"));- } catch (uploadError) {- cancelMobileEditorUpload(editorRef, uploadId);- setError(uploadError instanceof Error ? uploadError.message : "附件上传失败");- } finally {- uploadingRef.current = false;- setUploading(false);- }- };-- const canMutateEditorResource = useCallback(() => Boolean(memo && !memo.id.startsWith("local:")), [memo]);- const {- deleteResource,- downloadResource,- loadEditorResource,- renameResource,- saveResourceAs,- selectResource,- } = useMobileEditorResourceActions({- baseUrl,- canMutate: canMutateEditorResource,- client,- editorRef,- onLoadFailure: imageLoadFailureNotifier,- onSelect: setResourceTarget,- resolvedLocale,- resourceCacheRef: resourceDataUrlCacheRef,- sessionBaseUrl: session?.baseUrl,- token: session?.token,- });-- const editorElement = useMemo(- () => memo && baseUrl ? (- <LocalTiptapEditor- autoFocus- aiPromptsJson={aiPromptsJson}- baseUrl={baseUrl}- content={contentJsonRef.current}- dom={{- ...SAFE_DOM_WEBVIEW_PROPS,- bounces: false,- contentInsetAdjustmentBehavior: "never",- overScrollMode: "never",- scrollEnabled: false,- style: styles.richEditorWebView,- }}- onChange={persistDraft}- onAiCancel={cancelSelectionAi}- onAiRequest={requestSelectionAi}- onResourcePress={selectResource}- onLoadResource={loadEditorResource}- onPickImage={pickAndUploadImage}- onReady={async (elapsedMs) => {- setStartupMs(elapsedMs);- setReady(true);- recordEditorStartup(elapsedMs);- if (initialFocusTimerRef.current !== null) {- clearTimeout(initialFocusTimerRef.current);- }- // The DOM editor performs its own bounded focus retry. Reveal the Android- // keyboard only after that retry instead of issuing another competing focus.- if (Platform.OS === "android") {- initialFocusTimerRef.current = setTimeout(() => {- initialFocusTimerRef.current = null;- showEdgeEverKeyboard();- }, 180);- }- }}- key={editorStartup.attempt}- ref={editorRef}- locale={resolvedLocale}- theme={resolvedTheme}- />- ) : null,- [aiPromptsJson, baseUrl, cancelSelectionAi, editorStartup.attempt, loadEditorResource, memo?.id, requestSelectionAi, resolvedLocale, resolvedTheme, selectResource]- );-- useEffect(() => {- const currentMemo = memoBaseRef.current;- if (!currentMemo || !dirty) {- return;- }- const timeout = setTimeout(() => {- void writeMobileMemoDraft({- memoId: currentMemo.id,- expectedRevision: currentMemo.revision,- title: titleRef.current.trim(),- contentMarkdown: contentMarkdownRef.current,- notebookId: notebookIdRef.current,- tagsText: tagsTextRef.current,- updatedAt: new Date().toISOString(),- });- }, 350);- return () => clearTimeout(timeout);- }, [dirty, memo, notebookId, tagsText, title]);-- useEffect(() => {- if (!memoBaseRef.current || !dirty || !ready || savingRef.current || uploadingRef.current) {- return;- }- const timeout = setTimeout(() => {- void flushEditor().then(save);- }, 1200);- return () => clearTimeout(timeout);- }, [dirty, memo, notebookId, ready, tagsText, title]);-- return (- <SafeAreaView style={styles.richEditorSafeArea}>- <KeyboardAvoidingView- behavior="height"- enabled={Platform.OS === "android"}- style={styles.richEditorKeyboardAvoiding}- >- <View style={styles.createMemoHeader}>- <Pressable accessibilityLabel="返回" accessibilityRole="button" disabled={saving || uploading} onPress={() => void requestClose()} style={styles.createMemoBackButton}>- <ChevronLeft color={saving || uploading ? "#cbd5e1" : "#0f172a"} size={30} />- </Pressable>- <View style={styles.createMemoHeaderActions}>- <Text numberOfLines={1} style={[styles.createMemoStatus, styles.richEditorHeaderStatus, (saving || uploading || dirty) && styles.createMemoStatusActive, error && styles.richEditorStatusError]}>{saveLabel}</Text>- <Pressable- accessibilityLabel="完成编辑"- accessibilityRole="button"- disabled={saving || uploading || !ready}- onPress={() => void requestClose()}- style={[styles.createMemoDoneButton, (saving || uploading || !ready) && styles.createMemoDoneButtonDisabled]}- >- {saving ? <ActivityIndicator color="#64748b" size="small" /> : <Text style={[styles.createMemoDoneText, (uploading || !ready) && styles.createMemoDoneTextDisabled]}>完成</Text>}- </Pressable>- </View>- </View>-- {memo && baseUrl ? (- <View style={styles.richEditorContainer}>- <TextInput- onChangeText={(value) => {- setTitle(value);- dirtyRef.current = true;- setDirty(true);- }}- placeholder={DEFAULT_MEMO_TITLE}- placeholderTextColor="#94a3b8"- style={styles.createMemoTitleInput}- value={title}- />- <View style={[styles.createMemoMetaRow, styles.richStandaloneMetaRow]}>- <Pressable accessibilityLabel="所在笔记本" accessibilityRole="button" onPress={() => setNotebookPickerOpen(true)} style={styles.createMemoNotebookButton}>- <Text numberOfLines={1} style={styles.createMemoNotebookText}>{notebookLabel}</Text>- <ChevronDown color="#64748b" size={14} />- </Pressable>- <Pressable accessibilityLabel="选择笔记标签" accessibilityRole="button" onPress={() => setTagPickerOpen(true)} style={[styles.createMemoTagsButton, styles.richStandaloneTagsInput]}>- <Text numberOfLines={1} style={[styles.createMemoTagsInput, !tagsText && styles.createMemoTagsPlaceholder]}>- {tagsText || "添加标签"}- </Text>- <ChevronDown color="#94a3b8" size={14} />- </Pressable>- <SmartTagButton- client={client}- contentMarkdown={contentMarkdownRef.current}- disabled={saving || uploading}- onChange={(nextTags) => {- setTagsText(nextTags.join(", "));- dirtyRef.current = true;- setDirty(true);- }}- selectedTags={parseTags(tagsText)}- title={title}- />- </View>- {draftRestored ? <Text style={styles.richEditorDraftNotice}>已恢复上次未完成的本地草稿</Text> : null}- <View style={styles.richEditorFrame}>- {editorElement}- {!ready ? <MobileEditorStartupOverlay onRetry={retryEditorStartup} timedOut={editorStartup.timedOut} /> : null}- </View>- {error ? <Text style={styles.richEditorInlineError}>{error}</Text> : null}- {startupMs !== null && __DEV__ ? <Text style={styles.richEditorPerf}>本地编辑器启动:{startupMs}ms</Text> : null}- </View>- ) : (- <View style={styles.centerState}>- <Text style={styles.errorText}>缺少笔记数据,无法打开富文本编辑器</Text>- </View>- )}- <NotebookPickerModal- activeNotebookId={notebookId}- notebooks={notebooks}- onClose={() => setNotebookPickerOpen(false)}- onSelect={(nextNotebookId) => {- setNotebookId(nextNotebookId);- setNotebookPickerOpen(false);- dirtyRef.current = true;- setDirty(true);- }}- visible={notebookPickerOpen}- />- <TagPickerModal- dataScope={createMobileDataScope(session?.baseUrl ?? baseUrl, session?.user?.id)}- onChange={(nextTags) => {- setTagsText(nextTags.join(", "));- dirtyRef.current = true;- setDirty(true);- }}- onClose={() => setTagPickerOpen(false)}- selectedTags={parseTags(tagsText)}- visible={tagPickerOpen}- />- <MobileResourceActions- canMutate={Boolean(memo && !memo.id.startsWith("local:"))}- onClose={() => setResourceTarget(null)}- onDelete={deleteResource}- onDownload={downloadResource}- onRename={renameResource}- onSaveAs={saveResourceAs}- target={resourceTarget}- />- {uploadSourcePicker}- </KeyboardAvoidingView>- </SafeAreaView>- );-};--const MoveSelectionModal = ({- bottomOffset,- isMoving,- notebooks,- onClose,- onMove,- selectedCount,- selectedNotebookId,- visible,-}: {- bottomOffset: number;- isMoving: boolean;- notebooks: Notebook[];- onClose: () => void;- onMove: (notebookId: string) => void;- selectedCount: number;- selectedNotebookId: string;- visible: boolean;-}) => {- const [searchText, setSearchText] = useState("");- const notebookOptions = flattenNotebooks(notebooks);- const selectedScroll = useAutoCenterSelectedScrollRow(visible, selectedNotebookId);-- useEffect(() => {- if (visible) {- setSearchText("");- }- }, [visible]);-- return (- <Modal animationType="fade" onRequestClose={onClose} transparent visible={visible}>- <Pressable onPress={onClose} style={[styles.actionSheetBackdrop, { paddingBottom: bottomOffset }]}>- <Pressable style={[styles.listActionSheet, styles.moveSelectionSheet]}>- <View style={styles.actionSheetHandle} />- <View style={styles.listActionSheetHeader}>- <View style={styles.listActionSheetHeaderText}>- <Text style={styles.actionSheetTitle}>移动到笔记本</Text>- <Text style={styles.actionSheetSubtitle}>{selectedCount > 0 ? `已选择 ${selectedCount} 条` : "选择笔记"}</Text>- </View>- <Pressable accessibilityLabel="关闭" accessibilityRole="button" onPress={onClose} style={styles.sheetCloseButton}>- <X color="#0f172a" size={18} />- </Pressable>- </View>- <View style={styles.moveSelectionSearch}>- <View style={styles.searchBox}>- <Search color="#64748b" size={18} />- <TextInput- autoCapitalize="none"- autoCorrect={false}- onChangeText={setSearchText}- placeholder="搜索笔记本"- placeholderTextColor="#94a3b8"- style={styles.searchInput}- value={searchText}- />- {searchText ? (- <Pressable onPress={() => setSearchText("")}>- <X color="#64748b" size={18} />- </Pressable>- ) : null}- </View>- </View>- <ScrollView- contentContainerStyle={styles.moveSelectionList}- onLayout={selectedScroll.onViewportLayout}- ref={selectedScroll.scrollRef}- style={styles.listActionSheetScroll}- >- <NotebookTreeOptionRows- collapsible={false}- compact- disabled={isMoving}- emptyIconSize={28}- notebooks={notebooks}- onSelect={onMove}- options={notebookOptions}- searchText={searchText}- showDepthPrefix={false}- showMemoCount={false}- selectedNotebookId={selectedNotebookId}- onRowLayout={selectedScroll.onRowLayout}- />- {isMoving ? <ActivityIndicator color="#0f172a" style={styles.listLoadingFooter} /> : null}- </ScrollView>- </Pressable>- </Pressable>- </Modal>- );-};--const NotebookParentSelector = ({- currentParentId,- onChange,- options,-}: {- currentParentId: string | null;- onChange: (parentId: string | null) => void;- options: NotebookOption[];-}) => (- <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.parentSelectList}>- <OptionPill active={currentParentId === null} label="顶层" onPress={() => onChange(null)} />- {options.map(({ depth, notebook }) => (- <OptionPill- active={currentParentId === notebook.id}- key={notebook.id}- label={`${" ".repeat(depth)}${depth > 0 ? "└ " : ""}${notebook.name}`}- onPress={() => onChange(notebook.id)}- />- ))}- </ScrollView>-);--const NotebookTreeOptionRows = ({- collapsible = true,- compact = false,- disabled = false,- emptyIconSize,- notebooks,- onRowLayout,- onSelect,- options,- searchText,- selectedNotebookId,- showDepthPrefix = true,- showMemoCount = true,-}: {- collapsible?: boolean;- compact?: boolean;- disabled?: boolean;- emptyIconSize: number;- notebooks: Notebook[];- onRowLayout?: (notebookId: string, event: LayoutChangeEvent) => void;- onSelect: (notebookId: string) => void;- options: NotebookOption[];- searchText: string;- selectedNotebookId: string;- showDepthPrefix?: boolean;- showMemoCount?: boolean;-}) => {- const [collapsedNotebookIds, setCollapsedNotebookIds] = useState<Set<string>>(() => new Set());- const searchQuery = searchText.trim();- const childNotebookIds = getNotebookParentIdSet(notebooks);- const visibleNotebookOptions = searchQuery- ? filterNotebookOptions(options, searchText)- : filterCollapsedNotebookOptions(options, collapsedNotebookIds);-- const toggleNotebookCollapsed = (notebookId: string) => {- setCollapsedNotebookIds((current) => {- const next = new Set(current);-- if (next.has(notebookId)) {- next.delete(notebookId);- } else {- next.add(notebookId);- }-- return next;- });- };-- if (visibleNotebookOptions.length === 0) {- return (- <View style={styles.emptyInlinePanel}>- <Folder color="#94a3b8" size={emptyIconSize} />- <Text style={styles.mutedText}>没有匹配的笔记本</Text>- </View>- );- }-- return (- <View style={[styles.notebookTreeRows, compact && styles.notebookTreeRowsCompact]}>- {visibleNotebookOptions.map(({ depth, notebook }) => (- <View- key={notebook.id}- onLayout={onRowLayout ? (event) => onRowLayout(notebook.id, event) : undefined}- style={[- styles.moveNotebookRow,- compact && styles.moveNotebookRowCompact,- selectedNotebookId === notebook.id && styles.moveNotebookRowActive,- compact && selectedNotebookId === notebook.id && styles.moveNotebookRowCompactActive,- depth > 0 && { marginLeft: Math.min(depth * 14, 42) },- ]}- >- {collapsible && childNotebookIds.has(notebook.id) && !searchQuery ? (- <Pressable accessibilityRole="button" onPress={() => toggleNotebookCollapsed(notebook.id)} style={styles.notebookTreeToggle}>- {collapsedNotebookIds.has(notebook.id) ? <ChevronRight color="#64748b" size={17} /> : <ChevronDown color="#64748b" size={17} />}- </Pressable>- ) : !collapsible ? (- <View style={styles.notebookTreeTogglePlaceholder}>- <Folder color={selectedNotebookId === notebook.id ? "#059669" : "#64748b"} size={17} />- </View>- ) : (- <View style={styles.notebookTreeTogglePlaceholder} />- )}- <Pressable disabled={disabled} onPress={() => onSelect(notebook.id)} style={[styles.moveNotebookSelectArea, disabled && styles.buttonDisabled]}>- <Text numberOfLines={1} style={[styles.panelValue, compact && selectedNotebookId === notebook.id && styles.moveNotebookTextCompactActive]}>- {showDepthPrefix && depth > 0 ? `${"· ".repeat(depth)}${notebook.name}` : notebook.name}- </Text>- {showMemoCount ? <Text style={styles.panelLabel}>{notebook.memoCount} 条笔记</Text> : null}- </Pressable>- {selectedNotebookId === notebook.id ? <Check color={compact ? "#059669" : "#0f172a"} size={18} /> : null}- </View>- ))}- </View>- );-};--const NotebookPicker = ({- notebooks,- onChange,- selectedNotebookId,-}: {- notebooks: Notebook[];- onChange: (notebookId: string) => void;- selectedNotebookId: string;-}) => {- const [searchText, setSearchText] = useState("");- const notebookOptions = flattenNotebooks(notebooks);-- return (- <View style={styles.notebookPicker}>- <View style={styles.searchBox}>- <Search color="#64748b" size={18} />- <TextInput- autoCapitalize="none"- autoCorrect={false}- onChangeText={setSearchText}- placeholder="搜索笔记本"- placeholderTextColor="#94a3b8"- style={styles.searchInput}- value={searchText}- />- {searchText ? (- <Pressable onPress={() => setSearchText("")}>- <X color="#64748b" size={18} />- </Pressable>- ) : null}- </View>- <NotebookTreeOptionRows- emptyIconSize={24}- notebooks={notebooks}- onSelect={onChange}- options={notebookOptions}- searchText={searchText}- selectedNotebookId={selectedNotebookId}- />- </View>- );-};--const OptionPill = ({ active, label, onPress }: { active: boolean; label: string; onPress: () => void }) => (- <Pressable accessibilityRole="button" accessibilityState={{ selected: active }} onPress={onPress} style={[styles.optionPill, active && styles.optionPillActive]}>- <Text style={[styles.optionPillText, active && styles.optionPillTextActive]}>{label}</Text>- </Pressable>-);--const PanelRow = ({ label, value }: { label: string; value: string }) => (- <View style={styles.panelRow}>- <Text style={styles.panelLabel}>{label}</Text>- <Text selectable style={styles.panelValue}>- {value}- </Text>- </View>-);--const IconButton = ({ accessibilityLabel, children, disabled = false, onPress }: { accessibilityLabel?: string; children: ReactNode; disabled?: boolean; onPress: () => void }) => (- <Pressable accessibilityLabel={accessibilityLabel} accessibilityRole="button" disabled={disabled} onPress={onPress} style={[styles.iconButton, disabled && styles.buttonDisabled]}>- {children}- </Pressable>-);--const ActionButton = ({- children,- danger = false,- disabled = false,- label,- onPress,-}: {- children: ReactNode;- danger?: boolean;- disabled?: boolean;- label: string;- onPress: () => void;-}) => (- <Pressable disabled={disabled} onPress={onPress} style={[styles.actionButton, danger && styles.actionButtonDanger, disabled && styles.buttonDisabled]}>- {children}- <Text style={[styles.actionButtonText, danger && styles.actionButtonTextDanger]}>{label}</Text>- </Pressable>-);-const BottomNavItem = ({ active = false, badge = false, icon, label, onPress }: { active?: boolean; badge?: boolean; icon: ReactNode; label: string; onPress: () => void }) => (<PressableaccessibilityLabel={badge ? `${label},发现新版本` : label}@@ -3610,46 +1453,3 @@ const BottomNavItem = ({ active = false, badge = false, icon, label, onPress }:<Text style={[styles.bottomNavText, active && styles.bottomNavTextActive]}>{label}</Text></Pressable>);--const CreateMemoToolbarButton = ({- accessibilityLabel,- icon,- onPress,-}: {- accessibilityLabel: string;- icon: ReactNode;- onPress: () => void;-}) => (- <Pressable- accessibilityLabel={accessibilityLabel}- accessibilityRole="button"- onPress={onPress}- style={({ pressed }) => [styles.createMemoToolButton, pressed && styles.createMemoToolButtonPressed]}- >- {icon}- </Pressable>-);--const createMobileImageUploadId = () =>- `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;--const createLocalImagePreviewDataUrl = async (asset: { mimeType?: string | null; uri: string }) => {- const file = new ExpoFile(asset.uri);- const mimeType = asset.mimeType || file.type || "application/octet-stream";- return `data:${mimeType};base64,${await file.base64()}`;-};--const appendResourceMarkdown = (- currentMarkdown: string,- resource: {- filename: string;- kind: "image" | "attachment";- url: string;- }-) => {- const label = resource.filename.replace(/\]/g, "\\]");- const markdown = resource.kind === "image" ? `` : `附件:[${label}](${resource.url})`;- const trimmed = currentMarkdown.trimEnd();-- return trimmed ? `${trimmed}\n\n${markdown}\n` : `${markdown}\n`;-};diff --git a/apps/web/package.json b/apps/web/package.jsonindex 0e76fd33..cb20c671 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -4,6 +4,7 @@"private": true,"type": "module","dependencies": {+ "@edgeever/client": "workspace:*","@codemirror/lang-markdown": "^6.5.2","@fontsource-variable/noto-sans-sc": "^5.2.8","@tiptap/extension-code-block-lowlight": "3.27.1",diff --git a/apps/web/src/components/EditorOutline.tsx b/apps/web/src/components/EditorOutline.tsxindex 8a037f49..f92dcb63 100644--- a/apps/web/src/components/EditorOutline.tsx+++ b/apps/web/src/components/EditorOutline.tsx@@ -205,8 +205,8 @@ export const EditorOutline = ({ editor, scrollContainer, collapsed, shortcutLabeclassName={cn("group flex min-h-8 items-center rounded-[6px] pr-2 text-[13px] leading-5 transition-colors duration-150",isActive- ? "bg-slate-100 text-[#262626]"- : "text-[#3f3f3f] hover:bg-slate-50/70 hover:text-[#262626]"+ ? "bg-slate-100 text-slate-900"+ : "text-slate-700 hover:bg-slate-50/70 hover:text-slate-900")}style={{marginLeft: `${depth * -24}px`,@@ -285,7 +285,7 @@ export const EditorOutline = ({ editor, scrollContainer, collapsed, shortcutLabe<buttontype="button"className={cn(- "group flex items-center text-left text-[11px] font-bold uppercase tracking-wider text-slate-400 transition-colors hover:text-slate-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-500/60",+ "group flex items-center text-left text-[11px] font-bold uppercase tracking-wider text-slate-500 transition-colors hover:text-slate-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-500/60",collapsed ? "h-7 w-7 justify-center rounded-md hover:bg-slate-100" : "gap-1.5 rounded-sm")}onClick={() => onCollapsedChange(!collapsed)}diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsxindex 05baeecc..64e2d2b7 100644--- a/apps/web/src/components/EditorPane.tsx+++ b/apps/web/src/components/EditorPane.tsx@@ -1,5 +1,4 @@import { useRef, useState, useEffect, useCallback, useMemo, lazy, Suspense, type CSSProperties, type FocusEvent as ReactFocusEvent, type MouseEvent as ReactMouseEvent, type ReactNode } from "react";-import { createPortal } from "react-dom";import { useQuery, useQueryClient, useMutation } from "@tanstack/react-query";import { useEditor, EditorContent, type Editor } from "@tiptap/react";import { BubbleMenu } from "@tiptap/react/menus";@@ -47,20 +46,6 @@ import { Button } from "@/components/ui/button";import { GitHubRepositoryLink } from "@/components/GitHubRepositoryLink";import { ClipboardCopyNotice } from "@/components/ClipboardCopyNotice";import { Input } from "@/components/ui/input";-import {- Command,- CommandEmpty,- CommandGroup,- CommandInput,- CommandItem,- CommandList,-} from "@/components/ui/command";-import {- Drawer,- DrawerContent,- DrawerHeader,- DrawerTitle,-} from "@/components/ui/drawer";import {DropdownMenu,DropdownMenuContent,@@ -70,14 +55,6 @@ import {} from "@/components/ui/dropdown-menu";import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from "@/components/ui/select";import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from "@/components/ui/dialog";import { EditorToolbar } from "./EditorToolbar";import { EditorOutline } from "./EditorOutline";import { EditorTagPicker } from "./EditorTagPicker";@@ -227,17 +204,21 @@ import {import { ImageViewer } from "./editor/ImageViewer";import { PdfAttachment } from "./editor/PdfAttachment";import { FileAttachment } from "./editor/FileAttachment";-import {- createNoteSearchHighlightPlugin,- formatNoteSearchMatchLabel,- getNextSearchMatchIndex,- getSearchNavigationIdentity,- getSearchMatchesFromDocument,- NOTE_SEARCH_HIGHLIGHT_PLUGIN_KEY,- type NoteSearchMatch,-} from "./editor/note-search";import { getEditorScrollProgress, restoreEditorScrollProgress } from "./editor/editor-mode-scroll";import { useEditorSaveStatus } from "./editor/useEditorSaveStatus";+import { useEditorNoteSearchController } from "./editor/useEditorNoteSearchController";+import { EditorNoteLinkPicker } from "./editor/EditorNoteLinkPicker";+import { EditorResourceDialogs } from "./editor/EditorResourceDialogs";+import { EditorNoteSearchBar } from "./editor/EditorNoteSearchBar";+import { EditorSaveRecoveryBanner } from "./editor/EditorSaveRecoveryBanner";+import {+ EmptyEditorHeader,+ IconTooltip,+ MobileNotebookSelectSheet,+ NoteLinkInteractionHint,+ ResourceActionMenu,+ type NoteLinkHintPosition,+} from "./editor/EditorPaneChrome";import { resolveEditorDraftState } from "./editor/editor-draft-state";import type { EdgeEverPluginHost, PluginEditorAdapter } from "@/lib/plugins/plugin-host";import {@@ -264,27 +245,6 @@ const requiresLocalEditSession = (memo: MemoDetail) =>isLocalMemoId(memo.id) ||isBrowserOffline();-const IconTooltip = ({ label, children }: { label: string; children: ReactNode }) => (- <TooltipProvider delayDuration={0} skipDelayDuration={0}>- <Tooltip>- <TooltipTrigger asChild>{children}</TooltipTrigger>- <TooltipContent side="bottom">{label}</TooltipContent>- </Tooltip>- </TooltipProvider>-);--const EmptyEditorHeader = () => (- <header className="hidden h-12 shrink-0 items-center justify-end gap-1 border-b border-slate-100 px-5 lg:flex">- <ThemeToggle />- </header>-);--type NoteLinkHintPosition = {- left: number;- top: number;- placement: "above" | "below" | "inside-bottom-right";-};-type AiSelectionContext = {kind: "markdown" | "plain";from: number;@@ -340,102 +300,6 @@ const getNoteLinkHintPosition = (link: HTMLAnchorElement): NoteLinkHintPosition};};-const NoteLinkInteractionHint = ({- label,- position,-}: {- label: string;- position: NoteLinkHintPosition;-}) => createPortal(- <div- role="tooltip"- className="pointer-events-none fixed z-[100] whitespace-nowrap rounded-md bg-slate-950 px-2.5 py-1.5 text-xs font-medium text-white shadow-md"- style={{- left: position.left,- top: position.top,- transform: position.placement === "above" ? "translate(-50%, -100%)" : "translateX(-50%)",- }}- >- {label}- </div>,- document.body-);--const ResourceActionMenu = ({- target,- canRename,- canDelete,- labels,- onDownload,- onSaveAs,- onRename,- onDelete,- onMouseEnter,- onMouseLeave,-}: {- target: ResourceMenuTarget;- canRename: boolean;- canDelete: boolean;- labels: { download: string; saveAs: string; rename: string; delete: string; unavailable: string };- onDownload: () => void;- onSaveAs: () => void;- onRename: () => void;- onDelete: () => void;- onMouseEnter: () => void;- onMouseLeave: () => void;-}) => createPortal(- <div- data-edgeever-resource-menu- role="toolbar"- aria-label={labels.download}- className="fixed z-[110] flex items-center gap-1 rounded-lg border border-slate-200 bg-white p-1 shadow-lg"- style={{- left: target.position.left,- top: target.position.top,- transform: target.position.placement === "inside-bottom-right"- ? "translate(-100%, -100%)"- : target.position.placement === "above"- ? "translate(-50%, -100%)"- : "translateX(-50%)",- }}- onMouseEnter={onMouseEnter}- onMouseLeave={onMouseLeave}- >- <Button type="button" size="sm" variant="ghost" title={labels.download} onClick={onDownload}>- <FileDown className="h-3.5 w-3.5" />- {labels.download}- </Button>- <Button type="button" size="sm" variant="ghost" title={labels.saveAs} onClick={onSaveAs}>- <Save className="h-3.5 w-3.5" />- {labels.saveAs}- </Button>- <Button- type="button"- size="sm"- variant="ghost"- title={canRename ? labels.rename : labels.unavailable}- disabled={!canRename}- onClick={onRename}- >- <Pencil className="h-3.5 w-3.5" />- {labels.rename}- </Button>- <Button- type="button"- size="sm"- variant="ghost"- className="text-slate-600 hover:bg-rose-50 hover:text-rose-600"- title={canDelete ? labels.delete : labels.unavailable}- disabled={!canDelete}- onClick={onDelete}- >- <Trash2 className="h-3.5 w-3.5" />- {labels.delete}- </Button>- </div>,- document.body-);-const findAttachmentLinkRange = (editor: Editor,href: string@@ -457,43 +321,11 @@ const findAttachmentLinkRange = (return { from: from as number, to: to as number, marks };};-type MobileImeDebugEntry = {- id: number;- event: string;- activeElement: string;- inputType?: string;- isComposing?: boolean;- key?: string;- valueLength: number;- time: string;-};-type MobilePlainTextElement = HTMLTextAreaElement | HTMLDivElement;const isEditorReady = (editor: Editor | null | undefined): editor is Editor =>Boolean(editor && !editor.isDestroyed && (editor as { extensionManager?: unknown }).extensionManager);-const getActiveElementLabel = () => {- if (typeof document === "undefined") {- return "document unavailable";- }-- const element = document.activeElement;- if (!element) {- return "none";- }-- const tag = element.tagName.toLowerCase();- const id = element.id ? `#${element.id}` : "";- const className =- element instanceof HTMLElement && element.className- ? `.${String(element.className).trim().split(/\s+/).slice(0, 2).join(".")}`- : "";- const role = element.getAttribute("role");-- return `${tag}${id}${className}${role ? `[role=${role}]` : ""}`;-};-const getMobilePlainTextElementValue = (element: MobilePlainTextElement | null) => {if (!element) {return "";@@ -541,14 +373,6 @@ const focusMobilePlainTextElement = (element: MobilePlainTextElement | null) =>selection?.addRange(range);};-const getEditorSearchMatches = (editor: Editor | null, query: string): NoteSearchMatch[] => {- if (!isEditorReady(editor)) {- return [];- }-- return getSearchMatchesFromDocument(editor.state.doc, query);-};-const getResourceFilesFromDataTransfer = (dataTransfer: DataTransfer | null) => {if (!dataTransfer) {return [];@@ -587,77 +411,6 @@ class MemoSaveRequestError extends Error {}}-const MobileNotebookSelectSheet = ({- isUpdating,- options,- selectedNotebookId,- onClose,- onSelect,-}: {- isUpdating: boolean;- options: any[];- selectedNotebookId: string;- onClose: () => void;- onSelect: (notebookId: string) => void;-}) => {- const { t } = useTranslation();- const listRef = useRef<HTMLDivElement | null>(null);-- useEffect(() => {- window.setTimeout(() => {- const selectedNode = listRef.current?.querySelector<HTMLElement>(- `[data-mobile-notebook-select-id="${CSS.escape(selectedNotebookId)}"]`- );- selectedNode?.scrollIntoView({ block: "center" });- }, 0);- }, [selectedNotebookId]);-- return (- <Drawer open={true} onOpenChange={(open) => { if (!open) onClose(); }}>- <DrawerContent className="inset-x-0 max-h-[62dvh] overflow-hidden border-x-0 border-b-0 pb-[env(safe-area-inset-bottom)] lg:hidden">- <header className="flex h-12 items-center justify-between border-b border-slate-200 px-4">- <DrawerHeader className="min-w-0 p-0">- <DrawerTitle className="text-base">{t("editor.currentNotebook")}</DrawerTitle>- </DrawerHeader>- <Button size="icon" variant="ghost" title={t("editor.close")} aria-label={t("editor.close")} onClick={onClose}>- <X className="h-4 w-4" />- </Button>- </header>- <Command className="min-h-0 flex-1">- <CommandInput placeholder={t("editor.searchNotebook")} />- <CommandList ref={listRef} className="max-h-[calc(62dvh-6.25rem-env(safe-area-inset-bottom))] p-2">- <CommandEmpty>{t("editor.noNotebookFound")}</CommandEmpty>- <CommandGroup>- {options.map((option) => {- const selected = option.id === selectedNotebookId;- return (- <CommandItem- key={option.id}- className={cn(- "h-12 px-3 text-base",- selected ? "bg-emerald-50 font-semibold text-emerald-700 data-[selected=true]:bg-emerald-50" : "text-slate-700"- )}- style={{ paddingLeft: `${12 + option.depth * 18}px` }}- value={option.id}- keywords={[option.name, option.selectLabel, option.slug ?? ""]}- data-mobile-notebook-select-id={option.id}- aria-label={selected ? t("editor.currentNotebookAria", { name: option.name }) : t("editor.switchToNotebook", { name: option.name })}- aria-current={selected ? "page" : undefined}- disabled={isUpdating}- onSelect={() => onSelect(option.id)}- >- <span className="min-w-0 flex-1 truncate">{option.name}</span>- </CommandItem>- );- })}- </CommandGroup>- </CommandList>- </Command>- </DrawerContent>- </Drawer>- );-};-type EditorPaneProps = {memo: MemoDetail | null;repository: EdgeEverRepository;@@ -858,10 +611,7 @@ const RichEditorPane = ({const [markdownSource, setMarkdownSource] = useState("");const [isMarkdownMode, setIsMarkdownMode] = useState(false);const [mobileToolbarOpen, setMobileToolbarOpen] = useState(false);- const [mobileImeDebugOpen, setMobileImeDebugOpen] = useState(false);const [editorOutlineCollapsed, setEditorOutlineCollapsed] = useState(false);- const [mobileImeDebugActiveElement, setMobileImeDebugActiveElement] = useState(getActiveElementLabel);- const [mobileImeDebugEvents, setMobileImeDebugEvents] = useState<MobileImeDebugEntry[]>([]);const [wechatCopyState, setWechatCopyState] = useState<"idle" | "copying" | "copied" | "error">("idle");const [memoIdCopyNotice, setMemoIdCopyNotice] = useState<{ status: "copied" | "error"; id: string } | null>(null);const handledSaveAndSyncTokenRef = useRef(saveAndSyncToken);@@ -962,13 +712,8 @@ const RichEditorPane = ({const mobileTextAreaRef = useRef<MobilePlainTextElement | null>(null);const mobileDraftTimerRef = useRef<number | null>(null);const mobileSaveTimerRef = useRef<number | null>(null);- const mobileImeDebugEventIdRef = useRef(0);- const mobileImeDebugRecorderRef = useRef<(eventName: string, event?: unknown) => void>(() => undefined);- const markMobilePlainTextDirtyRef = useRef<() => void>(() => undefined);const fileInputRef = useRef<HTMLInputElement | null>(null);const noteSearchInputRef = useRef<HTMLInputElement | null>(null);- const noteReplaceInputRef = useRef<HTMLInputElement | null>(null);- const noteSearchAutoSelectionRef = useRef<{ editor: Editor; identity: string } | null>(null);const markdownSourceEditorRef = useRef<MarkdownSourceEditorRef | null>(null);const openExternalLinkDialogRef = useRef<() => void>(() => undefined);const slashCommandLabelsRef = useRef<SlashCommandLabels>({@@ -1970,208 +1715,32 @@ const RichEditorPane = ({};}, [editor]);- const noteSearchMatches = useMemo(- () => getEditorSearchMatches(editor, noteSearchQuery),- [dirtyVersion, editor, memo?.id, noteSearchQuery]- );- const contentSearchMatches = useMemo(- () => getEditorSearchMatches(editor, contentSearchQuery),- [contentSearchQuery, dirtyVersion, editor, memo?.id]- );-- const selectNoteSearchMatch = useCallback(- (index: number, matches: NoteSearchMatch[]) => {- const match = matches[index];-- if (!isEditorReady(editor) || !match) {- return;- }-- // `setTextSelection` updates the ProseMirror selection but does not- // request the view to scroll to it. This is especially visible while- // the search input keeps focus, because the browser cannot scroll the- // editor selection for us in that case.- editor.chain().setTextSelection({ from: match.from, to: match.to }).scrollIntoView().run();-- window.requestAnimationFrame(() => {- const scrollContainer = editorScrollContainerRef.current;- const domPosition = editor.view.domAtPos(match.from);- const node = domPosition.node.nodeType === Node.TEXT_NODE- ? domPosition.node.parentElement- : domPosition.node instanceof Element- ? domPosition.node- : domPosition.node.parentElement;-- if (!scrollContainer || !node) {- return;- }-- const containerRect = scrollContainer.getBoundingClientRect();- const nodeRect = node.getBoundingClientRect();- const padding = 24;- const isAbove = nodeRect.top < containerRect.top + padding;- const isBelow = nodeRect.bottom > containerRect.bottom - padding;-- if (isAbove || isBelow) {- const targetTop = scrollContainer.scrollTop + nodeRect.top - containerRect.top- - (scrollContainer.clientHeight - nodeRect.height) / 2;- scrollContainer.scrollTo({ top: Math.max(0, targetTop), behavior: "smooth" });- }- });- },- [editor]- );-- useEffect(() => {- if (!isEditorReady(editor)) {- return;- }-- const searchHighlightPlugin = createNoteSearchHighlightPlugin({- getQuery: () => noteSearchOpen ? noteSearchQuery : contentSearchQuery,- getActiveIndex: () => noteSearchOpen ? noteSearchIndex : 0,- });-- editor.registerPlugin(searchHighlightPlugin);-- return () => {- if (isEditorReady(editor)) {- editor.unregisterPlugin(NOTE_SEARCH_HIGHLIGHT_PLUGIN_KEY);- }- };- }, [contentSearchQuery, editor, noteSearchIndex, noteSearchOpen, noteSearchQuery]);-- const focusNoteSearchInput = useCallback(() => {- window.requestAnimationFrame(() => {- noteSearchInputRef.current?.focus();- noteSearchInputRef.current?.select();- });- }, []);-- const openNoteSearch = useCallback((showReplace = false) => {- setNoteSearchOpen(true);- setNoteSearchReplaceOpen(showReplace);- focusNoteSearchInput();- }, [focusNoteSearchInput]);-- const openNoteReplace = useCallback(() => {- if (effectiveReadOnly) return;- setNoteSearchOpen(true);- setNoteSearchReplaceOpen(true);- focusNoteSearchInput();- }, [effectiveReadOnly, focusNoteSearchInput]);-- const closeNoteSearch = useCallback(() => {- setNoteSearchOpen(false);- if (isEditorReady(editor)) {- editor.commands.focus();- }- }, [editor]);-- useEffect(() => {- if (!noteSearchOpen) {- return;- }-- const handleNoteSearchEscape = (event: KeyboardEvent) => {- if (event.key !== "Escape" || event.defaultPrevented) {- return;- }-- event.preventDefault();- event.stopPropagation();- closeNoteSearch();- };-- // Capture the event so Escape works even when focus has moved to the- // editor, toolbar, or another control outside the search inputs.- window.addEventListener("keydown", handleNoteSearchEscape, true);- return () => window.removeEventListener("keydown", handleNoteSearchEscape, true);- }, [closeNoteSearch, noteSearchOpen]);-- const moveNoteSearchMatch = useCallback(- (direction: 1 | -1) => {- if (noteSearchMatches.length === 0) {- return;- }-- setNoteSearchIndex((current) => {- const next = getNextSearchMatchIndex(current, direction, noteSearchMatches.length);- selectNoteSearchMatch(next, noteSearchMatches);- return next;- });- },- [noteSearchMatches, selectNoteSearchMatch]- );-- useEffect(() => {- if (searchFocusToken === 0) {- return;- }-- openNoteSearch();- }, [openNoteSearch, searchFocusToken]);-- useEffect(() => {- if (replaceFocusToken === 0) {- return;- }-- openNoteReplace();- }, [openNoteReplace, replaceFocusToken]);-- useEffect(() => {- if (!isEditorReady(editor)) {- return;- }-- const source = noteSearchOpen ? "note" : "content";- const query = noteSearchOpen ? noteSearchQuery : contentSearchQuery;- const matches = noteSearchOpen ? noteSearchMatches : contentSearchMatches;- const identity = getSearchNavigationIdentity(memo?.id ?? null, source, query);- const previousSelection = noteSearchAutoSelectionRef.current;-- // Match positions change after every document edit. Only a new search,- // note, or search source should move the editor selection automatically.- if (previousSelection?.editor === editor && previousSelection.identity === identity) {- return;- }-- noteSearchAutoSelectionRef.current = { editor, identity };- setNoteSearchIndex(0);-- if (matches[0]) {- selectNoteSearchMatch(0, matches);- }- }, [contentSearchMatches, contentSearchQuery, editor, memo?.id, noteSearchMatches, noteSearchOpen, noteSearchQuery, selectNoteSearchMatch]);-- useEffect(() => {- setNoteSearchIndex((current) => noteSearchMatches.length === 0- ? 0- : Math.min(current, noteSearchMatches.length - 1));- }, [noteSearchMatches.length]);-- const replaceAllNoteSearchMatches = useCallback(() => {- if (!isEditorReady(editor) || effectiveReadOnly || noteSearchMatches.length === 0) {- return;- }-- editor- .chain()- .focus()- .command(({ tr, dispatch }) => {- for (const match of [...noteSearchMatches].reverse()) {- tr.insertText(noteSearchReplacement, match.from, match.to);- }-- dispatch?.(tr);- return true;- })- .run();-- setNoteSearchIndex(0);- window.requestAnimationFrame(() => noteSearchInputRef.current?.focus());- }, [editor, effectiveReadOnly, noteSearchMatches, noteSearchReplacement]);+ const {+ closeSearch: closeNoteSearch,+ matchLabel: noteSearchMatchLabel,+ matches: noteSearchMatches,+ moveMatch: moveNoteSearchMatch,+ openReplace: openNoteReplace,+ openSearch: openNoteSearch,+ replaceAllMatches: replaceAllNoteSearchMatches,+ } = useEditorNoteSearchController({+ contentSearchQuery,+ dirtyVersion,+ editor,+ editorScrollContainerRef,+ memoId: memo?.id ?? null,+ noteSearchIndex,+ noteSearchInputRef,+ noteSearchOpen,+ noteSearchQuery,+ noteSearchReplacement,+ readOnly: effectiveReadOnly,+ replaceFocusToken,+ searchFocusToken,+ setNoteSearchIndex,+ setNoteSearchOpen,+ setNoteSearchReplaceOpen,+ });useEffect(() => {if (!isEditorReady(editor)) {@@ -2193,50 +1762,6 @@ const RichEditorPane = ({[mobilePlainText]);- const recordMobileImeDebugEvent = useCallback((eventName: string, event?: unknown) => {- const plainTextElement = mobileTextAreaRef.current;- const nativeEvent = event && typeof event === "object" && "nativeEvent" in event- ? (event as { nativeEvent?: unknown }).nativeEvent- : event;- const inputEvent = nativeEvent as Partial<InputEvent> | undefined;- const keyboardEvent = nativeEvent as Partial<KeyboardEvent> | undefined;-- mobileImeDebugEventIdRef.current += 1;- setMobileImeDebugActiveElement(getActiveElementLabel());- setMobileImeDebugEvents((current) =>- [- {- id: mobileImeDebugEventIdRef.current,- event: eventName,- activeElement: getActiveElementLabel(),- inputType: typeof inputEvent?.inputType === "string" ? inputEvent.inputType : undefined,- isComposing: typeof inputEvent?.isComposing === "boolean" ? inputEvent.isComposing : undefined,- key: typeof keyboardEvent?.key === "string" ? keyboardEvent.key : undefined,- valueLength: getMobilePlainTextElementValue(plainTextElement).length,- time: new Date().toLocaleTimeString("zh-CN", { hour12: false }),- },- ...current,- ].slice(0, 20)- );- }, []);-- useEffect(() => {- mobileImeDebugRecorderRef.current = recordMobileImeDebugEvent;- }, [recordMobileImeDebugEvent]);-- useEffect(() => {- if (!useMobilePlainTextEditor) {- return;- }-- recordMobileImeDebugEvent("mount-mobile-plain-editor");- const timer = window.setInterval(() => {- setMobileImeDebugActiveElement(getActiveElementLabel());- }, 800);-- return () => window.clearInterval(timer);- }, [recordMobileImeDebugEvent, useMobilePlainTextEditor]);-const persistCurrentDraft = useCallback((nextTitle = title, nextTagsText = tagsText, nextMobilePlainText = getMobilePlainTextValue()) => {const currentMemo = memoRef.current;@@ -3690,10 +3215,6 @@ const RichEditorPane = ({}, EDITOR_LOCAL_SAVE_DELAY_MS);}, [getMobilePlainTextValue, mutateSave, persistCurrentDraft, saveMutationPending, saveState, tagsText, title]);- useEffect(() => {- markMobilePlainTextDirtyRef.current = markMobilePlainTextDirty;- }, [markMobilePlainTextDirty]);-useEffect(() => {if (!useMobilePlainTextEditor) {return;@@ -3704,35 +3225,13 @@ const RichEditorPane = ({return;}- const recordNativeEvent = (event: Event) => {- mobileImeDebugRecorderRef.current(event.type, event);- };- const handleNativeInput = (event: Event) => {- mobileImeDebugRecorderRef.current(event.type, event);- markMobilePlainTextDirtyRef.current();- };-- plainTextElement.addEventListener("focus", recordNativeEvent);- plainTextElement.addEventListener("blur", recordNativeEvent);- plainTextElement.addEventListener("click", recordNativeEvent);- plainTextElement.addEventListener("beforeinput", recordNativeEvent);- plainTextElement.addEventListener("compositionstart", recordNativeEvent);- plainTextElement.addEventListener("compositionupdate", recordNativeEvent);- plainTextElement.addEventListener("compositionend", recordNativeEvent);+ const handleNativeInput = () => markMobilePlainTextDirty();plainTextElement.addEventListener("input", handleNativeInput);- mobileImeDebugRecorderRef.current("native-listeners-ready");return () => {- plainTextElement.removeEventListener("focus", recordNativeEvent);- plainTextElement.removeEventListener("blur", recordNativeEvent);- plainTextElement.removeEventListener("click", recordNativeEvent);- plainTextElement.removeEventListener("beforeinput", recordNativeEvent);- plainTextElement.removeEventListener("compositionstart", recordNativeEvent);- plainTextElement.removeEventListener("compositionupdate", recordNativeEvent);- plainTextElement.removeEventListener("compositionend", recordNativeEvent);plainTextElement.removeEventListener("input", handleNativeInput);};- }, [useMobilePlainTextEditor]);+ }, [markMobilePlainTextDirty, useMobilePlainTextEditor]);useEffect(() => () => clearMobileEditorTimers(), [clearMobileEditorTimers]);@@ -3980,38 +3479,12 @@ const RichEditorPane = ({notebookUpdatePending ||imageUploadState === "compressing" ||imageUploadState === "uploading";- const noteSearchMatchLabel = formatNoteSearchMatchLabel(- noteSearchQuery,- noteSearchIndex,- noteSearchMatches.length,- );- const mobileImeDebugEditorFocused =- typeof document !== "undefined" && mobileTextAreaRef.current === document.activeElement;- const mobileImeDebugLogText = [- `memoId=${memo.id}`,- `mobile=${isMobileViewport}`,- `editingState=${isMobileEditing}`,- `editingActive=${mobileEditingActive}`,- `plainTextEditor=${useMobilePlainTextEditor}`,- `editorFocused=${mobileImeDebugEditorFocused}`,- `activeElement=${mobileImeDebugActiveElement}`,- `valueLength=${getMobilePlainTextValue().length}`,- `saveState=${saveState}`,- ...mobileImeDebugEvents.map((entry) =>- `${entry.time} ${entry.event} active=${entry.activeElement} len=${entry.valueLength}` +- `${entry.inputType ? ` inputType=${entry.inputType}` : ""}` +- `${entry.isComposing !== undefined ? ` composing=${entry.isComposing}` : ""}` +- `${entry.key ? ` key=${entry.key}` : ""}`- ),- ].join("\n");-- const appendMobilePlainText = (nextText: string, eventName: string) => {+ const appendMobilePlainText = (nextText: string) => {const currentText = getMobilePlainTextValue();const nextValue = `${currentText}${currentText ? "\n" : ""}${nextText}`;setMobilePlainText(nextValue);setMobilePlainTextElementValue(mobileTextAreaRef.current, nextValue);markMobilePlainTextDirty();- recordMobileImeDebugEvent(eventName);window.requestAnimationFrame(() => focusMobileInputTarget());};@@ -4022,21 +3495,19 @@ const RichEditorPane = ({return;}- appendMobilePlainText(nextText, "prompt-input");+ appendMobilePlainText(nextText);};const handleMobileClipboardInput = async () => {try {const nextText = await navigator.clipboard?.readText();if (!nextText?.trim()) {- recordMobileImeDebugEvent("clipboard-empty");focusMobileInputTarget();return;}- appendMobilePlainText(nextText, "clipboard-input");+ appendMobilePlainText(nextText);} catch {- recordMobileImeDebugEvent("clipboard-error");window.alert(t("editor.clipboardReadFailed"));focusMobileInputTarget();}@@ -4164,51 +3635,15 @@ const RichEditorPane = ({onRemove={removeExternalLink}/>{noteLinkPickerOpen && (- <div className="absolute left-3 right-3 top-14 z-30 h-[min(22rem,calc(100%-4rem))] max-w-xl rounded-lg border border-slate-200 bg-white shadow-xl sm:left-5 sm:right-auto sm:w-[28rem]" role="dialog" aria-label={t("noteLinkPicker.title")}>- <Command shouldFilter={false}>- <div className="flex items-center justify-between border-b border-slate-100 pr-2">- <CommandInput- autoFocus- value={noteLinkQuery}- placeholder={t("noteLinkPicker.searchPlaceholder")}- onValueChange={setNoteLinkQuery}- onKeyDown={(event) => {- if (event.key === "Escape") {- setNoteLinkPickerOpen(false);- }- }}- />- <button- type="button"- className="rounded-md p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-700"- aria-label={t("noteLinkPicker.close")}- onClick={() => setNoteLinkPickerOpen(false)}- >- <X className="h-4 w-4" />- </button>- </div>- <CommandList>- {noteLinkResultsQuery.isLoading ? (- <div className="p-6 text-center text-sm text-slate-500">{t("noteLinkPicker.loading")}</div>- ) : (- <>- <CommandEmpty>{t("noteLinkPicker.empty")}</CommandEmpty>- <CommandGroup>- {(noteLinkResultsQuery.data?.memos ?? [])- .filter((candidate) => candidate.id !== memo?.id && !candidate.isDeleted)- .map((candidate) => (- <CommandItem key={candidate.id} value={candidate.id} onSelect={() => insertMemoLink(candidate)}>- <Link2 className="h-4 w-4 shrink-0 text-emerald-600" />- <span className="min-w-0 flex-1 truncate">{candidate.title || t("common.untitledMemo")}</span>- <span className="max-w-40 truncate text-xs text-slate-400">{candidate.excerpt}</span>- </CommandItem>- ))}- </CommandGroup>- </>- )}- </CommandList>- </Command>- </div>+ <EditorNoteLinkPicker+ query={noteLinkQuery}+ isLoading={noteLinkResultsQuery.isLoading}+ memos={noteLinkResultsQuery.data?.memos ?? []}+ currentMemoId={memo.id}+ onQueryChange={setNoteLinkQuery}+ onClose={() => setNoteLinkPickerOpen(false)}+ onInsert={insertMemoLink}+ />)}<header className="shrink-0 border-b border-slate-200 bg-white"><div className="flex min-h-12 items-center justify-between gap-2 border-b border-slate-100 px-3 py-2 sm:px-5">@@ -4684,95 +4119,22 @@ const RichEditorPane = ({)}</div></div>- {noteSearchOpen && (- <div className="flex flex-wrap items-center gap-2 border-t border-slate-100 px-4 py-2 sm:px-7">- <Search className="h-4 w-4 shrink-0 text-slate-400" />- <Input- ref={noteSearchInputRef}- value={noteSearchQuery}- className="h-8 min-w-[12rem] flex-1"- placeholder={t("editor.searchPlaceholder")}- onChange={(event) => setNoteSearchQuery(event.target.value)}- onKeyDown={(event) => {- if (event.key === "Enter") {- event.preventDefault();- moveNoteSearchMatch(event.shiftKey ? -1 : 1);- }-- if (event.key === "Escape") {- event.preventDefault();- closeNoteSearch();- }- }}- />- {noteSearchReplaceOpen && (- <Input- ref={noteReplaceInputRef}- value={noteSearchReplacement}- className="h-8 min-w-[12rem] flex-1"- placeholder={t("editor.replacePlaceholder")}- disabled={effectiveReadOnly}- onChange={(event) => setNoteSearchReplacement(event.target.value)}- onKeyDown={(event) => {- if (event.key === "Enter") {- event.preventDefault();- replaceAllNoteSearchMatches();- }-- if (event.key === "Escape") {- event.preventDefault();- closeNoteSearch();- }- }}- />- )}- <span- className={cn(- "w-12 shrink-0 text-center text-xs tabular-nums",- noteSearchQuery.trim() && noteSearchMatches.length === 0 ? "text-rose-500" : "text-slate-500"- )}- aria-live="polite"- >- {noteSearchMatchLabel}- </span>- <Button- size="icon"- variant="ghost"- title={t("editor.previousSearchResult")}- aria-label={t("editor.previousSearchResult")}- disabled={noteSearchMatches.length === 0}- onClick={() => moveNoteSearchMatch(-1)}- >- <ChevronLeft className="h-4 w-4" />- </Button>- <Button- size="icon"- variant="ghost"- title={t("editor.nextSearchResult")}- aria-label={t("editor.nextSearchResult")}- disabled={noteSearchMatches.length === 0}- onClick={() => moveNoteSearchMatch(1)}- >- <ChevronRight className="h-4 w-4" />- </Button>- {noteSearchReplaceOpen && (- <Button- size="sm"- variant="solid"- title={t("editor.replaceAll")}- aria-label={t("editor.replaceAll")}- disabled={effectiveReadOnly || noteSearchMatches.length === 0}- onClick={replaceAllNoteSearchMatches}- >- <ReplaceAll className="h-4 w-4" />- {t("editor.replaceAll")}- </Button>- )}- <Button size="icon" variant="ghost" title={t("editor.closeSearch")} aria-label={t("editor.closeSearch")} onClick={closeNoteSearch}>- <X className="h-4 w-4" />- </Button>- </div>- )}+ {noteSearchOpen ? (+ <EditorNoteSearchBar+ inputRef={noteSearchInputRef}+ query={noteSearchQuery}+ replacement={noteSearchReplacement}+ replaceOpen={noteSearchReplaceOpen}+ readOnly={effectiveReadOnly}+ matchCount={noteSearchMatches.length}+ matchLabel={noteSearchMatchLabel}+ onQueryChange={setNoteSearchQuery}+ onReplacementChange={setNoteSearchReplacement}+ onMoveMatch={moveNoteSearchMatch}+ onReplaceAll={replaceAllNoteSearchMatches}+ onClose={closeNoteSearch}+ />+ ) : null}{(!isMobileViewport || (mobileToolbarOpen && !useMobilePlainTextEditor)) && (<EditorToolbareditor={editor}@@ -4786,80 +4148,17 @@ const RichEditorPane = ({onPickNoteLink={() => setNoteLinkPickerOpen(true)}/>)}- {saveState === "conflict" && saveConflictReason ? (- <div- 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"- >- <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}- {saveState === "error" && storageSaveError ? (- <div- 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"- >- <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">{t("editor.saveState.storageUnavailable")}</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={saveMutationPending}- onClick={() => mutateSave()}- >- {t("editor.saveState.storageRetry")}- </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}+ <EditorSaveRecoveryBanner+ saveState={saveState}+ conflictReason={saveConflictReason}+ storageSaveError={storageSaveError}+ savePending={saveMutationPending}+ actionPending={conflictActionPending}+ actionMessage={conflictActionMessage}+ onAdoptCloud={handleAdoptCloudAndReload}+ onCopyDraft={handleCopyLocalDraft}+ onRetry={mutateSave}+ /></header><div@@ -5102,82 +4401,17 @@ const RichEditorPane = ({/>)}- <Dialog- open={resourceDialog?.action === "rename"}- onOpenChange={(open) => {- if (!open) closeResourceDialog();- }}- >- <DialogContent>- <form- className="contents"- onSubmit={(event) => {- event.preventDefault();- void handleResourceRename();- }}- >- <DialogHeader>- <DialogTitle>{resourceDialogLabels.renameTitle}</DialogTitle>- <DialogDescription>{resourceDialogLabels.renameDescription}</DialogDescription>- </DialogHeader>- <label className="grid gap-2 text-sm font-medium text-slate-700">- {resourceDialogLabels.filenameLabel}- <Input- autoFocus- value={resourceFilename}- maxLength={160}- disabled={resourceActionPending}- onChange={(event) => setResourceFilename(event.target.value)}- />- </label>- {resourceActionError && (- <p className="text-sm text-rose-600" role="alert">{resourceActionError}</p>- )}- <DialogFooter>- <Button type="button" variant="ghost" disabled={resourceActionPending} onClick={closeResourceDialog}>- {t("common.cancel")}- </Button>- <Button type="submit" variant="solid" disabled={resourceActionPending || !resourceFilename.trim()}>- {resourceActionPending ? t("common.saving") : t("common.save")}- </Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>-- <Dialog- open={resourceDialog?.action === "delete"}- onOpenChange={(open) => {- if (!open) closeResourceDialog();- }}- >- <DialogContent>- <DialogHeader>- <DialogTitle>{resourceDialogLabels.deleteTitle}</DialogTitle>- <DialogDescription>{resourceDialogLabels.deleteDescription}</DialogDescription>- </DialogHeader>- <p className="truncate rounded-md bg-slate-50 px-3 py-2 text-sm font-medium text-slate-700">- {resourceDialog?.target.filename}- </p>- {resourceActionError && (- <p className="text-sm text-rose-600" role="alert">{resourceActionError}</p>- )}- <DialogFooter>- <Button type="button" variant="ghost" disabled={resourceActionPending} onClick={closeResourceDialog}>- {t("common.cancel")}- </Button>- <Button type="button" variant="danger" disabled={resourceActionPending} onClick={() => void handleResourceDelete()}>- {resourceActionPending ? t("common.processing") : t("common.delete")}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>-- {resourceActionError && !resourceDialog && (- <div className="fixed bottom-5 left-1/2 z-[120] -translate-x-1/2 rounded-md bg-rose-600 px-3 py-2 text-sm font-medium text-white shadow-lg" role="alert">- {resourceActionError}- </div>- )}+ <EditorResourceDialogs+ dialog={resourceDialog}+ labels={resourceDialogLabels}+ filename={resourceFilename}+ pending={resourceActionPending}+ error={resourceActionError}+ onFilenameChange={setResourceFilename}+ onClose={closeResourceDialog}+ onRename={handleResourceRename}+ onDelete={handleResourceDelete}+ />{memoIdCopyNotice && (<ClipboardCopyNotice status={memoIdCopyNotice.status}>@@ -5185,75 +4419,6 @@ const RichEditorPane = ({</ClipboardCopyNotice>)}- {false && useMobilePlainTextEditor && (- <div className="fixed left-2 right-2 top-[max(3.5rem,env(safe-area-inset-top))] z-[70] rounded-md border border-amber-200 bg-amber-50/95 p-2 text-[11px] text-slate-800 shadow-lg backdrop-blur sm:hidden">- <div className="flex items-center justify-between gap-2">- <button- className="min-w-0 flex-1 truncate text-left font-semibold"- type="button"- onClick={() => setMobileImeDebugOpen((open) => !open)}- >- IME 诊断:{mobileImeDebugEditorFocused ? "正文已聚焦" : "正文未聚焦"} · len {getMobilePlainTextValue().length}- </button>- <button- className="rounded border border-amber-300 bg-white px-2 py-1 font-medium text-slate-700"- type="button"- onClick={() => void handleMobileClipboardInput()}- >- 粘贴- </button>- <button- className="rounded border border-amber-300 bg-white px-2 py-1 font-medium text-slate-700"- type="button"- onClick={handleMobilePromptInput}- >- 输入- </button>- <button- className="rounded border border-amber-300 bg-white px-2 py-1 font-medium text-slate-700"- type="button"- onClick={() => {- focusMobileInputTarget();- recordMobileImeDebugEvent("debug-focus-button");- }}- >- 聚焦- </button>- <button- className="rounded border border-amber-300 bg-white px-2 py-1 font-medium text-slate-700"- type="button"- onClick={() => {- void navigator.clipboard?.writeText(mobileImeDebugLogText);- }}- >- 复制- </button>- </div>- {mobileImeDebugOpen && (- <div className="mt-2 max-h-40 overflow-auto rounded border border-amber-200 bg-white/80 p-2 font-mono leading-5">- <div>active: {mobileImeDebugActiveElement}</div>- <div>editorFocused: {String(mobileImeDebugEditorFocused)}</div>- <div>mode: mobile={String(isMobileViewport)} editingState={String(isMobileEditing)} editingActive={String(mobileEditingActive)} plain={String(useMobilePlainTextEditor)}</div>- <div>save: {saveState} dirty={String(hasUnsavedChanges)}</div>- <div className="mt-1 border-t border-amber-100 pt-1">- {mobileImeDebugEvents.length === 0 ? (- <div>暂无事件。点正文或按键后这里应该变化。</div>- ) : (- mobileImeDebugEvents.map((entry) => (- <div key={entry.id}>- {entry.time} {entry.event} len={entry.valueLength}- {entry.inputType ? ` type=${entry.inputType}` : ""}- {entry.isComposing !== undefined ? ` comp=${entry.isComposing}` : ""}- {entry.key ? ` key=${entry.key}` : ""}- </div>- ))- )}- </div>- </div>- )}- </div>- )}-{isMobileViewport && !mobileEditingActive && !readOnly && (<ButtonclassName="fixed bottom-[calc(1rem+env(safe-area-inset-bottom))] right-4 z-30 h-12 w-12 rounded-full shadow-lg sm:hidden"diff --git a/apps/web/src/components/editor/EditorNoteLinkPicker.tsx b/apps/web/src/components/editor/EditorNoteLinkPicker.tsxnew file mode 100644index 00000000..9bb6211b--- /dev/null+++ b/apps/web/src/components/editor/EditorNoteLinkPicker.tsx@@ -0,0 +1,80 @@+import { Link2, X } from "lucide-react";+import { useTranslation } from "react-i18next";+import type { MemoSummary } from "@edgeever/shared";+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+} from "@/components/ui/command";++export const EditorNoteLinkPicker = ({+ query,+ isLoading,+ memos,+ currentMemoId,+ onQueryChange,+ onClose,+ onInsert,+}: {+ query: string;+ isLoading: boolean;+ memos: MemoSummary[];+ currentMemoId: string;+ onQueryChange: (query: string) => void;+ onClose: () => void;+ onInsert: (memo: MemoSummary) => void;+}) => {+ const { t } = useTranslation();+ const candidates = memos.filter((candidate) => candidate.id !== currentMemoId && !candidate.isDeleted);++ return (+ <div+ className="absolute left-3 right-3 top-14 z-30 h-[min(22rem,calc(100%-4rem))] max-w-xl rounded-lg border border-slate-200 bg-white shadow-xl sm:left-5 sm:right-auto sm:w-[28rem]"+ role="dialog"+ aria-label={t("noteLinkPicker.title")}+ >+ <Command shouldFilter={false}>+ <div className="flex items-center justify-between border-b border-slate-100 pr-2">+ <CommandInput+ autoFocus+ value={query}+ placeholder={t("noteLinkPicker.searchPlaceholder")}+ onValueChange={onQueryChange}+ onKeyDown={(event) => {+ if (event.key === "Escape") onClose();+ }}+ />+ <button+ type="button"+ className="rounded-md p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-700"+ aria-label={t("noteLinkPicker.close")}+ onClick={onClose}+ >+ <X className="h-4 w-4" />+ </button>+ </div>+ <CommandList>+ {isLoading ? (+ <div className="p-6 text-center text-sm text-slate-500">{t("noteLinkPicker.loading")}</div>+ ) : (+ <>+ <CommandEmpty>{t("noteLinkPicker.empty")}</CommandEmpty>+ <CommandGroup>+ {candidates.map((candidate) => (+ <CommandItem key={candidate.id} value={candidate.id} onSelect={() => onInsert(candidate)}>+ <Link2 className="h-4 w-4 shrink-0 text-emerald-600" />+ <span className="min-w-0 flex-1 truncate">{candidate.title || t("common.untitledMemo")}</span>+ <span className="max-w-40 truncate text-xs text-slate-400">{candidate.excerpt}</span>+ </CommandItem>+ ))}+ </CommandGroup>+ </>+ )}+ </CommandList>+ </Command>+ </div>+ );+};diff --git a/apps/web/src/components/editor/EditorNoteSearchBar.tsx b/apps/web/src/components/editor/EditorNoteSearchBar.tsxnew file mode 100644index 00000000..14b3fa6f--- /dev/null+++ b/apps/web/src/components/editor/EditorNoteSearchBar.tsx@@ -0,0 +1,102 @@+import type { KeyboardEvent, RefObject } from "react";+import { ChevronLeft, ChevronRight, ReplaceAll, Search, X } from "lucide-react";+import { useTranslation } from "react-i18next";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { cn } from "@/lib/utils";++export const EditorNoteSearchBar = ({+ inputRef,+ query,+ replacement,+ replaceOpen,+ readOnly,+ matchCount,+ matchLabel,+ onQueryChange,+ onReplacementChange,+ onMoveMatch,+ onReplaceAll,+ onClose,+}: {+ inputRef: RefObject<HTMLInputElement | null>;+ query: string;+ replacement: string;+ replaceOpen: boolean;+ readOnly: boolean;+ matchCount: number;+ matchLabel: string;+ onQueryChange: (query: string) => void;+ onReplacementChange: (replacement: string) => void;+ onMoveMatch: (direction: -1 | 1) => void;+ onReplaceAll: () => void;+ onClose: () => void;+}) => {+ const { t } = useTranslation();+ const handleEscape = (event: KeyboardEvent<HTMLInputElement>) => {+ if (event.key !== "Escape") return false;+ event.preventDefault();+ onClose();+ return true;+ };++ return (+ <div className="flex flex-wrap items-center gap-2 border-t border-slate-100 px-4 py-2 sm:px-7">+ <Search className="h-4 w-4 shrink-0 text-slate-400" />+ <Input+ ref={inputRef}+ value={query}+ className="h-8 min-w-[12rem] flex-1"+ placeholder={t("editor.searchPlaceholder")}+ onChange={(event) => onQueryChange(event.target.value)}+ onKeyDown={(event) => {+ if (handleEscape(event)) return;+ if (event.key === "Enter") {+ event.preventDefault();+ onMoveMatch(event.shiftKey ? -1 : 1);+ }+ }}+ />+ {replaceOpen ? (+ <Input+ value={replacement}+ className="h-8 min-w-[12rem] flex-1"+ placeholder={t("editor.replacePlaceholder")}+ disabled={readOnly}+ onChange={(event) => onReplacementChange(event.target.value)}+ onKeyDown={(event) => {+ if (handleEscape(event)) return;+ if (event.key === "Enter") {+ event.preventDefault();+ onReplaceAll();+ }+ }}+ />+ ) : null}+ <span+ className={cn(+ "w-12 shrink-0 text-center text-xs tabular-nums",+ query.trim() && matchCount === 0 ? "text-rose-500" : "text-slate-500",+ )}+ aria-live="polite"+ >+ {matchLabel}+ </span>+ <Button size="icon" variant="ghost" aria-label={t("editor.previousSearchResult")} disabled={matchCount === 0} onClick={() => onMoveMatch(-1)}>+ <ChevronLeft className="h-4 w-4" />+ </Button>+ <Button size="icon" variant="ghost" aria-label={t("editor.nextSearchResult")} disabled={matchCount === 0} onClick={() => onMoveMatch(1)}>+ <ChevronRight className="h-4 w-4" />+ </Button>+ {replaceOpen ? (+ <Button size="sm" variant="solid" aria-label={t("editor.replaceAll")} disabled={readOnly || matchCount === 0} onClick={onReplaceAll}>+ <ReplaceAll className="h-4 w-4" />+ {t("editor.replaceAll")}+ </Button>+ ) : null}+ <Button size="icon" variant="ghost" aria-label={t("editor.closeSearch")} onClick={onClose}>+ <X className="h-4 w-4" />+ </Button>+ </div>+ );+};diff --git a/apps/web/src/components/editor/EditorPaneChrome.tsx b/apps/web/src/components/editor/EditorPaneChrome.tsxnew file mode 100644index 00000000..b592809d--- /dev/null+++ b/apps/web/src/components/editor/EditorPaneChrome.tsx@@ -0,0 +1,223 @@+import { useEffect, useRef, type ReactNode } from "react";+import { createPortal } from "react-dom";+import { FileDown, Pencil, Save, Trash2, X } from "lucide-react";+import { useTranslation } from "react-i18next";+import { Button } from "@/components/ui/button";+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+} from "@/components/ui/command";+import { Drawer, DrawerContent, DrawerHeader, DrawerTitle } from "@/components/ui/drawer";+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";+import { ThemeToggle } from "@/components/ThemeToggle";+import { cn } from "@/lib/utils";+import type { getNotebookMoveOptions } from "@/lib/app-helpers";+import type { ResourceMenuTarget } from "./useEditorResourceActions";++export const IconTooltip = ({ label, children }: { label: string; children: ReactNode }) => (+ <TooltipProvider delayDuration={0} skipDelayDuration={0}>+ <Tooltip>+ <TooltipTrigger asChild>{children}</TooltipTrigger>+ <TooltipContent side="bottom">{label}</TooltipContent>+ </Tooltip>+ </TooltipProvider>+);++export const EmptyEditorHeader = () => (+ <header className="hidden h-12 shrink-0 items-center justify-end gap-1 border-b border-slate-100 px-5 lg:flex">+ <ThemeToggle />+ </header>+);++export type NoteLinkHintPosition = {+ left: number;+ top: number;+ placement: "above" | "below" | "inside-bottom-right";+};++export const NoteLinkInteractionHint = ({+ label,+ position,+}: {+ label: string;+ position: NoteLinkHintPosition;+}) => createPortal(+ <div+ role="tooltip"+ className="pointer-events-none fixed z-[100] whitespace-nowrap rounded-md bg-slate-950 px-2.5 py-1.5 text-xs font-medium text-white shadow-md"+ style={{+ left: position.left,+ top: position.top,+ transform: position.placement === "above" ? "translate(-50%, -100%)" : "translateX(-50%)",+ }}+ >+ {label}+ </div>,+ document.body,+);++type ResourceActionLabels = {+ download: string;+ saveAs: string;+ rename: string;+ delete: string;+ unavailable: string;+};++export const ResourceActionMenu = ({+ target,+ canRename,+ canDelete,+ labels,+ onDownload,+ onSaveAs,+ onRename,+ onDelete,+ onMouseEnter,+ onMouseLeave,+}: {+ target: ResourceMenuTarget;+ canRename: boolean;+ canDelete: boolean;+ labels: ResourceActionLabels;+ onDownload: () => void;+ onSaveAs: () => void;+ onRename: () => void;+ onDelete: () => void;+ onMouseEnter: () => void;+ onMouseLeave: () => void;+}) => createPortal(+ <TooltipProvider delayDuration={0} skipDelayDuration={0}>+ <div+ data-edgeever-resource-menu+ role="toolbar"+ aria-label={labels.download}+ className="fixed z-[110] flex items-center gap-1 rounded-lg border border-slate-200 bg-white p-1 shadow-lg"+ style={{+ left: target.position.left,+ top: target.position.top,+ transform: target.position.placement === "inside-bottom-right"+ ? "translate(-100%, -100%)"+ : target.position.placement === "above"+ ? "translate(-50%, -100%)"+ : "translateX(-50%)",+ }}+ onMouseEnter={onMouseEnter}+ onMouseLeave={onMouseLeave}+ >+ <IconTooltip label={labels.download}>+ <Button type="button" size="sm" variant="ghost" aria-label={labels.download} onClick={onDownload}>+ <FileDown className="h-3.5 w-3.5" />+ {labels.download}+ </Button>+ </IconTooltip>+ <IconTooltip label={labels.saveAs}>+ <Button type="button" size="sm" variant="ghost" aria-label={labels.saveAs} onClick={onSaveAs}>+ <Save className="h-3.5 w-3.5" />+ {labels.saveAs}+ </Button>+ </IconTooltip>+ <IconTooltip label={canRename ? labels.rename : labels.unavailable}>+ <Button type="button" size="sm" variant="ghost" aria-label={labels.rename} disabled={!canRename} onClick={onRename}>+ <Pencil className="h-3.5 w-3.5" />+ {labels.rename}+ </Button>+ </IconTooltip>+ <IconTooltip label={canDelete ? labels.delete : labels.unavailable}>+ <Button+ type="button"+ size="sm"+ variant="ghost"+ className="text-slate-600 hover:bg-rose-50 hover:text-rose-600"+ aria-label={labels.delete}+ disabled={!canDelete}+ onClick={onDelete}+ >+ <Trash2 className="h-3.5 w-3.5" />+ {labels.delete}+ </Button>+ </IconTooltip>+ </div>+ </TooltipProvider>,+ document.body,+);++type NotebookMoveOption = ReturnType<typeof getNotebookMoveOptions>[number];++export const MobileNotebookSelectSheet = ({+ isUpdating,+ options,+ selectedNotebookId,+ onClose,+ onSelect,+}: {+ isUpdating: boolean;+ options: NotebookMoveOption[];+ selectedNotebookId: string;+ onClose: () => void;+ onSelect: (notebookId: string) => void;+}) => {+ const { t } = useTranslation();+ const listRef = useRef<HTMLDivElement | null>(null);++ useEffect(() => {+ const timer = window.setTimeout(() => {+ const selectedNode = listRef.current?.querySelector<HTMLElement>(+ `[data-mobile-notebook-select-id="${CSS.escape(selectedNotebookId)}"]`,+ );+ selectedNode?.scrollIntoView({ block: "center" });+ }, 0);+ return () => window.clearTimeout(timer);+ }, [selectedNotebookId]);++ return (+ <Drawer open={true} onOpenChange={(open) => { if (!open) onClose(); }}>+ <DrawerContent className="inset-x-0 max-h-[62dvh] overflow-hidden border-x-0 border-b-0 pb-[env(safe-area-inset-bottom)] lg:hidden">+ <header className="flex h-12 items-center justify-between border-b border-slate-200 px-4">+ <DrawerHeader className="min-w-0 p-0">+ <DrawerTitle className="text-base">{t("editor.currentNotebook")}</DrawerTitle>+ </DrawerHeader>+ <IconTooltip label={t("editor.close")}>+ <Button size="icon" variant="ghost" aria-label={t("editor.close")} onClick={onClose}>+ <X className="h-4 w-4" />+ </Button>+ </IconTooltip>+ </header>+ <Command className="min-h-0 flex-1">+ <CommandInput placeholder={t("editor.searchNotebook")} />+ <CommandList ref={listRef} className="max-h-[calc(62dvh-6.25rem-env(safe-area-inset-bottom))] p-2">+ <CommandEmpty>{t("editor.noNotebookFound")}</CommandEmpty>+ <CommandGroup>+ {options.map((option) => {+ const selected = option.id === selectedNotebookId;+ return (+ <CommandItem+ key={option.id}+ className={cn(+ "h-12 px-3 text-base",+ selected ? "bg-emerald-50 font-semibold text-emerald-700 data-[selected=true]:bg-emerald-50" : "text-slate-700",+ )}+ style={{ paddingLeft: `${12 + option.depth * 18}px` }}+ value={option.id}+ keywords={[option.name, option.selectLabel, option.slug ?? ""]}+ data-mobile-notebook-select-id={option.id}+ aria-label={selected ? t("editor.currentNotebookAria", { name: option.name }) : t("editor.switchToNotebook", { name: option.name })}+ aria-current={selected ? "page" : undefined}+ disabled={isUpdating}+ onSelect={() => onSelect(option.id)}+ >+ <span className="min-w-0 flex-1 truncate">{option.name}</span>+ </CommandItem>+ );+ })}+ </CommandGroup>+ </CommandList>+ </Command>+ </DrawerContent>+ </Drawer>+ );+};diff --git a/apps/web/src/components/editor/EditorResourceDialogs.tsx b/apps/web/src/components/editor/EditorResourceDialogs.tsxnew file mode 100644index 00000000..12f3ffd8--- /dev/null+++ b/apps/web/src/components/editor/EditorResourceDialogs.tsx@@ -0,0 +1,114 @@+import { useTranslation } from "react-i18next";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import type { ResourceDialogState } from "./useEditorResourceActions";++export type EditorResourceDialogLabels = {+ renameTitle: string;+ renameDescription: string;+ filenameLabel: string;+ deleteTitle: string;+ deleteDescription: string;+};++export const EditorResourceDialogs = ({+ dialog,+ labels,+ filename,+ pending,+ error,+ onFilenameChange,+ onClose,+ onRename,+ onDelete,+}: {+ dialog: ResourceDialogState | null;+ labels: EditorResourceDialogLabels;+ filename: string;+ pending: boolean;+ error: string | null;+ onFilenameChange: (filename: string) => void;+ onClose: () => void;+ onRename: () => Promise<void> | void;+ onDelete: () => Promise<void> | void;+}) => {+ const { t } = useTranslation();++ return (+ <>+ <Dialog open={dialog?.action === "rename"} onOpenChange={(open) => { if (!open) onClose(); }}>+ <DialogContent>+ <form+ className="contents"+ onSubmit={(event) => {+ event.preventDefault();+ void onRename();+ }}+ >+ <DialogHeader>+ <DialogTitle>{labels.renameTitle}</DialogTitle>+ <DialogDescription>{labels.renameDescription}</DialogDescription>+ </DialogHeader>+ <label className="grid gap-2 text-sm font-medium text-slate-700">+ {labels.filenameLabel}+ <Input+ autoFocus+ value={filename}+ maxLength={160}+ disabled={pending}+ onChange={(event) => onFilenameChange(event.target.value)}+ />+ </label>+ {error ? <p className="text-sm text-rose-600" role="alert">{error}</p> : null}+ <DialogFooter>+ <Button type="button" variant="ghost" disabled={pending} onClick={onClose}>+ {t("common.cancel")}+ </Button>+ <Button type="submit" variant="solid" disabled={pending || !filename.trim()}>+ {pending ? t("common.saving") : t("common.save")}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>++ <Dialog open={dialog?.action === "delete"} onOpenChange={(open) => { if (!open) onClose(); }}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{labels.deleteTitle}</DialogTitle>+ <DialogDescription>{labels.deleteDescription}</DialogDescription>+ </DialogHeader>+ <p className="truncate rounded-md bg-slate-50 px-3 py-2 text-sm font-medium text-slate-700">+ {dialog?.target.filename}+ </p>+ {error ? <p className="text-sm text-rose-600" role="alert">{error}</p> : null}+ <DialogFooter>+ <Button type="button" variant="ghost" disabled={pending} onClick={onClose}>+ {t("common.cancel")}+ </Button>+ <Button type="button" variant="danger" disabled={pending} onClick={() => void onDelete()}>+ {pending ? t("common.processing") : t("common.delete")}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ {error && !dialog ? (+ <div+ className="fixed bottom-5 left-1/2 z-[120] -translate-x-1/2 rounded-md bg-rose-600 px-3 py-2 text-sm font-medium text-white shadow-lg"+ role="alert"+ >+ {error}+ </div>+ ) : null}+ </>+ );+};diff --git a/apps/web/src/components/editor/EditorSaveRecoveryBanner.tsx b/apps/web/src/components/editor/EditorSaveRecoveryBanner.tsxnew file mode 100644index 00000000..be0700c7--- /dev/null+++ b/apps/web/src/components/editor/EditorSaveRecoveryBanner.tsx@@ -0,0 +1,74 @@+import { CircleAlert } from "lucide-react";+import { useTranslation } from "react-i18next";+import { Button } from "@/components/ui/button";+import type { EditorSavePhase } from "./useEditorSaveStatus";++export const EditorSaveRecoveryBanner = ({+ saveState,+ conflictReason,+ storageSaveError,+ savePending,+ actionPending,+ actionMessage,+ onAdoptCloud,+ onCopyDraft,+ onRetry,+}: {+ saveState: EditorSavePhase;+ conflictReason: string | null;+ storageSaveError: boolean;+ savePending: boolean;+ actionPending: "adopt" | "copy" | null;+ actionMessage: string | null;+ onAdoptCloud: () => Promise<void> | void;+ onCopyDraft: () => Promise<void> | void;+ onRetry: () => void;+}) => {+ const { t } = useTranslation();+ const message = saveState === "conflict" && conflictReason+ ? conflictReason+ : saveState === "error" && storageSaveError+ ? t("editor.saveState.storageUnavailable")+ : null;++ if (!message) return null;+ const isConflict = saveState === "conflict";++ return (+ <div 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">+ <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">{message}</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={isConflict ? actionPending !== null : savePending}+ onClick={() => { if (isConflict) void onAdoptCloud(); else onRetry(); }}+ >+ {isConflict+ ? actionPending === "adopt"+ ? t("editor.saveState.conflictAdopting")+ : t("editor.saveState.conflictAdoptCloud")+ : t("editor.saveState.storageRetry")}+ </Button>+ <Button+ size="sm"+ variant="ghost"+ className="h-7 px-2.5 text-[11px] text-rose-800 hover:bg-rose-100"+ disabled={actionPending !== null}+ onClick={() => void onCopyDraft()}+ >+ {t("editor.saveState.conflictCopyDraft")}+ </Button>+ {actionMessage ? (+ <span className="text-[11px] font-medium text-rose-700" role="status" aria-live="polite">+ {actionMessage}+ </span>+ ) : null}+ </div>+ </div>+ );+};diff --git a/apps/web/src/components/editor/useEditorNoteSearchController.ts b/apps/web/src/components/editor/useEditorNoteSearchController.tsnew file mode 100644index 00000000..4df089e5--- /dev/null+++ b/apps/web/src/components/editor/useEditorNoteSearchController.ts@@ -0,0 +1,286 @@+import {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ type Dispatch,+ type RefObject,+ type SetStateAction,+} from "react";+import type { Editor } from "@tiptap/react";+import {+ createNoteSearchHighlightPlugin,+ formatNoteSearchMatchLabel,+ getNextSearchMatchIndex,+ getSearchMatchesFromDocument,+ getSearchNavigationIdentity,+ NOTE_SEARCH_HIGHLIGHT_PLUGIN_KEY,+ type NoteSearchMatch,+} from "./note-search";++type EditorNoteSearchControllerOptions = {+ contentSearchQuery: string;+ dirtyVersion: number;+ editor: Editor | null;+ editorScrollContainerRef: RefObject<HTMLDivElement | null>;+ noteSearchIndex: number;+ noteSearchInputRef: RefObject<HTMLInputElement | null>;+ noteSearchOpen: boolean;+ noteSearchQuery: string;+ noteSearchReplacement: string;+ readOnly: boolean;+ replaceFocusToken: number;+ searchFocusToken: number;+ memoId: string | null;+ setNoteSearchIndex: Dispatch<SetStateAction<number>>;+ setNoteSearchOpen: Dispatch<SetStateAction<boolean>>;+ setNoteSearchReplaceOpen: Dispatch<SetStateAction<boolean>>;+};++const isEditorReady = (editor: Editor | null | undefined): editor is Editor =>+ Boolean(editor && !editor.isDestroyed && (editor as { extensionManager?: unknown }).extensionManager);++const getEditorSearchMatches = (editor: Editor | null, query: string): NoteSearchMatch[] => {+ if (!isEditorReady(editor)) {+ return [];+ }++ return getSearchMatchesFromDocument(editor.state.doc, query);+};++export const useEditorNoteSearchController = ({+ contentSearchQuery,+ dirtyVersion,+ editor,+ editorScrollContainerRef,+ memoId,+ noteSearchIndex,+ noteSearchInputRef,+ noteSearchOpen,+ noteSearchQuery,+ noteSearchReplacement,+ readOnly,+ replaceFocusToken,+ searchFocusToken,+ setNoteSearchIndex,+ setNoteSearchOpen,+ setNoteSearchReplaceOpen,+}: EditorNoteSearchControllerOptions) => {+ const automaticSelectionRef = useRef<{ editor: Editor; identity: string } | null>(null);+ const noteSearchMatches = useMemo(+ () => getEditorSearchMatches(editor, noteSearchQuery),+ [dirtyVersion, editor, memoId, noteSearchQuery],+ );+ const contentSearchMatches = useMemo(+ () => getEditorSearchMatches(editor, contentSearchQuery),+ [contentSearchQuery, dirtyVersion, editor, memoId],+ );++ const selectMatch = useCallback(+ (index: number, matches: NoteSearchMatch[]) => {+ const match = matches[index];++ if (!isEditorReady(editor) || !match) {+ return;+ }++ editor.chain().setTextSelection({ from: match.from, to: match.to }).scrollIntoView().run();++ window.requestAnimationFrame(() => {+ const scrollContainer = editorScrollContainerRef.current;+ const domPosition = editor.view.domAtPos(match.from);+ const node = domPosition.node.nodeType === Node.TEXT_NODE+ ? domPosition.node.parentElement+ : domPosition.node instanceof Element+ ? domPosition.node+ : domPosition.node.parentElement;++ if (!scrollContainer || !node) {+ return;+ }++ const containerRect = scrollContainer.getBoundingClientRect();+ const nodeRect = node.getBoundingClientRect();+ const padding = 24;+ const isAbove = nodeRect.top < containerRect.top + padding;+ const isBelow = nodeRect.bottom > containerRect.bottom - padding;++ if (isAbove || isBelow) {+ const targetTop = scrollContainer.scrollTop + nodeRect.top - containerRect.top+ - (scrollContainer.clientHeight - nodeRect.height) / 2;+ scrollContainer.scrollTo({ top: Math.max(0, targetTop), behavior: "smooth" });+ }+ });+ },+ [editor, editorScrollContainerRef],+ );++ useEffect(() => {+ if (!isEditorReady(editor)) {+ return;+ }++ const searchHighlightPlugin = createNoteSearchHighlightPlugin({+ getQuery: () => noteSearchOpen ? noteSearchQuery : contentSearchQuery,+ getActiveIndex: () => noteSearchOpen ? noteSearchIndex : 0,+ });++ editor.registerPlugin(searchHighlightPlugin);++ return () => {+ if (isEditorReady(editor)) {+ editor.unregisterPlugin(NOTE_SEARCH_HIGHLIGHT_PLUGIN_KEY);+ }+ };+ }, [contentSearchQuery, editor, noteSearchIndex, noteSearchOpen, noteSearchQuery]);++ const focusSearchInput = useCallback(() => {+ window.requestAnimationFrame(() => {+ noteSearchInputRef.current?.focus();+ noteSearchInputRef.current?.select();+ });+ }, [noteSearchInputRef]);++ const openSearch = useCallback((showReplace = false) => {+ setNoteSearchOpen(true);+ setNoteSearchReplaceOpen(showReplace);+ focusSearchInput();+ }, [focusSearchInput, setNoteSearchOpen, setNoteSearchReplaceOpen]);++ const openReplace = useCallback(() => {+ if (readOnly) return;+ openSearch(true);+ }, [openSearch, readOnly]);++ const closeSearch = useCallback(() => {+ setNoteSearchOpen(false);+ if (isEditorReady(editor)) {+ editor.commands.focus();+ }+ }, [editor, setNoteSearchOpen]);++ useEffect(() => {+ if (!noteSearchOpen) {+ return;+ }++ const handleEscape = (event: KeyboardEvent) => {+ if (event.key !== "Escape" || event.defaultPrevented) {+ return;+ }++ event.preventDefault();+ event.stopPropagation();+ closeSearch();+ };++ window.addEventListener("keydown", handleEscape, true);+ return () => window.removeEventListener("keydown", handleEscape, true);+ }, [closeSearch, noteSearchOpen]);++ const moveMatch = useCallback((direction: 1 | -1) => {+ if (noteSearchMatches.length === 0) {+ return;+ }++ setNoteSearchIndex((current) => {+ const next = getNextSearchMatchIndex(current, direction, noteSearchMatches.length);+ selectMatch(next, noteSearchMatches);+ return next;+ });+ }, [noteSearchMatches, selectMatch, setNoteSearchIndex]);++ useEffect(() => {+ if (searchFocusToken !== 0) {+ openSearch();+ }+ }, [openSearch, searchFocusToken]);++ useEffect(() => {+ if (replaceFocusToken !== 0) {+ openReplace();+ }+ }, [openReplace, replaceFocusToken]);++ useEffect(() => {+ if (!isEditorReady(editor)) {+ return;+ }++ const source = noteSearchOpen ? "note" : "content";+ const query = noteSearchOpen ? noteSearchQuery : contentSearchQuery;+ const matches = noteSearchOpen ? noteSearchMatches : contentSearchMatches;+ const identity = getSearchNavigationIdentity(memoId, source, query);+ const previousSelection = automaticSelectionRef.current;++ if (previousSelection?.editor === editor && previousSelection.identity === identity) {+ return;+ }++ automaticSelectionRef.current = { editor, identity };+ setNoteSearchIndex(0);++ if (matches[0]) {+ selectMatch(0, matches);+ }+ }, [+ contentSearchMatches,+ contentSearchQuery,+ editor,+ memoId,+ noteSearchMatches,+ noteSearchOpen,+ noteSearchQuery,+ selectMatch,+ setNoteSearchIndex,+ ]);++ useEffect(() => {+ setNoteSearchIndex((current) => noteSearchMatches.length === 0+ ? 0+ : Math.min(current, noteSearchMatches.length - 1));+ }, [noteSearchMatches.length, setNoteSearchIndex]);++ const replaceAllMatches = useCallback(() => {+ if (!isEditorReady(editor) || readOnly || noteSearchMatches.length === 0) {+ return;+ }++ editor+ .chain()+ .focus()+ .command(({ tr, dispatch }) => {+ for (const match of [...noteSearchMatches].reverse()) {+ tr.insertText(noteSearchReplacement, match.from, match.to);+ }++ dispatch?.(tr);+ return true;+ })+ .run();++ setNoteSearchIndex(0);+ window.requestAnimationFrame(() => noteSearchInputRef.current?.focus());+ }, [+ editor,+ noteSearchInputRef,+ noteSearchMatches,+ noteSearchReplacement,+ readOnly,+ setNoteSearchIndex,+ ]);++ return {+ closeSearch,+ matchLabel: formatNoteSearchMatchLabel(+ noteSearchQuery,+ noteSearchIndex,+ noteSearchMatches.length,+ ),+ matches: noteSearchMatches,+ moveMatch,+ openReplace,+ openSearch,+ replaceAllMatches,+ };+};diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex 18b06a9a..2bebb53a 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -1,118 +1,25 @@-import type {- AuthSession,- LoginDeviceSession,- InstanceUser,- ApiToken,- CreatedApiToken,- JsonBackupMemo,- JsonBackupNotebook,- JsonBackupAiPrompt,- JsonBackupRevision,- MemoDetail,- MemoTemplate,- MemoEditSession,- MemoRevision,- MemoSummary,- MemoShare,- Notebook,- Resource,- ResourceListItem,- ResourceStorageSummary,- ObjectStorageSettings,- AiSettings,- AiDiscoveredModel,- AiProvider,- AiPromptTemplate,- AiPromptTemplateCreateInput,- AiPromptTemplateUpdateInput,- AiStreamEvent,- AiGenerateInput,- AiTagSuggestionPromptUpdateInput,- AiTagSuggestionsRequestInput,- AiTagSuggestionsResponse,- PublicMemoShare,- TagSummary,- TiptapDoc,- SyncBootstrapResponse,- SyncChangesResponse,-} from "@edgeever/shared";+import {+ ApiRequestError,+ createEdgeEverClient,+ type EdgeEverClientRequestContext,+} from "@edgeever/client";+import type { AuthSession } from "@edgeever/shared";import { resolveInstanceUrlInput } from "@edgeever/shared";-import type { MemoFilterMode, MemoSortMode } from "./app-helpers";import { readAiStreamingPreference } from "./ai-generation-preference";import { createClientUuid } from "./client-id";-type ListNotebooksResponse = {- notebooks: Notebook[];-};--export type InstanceRelease = {- version: string;- changes: Record<string, string[]>;-};--export type InstanceHealth = {- ok: true;- name: string;- runtime: string;- authMode: string;- build: string;- migration: string;- storage: {- database: "d1" | "sqlite";- resources: "r2" | "filesystem" | "s3";- };- objectStorageProvider: "builtin" | "s3" | "unknown";-};--type ListMemosResponse = {- memos: MemoSummary[];- totalCount: number;- nextCursor: string | null;-};--type ListMemoRevisionsResponse = {- revisions: MemoRevision[];-};--type ListResourcesResponse = {- resources: ResourceListItem[];- summary: ResourceStorageSummary;-};--type ListTagsResponse = {- tags: TagSummary[];-};--export type { SyncBootstrapResponse, SyncChangesResponse };--type ListApiTokensResponse = {- apiTokens: ApiToken[];- availableScopes: string[];-};--type ListUsersResponse = { users: InstanceUser[] };-type UserResponse = { user: InstanceUser };-type ListLoginDeviceSessionsResponse = { sessions: LoginDeviceSession[] };-type ObjectStorageSettingsResponse = {- settings: ObjectStorageSettings;- externalSettings?: ObjectStorageSettings | null;-};-export type AiProviderCreatePayload = {- provider: AiProvider;- displayName: string;- baseUrl: string;- apiKey: string;- isEnabled: boolean;- initialModelId?: string;-};--export type AiProviderUpdatePayload = {- provider: AiProvider;- displayName: string;- baseUrl: string;- apiKey?: string;- isEnabled: boolean;-};+export { ApiRequestError };+export type {+ AiProviderCreatePayload,+ AiProviderUpdatePayload,+ InstanceHealth,+ InstanceRelease,+ JsonBackupPage,+ MarkdownExportPage,+ MemoShareResponse,+ SyncBootstrapResponse,+ SyncChangesResponse,+} from "@edgeever/client";const WEB_DEVICE_ID_STORAGE_KEY = "edgeever.web.device-id";export const DESKTOP_API_BASE_URL_STORAGE_KEY = "edgeever.desktop.api-base-url";@@ -234,9 +141,7 @@ export const saveDesktopApiBaseUrl = async (value: string) => {return normalized;};-const createWebDeviceId = () => {- return `web-${createClientUuid()}`;-};+const createWebDeviceId = () => `web-${createClientUuid()}`;const getOrCreateWebDeviceId = () => {try {@@ -251,63 +156,6 @@ const getOrCreateWebDeviceId = () => {}};-type MemoResponse = {- memo: MemoDetail;-};--export type MemoShareResponse = { share: MemoShare | null };--type TemplateResponse = {- template: MemoTemplate;-};--type NotebookResponse = {- notebook: Notebook;-};--type ResourceResponse = {- resource: Resource;-};--export type MarkdownExportPage = {- memos: MemoDetail[];- resources: Resource[];- totalCount: number;- nextOffset: number | null;-};--export type JsonBackupPage = MarkdownExportPage & {- revisions: JsonBackupRevision[];-};--export class ApiRequestError extends Error {- status: number;- code?: string;- details?: unknown;- responseDiagnostics?: ApiResponseDiagnostics;-- constructor(- message: string,- status: number,- code?: string,- details?: unknown,- responseDiagnostics?: ApiResponseDiagnostics,- ) {- super(message);- this.name = "ApiRequestError";- this.status = status;- this.code = code;- this.details = details;- this.responseDiagnostics = responseDiagnostics;- }-}--export type ApiResponseDiagnostics = {- cloudflareMitigated: boolean;- isEdgeEverApiError: boolean;- rayId?: string;-};-let desktopSessionRejected = false;let unauthorizedConfirmPromise: Promise<boolean> | null = null;@@ -340,7 +188,6 @@ const confirmSessionLost = async (): Promise<boolean> => {} catch {return true;} finally {- // Allow a later 401 to re-check after this round finishes.queueMicrotask(() => {unauthorizedConfirmPromise = null;});@@ -353,10 +200,6 @@ const confirmSessionLost = async (): Promise<boolean> => {const notifyUnauthorized = async (isDesktop: boolean, rejectedDesktopSessionToken?: string) => {if (isDesktop && desktopSessionRejected) return;- // A desktop API request authenticates with one explicit bearer token. A 401- // therefore rejects that exact credential and does not need a second- // /auth/session request. Compare against the current token first so a late- // response from an older request cannot clear a freshly logged-in session.if (isDesktop && rejectedDesktopSessionToken) {if (getDesktopSessionToken() !== rejectedDesktopSessionToken) return;clearCachedDesktopSession();@@ -375,660 +218,56 @@ const notifyUnauthorized = async (isDesktop: boolean, rejectedDesktopSessionTokewindow.dispatchEvent(new CustomEvent("edgeever:unauthorized"));};-const request = async <T>(path: string, init?: RequestInit): Promise<T> => {- const headers = new Headers(init?.headers);+const beforeRequest = ({ path }: EdgeEverClientRequestContext) => {const isDesktop = Boolean(typeof window !== "undefined" && window.edgeeverDesktop?.isAvailable);- const sessionToken = isDesktop ? getDesktopSessionToken() : undefined;-if (isDesktop && desktopSessionRejected && !isDesktopPublicRequest(path)) {throw new ApiRequestError("Authentication required", 401, "unauthorized");}-- if (sessionToken && !headers.has("Authorization") && path !== "/api/v1/auth/login") {- headers.set("Authorization", `Bearer ${sessionToken}`);- }-- if (!(init?.body instanceof FormData) && !headers.has("Content-Type")) {- headers.set("Content-Type", "application/json");- }-- const baseUrl = getConfiguredDesktopApiBaseUrl();- const response = await fetch(`${baseUrl}${path}`, {- credentials: "include",- ...init,- headers,- });-- if (!response.ok) {- const body = await response.json().catch(() => null);- const rayId = response.headers.get("cf-ray")?.trim();- const error = body && typeof body === "object" && "error" in body- ? (body as { error?: { code?: string; message?: string; details?: unknown } }).error- : undefined;- const isEdgeEverApiError = Boolean(error && typeof error === "object");- const message =- body && typeof body === "object" && "error" in body- ? error?.message- : response.statusText;- const responseDiagnostics: ApiResponseDiagnostics = {- cloudflareMitigated: response.headers.get("cf-mitigated") === "challenge",- isEdgeEverApiError,- ...(rayId ? { rayId } : {}),- };-- if (response.status === 401 && path !== "/api/v1/auth/login") {- void notifyUnauthorized(isDesktop, sessionToken);- }-- throw new ApiRequestError(- message || "Request failed",- response.status,- error?.code,- error?.details,- responseDiagnostics,- );- }-- const body = await response.json() as T;- if (- isDesktop &&- path === "/api/v1/auth/session" &&- sessionToken &&- body &&- typeof body === "object" &&- "authenticated" in body &&- body.authenticated === false- ) {- clearCachedDesktopSession();- desktopSessionRejected = true;- window.dispatchEvent(new CustomEvent("edgeever:unauthorized"));- }- if (path === "/api/v1/auth/login") {- desktopSessionRejected = false;- }- return body;};-const requestArrayBuffer = async (path: string) => {- const isDesktop = Boolean(typeof window !== "undefined" && window.edgeeverDesktop?.isAvailable);- const sessionToken = isDesktop ? getDesktopSessionToken() : undefined;- const headers = new Headers();- if (sessionToken) headers.set("Authorization", `Bearer ${sessionToken}`);- const response = await fetch(`${getConfiguredDesktopApiBaseUrl()}${path}`, {- credentials: "include",- headers,- });- if (!response.ok) {- const body = await response.json().catch(() => null) as { error?: { message?: string } } | null;- if (response.status === 401) void notifyUnauthorized(isDesktop, sessionToken);- throw new ApiRequestError(body?.error?.message || response.statusText || "Binary download failed", response.status);- }- return response.arrayBuffer();+const handleUnauthorized = ({ path, token }: EdgeEverClientRequestContext) => {+ if (path === "/api/v1/auth/login" || typeof window === "undefined") return;+ const isDesktop = Boolean(window.edgeeverDesktop?.isAvailable);+ void notifyUnauthorized(isDesktop, token);};-export const api = {- getInstanceHealth: () => request<InstanceHealth>("/api/health"),-- getInstanceRelease: () => request<InstanceRelease>("/api/release"),-- getSession: () => request<AuthSession>("/api/v1/auth/session"),-- getPublicMemoShare: (token: string) =>- request<{ share: PublicMemoShare }>(`/api/public/shares/${encodeURIComponent(token)}`),-- listLoginDeviceSessions: () =>- request<ListLoginDeviceSessionsResponse>("/api/v1/auth/sessions"),-- revokeLoginDeviceSession: (sessionId: string) =>- request<{ ok: true }>(`/api/v1/auth/sessions/${sessionId}`, { method: "DELETE" }),-- updateLoginDeviceSession: (sessionId: string, payload: { label: string | null }) =>- request<{ ok: true }>(`/api/v1/auth/sessions/${sessionId}`, {- method: "PATCH",- body: JSON.stringify(payload),- }),-- revokeOtherLoginDeviceSessions: () =>- request<{ ok: true }>("/api/v1/auth/sessions", { method: "DELETE" }),-- login: (payload: { username: string; password: string }) =>- request<AuthSession>("/api/v1/auth/login", {- method: "POST",- body: JSON.stringify({ ...payload, deviceId: getOrCreateWebDeviceId() }),- }),-- changePassword: (payload: { currentPassword: string; newPassword: string; confirmPassword: string }) =>- request<{ ok: true }>("/api/v1/auth/change-password", {- method: "POST",- body: JSON.stringify(payload),- }),-- listUsers: () => request<ListUsersResponse>("/api/v1/users"),-- createUser: (payload: { username: string; displayName?: string | null; password: string }) =>- request<UserResponse>("/api/v1/users", {- method: "POST",- body: JSON.stringify(payload),- }),-- updateUser: (userId: string, payload: { displayName?: string | null; password?: string; isDisabled?: boolean }) =>- request<UserResponse>(`/api/v1/users/${userId}`, {- method: "PATCH",- body: JSON.stringify(payload),- }),-- getObjectStorageSettings: () =>- request<ObjectStorageSettingsResponse>("/api/v1/instance/object-storage"),-- testObjectStorageConnection: (payload: {- endpoint: string;- region: string;- bucket: string;- accessKeyId: string;- secretAccessKey?: string;- forcePathStyle: boolean;- objectPrefix: string;- }) => request<{ ok: true }>("/api/v1/instance/object-storage/test", {- method: "POST",- body: JSON.stringify(payload),- }),-- updateObjectStorageSettings: (payload:- | { provider: "builtin" }- | {- provider: "s3";- displayName: string;- endpoint: string;- region: string;- bucket: string;- accessKeyId: string;- secretAccessKey?: string;- forcePathStyle: boolean;- objectPrefix: string;- }) => request<ObjectStorageSettingsResponse>("/api/v1/instance/object-storage", {- method: "PUT",- body: JSON.stringify(payload),- }),-- logout: () =>- request<{ ok: true }>("/api/v1/auth/logout", {- method: "POST",- body: JSON.stringify({}),- }),-- listNotebooks: () => request<ListNotebooksResponse>("/api/v1/notebooks"),-- syncBootstrap: (params?: { afterId?: string | null; limit?: number }) => {- const search = new URLSearchParams();- if (params?.afterId) search.set("afterId", params.afterId);- if (params?.limit) search.set("limit", String(params.limit));- const suffix = search.toString() ? `?${search.toString()}` : "";- return request<SyncBootstrapResponse>(`/api/v1/sync/bootstrap${suffix}`);- },-- syncChanges: (params: { cursor: number; limit?: number }) => {- const search = new URLSearchParams({ cursor: String(params.cursor) });- if (params.limit) search.set("limit", String(params.limit));- return request<SyncChangesResponse>(`/api/v1/sync/changes?${search.toString()}`);- },-- createNotebook: (payload: { name: string; parentId?: string | null }) =>- request<NotebookResponse>("/api/v1/notebooks", {- method: "POST",- body: JSON.stringify(payload),- }),-- getAiSettings: (locale?: string) => {- const search = locale ? `?locale=${encodeURIComponent(locale)}` : "";- return request<AiSettings>(`/api/v1/ai/settings${search}`);- },-- createAiProvider: (payload: AiProviderCreatePayload) =>- request<AiSettings>("/api/v1/ai/providers", {- method: "POST",- body: JSON.stringify(payload),- }),-- updateAiProvider: (providerConfigId: string, payload: AiProviderUpdatePayload) =>- request<AiSettings>(`/api/v1/ai/providers/${encodeURIComponent(providerConfigId)}`, {- method: "PUT",- body: JSON.stringify(payload),- }),-- deleteAiProvider: (providerConfigId: string) =>- request<AiSettings>(`/api/v1/ai/providers/${encodeURIComponent(providerConfigId)}`, {- method: "DELETE",- }),-- testAiProvider: (providerConfigId: string, payload: {- modelId: string;- provider?: AiProvider;- baseUrl?: string;- apiKey?: string;- }) =>- request<{ ok: true; response: string }>(`/api/v1/ai/providers/${encodeURIComponent(providerConfigId)}/test`, {- method: "POST",- body: JSON.stringify(payload),- }),+const client = createEdgeEverClient({+ baseUrl: getConfiguredDesktopApiBaseUrl,+ token: getDesktopSessionToken,+ beforeRequest,+ shouldAttachToken: (path) => path !== "/api/v1/auth/login",+ onUnauthorized: handleUnauthorized,+});- discoverAiProviderModels: (providerConfigId: string) =>- request<{ models: AiDiscoveredModel[] }>(`/api/v1/ai/providers/${encodeURIComponent(providerConfigId)}/discover-models`, {- method: "POST",- body: JSON.stringify({}),- }),-- addAiModel: (providerConfigId: string, payload: { modelId: string; displayName?: string }) =>- request<AiSettings>(`/api/v1/ai/providers/${encodeURIComponent(providerConfigId)}/models`, {- method: "POST",- body: JSON.stringify(payload),- }),-- deleteAiModel: (providerConfigId: string, modelConfigId: string) =>- request<AiSettings>(`/api/v1/ai/providers/${encodeURIComponent(providerConfigId)}/models/${encodeURIComponent(modelConfigId)}`, {- method: "DELETE",- }),-- updateDefaultAiModel: (modelConfigId: string | null) =>- request<AiSettings>("/api/v1/ai/default-model", {- method: "PUT",- body: JSON.stringify({ modelConfigId }),- }),-- updateAiTagSuggestionPrompt: (payload: AiTagSuggestionPromptUpdateInput, locale?: string) =>- request<AiSettings>(`/api/v1/ai/tag-suggestion-prompt${locale ? `?locale=${encodeURIComponent(locale)}` : ""}`, {- method: "PUT",- body: JSON.stringify(payload),- }),-- listAiPrompts: (locale?: string) => {- const search = locale ? `?locale=${encodeURIComponent(locale)}` : "";- return request<{ prompts: AiPromptTemplate[] }>(`/api/v1/ai/prompts${search}`);- },-- createAiPrompt: (payload: AiPromptTemplateCreateInput) =>- request<{ prompt: AiPromptTemplate }>("/api/v1/ai/prompts", {- method: "POST",- body: JSON.stringify(payload),- }),-- updateAiPrompt: (- promptId: string,- payload: AiPromptTemplateUpdateInput,- ) =>- request<{ prompt: AiPromptTemplate }>(`/api/v1/ai/prompts/${encodeURIComponent(promptId)}`, {- method: "PATCH",- body: JSON.stringify(payload),- }),-- deleteAiPrompt: (promptId: string) =>- request<{ ok: true }>(`/api/v1/ai/prompts/${encodeURIComponent(promptId)}`, {- method: "DELETE",- }),-- restoreDefaultAiPrompts: (locale?: string) => {- const search = locale ? `?locale=${encodeURIComponent(locale)}` : "";- return request<{ prompts: AiPromptTemplate[]; restoredCount: number }>(`/api/v1/ai/prompts/restore-defaults${search}`, {- method: "POST",- body: JSON.stringify({}),- });- },-- suggestAiTags: (payload: AiTagSuggestionsRequestInput, signal?: AbortSignal) =>- request<AiTagSuggestionsResponse>("/api/v1/ai/tag-suggestions", {- method: "POST",- body: JSON.stringify(payload),- signal,- }),-- streamAiGeneration: async (- payload: AiGenerateInput,- options: { signal?: AbortSignal; onEvent: (event: AiStreamEvent) => void },- ) => {- const headers = new Headers({ "Content-Type": "application/json" });- const sessionToken = typeof window !== "undefined" && window.edgeeverDesktop?.isAvailable- ? getDesktopSessionToken()- : undefined;- if (sessionToken) headers.set("Authorization", `Bearer ${sessionToken}`);- const response = await fetch(`${getConfiguredDesktopApiBaseUrl()}/api/v1/ai/generate`, {- method: "POST",- credentials: "include",- headers,- body: JSON.stringify({- ...payload,- stream: payload.stream ?? readAiStreamingPreference(),- }),- signal: options.signal,- });- if (!response.ok) {- const body = await response.json().catch(() => null) as { error?: { code?: string; message?: string } } | null;- throw new ApiRequestError(body?.error?.message || response.statusText, response.status, body?.error?.code);- }- if (!response.body) throw new ApiRequestError("Streaming response is unavailable", 502, "ai_stream_unavailable");-- const reader = response.body.getReader();- const decoder = new TextDecoder();- let buffer = "";- while (true) {- const { done, value } = await reader.read();- buffer += decoder.decode(value, { stream: !done });- const frames = buffer.split("\n\n");- buffer = frames.pop() ?? "";- for (const frame of frames) {- const data = frame.split("\n").find((line) => line.startsWith("data: "))?.slice(6);- if (data) options.onEvent(JSON.parse(data) as AiStreamEvent);- }- if (done) break;- }- const trailingData = buffer.split("\n").find((line) => line.startsWith("data: "))?.slice(6);- if (trailingData) options.onEvent(JSON.parse(trailingData) as AiStreamEvent);- },-- updateNotebook: (notebookId: string, payload: { name?: string; parentId?: string | null; sortOrder?: number }) =>- request<NotebookResponse>(`/api/v1/notebooks/${notebookId}`, {- method: "PATCH",- body: JSON.stringify(payload),- }),-- deleteNotebook: (notebookId: string) =>- request<{ ok: true }>(`/api/v1/notebooks/${notebookId}`, {- method: "DELETE",- }),-- restoreNotebook: (notebookId: string) =>- request<NotebookResponse>(`/api/v1/notebooks/${notebookId}/restore`, {- method: "POST",- }),-- listTags: () => request<ListTagsResponse>("/api/v1/tags"),-- renameTag: (tag: string, name: string) =>- request<{ ok: true; updated: number }>(`/api/v1/tags/${encodeURIComponent(tag)}`, {- method: "PATCH",- body: JSON.stringify({ name }),- }),-- deleteTag: (tag: string) =>- request<{ ok: true; updated: number }>(`/api/v1/tags/${encodeURIComponent(tag)}`, {- method: "DELETE",- }),-- listApiTokens: () => request<ListApiTokensResponse>("/api/v1/api-tokens"),-- createApiToken: (payload: { name: string; scopes: string[]; expiresAt?: string | null }) =>- request<CreatedApiToken>("/api/v1/api-tokens", {- method: "POST",- body: JSON.stringify(payload),- }),-- revokeApiToken: (tokenId: string) =>- request<{ ok: true }>(`/api/v1/api-tokens/${tokenId}`, {- method: "DELETE",- }),-- listMemos: (params: {- notebookId?: string | null;- includeDescendants?: boolean;- q?: string;- tag?: string;- trash?: boolean;- sort?: MemoSortMode;- filter?: MemoFilterMode;- cursor?: string | null;- limit?: number;- }) => {- const search = new URLSearchParams();-- if (params.notebookId) {- search.set("notebookId", params.notebookId);- }-- if (params.includeDescendants) {- search.set("includeDescendants", "1");- }-- if (params.q?.trim()) {- search.set("q", params.q.trim());- }-- if (params.tag?.trim()) {- search.set("tag", params.tag.trim());- }-- if (params.trash) {- search.set("trash", "1");- }-- if (params.sort) {- search.set("sort", params.sort);- }-- if (params.filter && params.filter !== "all") {- search.set("filter", params.filter);- }-- if (params.cursor) {- search.set("cursor", params.cursor);- }-- if (params.limit) {- search.set("limit", String(params.limit));- }-- return request<ListMemosResponse>(`/api/v1/memos?${search.toString()}`);- },-- createMemo: (payload: { notebookId: string; title?: string; contentMarkdown?: string; tags?: string[]; createdAt?: string; updatedAt?: string }) =>- request<MemoResponse>("/api/v1/memos", {- method: "POST",- body: JSON.stringify(payload),- }),-- listTemplates: () => request<{ templates: MemoTemplate[] }>("/api/v1/templates"),-- createTemplate: (payload: { name: string; description?: string | null; memoId?: string; title?: string | null; contentMarkdown?: string; tags?: string[] }) =>- request<TemplateResponse>("/api/v1/templates", {- method: "POST",- body: JSON.stringify(payload),- }),-- updateTemplate: (templateId: string, payload: { name?: string; description?: string | null; title?: string | null; contentMarkdown?: string; tags?: string[] }) =>- request<TemplateResponse>(`/api/v1/templates/${templateId}`, {- method: "PATCH",- body: JSON.stringify(payload),- }),-- useTemplate: (templateId: string, notebookId: string) =>- request<MemoResponse>(`/api/v1/templates/${templateId}/use`, {- method: "POST",- body: JSON.stringify({ notebookId }),- }),-- deleteTemplate: (templateId: string) =>- request<{ ok: true }>(`/api/v1/templates/${templateId}`, { method: "DELETE" }),-- moveMemos: (payload: { memoIds: string[]; notebookId: string }) =>- request<{ ok: true; moved: number }>("/api/v1/memos/batch/move", {- method: "POST",- body: JSON.stringify(payload),- }),-- deleteMemos: (payload: { memoIds: string[]; permanent?: boolean }) =>- request<{ ok: true; deleted: number }>("/api/v1/memos/batch/delete", {- method: "POST",- body: JSON.stringify(payload),- }),-- emptyTrash: () =>- request<{ ok: true; deleted: number }>("/api/v1/memos/trash/empty", {- method: "DELETE",- }),-- getMemo: (memoId: string, options?: { includeDeleted?: boolean }) => {- const search = new URLSearchParams();-- if (options?.includeDeleted) {- search.set("includeDeleted", "1");+export const api = {+ ...client,++ getSession: async () => {+ const session = await client.getSession();+ if (+ typeof window !== "undefined"+ && window.edgeeverDesktop?.isAvailable+ && !session.authenticated+ && getDesktopSessionToken()+ ) {+ clearCachedDesktopSession();+ desktopSessionRejected = true;+ window.dispatchEvent(new CustomEvent("edgeever:unauthorized"));}-- const suffix = search.toString() ? `?${search.toString()}` : "";- return request<MemoResponse>(`/api/v1/memos/${memoId}${suffix}`);- },-- getMemoShare: (memoId: string) =>- request<MemoShareResponse>(`/api/v1/memos/${memoId}/share`),-- createMemoShare: (memoId: string) =>- request<{ share: MemoShare }>(`/api/v1/memos/${memoId}/share`, {- method: "POST",- body: JSON.stringify({}),- }),-- revokeMemoShare: (memoId: string) =>- request<{ ok: true }>(`/api/v1/memos/${memoId}/share`, { method: "DELETE" }),-- createMemoEditSession: (memoId: string) =>- request<{ editSession: MemoEditSession }>(`/api/v1/memos/${memoId}/edit-sessions`, {- method: "POST",- body: JSON.stringify({}),- }),-- listMemoRevisions: (memoId: string) =>- request<ListMemoRevisionsResponse>(`/api/v1/memos/${memoId}/revisions`),-- restoreMemoRevision: (memoId: string, revisionId: string) =>- request<MemoResponse>(`/api/v1/memos/${memoId}/revisions/${revisionId}/restore`, {- method: "POST",- body: JSON.stringify({}),- }),-- listResources: () => request<ListResourcesResponse>("/api/v1/resources"),-- renameResource: (resourceId: string, filename: string) =>- request<ResourceResponse>(`/api/v1/resources/${encodeURIComponent(resourceId)}`, {- method: "PATCH",- body: JSON.stringify({ filename }),- }),-- deleteResource: (resourceId: string) =>- request<{ ok: true }>(`/api/v1/resources/${encodeURIComponent(resourceId)}`, {- method: "DELETE",- }),-- getMarkdownExportPage: (offset = 0, limit = 50) =>- request<MarkdownExportPage>(`/api/v1/exports/markdown?offset=${offset}&limit=${limit}`),-- getJsonBackupPage: (offset = 0, limit = 25) =>- request<JsonBackupPage>(`/api/v1/backups/json?offset=${offset}&limit=${limit}`),-- restoreJsonNotebooks: (notebooks: JsonBackupNotebook[]) =>- request<{ ok: true }>("/api/v1/restores/json/notebooks", {- method: "POST",- body: JSON.stringify({ notebooks }),- }),-- restoreJsonMemos: (memos: JsonBackupMemo[]) =>- request<{ ok: true }>("/api/v1/restores/json/memos", {- method: "POST",- body: JSON.stringify({ memos }),- }),-- restoreJsonAiPrompts: (prompts: JsonBackupAiPrompt[]) =>- request<{ ok: true }>("/api/v1/restores/json/ai-prompts", {- method: "POST",- body: JSON.stringify({ prompts }),- }),-- restoreJsonResource: (resourceId: string, metadata: JsonBackupMemo["resources"][number], file: Blob) => {- const form = new FormData();- form.append("metadata", JSON.stringify(metadata));- form.append("file", file, metadata.filename || metadata.id);- return request<{ ok: true }>(`/api/v1/restores/json/resources/${encodeURIComponent(resourceId)}`, {- method: "PUT",- body: form,- });+ return session;},- getResourceBlob: async (resourceUrl: string) => {- const baseUrl = getConfiguredDesktopApiBaseUrl();- const response = await fetch(resourceUrl.startsWith("/") ? `${baseUrl}${resourceUrl}` : resourceUrl, { credentials: "include" });-- if (!response.ok) {- if (response.status === 401) {- void notifyUnauthorized(Boolean(window.edgeeverDesktop?.isAvailable));- }-- throw new ApiRequestError(response.statusText || "Resource download failed", response.status);- }-- return response.blob();+ login: async (payload: { username: string; password: string }) => {+ const session = await client.login({ ...payload, deviceId: getOrCreateWebDeviceId() });+ desktopSessionRejected = false;+ return session;},- downloadGithubPluginAsset: (- owner: string,- repository: string,- assetId: number,- assetName: "manifest.json" | "main.js" | "styles.css",- ) => requestArrayBuffer(- `/api/v1/plugins/github/${encodeURIComponent(owner)}/${encodeURIComponent(repository)}/assets/${assetId}/${encodeURIComponent(assetName)}`,+ streamAiGeneration: (+ payload: Parameters<typeof client.streamAiGeneration>[0],+ options: Parameters<typeof client.streamAiGeneration>[1],+ ) => client.streamAiGeneration(+ { ...payload, stream: payload.stream ?? readAiStreamingPreference() },+ options,),-- uploadMemoResource: (memoId: string, file: File) => {- const form = new FormData();- form.append("file", file);-- return request<ResourceResponse>(`/api/v1/memos/${memoId}/resources`, {- method: "POST",- body: form,- });- },-- updateMemo: (- memoId: string,- payload: {- expectedRevision?: number;- expectedContentHash?: string;- editSessionId?: string;- notebookId?: string;- title?: string;- isPinned?: boolean;- contentJson?: TiptapDoc;- contentMarkdown?: string;- tags?: string[];- allowDestructiveOverwrite?: boolean;- }- ) =>- request<MemoResponse>(`/api/v1/memos/${memoId}`, {- method: "PATCH",- body: JSON.stringify(payload),- }),-- deleteMemo: (memoId: string, options?: { permanent?: boolean }) => {- const search = new URLSearchParams();-- if (options?.permanent) {- search.set("permanent", "1");- }-- const suffix = search.toString() ? `?${search.toString()}` : "";- return request<{ ok: true }>(`/api/v1/memos/${memoId}${suffix}`, {- method: "DELETE",- });- },-- restoreMemo: (memoId: string) =>- request<MemoResponse>(`/api/v1/memos/${memoId}/restore`, {- method: "POST",- body: JSON.stringify({}),- }),-- mergeMemos: (payload: { memoIds: string[]; notebookId?: string; title?: string }) =>- request<MemoResponse>("/api/v1/memos/merge", {- method: "POST",- body: JSON.stringify(payload),- }),-- resetDemo: () =>- request<{ success: true }>("/api/v1/demo/reset", {- method: "POST",- }),};diff --git a/apps/web/src/lib/app-helpers.ts b/apps/web/src/lib/app-helpers.tsindex 1300aee2..dbb5427c 100644--- a/apps/web/src/lib/app-helpers.ts+++ b/apps/web/src/lib/app-helpers.ts@@ -1,6 +1,7 @@import type { MemoSummary, Notebook, TiptapDoc } from "@edgeever/shared";import { DEFAULT_MEMO_TITLE } from "@edgeever/shared";import { getMobileNotebookSearchVisibleIds } from "@edgeever/shared/mobile-ui";+import type { MemoFilterMode, MemoSortMode } from "@edgeever/client";import { buildNotebookTree, type NotebookNode, type NotebookNodeComparator } from "./utils";import * as React from "react";import type { ReactNode } from "react";@@ -8,8 +9,7 @@ import type { TFunction } from "i18next";export type Pane = "notebooks" | "memos" | "editor";export type MemoView = "notebook" | "trash";-export type MemoFilterMode = "all" | "tagged" | "untagged" | "pinned";-export type MemoSortMode = "updated-desc" | "created-desc" | "title-asc";+export type { MemoFilterMode, MemoSortMode } from "@edgeever/client";export type NotebookSortMode = "custom" | "name-asc" | "memo-count-desc" | "updated-desc";export type EditorContentAlignment = "start" | "center";export type MemoListDensity = "preview" | "compact";diff --git a/apps/web/src/lib/desktop-sync.ts b/apps/web/src/lib/desktop-sync.tsindex 5ed7005e..165fc903 100644--- a/apps/web/src/lib/desktop-sync.ts+++ b/apps/web/src/lib/desktop-sync.ts@@ -1,6 +1,7 @@import {getMemoSyncBaseConflictDetails,getSyncRetryAt,+ hasSyncStateReset,isMemoSyncBaseCurrent,type DesktopOutboxItem,type DesktopRpcParams,@@ -428,9 +429,7 @@ const applyBootstrap = async (page: SyncBootstrapResponse) => {export const hasDesktopSyncStateReset = (local: { cursor: number; syncIdentity: string },remote: Pick<SyncChangesResponse, "serverCursor" | "syncIdentity">,-) => remote.serverCursor < local.cursor || Boolean(- remote.syncIdentity && remote.syncIdentity !== local.syncIdentity,-);+) => hasSyncStateReset(local, remote);export const classifyDesktopSyncFailure = (item: Pick<DesktopOutboxItem, "kind">, error: unknown) => {const conflict = error instanceof ApiRequestErrordiff --git a/apps/web/src/lib/local-mirror.ts b/apps/web/src/lib/local-mirror.tsindex 0992ae18..a7a5288a 100644--- a/apps/web/src/lib/local-mirror.ts+++ b/apps/web/src/lib/local-mirror.ts@@ -1,4 +1,22 @@-import { createExcerpt, docToMarkdown, docToText, markdownToDoc, mergeMemoDocs, resolveMemoContentDoc, resolveMergedMemoTitle, type MemoDetail, type MemoRevision, type MemoSummary, type MemoTemplate, type Notebook, type ResourceListItem, type TagSummary, type TiptapDoc } from "@edgeever/shared";+import {+ createExcerpt,+ docToMarkdown,+ docToText,+ hasSyncCursorRewound,+ hasSyncStateReset,+ markdownToDoc,+ mergeMemoDocs,+ resolveMemoContentDoc,+ resolveMergedMemoTitle,+ type MemoDetail,+ type MemoRevision,+ type MemoSummary,+ type MemoTemplate,+ type Notebook,+ type ResourceListItem,+ type TagSummary,+ type TiptapDoc,+} from "@edgeever/shared";import { liveQuery } from "dexie";import type { MemoFilterMode, MemoSortMode } from "@/lib/app-helpers";import { api, type SyncChangesResponse } from "@/lib/api";@@ -38,8 +56,7 @@ export const createLocalDataScope = (baseUrl: string, userId?: string | null) =>const getMeta = async (scope: string, key: string) =>(await localDb.syncMeta.get([scope, key]))?.value ?? null;-export const hasLocalSyncCursorRewound = (localCursor: number, serverCursor?: number) =>- typeof serverCursor === "number" && Number.isFinite(serverCursor) && serverCursor < localCursor;+export const hasLocalSyncCursorRewound = hasSyncCursorRewound;export const isLocalMirrorInitialized = async (scope: string) => Boolean(await getMeta(scope, SYNC_IDENTITY_KEY));@@ -147,10 +164,10 @@ const performSyncLocalMirror = async (scope: string) => {let currentCursor = cursor;let response = await api.syncChanges({ cursor: currentCursor, limit: CHANGE_PAGE_SIZE });- if (- hasLocalSyncCursorRewound(currentCursor, response.serverCursor) ||- (response.syncIdentity && response.syncIdentity !== storedIdentity)- ) {+ if (hasSyncStateReset(+ { cursor: currentCursor, syncIdentity: storedIdentity },+ response,+ )) {// Restoring or clearing a server database can restart the change-log// sequence without replacing the workspace row. In that case the saved// browser cursor is ahead of the server and an incremental request looks@@ -172,7 +189,11 @@ const performSyncLocalMirror = async (scope: string) => {if (response.syncIdentity) {await setMeta(scope, SYNC_IDENTITY_KEY, response.syncIdentity);}- if (response.serverCursor > currentCursor && response.changes.length === 0) {+ if (+ typeof response.serverCursor === "number"+ && response.serverCursor > currentCursor+ && response.changes.length === 0+ ) {await setMeta(scope, SYNC_CURSOR_KEY, String(response.cursor));}return { bootstrapped: false, changed };diff --git a/bun.lock b/bun.lockindex fd57b1a8..7addd253 100644--- a/bun.lock+++ b/bun.lock@@ -90,7 +90,7 @@},"apps/desktop": {"name": "@edgeever/desktop",- "version": "1.45.2",+ "version": "1.47.0","dependencies": {"electron-updater": "^6.6.2",},@@ -203,6 +203,7 @@"version": "0.1.3","dependencies": {"@codemirror/lang-markdown": "^6.5.2",+ "@edgeever/client": "workspace:*","@fontsource-variable/noto-sans-sc": "^5.2.8","@tiptap/extension-code-block-lowlight": "3.27.1","@tiptap/pm": "3.27.1",diff --git a/crates/desktop-sidecar/src/catalog.rs b/crates/desktop-sidecar/src/catalog.rsnew file mode 100644index 00000000..2b7b6f7b--- /dev/null+++ b/crates/desktop-sidecar/src/catalog.rs@@ -0,0 +1,370 @@+use rusqlite::Connection;+use serde_json::{json, Value};+use std::time::{SystemTime, UNIX_EPOCH};++use crate::memo::memo_value;+use crate::{enqueue_change, markdown_doc, now_id, string_param, tags_from_json};++pub(crate) fn list_notebooks(database: &Connection) -> Result<Value, String> {+ let mut statement = database.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(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 notebooks n LEFT JOIN memos m ON m.notebook_id = n.id+ WHERE n.is_deleted = 0 GROUP BY n.id ORDER BY n.sort_order, n.name",+ ).map_err(|e| e.to_string())?;+ let rows = statement.query_map([], |row| Ok(json!({+ "id": row.get::<_, String>("id")?, "parentId": row.get::<_, Option<String>>("parent_id")?,+ "name": row.get::<_, String>("name")?, "slug": row.get::<_, Option<String>>("slug")?,+ "icon": row.get::<_, Option<String>>("icon")?, "color": row.get::<_, Option<String>>("color")?,+ "sortOrder": row.get::<_, i64>("sort_order")?, "memoCount": row.get::<_, i64>("memo_count")?,+ "lastMemoUpdatedAt": row.get::<_, Option<String>>("last_memo_updated_at")?,+ "createdAt": row.get::<_, String>("created_at")?, "updatedAt": row.get::<_, String>("updated_at")?,+ }))).map_err(|e| e.to_string())?;+ let notebooks: Result<Vec<_>, _> = rows.collect();+ Ok(json!({ "notebooks": notebooks.map_err(|e| e.to_string())? }))+}++fn notebook_value(+ database: &Connection,+ notebook_id: &str,+ include_deleted: bool,+) -> Result<Value, String> {+ let mut statement = database.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(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 notebooks n LEFT JOIN memos m ON m.notebook_id = n.id+ WHERE n.id = ?1 AND (?2 OR n.is_deleted = 0) GROUP BY n.id",+ ).map_err(|e| e.to_string())?;+ statement.query_row(rusqlite::params![notebook_id, include_deleted as i64], |row| Ok(json!({+ "id": row.get::<_, String>("id")?, "parentId": row.get::<_, Option<String>>("parent_id")?,+ "name": row.get::<_, String>("name")?, "slug": row.get::<_, Option<String>>("slug")?,+ "icon": row.get::<_, Option<String>>("icon")?, "color": row.get::<_, Option<String>>("color")?,+ "sortOrder": row.get::<_, i64>("sort_order")?, "memoCount": row.get::<_, i64>("memo_count")?,+ "lastMemoUpdatedAt": row.get::<_, Option<String>>("last_memo_updated_at")?,+ "createdAt": row.get::<_, String>("created_at")?, "updatedAt": row.get::<_, String>("updated_at")?,+ }))).map_err(|e| e.to_string())+}++pub(crate) fn create_notebook(database: &Connection, params: &Value) -> Result<Value, String> {+ let name = string_param(params, "name")?;+ let parent_id = params.get("parentId").and_then(Value::as_str);+ let id = now_id("nb_local");+ database.execute("INSERT INTO notebooks (id, parent_id, name, slug, sort_order) VALUES (?1, ?2, ?3, ?4, ?5)", rusqlite::params![id, parent_id, name, name.to_lowercase().replace(' ', "-"), SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_millis() as i64]).map_err(|e| e.to_string())?;+ let notebook = notebook_value(database, &id, true)?;+ enqueue_change(+ database,+ "notebook.create",+ &id,+ &json!({ "temporaryId": id, "name": name, "parentId": parent_id }),+ )?;+ Ok(notebook)+}++pub(crate) fn update_notebook(database: &Connection, params: &Value) -> Result<Value, String> {+ let notebook_id = string_param(params, "notebookId")?;+ if let Some(name) = params.get("name").and_then(Value::as_str) {+ database.execute("UPDATE notebooks SET name = ?1, slug = ?2, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?3 AND is_deleted = 0", rusqlite::params![name, name.to_lowercase().replace(' ', "-"), notebook_id]).map_err(|e| e.to_string())?;+ }+ if params.get("parentId").is_some() {+ database.execute("UPDATE notebooks SET parent_id = ?1, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?2 AND is_deleted = 0", rusqlite::params![params.get("parentId").and_then(Value::as_str), notebook_id]).map_err(|e| e.to_string())?;+ }+ if let Some(sort_order) = params.get("sortOrder").and_then(Value::as_i64) {+ database.execute("UPDATE notebooks SET sort_order = ?1, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?2 AND is_deleted = 0", rusqlite::params![sort_order, notebook_id]).map_err(|e| e.to_string())?;+ }+ let notebook = notebook_value(database, ¬ebook_id, true)?;+ enqueue_change(database, "notebook.update", ¬ebook_id, params)?;+ Ok(notebook)+}++pub(crate) fn delete_notebook(database: &Connection, params: &Value) -> Result<Value, String> {+ let notebook_id = string_param(params, "notebookId")?;+ let child_count: i64 = database+ .query_row(+ "SELECT COUNT(*) FROM notebooks WHERE parent_id = ?1 AND is_deleted = 0",+ [¬ebook_id],+ |row| row.get(0),+ )+ .map_err(|e| e.to_string())?;+ let memo_count: i64 = database+ .query_row(+ "SELECT COUNT(*) FROM memos WHERE notebook_id = ?1 AND is_deleted = 0",+ [¬ebook_id],+ |row| row.get(0),+ )+ .map_err(|e| e.to_string())?;+ if child_count > 0 || memo_count > 0 {+ return Err("notebook_not_empty".to_owned());+ }+ database.execute("UPDATE notebooks SET is_deleted = 1, deleted_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?1 AND slug <> 'inbox'", [¬ebook_id]).map_err(|e| e.to_string())?;+ enqueue_change(+ database,+ "notebook.delete",+ ¬ebook_id,+ &json!({ "notebookId": notebook_id }),+ )?;+ Ok(json!({ "ok": true }))+}++pub(crate) fn restore_notebook(database: &Connection, params: &Value) -> Result<Value, String> {+ let notebook_id = string_param(params, "notebookId")?;+ let changed = database.execute("UPDATE notebooks SET is_deleted = 0, deleted_at = NULL, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?1 AND slug <> 'inbox'", [¬ebook_id]).map_err(|e| e.to_string())?;+ if changed == 0 {+ return Err(format!("Notebook not found: {notebook_id}"));+ }+ let notebook = notebook_value(database, ¬ebook_id, true)?;+ enqueue_change(+ database,+ "notebook.restore",+ ¬ebook_id,+ &json!({ "notebookId": notebook_id }),+ )?;+ Ok(notebook)+}++fn template_value(database: &Connection, template_id: &str) -> Result<Value, String> {+ let mut statement = database.prepare("SELECT id, name, description, title, content_json, content_markdown, tags_json, created_at, updated_at FROM memo_templates WHERE id = ?1").map_err(|e| e.to_string())?;+ statement.query_row([template_id], |row| {+ let content_json: String = row.get("content_json")?;+ let tags: String = row.get("tags_json")?;+ Ok(json!({ "id": row.get::<_, String>("id")?, "name": row.get::<_, String>("name")?, "description": row.get::<_, Option<String>>("description")?, "title": row.get::<_, Option<String>>("title")?, "contentJson": serde_json::from_str::<Value>(&content_json).unwrap_or_else(|_| json!({"type":"doc","content":[]})), "contentMarkdown": row.get::<_, String>("content_markdown")?, "tags": tags_from_json(&tags), "createdAt": row.get::<_, String>("created_at")?, "updatedAt": row.get::<_, String>("updated_at")? }))+ }).map_err(|e| e.to_string())+}++pub(crate) fn list_templates(database: &Connection) -> Result<Value, String> {+ let mut statement = database.prepare("SELECT id, name, description, title, content_json, content_markdown, tags_json, created_at, updated_at FROM memo_templates ORDER BY updated_at DESC, name").map_err(|e| e.to_string())?;+ let rows = statement.query_map([], |row| {+ let content_json: String = row.get("content_json")?;+ let tags: String = row.get("tags_json")?;+ Ok(json!({ "id": row.get::<_, String>("id")?, "name": row.get::<_, String>("name")?, "description": row.get::<_, Option<String>>("description")?, "title": row.get::<_, Option<String>>("title")?, "contentJson": serde_json::from_str::<Value>(&content_json).unwrap_or_else(|_| json!({"type":"doc","content":[]})), "contentMarkdown": row.get::<_, String>("content_markdown")?, "tags": tags_from_json(&tags), "createdAt": row.get::<_, String>("created_at")?, "updatedAt": row.get::<_, String>("updated_at")? }))+ }).map_err(|e| e.to_string())?;+ let templates: Result<Vec<_>, _> = rows.collect();+ Ok(json!({ "templates": templates.map_err(|e| e.to_string())? }))+}++pub(crate) fn cache_template(database: &Connection, params: &Value) -> Result<Value, String> {+ let template = params+ .get("template")+ .ok_or_else(|| "Missing template payload".to_owned())?;+ let id = string_param(template, "id")?;+ let name = string_param(template, "name")?;+ let markdown = template+ .get("contentMarkdown")+ .and_then(Value::as_str)+ .unwrap_or("");+ let content_json = template+ .get("contentJson")+ .cloned()+ .unwrap_or_else(|| markdown_doc(markdown));+ let tags = template.get("tags").cloned().unwrap_or_else(|| json!([]));+ database.execute("INSERT INTO memo_templates (id, workspace_id, name, description, title, content_json, content_markdown, tags_json, created_at, updated_at) VALUES (?1, 'ws_default', ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9) ON CONFLICT(id) DO UPDATE SET name=excluded.name, description=excluded.description, title=excluded.title, content_json=excluded.content_json, content_markdown=excluded.content_markdown, tags_json=excluded.tags_json, updated_at=excluded.updated_at", rusqlite::params![id, name, template.get("description").and_then(Value::as_str), template.get("title").and_then(Value::as_str), content_json.to_string(), markdown, tags.to_string(), string_param(template, "createdAt")?, string_param(template, "updatedAt")?]).map_err(|e| e.to_string())?;+ template_value(database, &id).map(|template| json!({ "template": template }))+}++pub(crate) fn create_template(database: &Connection, params: &Value) -> Result<Value, String> {+ let name = string_param(params, "name")?;+ let id = now_id("tpl_local");+ let (title, markdown, tags, content_json) =+ if let Some(memo_id) = params.get("memoId").and_then(Value::as_str) {+ let memo = memo_value(database, memo_id, true)?;+ (+ memo.get("title")+ .and_then(Value::as_str)+ .unwrap_or("")+ .to_owned(),+ memo.get("contentMarkdown")+ .and_then(Value::as_str)+ .unwrap_or("")+ .to_owned(),+ memo.get("tags").cloned().unwrap_or_else(|| json!([])),+ memo.get("contentJson")+ .cloned()+ .unwrap_or_else(|| markdown_doc("")),+ )+ } else {+ let markdown = params+ .get("contentMarkdown")+ .and_then(Value::as_str)+ .unwrap_or("")+ .to_owned();+ (+ params+ .get("title")+ .and_then(Value::as_str)+ .unwrap_or("")+ .to_owned(),+ markdown.clone(),+ params.get("tags").cloned().unwrap_or_else(|| json!([])),+ markdown_doc(&markdown),+ )+ };+ let description = params.get("description").and_then(Value::as_str);+ database.execute("INSERT INTO memo_templates (id, workspace_id, name, description, title, content_json, content_markdown, tags_json) VALUES (?1, 'ws_default', ?2, ?3, ?4, ?5, ?6, ?7)", rusqlite::params![id, name, description, if title.is_empty() { None } else { Some(title.clone()) }, content_json.to_string(), markdown, tags.to_string()]).map_err(|e| e.to_string())?;+ let template = template_value(database, &id)?;+ enqueue_change(+ database,+ "template.create",+ &id,+ &json!({+ "temporaryId": id, "name": name, "description": description,+ "title": if title.is_empty() { Value::Null } else { json!(title) },+ "contentMarkdown": markdown, "tags": tags,+ }),+ )?;+ Ok(template)+}++pub(crate) fn update_template(database: &Connection, params: &Value) -> Result<Value, String> {+ let template_id = string_param(params, "templateId")?;+ let current = template_value(database, &template_id)?;+ let name = params+ .get("name")+ .and_then(Value::as_str)+ .unwrap_or_else(|| current.get("name").and_then(Value::as_str).unwrap_or(""));+ let description = if params.get("description").is_some() {+ params.get("description").and_then(Value::as_str)+ } else {+ current.get("description").and_then(Value::as_str)+ };+ let title = if params.get("title").is_some() {+ params.get("title").and_then(Value::as_str)+ } else {+ current.get("title").and_then(Value::as_str)+ };+ let markdown = params+ .get("contentMarkdown")+ .and_then(Value::as_str)+ .unwrap_or_else(|| {+ current+ .get("contentMarkdown")+ .and_then(Value::as_str)+ .unwrap_or("")+ });+ let tags = params+ .get("tags")+ .cloned()+ .unwrap_or_else(|| current.get("tags").cloned().unwrap_or_else(|| json!([])));+ database.execute("UPDATE memo_templates SET name = ?1, description = ?2, title = ?3, content_json = ?4, content_markdown = ?5, tags_json = ?6, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?7", rusqlite::params![name, description, title, markdown_doc(markdown).to_string(), markdown, tags.to_string(), template_id]).map_err(|e| e.to_string())?;+ let template = template_value(database, &template_id)?;+ enqueue_change(database, "template.update", &template_id, params)?;+ Ok(template)+}++pub(crate) fn delete_template(database: &Connection, params: &Value) -> Result<Value, String> {+ let template_id = string_param(params, "templateId")?;+ database+ .execute("DELETE FROM memo_templates WHERE id = ?1", [&template_id])+ .map_err(|e| e.to_string())?;+ enqueue_change(database, "template.delete", &template_id, params)?;+ Ok(json!({ "ok": true }))+}++pub(crate) fn list_resources(database: &Connection, params: &Value) -> Result<Value, String> {+ let limit = params+ .get("limit")+ .and_then(Value::as_i64)+ .unwrap_or(500)+ .clamp(1, 500);+ let mut statement = database.prepare(+ "SELECT r.id, r.memo_id, r.original_memo_id, r.kind, r.mime_type, r.filename, r.byte_size, r.sha256, r.width, r.height, r.created_at, r.updated_at, m.title, m.excerpt, m.is_deleted+ FROM resources r INNER JOIN memos m ON m.id = r.memo_id+ WHERE r.is_deleted = 0 ORDER BY r.created_at DESC LIMIT ?1",+ ).map_err(|e| e.to_string())?;+ let rows = statement.query_map([limit], |row| Ok(json!({+ "id": row.get::<_, String>("id")?, "memoId": row.get::<_, String>("memo_id")?, "originalMemoId": row.get::<_, Option<String>>("original_memo_id")?,+ "kind": row.get::<_, String>("kind")?, "mimeType": row.get::<_, Option<String>>("mime_type")?, "filename": row.get::<_, Option<String>>("filename")?,+ "byteSize": row.get::<_, i64>("byte_size")?, "sha256": row.get::<_, Option<String>>("sha256")?, "width": row.get::<_, Option<i64>>("width")?, "height": row.get::<_, Option<i64>>("height")?,+ "createdAt": row.get::<_, String>("created_at")?, "updatedAt": row.get::<_, String>("updated_at")?, "url": format!("/api/v1/resources/{}/blob", row.get::<_, String>("id")?),+ "memoTitle": row.get::<_, Option<String>>("title")?, "memoExcerpt": row.get::<_, Option<String>>("excerpt")?, "memoDeleted": row.get::<_, i64>("is_deleted")? != 0+ }))).map_err(|e| e.to_string())?;+ let resources: Result<Vec<_>, _> = rows.collect();+ let stats = database.query_row("SELECT COUNT(*), COALESCE(SUM(byte_size), 0), COALESCE(SUM(CASE WHEN kind = 'image' THEN 1 ELSE 0 END), 0), COALESCE(SUM(CASE WHEN kind = 'attachment' THEN 1 ELSE 0 END), 0) FROM resources WHERE is_deleted = 0", [], |row| Ok(json!({ "totalCount": row.get::<_, i64>(0)?, "totalBytes": row.get::<_, i64>(1)?, "imageCount": row.get::<_, i64>(2)?, "attachmentCount": row.get::<_, i64>(3)? }))).map_err(|e| e.to_string())?;+ Ok(json!({ "resources": resources.map_err(|e| e.to_string())?, "summary": stats }))+}++pub(crate) fn cache_resource(database: &Connection, params: &Value) -> Result<Value, String> {+ let resource = params+ .get("resource")+ .ok_or_else(|| "Missing resource payload".to_owned())?;+ let id = string_param(resource, "id")?;+ let memo_id = string_param(resource, "memoId")?;+ database.execute("INSERT INTO resources (id, memo_id, original_memo_id, bucket_name, object_key, kind, mime_type, filename, byte_size, sha256, width, height, metadata_json) VALUES (?1, ?2, ?3, 'edgeever-resources', ?1, ?4, ?5, ?6, ?7, ?8, ?9, ?10, '{}') ON CONFLICT(id) DO UPDATE SET memo_id=excluded.memo_id, kind=excluded.kind, mime_type=excluded.mime_type, filename=excluded.filename, byte_size=excluded.byte_size, sha256=excluded.sha256, width=excluded.width, height=excluded.height, is_deleted=0, updated_at=strftime('%Y-%m-%dT%H:%M:%fZ','now')", rusqlite::params![id, memo_id, resource.get("originalMemoId").and_then(Value::as_str), string_param(resource, "kind")?, resource.get("mimeType").and_then(Value::as_str), resource.get("filename").and_then(Value::as_str), resource.get("byteSize").and_then(Value::as_i64).unwrap_or(0), resource.get("sha256").and_then(Value::as_str), resource.get("width").and_then(Value::as_i64), resource.get("height").and_then(Value::as_i64)]).map_err(|e| e.to_string())?;+ Ok(json!({ "ok": true }))+}++pub(crate) fn delete_cached_resource(+ database: &Connection,+ params: &Value,+) -> Result<Value, String> {+ let resource_id = string_param(params, "resourceId")?;+ database+ .execute("DELETE FROM resources WHERE id = ?1", [&resource_id])+ .map_err(|e| e.to_string())?;+ Ok(json!({ "ok": true }))+}++pub(crate) fn list_tags(database: &Connection) -> Result<Value, String> {+ let mut statement = database.prepare(+ "SELECT trim(j.value) AS name, COUNT(DISTINCT m.id) AS memo_count, MAX(m.updated_at) AS updated_at+ FROM memos m, json_each(m.tags_json) j+ WHERE m.is_deleted = 0 AND trim(j.value) <> ''+ GROUP BY trim(j.value) ORDER BY name COLLATE NOCASE",+ ).map_err(|e| e.to_string())?;+ let rows = statement.query_map([], |row| Ok(json!({ "name": row.get::<_, String>("name")?, "memoCount": row.get::<_, i64>("memo_count")?, "updatedAt": row.get::<_, Option<String>>("updated_at")? }))).map_err(|e| e.to_string())?;+ let tags: Result<Vec<_>, _> = rows.collect();+ Ok(json!({ "tags": tags.map_err(|e| e.to_string())? }))+}++pub(crate) fn rewrite_tag(+ database: &Connection,+ params: &Value,+ delete: bool,+) -> Result<Value, String> {+ let tag = string_param(params, "tag")?;+ let replacement = params+ .get("name")+ .and_then(Value::as_str)+ .map(str::to_owned);+ let mut statement = database+ .prepare("SELECT id, tags_json FROM memos WHERE is_deleted = 0")+ .map_err(|e| e.to_string())?;+ let rows: Vec<(String, String)> = statement+ .query_map([], |row| Ok((row.get(0)?, row.get(1)?)))+ .map_err(|e| e.to_string())?+ .collect::<Result<_, _>>()+ .map_err(|e| e.to_string())?;+ let tx = database+ .unchecked_transaction()+ .map_err(|e| e.to_string())?;+ let mut updated = 0;+ for (memo_id, tags_json) in rows {+ let mut tags: Vec<String> = serde_json::from_str(&tags_json).unwrap_or_default();+ let mut changed = false;+ for value in &mut tags {+ if value == &tag {+ changed = true;+ if delete {+ value.clear();+ } else if let Some(name) = replacement.as_ref() {+ *value = name.clone();+ }+ }+ }+ tags.retain(|value| !value.is_empty());+ tags.sort();+ tags.dedup();+ if changed {+ tx.execute("UPDATE memos SET tags_json = ?1, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), updated_by = 'desktop' WHERE id = ?2", rusqlite::params![serde_json::to_string(&tags).unwrap_or_else(|_| "[]".to_owned()), memo_id]).map_err(|e| e.to_string())?;+ updated += 1;+ }+ }+ tx.commit().map_err(|e| e.to_string())?;+ enqueue_change(+ database,+ if delete { "tag.delete" } else { "tag.rename" },+ &tag,+ params,+ )?;+ Ok(json!({ "ok": true, "updated": updated }))+}diff --git a/crates/desktop-sidecar/src/main.rs b/crates/desktop-sidecar/src/main.rsindex f44ac14b..115ceecf 100644--- a/crates/desktop-sidecar/src/main.rs+++ b/crates/desktop-sidecar/src/main.rs@@ -1,33 +1,17 @@+mod catalog;mod database;+mod memo;+mod rpc;+mod sync;-use database::{- backup_database, data_dir, list_backups, migrations_dir, open_database, restore_database,-};+use database::{data_dir, migrations_dir, open_database};+use rpc::{handle, RpcError, RpcRequest, PROTOCOL_VERSION};use rusqlite::{Connection, OptionalExtension};-use serde::{Deserialize, Serialize};use serde_json::{json, Value};use sha2::{Digest, Sha256};-use std::env;use std::io::{self, BufRead, Write};-use std::path::Path;use std::time::{SystemTime, UNIX_EPOCH};-const PROTOCOL_VERSION: i64 = 2;--#[derive(Debug, Deserialize)]-struct RpcRequest {- id: Value,- method: String,- #[serde(default)]- params: Value,-}--#[derive(Debug, Serialize)]-struct RpcError<'a> {- code: &'a str,- message: String,-}-fn enqueue_change(database: &Connection,kind: &str,@@ -178,1819 +162,6 @@ fn tags_from_json(value: &str) -> Vec<String> {serde_json::from_str(value).unwrap_or_default()}-fn summary_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Value> {- let tags: String = row.get("tags_json")?;- Ok(json!({- "id": row.get::<_, String>("id")?,- "notebookId": row.get::<_, String>("notebook_id")?,- "title": row.get::<_, Option<String>>("title")?,- "excerpt": row.get::<_, String>("excerpt")?,- "tags": tags_from_json(&tags),- "isPinned": row.get::<_, i64>("is_pinned")? != 0,- "isArchived": row.get::<_, i64>("is_archived")? != 0,- "isDeleted": row.get::<_, i64>("is_deleted")? != 0,- "revision": row.get::<_, i64>("revision")?,- "createdAt": row.get::<_, String>("created_at")?,- "updatedAt": row.get::<_, String>("updated_at")?,- "deletedAt": row.get::<_, Option<String>>("deleted_at")?,- }))-}--fn memo_value(- database: &Connection,- memo_id: &str,- include_deleted: bool,-) -> Result<Value, String> {- let mut statement = database.prepare(- "SELECT m.id, m.notebook_id, m.title, m.excerpt, m.tags_json, m.is_pinned, m.is_archived, m.is_deleted,- m.source_memo_ids, m.merge_source_count, m.merged_into_memo_id, m.created_at, m.updated_at, m.deleted_at,- c.content_json, c.content_markdown, c.content_text, c.content_hash, c.revision- FROM memos m JOIN memo_contents c ON c.memo_id = m.id- WHERE m.id = ?1 AND (?2 OR m.is_deleted = 0)",- ).map_err(|e| e.to_string())?;- statement.query_row(rusqlite::params![memo_id, include_deleted as i64], |row| {- let tags: String = row.get("tags_json")?;- let source_ids: String = row.get("source_memo_ids")?;- let content_json: String = row.get("content_json")?;- Ok(json!({- "id": row.get::<_, String>("id")?, "notebookId": row.get::<_, String>("notebook_id")?,- "title": row.get::<_, Option<String>>("title")?, "excerpt": row.get::<_, String>("excerpt")?,- "tags": tags_from_json(&tags), "isPinned": row.get::<_, i64>("is_pinned")? != 0,- "isArchived": row.get::<_, i64>("is_archived")? != 0, "isDeleted": row.get::<_, i64>("is_deleted")? != 0,- "revision": row.get::<_, i64>("revision")?, "createdAt": row.get::<_, String>("created_at")?,- "updatedAt": row.get::<_, String>("updated_at")?, "deletedAt": row.get::<_, Option<String>>("deleted_at")?,- "contentJson": serde_json::from_str::<Value>(&content_json).unwrap_or_else(|_| json!({"type":"doc","content":[]})),- "contentMarkdown": row.get::<_, String>("content_markdown")?, "contentText": row.get::<_, String>("content_text")?,- "contentHash": row.get::<_, String>("content_hash")?, "sourceMemoIds": tags_from_json(&source_ids),- "mergeSourceCount": row.get::<_, i64>("merge_source_count")?, "mergedIntoMemoId": row.get::<_, Option<String>>("merged_into_memo_id")?,- }))- }).map_err(|e| e.to_string())-}--fn insert_revision(- transaction: &rusqlite::Transaction<'_>,- memo: &Value,- created_by: &str,-) -> Result<(), String> {- let memo_id = string_param(memo, "id")?;- let content_json = memo- .get("contentJson")- .cloned()- .unwrap_or_else(|| json!({"type":"doc","content":[]}));- let tags = memo.get("tags").cloned().unwrap_or_else(|| json!([]));- transaction.execute(- "INSERT INTO memo_revisions (id, memo_id, revision, title, content_json, content_markdown, content_hash, created_by, created_at, tags_json, content_text) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, strftime('%Y-%m-%dT%H:%M:%fZ','now'), ?9, ?10)",- rusqlite::params![- now_id("revision_local"), memo_id,- memo.get("revision").and_then(Value::as_i64).unwrap_or(0),- memo.get("title").and_then(Value::as_str), content_json.to_string(),- memo.get("contentMarkdown").and_then(Value::as_str).unwrap_or(""),- memo.get("contentHash").and_then(Value::as_str).unwrap_or(""), created_by,- tags.to_string(), memo.get("contentText").and_then(Value::as_str).unwrap_or(""),- ],- ).map(|_| ()).map_err(|e| e.to_string())-}--fn revision_value(- database: &Connection,- memo_id: &str,- revision_id: &str,-) -> Result<Value, String> {- database.query_row(- "SELECT id, memo_id, revision, title, tags_json, content_json, content_markdown, content_text, content_hash, created_by, created_at FROM memo_revisions WHERE id = ?1 AND memo_id = ?2",- rusqlite::params![revision_id, memo_id],- |row| {- let tags: String = row.get(4)?;- let content_json: String = row.get(5)?;- Ok(json!({- "id": row.get::<_, String>(0)?, "memoId": row.get::<_, String>(1)?, "revision": row.get::<_, i64>(2)?,- "title": row.get::<_, Option<String>>(3)?, "tags": tags_from_json(&tags),- "contentJson": serde_json::from_str::<Value>(&content_json).unwrap_or_else(|_| json!({"type":"doc","content":[]})),- "contentMarkdown": row.get::<_, String>(6)?, "contentText": row.get::<_, String>(7)?,- "contentHash": row.get::<_, String>(8)?, "createdBy": row.get::<_, String>(9)?, "createdAt": row.get::<_, String>(10)?,- }))- },- ).map_err(|e| e.to_string())-}--fn list_memo_revisions(database: &Connection, params: &Value) -> Result<Value, String> {- let memo_id = string_param(params, "memoId")?;- let limit = params- .get("limit")- .and_then(Value::as_i64)- .unwrap_or(100)- .clamp(1, 200);- let mut statement = database.prepare("SELECT id, memo_id, revision, title, tags_json, content_json, content_markdown, content_text, content_hash, created_by, created_at FROM memo_revisions WHERE memo_id = ?1 ORDER BY revision DESC, created_at DESC LIMIT ?2").map_err(|e| e.to_string())?;- let rows = statement.query_map(rusqlite::params![memo_id, limit], |row| {- let tags: String = row.get(4)?;- let content_json: String = row.get(5)?;- Ok(json!({- "id": row.get::<_, String>(0)?, "memoId": row.get::<_, String>(1)?, "revision": row.get::<_, i64>(2)?,- "title": row.get::<_, Option<String>>(3)?, "tags": tags_from_json(&tags),- "contentJson": serde_json::from_str::<Value>(&content_json).unwrap_or_else(|_| json!({"type":"doc","content":[]})),- "contentMarkdown": row.get::<_, String>(6)?, "contentText": row.get::<_, String>(7)?,- "contentHash": row.get::<_, String>(8)?, "createdBy": row.get::<_, String>(9)?, "createdAt": row.get::<_, String>(10)?,- }))- }).map_err(|e| e.to_string())?;- let revisions: Result<Vec<_>, _> = rows.collect();- Ok(json!({ "revisions": revisions.map_err(|e| e.to_string())? }))-}--fn cache_memo_revision(database: &Connection, params: &Value) -> Result<Value, String> {- let revision = params- .get("revision")- .ok_or_else(|| "Missing revision".to_owned())?;- let memo_id = string_param(revision, "memoId")?;- let revision_id = string_param(revision, "id")?;- let content_json = revision- .get("contentJson")- .cloned()- .unwrap_or_else(|| json!({"type":"doc","content":[]}));- let tags = revision.get("tags").cloned().unwrap_or_else(|| json!([]));- database.execute(- "INSERT INTO memo_revisions (id, memo_id, revision, title, content_json, content_markdown, content_hash, created_by, created_at, tags_json, content_text) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11) ON CONFLICT(id) DO UPDATE SET memo_id=excluded.memo_id, revision=excluded.revision, title=excluded.title, content_json=excluded.content_json, content_markdown=excluded.content_markdown, content_hash=excluded.content_hash, created_by=excluded.created_by, created_at=excluded.created_at, tags_json=excluded.tags_json, content_text=excluded.content_text",- rusqlite::params![- revision_id, memo_id, revision.get("revision").and_then(Value::as_i64).unwrap_or(0),- revision.get("title").and_then(Value::as_str), content_json.to_string(),- revision.get("contentMarkdown").and_then(Value::as_str).unwrap_or(""),- revision.get("contentHash").and_then(Value::as_str).unwrap_or(""),- revision.get("createdBy").and_then(Value::as_str).unwrap_or("remote"),- revision.get("createdAt").and_then(Value::as_str).unwrap_or(""), tags.to_string(),- revision.get("contentText").and_then(Value::as_str).unwrap_or(""),- ],- ).map_err(|e| e.to_string())?;- Ok(json!({ "ok": true }))-}--fn list_notebooks(database: &Connection) -> Result<Value, String> {- let mut statement = database.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(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 notebooks n LEFT JOIN memos m ON m.notebook_id = n.id- WHERE n.is_deleted = 0 GROUP BY n.id ORDER BY n.sort_order, n.name",- ).map_err(|e| e.to_string())?;- let rows = statement.query_map([], |row| Ok(json!({- "id": row.get::<_, String>("id")?, "parentId": row.get::<_, Option<String>>("parent_id")?,- "name": row.get::<_, String>("name")?, "slug": row.get::<_, Option<String>>("slug")?,- "icon": row.get::<_, Option<String>>("icon")?, "color": row.get::<_, Option<String>>("color")?,- "sortOrder": row.get::<_, i64>("sort_order")?, "memoCount": row.get::<_, i64>("memo_count")?,- "lastMemoUpdatedAt": row.get::<_, Option<String>>("last_memo_updated_at")?,- "createdAt": row.get::<_, String>("created_at")?, "updatedAt": row.get::<_, String>("updated_at")?,- }))).map_err(|e| e.to_string())?;- let notebooks: Result<Vec<_>, _> = rows.collect();- Ok(json!({ "notebooks": notebooks.map_err(|e| e.to_string())? }))-}--fn notebook_value(- database: &Connection,- notebook_id: &str,- include_deleted: bool,-) -> Result<Value, String> {- let mut statement = database.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(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 notebooks n LEFT JOIN memos m ON m.notebook_id = n.id- WHERE n.id = ?1 AND (?2 OR n.is_deleted = 0) GROUP BY n.id",- ).map_err(|e| e.to_string())?;- statement.query_row(rusqlite::params![notebook_id, include_deleted as i64], |row| Ok(json!({- "id": row.get::<_, String>("id")?, "parentId": row.get::<_, Option<String>>("parent_id")?,- "name": row.get::<_, String>("name")?, "slug": row.get::<_, Option<String>>("slug")?,- "icon": row.get::<_, Option<String>>("icon")?, "color": row.get::<_, Option<String>>("color")?,- "sortOrder": row.get::<_, i64>("sort_order")?, "memoCount": row.get::<_, i64>("memo_count")?,- "lastMemoUpdatedAt": row.get::<_, Option<String>>("last_memo_updated_at")?,- "createdAt": row.get::<_, String>("created_at")?, "updatedAt": row.get::<_, String>("updated_at")?,- }))).map_err(|e| e.to_string())-}--fn create_notebook(database: &Connection, params: &Value) -> Result<Value, String> {- let name = string_param(params, "name")?;- let parent_id = params.get("parentId").and_then(Value::as_str);- let id = now_id("nb_local");- database.execute("INSERT INTO notebooks (id, parent_id, name, slug, sort_order) VALUES (?1, ?2, ?3, ?4, ?5)", rusqlite::params![id, parent_id, name, name.to_lowercase().replace(' ', "-"), SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_millis() as i64]).map_err(|e| e.to_string())?;- let notebook = notebook_value(database, &id, true)?;- enqueue_change(- database,- "notebook.create",- &id,- &json!({ "temporaryId": id, "name": name, "parentId": parent_id }),- )?;- Ok(notebook)-}--fn update_notebook(database: &Connection, params: &Value) -> Result<Value, String> {- let notebook_id = string_param(params, "notebookId")?;- if let Some(name) = params.get("name").and_then(Value::as_str) {- database.execute("UPDATE notebooks SET name = ?1, slug = ?2, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?3 AND is_deleted = 0", rusqlite::params![name, name.to_lowercase().replace(' ', "-"), notebook_id]).map_err(|e| e.to_string())?;- }- if params.get("parentId").is_some() {- database.execute("UPDATE notebooks SET parent_id = ?1, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?2 AND is_deleted = 0", rusqlite::params![params.get("parentId").and_then(Value::as_str), notebook_id]).map_err(|e| e.to_string())?;- }- if let Some(sort_order) = params.get("sortOrder").and_then(Value::as_i64) {- database.execute("UPDATE notebooks SET sort_order = ?1, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?2 AND is_deleted = 0", rusqlite::params![sort_order, notebook_id]).map_err(|e| e.to_string())?;- }- let notebook = notebook_value(database, ¬ebook_id, true)?;- enqueue_change(database, "notebook.update", ¬ebook_id, params)?;- Ok(notebook)-}--fn delete_notebook(database: &Connection, params: &Value) -> Result<Value, String> {- let notebook_id = string_param(params, "notebookId")?;- let child_count: i64 = database- .query_row(- "SELECT COUNT(*) FROM notebooks WHERE parent_id = ?1 AND is_deleted = 0",- [¬ebook_id],- |row| row.get(0),- )- .map_err(|e| e.to_string())?;- let memo_count: i64 = database- .query_row(- "SELECT COUNT(*) FROM memos WHERE notebook_id = ?1 AND is_deleted = 0",- [¬ebook_id],- |row| row.get(0),- )- .map_err(|e| e.to_string())?;- if child_count > 0 || memo_count > 0 {- return Err("notebook_not_empty".to_owned());- }- database.execute("UPDATE notebooks SET is_deleted = 1, deleted_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?1 AND slug <> 'inbox'", [¬ebook_id]).map_err(|e| e.to_string())?;- enqueue_change(- database,- "notebook.delete",- ¬ebook_id,- &json!({ "notebookId": notebook_id }),- )?;- Ok(json!({ "ok": true }))-}--fn restore_notebook(database: &Connection, params: &Value) -> Result<Value, String> {- let notebook_id = string_param(params, "notebookId")?;- let changed = database.execute("UPDATE notebooks SET is_deleted = 0, deleted_at = NULL, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?1 AND slug <> 'inbox'", [¬ebook_id]).map_err(|e| e.to_string())?;- if changed == 0 {- return Err(format!("Notebook not found: {notebook_id}"));- }- let notebook = notebook_value(database, ¬ebook_id, true)?;- enqueue_change(- database,- "notebook.restore",- ¬ebook_id,- &json!({ "notebookId": notebook_id }),- )?;- Ok(notebook)-}--fn template_value(database: &Connection, template_id: &str) -> Result<Value, String> {- let mut statement = database.prepare("SELECT id, name, description, title, content_json, content_markdown, tags_json, created_at, updated_at FROM memo_templates WHERE id = ?1").map_err(|e| e.to_string())?;- statement.query_row([template_id], |row| {- let content_json: String = row.get("content_json")?;- let tags: String = row.get("tags_json")?;- Ok(json!({ "id": row.get::<_, String>("id")?, "name": row.get::<_, String>("name")?, "description": row.get::<_, Option<String>>("description")?, "title": row.get::<_, Option<String>>("title")?, "contentJson": serde_json::from_str::<Value>(&content_json).unwrap_or_else(|_| json!({"type":"doc","content":[]})), "contentMarkdown": row.get::<_, String>("content_markdown")?, "tags": tags_from_json(&tags), "createdAt": row.get::<_, String>("created_at")?, "updatedAt": row.get::<_, String>("updated_at")? }))- }).map_err(|e| e.to_string())-}--fn list_templates(database: &Connection) -> Result<Value, String> {- let mut statement = database.prepare("SELECT id, name, description, title, content_json, content_markdown, tags_json, created_at, updated_at FROM memo_templates ORDER BY updated_at DESC, name").map_err(|e| e.to_string())?;- let rows = statement.query_map([], |row| {- let content_json: String = row.get("content_json")?;- let tags: String = row.get("tags_json")?;- Ok(json!({ "id": row.get::<_, String>("id")?, "name": row.get::<_, String>("name")?, "description": row.get::<_, Option<String>>("description")?, "title": row.get::<_, Option<String>>("title")?, "contentJson": serde_json::from_str::<Value>(&content_json).unwrap_or_else(|_| json!({"type":"doc","content":[]})), "contentMarkdown": row.get::<_, String>("content_markdown")?, "tags": tags_from_json(&tags), "createdAt": row.get::<_, String>("created_at")?, "updatedAt": row.get::<_, String>("updated_at")? }))- }).map_err(|e| e.to_string())?;- let templates: Result<Vec<_>, _> = rows.collect();- Ok(json!({ "templates": templates.map_err(|e| e.to_string())? }))-}--fn cache_template(database: &Connection, params: &Value) -> Result<Value, String> {- let template = params- .get("template")- .ok_or_else(|| "Missing template payload".to_owned())?;- let id = string_param(template, "id")?;- let name = string_param(template, "name")?;- let markdown = template- .get("contentMarkdown")- .and_then(Value::as_str)- .unwrap_or("");- let content_json = template- .get("contentJson")- .cloned()- .unwrap_or_else(|| markdown_doc(markdown));- let tags = template.get("tags").cloned().unwrap_or_else(|| json!([]));- database.execute("INSERT INTO memo_templates (id, workspace_id, name, description, title, content_json, content_markdown, tags_json, created_at, updated_at) VALUES (?1, 'ws_default', ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9) ON CONFLICT(id) DO UPDATE SET name=excluded.name, description=excluded.description, title=excluded.title, content_json=excluded.content_json, content_markdown=excluded.content_markdown, tags_json=excluded.tags_json, updated_at=excluded.updated_at", rusqlite::params![id, name, template.get("description").and_then(Value::as_str), template.get("title").and_then(Value::as_str), content_json.to_string(), markdown, tags.to_string(), string_param(template, "createdAt")?, string_param(template, "updatedAt")?]).map_err(|e| e.to_string())?;- template_value(database, &id).map(|template| json!({ "template": template }))-}--fn create_template(database: &Connection, params: &Value) -> Result<Value, String> {- let name = string_param(params, "name")?;- let id = now_id("tpl_local");- let (title, markdown, tags, content_json) =- if let Some(memo_id) = params.get("memoId").and_then(Value::as_str) {- let memo = memo_value(database, memo_id, true)?;- (- memo.get("title")- .and_then(Value::as_str)- .unwrap_or("")- .to_owned(),- memo.get("contentMarkdown")- .and_then(Value::as_str)- .unwrap_or("")- .to_owned(),- memo.get("tags").cloned().unwrap_or_else(|| json!([])),- memo.get("contentJson")- .cloned()- .unwrap_or_else(|| markdown_doc("")),- )- } else {- let markdown = params- .get("contentMarkdown")- .and_then(Value::as_str)- .unwrap_or("")- .to_owned();- (- params- .get("title")- .and_then(Value::as_str)- .unwrap_or("")- .to_owned(),- markdown.clone(),- params.get("tags").cloned().unwrap_or_else(|| json!([])),- markdown_doc(&markdown),- )- };- let description = params.get("description").and_then(Value::as_str);- database.execute("INSERT INTO memo_templates (id, workspace_id, name, description, title, content_json, content_markdown, tags_json) VALUES (?1, 'ws_default', ?2, ?3, ?4, ?5, ?6, ?7)", rusqlite::params![id, name, description, if title.is_empty() { None } else { Some(title.clone()) }, content_json.to_string(), markdown, tags.to_string()]).map_err(|e| e.to_string())?;- let template = template_value(database, &id)?;- enqueue_change(- database,- "template.create",- &id,- &json!({- "temporaryId": id, "name": name, "description": description,- "title": if title.is_empty() { Value::Null } else { json!(title) },- "contentMarkdown": markdown, "tags": tags,- }),- )?;- Ok(template)-}--fn update_template(database: &Connection, params: &Value) -> Result<Value, String> {- let template_id = string_param(params, "templateId")?;- let current = template_value(database, &template_id)?;- let name = params- .get("name")- .and_then(Value::as_str)- .unwrap_or_else(|| current.get("name").and_then(Value::as_str).unwrap_or(""));- let description = if params.get("description").is_some() {- params.get("description").and_then(Value::as_str)- } else {- current.get("description").and_then(Value::as_str)- };- let title = if params.get("title").is_some() {- params.get("title").and_then(Value::as_str)- } else {- current.get("title").and_then(Value::as_str)- };- let markdown = params- .get("contentMarkdown")- .and_then(Value::as_str)- .unwrap_or_else(|| {- current- .get("contentMarkdown")- .and_then(Value::as_str)- .unwrap_or("")- });- let tags = params- .get("tags")- .cloned()- .unwrap_or_else(|| current.get("tags").cloned().unwrap_or_else(|| json!([])));- database.execute("UPDATE memo_templates SET name = ?1, description = ?2, title = ?3, content_json = ?4, content_markdown = ?5, tags_json = ?6, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?7", rusqlite::params![name, description, title, markdown_doc(markdown).to_string(), markdown, tags.to_string(), template_id]).map_err(|e| e.to_string())?;- let template = template_value(database, &template_id)?;- enqueue_change(database, "template.update", &template_id, params)?;- Ok(template)-}--fn delete_template(database: &Connection, params: &Value) -> Result<Value, String> {- let template_id = string_param(params, "templateId")?;- database- .execute("DELETE FROM memo_templates WHERE id = ?1", [&template_id])- .map_err(|e| e.to_string())?;- enqueue_change(database, "template.delete", &template_id, params)?;- Ok(json!({ "ok": true }))-}--fn list_resources(database: &Connection, params: &Value) -> Result<Value, String> {- let limit = params- .get("limit")- .and_then(Value::as_i64)- .unwrap_or(500)- .clamp(1, 500);- let mut statement = database.prepare(- "SELECT r.id, r.memo_id, r.original_memo_id, r.kind, r.mime_type, r.filename, r.byte_size, r.sha256, r.width, r.height, r.created_at, r.updated_at, m.title, m.excerpt, m.is_deleted- FROM resources r INNER JOIN memos m ON m.id = r.memo_id- WHERE r.is_deleted = 0 ORDER BY r.created_at DESC LIMIT ?1",- ).map_err(|e| e.to_string())?;- let rows = statement.query_map([limit], |row| Ok(json!({- "id": row.get::<_, String>("id")?, "memoId": row.get::<_, String>("memo_id")?, "originalMemoId": row.get::<_, Option<String>>("original_memo_id")?,- "kind": row.get::<_, String>("kind")?, "mimeType": row.get::<_, Option<String>>("mime_type")?, "filename": row.get::<_, Option<String>>("filename")?,- "byteSize": row.get::<_, i64>("byte_size")?, "sha256": row.get::<_, Option<String>>("sha256")?, "width": row.get::<_, Option<i64>>("width")?, "height": row.get::<_, Option<i64>>("height")?,- "createdAt": row.get::<_, String>("created_at")?, "updatedAt": row.get::<_, String>("updated_at")?, "url": format!("/api/v1/resources/{}/blob", row.get::<_, String>("id")?),- "memoTitle": row.get::<_, Option<String>>("title")?, "memoExcerpt": row.get::<_, Option<String>>("excerpt")?, "memoDeleted": row.get::<_, i64>("is_deleted")? != 0- }))).map_err(|e| e.to_string())?;- let resources: Result<Vec<_>, _> = rows.collect();- let stats = database.query_row("SELECT COUNT(*), COALESCE(SUM(byte_size), 0), COALESCE(SUM(CASE WHEN kind = 'image' THEN 1 ELSE 0 END), 0), COALESCE(SUM(CASE WHEN kind = 'attachment' THEN 1 ELSE 0 END), 0) FROM resources WHERE is_deleted = 0", [], |row| Ok(json!({ "totalCount": row.get::<_, i64>(0)?, "totalBytes": row.get::<_, i64>(1)?, "imageCount": row.get::<_, i64>(2)?, "attachmentCount": row.get::<_, i64>(3)? }))).map_err(|e| e.to_string())?;- Ok(json!({ "resources": resources.map_err(|e| e.to_string())?, "summary": stats }))-}--fn cache_resource(database: &Connection, params: &Value) -> Result<Value, String> {- let resource = params- .get("resource")- .ok_or_else(|| "Missing resource payload".to_owned())?;- let id = string_param(resource, "id")?;- let memo_id = string_param(resource, "memoId")?;- database.execute("INSERT INTO resources (id, memo_id, original_memo_id, bucket_name, object_key, kind, mime_type, filename, byte_size, sha256, width, height, metadata_json) VALUES (?1, ?2, ?3, 'edgeever-resources', ?1, ?4, ?5, ?6, ?7, ?8, ?9, ?10, '{}') ON CONFLICT(id) DO UPDATE SET memo_id=excluded.memo_id, kind=excluded.kind, mime_type=excluded.mime_type, filename=excluded.filename, byte_size=excluded.byte_size, sha256=excluded.sha256, width=excluded.width, height=excluded.height, is_deleted=0, updated_at=strftime('%Y-%m-%dT%H:%M:%fZ','now')", rusqlite::params![id, memo_id, resource.get("originalMemoId").and_then(Value::as_str), string_param(resource, "kind")?, resource.get("mimeType").and_then(Value::as_str), resource.get("filename").and_then(Value::as_str), resource.get("byteSize").and_then(Value::as_i64).unwrap_or(0), resource.get("sha256").and_then(Value::as_str), resource.get("width").and_then(Value::as_i64), resource.get("height").and_then(Value::as_i64)]).map_err(|e| e.to_string())?;- Ok(json!({ "ok": true }))-}--fn delete_cached_resource(database: &Connection, params: &Value) -> Result<Value, String> {- let resource_id = string_param(params, "resourceId")?;- database- .execute("DELETE FROM resources WHERE id = ?1", [&resource_id])- .map_err(|e| e.to_string())?;- Ok(json!({ "ok": true }))-}--fn list_tags(database: &Connection) -> Result<Value, String> {- let mut statement = database.prepare(- "SELECT trim(j.value) AS name, COUNT(DISTINCT m.id) AS memo_count, MAX(m.updated_at) AS updated_at- FROM memos m, json_each(m.tags_json) j- WHERE m.is_deleted = 0 AND trim(j.value) <> ''- GROUP BY trim(j.value) ORDER BY name COLLATE NOCASE",- ).map_err(|e| e.to_string())?;- let rows = statement.query_map([], |row| Ok(json!({ "name": row.get::<_, String>("name")?, "memoCount": row.get::<_, i64>("memo_count")?, "updatedAt": row.get::<_, Option<String>>("updated_at")? }))).map_err(|e| e.to_string())?;- let tags: Result<Vec<_>, _> = rows.collect();- Ok(json!({ "tags": tags.map_err(|e| e.to_string())? }))-}--fn rewrite_tag(database: &Connection, params: &Value, delete: bool) -> Result<Value, String> {- let tag = string_param(params, "tag")?;- let replacement = params- .get("name")- .and_then(Value::as_str)- .map(str::to_owned);- let mut statement = database- .prepare("SELECT id, tags_json FROM memos WHERE is_deleted = 0")- .map_err(|e| e.to_string())?;- let rows: Vec<(String, String)> = statement- .query_map([], |row| Ok((row.get(0)?, row.get(1)?)))- .map_err(|e| e.to_string())?- .collect::<Result<_, _>>()- .map_err(|e| e.to_string())?;- let tx = database- .unchecked_transaction()- .map_err(|e| e.to_string())?;- let mut updated = 0;- for (memo_id, tags_json) in rows {- let mut tags: Vec<String> = serde_json::from_str(&tags_json).unwrap_or_default();- let mut changed = false;- for value in &mut tags {- if value == &tag {- changed = true;- if delete {- value.clear();- } else if let Some(name) = replacement.as_ref() {- *value = name.clone();- }- }- }- tags.retain(|value| !value.is_empty());- tags.sort();- tags.dedup();- if changed {- tx.execute("UPDATE memos SET tags_json = ?1, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), updated_by = 'desktop' WHERE id = ?2", rusqlite::params![serde_json::to_string(&tags).unwrap_or_else(|_| "[]".to_owned()), memo_id]).map_err(|e| e.to_string())?;- updated += 1;- }- }- tx.commit().map_err(|e| e.to_string())?;- enqueue_change(- database,- if delete { "tag.delete" } else { "tag.rename" },- &tag,- params,- )?;- Ok(json!({ "ok": true, "updated": updated }))-}--fn move_memos(database: &Connection, params: &Value) -> Result<Value, String> {- let notebook_id = string_param(params, "notebookId")?;- let memo_ids = params- .get("memoIds")- .and_then(Value::as_array)- .ok_or_else(|| "Missing memoIds array".to_owned())?;- if memo_ids.is_empty() {- return Ok(json!({ "ok": true, "moved": 0 }));- }- let exists: bool = database- .query_row(- "SELECT EXISTS(SELECT 1 FROM notebooks WHERE id = ?1 AND is_deleted = 0)",- [¬ebook_id],- |row| row.get(0),- )- .map_err(|e| e.to_string())?;- if !exists {- return Err(format!("Notebook not found: {notebook_id}"));- }- let tx = database- .unchecked_transaction()- .map_err(|e| e.to_string())?;- let mut moved = 0;- for memo_id in memo_ids {- if let Some(id) = memo_id.as_str() {- moved += tx.execute("UPDATE memos SET notebook_id = ?1, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), updated_by = 'desktop' WHERE id = ?2 AND is_deleted = 0", rusqlite::params![notebook_id, id]).map_err(|e| e.to_string())?;- }- }- tx.commit().map_err(|e| e.to_string())?;- enqueue_change(database, "memo.move", ¬ebook_id, params)?;- Ok(json!({ "ok": true, "moved": moved }))-}--fn delete_memos(database: &Connection, params: &Value) -> Result<Value, String> {- let memo_ids = params- .get("memoIds")- .and_then(Value::as_array)- .ok_or_else(|| "Missing memoIds array".to_owned())?;- let permanent = bool_param(params, "permanent", false);- if memo_ids.is_empty() {- return Ok(json!({ "ok": true, "deleted": 0 }));- }- let tx = database- .unchecked_transaction()- .map_err(|e| e.to_string())?;- let mut deleted = 0;- for memo_id in memo_ids {- let Some(id) = memo_id.as_str() else { continue };- if permanent {- tx.execute("DELETE FROM resources WHERE memo_id = ?1", [id])- .map_err(|e| e.to_string())?;- deleted += tx- .execute("DELETE FROM memos WHERE id = ?1 AND is_deleted = 1", [id])- .map_err(|e| e.to_string())?;- } else {- deleted += tx.execute("UPDATE memos SET is_deleted = 1, deleted_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?1 AND is_deleted = 0", [id]).map_err(|e| e.to_string())?;- }- }- tx.commit().map_err(|e| e.to_string())?;- enqueue_change(database, "memo.deleteBatch", "batch", params)?;- Ok(json!({ "ok": true, "deleted": deleted }))-}--fn empty_trash(database: &Connection) -> Result<Value, String> {- let tx = database- .unchecked_transaction()- .map_err(|e| e.to_string())?;- tx.execute(- "DELETE FROM resources WHERE memo_id IN (SELECT id FROM memos WHERE is_deleted = 1)",- [],- )- .map_err(|e| e.to_string())?;- let deleted = tx- .execute("DELETE FROM memos WHERE is_deleted = 1", [])- .map_err(|e| e.to_string())?;- tx.commit().map_err(|e| e.to_string())?;- enqueue_change(database, "memo.emptyTrash", "trash", &json!({}))?;- Ok(json!({ "ok": true, "deleted": deleted }))-}--fn pin_memos(database: &Connection, params: &Value) -> Result<Value, String> {- let memo_ids = params- .get("memoIds")- .and_then(Value::as_array)- .ok_or_else(|| "Missing memoIds array".to_owned())?;- let is_pinned = bool_param(params, "isPinned", false);- let tx = database- .unchecked_transaction()- .map_err(|e| e.to_string())?;- let mut updated = 0;- for memo_id in memo_ids {- if let Some(id) = memo_id.as_str() {- updated += tx.execute("UPDATE memos SET is_pinned = ?1, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), updated_by = 'desktop' WHERE id = ?2 AND is_deleted = 0", rusqlite::params![is_pinned as i64, id]).map_err(|e| e.to_string())?;- }- }- tx.commit().map_err(|e| e.to_string())?;- enqueue_change(database, "memo.pinBatch", "batch", params)?;- Ok(json!({ "ok": true, "updated": updated }))-}--fn merge_memos(database: &Connection, params: &Value) -> Result<Value, String> {- let memo_ids = params- .get("memoIds")- .and_then(Value::as_array)- .ok_or_else(|| "Missing memoIds array".to_owned())?;- let ids: Vec<String> = memo_ids- .iter()- .filter_map(Value::as_str)- .map(str::to_owned)- .collect();- if ids.len() < 2 {- return Err("At least two memos are required to merge".to_owned());- }- let target_notebook = params- .get("notebookId")- .and_then(Value::as_str)- .map(str::to_owned);- let mut first_notebook_id: Option<String> = None;- let mut titles = Vec::new();- let mut markdowns = Vec::new();- let mut tags = Vec::<String>::new();- for id in &ids {- let row = database.query_row("SELECT m.title, m.notebook_id, c.content_markdown, m.tags_json, c.content_text, c.content_json FROM memos m JOIN memo_contents c ON c.memo_id = m.id WHERE m.id = ?1 AND m.is_deleted = 0", [id], |row| Ok((row.get::<_, Option<String>>(0)?, row.get::<_, String>(1)?, row.get::<_, String>(2)?, row.get::<_, String>(3)?, row.get::<_, String>(4)?, row.get::<_, String>(5)?))).map_err(|e| e.to_string())?;- if first_notebook_id.is_none() {- first_notebook_id = Some(row.1);- }- if let Some(title) = row.0 {- if !title.trim().is_empty() {- titles.push(title);- }- }- markdowns.push(resolve_sidecar_merge_markdown(&row.2, &row.4, &row.5)?);- let memo_tags: Vec<String> = serde_json::from_str(&row.3).unwrap_or_default();- tags.extend(memo_tags);- }- let notebook_id = target_notebook.or(first_notebook_id).unwrap_or_default();- if notebook_id.is_empty() {- return Err("Target notebook not found".to_owned());- }- let title = params- .get("title")- .and_then(Value::as_str)- .filter(|value| !value.trim().is_empty())- .map(|value| value.trim().to_owned())- .or_else(|| resolve_custom_merge_title(titles.iter().map(String::as_str)))- .unwrap_or_default();- tags.sort();- tags.dedup();- let markdown = markdowns.join("\n\n---\n\n");- let content_json = markdown_doc(&markdown);- let content_json_text = content_json.to_string();- let content_text = markdown.lines().collect::<Vec<_>>().join(" ");- let id = now_id("memo_local");- let source_ids = serde_json::to_string(&ids).unwrap_or_else(|_| "[]".to_owned());- let tx = database- .unchecked_transaction()- .map_err(|e| e.to_string())?;- tx.execute("INSERT INTO memos (id, notebook_id, title, excerpt, tags_json, source_memo_ids, merge_source_count, created_by, updated_by) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, 'desktop', 'desktop')", rusqlite::params![id, notebook_id, if title.is_empty() { None } else { Some(title.clone()) }, content_text.chars().take(180).collect::<String>(), serde_json::to_string(&tags).unwrap_or_else(|_| "[]".to_owned()), source_ids, ids.len() as i64]).map_err(|e| e.to_string())?;- tx.execute("INSERT INTO memo_contents (memo_id, content_json, content_markdown, content_text, content_hash) VALUES (?1, ?2, ?3, ?4, ?5)", rusqlite::params![id, content_json_text, markdown, content_text, content_hash(&markdown, &content_json_text)]).map_err(|e| e.to_string())?;- for source_id in &ids {- tx.execute("UPDATE memos SET is_deleted = 1, deleted_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), merged_into_memo_id = ?1, merged_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?2", rusqlite::params![id, source_id]).map_err(|e| e.to_string())?;- tx.execute("UPDATE resources SET original_memo_id = COALESCE(original_memo_id, memo_id), memo_id = ?1, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE memo_id = ?2", rusqlite::params![id, source_id]).map_err(|e| e.to_string())?;- }- tx.commit().map_err(|e| e.to_string())?;- enqueue_change(- database,- "memo.merge",- &id,- &json!({ "memoIds": ids, "notebookId": notebook_id, "title": title, "temporaryId": id }),- )?;- memo_value(database, &id, true).map(|memo| json!({ "memo": memo }))-}--fn resolve_custom_merge_title<'a>(titles: impl IntoIterator<Item = &'a str>) -> Option<String> {- titles- .into_iter()- .map(str::trim)- .find(|title| !title.is_empty() && *title != "无标题笔记")- .map(str::to_owned)-}--fn resolve_sidecar_merge_markdown(- markdown: &str,- content_text: &str,- content_json: &str,-) -> Result<String, String> {- if !markdown.trim().is_empty() {- return Ok(markdown.to_owned());- }-- if !content_text.trim().is_empty() {- return Ok(content_text.to_owned());- }-- let content: Value = serde_json::from_str(content_json).unwrap_or(Value::Null);- if sidecar_doc_has_non_text_content(&content) {- return Err(- "Source note content could not be recovered safely. Merge was cancelled.".to_owned(),- );- }-- Ok(String::new())-}--fn sidecar_doc_has_non_text_content(value: &Value) -> bool {- let node_type = value.get("type").and_then(Value::as_str).unwrap_or("");- if matches!(- node_type,- "image"- | "table"- | "codeBlock"- | "bulletList"- | "orderedList"- | "blockquote"- | "horizontalRule"- | "edgeeverThemeBlock"- ) {- return true;- }-- value- .get("content")- .and_then(Value::as_array)- .is_some_and(|children| children.iter().any(sidecar_doc_has_non_text_content))-}--fn list_memos(database: &Connection, params: &Value) -> Result<Value, String> {- let trash = bool_param(params, "trash", false);- let q = params- .get("q")- .and_then(Value::as_str)- .unwrap_or("")- .trim()- .to_owned();- let notebook_ids = params- .get("notebookIds")- .and_then(Value::as_array)- .cloned()- .unwrap_or_default();- // A notebookIds collection represents the complete notebook subtree and- // therefore supersedes the singular notebookId. Applying both filters- // would reduce the subtree back to the parent notebook alone.- let notebook_id = if notebook_ids.is_empty() {- params.get("notebookId").and_then(Value::as_str)- } else {- None- };- let notebook_ids_json = Value::Array(notebook_ids).to_string();- let filter = match params.get("filter").and_then(Value::as_str) {- Some("pinned") => " AND m.is_pinned = 1",- Some("tagged") => " AND json_array_length(m.tags_json) > 0",- Some("untagged") => " AND json_array_length(m.tags_json) = 0",- _ => "",- };- let order = match params.get("sort").and_then(Value::as_str) {- Some("created-desc") => "m.created_at DESC, m.id DESC",- Some("title-asc") => {- "COALESCE(m.title, m.excerpt) COLLATE NOCASE ASC, m.updated_at DESC, m.id DESC"- }- _ if trash => "m.deleted_at DESC, m.id DESC",- _ => "m.is_pinned DESC, m.updated_at DESC, m.id DESC",- };- let limit = params- .get("limit")- .and_then(Value::as_i64)- .unwrap_or(50)- .clamp(1, 200);- let offset = params- .get("offset")- .and_then(Value::as_i64)- .unwrap_or(0)- .max(0);- let query = format!("SELECT m.id, m.notebook_id, m.title, m.excerpt, m.tags_json, m.is_pinned, m.is_archived, m.is_deleted,- c.revision, m.created_at, m.updated_at, m.deleted_at- FROM memos m JOIN memo_contents c ON c.memo_id = m.id- WHERE m.is_deleted = ?1 AND (?2 = '' OR lower(COALESCE(m.title, '') || ' ' || m.excerpt || ' ' || c.content_text || ' ' || m.tags_json) LIKE '%' || lower(?2) || '%')- AND (?3 IS NULL OR m.notebook_id = ?3)- AND (?4 = '[]' OR m.notebook_id IN (SELECT value FROM json_each(?4))){}- ORDER BY {} LIMIT ?5 OFFSET ?6", filter, order);- let mut statement = database.prepare(&query).map_err(|e| e.to_string())?;- let rows = statement- .query_map(- rusqlite::params![- trash as i64,- q,- notebook_id,- notebook_ids_json,- limit,- offset- ],- summary_from_row,- )- .map_err(|e| e.to_string())?;- let memos: Result<Vec<_>, _> = rows.collect();- let count_query = format!("SELECT COUNT(*) FROM memos m JOIN memo_contents c ON c.memo_id = m.id WHERE m.is_deleted = ?1 AND (?2 = '' OR lower(COALESCE(m.title, '') || ' ' || m.excerpt || ' ' || c.content_text || ' ' || m.tags_json) LIKE '%' || lower(?2) || '%') AND (?3 IS NULL OR m.notebook_id = ?3) AND (?4 = '[]' OR m.notebook_id IN (SELECT value FROM json_each(?4))){}", filter);- let total: i64 = database- .query_row(- &count_query,- rusqlite::params![trash as i64, q, notebook_id, notebook_ids_json],- |row| row.get(0),- )- .map_err(|e| e.to_string())?;- let memos = memos.map_err(|e| e.to_string())?;- let next_cursor = if offset + (memos.len() as i64) < total {- Some((offset + memos.len() as i64).to_string())- } else {- None- };- Ok(json!({ "memos": memos, "totalCount": total, "nextCursor": next_cursor }))-}--fn create_memo(database: &Connection, params: &Value) -> Result<Value, String> {- let notebook_id = string_param(params, "notebookId")?;- let title = params- .get("title")- .and_then(Value::as_str)- .unwrap_or("")- .trim()- .to_owned();- let markdown = params- .get("contentMarkdown")- .and_then(Value::as_str)- .unwrap_or("")- .to_owned();- let tags = params.get("tags").cloned().unwrap_or_else(|| json!([]));- let content_json = params- .get("contentJson")- .cloned()- .unwrap_or_else(|| markdown_doc(&markdown));- let content_json_text = content_json.to_string();- let text = markdown.lines().collect::<Vec<_>>().join(" ");- let id = now_id("memo_local");- let hash = content_hash(&markdown, &content_json_text);- let tx = database- .unchecked_transaction()- .map_err(|e| e.to_string())?;- tx.execute("INSERT INTO memos (id, notebook_id, title, excerpt, tags_json, created_by, updated_by) VALUES (?1, ?2, ?3, ?4, ?5, 'desktop', 'desktop')", rusqlite::params![id, notebook_id, if title.is_empty() { None } else { Some(title.clone()) }, text.chars().take(180).collect::<String>(), tags.to_string()]).map_err(|e| e.to_string())?;- tx.execute("INSERT INTO memo_contents (memo_id, content_json, content_markdown, content_text, content_hash) VALUES (?1, ?2, ?3, ?4, ?5)", rusqlite::params![id, content_json_text, markdown, text, hash]).map_err(|e| e.to_string())?;- tx.commit().map_err(|e| e.to_string())?;- let memo = memo_value(database, &id, true)?;- enqueue_change(- database,- "memo.create",- &id,- &json!({- "temporaryId": id, "notebookId": notebook_id, "title": title, "contentMarkdown": markdown,- "tags": tags, "createdAt": memo.get("createdAt").and_then(Value::as_str).unwrap_or(""),- "updatedAt": memo.get("updatedAt").and_then(Value::as_str).unwrap_or("")- }),- )?;- Ok(memo)-}--fn update_memo(database: &Connection, params: &Value) -> Result<Value, String> {- let memo_id = string_param(params, "memoId")?;- let previous = memo_value(database, &memo_id, true)?;- let requested_revision = params- .get("expectedRevision")- .and_then(Value::as_i64)- .unwrap_or(0);- let requested_content_hash = params- .get("expectedContentHash")- .and_then(Value::as_str)- .unwrap_or("");- // A freshly-created desktop note changes from its local id/revision 0 to- // the server id/revision while the editor is still live. If an autosave- // was already scheduled, translate that one known local base to the exact- // create acknowledgement instead of misclassifying our own create as a- // remote edit. The marker retains both sides of the mapping, so a genuine- // later remote revision still conflicts normally.- let (expected_revision, expected_content_hash, consumed_remap_base) =- resolve_remapped_memo_base(- database,- &memo_id,- requested_revision,- requested_content_hash,- );- let title = params- .get("title")- .and_then(Value::as_str)- .unwrap_or("")- .trim()- .to_owned();- let content_json = params.get("contentJson").cloned().unwrap_or_else(|| {- markdown_doc(- params- .get("contentMarkdown")- .and_then(Value::as_str)- .unwrap_or(""),- )- });- let content_json_text = content_json.to_string();- let markdown = params- .get("contentMarkdown")- .and_then(Value::as_str)- .or_else(|| previous.get("contentMarkdown").and_then(Value::as_str))- .unwrap_or("")- .to_owned();- let text = params- .get("contentText")- .and_then(Value::as_str)- .unwrap_or(&markdown)- .to_owned();- let tags = params.get("tags").cloned().unwrap_or_else(|| json!([]));- let hash = content_hash(&markdown, &content_json_text);- let tx = database- .unchecked_transaction()- .map_err(|e| e.to_string())?;- insert_revision(&tx, &previous, "desktop")?;- let changed = tx.execute("UPDATE memos SET title = ?2, excerpt = ?3, tags_json = ?4, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), updated_by = 'desktop' WHERE id = ?1 AND is_deleted = 0", rusqlite::params![memo_id, if title.is_empty() { None } else { Some(title) }, text.chars().take(180).collect::<String>(), tags.to_string()]).map_err(|e| e.to_string())?;- if changed == 0 {- return Err(format!("Memo not found or deleted: {memo_id}"));- }- // `revision` is the last acknowledged cloud revision, not a counter for- // local autosaves. Advancing it here makes several saves on one device- // look newer than the cloud and produces a false revision conflict once- // the coalesced outbox item is synced.- tx.execute("UPDATE memo_contents SET content_json = ?2, content_markdown = ?3, content_text = ?4, content_hash = ?5, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE memo_id = ?1", rusqlite::params![memo_id, content_json_text, markdown, text, hash]).map_err(|e| e.to_string())?;- tx.commit().map_err(|e| e.to_string())?;- enqueue_change(- database,- "memo.update",- &memo_id,- &json!({- "memoId": memo_id, "expectedRevision": expected_revision,- "expectedContentHash": expected_content_hash,- "title": params.get("title").and_then(Value::as_str).unwrap_or(""), "contentJson": content_json,- "contentMarkdown": markdown, "tags": tags- }),- )?;- if consumed_remap_base {- database- .execute(- "DELETE FROM _edgeever_sidecar_meta WHERE key = ?1",- [memo_remap_base_key(&memo_id)],- )- .map_err(|e| e.to_string())?;- }- memo_value(database, &memo_id, true)-}--fn delete_memo(database: &Connection, params: &Value) -> Result<Value, String> {- let memo_id = string_param(params, "memoId")?;- if bool_param(params, "permanent", false) {- database- .execute("DELETE FROM memos WHERE id = ?1", [&memo_id])- .map_err(|e| e.to_string())?;- } else {- database.execute("UPDATE memos SET is_deleted = 1, deleted_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?1", [&memo_id]).map_err(|e| e.to_string())?;- }- enqueue_change(- database,- "memo.delete",- &memo_id,- &json!({ "memoId": memo_id, "permanent": bool_param(params, "permanent", false) }),- )?;- Ok(json!({ "ok": true }))-}--fn restore_memo(database: &Connection, params: &Value) -> Result<Value, String> {- let memo_id = string_param(params, "memoId")?;- let changed = database.execute("UPDATE memos SET is_deleted = 0, deleted_at = NULL, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?1", [&memo_id]).map_err(|e| e.to_string())?;- if changed == 0 {- return Err(format!("Memo not found: {memo_id}"));- }- enqueue_change(- database,- "memo.restore",- &memo_id,- &json!({ "memoId": memo_id }),- )?;- memo_value(database, &memo_id, true)-}--fn restore_memo_revision(database: &Connection, params: &Value) -> Result<Value, String> {- let memo_id = string_param(params, "memoId")?;- let revision_id = string_param(params, "revisionId")?;- let current = memo_value(database, &memo_id, true)?;- let revision = revision_value(database, &memo_id, &revision_id)?;- let title = revision- .get("title")- .and_then(Value::as_str)- .unwrap_or("")- .trim()- .to_owned();- let content_json = revision- .get("contentJson")- .cloned()- .unwrap_or_else(|| json!({"type":"doc","content":[]}));- let content_json_text = content_json.to_string();- let markdown = revision- .get("contentMarkdown")- .and_then(Value::as_str)- .unwrap_or("")- .to_owned();- let text = revision- .get("contentText")- .and_then(Value::as_str)- .unwrap_or(&markdown)- .to_owned();- let tags = revision.get("tags").cloned().unwrap_or_else(|| json!([]));- let hash = content_hash(&markdown, &content_json_text);- let next_revision = current.get("revision").and_then(Value::as_i64).unwrap_or(0) + 1;- let tx = database- .unchecked_transaction()- .map_err(|e| e.to_string())?;- insert_revision(&tx, ¤t, "desktop")?;- tx.execute("UPDATE memos SET title = ?2, excerpt = ?3, tags_json = ?4, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), updated_by = 'desktop' WHERE id = ?1", rusqlite::params![memo_id, if title.is_empty() { None } else { Some(title.clone()) }, text.chars().take(180).collect::<String>(), tags.to_string()]).map_err(|e| e.to_string())?;- tx.execute("UPDATE memo_contents SET content_json = ?2, content_markdown = ?3, content_text = ?4, content_hash = ?5, revision = ?6, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE memo_id = ?1", rusqlite::params![memo_id, content_json_text, markdown, text, hash, next_revision]).map_err(|e| e.to_string())?;- tx.commit().map_err(|e| e.to_string())?;- enqueue_change(- database,- "memo.update",- &memo_id,- &json!({- "memoId": memo_id, "expectedRevision": current.get("revision").and_then(Value::as_i64).unwrap_or(0),- "expectedContentHash": current.get("contentHash").and_then(Value::as_str).unwrap_or(""),- "title": title, "contentJson": content_json, "contentMarkdown": markdown, "tags": tags,- }),- )?;- memo_value(database, &memo_id, true).map(|memo| json!({ "memo": memo }))-}--fn sync_status(database: &Connection) -> Result<Value, String> {- let count = |status: &str| -> Result<i64, String> {- database- .query_row(- "SELECT COUNT(*) FROM _edgeever_sidecar_outbox WHERE status = ?1",- [status],- |row| row.get(0),- )- .map_err(|e| e.to_string())- };- Ok(json!({- "pending": count("pending")?, "syncing": count("syncing")?, "conflict": count("conflict")?, "error": count("error")?,- "cursor": meta_value(database, "sync.cursor").and_then(|v| v.parse::<i64>().ok()).unwrap_or(0),- "syncIdentity": meta_value(database, "sync.identity"), "lastSyncedAt": meta_value(database, "sync.last_synced_at")- }))-}--const SYNC_BOOTSTRAP_RESET_KEY: &str = "sync.bootstrap.reset_pending";--fn reset_sync_mirror(database: &Connection) -> Result<(), String> {- let tx = database- .unchecked_transaction()- .map_err(|e| e.to_string())?;- tx.execute_batch(- "CREATE TEMP TABLE IF NOT EXISTS _edgeever_bootstrap_preserved_memos (id TEXT PRIMARY KEY);- CREATE TEMP TABLE IF NOT EXISTS _edgeever_bootstrap_preserved_notebooks (id TEXT PRIMARY KEY);- DELETE FROM _edgeever_bootstrap_preserved_memos;- DELETE FROM _edgeever_bootstrap_preserved_notebooks;- INSERT OR IGNORE INTO _edgeever_bootstrap_preserved_memos (id)- SELECT m.id FROM memos m- WHERE EXISTS (- SELECT 1 FROM _edgeever_sidecar_outbox o- WHERE o.entity_id = m.id OR instr(o.payload_json, m.id) > 0- );- INSERT OR IGNORE INTO _edgeever_bootstrap_preserved_notebooks (id)- SELECT n.id FROM notebooks n- WHERE EXISTS (- SELECT 1 FROM _edgeever_sidecar_outbox o- WHERE o.entity_id = n.id OR instr(o.payload_json, n.id) > 0- );- INSERT OR IGNORE INTO _edgeever_bootstrap_preserved_notebooks (id)- SELECT DISTINCT m.notebook_id- FROM memos m- INNER JOIN _edgeever_bootstrap_preserved_memos p ON p.id = m.id;- WITH RECURSIVE preserved_ancestors(id, parent_id) AS (- SELECT n.id, n.parent_id- FROM notebooks n- INNER JOIN _edgeever_bootstrap_preserved_notebooks p ON p.id = n.id- UNION- SELECT parent.id, parent.parent_id- FROM notebooks parent- INNER JOIN preserved_ancestors child ON child.parent_id = parent.id- )- INSERT OR IGNORE INTO _edgeever_bootstrap_preserved_notebooks (id)- SELECT id FROM preserved_ancestors;- DELETE FROM resources- WHERE memo_id NOT IN (SELECT id FROM _edgeever_bootstrap_preserved_memos);- DELETE FROM memos- WHERE id NOT IN (SELECT id FROM _edgeever_bootstrap_preserved_memos);- UPDATE notebooks SET parent_id = NULL- WHERE id NOT IN (SELECT id FROM _edgeever_bootstrap_preserved_notebooks);- DELETE FROM notebooks- WHERE id NOT IN (SELECT id FROM _edgeever_bootstrap_preserved_notebooks);- DELETE FROM _edgeever_sidecar_meta- WHERE key IN ('sync.cursor', 'sync.identity', 'sync.last_synced_at')- OR key LIKE 'memo.remap-base:%';- INSERT INTO _edgeever_sidecar_meta (key, value, updated_at)- VALUES ('sync.bootstrap.reset_pending', '1', strftime('%Y-%m-%dT%H:%M:%fZ','now'))- ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at;",- )- .map_err(|e| e.to_string())?;- tx.commit().map_err(|e| e.to_string())-}--fn prepare_sync_bootstrap(database: &Connection, params: &Value) -> Result<Value, String> {- let reset_requested = bool_param(params, "reset", false)- || meta_value(database, SYNC_BOOTSTRAP_RESET_KEY).as_deref() == Some("1");- if reset_requested {- reset_sync_mirror(database)?;- return Ok(json!({ "clearedSeedData": false, "rebuiltMirror": true }));- }-- if meta_value(database, "sync.identity").is_some_and(|identity| !identity.is_empty()) {- return Ok(json!({ "clearedSeedData": false, "rebuiltMirror": false }));- }-- let outbox_count = database- .query_row("SELECT COUNT(*) FROM _edgeever_sidecar_outbox", [], |row| {- row.get::<_, i64>(0)- })- .map_err(|e| e.to_string())?;- let non_seed_memos = database- .query_row(- "SELECT COUNT(*) FROM memos WHERE id <> 'memo_welcome'",- [],- |row| row.get::<_, i64>(0),- )- .map_err(|e| e.to_string())?;- let non_seed_notebooks = database- .query_row(- "SELECT COUNT(*) FROM notebooks- WHERE id NOT IN ('nb_inbox', 'nb_projects', 'nb_learning', 'nb_creative', 'nb_personal')",- [],- |row| row.get::<_, i64>(0),- )- .map_err(|e| e.to_string())?;-- if outbox_count > 0 || non_seed_memos > 0 || non_seed_notebooks > 0 {- return Ok(json!({ "clearedSeedData": false, "rebuiltMirror": false }));- }-- let tx = database- .unchecked_transaction()- .map_err(|e| e.to_string())?;- tx.execute("DELETE FROM memos WHERE id = 'memo_welcome'", [])- .map_err(|e| e.to_string())?;- tx.execute(- "DELETE FROM notebooks- WHERE id IN ('nb_inbox', 'nb_projects', 'nb_learning', 'nb_creative', 'nb_personal')",- [],- )- .map_err(|e| e.to_string())?;- tx.commit().map_err(|e| e.to_string())?;- Ok(json!({ "clearedSeedData": true, "rebuiltMirror": false }))-}--fn sync_outbox_list(database: &Connection, params: &Value) -> Result<Value, String> {- let limit = params- .get("limit")- .and_then(Value::as_i64)- .unwrap_or(50)- .clamp(1, 200);- let include_conflicts = bool_param(params, "includeConflicts", false);- let sql = if include_conflicts {- "SELECT id, kind, entity_id, payload_json, attempt_count, status, last_error, version, last_error_code, retryable, next_attempt_at, created_at, updated_at FROM _edgeever_sidecar_outbox WHERE status IN ('pending', 'error', 'conflict') ORDER BY id LIMIT ?1"- } else {- "SELECT id, kind, entity_id, payload_json, attempt_count, status, last_error, version, last_error_code, retryable, next_attempt_at, created_at, updated_at FROM _edgeever_sidecar_outbox WHERE status = 'pending' OR (status = 'error' AND retryable = 1 AND (next_attempt_at IS NULL OR next_attempt_at <= strftime('%Y-%m-%dT%H:%M:%fZ','now'))) ORDER BY id LIMIT ?1"- };- let mut statement = database.prepare(sql).map_err(|e| e.to_string())?;- let rows = statement.query_map([limit], |row| {- let payload: String = row.get(3)?;- Ok(json!({ "id": row.get::<_, i64>(0)?, "kind": row.get::<_, String>(1)?, "entityId": row.get::<_, String>(2)?, "payload": serde_json::from_str::<Value>(&payload).unwrap_or_else(|_| json!({})), "attemptCount": row.get::<_, i64>(4)?, "status": row.get::<_, String>(5)?, "lastError": row.get::<_, Option<String>>(6)?, "version": row.get::<_, i64>(7)?, "lastErrorCode": row.get::<_, Option<String>>(8)?, "retryable": row.get::<_, bool>(9)?, "nextAttemptAt": row.get::<_, Option<String>>(10)?, "createdAt": row.get::<_, String>(11)?, "updatedAt": row.get::<_, String>(12)? }))- }).map_err(|e| e.to_string())?;- let items: Result<Vec<_>, _> = rows.collect();- Ok(json!({ "items": items.map_err(|e| e.to_string())? }))-}--fn sync_outbox_ack(database: &Connection, params: &Value) -> Result<Value, String> {- let id = params- .get("id")- .and_then(Value::as_i64)- .ok_or_else(|| "Missing outbox id".to_owned())?;- let (kind, entity_id, current_version): (String, String, i64) = database- .query_row(- "SELECT kind, entity_id, version FROM _edgeever_sidecar_outbox WHERE id = ?1",- [id],- |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),- )- .map_err(|e| e.to_string())?;- let requested_version = params.get("version").and_then(Value::as_i64);- let superseded = requested_version.is_some_and(|version| version != current_version);- let remote_memo = params.get("remoteMemo").cloned();- let remote_notebook = params.get("remoteNotebook").cloned();- let remote_template = params.get("remoteTemplate").cloned();- let temporary_memo_base = if kind == "memo.create" {- memo_value(database, &entity_id, true).ok().map(|memo| {- (- memo.get("revision").and_then(Value::as_i64).unwrap_or(0),- memo.get("contentHash")- .and_then(Value::as_str)- .unwrap_or("")- .to_owned(),- )- })- } else {- None- };-- if kind == "memo.update" && superseded {- if let Some(remote) = remote_memo.as_ref() {- let remote_revision = remote.get("revision").and_then(Value::as_i64).unwrap_or(0);- let remote_hash = remote- .get("contentHash")- .and_then(Value::as_str)- .unwrap_or("");- let payload_text: String = database- .query_row(- "SELECT payload_json FROM _edgeever_sidecar_outbox WHERE id = ?1",- [id],- |row| row.get(0),- )- .map_err(|e| e.to_string())?;- let mut payload: Value =- serde_json::from_str(&payload_text).unwrap_or_else(|_| json!({}));- payload["expectedRevision"] = json!(remote_revision);- payload["expectedContentHash"] = json!(remote_hash);- let tx = database- .unchecked_transaction()- .map_err(|e| e.to_string())?;- // Preserve the successor draft's content while advancing only its- // acknowledged cloud base. The next flush will send that draft on- // top of the response that just succeeded.- tx.execute(- "UPDATE memo_contents SET revision = ?1 WHERE memo_id = ?2",- rusqlite::params![remote_revision, entity_id],- )- .map_err(|e| e.to_string())?;- tx.execute(- "UPDATE _edgeever_sidecar_outbox- SET payload_json = ?1, status = 'pending', last_error = NULL,- updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')- WHERE id = ?2",- rusqlite::params![payload.to_string(), id],- )- .map_err(|e| e.to_string())?;- tx.commit().map_err(|e| e.to_string())?;- }- return Ok(json!({- "ok": true,- "superseded": true,- "memo": remote_memo,- "notebook": remote_notebook,- "template": remote_template- }));- }-- if let Some(remote) = remote_memo.as_ref() {- let remote_id = string_param(remote, "id")?;- apply_sync_changes(- database,- &json!({- "changes": [{- "entityType": "memo",- "operation": "upsert",- "entityId": remote_id,- "memo": remote,- "notebook": null- }]- }),- )?;- }- if kind == "memo.create" || kind == "memo.merge" {- if let Some(remote) = remote_memo.as_ref() {- let remote_id = string_param(remote, "id")?;- let remote_exists: bool = database- .query_row(- "SELECT EXISTS(SELECT 1 FROM memos WHERE id = ?1)",- [&remote_id],- |row| row.get(0),- )- .map_err(|e| e.to_string())?;- if remote_exists {- // The acknowledgement caches the remote memo before reconciling- // the local placeholder, so the remote id exists here.- // A merged local memo can still own resources moved from its- // sources. Deleting it directly is rejected by the resources- // foreign key and leaves both the local placeholder and remote- // memo visible forever. Repoint every surviving relationship- // before removing the placeholder, and keep the reconciliation- // atomic so a crash cannot strand a partially remapped merge.- let tx = database- .unchecked_transaction()- .map_err(|e| e.to_string())?;- tx.execute(- "UPDATE resources SET memo_id = ?1 WHERE memo_id = ?2",- rusqlite::params![remote_id, entity_id],- )- .map_err(|e| e.to_string())?;- tx.execute(- "UPDATE resources SET original_memo_id = ?1 WHERE original_memo_id = ?2",- rusqlite::params![remote_id, entity_id],- )- .map_err(|e| e.to_string())?;- tx.execute(- "UPDATE memos SET merged_into_memo_id = ?1 WHERE merged_into_memo_id = ?2",- rusqlite::params![remote_id, entity_id],- )- .map_err(|e| e.to_string())?;- tx.execute("DELETE FROM memos WHERE id = ?1", [&entity_id])- .map_err(|e| e.to_string())?;- tx.commit().map_err(|e| e.to_string())?;- } else {- database- .execute(- "UPDATE memos SET id = ?1 WHERE id = ?2",- rusqlite::params![remote_id, entity_id],- )- .map_err(|e| e.to_string())?;- }- let mut pending = database.prepare("SELECT id, entity_id, payload_json FROM _edgeever_sidecar_outbox WHERE id <> ?1").map_err(|e| e.to_string())?;- let rows: Vec<(i64, String, String)> = pending- .query_map([id], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))- .map_err(|e| e.to_string())?- .collect::<Result<_, _>>()- .map_err(|e| e.to_string())?;- for (outbox_id, outbox_entity, payload_text) in rows {- if outbox_entity != entity_id && !payload_text.contains(&entity_id) {- continue;- }- let mut payload: Value =- serde_json::from_str(&payload_text).unwrap_or_else(|_| json!({}));- if payload.get("memoId").and_then(Value::as_str) == Some(entity_id.as_str()) {- payload["memoId"] = json!(remote_id);- }- if payload.get("temporaryId").and_then(Value::as_str) == Some(entity_id.as_str()) {- payload["temporaryId"] = json!(remote_id);- }- if payload.get("memoId").and_then(Value::as_str) == Some(remote_id.as_str()) {- if let Some(revision) = remote.get("revision") {- payload["expectedRevision"] = revision.clone();- }- if let Some(hash) = remote.get("contentHash") {- payload["expectedContentHash"] = hash.clone();- }- }- let next_entity = if outbox_entity == entity_id {- remote_id.clone()- } else {- outbox_entity- };- database.execute("UPDATE _edgeever_sidecar_outbox SET entity_id = ?1, payload_json = ?2, version = version + 1 WHERE id = ?3", rusqlite::params![next_entity, payload.to_string(), outbox_id]).map_err(|e| e.to_string())?;- }- if kind == "memo.create" {- if let Some((temporary_revision, temporary_content_hash)) =- temporary_memo_base.as_ref()- {- set_meta(- database,- &memo_remap_base_key(&remote_id),- &json!({- "temporaryRevision": temporary_revision,- "temporaryContentHash": temporary_content_hash,- "remoteRevision": remote.get("revision").and_then(Value::as_i64).unwrap_or(0),- "remoteContentHash": remote.get("contentHash").and_then(Value::as_str).unwrap_or("")- })- .to_string(),- )?;- }- }- }- }- if kind == "notebook.create" {- if let Some(remote) = remote_notebook.as_ref() {- let remote_id = string_param(remote, "id")?;- let remote_exists: bool = database- .query_row(- "SELECT EXISTS(SELECT 1 FROM notebooks WHERE id = ?1)",- [&remote_id],- |row| row.get(0),- )- .map_err(|e| e.to_string())?;- if remote_exists {- database- .execute("DELETE FROM notebooks WHERE id = ?1", [&entity_id])- .map_err(|e| e.to_string())?;- } else {- database- .execute(- "UPDATE notebooks SET id = ?1 WHERE id = ?2",- rusqlite::params![remote_id, entity_id],- )- .map_err(|e| e.to_string())?;- }- let mut pending = database.prepare("SELECT id, entity_id, payload_json FROM _edgeever_sidecar_outbox WHERE id <> ?1").map_err(|e| e.to_string())?;- let rows: Vec<(i64, String, String)> = pending- .query_map([id], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))- .map_err(|e| e.to_string())?- .collect::<Result<_, _>>()- .map_err(|e| e.to_string())?;- for (outbox_id, outbox_entity, payload_text) in rows {- if outbox_entity != entity_id && !payload_text.contains(&entity_id) {- continue;- }- let mut payload: Value =- serde_json::from_str(&payload_text).unwrap_or_else(|_| json!({}));- if payload.get("notebookId").and_then(Value::as_str) == Some(entity_id.as_str()) {- payload["notebookId"] = json!(remote_id);- }- if payload.get("temporaryId").and_then(Value::as_str) == Some(entity_id.as_str()) {- payload["temporaryId"] = json!(remote_id);- }- let next_entity = if outbox_entity == entity_id {- remote_id.clone()- } else {- outbox_entity- };- database.execute("UPDATE _edgeever_sidecar_outbox SET entity_id = ?1, payload_json = ?2, version = version + 1 WHERE id = ?3", rusqlite::params![next_entity, payload.to_string(), outbox_id]).map_err(|e| e.to_string())?;- }- }- }- if kind == "template.create" {- if let Some(remote) = remote_template.as_ref() {- let remote_id = string_param(remote, "id")?;- let remote_exists: bool = database- .query_row(- "SELECT EXISTS(SELECT 1 FROM memo_templates WHERE id = ?1)",- [&remote_id],- |row| row.get(0),- )- .map_err(|e| e.to_string())?;- if remote_exists {- database- .execute("DELETE FROM memo_templates WHERE id = ?1", [&entity_id])- .map_err(|e| e.to_string())?;- } else {- database- .execute(- "UPDATE memo_templates SET id = ?1 WHERE id = ?2",- rusqlite::params![remote_id, entity_id],- )- .map_err(|e| e.to_string())?;- }- let mut pending = database.prepare("SELECT id, entity_id, payload_json FROM _edgeever_sidecar_outbox WHERE id <> ?1").map_err(|e| e.to_string())?;- let rows: Vec<(i64, String, String)> = pending- .query_map([id], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))- .map_err(|e| e.to_string())?- .collect::<Result<_, _>>()- .map_err(|e| e.to_string())?;- for (outbox_id, outbox_entity, payload_text) in rows {- if outbox_entity != entity_id && !payload_text.contains(&entity_id) {- continue;- }- let mut payload: Value =- serde_json::from_str(&payload_text).unwrap_or_else(|_| json!({}));- if payload.get("templateId").and_then(Value::as_str) == Some(entity_id.as_str()) {- payload["templateId"] = json!(remote_id);- }- if payload.get("temporaryId").and_then(Value::as_str) == Some(entity_id.as_str()) {- payload["temporaryId"] = json!(remote_id);- }- let next_entity = if outbox_entity == entity_id {- remote_id.clone()- } else {- outbox_entity- };- database.execute("UPDATE _edgeever_sidecar_outbox SET entity_id = ?1, payload_json = ?2, version = version + 1 WHERE id = ?3", rusqlite::params![next_entity, payload.to_string(), outbox_id]).map_err(|e| e.to_string())?;- }- }- }- let deleted = if let Some(version) = requested_version {- database- .execute(- "DELETE FROM _edgeever_sidecar_outbox WHERE id = ?1 AND version = ?2",- rusqlite::params![id, version],- )- .map_err(|e| e.to_string())?- } else {- database- .execute("DELETE FROM _edgeever_sidecar_outbox WHERE id = ?1", [id])- .map_err(|e| e.to_string())?- };- Ok(- json!({ "ok": true, "superseded": deleted == 0, "memo": remote_memo, "notebook": remote_notebook, "template": remote_template }),- )-}--fn sync_outbox_fail(database: &Connection, params: &Value) -> Result<Value, String> {- let id = params- .get("id")- .and_then(Value::as_i64)- .ok_or_else(|| "Missing outbox id".to_owned())?;- let error = params- .get("error")- .and_then(Value::as_str)- .unwrap_or("sync failed");- let status = if bool_param(params, "conflict", false) {- "conflict"- } else {- "error"- };- let error_code = params.get("errorCode").and_then(Value::as_str);- let retryable = params- .get("retryable")- .and_then(Value::as_bool)- .unwrap_or(true);- let next_attempt_at = params.get("nextAttemptAt").and_then(Value::as_str);- let updated = if let Some(version) = params.get("version").and_then(Value::as_i64) {- database.execute("UPDATE _edgeever_sidecar_outbox SET status = ?1, attempt_count = attempt_count + 1, last_error = ?2, last_error_code = ?3, retryable = ?4, next_attempt_at = ?5, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?6 AND version = ?7", rusqlite::params![status, error, error_code, retryable, next_attempt_at, id, version]).map_err(|e| e.to_string())?- } else {- database.execute("UPDATE _edgeever_sidecar_outbox SET status = ?1, attempt_count = attempt_count + 1, last_error = ?2, last_error_code = ?3, retryable = ?4, next_attempt_at = ?5, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?6", rusqlite::params![status, error, error_code, retryable, next_attempt_at, id]).map_err(|e| e.to_string())?- };- Ok(json!({ "ok": true, "superseded": updated == 0 }))-}--fn sync_outbox_retry(database: &Connection, params: &Value) -> Result<Value, String> {- let id = params- .get("id")- .and_then(Value::as_i64)- .ok_or_else(|| "Missing outbox id".to_owned())?;- let version = params.get("version").and_then(Value::as_i64);- let updated = if let Some(version) = version {- database.execute(- "UPDATE _edgeever_sidecar_outbox SET status = 'pending', retryable = 1, next_attempt_at = NULL, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?1 AND version = ?2 AND status = 'error'",- rusqlite::params![id, version],- )- } else {- database.execute(- "UPDATE _edgeever_sidecar_outbox SET status = 'pending', retryable = 1, next_attempt_at = NULL, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?1 AND status = 'error'",- [id],- )- }- .map_err(|e| e.to_string())?;- if updated == 0 {- return Err("The failed sync item changed before retry".to_owned());- }- Ok(json!({ "ok": true }))-}--fn sync_outbox_recover_memo_update(database: &Connection, params: &Value) -> Result<Value, String> {- let id = params- .get("id")- .and_then(Value::as_i64)- .ok_or_else(|| "Missing outbox id".to_owned())?;- let notebook_id = string_param(params, "notebookId")?;- let requested_version = params.get("version").and_then(Value::as_i64);- let (kind, payload_text, version, status): (String, String, i64, String) = database- .query_row(- "SELECT kind, payload_json, version, status FROM _edgeever_sidecar_outbox WHERE id = ?1",- [id],- |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),- )- .map_err(|e| e.to_string())?;- if kind != "memo.update" || status != "error" {- return Err("Only failed memo updates can be recovered".to_owned());- }- if requested_version.is_some_and(|value| value != version) {- return Err("The failed update changed before recovery".to_owned());- }- let notebook_exists: bool = database- .query_row(- "SELECT EXISTS(SELECT 1 FROM notebooks WHERE id = ?1 AND is_deleted = 0)",- [¬ebook_id],- |row| row.get(0),- )- .map_err(|e| e.to_string())?;- if !notebook_exists {- return Err("Recovery notebook not found".to_owned());- }- let mut payload: Value = serde_json::from_str(&payload_text).map_err(|e| e.to_string())?;- let object = payload- .as_object_mut()- .ok_or_else(|| "Invalid failed memo payload".to_owned())?;- object.insert("notebookId".to_owned(), json!(notebook_id));- let memo = create_memo(database, &payload)?;- let recovered_id = string_param(&memo, "id")?;- payload["memoId"] = json!(recovered_id);- payload["expectedRevision"] = json!(0);- payload["expectedContentHash"] = memo- .get("contentHash")- .cloned()- .unwrap_or_else(|| json!(""));- enqueue_change(database, "memo.update", &recovered_id, &payload)?;- let removed = database- .execute(- "DELETE FROM _edgeever_sidecar_outbox WHERE id = ?1 AND version = ?2 AND status = 'error'",- rusqlite::params![id, version],- )- .map_err(|e| e.to_string())?;- if removed == 0 {- database- .execute(- "DELETE FROM _edgeever_sidecar_outbox WHERE entity_id = ?1",- [&recovered_id],- )- .ok();- database- .execute("DELETE FROM memos WHERE id = ?1", [&recovered_id])- .ok();- return Err("The failed update changed before recovery".to_owned());- }- Ok(json!({ "ok": true, "memo": memo }))-}--fn sync_outbox_discard(database: &Connection, params: &Value) -> Result<Value, String> {- let id = params- .get("id")- .and_then(Value::as_i64)- .ok_or_else(|| "Missing outbox id".to_owned())?;- let removed = if let Some(version) = params.get("version").and_then(Value::as_i64) {- database.execute(- "DELETE FROM _edgeever_sidecar_outbox WHERE id = ?1 AND version = ?2",- rusqlite::params![id, version],- )- } else {- database.execute("DELETE FROM _edgeever_sidecar_outbox WHERE id = ?1", [id])- }- .map_err(|e| e.to_string())?;- if removed == 0 {- return Err("The sync item changed before it was discarded".to_owned());- }- Ok(json!({ "ok": true }))-}--fn apply_sync_changes(database: &Connection, params: &Value) -> Result<Value, String> {- let changes = params- .get("changes")- .and_then(Value::as_array)- .ok_or_else(|| "Missing changes array".to_owned())?;- let rebuilding = meta_value(database, SYNC_BOOTSTRAP_RESET_KEY).as_deref() == Some("1");- let tx = database- .unchecked_transaction()- .map_err(|e| e.to_string())?;- for change in changes {- let entity_type = string_param(change, "entityType")?;- let operation = string_param(change, "operation")?;- let entity_id = string_param(change, "entityId")?;- if rebuilding {- let preserved_table = if entity_type == "notebook" {- "_edgeever_bootstrap_preserved_notebooks"- } else {- "_edgeever_bootstrap_preserved_memos"- };- let preserved = tx- .query_row(- &format!("SELECT EXISTS(SELECT 1 FROM {preserved_table} WHERE id = ?1)"),- [&entity_id],- |row| row.get::<_, bool>(0),- )- .unwrap_or(false);- if preserved {- continue;- }- }- if entity_type == "notebook" {- if operation == "delete" {- tx.execute("UPDATE notebooks SET is_deleted = 1, deleted_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?1", [&entity_id]).map_err(|e| e.to_string())?;- continue;- }- let notebook = change- .get("notebook")- .ok_or_else(|| "Missing notebook change payload".to_owned())?;- tx.execute("INSERT INTO notebooks (id, parent_id, name, slug, icon, color, sort_order, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9) ON CONFLICT(id) DO UPDATE SET parent_id=excluded.parent_id, name=excluded.name, slug=excluded.slug, icon=excluded.icon, color=excluded.color, sort_order=excluded.sort_order, updated_at=excluded.updated_at, is_deleted=0", rusqlite::params![entity_id, notebook.get("parentId").and_then(Value::as_str), string_param(notebook, "name")?, notebook.get("slug").and_then(Value::as_str), notebook.get("icon").and_then(Value::as_str), notebook.get("color").and_then(Value::as_str), notebook.get("sortOrder").and_then(Value::as_i64).unwrap_or(0), string_param(notebook, "createdAt")?, string_param(notebook, "updatedAt")?]).map_err(|e| e.to_string())?;- continue;- }- if operation == "delete" {- tx.execute("UPDATE memos SET is_deleted = 1, deleted_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?1", [&entity_id]).map_err(|e| e.to_string())?;- continue;- }- let memo = change- .get("memo")- .ok_or_else(|| "Missing memo change payload".to_owned())?;- let tags = memo- .get("tags")- .cloned()- .unwrap_or_else(|| json!([]))- .to_string();- let source_ids = memo- .get("sourceMemoIds")- .cloned()- .unwrap_or_else(|| json!([]))- .to_string();- let content_json = memo- .get("contentJson")- .cloned()- .unwrap_or_else(|| json!({"type":"doc","content":[]}));- tx.execute("INSERT INTO memos (id, notebook_id, title, excerpt, tags_json, is_pinned, is_archived, is_deleted, source_memo_ids, merge_source_count, merged_into_memo_id, created_at, updated_at, deleted_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14) ON CONFLICT(id) DO UPDATE SET notebook_id=excluded.notebook_id, title=excluded.title, excerpt=excluded.excerpt, tags_json=excluded.tags_json, is_pinned=excluded.is_pinned, is_archived=excluded.is_archived, is_deleted=excluded.is_deleted, updated_at=excluded.updated_at, deleted_at=excluded.deleted_at", rusqlite::params![entity_id, string_param(memo, "notebookId")?, memo.get("title").and_then(Value::as_str), string_param(memo, "excerpt")?, tags, memo.get("isPinned").and_then(Value::as_bool).unwrap_or(false) as i64, memo.get("isArchived").and_then(Value::as_bool).unwrap_or(false) as i64, memo.get("isDeleted").and_then(Value::as_bool).unwrap_or(false) as i64, source_ids, memo.get("mergeSourceCount").and_then(Value::as_i64).unwrap_or(0), memo.get("mergedIntoMemoId").and_then(Value::as_str), string_param(memo, "createdAt")?, string_param(memo, "updatedAt")?, memo.get("deletedAt").and_then(Value::as_str)]).map_err(|e| e.to_string())?;- tx.execute("INSERT INTO memo_contents (memo_id, content_json, content_markdown, content_text, content_hash, revision) VALUES (?1, ?2, ?3, ?4, ?5, ?6) ON CONFLICT(memo_id) DO UPDATE SET content_json=excluded.content_json, content_markdown=excluded.content_markdown, content_text=excluded.content_text, content_hash=excluded.content_hash, revision=excluded.revision, updated_at=strftime('%Y-%m-%dT%H:%M:%fZ','now')", rusqlite::params![entity_id, content_json.to_string(), string_param(memo, "contentMarkdown")?, string_param(memo, "contentText")?, string_param(memo, "contentHash")?, memo.get("revision").and_then(Value::as_i64).unwrap_or(0)]).map_err(|e| e.to_string())?;- }- tx.commit().map_err(|e| e.to_string())?;- Ok(json!({ "applied": changes.len() }))-}--fn handle(- request: RpcRequest,- database: &mut Connection,- root: &Path,- migrations: &Path,-) -> Result<Value, String> {- match request.method.as_str() {- "system.info" => Ok(json!({- "platform": env::consts::OS,- "architecture": env::consts::ARCH,- "dataDir": root,- "protocolVersion": PROTOCOL_VERSION,- })),- "storage.health" => database- .query_row("SELECT 1", [], |row| row.get::<_, i64>(0))- .map(|_| json!({ "ok": true }))- .map_err(|error| error.to_string()),- "storage.backup" => backup_database(database, root)- .map(|path| json!({ "ok": true, "path": path }))- .map_err(|error| error.to_string()),- "storage.backups" => list_backups(root).map_err(|error| error.to_string()),- "storage.restore" => restore_database(database, root, migrations, &request.params),- "sync.status" => sync_status(database),- "sync.bootstrap.prepare" => prepare_sync_bootstrap(database, &request.params),- "sync.outbox.list" => sync_outbox_list(database, &request.params),- "sync.outbox.ack" => sync_outbox_ack(database, &request.params),- "sync.outbox.fail" => sync_outbox_fail(database, &request.params),- "sync.outbox.retry" => sync_outbox_retry(database, &request.params),- "sync.outbox.recoverMemoUpdate" => {- sync_outbox_recover_memo_update(database, &request.params)- }- "sync.outbox.discard" => sync_outbox_discard(database, &request.params),- "sync.apply" => apply_sync_changes(database, &request.params),- "sync.cursor.set" => {- set_meta(- database,- "sync.cursor",- &request- .params- .get("cursor")- .and_then(Value::as_i64)- .unwrap_or(0)- .to_string(),- )?;- set_meta(- database,- "sync.identity",- request- .params- .get("syncIdentity")- .and_then(Value::as_str)- .unwrap_or(""),- )?;- set_meta(database, "sync.last_synced_at", &chrono_like_now())?;- database- .execute(- "DELETE FROM _edgeever_sidecar_meta WHERE key = ?1",- [SYNC_BOOTSTRAP_RESET_KEY],- )- .map_err(|e| e.to_string())?;- database- .execute_batch(- "DROP TABLE IF EXISTS temp._edgeever_bootstrap_preserved_memos;- DROP TABLE IF EXISTS temp._edgeever_bootstrap_preserved_notebooks;",- )- .map_err(|e| e.to_string())?;- Ok(json!({ "ok": true }))- }- "notebook.list" => list_notebooks(database),- "notebook.create" => create_notebook(database, &request.params)- .map(|notebook| json!({ "notebook": notebook })),- "notebook.update" => update_notebook(database, &request.params)- .map(|notebook| json!({ "notebook": notebook })),- "notebook.delete" => delete_notebook(database, &request.params),- "notebook.restore" => restore_notebook(database, &request.params)- .map(|notebook| json!({ "notebook": notebook })),- "template.list" => list_templates(database),- "template.cache" => cache_template(database, &request.params),- "template.create" => create_template(database, &request.params)- .map(|template| json!({ "template": template })),- "template.update" => update_template(database, &request.params)- .map(|template| json!({ "template": template })),- "template.delete" => delete_template(database, &request.params),- "resource.list" => list_resources(database, &request.params),- "resource.cache" => cache_resource(database, &request.params),- "resource.delete" => delete_cached_resource(database, &request.params),- "tag.list" => list_tags(database),- "tag.rename" => rewrite_tag(database, &request.params, false),- "tag.delete" => rewrite_tag(database, &request.params, true),- "memo.moveBatch" => move_memos(database, &request.params),- "memo.deleteBatch" => delete_memos(database, &request.params),- "memo.emptyTrash" => empty_trash(database),- "memo.pinBatch" => pin_memos(database, &request.params),- "memo.merge" => merge_memos(database, &request.params),- "memo.list" => list_memos(database, &request.params),- "memo.get" => {- let memo_id = string_param(&request.params, "memoId")?;- memo_value(- database,- &memo_id,- bool_param(&request.params, "includeDeleted", false),- )- .map(|memo| json!({ "memo": memo }))- }- "memo.create" => create_memo(database, &request.params).map(|memo| json!({ "memo": memo })),- "memo.update" => update_memo(database, &request.params).map(|memo| json!({ "memo": memo })),- "memo.delete" => delete_memo(database, &request.params),- "memo.restore" => {- restore_memo(database, &request.params).map(|memo| json!({ "memo": memo }))- }- "memo.revisions" => list_memo_revisions(database, &request.params),- "memo.restoreRevision" => restore_memo_revision(database, &request.params),- "memo.revision.cache" => cache_memo_revision(database, &request.params),- "app.shutdown" => Ok(json!({ "ok": true })),- _ => Err(format!("Unknown sidecar method: {}", request.method)),- }-}--fn chrono_like_now() -> String {- // SQLite owns persisted timestamps; this value is only a human-readable sync marker.- SystemTime::now()- .duration_since(UNIX_EPOCH)- .unwrap_or_default()- .as_secs()- .to_string()-}-fn main() -> Result<(), Box<dyn std::error::Error>> {let root = data_dir();let mut database = open_database(&root, &migrations_dir())?;@@ -2020,6 +191,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {#[cfg(test)]mod tests {use super::*;+ use crate::memo::{resolve_custom_merge_title, resolve_sidecar_merge_markdown};+ use crate::sync::{apply_sync_changes, prepare_sync_bootstrap};#[test]fn string_param_rejects_missing_or_non_string_values() {diff --git a/crates/desktop-sidecar/src/memo.rs b/crates/desktop-sidecar/src/memo.rsnew file mode 100644index 00000000..324e9903--- /dev/null+++ b/crates/desktop-sidecar/src/memo.rs@@ -0,0 +1,679 @@+use rusqlite::Connection;+use serde_json::{json, Value};++use crate::{+ bool_param, content_hash, enqueue_change, markdown_doc, memo_remap_base_key, now_id,+ resolve_remapped_memo_base, string_param, tags_from_json,+};++fn summary_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Value> {+ let tags: String = row.get("tags_json")?;+ Ok(json!({+ "id": row.get::<_, String>("id")?,+ "notebookId": row.get::<_, String>("notebook_id")?,+ "title": row.get::<_, Option<String>>("title")?,+ "excerpt": row.get::<_, String>("excerpt")?,+ "tags": tags_from_json(&tags),+ "isPinned": row.get::<_, i64>("is_pinned")? != 0,+ "isArchived": row.get::<_, i64>("is_archived")? != 0,+ "isDeleted": row.get::<_, i64>("is_deleted")? != 0,+ "revision": row.get::<_, i64>("revision")?,+ "createdAt": row.get::<_, String>("created_at")?,+ "updatedAt": row.get::<_, String>("updated_at")?,+ "deletedAt": row.get::<_, Option<String>>("deleted_at")?,+ }))+}++pub(crate) fn memo_value(+ database: &Connection,+ memo_id: &str,+ include_deleted: bool,+) -> Result<Value, String> {+ let mut statement = database.prepare(+ "SELECT m.id, m.notebook_id, m.title, m.excerpt, m.tags_json, m.is_pinned, m.is_archived, m.is_deleted,+ m.source_memo_ids, m.merge_source_count, m.merged_into_memo_id, m.created_at, m.updated_at, m.deleted_at,+ c.content_json, c.content_markdown, c.content_text, c.content_hash, c.revision+ FROM memos m JOIN memo_contents c ON c.memo_id = m.id+ WHERE m.id = ?1 AND (?2 OR m.is_deleted = 0)",+ ).map_err(|e| e.to_string())?;+ statement.query_row(rusqlite::params![memo_id, include_deleted as i64], |row| {+ let tags: String = row.get("tags_json")?;+ let source_ids: String = row.get("source_memo_ids")?;+ let content_json: String = row.get("content_json")?;+ Ok(json!({+ "id": row.get::<_, String>("id")?, "notebookId": row.get::<_, String>("notebook_id")?,+ "title": row.get::<_, Option<String>>("title")?, "excerpt": row.get::<_, String>("excerpt")?,+ "tags": tags_from_json(&tags), "isPinned": row.get::<_, i64>("is_pinned")? != 0,+ "isArchived": row.get::<_, i64>("is_archived")? != 0, "isDeleted": row.get::<_, i64>("is_deleted")? != 0,+ "revision": row.get::<_, i64>("revision")?, "createdAt": row.get::<_, String>("created_at")?,+ "updatedAt": row.get::<_, String>("updated_at")?, "deletedAt": row.get::<_, Option<String>>("deleted_at")?,+ "contentJson": serde_json::from_str::<Value>(&content_json).unwrap_or_else(|_| json!({"type":"doc","content":[]})),+ "contentMarkdown": row.get::<_, String>("content_markdown")?, "contentText": row.get::<_, String>("content_text")?,+ "contentHash": row.get::<_, String>("content_hash")?, "sourceMemoIds": tags_from_json(&source_ids),+ "mergeSourceCount": row.get::<_, i64>("merge_source_count")?, "mergedIntoMemoId": row.get::<_, Option<String>>("merged_into_memo_id")?,+ }))+ }).map_err(|e| e.to_string())+}++fn insert_revision(+ transaction: &rusqlite::Transaction<'_>,+ memo: &Value,+ created_by: &str,+) -> Result<(), String> {+ let memo_id = string_param(memo, "id")?;+ let content_json = memo+ .get("contentJson")+ .cloned()+ .unwrap_or_else(|| json!({"type":"doc","content":[]}));+ let tags = memo.get("tags").cloned().unwrap_or_else(|| json!([]));+ transaction.execute(+ "INSERT INTO memo_revisions (id, memo_id, revision, title, content_json, content_markdown, content_hash, created_by, created_at, tags_json, content_text) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, strftime('%Y-%m-%dT%H:%M:%fZ','now'), ?9, ?10)",+ rusqlite::params![+ now_id("revision_local"), memo_id,+ memo.get("revision").and_then(Value::as_i64).unwrap_or(0),+ memo.get("title").and_then(Value::as_str), content_json.to_string(),+ memo.get("contentMarkdown").and_then(Value::as_str).unwrap_or(""),+ memo.get("contentHash").and_then(Value::as_str).unwrap_or(""), created_by,+ tags.to_string(), memo.get("contentText").and_then(Value::as_str).unwrap_or(""),+ ],+ ).map(|_| ()).map_err(|e| e.to_string())+}++fn revision_value(+ database: &Connection,+ memo_id: &str,+ revision_id: &str,+) -> Result<Value, String> {+ database.query_row(+ "SELECT id, memo_id, revision, title, tags_json, content_json, content_markdown, content_text, content_hash, created_by, created_at FROM memo_revisions WHERE id = ?1 AND memo_id = ?2",+ rusqlite::params![revision_id, memo_id],+ |row| {+ let tags: String = row.get(4)?;+ let content_json: String = row.get(5)?;+ Ok(json!({+ "id": row.get::<_, String>(0)?, "memoId": row.get::<_, String>(1)?, "revision": row.get::<_, i64>(2)?,+ "title": row.get::<_, Option<String>>(3)?, "tags": tags_from_json(&tags),+ "contentJson": serde_json::from_str::<Value>(&content_json).unwrap_or_else(|_| json!({"type":"doc","content":[]})),+ "contentMarkdown": row.get::<_, String>(6)?, "contentText": row.get::<_, String>(7)?,+ "contentHash": row.get::<_, String>(8)?, "createdBy": row.get::<_, String>(9)?, "createdAt": row.get::<_, String>(10)?,+ }))+ },+ ).map_err(|e| e.to_string())+}++pub(crate) fn list_memo_revisions(database: &Connection, params: &Value) -> Result<Value, String> {+ let memo_id = string_param(params, "memoId")?;+ let limit = params+ .get("limit")+ .and_then(Value::as_i64)+ .unwrap_or(100)+ .clamp(1, 200);+ let mut statement = database.prepare("SELECT id, memo_id, revision, title, tags_json, content_json, content_markdown, content_text, content_hash, created_by, created_at FROM memo_revisions WHERE memo_id = ?1 ORDER BY revision DESC, created_at DESC LIMIT ?2").map_err(|e| e.to_string())?;+ let rows = statement.query_map(rusqlite::params![memo_id, limit], |row| {+ let tags: String = row.get(4)?;+ let content_json: String = row.get(5)?;+ Ok(json!({+ "id": row.get::<_, String>(0)?, "memoId": row.get::<_, String>(1)?, "revision": row.get::<_, i64>(2)?,+ "title": row.get::<_, Option<String>>(3)?, "tags": tags_from_json(&tags),+ "contentJson": serde_json::from_str::<Value>(&content_json).unwrap_or_else(|_| json!({"type":"doc","content":[]})),+ "contentMarkdown": row.get::<_, String>(6)?, "contentText": row.get::<_, String>(7)?,+ "contentHash": row.get::<_, String>(8)?, "createdBy": row.get::<_, String>(9)?, "createdAt": row.get::<_, String>(10)?,+ }))+ }).map_err(|e| e.to_string())?;+ let revisions: Result<Vec<_>, _> = rows.collect();+ Ok(json!({ "revisions": revisions.map_err(|e| e.to_string())? }))+}++pub(crate) fn cache_memo_revision(database: &Connection, params: &Value) -> Result<Value, String> {+ let revision = params+ .get("revision")+ .ok_or_else(|| "Missing revision".to_owned())?;+ let memo_id = string_param(revision, "memoId")?;+ let revision_id = string_param(revision, "id")?;+ let content_json = revision+ .get("contentJson")+ .cloned()+ .unwrap_or_else(|| json!({"type":"doc","content":[]}));+ let tags = revision.get("tags").cloned().unwrap_or_else(|| json!([]));+ database.execute(+ "INSERT INTO memo_revisions (id, memo_id, revision, title, content_json, content_markdown, content_hash, created_by, created_at, tags_json, content_text) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11) ON CONFLICT(id) DO UPDATE SET memo_id=excluded.memo_id, revision=excluded.revision, title=excluded.title, content_json=excluded.content_json, content_markdown=excluded.content_markdown, content_hash=excluded.content_hash, created_by=excluded.created_by, created_at=excluded.created_at, tags_json=excluded.tags_json, content_text=excluded.content_text",+ rusqlite::params![+ revision_id, memo_id, revision.get("revision").and_then(Value::as_i64).unwrap_or(0),+ revision.get("title").and_then(Value::as_str), content_json.to_string(),+ revision.get("contentMarkdown").and_then(Value::as_str).unwrap_or(""),+ revision.get("contentHash").and_then(Value::as_str).unwrap_or(""),+ revision.get("createdBy").and_then(Value::as_str).unwrap_or("remote"),+ revision.get("createdAt").and_then(Value::as_str).unwrap_or(""), tags.to_string(),+ revision.get("contentText").and_then(Value::as_str).unwrap_or(""),+ ],+ ).map_err(|e| e.to_string())?;+ Ok(json!({ "ok": true }))+}++pub(crate) fn move_memos(database: &Connection, params: &Value) -> Result<Value, String> {+ let notebook_id = string_param(params, "notebookId")?;+ let memo_ids = params+ .get("memoIds")+ .and_then(Value::as_array)+ .ok_or_else(|| "Missing memoIds array".to_owned())?;+ if memo_ids.is_empty() {+ return Ok(json!({ "ok": true, "moved": 0 }));+ }+ let exists: bool = database+ .query_row(+ "SELECT EXISTS(SELECT 1 FROM notebooks WHERE id = ?1 AND is_deleted = 0)",+ [¬ebook_id],+ |row| row.get(0),+ )+ .map_err(|e| e.to_string())?;+ if !exists {+ return Err(format!("Notebook not found: {notebook_id}"));+ }+ let tx = database+ .unchecked_transaction()+ .map_err(|e| e.to_string())?;+ let mut moved = 0;+ for memo_id in memo_ids {+ if let Some(id) = memo_id.as_str() {+ moved += tx.execute("UPDATE memos SET notebook_id = ?1, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), updated_by = 'desktop' WHERE id = ?2 AND is_deleted = 0", rusqlite::params![notebook_id, id]).map_err(|e| e.to_string())?;+ }+ }+ tx.commit().map_err(|e| e.to_string())?;+ enqueue_change(database, "memo.move", ¬ebook_id, params)?;+ Ok(json!({ "ok": true, "moved": moved }))+}++pub(crate) fn delete_memos(database: &Connection, params: &Value) -> Result<Value, String> {+ let memo_ids = params+ .get("memoIds")+ .and_then(Value::as_array)+ .ok_or_else(|| "Missing memoIds array".to_owned())?;+ let permanent = bool_param(params, "permanent", false);+ if memo_ids.is_empty() {+ return Ok(json!({ "ok": true, "deleted": 0 }));+ }+ let tx = database+ .unchecked_transaction()+ .map_err(|e| e.to_string())?;+ let mut deleted = 0;+ for memo_id in memo_ids {+ let Some(id) = memo_id.as_str() else { continue };+ if permanent {+ tx.execute("DELETE FROM resources WHERE memo_id = ?1", [id])+ .map_err(|e| e.to_string())?;+ deleted += tx+ .execute("DELETE FROM memos WHERE id = ?1 AND is_deleted = 1", [id])+ .map_err(|e| e.to_string())?;+ } else {+ deleted += tx.execute("UPDATE memos SET is_deleted = 1, deleted_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?1 AND is_deleted = 0", [id]).map_err(|e| e.to_string())?;+ }+ }+ tx.commit().map_err(|e| e.to_string())?;+ enqueue_change(database, "memo.deleteBatch", "batch", params)?;+ Ok(json!({ "ok": true, "deleted": deleted }))+}++pub(crate) fn empty_trash(database: &Connection) -> Result<Value, String> {+ let tx = database+ .unchecked_transaction()+ .map_err(|e| e.to_string())?;+ tx.execute(+ "DELETE FROM resources WHERE memo_id IN (SELECT id FROM memos WHERE is_deleted = 1)",+ [],+ )+ .map_err(|e| e.to_string())?;+ let deleted = tx+ .execute("DELETE FROM memos WHERE is_deleted = 1", [])+ .map_err(|e| e.to_string())?;+ tx.commit().map_err(|e| e.to_string())?;+ enqueue_change(database, "memo.emptyTrash", "trash", &json!({}))?;+ Ok(json!({ "ok": true, "deleted": deleted }))+}++pub(crate) fn pin_memos(database: &Connection, params: &Value) -> Result<Value, String> {+ let memo_ids = params+ .get("memoIds")+ .and_then(Value::as_array)+ .ok_or_else(|| "Missing memoIds array".to_owned())?;+ let is_pinned = bool_param(params, "isPinned", false);+ let tx = database+ .unchecked_transaction()+ .map_err(|e| e.to_string())?;+ let mut updated = 0;+ for memo_id in memo_ids {+ if let Some(id) = memo_id.as_str() {+ updated += tx.execute("UPDATE memos SET is_pinned = ?1, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), updated_by = 'desktop' WHERE id = ?2 AND is_deleted = 0", rusqlite::params![is_pinned as i64, id]).map_err(|e| e.to_string())?;+ }+ }+ tx.commit().map_err(|e| e.to_string())?;+ enqueue_change(database, "memo.pinBatch", "batch", params)?;+ Ok(json!({ "ok": true, "updated": updated }))+}++pub(crate) fn merge_memos(database: &Connection, params: &Value) -> Result<Value, String> {+ let memo_ids = params+ .get("memoIds")+ .and_then(Value::as_array)+ .ok_or_else(|| "Missing memoIds array".to_owned())?;+ let ids: Vec<String> = memo_ids+ .iter()+ .filter_map(Value::as_str)+ .map(str::to_owned)+ .collect();+ if ids.len() < 2 {+ return Err("At least two memos are required to merge".to_owned());+ }+ let target_notebook = params+ .get("notebookId")+ .and_then(Value::as_str)+ .map(str::to_owned);+ let mut first_notebook_id: Option<String> = None;+ let mut titles = Vec::new();+ let mut markdowns = Vec::new();+ let mut tags = Vec::<String>::new();+ for id in &ids {+ let row = database.query_row("SELECT m.title, m.notebook_id, c.content_markdown, m.tags_json, c.content_text, c.content_json FROM memos m JOIN memo_contents c ON c.memo_id = m.id WHERE m.id = ?1 AND m.is_deleted = 0", [id], |row| Ok((row.get::<_, Option<String>>(0)?, row.get::<_, String>(1)?, row.get::<_, String>(2)?, row.get::<_, String>(3)?, row.get::<_, String>(4)?, row.get::<_, String>(5)?))).map_err(|e| e.to_string())?;+ if first_notebook_id.is_none() {+ first_notebook_id = Some(row.1);+ }+ if let Some(title) = row.0 {+ if !title.trim().is_empty() {+ titles.push(title);+ }+ }+ markdowns.push(resolve_sidecar_merge_markdown(&row.2, &row.4, &row.5)?);+ let memo_tags: Vec<String> = serde_json::from_str(&row.3).unwrap_or_default();+ tags.extend(memo_tags);+ }+ let notebook_id = target_notebook.or(first_notebook_id).unwrap_or_default();+ if notebook_id.is_empty() {+ return Err("Target notebook not found".to_owned());+ }+ let title = params+ .get("title")+ .and_then(Value::as_str)+ .filter(|value| !value.trim().is_empty())+ .map(|value| value.trim().to_owned())+ .or_else(|| resolve_custom_merge_title(titles.iter().map(String::as_str)))+ .unwrap_or_default();+ tags.sort();+ tags.dedup();+ let markdown = markdowns.join("\n\n---\n\n");+ let content_json = markdown_doc(&markdown);+ let content_json_text = content_json.to_string();+ let content_text = markdown.lines().collect::<Vec<_>>().join(" ");+ let id = now_id("memo_local");+ let source_ids = serde_json::to_string(&ids).unwrap_or_else(|_| "[]".to_owned());+ let tx = database+ .unchecked_transaction()+ .map_err(|e| e.to_string())?;+ tx.execute("INSERT INTO memos (id, notebook_id, title, excerpt, tags_json, source_memo_ids, merge_source_count, created_by, updated_by) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, 'desktop', 'desktop')", rusqlite::params![id, notebook_id, if title.is_empty() { None } else { Some(title.clone()) }, content_text.chars().take(180).collect::<String>(), serde_json::to_string(&tags).unwrap_or_else(|_| "[]".to_owned()), source_ids, ids.len() as i64]).map_err(|e| e.to_string())?;+ tx.execute("INSERT INTO memo_contents (memo_id, content_json, content_markdown, content_text, content_hash) VALUES (?1, ?2, ?3, ?4, ?5)", rusqlite::params![id, content_json_text, markdown, content_text, content_hash(&markdown, &content_json_text)]).map_err(|e| e.to_string())?;+ for source_id in &ids {+ tx.execute("UPDATE memos SET is_deleted = 1, deleted_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), merged_into_memo_id = ?1, merged_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?2", rusqlite::params![id, source_id]).map_err(|e| e.to_string())?;+ tx.execute("UPDATE resources SET original_memo_id = COALESCE(original_memo_id, memo_id), memo_id = ?1, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE memo_id = ?2", rusqlite::params![id, source_id]).map_err(|e| e.to_string())?;+ }+ tx.commit().map_err(|e| e.to_string())?;+ enqueue_change(+ database,+ "memo.merge",+ &id,+ &json!({ "memoIds": ids, "notebookId": notebook_id, "title": title, "temporaryId": id }),+ )?;+ memo_value(database, &id, true).map(|memo| json!({ "memo": memo }))+}++pub(crate) fn resolve_custom_merge_title<'a>(+ titles: impl IntoIterator<Item = &'a str>,+) -> Option<String> {+ titles+ .into_iter()+ .map(str::trim)+ .find(|title| !title.is_empty() && *title != "无标题笔记")+ .map(str::to_owned)+}++pub(crate) fn resolve_sidecar_merge_markdown(+ markdown: &str,+ content_text: &str,+ content_json: &str,+) -> Result<String, String> {+ if !markdown.trim().is_empty() {+ return Ok(markdown.to_owned());+ }++ if !content_text.trim().is_empty() {+ return Ok(content_text.to_owned());+ }++ let content: Value = serde_json::from_str(content_json).unwrap_or(Value::Null);+ if sidecar_doc_has_non_text_content(&content) {+ return Err(+ "Source note content could not be recovered safely. Merge was cancelled.".to_owned(),+ );+ }++ Ok(String::new())+}++fn sidecar_doc_has_non_text_content(value: &Value) -> bool {+ let node_type = value.get("type").and_then(Value::as_str).unwrap_or("");+ if matches!(+ node_type,+ "image"+ | "table"+ | "codeBlock"+ | "bulletList"+ | "orderedList"+ | "blockquote"+ | "horizontalRule"+ | "edgeeverThemeBlock"+ ) {+ return true;+ }++ value+ .get("content")+ .and_then(Value::as_array)+ .is_some_and(|children| children.iter().any(sidecar_doc_has_non_text_content))+}++pub(crate) fn list_memos(database: &Connection, params: &Value) -> Result<Value, String> {+ let trash = bool_param(params, "trash", false);+ let q = params+ .get("q")+ .and_then(Value::as_str)+ .unwrap_or("")+ .trim()+ .to_owned();+ let notebook_ids = params+ .get("notebookIds")+ .and_then(Value::as_array)+ .cloned()+ .unwrap_or_default();+ // A notebookIds collection represents the complete notebook subtree and+ // therefore supersedes the singular notebookId. Applying both filters+ // would reduce the subtree back to the parent notebook alone.+ let notebook_id = if notebook_ids.is_empty() {+ params.get("notebookId").and_then(Value::as_str)+ } else {+ None+ };+ let notebook_ids_json = Value::Array(notebook_ids).to_string();+ let filter = match params.get("filter").and_then(Value::as_str) {+ Some("pinned") => " AND m.is_pinned = 1",+ Some("tagged") => " AND json_array_length(m.tags_json) > 0",+ Some("untagged") => " AND json_array_length(m.tags_json) = 0",+ _ => "",+ };+ let order = match params.get("sort").and_then(Value::as_str) {+ Some("created-desc") => "m.created_at DESC, m.id DESC",+ Some("title-asc") => {+ "COALESCE(m.title, m.excerpt) COLLATE NOCASE ASC, m.updated_at DESC, m.id DESC"+ }+ _ if trash => "m.deleted_at DESC, m.id DESC",+ _ => "m.is_pinned DESC, m.updated_at DESC, m.id DESC",+ };+ let limit = params+ .get("limit")+ .and_then(Value::as_i64)+ .unwrap_or(50)+ .clamp(1, 200);+ let offset = params+ .get("offset")+ .and_then(Value::as_i64)+ .unwrap_or(0)+ .max(0);+ let query = format!("SELECT m.id, m.notebook_id, m.title, m.excerpt, m.tags_json, m.is_pinned, m.is_archived, m.is_deleted,+ c.revision, m.created_at, m.updated_at, m.deleted_at+ FROM memos m JOIN memo_contents c ON c.memo_id = m.id+ WHERE m.is_deleted = ?1 AND (?2 = '' OR lower(COALESCE(m.title, '') || ' ' || m.excerpt || ' ' || c.content_text || ' ' || m.tags_json) LIKE '%' || lower(?2) || '%')+ AND (?3 IS NULL OR m.notebook_id = ?3)+ AND (?4 = '[]' OR m.notebook_id IN (SELECT value FROM json_each(?4))){}+ ORDER BY {} LIMIT ?5 OFFSET ?6", filter, order);+ let mut statement = database.prepare(&query).map_err(|e| e.to_string())?;+ let rows = statement+ .query_map(+ rusqlite::params![+ trash as i64,+ q,+ notebook_id,+ notebook_ids_json,+ limit,+ offset+ ],+ summary_from_row,+ )+ .map_err(|e| e.to_string())?;+ let memos: Result<Vec<_>, _> = rows.collect();+ let count_query = format!("SELECT COUNT(*) FROM memos m JOIN memo_contents c ON c.memo_id = m.id WHERE m.is_deleted = ?1 AND (?2 = '' OR lower(COALESCE(m.title, '') || ' ' || m.excerpt || ' ' || c.content_text || ' ' || m.tags_json) LIKE '%' || lower(?2) || '%') AND (?3 IS NULL OR m.notebook_id = ?3) AND (?4 = '[]' OR m.notebook_id IN (SELECT value FROM json_each(?4))){}", filter);+ let total: i64 = database+ .query_row(+ &count_query,+ rusqlite::params![trash as i64, q, notebook_id, notebook_ids_json],+ |row| row.get(0),+ )+ .map_err(|e| e.to_string())?;+ let memos = memos.map_err(|e| e.to_string())?;+ let next_cursor = if offset + (memos.len() as i64) < total {+ Some((offset + memos.len() as i64).to_string())+ } else {+ None+ };+ Ok(json!({ "memos": memos, "totalCount": total, "nextCursor": next_cursor }))+}++pub(crate) fn create_memo(database: &Connection, params: &Value) -> Result<Value, String> {+ let notebook_id = string_param(params, "notebookId")?;+ let title = params+ .get("title")+ .and_then(Value::as_str)+ .unwrap_or("")+ .trim()+ .to_owned();+ let markdown = params+ .get("contentMarkdown")+ .and_then(Value::as_str)+ .unwrap_or("")+ .to_owned();+ let tags = params.get("tags").cloned().unwrap_or_else(|| json!([]));+ let content_json = params+ .get("contentJson")+ .cloned()+ .unwrap_or_else(|| markdown_doc(&markdown));+ let content_json_text = content_json.to_string();+ let text = markdown.lines().collect::<Vec<_>>().join(" ");+ let id = now_id("memo_local");+ let hash = content_hash(&markdown, &content_json_text);+ let tx = database+ .unchecked_transaction()+ .map_err(|e| e.to_string())?;+ tx.execute("INSERT INTO memos (id, notebook_id, title, excerpt, tags_json, created_by, updated_by) VALUES (?1, ?2, ?3, ?4, ?5, 'desktop', 'desktop')", rusqlite::params![id, notebook_id, if title.is_empty() { None } else { Some(title.clone()) }, text.chars().take(180).collect::<String>(), tags.to_string()]).map_err(|e| e.to_string())?;+ tx.execute("INSERT INTO memo_contents (memo_id, content_json, content_markdown, content_text, content_hash) VALUES (?1, ?2, ?3, ?4, ?5)", rusqlite::params![id, content_json_text, markdown, text, hash]).map_err(|e| e.to_string())?;+ tx.commit().map_err(|e| e.to_string())?;+ let memo = memo_value(database, &id, true)?;+ enqueue_change(+ database,+ "memo.create",+ &id,+ &json!({+ "temporaryId": id, "notebookId": notebook_id, "title": title, "contentMarkdown": markdown,+ "tags": tags, "createdAt": memo.get("createdAt").and_then(Value::as_str).unwrap_or(""),+ "updatedAt": memo.get("updatedAt").and_then(Value::as_str).unwrap_or("")+ }),+ )?;+ Ok(memo)+}++pub(crate) fn update_memo(database: &Connection, params: &Value) -> Result<Value, String> {+ let memo_id = string_param(params, "memoId")?;+ let previous = memo_value(database, &memo_id, true)?;+ let requested_revision = params+ .get("expectedRevision")+ .and_then(Value::as_i64)+ .unwrap_or(0);+ let requested_content_hash = params+ .get("expectedContentHash")+ .and_then(Value::as_str)+ .unwrap_or("");+ // A freshly-created desktop note changes from its local id/revision 0 to+ // the server id/revision while the editor is still live. If an autosave+ // was already scheduled, translate that one known local base to the exact+ // create acknowledgement instead of misclassifying our own create as a+ // remote edit. The marker retains both sides of the mapping, so a genuine+ // later remote revision still conflicts normally.+ let (expected_revision, expected_content_hash, consumed_remap_base) =+ resolve_remapped_memo_base(+ database,+ &memo_id,+ requested_revision,+ requested_content_hash,+ );+ let title = params+ .get("title")+ .and_then(Value::as_str)+ .unwrap_or("")+ .trim()+ .to_owned();+ let content_json = params.get("contentJson").cloned().unwrap_or_else(|| {+ markdown_doc(+ params+ .get("contentMarkdown")+ .and_then(Value::as_str)+ .unwrap_or(""),+ )+ });+ let content_json_text = content_json.to_string();+ let markdown = params+ .get("contentMarkdown")+ .and_then(Value::as_str)+ .or_else(|| previous.get("contentMarkdown").and_then(Value::as_str))+ .unwrap_or("")+ .to_owned();+ let text = params+ .get("contentText")+ .and_then(Value::as_str)+ .unwrap_or(&markdown)+ .to_owned();+ let tags = params.get("tags").cloned().unwrap_or_else(|| json!([]));+ let hash = content_hash(&markdown, &content_json_text);+ let tx = database+ .unchecked_transaction()+ .map_err(|e| e.to_string())?;+ insert_revision(&tx, &previous, "desktop")?;+ let changed = tx.execute("UPDATE memos SET title = ?2, excerpt = ?3, tags_json = ?4, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), updated_by = 'desktop' WHERE id = ?1 AND is_deleted = 0", rusqlite::params![memo_id, if title.is_empty() { None } else { Some(title) }, text.chars().take(180).collect::<String>(), tags.to_string()]).map_err(|e| e.to_string())?;+ if changed == 0 {+ return Err(format!("Memo not found or deleted: {memo_id}"));+ }+ // `revision` is the last acknowledged cloud revision, not a counter for+ // local autosaves. Advancing it here makes several saves on one device+ // look newer than the cloud and produces a false revision conflict once+ // the coalesced outbox item is synced.+ tx.execute("UPDATE memo_contents SET content_json = ?2, content_markdown = ?3, content_text = ?4, content_hash = ?5, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE memo_id = ?1", rusqlite::params![memo_id, content_json_text, markdown, text, hash]).map_err(|e| e.to_string())?;+ tx.commit().map_err(|e| e.to_string())?;+ enqueue_change(+ database,+ "memo.update",+ &memo_id,+ &json!({+ "memoId": memo_id, "expectedRevision": expected_revision,+ "expectedContentHash": expected_content_hash,+ "title": params.get("title").and_then(Value::as_str).unwrap_or(""), "contentJson": content_json,+ "contentMarkdown": markdown, "tags": tags+ }),+ )?;+ if consumed_remap_base {+ database+ .execute(+ "DELETE FROM _edgeever_sidecar_meta WHERE key = ?1",+ [memo_remap_base_key(&memo_id)],+ )+ .map_err(|e| e.to_string())?;+ }+ memo_value(database, &memo_id, true)+}++pub(crate) fn delete_memo(database: &Connection, params: &Value) -> Result<Value, String> {+ let memo_id = string_param(params, "memoId")?;+ if bool_param(params, "permanent", false) {+ database+ .execute("DELETE FROM memos WHERE id = ?1", [&memo_id])+ .map_err(|e| e.to_string())?;+ } else {+ database.execute("UPDATE memos SET is_deleted = 1, deleted_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?1", [&memo_id]).map_err(|e| e.to_string())?;+ }+ enqueue_change(+ database,+ "memo.delete",+ &memo_id,+ &json!({ "memoId": memo_id, "permanent": bool_param(params, "permanent", false) }),+ )?;+ Ok(json!({ "ok": true }))+}++pub(crate) fn restore_memo(database: &Connection, params: &Value) -> Result<Value, String> {+ let memo_id = string_param(params, "memoId")?;+ let changed = database.execute("UPDATE memos SET is_deleted = 0, deleted_at = NULL, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?1", [&memo_id]).map_err(|e| e.to_string())?;+ if changed == 0 {+ return Err(format!("Memo not found: {memo_id}"));+ }+ enqueue_change(+ database,+ "memo.restore",+ &memo_id,+ &json!({ "memoId": memo_id }),+ )?;+ memo_value(database, &memo_id, true)+}++pub(crate) fn restore_memo_revision(+ database: &Connection,+ params: &Value,+) -> Result<Value, String> {+ let memo_id = string_param(params, "memoId")?;+ let revision_id = string_param(params, "revisionId")?;+ let current = memo_value(database, &memo_id, true)?;+ let revision = revision_value(database, &memo_id, &revision_id)?;+ let title = revision+ .get("title")+ .and_then(Value::as_str)+ .unwrap_or("")+ .trim()+ .to_owned();+ let content_json = revision+ .get("contentJson")+ .cloned()+ .unwrap_or_else(|| json!({"type":"doc","content":[]}));+ let content_json_text = content_json.to_string();+ let markdown = revision+ .get("contentMarkdown")+ .and_then(Value::as_str)+ .unwrap_or("")+ .to_owned();+ let text = revision+ .get("contentText")+ .and_then(Value::as_str)+ .unwrap_or(&markdown)+ .to_owned();+ let tags = revision.get("tags").cloned().unwrap_or_else(|| json!([]));+ let hash = content_hash(&markdown, &content_json_text);+ let next_revision = current.get("revision").and_then(Value::as_i64).unwrap_or(0) + 1;+ let tx = database+ .unchecked_transaction()+ .map_err(|e| e.to_string())?;+ insert_revision(&tx, ¤t, "desktop")?;+ tx.execute("UPDATE memos SET title = ?2, excerpt = ?3, tags_json = ?4, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), updated_by = 'desktop' WHERE id = ?1", rusqlite::params![memo_id, if title.is_empty() { None } else { Some(title.clone()) }, text.chars().take(180).collect::<String>(), tags.to_string()]).map_err(|e| e.to_string())?;+ tx.execute("UPDATE memo_contents SET content_json = ?2, content_markdown = ?3, content_text = ?4, content_hash = ?5, revision = ?6, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE memo_id = ?1", rusqlite::params![memo_id, content_json_text, markdown, text, hash, next_revision]).map_err(|e| e.to_string())?;+ tx.commit().map_err(|e| e.to_string())?;+ enqueue_change(+ database,+ "memo.update",+ &memo_id,+ &json!({+ "memoId": memo_id, "expectedRevision": current.get("revision").and_then(Value::as_i64).unwrap_or(0),+ "expectedContentHash": current.get("contentHash").and_then(Value::as_str).unwrap_or(""),+ "title": title, "contentJson": content_json, "contentMarkdown": markdown, "tags": tags,+ }),+ )?;+ memo_value(database, &memo_id, true).map(|memo| json!({ "memo": memo }))+}diff --git a/crates/desktop-sidecar/src/rpc.rs b/crates/desktop-sidecar/src/rpc.rsnew file mode 100644index 00000000..fd50cd80--- /dev/null+++ b/crates/desktop-sidecar/src/rpc.rs@@ -0,0 +1,167 @@+use rusqlite::Connection;+use serde::{Deserialize, Serialize};+use serde_json::{json, Value};+use std::env;+use std::path::Path;+use std::time::{SystemTime, UNIX_EPOCH};++use crate::catalog::{+ cache_resource, cache_template, create_notebook, create_template, delete_cached_resource,+ delete_notebook, delete_template, list_notebooks, list_resources, list_tags, list_templates,+ restore_notebook, rewrite_tag, update_notebook, update_template,+};+use crate::database::{backup_database, list_backups, restore_database};+use crate::memo::{+ cache_memo_revision, create_memo, delete_memo, delete_memos, empty_trash, list_memo_revisions,+ list_memos, memo_value, merge_memos, move_memos, pin_memos, restore_memo,+ restore_memo_revision, update_memo,+};+use crate::sync::{+ apply_sync_changes, prepare_sync_bootstrap, sync_outbox_ack, sync_outbox_discard,+ sync_outbox_fail, sync_outbox_list, sync_outbox_recover_memo_update, sync_outbox_retry,+ sync_status, SYNC_BOOTSTRAP_RESET_KEY,+};+use crate::{bool_param, set_meta, string_param};++pub(crate) const PROTOCOL_VERSION: i64 = 2;++#[derive(Debug, Deserialize)]+pub(crate) struct RpcRequest {+ pub(crate) id: Value,+ method: String,+ #[serde(default)]+ params: Value,+}++#[derive(Debug, Serialize)]+pub(crate) struct RpcError<'a> {+ pub(crate) code: &'a str,+ pub(crate) message: String,+}++pub(crate) fn handle(+ request: RpcRequest,+ database: &mut Connection,+ root: &Path,+ migrations: &Path,+) -> Result<Value, String> {+ match request.method.as_str() {+ "system.info" => Ok(json!({+ "platform": env::consts::OS,+ "architecture": env::consts::ARCH,+ "dataDir": root,+ "protocolVersion": PROTOCOL_VERSION,+ })),+ "storage.health" => database+ .query_row("SELECT 1", [], |row| row.get::<_, i64>(0))+ .map(|_| json!({ "ok": true }))+ .map_err(|error| error.to_string()),+ "storage.backup" => backup_database(database, root)+ .map(|path| json!({ "ok": true, "path": path }))+ .map_err(|error| error.to_string()),+ "storage.backups" => list_backups(root).map_err(|error| error.to_string()),+ "storage.restore" => restore_database(database, root, migrations, &request.params),+ "sync.status" => sync_status(database),+ "sync.bootstrap.prepare" => prepare_sync_bootstrap(database, &request.params),+ "sync.outbox.list" => sync_outbox_list(database, &request.params),+ "sync.outbox.ack" => sync_outbox_ack(database, &request.params),+ "sync.outbox.fail" => sync_outbox_fail(database, &request.params),+ "sync.outbox.retry" => sync_outbox_retry(database, &request.params),+ "sync.outbox.recoverMemoUpdate" => {+ sync_outbox_recover_memo_update(database, &request.params)+ }+ "sync.outbox.discard" => sync_outbox_discard(database, &request.params),+ "sync.apply" => apply_sync_changes(database, &request.params),+ "sync.cursor.set" => {+ set_meta(+ database,+ "sync.cursor",+ &request+ .params+ .get("cursor")+ .and_then(Value::as_i64)+ .unwrap_or(0)+ .to_string(),+ )?;+ set_meta(+ database,+ "sync.identity",+ request+ .params+ .get("syncIdentity")+ .and_then(Value::as_str)+ .unwrap_or(""),+ )?;+ set_meta(database, "sync.last_synced_at", &chrono_like_now())?;+ database+ .execute(+ "DELETE FROM _edgeever_sidecar_meta WHERE key = ?1",+ [SYNC_BOOTSTRAP_RESET_KEY],+ )+ .map_err(|e| e.to_string())?;+ database+ .execute_batch(+ "DROP TABLE IF EXISTS temp._edgeever_bootstrap_preserved_memos;+ DROP TABLE IF EXISTS temp._edgeever_bootstrap_preserved_notebooks;",+ )+ .map_err(|e| e.to_string())?;+ Ok(json!({ "ok": true }))+ }+ "notebook.list" => list_notebooks(database),+ "notebook.create" => create_notebook(database, &request.params)+ .map(|notebook| json!({ "notebook": notebook })),+ "notebook.update" => update_notebook(database, &request.params)+ .map(|notebook| json!({ "notebook": notebook })),+ "notebook.delete" => delete_notebook(database, &request.params),+ "notebook.restore" => restore_notebook(database, &request.params)+ .map(|notebook| json!({ "notebook": notebook })),+ "template.list" => list_templates(database),+ "template.cache" => cache_template(database, &request.params),+ "template.create" => create_template(database, &request.params)+ .map(|template| json!({ "template": template })),+ "template.update" => update_template(database, &request.params)+ .map(|template| json!({ "template": template })),+ "template.delete" => delete_template(database, &request.params),+ "resource.list" => list_resources(database, &request.params),+ "resource.cache" => cache_resource(database, &request.params),+ "resource.delete" => delete_cached_resource(database, &request.params),+ "tag.list" => list_tags(database),+ "tag.rename" => rewrite_tag(database, &request.params, false),+ "tag.delete" => rewrite_tag(database, &request.params, true),+ "memo.moveBatch" => move_memos(database, &request.params),+ "memo.deleteBatch" => delete_memos(database, &request.params),+ "memo.emptyTrash" => empty_trash(database),+ "memo.pinBatch" => pin_memos(database, &request.params),+ "memo.merge" => merge_memos(database, &request.params),+ "memo.list" => list_memos(database, &request.params),+ "memo.get" => {+ let memo_id = string_param(&request.params, "memoId")?;+ memo_value(+ database,+ &memo_id,+ bool_param(&request.params, "includeDeleted", false),+ )+ .map(|memo| json!({ "memo": memo }))+ }+ "memo.create" => create_memo(database, &request.params).map(|memo| json!({ "memo": memo })),+ "memo.update" => update_memo(database, &request.params).map(|memo| json!({ "memo": memo })),+ "memo.delete" => delete_memo(database, &request.params),+ "memo.restore" => {+ restore_memo(database, &request.params).map(|memo| json!({ "memo": memo }))+ }+ "memo.revisions" => list_memo_revisions(database, &request.params),+ "memo.restoreRevision" => restore_memo_revision(database, &request.params),+ "memo.revision.cache" => cache_memo_revision(database, &request.params),+ "app.shutdown" => Ok(json!({ "ok": true })),+ _ => Err(format!("Unknown sidecar method: {}", request.method)),+ }+}++fn chrono_like_now() -> String {+ // SQLite owns persisted timestamps; this value is only a human-readable sync marker.+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap_or_default()+ .as_secs()+ .to_string()+}diff --git a/crates/desktop-sidecar/src/sync.rs b/crates/desktop-sidecar/src/sync.rsnew file mode 100644index 00000000..ce522531--- /dev/null+++ b/crates/desktop-sidecar/src/sync.rs@@ -0,0 +1,673 @@+use rusqlite::Connection;+use serde_json::{json, Value};++use crate::memo::{create_memo, memo_value};+use crate::{bool_param, enqueue_change, memo_remap_base_key, meta_value, set_meta, string_param};++pub(crate) fn sync_status(database: &Connection) -> Result<Value, String> {+ let count = |status: &str| -> Result<i64, String> {+ database+ .query_row(+ "SELECT COUNT(*) FROM _edgeever_sidecar_outbox WHERE status = ?1",+ [status],+ |row| row.get(0),+ )+ .map_err(|e| e.to_string())+ };+ Ok(json!({+ "pending": count("pending")?, "syncing": count("syncing")?, "conflict": count("conflict")?, "error": count("error")?,+ "cursor": meta_value(database, "sync.cursor").and_then(|v| v.parse::<i64>().ok()).unwrap_or(0),+ "syncIdentity": meta_value(database, "sync.identity"), "lastSyncedAt": meta_value(database, "sync.last_synced_at")+ }))+}++pub(crate) const SYNC_BOOTSTRAP_RESET_KEY: &str = "sync.bootstrap.reset_pending";++fn reset_sync_mirror(database: &Connection) -> Result<(), String> {+ let tx = database+ .unchecked_transaction()+ .map_err(|e| e.to_string())?;+ tx.execute_batch(+ "CREATE TEMP TABLE IF NOT EXISTS _edgeever_bootstrap_preserved_memos (id TEXT PRIMARY KEY);+ CREATE TEMP TABLE IF NOT EXISTS _edgeever_bootstrap_preserved_notebooks (id TEXT PRIMARY KEY);+ DELETE FROM _edgeever_bootstrap_preserved_memos;+ DELETE FROM _edgeever_bootstrap_preserved_notebooks;+ INSERT OR IGNORE INTO _edgeever_bootstrap_preserved_memos (id)+ SELECT m.id FROM memos m+ WHERE EXISTS (+ SELECT 1 FROM _edgeever_sidecar_outbox o+ WHERE o.entity_id = m.id OR instr(o.payload_json, m.id) > 0+ );+ INSERT OR IGNORE INTO _edgeever_bootstrap_preserved_notebooks (id)+ SELECT n.id FROM notebooks n+ WHERE EXISTS (+ SELECT 1 FROM _edgeever_sidecar_outbox o+ WHERE o.entity_id = n.id OR instr(o.payload_json, n.id) > 0+ );+ INSERT OR IGNORE INTO _edgeever_bootstrap_preserved_notebooks (id)+ SELECT DISTINCT m.notebook_id+ FROM memos m+ INNER JOIN _edgeever_bootstrap_preserved_memos p ON p.id = m.id;+ WITH RECURSIVE preserved_ancestors(id, parent_id) AS (+ SELECT n.id, n.parent_id+ FROM notebooks n+ INNER JOIN _edgeever_bootstrap_preserved_notebooks p ON p.id = n.id+ UNION+ SELECT parent.id, parent.parent_id+ FROM notebooks parent+ INNER JOIN preserved_ancestors child ON child.parent_id = parent.id+ )+ INSERT OR IGNORE INTO _edgeever_bootstrap_preserved_notebooks (id)+ SELECT id FROM preserved_ancestors;+ DELETE FROM resources+ WHERE memo_id NOT IN (SELECT id FROM _edgeever_bootstrap_preserved_memos);+ DELETE FROM memos+ WHERE id NOT IN (SELECT id FROM _edgeever_bootstrap_preserved_memos);+ UPDATE notebooks SET parent_id = NULL+ WHERE id NOT IN (SELECT id FROM _edgeever_bootstrap_preserved_notebooks);+ DELETE FROM notebooks+ WHERE id NOT IN (SELECT id FROM _edgeever_bootstrap_preserved_notebooks);+ DELETE FROM _edgeever_sidecar_meta+ WHERE key IN ('sync.cursor', 'sync.identity', 'sync.last_synced_at')+ OR key LIKE 'memo.remap-base:%';+ INSERT INTO _edgeever_sidecar_meta (key, value, updated_at)+ VALUES ('sync.bootstrap.reset_pending', '1', strftime('%Y-%m-%dT%H:%M:%fZ','now'))+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at;",+ )+ .map_err(|e| e.to_string())?;+ tx.commit().map_err(|e| e.to_string())+}++pub(crate) fn prepare_sync_bootstrap(+ database: &Connection,+ params: &Value,+) -> Result<Value, String> {+ let reset_requested = bool_param(params, "reset", false)+ || meta_value(database, SYNC_BOOTSTRAP_RESET_KEY).as_deref() == Some("1");+ if reset_requested {+ reset_sync_mirror(database)?;+ return Ok(json!({ "clearedSeedData": false, "rebuiltMirror": true }));+ }++ if meta_value(database, "sync.identity").is_some_and(|identity| !identity.is_empty()) {+ return Ok(json!({ "clearedSeedData": false, "rebuiltMirror": false }));+ }++ let outbox_count = database+ .query_row("SELECT COUNT(*) FROM _edgeever_sidecar_outbox", [], |row| {+ row.get::<_, i64>(0)+ })+ .map_err(|e| e.to_string())?;+ let non_seed_memos = database+ .query_row(+ "SELECT COUNT(*) FROM memos WHERE id <> 'memo_welcome'",+ [],+ |row| row.get::<_, i64>(0),+ )+ .map_err(|e| e.to_string())?;+ let non_seed_notebooks = database+ .query_row(+ "SELECT COUNT(*) FROM notebooks+ WHERE id NOT IN ('nb_inbox', 'nb_projects', 'nb_learning', 'nb_creative', 'nb_personal')",+ [],+ |row| row.get::<_, i64>(0),+ )+ .map_err(|e| e.to_string())?;++ if outbox_count > 0 || non_seed_memos > 0 || non_seed_notebooks > 0 {+ return Ok(json!({ "clearedSeedData": false, "rebuiltMirror": false }));+ }++ let tx = database+ .unchecked_transaction()+ .map_err(|e| e.to_string())?;+ tx.execute("DELETE FROM memos WHERE id = 'memo_welcome'", [])+ .map_err(|e| e.to_string())?;+ tx.execute(+ "DELETE FROM notebooks+ WHERE id IN ('nb_inbox', 'nb_projects', 'nb_learning', 'nb_creative', 'nb_personal')",+ [],+ )+ .map_err(|e| e.to_string())?;+ tx.commit().map_err(|e| e.to_string())?;+ Ok(json!({ "clearedSeedData": true, "rebuiltMirror": false }))+}++pub(crate) fn sync_outbox_list(database: &Connection, params: &Value) -> Result<Value, String> {+ let limit = params+ .get("limit")+ .and_then(Value::as_i64)+ .unwrap_or(50)+ .clamp(1, 200);+ let include_conflicts = bool_param(params, "includeConflicts", false);+ let sql = if include_conflicts {+ "SELECT id, kind, entity_id, payload_json, attempt_count, status, last_error, version, last_error_code, retryable, next_attempt_at, created_at, updated_at FROM _edgeever_sidecar_outbox WHERE status IN ('pending', 'error', 'conflict') ORDER BY id LIMIT ?1"+ } else {+ "SELECT id, kind, entity_id, payload_json, attempt_count, status, last_error, version, last_error_code, retryable, next_attempt_at, created_at, updated_at FROM _edgeever_sidecar_outbox WHERE status = 'pending' OR (status = 'error' AND retryable = 1 AND (next_attempt_at IS NULL OR next_attempt_at <= strftime('%Y-%m-%dT%H:%M:%fZ','now'))) ORDER BY id LIMIT ?1"+ };+ let mut statement = database.prepare(sql).map_err(|e| e.to_string())?;+ let rows = statement.query_map([limit], |row| {+ let payload: String = row.get(3)?;+ Ok(json!({ "id": row.get::<_, i64>(0)?, "kind": row.get::<_, String>(1)?, "entityId": row.get::<_, String>(2)?, "payload": serde_json::from_str::<Value>(&payload).unwrap_or_else(|_| json!({})), "attemptCount": row.get::<_, i64>(4)?, "status": row.get::<_, String>(5)?, "lastError": row.get::<_, Option<String>>(6)?, "version": row.get::<_, i64>(7)?, "lastErrorCode": row.get::<_, Option<String>>(8)?, "retryable": row.get::<_, bool>(9)?, "nextAttemptAt": row.get::<_, Option<String>>(10)?, "createdAt": row.get::<_, String>(11)?, "updatedAt": row.get::<_, String>(12)? }))+ }).map_err(|e| e.to_string())?;+ let items: Result<Vec<_>, _> = rows.collect();+ Ok(json!({ "items": items.map_err(|e| e.to_string())? }))+}++pub(crate) fn sync_outbox_ack(database: &Connection, params: &Value) -> Result<Value, String> {+ let id = params+ .get("id")+ .and_then(Value::as_i64)+ .ok_or_else(|| "Missing outbox id".to_owned())?;+ let (kind, entity_id, current_version): (String, String, i64) = database+ .query_row(+ "SELECT kind, entity_id, version FROM _edgeever_sidecar_outbox WHERE id = ?1",+ [id],+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),+ )+ .map_err(|e| e.to_string())?;+ let requested_version = params.get("version").and_then(Value::as_i64);+ let superseded = requested_version.is_some_and(|version| version != current_version);+ let remote_memo = params.get("remoteMemo").cloned();+ let remote_notebook = params.get("remoteNotebook").cloned();+ let remote_template = params.get("remoteTemplate").cloned();+ let temporary_memo_base = if kind == "memo.create" {+ memo_value(database, &entity_id, true).ok().map(|memo| {+ (+ memo.get("revision").and_then(Value::as_i64).unwrap_or(0),+ memo.get("contentHash")+ .and_then(Value::as_str)+ .unwrap_or("")+ .to_owned(),+ )+ })+ } else {+ None+ };++ if kind == "memo.update" && superseded {+ if let Some(remote) = remote_memo.as_ref() {+ let remote_revision = remote.get("revision").and_then(Value::as_i64).unwrap_or(0);+ let remote_hash = remote+ .get("contentHash")+ .and_then(Value::as_str)+ .unwrap_or("");+ let payload_text: String = database+ .query_row(+ "SELECT payload_json FROM _edgeever_sidecar_outbox WHERE id = ?1",+ [id],+ |row| row.get(0),+ )+ .map_err(|e| e.to_string())?;+ let mut payload: Value =+ serde_json::from_str(&payload_text).unwrap_or_else(|_| json!({}));+ payload["expectedRevision"] = json!(remote_revision);+ payload["expectedContentHash"] = json!(remote_hash);+ let tx = database+ .unchecked_transaction()+ .map_err(|e| e.to_string())?;+ // Preserve the successor draft's content while advancing only its+ // acknowledged cloud base. The next flush will send that draft on+ // top of the response that just succeeded.+ tx.execute(+ "UPDATE memo_contents SET revision = ?1 WHERE memo_id = ?2",+ rusqlite::params![remote_revision, entity_id],+ )+ .map_err(|e| e.to_string())?;+ tx.execute(+ "UPDATE _edgeever_sidecar_outbox+ SET payload_json = ?1, status = 'pending', last_error = NULL,+ updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')+ WHERE id = ?2",+ rusqlite::params![payload.to_string(), id],+ )+ .map_err(|e| e.to_string())?;+ tx.commit().map_err(|e| e.to_string())?;+ }+ return Ok(json!({+ "ok": true,+ "superseded": true,+ "memo": remote_memo,+ "notebook": remote_notebook,+ "template": remote_template+ }));+ }++ if let Some(remote) = remote_memo.as_ref() {+ let remote_id = string_param(remote, "id")?;+ apply_sync_changes(+ database,+ &json!({+ "changes": [{+ "entityType": "memo",+ "operation": "upsert",+ "entityId": remote_id,+ "memo": remote,+ "notebook": null+ }]+ }),+ )?;+ }+ if kind == "memo.create" || kind == "memo.merge" {+ if let Some(remote) = remote_memo.as_ref() {+ let remote_id = string_param(remote, "id")?;+ let remote_exists: bool = database+ .query_row(+ "SELECT EXISTS(SELECT 1 FROM memos WHERE id = ?1)",+ [&remote_id],+ |row| row.get(0),+ )+ .map_err(|e| e.to_string())?;+ if remote_exists {+ // The acknowledgement caches the remote memo before reconciling+ // the local placeholder, so the remote id exists here.+ // A merged local memo can still own resources moved from its+ // sources. Deleting it directly is rejected by the resources+ // foreign key and leaves both the local placeholder and remote+ // memo visible forever. Repoint every surviving relationship+ // before removing the placeholder, and keep the reconciliation+ // atomic so a crash cannot strand a partially remapped merge.+ let tx = database+ .unchecked_transaction()+ .map_err(|e| e.to_string())?;+ tx.execute(+ "UPDATE resources SET memo_id = ?1 WHERE memo_id = ?2",+ rusqlite::params![remote_id, entity_id],+ )+ .map_err(|e| e.to_string())?;+ tx.execute(+ "UPDATE resources SET original_memo_id = ?1 WHERE original_memo_id = ?2",+ rusqlite::params![remote_id, entity_id],+ )+ .map_err(|e| e.to_string())?;+ tx.execute(+ "UPDATE memos SET merged_into_memo_id = ?1 WHERE merged_into_memo_id = ?2",+ rusqlite::params![remote_id, entity_id],+ )+ .map_err(|e| e.to_string())?;+ tx.execute("DELETE FROM memos WHERE id = ?1", [&entity_id])+ .map_err(|e| e.to_string())?;+ tx.commit().map_err(|e| e.to_string())?;+ } else {+ database+ .execute(+ "UPDATE memos SET id = ?1 WHERE id = ?2",+ rusqlite::params![remote_id, entity_id],+ )+ .map_err(|e| e.to_string())?;+ }+ let mut pending = database.prepare("SELECT id, entity_id, payload_json FROM _edgeever_sidecar_outbox WHERE id <> ?1").map_err(|e| e.to_string())?;+ let rows: Vec<(i64, String, String)> = pending+ .query_map([id], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))+ .map_err(|e| e.to_string())?+ .collect::<Result<_, _>>()+ .map_err(|e| e.to_string())?;+ for (outbox_id, outbox_entity, payload_text) in rows {+ if outbox_entity != entity_id && !payload_text.contains(&entity_id) {+ continue;+ }+ let mut payload: Value =+ serde_json::from_str(&payload_text).unwrap_or_else(|_| json!({}));+ if payload.get("memoId").and_then(Value::as_str) == Some(entity_id.as_str()) {+ payload["memoId"] = json!(remote_id);+ }+ if payload.get("temporaryId").and_then(Value::as_str) == Some(entity_id.as_str()) {+ payload["temporaryId"] = json!(remote_id);+ }+ if payload.get("memoId").and_then(Value::as_str) == Some(remote_id.as_str()) {+ if let Some(revision) = remote.get("revision") {+ payload["expectedRevision"] = revision.clone();+ }+ if let Some(hash) = remote.get("contentHash") {+ payload["expectedContentHash"] = hash.clone();+ }+ }+ let next_entity = if outbox_entity == entity_id {+ remote_id.clone()+ } else {+ outbox_entity+ };+ database.execute("UPDATE _edgeever_sidecar_outbox SET entity_id = ?1, payload_json = ?2, version = version + 1 WHERE id = ?3", rusqlite::params![next_entity, payload.to_string(), outbox_id]).map_err(|e| e.to_string())?;+ }+ if kind == "memo.create" {+ if let Some((temporary_revision, temporary_content_hash)) =+ temporary_memo_base.as_ref()+ {+ set_meta(+ database,+ &memo_remap_base_key(&remote_id),+ &json!({+ "temporaryRevision": temporary_revision,+ "temporaryContentHash": temporary_content_hash,+ "remoteRevision": remote.get("revision").and_then(Value::as_i64).unwrap_or(0),+ "remoteContentHash": remote.get("contentHash").and_then(Value::as_str).unwrap_or("")+ })+ .to_string(),+ )?;+ }+ }+ }+ }+ if kind == "notebook.create" {+ if let Some(remote) = remote_notebook.as_ref() {+ let remote_id = string_param(remote, "id")?;+ let remote_exists: bool = database+ .query_row(+ "SELECT EXISTS(SELECT 1 FROM notebooks WHERE id = ?1)",+ [&remote_id],+ |row| row.get(0),+ )+ .map_err(|e| e.to_string())?;+ if remote_exists {+ database+ .execute("DELETE FROM notebooks WHERE id = ?1", [&entity_id])+ .map_err(|e| e.to_string())?;+ } else {+ database+ .execute(+ "UPDATE notebooks SET id = ?1 WHERE id = ?2",+ rusqlite::params![remote_id, entity_id],+ )+ .map_err(|e| e.to_string())?;+ }+ let mut pending = database.prepare("SELECT id, entity_id, payload_json FROM _edgeever_sidecar_outbox WHERE id <> ?1").map_err(|e| e.to_string())?;+ let rows: Vec<(i64, String, String)> = pending+ .query_map([id], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))+ .map_err(|e| e.to_string())?+ .collect::<Result<_, _>>()+ .map_err(|e| e.to_string())?;+ for (outbox_id, outbox_entity, payload_text) in rows {+ if outbox_entity != entity_id && !payload_text.contains(&entity_id) {+ continue;+ }+ let mut payload: Value =+ serde_json::from_str(&payload_text).unwrap_or_else(|_| json!({}));+ if payload.get("notebookId").and_then(Value::as_str) == Some(entity_id.as_str()) {+ payload["notebookId"] = json!(remote_id);+ }+ if payload.get("temporaryId").and_then(Value::as_str) == Some(entity_id.as_str()) {+ payload["temporaryId"] = json!(remote_id);+ }+ let next_entity = if outbox_entity == entity_id {+ remote_id.clone()+ } else {+ outbox_entity+ };+ database.execute("UPDATE _edgeever_sidecar_outbox SET entity_id = ?1, payload_json = ?2, version = version + 1 WHERE id = ?3", rusqlite::params![next_entity, payload.to_string(), outbox_id]).map_err(|e| e.to_string())?;+ }+ }+ }+ if kind == "template.create" {+ if let Some(remote) = remote_template.as_ref() {+ let remote_id = string_param(remote, "id")?;+ let remote_exists: bool = database+ .query_row(+ "SELECT EXISTS(SELECT 1 FROM memo_templates WHERE id = ?1)",+ [&remote_id],+ |row| row.get(0),+ )+ .map_err(|e| e.to_string())?;+ if remote_exists {+ database+ .execute("DELETE FROM memo_templates WHERE id = ?1", [&entity_id])+ .map_err(|e| e.to_string())?;+ } else {+ database+ .execute(+ "UPDATE memo_templates SET id = ?1 WHERE id = ?2",+ rusqlite::params![remote_id, entity_id],+ )+ .map_err(|e| e.to_string())?;+ }+ let mut pending = database.prepare("SELECT id, entity_id, payload_json FROM _edgeever_sidecar_outbox WHERE id <> ?1").map_err(|e| e.to_string())?;+ let rows: Vec<(i64, String, String)> = pending+ .query_map([id], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))+ .map_err(|e| e.to_string())?+ .collect::<Result<_, _>>()+ .map_err(|e| e.to_string())?;+ for (outbox_id, outbox_entity, payload_text) in rows {+ if outbox_entity != entity_id && !payload_text.contains(&entity_id) {+ continue;+ }+ let mut payload: Value =+ serde_json::from_str(&payload_text).unwrap_or_else(|_| json!({}));+ if payload.get("templateId").and_then(Value::as_str) == Some(entity_id.as_str()) {+ payload["templateId"] = json!(remote_id);+ }+ if payload.get("temporaryId").and_then(Value::as_str) == Some(entity_id.as_str()) {+ payload["temporaryId"] = json!(remote_id);+ }+ let next_entity = if outbox_entity == entity_id {+ remote_id.clone()+ } else {+ outbox_entity+ };+ database.execute("UPDATE _edgeever_sidecar_outbox SET entity_id = ?1, payload_json = ?2, version = version + 1 WHERE id = ?3", rusqlite::params![next_entity, payload.to_string(), outbox_id]).map_err(|e| e.to_string())?;+ }+ }+ }+ let deleted = if let Some(version) = requested_version {+ database+ .execute(+ "DELETE FROM _edgeever_sidecar_outbox WHERE id = ?1 AND version = ?2",+ rusqlite::params![id, version],+ )+ .map_err(|e| e.to_string())?+ } else {+ database+ .execute("DELETE FROM _edgeever_sidecar_outbox WHERE id = ?1", [id])+ .map_err(|e| e.to_string())?+ };+ Ok(+ json!({ "ok": true, "superseded": deleted == 0, "memo": remote_memo, "notebook": remote_notebook, "template": remote_template }),+ )+}++pub(crate) fn sync_outbox_fail(database: &Connection, params: &Value) -> Result<Value, String> {+ let id = params+ .get("id")+ .and_then(Value::as_i64)+ .ok_or_else(|| "Missing outbox id".to_owned())?;+ let error = params+ .get("error")+ .and_then(Value::as_str)+ .unwrap_or("sync failed");+ let status = if bool_param(params, "conflict", false) {+ "conflict"+ } else {+ "error"+ };+ let error_code = params.get("errorCode").and_then(Value::as_str);+ let retryable = params+ .get("retryable")+ .and_then(Value::as_bool)+ .unwrap_or(true);+ let next_attempt_at = params.get("nextAttemptAt").and_then(Value::as_str);+ let updated = if let Some(version) = params.get("version").and_then(Value::as_i64) {+ database.execute("UPDATE _edgeever_sidecar_outbox SET status = ?1, attempt_count = attempt_count + 1, last_error = ?2, last_error_code = ?3, retryable = ?4, next_attempt_at = ?5, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?6 AND version = ?7", rusqlite::params![status, error, error_code, retryable, next_attempt_at, id, version]).map_err(|e| e.to_string())?+ } else {+ database.execute("UPDATE _edgeever_sidecar_outbox SET status = ?1, attempt_count = attempt_count + 1, last_error = ?2, last_error_code = ?3, retryable = ?4, next_attempt_at = ?5, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?6", rusqlite::params![status, error, error_code, retryable, next_attempt_at, id]).map_err(|e| e.to_string())?+ };+ Ok(json!({ "ok": true, "superseded": updated == 0 }))+}++pub(crate) fn sync_outbox_retry(database: &Connection, params: &Value) -> Result<Value, String> {+ let id = params+ .get("id")+ .and_then(Value::as_i64)+ .ok_or_else(|| "Missing outbox id".to_owned())?;+ let version = params.get("version").and_then(Value::as_i64);+ let updated = if let Some(version) = version {+ database.execute(+ "UPDATE _edgeever_sidecar_outbox SET status = 'pending', retryable = 1, next_attempt_at = NULL, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?1 AND version = ?2 AND status = 'error'",+ rusqlite::params![id, version],+ )+ } else {+ database.execute(+ "UPDATE _edgeever_sidecar_outbox SET status = 'pending', retryable = 1, next_attempt_at = NULL, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?1 AND status = 'error'",+ [id],+ )+ }+ .map_err(|e| e.to_string())?;+ if updated == 0 {+ return Err("The failed sync item changed before retry".to_owned());+ }+ Ok(json!({ "ok": true }))+}++pub(crate) fn sync_outbox_recover_memo_update(+ database: &Connection,+ params: &Value,+) -> Result<Value, String> {+ let id = params+ .get("id")+ .and_then(Value::as_i64)+ .ok_or_else(|| "Missing outbox id".to_owned())?;+ let notebook_id = string_param(params, "notebookId")?;+ let requested_version = params.get("version").and_then(Value::as_i64);+ let (kind, payload_text, version, status): (String, String, i64, String) = database+ .query_row(+ "SELECT kind, payload_json, version, status FROM _edgeever_sidecar_outbox WHERE id = ?1",+ [id],+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),+ )+ .map_err(|e| e.to_string())?;+ if kind != "memo.update" || status != "error" {+ return Err("Only failed memo updates can be recovered".to_owned());+ }+ if requested_version.is_some_and(|value| value != version) {+ return Err("The failed update changed before recovery".to_owned());+ }+ let notebook_exists: bool = database+ .query_row(+ "SELECT EXISTS(SELECT 1 FROM notebooks WHERE id = ?1 AND is_deleted = 0)",+ [¬ebook_id],+ |row| row.get(0),+ )+ .map_err(|e| e.to_string())?;+ if !notebook_exists {+ return Err("Recovery notebook not found".to_owned());+ }+ let mut payload: Value = serde_json::from_str(&payload_text).map_err(|e| e.to_string())?;+ let object = payload+ .as_object_mut()+ .ok_or_else(|| "Invalid failed memo payload".to_owned())?;+ object.insert("notebookId".to_owned(), json!(notebook_id));+ let memo = create_memo(database, &payload)?;+ let recovered_id = string_param(&memo, "id")?;+ payload["memoId"] = json!(recovered_id);+ payload["expectedRevision"] = json!(0);+ payload["expectedContentHash"] = memo+ .get("contentHash")+ .cloned()+ .unwrap_or_else(|| json!(""));+ enqueue_change(database, "memo.update", &recovered_id, &payload)?;+ let removed = database+ .execute(+ "DELETE FROM _edgeever_sidecar_outbox WHERE id = ?1 AND version = ?2 AND status = 'error'",+ rusqlite::params![id, version],+ )+ .map_err(|e| e.to_string())?;+ if removed == 0 {+ database+ .execute(+ "DELETE FROM _edgeever_sidecar_outbox WHERE entity_id = ?1",+ [&recovered_id],+ )+ .ok();+ database+ .execute("DELETE FROM memos WHERE id = ?1", [&recovered_id])+ .ok();+ return Err("The failed update changed before recovery".to_owned());+ }+ Ok(json!({ "ok": true, "memo": memo }))+}++pub(crate) fn sync_outbox_discard(database: &Connection, params: &Value) -> Result<Value, String> {+ let id = params+ .get("id")+ .and_then(Value::as_i64)+ .ok_or_else(|| "Missing outbox id".to_owned())?;+ let removed = if let Some(version) = params.get("version").and_then(Value::as_i64) {+ database.execute(+ "DELETE FROM _edgeever_sidecar_outbox WHERE id = ?1 AND version = ?2",+ rusqlite::params![id, version],+ )+ } else {+ database.execute("DELETE FROM _edgeever_sidecar_outbox WHERE id = ?1", [id])+ }+ .map_err(|e| e.to_string())?;+ if removed == 0 {+ return Err("The sync item changed before it was discarded".to_owned());+ }+ Ok(json!({ "ok": true }))+}++pub(crate) fn apply_sync_changes(database: &Connection, params: &Value) -> Result<Value, String> {+ let changes = params+ .get("changes")+ .and_then(Value::as_array)+ .ok_or_else(|| "Missing changes array".to_owned())?;+ let rebuilding = meta_value(database, SYNC_BOOTSTRAP_RESET_KEY).as_deref() == Some("1");+ let tx = database+ .unchecked_transaction()+ .map_err(|e| e.to_string())?;+ for change in changes {+ let entity_type = string_param(change, "entityType")?;+ let operation = string_param(change, "operation")?;+ let entity_id = string_param(change, "entityId")?;+ if rebuilding {+ let preserved_table = if entity_type == "notebook" {+ "_edgeever_bootstrap_preserved_notebooks"+ } else {+ "_edgeever_bootstrap_preserved_memos"+ };+ let preserved = tx+ .query_row(+ &format!("SELECT EXISTS(SELECT 1 FROM {preserved_table} WHERE id = ?1)"),+ [&entity_id],+ |row| row.get::<_, bool>(0),+ )+ .unwrap_or(false);+ if preserved {+ continue;+ }+ }+ if entity_type == "notebook" {+ if operation == "delete" {+ tx.execute("UPDATE notebooks SET is_deleted = 1, deleted_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?1", [&entity_id]).map_err(|e| e.to_string())?;+ continue;+ }+ let notebook = change+ .get("notebook")+ .ok_or_else(|| "Missing notebook change payload".to_owned())?;+ tx.execute("INSERT INTO notebooks (id, parent_id, name, slug, icon, color, sort_order, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9) ON CONFLICT(id) DO UPDATE SET parent_id=excluded.parent_id, name=excluded.name, slug=excluded.slug, icon=excluded.icon, color=excluded.color, sort_order=excluded.sort_order, updated_at=excluded.updated_at, is_deleted=0", rusqlite::params![entity_id, notebook.get("parentId").and_then(Value::as_str), string_param(notebook, "name")?, notebook.get("slug").and_then(Value::as_str), notebook.get("icon").and_then(Value::as_str), notebook.get("color").and_then(Value::as_str), notebook.get("sortOrder").and_then(Value::as_i64).unwrap_or(0), string_param(notebook, "createdAt")?, string_param(notebook, "updatedAt")?]).map_err(|e| e.to_string())?;+ continue;+ }+ if operation == "delete" {+ tx.execute("UPDATE memos SET is_deleted = 1, deleted_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?1", [&entity_id]).map_err(|e| e.to_string())?;+ continue;+ }+ let memo = change+ .get("memo")+ .ok_or_else(|| "Missing memo change payload".to_owned())?;+ let tags = memo+ .get("tags")+ .cloned()+ .unwrap_or_else(|| json!([]))+ .to_string();+ let source_ids = memo+ .get("sourceMemoIds")+ .cloned()+ .unwrap_or_else(|| json!([]))+ .to_string();+ let content_json = memo+ .get("contentJson")+ .cloned()+ .unwrap_or_else(|| json!({"type":"doc","content":[]}));+ tx.execute("INSERT INTO memos (id, notebook_id, title, excerpt, tags_json, is_pinned, is_archived, is_deleted, source_memo_ids, merge_source_count, merged_into_memo_id, created_at, updated_at, deleted_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14) ON CONFLICT(id) DO UPDATE SET notebook_id=excluded.notebook_id, title=excluded.title, excerpt=excluded.excerpt, tags_json=excluded.tags_json, is_pinned=excluded.is_pinned, is_archived=excluded.is_archived, is_deleted=excluded.is_deleted, updated_at=excluded.updated_at, deleted_at=excluded.deleted_at", rusqlite::params![entity_id, string_param(memo, "notebookId")?, memo.get("title").and_then(Value::as_str), string_param(memo, "excerpt")?, tags, memo.get("isPinned").and_then(Value::as_bool).unwrap_or(false) as i64, memo.get("isArchived").and_then(Value::as_bool).unwrap_or(false) as i64, memo.get("isDeleted").and_then(Value::as_bool).unwrap_or(false) as i64, source_ids, memo.get("mergeSourceCount").and_then(Value::as_i64).unwrap_or(0), memo.get("mergedIntoMemoId").and_then(Value::as_str), string_param(memo, "createdAt")?, string_param(memo, "updatedAt")?, memo.get("deletedAt").and_then(Value::as_str)]).map_err(|e| e.to_string())?;+ tx.execute("INSERT INTO memo_contents (memo_id, content_json, content_markdown, content_text, content_hash, revision) VALUES (?1, ?2, ?3, ?4, ?5, ?6) ON CONFLICT(memo_id) DO UPDATE SET content_json=excluded.content_json, content_markdown=excluded.content_markdown, content_text=excluded.content_text, content_hash=excluded.content_hash, revision=excluded.revision, updated_at=strftime('%Y-%m-%dT%H:%M:%fZ','now')", rusqlite::params![entity_id, content_json.to_string(), string_param(memo, "contentMarkdown")?, string_param(memo, "contentText")?, string_param(memo, "contentHash")?, memo.get("revision").and_then(Value::as_i64).unwrap_or(0)]).map_err(|e| e.to_string())?;+ }+ tx.commit().map_err(|e| e.to_string())?;+ Ok(json!({ "applied": changes.len() }))+}diff --git a/packages/client/src/index.test.mjs b/packages/client/src/index.test.mjsindex 46bd5f64..c5c063b9 100644--- a/packages/client/src/index.test.mjs+++ b/packages/client/src/index.test.mjs@@ -50,6 +50,62 @@ describe("EdgeEver client HTTP contract", () => {expect(calls[0].init.credentials).toBe("include");});+ test("resolves runtime base URLs and credentials for every request", async () => {+ let baseUrl = "https://first.example/";+ let token = "first-token";+ const calls = [];+ const contexts = [];+ const client = createEdgeEverClient({+ baseUrl: () => baseUrl,+ token: () => token,+ beforeRequest: (context) => contexts.push(context),+ shouldAttachToken: (path) => path !== "/api/v1/auth/login",+ fetch: async (input, init) => {+ calls.push({+ input: String(input),+ authorization: new Headers(init.headers).get("Authorization"),+ });+ return jsonResponse({ authenticated: true, notebooks: [], memos: [], totalCount: 0, nextAfterId: null });+ },+ });++ await client.getSession();+ baseUrl = "https://second.example///";+ token = "second-token";+ await client.syncBootstrap({ limit: 20 });+ await client.login({ username: "admin", password: "secret" });++ expect(calls).toEqual([+ { input: "https://first.example/api/v1/auth/session", authorization: "Bearer first-token" },+ { input: "https://second.example/api/v1/sync/bootstrap?limit=20", authorization: "Bearer second-token" },+ { input: "https://second.example/api/v1/auth/login", authorization: null },+ ]);+ expect(contexts.map(({ path, token: requestToken }) => [path, requestToken])).toEqual([+ ["/api/v1/auth/session", "first-token"],+ ["/api/v1/sync/bootstrap?limit=20", "second-token"],+ ["/api/v1/auth/login", "second-token"],+ ]);+ });++ test("does not leak API credentials or JSON headers to absolute resource URLs", async () => {+ let call;+ const client = createEdgeEverClient({+ baseUrl: "https://notes.example",+ token: "secret",+ fetch: async (input, init) => {+ call = { input: String(input), headers: new Headers(init.headers) };+ return new Response("asset");+ },+ });++ const blob = await client.getResourceBlob("https://assets.example/file.bin");++ expect(await blob.text()).toBe("asset");+ expect(call.input).toBe("https://assets.example/file.bin");+ expect(call.headers.get("Authorization")).toBeNull();+ expect(call.headers.get("Content-Type")).toBeNull();+ });+test("keeps multipart restore bodies free of a synthetic JSON content type", async () => {let headers;const client = createEdgeEverClient({diff --git a/packages/client/src/index.ts b/packages/client/src/index.tsindex 51e8d10b..baaa33a9 100644--- a/packages/client/src/index.ts+++ b/packages/client/src/index.ts@@ -19,6 +19,7 @@ import type {Resource,ResourceListItem,ResourceStorageSummary,+ ObjectStorageSettings,PublicMemoShare,TagSummary,TiptapDoc,@@ -33,13 +34,23 @@ import type {AiTagSuggestionPromptUpdateInput,AiTagSuggestionsRequestInput,AiTagSuggestionsResponse,+ SyncBootstrapResponse,+ SyncChange,+ SyncChangesResponse,} from "@edgeever/shared";+export type EdgeEverClientRequestContext = {+ path: string;+ token?: string;+};+export type EdgeEverClientOptions = {- baseUrl?: string;- token?: string | null;+ baseUrl?: string | (() => string);+ token?: string | null | (() => string | null | undefined);fetch?: typeof fetch;- onUnauthorized?: () => void;+ beforeRequest?: (context: EdgeEverClientRequestContext) => void | Promise<void>;+ shouldAttachToken?: (path: string) => boolean;+ onUnauthorized?: (context: EdgeEverClientRequestContext) => void | Promise<void>;};export type InstanceHealth = {@@ -104,6 +115,11 @@ export type ListLoginDeviceSessionsResponse = {sessions: LoginDeviceSession[];};+export type ObjectStorageSettingsResponse = {+ settings: ObjectStorageSettings;+ externalSettings?: ObjectStorageSettings | null;+};+export type MemoResponse = {memo: MemoDetail;};@@ -160,31 +176,14 @@ export type AiProviderUpdatePayload = {isEnabled: boolean;};-export type MobileSyncBootstrapPage = {- notebooks: Notebook[];- memos: MemoDetail[];- snapshotCursor: number;- syncIdentity?: string;- totalCount: number;- nextAfterId: string | null;-};+/** @deprecated Use SyncBootstrapResponse; kept for mobile source compatibility. */+export type MobileSyncBootstrapPage = SyncBootstrapResponse;-export type MobileSyncChange = {- cursor: number;- entityType: "notebook" | "memo";- entityId: string;- operation: "upsert" | "delete";- notebook: Notebook | null;- memo: MemoDetail | null;-};+/** @deprecated Use SyncChange; kept for mobile source compatibility. */+export type MobileSyncChange = SyncChange;-export type MobileSyncChangesPage = {- changes: MobileSyncChange[];- cursor: number;- hasMore: boolean;- serverCursor?: number;- syncIdentity?: string;-};+/** @deprecated Use SyncChangesResponse; kept for mobile source compatibility. */+export type MobileSyncChangesPage = SyncChangesResponse;export class ApiRequestError extends Error {status: number;@@ -214,57 +213,110 @@ export type ApiResponseDiagnostics = {rayId?: string;};+export type { SyncBootstrapResponse, SyncChangesResponse };+export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {- const fetchImpl = options.fetch ?? fetch;- const baseUrl = normalizeBaseUrl(options.baseUrl);+ const getFetch = () => options.fetch ?? globalThis.fetch;+ const getBaseUrl = () => normalizeBaseUrl(+ typeof options.baseUrl === "function" ? options.baseUrl() : options.baseUrl,+ );+ const getToken = () => {+ const token = typeof options.token === "function" ? options.token() : options.token;+ return token || undefined;+ };++ const send = async (+ path: string,+ init?: RequestInit,+ requestOptions?: { attachToken?: boolean; setJsonContentType?: boolean },+ ) => {+ const token = getToken();+ const context: EdgeEverClientRequestContext = { path, ...(token ? { token } : {}) };+ await options.beforeRequest?.(context);- const request = async <T>(path: string, init?: RequestInit): Promise<T> => {const headers = new Headers(init?.headers);+ const attachToken = requestOptions?.attachToken+ ?? options.shouldAttachToken?.(path)+ ?? true;- if (options.token && !headers.has("Authorization")) {- headers.set("Authorization", `Bearer ${options.token}`);+ if (token && attachToken && !headers.has("Authorization")) {+ headers.set("Authorization", `Bearer ${token}`);}- if (!(init?.body instanceof FormData) && !headers.has("Content-Type")) {+ if (+ requestOptions?.setJsonContentType !== false+ && !(init?.body instanceof FormData)+ && !headers.has("Content-Type")+ ) {headers.set("Content-Type", "application/json");}- const response = await fetchImpl(`${baseUrl}${path}`, {+ const requestUrl = isAbsoluteHttpUrl(path) ? path : `${getBaseUrl()}${path}`;+ const response = await getFetch()(requestUrl, {credentials: "include",...init,headers,});- if (!response.ok) {- const body = await response.json().catch(() => null);- const rayId = response.headers.get("cf-ray")?.trim();- const error =- body && typeof body === "object" && "error" in body- ? (body as { error?: { code?: string; message?: string; details?: unknown } }).error- : undefined;- const message = error?.message ?? response.statusText;- const responseDiagnostics: ApiResponseDiagnostics = {- cloudflareMitigated: response.headers.get("cf-mitigated") === "challenge",- isEdgeEverApiError: Boolean(error && typeof error === "object"),- ...(rayId ? { rayId } : {}),- };-- if (response.status === 401) {- options.onUnauthorized?.();- }+ return { context, response };+ };- throw new ApiRequestError(- message || "Request failed",- response.status,- error?.code,- error?.details,- responseDiagnostics,- );+ const throwRequestError = async (+ context: EdgeEverClientRequestContext,+ response: Response,+ fallbackMessage = "Request failed",+ ): Promise<never> => {+ const body = await response.json().catch(() => null);+ const rayId = response.headers.get("cf-ray")?.trim();+ const error =+ body && typeof body === "object" && "error" in body+ ? (body as { error?: { code?: string; message?: string; details?: unknown } }).error+ : undefined;+ const responseDiagnostics: ApiResponseDiagnostics = {+ cloudflareMitigated: response.headers.get("cf-mitigated") === "challenge",+ isEdgeEverApiError: Boolean(error && typeof error === "object"),+ ...(rayId ? { rayId } : {}),+ };++ if (response.status === 401) {+ void options.onUnauthorized?.(context);+ }++ throw new ApiRequestError(+ error?.message || response.statusText || fallbackMessage,+ response.status,+ error?.code,+ error?.details,+ responseDiagnostics,+ );+ };++ const request = async <T>(path: string, init?: RequestInit): Promise<T> => {+ const { context, response } = await send(path, init);++ if (!response.ok) {+ await throwRequestError(context, response);}return response.json() as Promise<T>;};+ const requestBlob = async (path: string) => {+ const isAbsolute = isAbsoluteHttpUrl(path);+ const { context, response } = await send(path, undefined, {+ attachToken: !isAbsolute,+ setJsonContentType: false,+ });+ if (!response.ok) await throwRequestError(context, response, "Resource download failed");+ return response.blob();+ };++ const requestArrayBuffer = async (path: string) => {+ const { context, response } = await send(path, undefined, { setJsonContentType: false });+ if (!response.ok) await throwRequestError(context, response, "Binary download failed");+ return response.arrayBuffer();+ };+return {getInstanceHealth: () => request<InstanceHealth>("/api/health"),@@ -281,6 +333,12 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {revokeLoginDeviceSession: (sessionId: string) =>request<{ ok: true }>(`/api/v1/auth/sessions/${sessionId}`, { method: "DELETE" }),+ updateLoginDeviceSession: (sessionId: string, payload: { label: string | null }) =>+ request<{ ok: true }>(`/api/v1/auth/sessions/${sessionId}`, {+ method: "PATCH",+ body: JSON.stringify(payload),+ }),+revokeOtherLoginDeviceSessions: () =>request<{ ok: true }>("/api/v1/auth/sessions", { method: "DELETE" }),@@ -296,6 +354,39 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {body: JSON.stringify(payload),}),+ getObjectStorageSettings: () =>+ request<ObjectStorageSettingsResponse>("/api/v1/instance/object-storage"),++ testObjectStorageConnection: (payload: {+ endpoint: string;+ region: string;+ bucket: string;+ accessKeyId: string;+ secretAccessKey?: string;+ forcePathStyle: boolean;+ objectPrefix: string;+ }) => request<{ ok: true }>("/api/v1/instance/object-storage/test", {+ method: "POST",+ body: JSON.stringify(payload),+ }),++ updateObjectStorageSettings: (payload:+ | { provider: "builtin" }+ | {+ provider: "s3";+ displayName: string;+ endpoint: string;+ region: string;+ bucket: string;+ accessKeyId: string;+ secretAccessKey?: string;+ forcePathStyle: boolean;+ objectPrefix: string;+ }) => request<ObjectStorageSettingsResponse>("/api/v1/instance/object-storage", {+ method: "PUT",+ body: JSON.stringify(payload),+ }),+getAiSettings: (locale?: string) => {const search = locale ? `?locale=${encodeURIComponent(locale)}` : "";return request<AiSettings>(`/api/v1/ai/settings${search}`);@@ -318,7 +409,12 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {method: "DELETE",}),- testAiProvider: (providerConfigId: string, payload: { modelId: string }) =>+ testAiProvider: (providerConfigId: string, payload: {+ modelId: string;+ provider?: AiProvider;+ baseUrl?: string;+ apiKey?: string;+ }) =>request<{ ok: true; response: string }>(`/api/v1/ai/providers/${encodeURIComponent(providerConfigId)}/test`, {method: "POST",body: JSON.stringify(payload),@@ -397,19 +493,14 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {payload: AiGenerateInput,streamOptions: { signal?: AbortSignal; onEvent: (event: AiStreamEvent) => void },) => {- const headers = new Headers({ "Content-Type": "application/json" });- if (options.token) headers.set("Authorization", `Bearer ${options.token}`);- const response = await fetchImpl(`${baseUrl}/api/v1/ai/generate`, {+ const path = "/api/v1/ai/generate";+ const { context, response } = await send(path, {method: "POST",- credentials: "include",- headers,body: JSON.stringify(payload),signal: streamOptions.signal,});if (!response.ok) {- const body = await response.json().catch(() => null) as { error?: { code?: string; message?: string } } | null;- if (response.status === 401) options.onUnauthorized?.();- throw new ApiRequestError(body?.error?.message || response.statusText, response.status, body?.error?.code);+ await throwRequestError(context, response);}if (!response.body) throw new ApiRequestError("Streaming response is unavailable", 502, "ai_stream_unavailable");const reader = response.body.getReader();@@ -452,6 +543,20 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {listNotebooks: () => request<ListNotebooksResponse>("/api/v1/notebooks"),+ syncBootstrap: (params?: { afterId?: string | null; limit?: number }) => {+ const search = new URLSearchParams();+ if (params?.afterId) search.set("afterId", params.afterId);+ if (params?.limit) search.set("limit", String(params.limit));+ const suffix = search.toString() ? `?${search.toString()}` : "";+ return request<SyncBootstrapResponse>(`/api/v1/sync/bootstrap${suffix}`);+ },++ syncChanges: (params: { cursor: number; limit?: number }) => {+ const search = new URLSearchParams({ cursor: String(params.cursor) });+ if (params.limit) search.set("limit", String(params.limit));+ return request<SyncChangesResponse>(`/api/v1/sync/changes?${search.toString()}`);+ },+getMobileSyncBootstrapPage: (afterId: string | null = null, limit = 100) => {const search = new URLSearchParams({ limit: String(limit) });if (afterId) {@@ -480,6 +585,11 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {method: "DELETE",}),+ restoreNotebook: (notebookId: string) =>+ request<NotebookResponse>(`/api/v1/notebooks/${notebookId}/restore`, {+ method: "POST",+ }),+listTags: () => request<ListTagsResponse>("/api/v1/tags"),renameTag: (tag: string, name: string) =>@@ -573,12 +683,38 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {listTemplates: () => request<ListTemplatesResponse>("/api/v1/templates"),+ createTemplate: (payload: {+ name: string;+ description?: string | null;+ memoId?: string;+ title?: string | null;+ contentMarkdown?: string;+ tags?: string[];+ }) => request<TemplateResponse>("/api/v1/templates", {+ method: "POST",+ body: JSON.stringify(payload),+ }),++ updateTemplate: (templateId: string, payload: {+ name?: string;+ description?: string | null;+ title?: string | null;+ contentMarkdown?: string;+ tags?: string[];+ }) => request<TemplateResponse>(`/api/v1/templates/${templateId}`, {+ method: "PATCH",+ body: JSON.stringify(payload),+ }),+useTemplate: (templateId: string, notebookId: string) =>request<MemoResponse>(`/api/v1/templates/${templateId}/use`, {method: "POST",body: JSON.stringify({ notebookId }),}),+ deleteTemplate: (templateId: string) =>+ request<{ ok: true }>(`/api/v1/templates/${templateId}`, { method: "DELETE" }),+moveMemos: (payload: { memoIds: string[]; notebookId: string }) =>request<{ ok: true; moved: number }>("/api/v1/memos/batch/move", {method: "POST",@@ -680,35 +816,26 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {});},- getResourceBlob: async (resourceUrl: string) => {- const headers = new Headers();-- if (options.token) {- headers.set("Authorization", `Bearer ${options.token}`);- }-- const response = await fetchImpl(`${baseUrl}${resourceUrl}`, {- credentials: "include",- headers,+ getResourceBlob: (resourceUrl: string) => requestBlob(resourceUrl),++ downloadGithubPluginAsset: (+ owner: string,+ repository: string,+ assetId: number,+ assetName: "manifest.json" | "main.js" | "styles.css",+ ) => requestArrayBuffer(+ `/api/v1/plugins/github/${encodeURIComponent(owner)}/${encodeURIComponent(repository)}/assets/${assetId}/${encodeURIComponent(assetName)}`,+ ),++ uploadMemoResource: (memoId: string, file: Blob | FormData) => {+ const form = file instanceof FormData ? file : new FormData();+ if (!(file instanceof FormData)) form.append("file", file);+ return request<ResourceResponse>(`/api/v1/memos/${memoId}/resources`, {+ method: "POST",+ body: form,});-- if (!response.ok) {- if (response.status === 401) {- options.onUnauthorized?.();- }-- throw new ApiRequestError(response.statusText || "Resource download failed", response.status);- }-- return response.blob();},- uploadMemoResource: (memoId: string, file: FormData) =>- request<ResourceResponse>(`/api/v1/memos/${memoId}/resources`, {- method: "POST",- body: file,- }),-updateMemo: (memoId: string,payload: {@@ -753,6 +880,11 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {method: "POST",body: JSON.stringify(payload),}),++ resetDemo: () =>+ request<{ success: true }>("/api/v1/demo/reset", {+ method: "POST",+ }),};};@@ -763,3 +895,5 @@ const normalizeBaseUrl = (value?: string) => {return value.replace(/\/+$/, "");};++const isAbsoluteHttpUrl = (value: string) => /^https?:\/\//i.test(value);diff --git a/packages/shared/src/desktop-rpc.test.mjs b/packages/shared/src/desktop-rpc.test.mjsnew file mode 100644index 00000000..7ff68363--- /dev/null+++ b/packages/shared/src/desktop-rpc.test.mjs@@ -0,0 +1,39 @@+import { describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";+import {+ DESKTOP_RPC_METHODS,+ DESKTOP_SIDECAR_PROTOCOL_VERSION,+} from "./desktop-rpc.ts";++const rustRpcSource = readFileSync(+ new URL("../../../crates/desktop-sidecar/src/rpc.rs", import.meta.url),+ "utf8",+);+const electronRpcSource = readFileSync(+ new URL("../../../apps/desktop/src/main/rpc.mjs", import.meta.url),+ "utf8",+);++describe("desktop sidecar RPC contract", () => {+ test("keeps the TypeScript method registry aligned with the Rust dispatcher", () => {+ const dispatcherStart = rustRpcSource.indexOf("match request.method.as_str()");+ const dispatcherEnd = rustRpcSource.indexOf("\n }\n}\n\nfn chrono_like_now", dispatcherStart);+ const dispatcher = rustRpcSource.slice(dispatcherStart, dispatcherEnd);+ const rustMethods = [...dispatcher.matchAll(/"([^"]+)"\s*=>/g)]+ .map((match) => match[1])+ .filter((method) => method !== "app.shutdown")+ .sort();++ expect([...DESKTOP_RPC_METHODS].sort()).toEqual(rustMethods);+ });++ test("keeps the native and Electron protocol guards aligned", () => {+ const rustVersion = Number(rustRpcSource.match(/const PROTOCOL_VERSION: i64 = (\d+);/)?.[1]);+ const electronVersion = Number(+ electronRpcSource.match(/SIDECAR_PROTOCOL_VERSION = (\d+);/)?.[1],+ );++ expect(rustVersion).toBe(DESKTOP_SIDECAR_PROTOCOL_VERSION);+ expect(electronVersion).toBe(DESKTOP_SIDECAR_PROTOCOL_VERSION);+ });+});diff --git a/packages/shared/src/desktop-rpc.ts b/packages/shared/src/desktop-rpc.tsindex 67f41fec..fdcf83be 100644--- a/packages/shared/src/desktop-rpc.ts+++ b/packages/shared/src/desktop-rpc.ts@@ -1,50 +1,57 @@import type { MemoDetail, MemoSummary, MemoTemplate, Notebook, ResourceListItem, ResourceStorageSummary } from "./types";import type { TiptapDoc } from "./content";-export type DesktopRpcMethod =- | "system.info"- | "storage.health"- | "storage.backup"- | "storage.backups"- | "storage.restore"- | "sync.status"- | "sync.bootstrap.prepare"- | "notebook.list"- | "notebook.create"- | "notebook.update"- | "notebook.delete"- | "notebook.restore"- | "template.list"- | "template.cache"- | "template.create"- | "template.update"- | "template.delete"- | "resource.list"- | "resource.cache"- | "resource.delete"- | "tag.list"- | "tag.rename"- | "tag.delete"- | "memo.moveBatch"- | "memo.deleteBatch"- | "memo.emptyTrash"- | "memo.pinBatch"- | "memo.merge"- | "memo.list"- | "memo.get"- | "memo.create"- | "memo.update"- | "memo.delete"- | "memo.restore"- | "memo.revisions"- | "memo.restoreRevision"- | "memo.revision.cache"- | "sync.outbox.list"- | "sync.outbox.ack"- | "sync.outbox.fail"- | "sync.outbox.discard"- | "sync.apply"- | "sync.cursor.set";+export const DESKTOP_SIDECAR_PROTOCOL_VERSION = 2;++export const DESKTOP_RPC_METHODS = [+ "system.info",+ "storage.health",+ "storage.backup",+ "storage.backups",+ "storage.restore",+ "sync.status",+ "sync.bootstrap.prepare",+ "sync.outbox.list",+ "sync.outbox.ack",+ "sync.outbox.fail",+ "sync.outbox.retry",+ "sync.outbox.recoverMemoUpdate",+ "sync.outbox.discard",+ "sync.apply",+ "sync.cursor.set",+ "notebook.list",+ "notebook.create",+ "notebook.update",+ "notebook.delete",+ "notebook.restore",+ "template.list",+ "template.cache",+ "template.create",+ "template.update",+ "template.delete",+ "resource.list",+ "resource.cache",+ "resource.delete",+ "tag.list",+ "tag.rename",+ "tag.delete",+ "memo.moveBatch",+ "memo.deleteBatch",+ "memo.emptyTrash",+ "memo.pinBatch",+ "memo.merge",+ "memo.list",+ "memo.get",+ "memo.create",+ "memo.update",+ "memo.delete",+ "memo.restore",+ "memo.revisions",+ "memo.restoreRevision",+ "memo.revision.cache",+] as const;++export type DesktopRpcMethod = (typeof DESKTOP_RPC_METHODS)[number];export type DesktopMemoListParams = {notebookId?: string | null;@@ -170,6 +177,17 @@ export type DesktopRpcParams = {"storage.restore": { path: string };};+type DesktopRpcContractMismatch =+ | Exclude<DesktopRpcMethod, keyof DesktopRpcParams>+ | Exclude<keyof DesktopRpcParams, DesktopRpcMethod>+ | Exclude<DesktopRpcMethod, keyof DesktopRpcResponses>+ | Exclude<keyof DesktopRpcResponses, DesktopRpcMethod>;++type AssertNoDesktopRpcContractMismatch<Mismatch extends never> = Mismatch;++export type DesktopRpcContractIsComplete =+ AssertNoDesktopRpcContractMismatch<DesktopRpcContractMismatch>;+export type DesktopOutboxItem = {id: number;kind: "memo.create" | "memo.update" | "memo.delete" | "memo.restore" | "memo.move" | "memo.deleteBatch" | "memo.emptyTrash" | "memo.pinBatch" | "memo.merge" | "notebook.create" | "notebook.update" | "notebook.delete" | "notebook.restore" | "template.create" | "template.update" | "template.delete" | "tag.rename" | "tag.delete";diff --git a/packages/shared/src/sync.test.mjs b/packages/shared/src/sync.test.mjsindex f6374574..0a4b0f04 100644--- a/packages/shared/src/sync.test.mjs+++ b/packages/shared/src/sync.test.mjs@@ -6,7 +6,12 @@ import {getNextSyncQueueRetryDelay,getSyncRetryAt,getSyncRetryDelayMs,+ hasSyncCursorRewound,+ hasSyncIdentityChanged,+ hasSyncStateReset,+ isSyncMetadataInitialized,isMemoSyncBaseCurrent,+ splitSyncBootstrapWriteBatches,summarizeSyncQueue,} from "./sync.ts";@@ -82,4 +87,23 @@ describe("shared sync queue contract", () => {source: "offline_sync",});});++ test("detects a reset shared by mobile and desktop mirrors", () => {+ expect(hasSyncCursorRewound(42, 7)).toBe(true);+ expect(hasSyncCursorRewound(42, 42)).toBe(false);+ expect(hasSyncIdentityChanged("workspace-a", "workspace-b")).toBe(true);+ expect(hasSyncIdentityChanged("workspace-a", "workspace-a")).toBe(false);+ expect(hasSyncStateReset(+ { cursor: 42, syncIdentity: "workspace-a" },+ { serverCursor: 64, syncIdentity: "workspace-b" },+ )).toBe(true);+ });++ test("validates mirror metadata and splits bootstrap writes", () => {+ expect(isSyncMetadataInitialized("42", "workspace-a")).toBe(true);+ expect(isSyncMetadataInitialized("not-a-number", "workspace-a")).toBe(false);+ expect(splitSyncBootstrapWriteBatches(Array.from({ length: 123 }, (_, index) => index), 50)+ .map((batch) => batch.length)).toEqual([50, 50, 23]);+ expect(splitSyncBootstrapWriteBatches([], 50)).toEqual([[]]);+ });});diff --git a/packages/shared/src/sync.ts b/packages/shared/src/sync.tsindex 75790155..ecceae3b 100644--- a/packages/shared/src/sync.ts+++ b/packages/shared/src/sync.ts@@ -25,7 +25,8 @@ export type SyncChangesResponse = {changes: SyncChange[];cursor: number;hasMore: boolean;- serverCursor: number;+ /** Absent on older servers; clients must keep the current mirror when omitted. */+ serverCursor?: number;syncIdentity?: string;};@@ -34,6 +35,11 @@ export type SyncCursorState = {syncIdentity: string;};+export type RemoteSyncCursorState = {+ serverCursor?: number;+ syncIdentity?: string;+};+export type SyncOutboxOperation =| "memo.create"| "memo.update"@@ -140,3 +146,41 @@ export const getNextSyncQueueRetryDelay = (return Math.max(minimumDelayMs, Math.min(...retryTimes) - now);};++export const hasSyncCursorRewound = (localCursor: number, serverCursor?: number) =>+ typeof serverCursor === "number"+ && Number.isFinite(serverCursor)+ && serverCursor < localCursor;++export const hasSyncIdentityChanged = (localIdentity: string, serverIdentity?: string) =>+ typeof serverIdentity === "string"+ && serverIdentity.length > 0+ && serverIdentity !== localIdentity;++export const hasSyncStateReset = (+ local: SyncCursorState,+ remote: RemoteSyncCursorState,+) => hasSyncCursorRewound(local.cursor, remote.serverCursor)+ || hasSyncIdentityChanged(local.syncIdentity, remote.syncIdentity);++export const isSyncMetadataInitialized = (+ cursorValue: string | null | undefined,+ identityValue: string | null | undefined,+) => Boolean(identityValue?.trim())+ && typeof cursorValue === "string"+ && cursorValue.trim().length > 0+ && Number.isFinite(Number(cursorValue));++export const splitSyncBootstrapWriteBatches = <T>(+ items: readonly 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/tests/e2e/ai-custom-prompts.spec.ts b/tests/e2e/ai-custom-prompts.spec.tsindex 10e11f75..d5b8b7d3 100644--- a/tests/e2e/ai-custom-prompts.spec.ts+++ b/tests/e2e/ai-custom-prompts.spec.ts@@ -244,7 +244,7 @@ test.describe("AI custom prompts", () => {await page.keyboard.press("Enter");const emptyParagraph = editor.locator("p").last();await expect(emptyParagraph).toHaveClass(/is-empty/);- await expect(emptyParagraph).toHaveAttribute("data-placeholder", "按 Space 使用 AI,输入 / 浏览命令");+ await expect(emptyParagraph).toHaveAttribute("data-placeholder", "Space 唤起 AI · / 浏览命令 · @ 引用笔记");const renderedPlaceholder = await emptyParagraph.evaluate((element) => {const style = getComputedStyle(element, "::before");return {@@ -253,7 +253,7 @@ test.describe("AI custom prompts", () => {visibility: style.visibility,};});- expect(renderedPlaceholder.content).toContain("按 Space 使用 AI,输入 / 浏览命令");+ expect(renderedPlaceholder.content).toContain("Space 唤起 AI · / 浏览命令 · @ 引用笔记");expect(renderedPlaceholder.display).not.toBe("none");expect(renderedPlaceholder.visibility).not.toBe("hidden");@@ -292,7 +292,7 @@ test.describe("AI custom prompts", () => {await page.keyboard.press("End");await page.keyboard.press("Enter");const emptyParagraph = editor.locator("p").last();- await expect(emptyParagraph).toHaveAttribute("data-placeholder", "输入 / 浏览命令");+ await expect(emptyParagraph).toHaveAttribute("data-placeholder", "/ 浏览命令 · @ 引用笔记");await page.keyboard.press("Space");await expect(page.getByRole("dialog", { name: "AI 笔记助手" })).toBeHidden();diff --git a/tests/e2e/dark-mode.spec.ts b/tests/e2e/dark-mode.spec.tsindex 01a2ebc3..78453994 100644--- a/tests/e2e/dark-mode.spec.ts+++ b/tests/e2e/dark-mode.spec.ts@@ -98,7 +98,12 @@ test.describe("dark mode visual contracts", () => {test("notebook move picker keeps highlighted options dark and selected labels clean", async ({ page }) => {await page.goto("/");- await page.getByRole("button", { name: "选择笔记", exact: true }).click();+ const selectMemosButton = page.getByRole("button", { name: "选择笔记", exact: true });+ if (await selectMemosButton.isDisabled()) {+ await page.getByRole("button", { name: "手动同步笔记", exact: true }).click();+ }+ await expect(selectMemosButton).toBeEnabled({ timeout: 20_000 });+ await selectMemosButton.click();const actionBar = page.locator("[data-memo-selection-action-bar]");const actionCard = actionBar.locator(":scope > div");diff --git a/tests/mobile-ai-assistant.test.ts b/tests/mobile-ai-assistant.test.tsindex d1fbd8ea..1de8dbb2 100644--- a/tests/mobile-ai-assistant.test.ts+++ b/tests/mobile-ai-assistant.test.ts@@ -6,7 +6,11 @@ const readSource = (path: string) => readFileSync(new URL(path, import.meta.url)const androidAssistantSource = readSource("../apps/mobile/src/components/MobileAiAssistantModal.tsx");const androidEditorSource = readSource("../apps/mobile/src/components/LocalTiptapEditor.tsx");const androidDetailSource = readSource("../apps/mobile/src/screens/WorkspaceMemoDetail.tsx");-const androidWorkspaceSource = readSource("../apps/mobile/src/screens/WorkspaceScreen.tsx");+const androidWorkspaceSource = [+ readSource("../apps/mobile/src/screens/WorkspaceScreen.tsx"),+ readSource("../apps/mobile/src/screens/WorkspaceEditors.tsx"),+ readSource("../apps/mobile/src/screens/WorkspacePickers.tsx"),+].join("\n");const androidSessionSource = readSource("../apps/mobile/src/lib/session.tsx");const iosAssistantSource = readSource("../apps/ios/EdgeEver/Features/Workspace/AiAssistantSheet.swift");const iosDetailSource = readSource("../apps/ios/EdgeEver/Features/Workspace/MemoDetailView.swift");diff --git a/tests/mobile-app-scope.test.ts b/tests/mobile-app-scope.test.tsindex 96e55972..7cffb97d 100644--- a/tests/mobile-app-scope.test.ts+++ b/tests/mobile-app-scope.test.ts@@ -5,6 +5,10 @@ const workspaceSource = readFileSync(new URL("../apps/mobile/src/screens/WorkspaceScreen.tsx", import.meta.url),"utf8");+const workspaceEditorsSource = readFileSync(+ new URL("../apps/mobile/src/screens/WorkspaceEditors.tsx", import.meta.url),+ "utf8"+);const memoDetailSource = readFileSync(new URL("../apps/mobile/src/screens/WorkspaceMemoDetail.tsx", import.meta.url),"utf8"@@ -84,8 +88,8 @@ describe("mobile app scope", () => {});test("keeps the Android editor caret visible while the keyboard viewport changes", () => {- expect(workspaceSource).toContain("KeyboardAvoidingView");- expect(workspaceSource).toContain('enabled={Platform.OS === "android"}');+ expect(workspaceEditorsSource).toContain("KeyboardAvoidingView");+ expect(workspaceEditorsSource).toContain('enabled={Platform.OS === "android"}');expect(localTiptapEditorSource).toContain('visualViewport?.addEventListener("resize", ensureSelectionVisible)');expect(localTiptapEditorSource).toContain("--edgeever-keyboard-inset");expect(localTiptapEditorSource).toContain("scrollEditorPositionIntoView(editor, editor.state.selection.head)");@@ -102,18 +106,18 @@ describe("mobile app scope", () => {test("hardens DOM/WebView hosts against media capture probes during App Review", () => {expect(mobileDomSource).toContain('mediaCapturePermissionGrantType: "deny"');expect(mobileDomSource).toContain("mediaPlaybackRequiresUserAction: true");- expect(workspaceSource).toContain("SAFE_DOM_WEBVIEW_PROPS");+ expect(workspaceEditorsSource).toContain("SAFE_DOM_WEBVIEW_PROPS");expect(memoDetailSource).toContain("SAFE_DOM_WEBVIEW_PROPS");});test("reads the latest create and upload state from the hardware-back handler", () => {- expect(workspaceSource).toContain("createPendingRef.current || imageOperationRef.current");+ expect(workspaceEditorsSource).toContain("createPendingRef.current || imageOperationRef.current");});test("focuses the note body instead of the title when creating a note", () => {- const createMemoSource = workspaceSource.slice(- workspaceSource.indexOf("const CreateMemoModal ="),- workspaceSource.indexOf("const RichEditorModal =")+ const createMemoSource = workspaceEditorsSource.slice(+ workspaceEditorsSource.indexOf("export const CreateMemoModal ="),+ workspaceEditorsSource.indexOf("export const RichEditorModal ="));const titleInput = createMemoSource.match(/<TextInput\s+autoCorrect\s+accessibilityLabel="笔记标题"[\s\S]*?\/>/@@ -127,9 +131,9 @@ describe("mobile app scope", () => {});test("keeps editor startup recoverable and avoids competing autofocus paths", () => {- expect(workspaceSource).toContain("MOBILE_EDITOR_STARTUP_TIMEOUT_MS");- expect(workspaceSource).toContain("MobileEditorStartupOverlay");- expect(workspaceSource).toContain("key={editorStartup.attempt}");+ expect(workspaceEditorsSource).toContain("MOBILE_EDITOR_STARTUP_TIMEOUT_MS");+ expect(workspaceEditorsSource).toContain("MobileEditorStartupOverlay");+ expect(workspaceEditorsSource).toContain("key={editorStartup.attempt}");expect(localTiptapEditorSource).toContain("autofocus: false");expect(localTiptapEditorSource).toContain('import("mermaid/dist/mermaid.min.js")');expect(localTiptapEditorSource).toContain('import("beautiful-mermaid")');diff --git a/tests/storage-adapter.test.ts b/tests/storage-adapter.test.tsindex 1794f463..0a44107a 100644--- a/tests/storage-adapter.test.ts+++ b/tests/storage-adapter.test.ts@@ -25,6 +25,43 @@ describe("storage adapter", () => {expect(SELF_HOSTED_DATABASE_DIALECT).toBe("sqlite");});+ test("implements the portable statement result contract without D1 types", async () => {+ const executions: Array<{ sql: string; bindings: unknown[] }> = [];+ const sqlite = {+ query: (sql: string) => ({+ all: (...bindings: unknown[]) => [{ sql, value: bindings[0] }],+ get: (...bindings: unknown[]) => ({ sql, value: bindings[0] }),+ run: (...bindings: unknown[]) => {+ executions.push({ sql, bindings });+ return { changes: 1, lastInsertRowid: 7 };+ },+ }),+ transaction: (callback: () => void) => () => callback(),+ };+ const database = createSelfHostedStorageAdapter(sqlite, ".edgeever-unused-resources").db;+ const statement = database.prepare("SELECT ? AS value").bind("edgeever");++ await expect(statement.all<{ sql: string; value: string }>()).resolves.toMatchObject({+ success: true,+ results: [{ sql: "SELECT ? AS value", value: "edgeever" }],+ });+ await expect(statement.first<string>("value")).resolves.toBe("edgeever");+ await expect(database.prepare("UPDATE notes SET value = ?").bind("updated").run()).resolves.toMatchObject({+ success: true,+ results: [],+ meta: { changes: 1, lastInsertRowid: 7 },+ });+ await expect(database.batch([+ database.prepare("DELETE FROM notes WHERE id = ?").bind("one"),+ database.prepare("DELETE FROM notes WHERE id = ?").bind("two"),+ ])).resolves.toHaveLength(2);+ expect(executions.map(({ bindings }) => bindings)).toEqual([+ ["updated"],+ ["one"],+ ["two"],+ ]);+ });+test("stores attachments in a persistent filesystem directory", async () => {const directory = await mkdtemp(`${tmpdir()}/edgeever-storage-`);const sqlite = {