Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat(memos): duplicate a note with its files (#566)

Dariusz Koryto72ab4816a19a
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index a60fc3cb..5fc5de34 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -117,6 +117,7 @@ import {
searchMemoSummaries,
updateMemoRecord,
} from "./memo-service";
+import { duplicateMemoRecord } from "./memo-duplicate-service";
export { createMemoEditSession, mergeMemosRecord, updateMemoRecord };
import { listMemos } from "./memo-list-service";
@@ -357,6 +358,7 @@ registerMemoRoutes(app, {
getMemoDetail: (...args) => getMemoDetail(...args),
listMemos: (...args) => listMemos(...args),
listMemoRevisions: (...args) => listMemoRevisionsService(...args, getMemoDetail, false),
+ duplicateMemo: (...args) => duplicateMemoRecord(...args),
mergeMemos: (...args) => mergeMemosRecord(...args),
moveMemos: (...args) => moveMemosRecord(...args),
restoreMemo: (...args) => restoreMemoRecord(...args),
diff --git a/apps/api/src/memo-duplicate-service.test.mjs b/apps/api/src/memo-duplicate-service.test.mjs
new file mode 100644
index 00000000..c9567217
--- /dev/null
+++ b/apps/api/src/memo-duplicate-service.test.mjs
@@ -0,0 +1,362 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import { Database } from "bun:sqlite";
+import { globSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { MAX_DUPLICATE_RESOURCE_BYTES, MAX_DUPLICATE_RESOURCE_COUNT, duplicateMemoRecord } from "./memo-duplicate-service.ts";
+import { createMemoRecord, getMemoDetail } from "./memo-service.ts";
+import { createAttachmentResource, createImageResource } from "./resource-service.ts";
+import { createSelfHostedStorageAdapter } from "./self-hosted-storage-adapter.ts";
+
+const WORKSPACE_ID = "ws_default";
+const actor = { actorType: "user", actorId: "usr_owner" };
+const cleanups = [];
+afterEach(() => cleanups.splice(0).forEach((cleanup) => cleanup()));
+
+const setup = () => {
+ const sqlite = new Database(":memory:");
+ for (const file of globSync("migrations/*.sql").sort()) sqlite.exec(readFileSync(file, "utf8"));
+ const resourcesDirectory = mkdtempSync(join(tmpdir(), "edgeever-duplicate-"));
+ cleanups.push(() => {
+ sqlite.close();
+ rmSync(resourcesDirectory, { recursive: true, force: true });
+ });
+ const storage = createSelfHostedStorageAdapter(sqlite, resourcesDirectory);
+ const auth = { kind: "user", actorType: "user", actorId: "usr_owner", workspaceId: WORKSPACE_ID, scopes: [], role: "owner" };
+ const context = { env: { storage }, get: (key) => (key === "auth" ? auth : undefined) };
+ const notebookId = sqlite.query("SELECT id FROM notebooks WHERE workspace_id = ? AND slug = 'inbox'").get(WORKSPACE_ID).id;
+ const otherNotebookId = sqlite.query("SELECT id FROM notebooks WHERE workspace_id = ? AND slug = 'work-projects'").get(WORKSPACE_ID).id;
+ const storedFiles = () => (readdirSync(resourcesDirectory, { recursive: true, withFileTypes: true })
+ .filter((entry) => entry.isFile())
+ .map((entry) => join(entry.parentPath ?? entry.path, entry.name)));
+ const readObject = async (objectKey) => {
+ const object = await storage.resources.get(objectKey);
+ return object ? new Uint8Array(await new Response(object.body).arrayBuffer()) : null;
+ };
+ return { sqlite, storage, context, notebookId, otherNotebookId, storedFiles, readObject };
+};
+
+// A note with an image, an attachment and tags, as the editor saves them.
+const createSourceNote = async ({ sqlite, storage, context, notebookId }) => {
+ const memo = await createMemoRecord(storage.db, WORKSPACE_ID, {
+ notebookId,
+ title: "Trip plan",
+ contentMarkdown: "Draft",
+ tags: ["travel", "2026"],
+ }, actor, "admin");
+ const image = await createImageResource(context, {
+ memoId: memo.id,
+ filename: "map.png",
+ mimeType: "image/png",
+ bytes: Uint8Array.of(0x89, 0x50, 0x4e, 0x47, 1, 2, 3),
+ actor,
+ source: "upload",
+ });
+ const attachment = await createAttachmentResource(context, {
+ memoId: memo.id,
+ filename: "tickets.pdf",
+ mimeType: "application/pdf",
+ bytes: new TextEncoder().encode("%PDF tickets"),
+ actor,
+ });
+ const markdown = `## Trip plan\n\n![map](/api/v1/resources/${image.id}/blob)\n\n[tickets.pdf](/api/v1/resources/${attachment.id}/blob)`;
+ const json = JSON.stringify({
+ type: "doc",
+ content: [
+ { type: "heading", attrs: { level: 2 }, content: [{ type: "text", text: "Trip plan" }] },
+ { type: "image", attrs: { src: `/api/v1/resources/${image.id}/blob`, alt: "map" } },
+ { type: "paragraph", content: [{ type: "text", text: "tickets.pdf", marks: [{ type: "link", attrs: { href: `/api/v1/resources/${attachment.id}/blob` } }] }] },
+ ],
+ });
+ sqlite.query("UPDATE memo_contents SET content_markdown = ?, content_json = ?, content_text = 'Trip plan tickets.pdf' WHERE memo_id = ?")
+ .run(markdown, json, memo.id);
+ return { memo, image, attachment };
+};
+
+const byKind = (rows) => [rows.find((row) => row.kind === "image"), rows.find((row) => row.kind === "attachment")];
+
+const resourceRows = (sqlite, memoId) => sqlite
+ .query("SELECT id, object_key, kind, mime_type, filename, byte_size, sha256 FROM resources WHERE memo_id = ? AND is_deleted = 0 ORDER BY created_at, id")
+ .all(memoId);
+
+describe("duplicate a note", () => {
+ test("copies the title, content, tags and files into an independent note", async () => {
+ const fixture = setup();
+ const { sqlite, context, storage } = fixture;
+ const { memo, image, attachment } = await createSourceNote(fixture);
+ const sourceBefore = await getMemoDetail(storage.db, WORKSPACE_ID, memo.id);
+
+ const copy = await duplicateMemoRecord(context, memo.id, { title: "Trip plan (copy)" }, actor, "admin");
+
+ expect(copy.id).not.toBe(memo.id);
+ expect(copy.title).toBe("Trip plan (copy)");
+ expect(copy.notebookId).toBe(memo.notebookId);
+ expect(copy.tags).toEqual(["travel", "2026"]);
+ expect(copy.revision).toBe(0);
+
+ const copiedResources = resourceRows(sqlite, copy.id);
+ expect(copiedResources).toHaveLength(2);
+ const [copiedImage, copiedAttachment] = byKind(copiedResources);
+ expect(copiedImage).toMatchObject({ kind: "image", filename: "map.png", mime_type: "image/png", sha256: image.sha256 });
+ expect(copiedAttachment).toMatchObject({ kind: "attachment", filename: "tickets.pdf", mime_type: "application/pdf" });
+ expect(copiedImage.id).not.toBe(image.id);
+ expect(copiedAttachment.id).not.toBe(attachment.id);
+ expect(copiedImage.object_key).toBe(`workspaces/${WORKSPACE_ID}/memos/${copy.id}/${copiedImage.id}.png`);
+
+ // The copy references its own files, and only those.
+ expect(copy.contentMarkdown).toBe(sourceBefore.contentMarkdown
+ .replace(image.id, copiedImage.id)
+ .replace(attachment.id, copiedAttachment.id));
+ expect(JSON.stringify(copy.contentJson)).not.toContain(image.id);
+ expect(JSON.stringify(copy.contentJson)).toContain(copiedImage.id);
+ expect(JSON.stringify(copy.contentJson)).toContain(copiedAttachment.id);
+
+ // Same bytes, separate objects.
+ const [sourceImage, sourceAttachment] = byKind(resourceRows(sqlite, memo.id));
+ expect(await fixture.readObject(copiedImage.object_key)).toEqual(await fixture.readObject(sourceImage.object_key));
+ expect(await fixture.readObject(copiedAttachment.object_key)).toEqual(await fixture.readObject(sourceAttachment.object_key));
+
+ // The source is unchanged, and the copy is searchable and tagged.
+ expect(await getMemoDetail(storage.db, WORKSPACE_ID, memo.id)).toEqual(sourceBefore);
+ expect(sqlite.query("SELECT memo_id FROM memos_fts WHERE memos_fts MATCH 'tickets'").all().map((row) => row.memo_id))
+ .toContain(copy.id);
+ expect(sqlite.query("SELECT name FROM memo_tags WHERE memo_id = ? ORDER BY name").all(copy.id).map((row) => row.name))
+ .toEqual(["2026", "travel"]);
+ expect(sqlite.query("SELECT action, metadata_json FROM audit_events WHERE entity_id = ?").get(copy.id).action)
+ .toBe("memo.duplicate");
+ });
+
+ test("keeps the copy's files when the source's files are deleted", async () => {
+ const fixture = setup();
+ const { sqlite, context, storage } = fixture;
+ const { memo } = await createSourceNote(fixture);
+ const copy = await duplicateMemoRecord(context, memo.id, {}, actor, "admin");
+
+ for (const resource of resourceRows(sqlite, memo.id)) await storage.resources.delete(resource.object_key);
+
+ for (const resource of resourceRows(sqlite, copy.id)) {
+ expect(await fixture.readObject(resource.object_key)).not.toBeNull();
+ }
+ expect(copy.title).toBe("Trip plan");
+ });
+
+ test("places the copy in another notebook when asked", async () => {
+ const fixture = setup();
+ const { memo } = await createSourceNote(fixture);
+
+ const copy = await duplicateMemoRecord(fixture.context, memo.id, { notebookId: fixture.otherNotebookId }, actor, "admin");
+
+ expect(copy.notebookId).toBe(fixture.otherNotebookId);
+ });
+
+ test("rejects a missing or deleted note, or an unknown notebook", async () => {
+ const fixture = setup();
+ const { memo } = await createSourceNote(fixture);
+
+ await expect(duplicateMemoRecord(fixture.context, "memo_missing", {}, actor, "admin"))
+ .rejects.toMatchObject({ code: "not_found", status: 404 });
+ await expect(duplicateMemoRecord(fixture.context, memo.id, { notebookId: "nb_missing" }, actor, "admin"))
+ .rejects.toMatchObject({ code: "not_found", status: 404 });
+ fixture.sqlite.query("UPDATE memos SET is_deleted = 1 WHERE id = ?").run(memo.id);
+ await expect(duplicateMemoRecord(fixture.context, memo.id, {}, actor, "admin"))
+ .rejects.toMatchObject({ code: "not_found", status: 404 });
+ });
+
+ test("refuses files above the size limit without writing anything", async () => {
+ const fixture = setup();
+ const { memo } = await createSourceNote(fixture);
+ fixture.sqlite.query("UPDATE resources SET byte_size = ? WHERE memo_id = ? AND kind = 'attachment'")
+ .run(MAX_DUPLICATE_RESOURCE_BYTES, memo.id);
+ const filesBefore = fixture.storedFiles();
+ const memoCount = fixture.sqlite.query("SELECT COUNT(*) AS count FROM memos").get().count;
+
+ await expect(duplicateMemoRecord(fixture.context, memo.id, {}, actor, "admin"))
+ .rejects.toMatchObject({ code: "duplicate_too_large", status: 413 });
+
+ expect(fixture.storedFiles()).toEqual(filesBefore);
+ expect(fixture.sqlite.query("SELECT COUNT(*) AS count FROM memos").get().count).toBe(memoCount);
+ });
+
+ test("checks the size limit on the bytes read when a row records no size", async () => {
+ const fixture = setup();
+ const memo = await createMemoRecord(fixture.storage.db, WORKSPACE_ID, {
+ notebookId: fixture.notebookId, title: "Legacy", contentMarkdown: "Draft",
+ }, actor, "admin");
+ const big = await createAttachmentResource(fixture.context, {
+ memoId: memo.id, filename: "big.bin", mimeType: "application/octet-stream",
+ bytes: new Uint8Array(MAX_DUPLICATE_RESOURCE_BYTES + 1), actor,
+ });
+ fixture.sqlite.query("UPDATE resources SET byte_size = 0 WHERE id = ?").run(big.id);
+ const filesBefore = fixture.storedFiles();
+
+ await expect(duplicateMemoRecord(fixture.context, memo.id, {}, actor, "admin"))
+ .rejects.toMatchObject({ code: "duplicate_too_large", status: 413 });
+ expect(fixture.storedFiles()).toEqual(filesBefore);
+ });
+
+ test("removes the copied files when the database write fails", async () => {
+ const fixture = setup();
+ const { memo } = await createSourceNote(fixture);
+ const filesBefore = fixture.storedFiles();
+ const memoCount = fixture.sqlite.query("SELECT COUNT(*) AS count FROM memos").get().count;
+ fixture.storage.db.batch = async () => {
+ throw new Error("database unavailable");
+ };
+
+ await expect(duplicateMemoRecord(fixture.context, memo.id, {}, actor, "admin")).rejects.toThrow("database unavailable");
+
+ expect(fixture.storedFiles()).toEqual(filesBefore);
+ expect(fixture.sqlite.query("SELECT COUNT(*) AS count FROM memos").get().count).toBe(memoCount);
+ });
+
+ test("keeps the copy's files when reading the committed copy fails", async () => {
+ const fixture = setup();
+ const { memo } = await createSourceNote(fixture);
+ const { db } = fixture.storage;
+ const batch = db.batch.bind(db);
+ const prepare = db.prepare.bind(db);
+ let committed = false;
+ db.batch = async (statements) => {
+ const result = await batch(statements);
+ committed = true;
+ return result;
+ };
+ // The first database read after the write batch fails, as a transient error would.
+ db.prepare = (sql) => {
+ if (committed) {
+ db.prepare = prepare;
+ throw new Error("database read failed");
+ }
+ return prepare(sql);
+ };
+
+ await expect(duplicateMemoRecord(fixture.context, memo.id, {}, actor, "admin")).rejects.toThrow("database read failed");
+ db.batch = batch;
+ db.prepare = prepare;
+
+ const copy = fixture.sqlite.query("SELECT id FROM memos WHERE id <> ? AND title = 'Trip plan'").get(memo.id);
+ expect(copy).not.toBeNull();
+ const copiedResources = resourceRows(fixture.sqlite, copy.id);
+ expect(copiedResources).toHaveLength(2);
+ for (const resource of copiedResources) {
+ expect(await fixture.readObject(resource.object_key)).not.toBeNull();
+ }
+ });
+
+ test("fails without a partial copy when a source file is missing from storage", async () => {
+ const fixture = setup();
+ const { memo } = await createSourceNote(fixture);
+ const [, attachment] = byKind(resourceRows(fixture.sqlite, memo.id));
+ await fixture.storage.resources.delete(attachment.object_key);
+ const filesBefore = fixture.storedFiles();
+
+ await expect(duplicateMemoRecord(fixture.context, memo.id, {}, actor, "admin"))
+ .rejects.toMatchObject({ code: "duplicate_resource_missing", status: 409 });
+
+ expect(fixture.storedFiles()).toEqual(filesBefore);
+ });
+
+ test("refuses more files than the limit without writing anything", async () => {
+ const fixture = setup();
+ const { memo } = await createSourceNote(fixture);
+ for (let index = 0; index < MAX_DUPLICATE_RESOURCE_COUNT - 1; index += 1) {
+ await createAttachmentResource(fixture.context, {
+ memoId: memo.id,
+ filename: `extra-${index}.txt`,
+ mimeType: "text/plain",
+ bytes: new TextEncoder().encode(`extra ${index}`),
+ actor,
+ });
+ }
+ const filesBefore = fixture.storedFiles();
+
+ await expect(duplicateMemoRecord(fixture.context, memo.id, {}, actor, "admin"))
+ .rejects.toMatchObject({ code: "duplicate_too_large", status: 413 });
+ expect(fixture.storedFiles()).toEqual(filesBefore);
+ });
+
+ test("leaves out pending public-form uploads and the form link of submitted ones", async () => {
+ const fixture = setup();
+ const { memo, attachment } = await createSourceNote(fixture);
+ const pending = await createAttachmentResource(fixture.context, {
+ memoId: memo.id,
+ filename: "visitor.txt",
+ mimeType: "text/plain",
+ bytes: new TextEncoder().encode("not submitted"),
+ actor,
+ metadata: { tableFormId: "form_1", pending: 1 },
+ });
+ fixture.sqlite.query("UPDATE resources SET metadata_json = ? WHERE id = ?")
+ .run(JSON.stringify({ tableFormId: "form_1", pending: 0, originalFilename: "tickets.pdf" }), attachment.id);
+
+ const copy = await duplicateMemoRecord(fixture.context, memo.id, {}, actor, "admin");
+
+ const copied = fixture.sqlite.query("SELECT filename, metadata_json FROM resources WHERE memo_id = ? ORDER BY filename").all(copy.id);
+ expect(copied.map((row) => row.filename)).toEqual(["map.png", "tickets.pdf"]);
+ expect(copied.map((row) => row.filename)).not.toContain(pending.filename);
+ expect(JSON.parse(copied.find((row) => row.filename === "tickets.pdf").metadata_json)).toEqual({ originalFilename: "tickets.pdf" });
+ });
+
+ test("rewrites whole resource ids only", async () => {
+ const fixture = setup();
+ const memo = await createMemoRecord(fixture.storage.db, WORKSPACE_ID, {
+ notebookId: fixture.notebookId,
+ title: "Prefixes",
+ contentMarkdown: "Draft",
+ }, actor, "admin");
+ const short = await createAttachmentResource(fixture.context, {
+ memoId: memo.id, resourceId: "res_legacy01", filename: "a.txt", mimeType: "text/plain", bytes: Uint8Array.of(1), actor,
+ });
+ const long = await createAttachmentResource(fixture.context, {
+ memoId: memo.id, resourceId: "res_legacy01_x", filename: "b.txt", mimeType: "text/plain", bytes: Uint8Array.of(2), actor,
+ });
+ const markdown = `[a](/api/v1/resources/${short.id}/blob) [b](/api/v1/resources/${long.id}/blob) mentions res_legacy01abc`;
+ fixture.sqlite.query("UPDATE memo_contents SET content_markdown = ?, content_json = ? WHERE memo_id = ?")
+ .run(markdown, JSON.stringify({ type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: markdown }] }] }), memo.id);
+
+ const copy = await duplicateMemoRecord(fixture.context, memo.id, {}, actor, "admin");
+
+ const byFilename = Object.fromEntries(fixture.sqlite.query("SELECT id, filename FROM resources WHERE memo_id = ?").all(copy.id)
+ .map((row) => [row.filename, row.id]));
+ expect(copy.contentMarkdown).toBe(`[a](/api/v1/resources/${byFilename["a.txt"]}/blob) [b](/api/v1/resources/${byFilename["b.txt"]}/blob) mentions res_legacy01abc`);
+ expect(JSON.stringify(copy.contentJson)).toContain(byFilename["b.txt"]);
+ });
+
+ test("reports a cleanup failure and still returns the original error", async () => {
+ const fixture = setup();
+ const { memo } = await createSourceNote(fixture);
+ fixture.storage.db.batch = async () => {
+ throw new Error("database unavailable");
+ };
+ const remove = fixture.storage.resources.delete;
+ fixture.storage.resources.delete = async () => {
+ throw new Error("storage unavailable");
+ };
+ const errors = [];
+ const consoleError = console.error;
+ console.error = (...args) => errors.push(args);
+ try {
+ await expect(duplicateMemoRecord(fixture.context, memo.id, {}, actor, "admin")).rejects.toThrow("database unavailable");
+ } finally {
+ console.error = consoleError;
+ fixture.storage.resources.delete = remove;
+ }
+ expect(errors).toHaveLength(1);
+ expect(errors[0][1].objectKeys).toHaveLength(2);
+ });
+
+ test("copies a note without files", async () => {
+ const fixture = setup();
+ const memo = await createMemoRecord(fixture.storage.db, WORKSPACE_ID, {
+ notebookId: fixture.notebookId,
+ title: "Plain",
+ contentMarkdown: "Just **text**",
+ }, actor, "admin");
+
+ const copy = await duplicateMemoRecord(fixture.context, memo.id, {}, actor, "admin");
+
+ expect(copy.contentMarkdown).toBe(memo.contentMarkdown);
+ expect(copy.contentJson).toEqual(memo.contentJson);
+ expect(resourceRows(fixture.sqlite, copy.id)).toEqual([]);
+ });
+});
diff --git a/apps/api/src/memo-duplicate-service.ts b/apps/api/src/memo-duplicate-service.ts
new file mode 100644
index 00000000..06b5f83c
--- /dev/null
+++ b/apps/api/src/memo-duplicate-service.ts
@@ -0,0 +1,242 @@
+import { createExcerpt, docToText, emptyDoc, type MemoDetail, type TiptapDoc } from "@edgeever/shared";
+import { auditStatement } from "./audit";
+import type { AppContext, AuditActor } from "./api-context";
+import { AppError } from "./app-error";
+import { createId, isoNow, parseJsonArray } from "./entity-utils";
+import { sha256 } from "./hash-utils";
+import { getMemoDetail, getMemoDetailRow } from "./memo-service";
+import { upsertMemoSearchDocumentStatement } from "./memo-search-index";
+import { getNotebook } from "./notebook-service";
+import { resolveObjectStorage } from "./object-storage";
+import { inferImageExtension } from "./resource-service";
+import { getWorkspaceId } from "./request-auth";
+
+/**
+ * Upper bounds for the files copied with one duplicated note. Each file is
+ * read into memory before it is written under its new key, and each costs a
+ * read and a write against object storage, so these keep one copy within the
+ * memory and subrequest limits of a Cloudflare Worker, including external S3
+ * storage on the Workers Free plan.
+ */
+export const MAX_DUPLICATE_RESOURCE_BYTES = 64 * 1024 * 1024;
+export const MAX_DUPLICATE_RESOURCE_COUNT = 20;
+
+const COPYABLE_RESOURCE_ID = /^[A-Za-z0-9_-]{8,}$/;
+
+type DuplicateResourceRow = {
+ id: string;
+ object_key: string;
+ storage_config_id: string;
+ kind: "image" | "attachment";
+ mime_type: string | null;
+ filename: string | null;
+ byte_size: number;
+ sha256: string | null;
+ width: number | null;
+ height: number | null;
+ metadata_json: string;
+};
+
+const parseDoc = (json: string): TiptapDoc => {
+ try {
+ const value = JSON.parse(json);
+ return value && typeof value === "object" ? (value as TiptapDoc) : emptyDoc();
+ } catch {
+ return emptyDoc();
+ }
+};
+
+// Replaces whole resource ids only, so an id that is a prefix of another id,
+// or ordinary text that contains an id, is never rewritten.
+const replaceResourceIds = (value: string, replacements: ReadonlyMap<string, string>) => {
+ if (replacements.size === 0) return value;
+ const ids = [...replacements.keys()].sort((left, right) => right.length - left.length);
+ const pattern = new RegExp(`(?<![A-Za-z0-9_-])(?:${ids.join("|")})(?![A-Za-z0-9_-])`, "g");
+ return value.replace(pattern, (id) => replacements.get(id) ?? id);
+};
+
+// Public table-form uploads stay pending until the form is submitted; the
+// copy must not keep them or their link to the source note's form.
+const copiedMetadataJson = (value: string) => {
+ try {
+ const metadata = JSON.parse(value);
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return "{}";
+ const { tableFormId: _tableFormId, pending: _pending, ...rest } = metadata as Record<string, unknown>;
+ return JSON.stringify(rest);
+ } catch {
+ return "{}";
+ }
+};
+
+/**
+ * Creates a new note with the source note's title, content, and tags in the
+ * same or another notebook. Its images and attachments are copied to new
+ * resources with their own stored objects, and the content is rewritten to
+ * reference the copies, so editing or deleting either note never affects the
+ * other. Shares, revisions, public forms and the pinned state are not copied.
+ */
+export const duplicateMemoRecord = async (
+ context: AppContext,
+ memoId: string,
+ input: { notebookId?: string; title?: string },
+ actor: AuditActor,
+ actorLabel: string,
+): Promise<MemoDetail> => {
+ const db = context.env.storage.db;
+ const workspaceId = getWorkspaceId(context);
+ const source = await getMemoDetailRow(db, workspaceId, memoId);
+ if (!source) throw new AppError("not_found", "Memo not found", 404);
+
+ const notebookId = input.notebookId ?? source.notebook_id;
+ if (!(await getNotebook(db, workspaceId, notebookId))) {
+ throw new AppError("not_found", "Notebook not found", 404);
+ }
+
+ const resources = (await db.prepare(
+ `SELECT id, object_key, storage_config_id, kind, mime_type, filename, byte_size, sha256, width, height, metadata_json
+ FROM resources
+ WHERE memo_id = ? AND is_deleted = 0
+ AND COALESCE(json_extract(metadata_json, '$.pending'), 0) <> 1
+ ORDER BY created_at ASC, id ASC`,
+ ).bind(memoId).all<DuplicateResourceRow>()).results;
+ const totalBytes = resources.reduce((sum, resource) => sum + resource.byte_size, 0);
+ if (totalBytes > MAX_DUPLICATE_RESOURCE_BYTES || resources.length > MAX_DUPLICATE_RESOURCE_COUNT) {
+ throw new AppError(
+ "duplicate_too_large",
+ "The note has too many or too large files to duplicate. Duplicate notes with at most 20 files totaling at most 64 MiB.",
+ 413,
+ );
+ }
+ if (resources.some((resource) => !COPYABLE_RESOURCE_ID.test(resource.id))) {
+ throw new AppError("duplicate_unsupported", "This note references files that cannot be duplicated.", 409);
+ }
+
+ const newMemoId = createId("memo");
+ const now = isoNow();
+ const destination = await resolveObjectStorage(context.env);
+ const copies: (DuplicateResourceRow & { newId: string; newObjectKey: string })[] = [];
+ const writtenKeys: string[] = [];
+ const deleteWrittenObjects = async () => {
+ if (!writtenKeys.length) return;
+ try {
+ await destination.store.delete(writtenKeys);
+ } catch (error) {
+ console.error("Failed to remove the files of an unfinished note duplicate.", { objectKeys: writtenKeys, error });
+ }
+ };
+
+ let copiedBytes = 0;
+ try {
+ for (const resource of resources) {
+ const origin = await resolveObjectStorage(context.env, resource.storage_config_id);
+ const object = await origin.store.get(resource.object_key);
+ if (!object) {
+ throw new AppError("duplicate_resource_missing", "A file of this note is missing from storage.", 409);
+ }
+ const bytes = new Uint8Array(await new Response(object.body).arrayBuffer());
+ // Older rows may record no size, so the limit is also checked on the bytes read.
+ copiedBytes += bytes.byteLength;
+ if (copiedBytes > MAX_DUPLICATE_RESOURCE_BYTES) {
+ throw new AppError(
+ "duplicate_too_large",
+ "The note has too many or too large files to duplicate. Duplicate notes with at most 20 files totaling at most 64 MiB.",
+ 413,
+ );
+ }
+ const newId = createId("res");
+ const extension = resource.kind === "image"
+ ? inferImageExtension(resource.filename ?? "", resource.mime_type ?? "")
+ : "";
+ const newObjectKey = `workspaces/${workspaceId}/memos/${newMemoId}/${newId}${extension}`;
+ await destination.store.put(newObjectKey, bytes, {
+ httpMetadata: {
+ contentType: resource.mime_type ?? "application/octet-stream",
+ cacheControl: "private, max-age=3600",
+ },
+ customMetadata: { memoId: newMemoId, resourceId: newId, filename: resource.filename ?? newId },
+ });
+ writtenKeys.push(newObjectKey);
+ copies.push({ ...resource, newId, newObjectKey });
+ }
+
+ const idReplacements = new Map(copies.map((copy) => [copy.id, copy.newId]));
+ const contentMarkdown = replaceResourceIds(source.content_markdown, idReplacements);
+ const contentJson = parseDoc(replaceResourceIds(source.content_json, idReplacements));
+ const contentText = docToText(contentJson);
+ const title = input.title?.trim() || source.title;
+ const tags = parseJsonArray(source.tags_json);
+ const contentHash = await sha256(contentMarkdown + JSON.stringify(contentJson));
+
+ 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(
+ newMemoId,
+ workspaceId,
+ title,
+ createExcerpt(contentText),
+ JSON.stringify(tags),
+ actorLabel,
+ actorLabel,
+ now,
+ now,
+ 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(newMemoId, JSON.stringify(contentJson), contentMarkdown, contentText, contentHash, now, now),
+ upsertMemoSearchDocumentStatement(db, newMemoId, title, contentText, tags.join(" ")),
+ ...copies.map((copy) => 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(
+ copy.newId,
+ newMemoId,
+ destination.bucketName,
+ copy.newObjectKey,
+ destination.configId,
+ copy.kind,
+ copy.mime_type,
+ copy.filename,
+ copy.byte_size,
+ copy.sha256,
+ copy.width,
+ copy.height,
+ copiedMetadataJson(copy.metadata_json),
+ now,
+ now,
+ )),
+ auditStatement(db, actor.actorType, actor.actorId, "memo.duplicate", "memo", newMemoId, {
+ sourceMemoId: memoId,
+ notebookId,
+ resourceCount: copies.length,
+ }),
+ ]);
+ } catch (error) {
+ // Nothing references the copied objects until the batch commits.
+ await deleteWrittenObjects();
+ throw error;
+ }
+
+ // From here on the committed rows reference the copied objects, so a failed
+ // read must never remove them.
+ const memo = await getMemoDetail(db, workspaceId, newMemoId);
+ if (memo) return memo;
+ // The notebook was removed between the check and the write, so the memo
+ // row was not inserted. Remove the rows written for it first, then the
+ // objects they referenced.
+ await db.batch([
+ db.prepare(`DELETE FROM resources WHERE memo_id = ?`).bind(newMemoId),
+ db.prepare(`DELETE FROM memo_search_documents WHERE memo_id = ?`).bind(newMemoId),
+ db.prepare(`DELETE FROM memo_contents WHERE memo_id = ?`).bind(newMemoId),
+ ]);
+ await deleteWrittenObjects();
+ throw new AppError("not_found", "Notebook not found", 404);
+};
diff --git a/apps/api/src/memo-routes.test.mjs b/apps/api/src/memo-routes.test.mjs
index 8e21f82e..fabac15e 100644
--- a/apps/api/src/memo-routes.test.mjs
+++ b/apps/api/src/memo-routes.test.mjs
@@ -32,6 +32,7 @@ const createDependencies = (overrides = {}) => ({
getMemoDetail: async () => null,
listMemos: async () => ({ memos: [], totalCount: 0, nextCursor: null }),
listMemoRevisions: async () => [],
+ duplicateMemo: async () => ({ id: "memo_copy" }),
mergeMemos: async () => ({ id: "memo_merged" }),
moveMemos: async () => 0,
restoreMemo: async () => ({ id: "memo_1" }),
@@ -352,6 +353,60 @@ describe("memo route contracts", () => {
expect(receivedInput).toEqual({ memoIds: ["memo_1", "memo_2"], title: "Merged" });
});
+ test("validates and delegates note duplication", async () => {
+ let received;
+ const dependencies = createDependencies({
+ duplicateMemo: async (_context, memoId, input, actor, actorLabel) => {
+ received = { memoId, input, actor, actorLabel };
+ return { id: "memo_copy", title: input.title };
+ },
+ });
+ const request = (body) => createApp(dependencies).request(
+ "/api/v1/memos/memo_1/duplicate",
+ { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) },
+ environment,
+ );
+
+ const response = await request({ title: " Plan (copy) ", notebookId: "nb_2" });
+ expect(response.status).toBe(201);
+ expect(await response.json()).toEqual({ memo: { id: "memo_copy", title: "Plan (copy)" } });
+ expect(received).toEqual({
+ memoId: "memo_1",
+ input: { title: "Plan (copy)", notebookId: "nb_2" },
+ actor: { actorType: "agent", actorId: "tok_memos" },
+ actorLabel: "agent:tok_memos",
+ });
+ expect((await request({ title: "x".repeat(161) })).status).toBe(400);
+ });
+
+ test("reports duplication errors and requires the write scope", async () => {
+ const failing = createDependencies({
+ duplicateMemo: async () => {
+ throw new AppError("duplicate_too_large", "Too large", 413);
+ },
+ });
+ const response = await createApp(failing).request(
+ "/api/v1/memos/memo_1/duplicate",
+ { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" },
+ environment,
+ );
+ expect(response.status).toBe(413);
+ expect((await response.json()).error.code).toBe("duplicate_too_large");
+
+ let called = false;
+ const readOnly = createApp(
+ createDependencies({ duplicateMemo: async () => { called = true; return { id: "memo_copy" }; } }),
+ { ...agentAuth, scopes: ["read:memos"] },
+ );
+ const denied = await readOnly.request(
+ "/api/v1/memos/memo_1/duplicate",
+ { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" },
+ environment,
+ );
+ expect(denied.status).toBe(403);
+ expect(called).toBe(false);
+ });
+
test("delegates batch moves through the memo service boundary", async () => {
let received;
const dependencies = createDependencies({
diff --git a/apps/api/src/memo-routes.ts b/apps/api/src/memo-routes.ts
index 1e34487b..7b264923 100644
--- a/apps/api/src/memo-routes.ts
+++ b/apps/api/src/memo-routes.ts
@@ -1,5 +1,6 @@
import {
DeleteMemosSchema,
+ DuplicateMemoSchema,
MemoCreateSchema,
MergeMemosSchema,
MemoUpdateSchema,
@@ -73,6 +74,13 @@ type MemoRouteDependencies = {
limit: number,
) => Promise<MemoRevision[]>;
listMemos: (database: DatabaseAdapter, input: ListMemosInput) => Promise<ListMemosResult>;
+ duplicateMemo: (
+ context: AppContext,
+ memoId: string,
+ input: { notebookId?: string; title?: string },
+ actor: AuditActor,
+ actorLabel: string,
+ ) => Promise<MemoDetail>;
mergeMemos: (
database: DatabaseAdapter,
workspaceId: string,
@@ -409,6 +417,24 @@ export const registerMemoRoutes = (
}
});
+ app.post("/api/v1/memos/:id/duplicate", zValidator("json", DuplicateMemoSchema), async (context) => {
+ const denied = requireScopes(context, "write:memos");
+ if (denied) return denied;
+
+ try {
+ const memo = await dependencies.duplicateMemo(
+ context,
+ context.req.param("id"),
+ context.req.valid("json"),
+ getAuditActor(context),
+ getActorLabel(context),
+ );
+ return context.json({ memo }, 201);
+ } catch (error) {
+ return handleAppError(context, error);
+ }
+ });
+
app.post("/api/v1/memos/merge", zValidator("json", MergeMemosSchema), async (context) => {
const denied = requireScopes(context, "write:memos");
if (denied) return denied;
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsx
index f82e6567..206d9953 100644
--- a/apps/web/src/components/EditorPane.tsx
+++ b/apps/web/src/components/EditorPane.tsx
@@ -29,6 +29,7 @@ import {
Share2,
Globe,
Copy,
+ CopyPlus,
Lock,
LockOpen,
} from "lucide-react";
@@ -342,6 +343,7 @@ type EditorPaneProps = {
onRestored: (memoId: string) => Promise<void>;
onMobileDefaultEditConsumed: () => void;
onSaveAsTemplate: (memo: MemoDetail, name: string) => Promise<void>;
+ onDuplicateMemo?: (memo: MemoDetail) => void;
searchFocusToken: number;
replaceFocusToken: number;
aiAssistantOpenToken: number;
@@ -420,6 +422,7 @@ const RichEditorPane = ({
onRestored,
onMobileDefaultEditConsumed,
onSaveAsTemplate,
+ onDuplicateMemo,
onCreatePoster,
searchFocusToken,
replaceFocusToken,
@@ -4201,6 +4204,23 @@ const RichEditorPane = ({
{t(isLocalMemoId(memo.id) ? "sharing.afterSync" : isMemoShared ? "sharing.manage" : "sharing.action")}
</DropdownMenuItem>
)}
+ {!readOnly && onDuplicateMemo && (
+ <DropdownMenuItem
+ className="flex h-9 w-full items-center gap-2 px-3 text-left text-xs text-slate-700 hover:bg-slate-50 cursor-pointer outline-none"
+ // The server copies the saved note, so wait until every edit is saved.
+ disabled={
+ isLocalMemoId(memo.id)
+ || hasUnsavedChanges
+ || saveMutationPending
+ || saveState === "conflict"
+ || saveState === "error"
+ }
+ onClick={() => onDuplicateMemo(memo)}
+ >
+ <CopyPlus className="h-4 w-4 text-slate-500" />
+ {t("editor.duplicate")}
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem
className="flex h-9 w-full items-center gap-2 px-3 text-left text-xs text-slate-700 hover:bg-slate-50 cursor-pointer outline-none"
onClick={handleExportMarkdown}
diff --git a/apps/web/src/components/MemoListPane.tsx b/apps/web/src/components/MemoListPane.tsx
index 533c7b24..fa3e9319 100644
--- a/apps/web/src/components/MemoListPane.tsx
+++ b/apps/web/src/components/MemoListPane.tsx
@@ -52,6 +52,7 @@ import {
Printer,
Pencil,
Copy,
+ CopyPlus,
} from "lucide-react";
import { WeChatIcon } from "./WeChatIcon";
import { Button } from "@/components/ui/button";
@@ -405,6 +406,7 @@ export const MemoListPane = ({
onDeleteSelectedMemos,
onEmptyTrash,
onMerge,
+ onDuplicateMemo,
onEnterSelectionMode,
onClearSelection,
onToggleMemo,
@@ -476,6 +478,7 @@ export const MemoListPane = ({
onDeleteMemo: (memoId: string) => void;
onRestoreMemo: (memoId: string) => void;
onTogglePinMemo: (memo: MemoSummary) => void;
+ onDuplicateMemo: (memo: MemoSummary) => void;
onMoveMemo: (memoId: string, notebookId: string) => void;
onRequestDocumentAction: (memoId: string, action: MemoDocumentAction, printWindow?: Window | null) => void;
onCopyMemoToWeChat: (memoId: string) => Promise<MemoWeChatCopyResult>;
@@ -1678,6 +1681,20 @@ export const MemoListPane = ({
))}
</DropdownMenuSubContent>
</DropdownMenuSub>
+ {canCreateMemo && view !== "trash" && (
+ <DropdownMenuItem
+ className="flex h-9 w-full items-center gap-2 px-3 text-left text-xs text-slate-700 hover:bg-slate-50 cursor-pointer outline-none"
+ disabled={isLocalMemoId(memoContextMenu.memo.id)}
+ onClick={() => {
+ const { memo } = memoContextMenu;
+ setMemoContextMenu(null);
+ onDuplicateMemo(memo);
+ }}
+ >
+ <CopyPlus className="h-4 w-4 text-slate-500" />
+ {t("editor.duplicate")}
+ </DropdownMenuItem>
+ )}
<DropdownMenuSeparator className="my-1 h-px bg-slate-100" />
<DropdownMenuItem
className="flex h-9 w-full items-center gap-2 px-3 text-left text-xs text-slate-700 hover:bg-slate-50 cursor-pointer outline-none"
diff --git a/apps/web/src/components/WorkspaceApp.tsx b/apps/web/src/components/WorkspaceApp.tsx
index a0ad4fa4..27110944 100644
--- a/apps/web/src/components/WorkspaceApp.tsx
+++ b/apps/web/src/components/WorkspaceApp.tsx
@@ -26,7 +26,7 @@ import { QuickMemoSwitcher } from "./QuickMemoSwitcher";
import { AppConfirmDialog, MemoDeleteConfirmDialog, NotebookNameDialog } from "./dialogs/ConfirmDialogs";
import { PluginPanelDialog } from "./plugins/PluginPanelDialog";
import { shouldDiscardPluginNoteSearchRequest } from "./editor/note-search";
-import { api, getOrCreateClientDeviceId } from "@/lib/api";
+import { api, ApiRequestError, getOrCreateClientDeviceId } from "@/lib/api";
import { useShowDescendantNotesPreference } from "@/lib/descendant-notes-preference";
import { MarkdownExportMemoryLimitError, type MarkdownExportProgress } from "@/lib/markdown-export";
import { exportSelectedMemosAsMarkdownZip } from "@/lib/selected-markdown-export";
@@ -1404,6 +1404,35 @@ export const WorkspaceApp = ({
},
});
+ const duplicateMemoMutation = useMutation({
+ mutationFn: (input: { memoId: string; title: string }) => repository.duplicateMemo(input.memoId, { title: input.title }),
+ onSuccess: async (data) => {
+ cacheMemoDetail(queryClient, data.memo, "notebook");
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: ["memos"] }),
+ queryClient.invalidateQueries({ queryKey: ["notebooks"] }),
+ ]);
+ setRightView("editor");
+ setSelectedMemoId(data.memo.id);
+ setActivePane("editor");
+ },
+ onError: (error) => {
+ const code = error instanceof ApiRequestError ? error.code : error instanceof Error ? error.message : null;
+ setAppNoticeDialog({
+ title: t("editor.duplicateFailedTitle"),
+ description: code === "memo_duplicate_offline"
+ ? t("editor.duplicateOffline")
+ : code === "memo_duplicate_pending_changes"
+ ? t("editor.duplicatePendingChanges")
+ : code === "duplicate_too_large"
+ ? t("editor.duplicateTooLarge")
+ : code === "duplicate_resource_missing" || code === "duplicate_unsupported"
+ ? t("editor.duplicateFilesUnavailable")
+ : t("editor.duplicateFailed"),
+ });
+ },
+ });
+
const moveMemosMutation = useMutation({
mutationFn: repository.moveMemos,
onSuccess: async () => {
@@ -2104,6 +2133,14 @@ export const WorkspaceApp = ({
);
};
+ const handleDuplicateMemo = (memo: { id: string; title: string | null }) => {
+ if (duplicateMemoMutation.isPending || memoView === "trash") return;
+ duplicateMemoMutation.mutate({
+ memoId: memo.id,
+ title: t("editor.duplicateTitle", { title: memo.title?.trim() || t("common.untitledMemo") }).slice(0, 160),
+ });
+ };
+
const handleMerge = () => {
if (selectedMemoIds.size < 2 || memoView === "trash") {
return;
@@ -3335,6 +3372,7 @@ export const WorkspaceApp = ({
});
}}
onMerge={handleMerge}
+ onDuplicateMemo={handleDuplicateMemo}
onDeleteMemo={handleDeleteMemoFromList}
onEmptyTrash={handleEmptyTrash}
onRestoreMemo={handleRestoreMemoFromList}
@@ -3721,6 +3759,7 @@ export const WorkspaceApp = ({
}}
onMobileDefaultEditConsumed={handleMobileDefaultEditConsumed}
onSaveAsTemplate={handleSaveAsTemplate}
+ onDuplicateMemo={handleDuplicateMemo}
/>
)}
</EditorPaneErrorBoundary>
diff --git a/apps/web/src/lib/desktop-repository.test.mjs b/apps/web/src/lib/desktop-repository.test.mjs
index 0826c04e..64e3a17d 100644
--- a/apps/web/src/lib/desktop-repository.test.mjs
+++ b/apps/web/src/lib/desktop-repository.test.mjs
@@ -203,3 +203,94 @@ describe("guarded desktop plugin saves", () => {
} finally { window.edgeeverDesktop.sidecarRequest = request; }
});
});
+
+describe("desktop note duplication", () => {
+ const withDuplicateHarness = async (outboxItems, run) => {
+ // Paused, the real synchronization returns at once. Replacing the module
+ // instead would leak into other test files run in the same process.
+ const { pauseDesktopSyncForImport } = await import("./desktop-sync.ts");
+ const resumeSync = await pauseDesktopSyncForImport();
+ const { api } = await import("./api.ts");
+ const request = window.edgeeverDesktop.sidecarRequest;
+ const duplicate = api.duplicateMemo;
+ const onLine = Object.getOwnPropertyDescriptor(globalThis.navigator, "onLine");
+ Object.defineProperty(globalThis.navigator, "onLine", { configurable: true, value: true });
+ const calls = [];
+ const apiCalls = [];
+ api.duplicateMemo = async (memoId, input) => {
+ apiCalls.push({ memoId, input });
+ return { memo: { id: "memo_copy", title: input.title, contentMarkdown: "Copy", contentJson: { type: "doc", content: [] } } };
+ };
+ window.edgeeverDesktop.sidecarRequest = async (method, params) => {
+ calls.push({ method, params });
+ // Like the sidecar (crates/desktop-sidecar/src/sync.rs): the list holds
+ // pending, error and conflict items in queue order, at most 200 of them.
+ if (method === "sync.outbox.list") {
+ const listed = outboxItems.filter((item) => ["pending", "error", "conflict"].includes(item.status ?? "pending"));
+ return { items: listed.slice(0, Math.min(Math.max(params.limit ?? 50, 1), 200)) };
+ }
+ if (method === "sync.status") {
+ const count = (status) => outboxItems.filter((item) => (item.status ?? "pending") === status).length;
+ return { pending: count("pending"), syncing: count("syncing"), conflict: count("conflict"), error: count("error"), cursor: 0, syncIdentity: null, lastSyncedAt: null };
+ }
+ if (method === "memo.get") return { memo: { id: params.memoId, title: "Plan (copy)", contentMarkdown: "Copy", contentJson: { type: "doc", content: [] } } };
+ return {};
+ };
+ try {
+ await run({ calls, apiCalls });
+ } finally {
+ resumeSync();
+ window.edgeeverDesktop.sidecarRequest = request;
+ api.duplicateMemo = duplicate;
+ if (onLine) Object.defineProperty(globalThis.navigator, "onLine", onLine);
+ else delete globalThis.navigator.onLine;
+ }
+ };
+
+ test("checks the outbox, copies on the server and stores the copy in the sidecar", async () => {
+ await withDuplicateHarness([], async ({ calls, apiCalls }) => {
+ const result = await createDesktopRepository().duplicateMemo("memo_plan", { title: "Plan (copy)" });
+
+ expect(apiCalls).toEqual([{ memoId: "memo_plan", input: { title: "Plan (copy)" } }]);
+ expect(calls.map((call) => call.method)).toEqual(["sync.status", "sync.outbox.list", "sync.apply", "memo.get"]);
+ expect(calls[2].params.changes[0]).toMatchObject({ entityType: "memo", operation: "upsert", entityId: "memo_copy" });
+ expect(result.memo).toMatchObject({ id: "memo_copy", title: "Plan (copy)" });
+ });
+ });
+
+ const conflicts = (count) => Array.from({ length: count }, (_, index) => ({
+ id: index + 1, kind: "memo.update", entityId: `memo_other_${index}`, status: "conflict",
+ }));
+
+ test("refuses when the note's conflict lies beyond the 200 items the sidecar lists", async () => {
+ const outbox = [...conflicts(200), { id: 201, kind: "memo.update", entityId: "memo_plan", status: "conflict" }];
+ await withDuplicateHarness(outbox, async ({ apiCalls }) => {
+ await expect(createDesktopRepository().duplicateMemo("memo_plan", { title: "Plan (copy)" }))
+ .rejects.toThrow("memo_duplicate_pending_changes");
+ expect(apiCalls).toEqual([]);
+ });
+ });
+
+ test("copies when every outstanding item was listed and none belongs to the note", async () => {
+ await withDuplicateHarness(conflicts(150), async ({ apiCalls }) => {
+ await createDesktopRepository().duplicateMemo("memo_plan", { title: "Plan (copy)" });
+ expect(apiCalls).toHaveLength(1);
+ });
+ });
+
+ test("refuses while another synchronization is still sending changes", async () => {
+ await withDuplicateHarness([{ id: 1, kind: "memo.update", entityId: "memo_other", status: "syncing" }], async ({ apiCalls }) => {
+ await expect(createDesktopRepository().duplicateMemo("memo_plan", { title: "Plan (copy)" }))
+ .rejects.toThrow("memo_duplicate_pending_changes");
+ expect(apiCalls).toEqual([]);
+ });
+ });
+
+ test("refuses while the note still has unsynchronized changes", async () => {
+ await withDuplicateHarness([{ id: 1, kind: "memo.update", entityId: "memo_plan" }], async ({ apiCalls }) => {
+ await expect(createDesktopRepository().duplicateMemo("memo_plan", { title: "Plan (copy)" }))
+ .rejects.toThrow("memo_duplicate_pending_changes");
+ expect(apiCalls).toEqual([]);
+ });
+ });
+});
diff --git a/apps/web/src/lib/desktop-repository.ts b/apps/web/src/lib/desktop-repository.ts
index b4fe2fd5..57e53e8a 100644
--- a/apps/web/src/lib/desktop-repository.ts
+++ b/apps/web/src/lib/desktop-repository.ts
@@ -275,6 +275,33 @@ export const createDesktopRepository = (): EdgeEverRepository => ({
return { memo: await repairDisplayedMemo(result.memo) };
},
+ duplicateMemo: async (memoId, input = {}) => {
+ if (typeof navigator !== "undefined" && !navigator.onLine) throw new Error("memo_duplicate_offline");
+ // The server copies the note, so its local edits are synchronized first.
+ const { syncDesktopData } = await import("@/lib/desktop-sync");
+ await syncDesktopData();
+ // The sidecar lists at most 200 outbox items, so a change of this note
+ // further down the queue cannot be seen. Duplicate only when the whole
+ // outstanding queue was listed and none of it belongs to this note.
+ const [status, outbox] = await Promise.all([
+ request("sync.status", {}),
+ request("sync.outbox.list", { limit: 200, includeConflicts: true }),
+ ]);
+ const outstanding = status.pending + status.error + status.conflict;
+ if (
+ status.syncing > 0
+ || outbox.items.length < outstanding
+ || outbox.items.some((item) => item.entityId === memoId)
+ ) {
+ throw new Error("memo_duplicate_pending_changes");
+ }
+ const result = await api.duplicateMemo(memoId, input);
+ await request("sync.apply", {
+ changes: [{ entityType: "memo", operation: "upsert", entityId: result.memo.id, memo: result.memo, notebook: null }],
+ });
+ return { memo: await repairDisplayedMemo((await request("memo.get", { memoId: result.memo.id, includeDeleted: false })).memo) };
+ },
+
listMemos: (params) => {
const rpcParams: DesktopMemoListParams = {
...params,
diff --git a/apps/web/src/lib/repository-events.ts b/apps/web/src/lib/repository-events.ts
index c6f23f5d..5ca84201 100644
--- a/apps/web/src/lib/repository-events.ts
+++ b/apps/web/src/lib/repository-events.ts
@@ -99,6 +99,11 @@ export const withRepositoryMutationEvents = (repository: EdgeEverRepository, sco
notifyRepositoryMutation(scope, { type: "template.deleted", templateId });
return result;
},
+ async duplicateMemo(memoId, input) {
+ const result = await repository.duplicateMemo(memoId, input);
+ notifyRepositoryMutation(scope, { type: "note.created", note: result.memo });
+ return result;
+ },
async mergeMemos(input) {
const result = await repository.mergeMemos(input);
notifyRepositoryMutation(scope, { type: "note.created", note: result.memo });
diff --git a/apps/web/src/lib/repository.test.mjs b/apps/web/src/lib/repository.test.mjs
index 30d40261..8e6cf052 100644
--- a/apps/web/src/lib/repository.test.mjs
+++ b/apps/web/src/lib/repository.test.mjs
@@ -473,3 +473,90 @@ describe("guarded plugin saves in the Web repository", () => {
} finally { restoreWindow(); }
});
});
+
+describe("note duplication in the Web repository", () => {
+ test("copies on the server and keeps the copy in the local mirror", async () => {
+ const restoreWindow = installTestWindow();
+ const duplicate = api.duplicateMemo;
+ const calls = [];
+ const scope = "https://demo.edgeever.org|user-1";
+ const copy = { ...(await createLocalMemo(scope, { notebookId: "nb-1" })), id: "memo_copy", title: "Plan (copy)" };
+ api.duplicateMemo = async (memoId, input) => {
+ calls.push({ memoId, input });
+ return { memo: copy };
+ };
+ try {
+ const result = await createWebRepository(scope).duplicateMemo("memo_plan", { title: "Plan (copy)" });
+
+ expect(calls).toEqual([{ memoId: "memo_plan", input: { title: "Plan (copy)" } }]);
+ expect(result.memo).toEqual(copy);
+ const { getLocalMemo } = await import("./local-mirror.ts");
+ expect((await getLocalMemo(scope, "memo_copy"))?.title).toBe("Plan (copy)");
+ } finally {
+ api.duplicateMemo = duplicate;
+ restoreWindow();
+ }
+ });
+
+ test("never copies a note in an unresolved sync conflict", async () => {
+ const restoreWindow = installTestWindow();
+ const duplicate = api.duplicateMemo;
+ const calls = [];
+ api.duplicateMemo = async (memoId) => {
+ calls.push(memoId);
+ return { memo: { id: "memo_copy" } };
+ };
+ const scope = "https://demo.edgeever.org|user-1";
+ try {
+ await localDb.syncQueue.put({
+ id: "memo.update:memo_conflicted",
+ kind: "memo.update",
+ scope,
+ memoId: "memo_conflicted",
+ status: "conflict",
+ payload: { memoId: "memo_conflicted" },
+ attemptCount: 1,
+ lastError: "Memo was updated elsewhere",
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ nextAttemptAt: null,
+ });
+
+ await expect(createWebRepository(scope).duplicateMemo("memo_conflicted", { title: "Copy" }))
+ .rejects.toThrow("memo_duplicate_pending_changes");
+ expect(calls).toEqual([]);
+ } finally {
+ api.duplicateMemo = duplicate;
+ restoreWindow();
+ }
+ });
+
+ test("never copies a note whose local edits could not be synchronized", async () => {
+ const restoreWindow = installTestWindow();
+ const duplicate = api.duplicateMemo;
+ const calls = [];
+ api.duplicateMemo = async (memoId) => {
+ calls.push(memoId);
+ return { memo: { id: "memo_copy" } };
+ };
+ const scope = "https://demo.edgeever.org|user-1";
+ try {
+ const memo = await createLocalMemo(scope, { notebookId: "nb-1" });
+ const repository = createWebRepository(scope);
+ await repository.updateMemo(memo, {
+ expectedRevision: memo.revision,
+ expectedContentHash: memo.contentHash,
+ editSessionId: "local-edit",
+ title: "Edited offline",
+ contentJson: { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: "Unsynced" }] }] },
+ tags: [],
+ });
+
+ await expect(repository.duplicateMemo(memo.id, { title: "Copy" })).rejects.toThrow("memo_duplicate_pending_changes");
+ expect(calls).toEqual([]);
+ } finally {
+ api.duplicateMemo = duplicate;
+ restoreWindow();
+ }
+ });
+});
diff --git a/apps/web/src/lib/repository.ts b/apps/web/src/lib/repository.ts
index 354f69b6..930f01c2 100644
--- a/apps/web/src/lib/repository.ts
+++ b/apps/web/src/lib/repository.ts
@@ -79,6 +79,11 @@ export type EdgeEverRepository = {
emptyTrash(): Promise<{ ok: true; deleted: number }>;
pinMemos(input: { memoIds: string[]; isPinned: boolean }): Promise<{ ok: true; updated: number }>;
mergeMemos(input: { memoIds: string[]; notebookId?: string; title?: string }): Promise<{ memo: MemoDetail }>;
+ /**
+ * Copies a note, its tags and its files on the server. Requires a connection;
+ * local edits of the note are synchronized first so the copy includes them.
+ */
+ duplicateMemo(memoId: string, input?: { notebookId?: string; title?: string }): Promise<{ memo: MemoDetail }>;
listMemos(params: LocalMemoListParams): Promise<LocalMemoListResponse>;
getMemo(memoId: string, includeDeleted?: boolean): Promise<{ memo: MemoDetail }>;
createMemo(input: { notebookId: string; title?: string; contentJson?: TiptapDoc; contentMarkdown?: string; tags?: string[] }): Promise<{ memo: MemoDetail }>;
@@ -442,6 +447,22 @@ export const createWebRepository = (scope: string): EdgeEverRepository => {
return { memo };
},
+ duplicateMemo: async (memoId, input = {}) => {
+ if (isOffline()) throw new Error("memo_duplicate_offline");
+ // The server copies what it stores, so every queued change of the note,
+ // including an unresolved conflict, must reach it first.
+ const hasQueuedChange = async () => (await localDb.syncQueue.where("memoId").equals(memoId).toArray())
+ .some((item) => !item.scope || item.scope === scope);
+ if (await hasQueuedChange()) {
+ // A failed synchronization leaves the change queued, which is reported below.
+ await syncLocalMirror(scope).catch(() => undefined);
+ if (await hasQueuedChange()) throw new Error("memo_duplicate_pending_changes");
+ }
+ const result = await api.duplicateMemo(memoId, input);
+ await putLocalMemo(scope, result.memo);
+ return result;
+ },
+
async listMemos(params) {
if (await isLocalMirrorInitialized(scope) || await hasLocalMirrorData(scope)) {
return listLocalMemos(scope, params);
diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts
index bf0b95e5..39595019 100644
--- a/packages/client/src/index.ts
+++ b/packages/client/src/index.ts
@@ -1891,6 +1891,12 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {
body: JSON.stringify({}),
}),
+ duplicateMemo: (memoId: string, payload: { notebookId?: string; title?: string } = {}) =>
+ request<MemoResponse>(`/api/v1/memos/${encodeURIComponent(memoId)}/duplicate`, {
+ method: "POST",
+ body: JSON.stringify(payload),
+ }),
+
mergeMemos: (payload: { memoIds: string[]; notebookId?: string; title?: string }) =>
request<MemoResponse>("/api/v1/memos/merge", {
method: "POST",
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index e924533b..5ce127ef 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -2402,6 +2402,14 @@ export const enUS = {
noteIdCopied: "Note ID copied: {{id}}",
noteIdCopyFailed: "Could not copy the note ID.",
exportMarkdown: "Export Markdown",
+ duplicate: "Duplicate note",
+ duplicateTitle: "{{title}} (copy)",
+ duplicateFailedTitle: "Couldn't duplicate this note",
+ duplicateFailed: "The copy was not created. Try again in a moment.",
+ duplicateOffline: "Duplicating a note needs a connection to the server. Try again when you are online.",
+ duplicatePendingChanges: "This note has changes that are not synchronized yet. Wait for synchronization, then try again.",
+ duplicateTooLarge: "This note has too many or too large files to duplicate. Notes with up to 20 files totaling 64 MiB can be duplicated.",
+ duplicateFilesUnavailable: "Some files of this note are unavailable, so it cannot be duplicated.",
exportHtml: "Export HTML",
exportPdf: "Export PDF",
exportPng: "Export PNG",
diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.ts
index 76668dd3..cd4a9d72 100644
--- a/packages/shared/src/i18n/ja.ts
+++ b/packages/shared/src/i18n/ja.ts
@@ -2391,6 +2391,14 @@ export const ja = {
noteIdCopied: "ノート ID をコピーしました:{{id}}",
noteIdCopyFailed: "ノート ID をコピーできませんでした。",
exportMarkdown: "Markdown をエクスポート",
+ duplicate: "ノートを複製",
+ duplicateTitle: "{{title}}(コピー)",
+ duplicateFailedTitle: "このノートを複製できませんでした",
+ duplicateFailed: "コピーは作成されませんでした。しばらくしてから再試行してください。",
+ duplicateOffline: "ノートの複製にはサーバーへの接続が必要です。オンラインになってから再試行してください。",
+ duplicatePendingChanges: "このノートには未同期の変更があります。同期が完了してから再試行してください。",
+ duplicateTooLarge: "このノートはファイルが多すぎるか大きすぎるため複製できません。ファイルが 20 個以内で合計 64 MiB 以下のノートを複製できます。",
+ duplicateFilesUnavailable: "このノートの一部のファイルを利用できないため、複製できません。",
exportHtml: "HTML をエクスポート",
exportPdf: "PDF をエクスポート",
exportPng: "PNG をエクスポート",
diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.ts
index 9fdbc287..ca0bb716 100644
--- a/packages/shared/src/i18n/pl.ts
+++ b/packages/shared/src/i18n/pl.ts
@@ -2391,6 +2391,14 @@ export const pl = {
noteIdCopied: "Skopiowano ID notatki: {{id}}",
noteIdCopyFailed: "Nie udało się skopiować ID notatki.",
exportMarkdown: "Eksportuj Markdown",
+ duplicate: "Duplikuj notatkę",
+ duplicateTitle: "{{title}} (kopia)",
+ duplicateFailedTitle: "Nie udało się zduplikować notatki",
+ duplicateFailed: "Kopia nie została utworzona. Spróbuj ponownie za chwilę.",
+ duplicateOffline: "Duplikowanie notatki wymaga połączenia z serwerem. Spróbuj ponownie, gdy będziesz online.",
+ duplicatePendingChanges: "Ta notatka ma jeszcze niezsynchronizowane zmiany. Poczekaj na synchronizację i spróbuj ponownie.",
+ duplicateTooLarge: "Ta notatka ma za dużo plików albo są one zbyt duże, żeby ją zduplikować. Można duplikować notatki z maksymalnie 20 plikami o łącznym rozmiarze do 64 MiB.",
+ duplicateFilesUnavailable: "Część plików tej notatki jest niedostępna, więc nie można jej zduplikować.",
exportHtml: "Eksportuj HTML",
exportPdf: "Eksportuj PDF",
exportPng: "Eksportuj PNG",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index 25092148..f8b6be33 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -2402,6 +2402,14 @@ export const zhCN = {
noteIdCopied: "笔记 ID 已复制:{{id}}",
noteIdCopyFailed: "复制笔记 ID 失败。",
exportMarkdown: "导出 Markdown",
+ duplicate: "创建副本",
+ duplicateTitle: "{{title}}(副本)",
+ duplicateFailedTitle: "没能创建这条笔记的副本",
+ duplicateFailed: "副本未创建,请稍后重试。",
+ duplicateOffline: "创建笔记副本需要连接服务器,请联网后重试。",
+ duplicatePendingChanges: "这条笔记还有未同步的修改,请等待同步完成后重试。",
+ duplicateTooLarge: "这条笔记的文件过多或过大,无法创建副本。最多 20 个文件且总大小不超过 64 MiB 的笔记才能创建副本。",
+ duplicateFilesUnavailable: "这条笔记的部分文件不可用,无法创建副本。",
exportHtml: "导出 HTML",
exportPdf: "导出 PDF",
exportPng: "导出 PNG",
diff --git a/packages/shared/src/schemas.ts b/packages/shared/src/schemas.ts
index 7977326a..7bd1c62d 100644
--- a/packages/shared/src/schemas.ts
+++ b/packages/shared/src/schemas.ts
@@ -166,6 +166,11 @@ export const DeleteMemosSchema = z.object({
permanent: z.boolean().optional(),
});
+export const DuplicateMemoSchema = z.object({
+ notebookId: z.string().trim().min(1).optional(),
+ title: z.string().trim().max(160).optional(),
+});
+
export const MergeMemosSchema = z.object({
memoIds: z.array(z.string().trim().min(1)).min(2).max(50),
notebookId: z.string().trim().min(1).optional(),