AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
feat: add memo revision history
tianma5fde1e90bff5
diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex 48b9faa7..4fbdeb4a 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -12,6 +12,7 @@ import {NotebookCreateSchema,NotebookUpdateSchema,type MemoDetail,+ type MemoRevision,type MemoSummary,type Notebook,type Resource,@@ -81,6 +82,20 @@ type MemoDetailRow = MemoSummaryRow & {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 UserRow = {id: string;username: string;@@ -145,6 +160,7 @@ const SESSION_TOKEN_BYTES = 32;const DEFAULT_SESSION_TTL_DAYS = 30;const DEFAULT_R2_BUCKET_NAME = "edgeever-resources";const MAX_IMAGE_UPLOAD_BYTES = 10 * 1024 * 1024;+const REVISION_SNAPSHOT_INTERVAL_MS = 5 * 60 * 1000;const SUPPORTED_IMAGE_MIME_TYPES = new Set(["image/png","image/jpeg",@@ -465,6 +481,84 @@ app.get("/api/v1/memos/:id", async (c) => {return c.json({ memo });});+app.get("/api/v1/memos/:id/revisions", async (c) => {+ const memoId = c.req.param("id");+ const memo = await getMemoDetail(c.env.DB, memoId);++ if (!memo) {+ return notFound(c, "Memo not found");+ }++ const limit = clampNumber(Number(c.req.query("limit") ?? 50), 1, 100);+ const rows = await c.env.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 c.json({ revisions: rows.results.map(mapMemoRevision) });+});++app.post("/api/v1/memos/:id/revisions/:revisionId/restore", async (c) => {+ const memoId = c.req.param("id");+ const revisionId = c.req.param("revisionId");+ const actor = getAuditActor(c);+ const actorLabel = getActorLabel(c);+ const current = await getMemoDetailRow(c.env.DB, memoId);++ if (!current) {+ return notFound(c, "Memo not found");+ }++ const revision = await getMemoRevisionRow(c.env.DB, memoId, revisionId);++ if (!revision) {+ return notFound(c, "Memo revision not found");+ }++ 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 = revision.title ?? deriveTitle(contentText);+ const excerpt = createExcerpt(contentText || title || "");+ const contentHash = await sha256(contentMarkdown + JSON.stringify(contentJson));+ const nextRevision = current.revision + 1;+ const now = isoNow();++ await c.env.DB.batch([+ createMemoRevisionStatement(c.env.DB, current, actorLabel, now),+ c.env.DB.prepare(+ `UPDATE memos+ SET title = ?, excerpt = ?, tags_json = ?, updated_by = ?, updated_at = ?+ WHERE id = ? AND is_deleted = 0`+ ).bind(title, excerpt, JSON.stringify(tags), actorLabel, now, memoId),+ c.env.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),+ c.env.DB.prepare(`DELETE FROM memos_fts WHERE memo_id = ?`).bind(memoId),+ c.env.DB.prepare(+ `INSERT INTO memos_fts (memo_id, title, content_text, tags)+ VALUES (?, ?, ?, ?)`+ ).bind(memoId, title, contentText, tags.join(" ")),+ auditStatement(c.env.DB, actor.actorType, actor.actorId, "memo.revision_restore", "memo", memoId, {+ revisionId,+ restoredRevision: revision.revision,+ revision: nextRevision,+ }),+ ]);++ return c.json({ memo: await getMemoDetail(c.env.DB, memoId) });+});+app.get("/api/v1/resources", async (c) => {const limit = clampNumber(Number(c.req.query("limit") ?? 500), 1, 500);const [rows, stats] = await Promise.all([@@ -666,23 +760,12 @@ app.patch("/api/v1/memos/:id", zValidator("json", MemoUpdateSchema), async (c) =const nextRevision = current.revision + 1;const contentHash = await sha256(contentMarkdown + JSON.stringify(contentJson));const now = isoNow();+ const revisionStatements = (await shouldSnapshotMemoRevision(c.env.DB, current, title, JSON.stringify(tags), contentHash, now))+ ? [createMemoRevisionStatement(c.env.DB, current, actorLabel, now)]+ : [];await c.env.DB.batch([- c.env.DB.prepare(- `INSERT INTO memo_revisions (- id, memo_id, revision, title, content_json, content_markdown, content_hash, created_by, created_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`- ).bind(- createId("rev"),- id,- current.revision,- current.title,- current.content_json,- current.content_markdown,- current.content_hash,- actorLabel,- now- ),+ ...revisionStatements,c.env.DB.prepare(`UPDATE memosSET notebook_id = ?, title = ?, excerpt = ?, tags_json = ?, updated_by = ?, updated_at = ?@@ -1239,6 +1322,19 @@ const mapMemoDetail = (row: MemoDetailRow): MemoDetail => ({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 mapResource = (row: ResourceRow): Resource => ({id: row.id,memoId: row.memo_id,@@ -1305,6 +1401,96 @@ const getMemoDetail = async (db: D1Database, id: string, includeDeleted = false)return row ? mapMemoDetail(row) : null;};+const getMemoRevisionRow = async (+ db: D1Database,+ memoId: string,+ revisionId: 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 id = ? AND memo_id = ?`+ )+ .bind(revisionId, memoId)+ .first<MemoRevisionRow>();++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, id: string): Promise<ResourceRow | null> =>db.prepare(diff --git a/apps/web/src/app/App.tsx b/apps/web/src/app/App.tsxindex 1e06a481..d32e2446 100644--- a/apps/web/src/app/App.tsx+++ b/apps/web/src/app/App.tsx@@ -1,4 +1,12 @@-import type { AuthSession, AuthUser, MemoDetail, MemoSummary, Notebook, TiptapDoc } from "@edgeever/shared";+import {+ docToMarkdown,+ type AuthSession,+ type AuthUser,+ type MemoDetail,+ type MemoSummary,+ type Notebook,+ type TiptapDoc,+} from "@edgeever/shared";import Image from "@tiptap/extension-image";import Placeholder from "@tiptap/extension-placeholder";import { EditorContent, useEditor, type Editor } from "@tiptap/react";@@ -14,6 +22,7 @@ import {FilePlus2,Folder,HardDrive,+ History,ImageIcon,Inbox,LayoutList,@@ -1027,6 +1036,161 @@ const formatBytes = (bytes: number) => {return `${exponent === 0 ? value.toFixed(0) : value.toFixed(value >= 10 ? 1 : 2)} ${units[exponent]}`;};+const RevisionHistoryDialog = ({+ memo,+ currentMarkdown,+ onClose,+ onRestored,+}: {+ memo: MemoDetail;+ currentMarkdown: string;+ onClose: () => void;+ onRestored: (memo: MemoDetail) => Promise<void>;+}) => {+ const [selectedRevisionId, setSelectedRevisionId] = useState<string | null>(null);+ const revisionsQuery = useQuery({+ queryKey: ["memo-revisions", memo.id],+ queryFn: () => api.listMemoRevisions(memo.id),+ });+ const revisions = revisionsQuery.data?.revisions ?? [];+ const selectedRevision =+ revisions.find((revision) => revision.id === selectedRevisionId) ?? revisions[0] ?? null;+ const diffSummary = useMemo(+ () => summarizeMarkdownDiff(selectedRevision?.contentMarkdown ?? "", currentMarkdown),+ [currentMarkdown, selectedRevision?.contentMarkdown]+ );+ const restoreMutation = useMutation({+ mutationFn: (revisionId: string) => api.restoreMemoRevision(memo.id, revisionId),+ onSuccess: async (data) => {+ await onRestored(data.memo);+ },+ });++ useEffect(() => {+ if (!selectedRevisionId && revisions.length > 0) {+ setSelectedRevisionId(revisions[0].id);+ }+ }, [revisions, selectedRevisionId]);++ return (+ <div className="fixed inset-0 z-50 flex items-end bg-slate-950/35 p-0 sm:items-center sm:justify-center sm:p-6">+ <section className="flex max-h-[88dvh] w-full flex-col rounded-t-md bg-white shadow-panel sm:max-w-[980px] sm:rounded-md">+ <header className="flex shrink-0 items-center justify-between gap-3 border-b border-emerald-100 px-4 py-3 sm:px-5">+ <div className="min-w-0">+ <div className="flex items-center gap-2 text-base font-semibold text-slate-950">+ <History className="h-4 w-4 text-emerald-700" />+ 版本历史+ </div>+ <div className="mt-1 truncate text-xs text-slate-500">{memo.title || "Untitled memo"}</div>+ </div>+ <Button size="icon" variant="ghost" title="关闭" onClick={onClose}>+ <X className="h-4 w-4" />+ </Button>+ </header>++ <div className="grid min-h-0 flex-1 grid-rows-[auto_minmax(0,1fr)] sm:grid-cols-[280px_minmax(0,1fr)] sm:grid-rows-1">+ <aside className="min-h-0 border-b border-emerald-100 p-3 sm:border-b-0 sm:border-r">+ {revisionsQuery.isLoading ? (+ <div className="px-2 py-8 text-center text-sm text-slate-500">加载中</div>+ ) : revisions.length === 0 ? (+ <div className="rounded-md border border-dashed border-slate-300 px-4 py-8 text-center text-sm text-slate-500">+ 暂无历史版本+ </div>+ ) : (+ <div className="max-h-44 space-y-2 overflow-y-auto sm:max-h-none">+ {revisions.map((revision) => (+ <button+ key={revision.id}+ className={cn(+ "block w-full rounded-md border px-3 py-2 text-left transition",+ selectedRevision?.id === revision.id+ ? "border-emerald-300 bg-emerald-50"+ : "border-emerald-100 hover:border-emerald-200 hover:bg-emerald-50/50"+ )}+ onClick={() => setSelectedRevisionId(revision.id)}+ >+ <span className="block text-sm font-semibold text-slate-950">+ Revision {revision.revision}+ </span>+ <span className="mt-1 block truncate text-xs text-slate-500">+ {formatDateTime(revision.createdAt)}+ </span>+ <span className="mt-1 block truncate text-xs text-slate-400">+ {formatRevisionActor(revision.createdBy)}+ </span>+ </button>+ ))}+ </div>+ )}+ </aside>++ <div className="flex min-h-0 flex-col">+ <div className="flex shrink-0 flex-wrap items-center justify-between gap-2 border-b border-emerald-100 px-4 py-3">+ <div className="text-xs font-medium text-slate-500">+ {selectedRevision ? `${diffSummary.changed} changed lines` : "No revision selected"}+ </div>+ <Button+ size="sm"+ variant="solid"+ disabled={!selectedRevision || memo.isDeleted || restoreMutation.isPending}+ onClick={() => {+ if (selectedRevision && window.confirm("恢复到这个历史版本?")) {+ restoreMutation.mutate(selectedRevision.id);+ }+ }}+ >+ <RotateCcw className="h-4 w-4" />+ 恢复该版本+ </Button>+ </div>++ <div className="grid min-h-0 flex-1 gap-0 overflow-y-auto sm:grid-cols-2">+ <RevisionPreview title="历史版本" markdown={selectedRevision?.contentMarkdown ?? ""} />+ <RevisionPreview title="当前内容" markdown={currentMarkdown} />+ </div>+ </div>+ </div>+ </section>+ </div>+ );+};++const RevisionPreview = ({ title, markdown }: { title: string; markdown: string }) => (+ <div className="min-h-[260px] border-b border-emerald-100 p-4 sm:border-b-0 sm:border-r">+ <div className="mb-3 text-xs font-semibold uppercase text-slate-500">{title}</div>+ <pre className="max-h-[54dvh] overflow-auto whitespace-pre-wrap break-words rounded-md border border-emerald-100 bg-emerald-50/30 p-3 text-sm leading-6 text-slate-700">+ {markdown || "Empty memo"}+ </pre>+ </div>+);++const summarizeMarkdownDiff = (left: string, right: string) => {+ const leftLines = left.split("\n");+ const rightLines = right.split("\n");+ const maxLines = Math.max(leftLines.length, rightLines.length);+ let changed = 0;++ for (let index = 0; index < maxLines; index += 1) {+ if ((leftLines[index] ?? "") !== (rightLines[index] ?? "")) {+ changed += 1;+ }+ }++ return { changed };+};++const formatRevisionActor = (actor: string) => {+ if (actor.startsWith("user:")) {+ return "user";+ }++ if (actor.startsWith("agent:")) {+ return "agent";+ }++ return actor || "system";+};+const EditorPane = ({memo,isTrashView,@@ -1057,6 +1221,7 @@ const EditorPane = ({const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);const [dirtyVersion, setDirtyVersion] = useState(0);const [imageUploadState, setImageUploadState] = useState<"idle" | "compressing" | "uploading" | "error">("idle");+ const [historyOpen, setHistoryOpen] = useState(false);const memoRef = useRef<MemoDetail | null>(memo);const editorRef = useRef<Editor | null>(null);const hydratingRef = useRef(false);@@ -1419,6 +1584,9 @@ const EditorPane = ({: "图片上传中"}</span>) : null}+ <Button size="sm" variant="ghost" title="版本历史" onClick={() => setHistoryOpen(true)}>+ <History className="h-4 w-4" />+ </Button>{readOnly ? (<><Button size="sm" variant="solid" title="恢复笔记" onClick={() => void onRestored(memo.id)}>@@ -1489,6 +1657,20 @@ const EditorPane = ({<div className="edgeever-editor min-h-0 flex-1 overflow-y-auto"><EditorContent editor={editor} /></div>+ {historyOpen ? (+ <RevisionHistoryDialog+ currentMarkdown={editor ? docToMarkdown(editor.getJSON() as TiptapDoc) : memo.contentMarkdown}+ memo={memo}+ onClose={() => setHistoryOpen(false)}+ onRestored={async (restoredMemo) => {+ await localDb.drafts.delete(restoredMemo.id);+ hasUnsavedChangesRef.current = false;+ setHasUnsavedChanges(false);+ await onSaved(restoredMemo);+ setHistoryOpen(false);+ }}+ />+ ) : null}</div>);};diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex 5f02c8a8..07b5f14a 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -1,6 +1,7 @@import type {AuthSession,MemoDetail,+ MemoRevision,MemoSummary,Notebook,Resource,@@ -17,6 +18,10 @@ type ListMemosResponse = {memos: MemoSummary[];};+type ListMemoRevisionsResponse = {+ revisions: MemoRevision[];+};+type ListResourcesResponse = {resources: ResourceListItem[];summary: ResourceStorageSummary;@@ -135,6 +140,15 @@ export const api = {return request<MemoResponse>(`/api/v1/memos/${memoId}${suffix}`);},+ 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"),uploadMemoResource: (memoId: string, file: File) => {diff --git a/migrations/0004_memo_revision_metadata.sql b/migrations/0004_memo_revision_metadata.sqlnew file mode 100644index 00000000..890ae1b9--- /dev/null+++ b/migrations/0004_memo_revision_metadata.sql@@ -0,0 +1,7 @@+PRAGMA foreign_keys = ON;++ALTER TABLE memo_revisions+ ADD COLUMN tags_json TEXT NOT NULL DEFAULT '[]';++ALTER TABLE memo_revisions+ ADD COLUMN content_text TEXT NOT NULL DEFAULT '';diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.tsindex 11d53ce0..58e2973c 100644--- a/packages/shared/src/types.ts+++ b/packages/shared/src/types.ts@@ -36,6 +36,19 @@ export type MemoDetail = MemoSummary & {mergedIntoMemoId: string | null;};+export type MemoRevision = {+ id: string;+ memoId: string;+ revision: number;+ title: string | null;+ tags: string[];+ contentMarkdown: string;+ contentText: string;+ contentHash: string;+ createdBy: string;+ createdAt: string;+};+export type ResourceKind = "image" | "attachment";export type Resource = {