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
perf: pipeline image compression and resource uploads
tianma-ife9476ba1ac97
diff --git a/apps/api/src/resource-upload-integration.test.mjs b/apps/api/src/resource-upload-integration.test.mjsindex 4b06a2df..24971d6a 100644--- a/apps/api/src/resource-upload-integration.test.mjs+++ b/apps/api/src/resource-upload-integration.test.mjs@@ -5,6 +5,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { fetchEdgeEverApp } from "./index.ts";import { createSelfHostedStorageAdapter } from "./self-hosted-storage-adapter.ts";+import { createEdgeEverClient } from "../../../packages/client/src/index.ts";const temporaryDirectories = [];afterEach(async () => {@@ -22,8 +23,8 @@ const requestJson = async (environment, path, init = {}) => {return body;};-describe("resource multipart upload integration", () => {- test("assembles a large resource through the shared API and filesystem adapter", async () => {+describe("resource upload integration", () => {+ test("uploads small images directly and assembles large resources through the filesystem adapter", async () => {const directory = await mkdtemp(`${tmpdir()}/edgeever-upload-integration-`);temporaryDirectories.push(directory);const database = new Database(join(directory, "edgeever.sqlite"), { create: true });@@ -53,6 +54,27 @@ describe("resource multipart upload integration", () => {body: JSON.stringify({ notebookId: notebook.notebook.id, title: "Multipart", contentMarkdown: "" }),});+ const uploadPaths = [];+ const client = createEdgeEverClient({+ baseUrl: "http://edgeever.test",+ fetch: (input, init) => {+ uploadPaths.push(new URL(input).pathname);+ return fetchEdgeEverApp(new Request(input, init), environment,+ { waitUntil: () => undefined, passThroughOnException: () => undefined });+ },+ });+ const smallImage = new File([+ Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=", "base64"),+ ], "small.png", { type: "image/png" });+ const images = await Promise.all([0, 1].map(() => client.uploadMemoResource(memo.memo.id, smallImage)));+ expect(uploadPaths).toEqual(Array(2).fill(`/api/v1/memos/${memo.memo.id}/resources`));+ for (const { resource } of images) {+ expect(resource).toMatchObject({ filename: "small.png", kind: "image", mimeType: "image/png", byteSize: smallImage.size });+ const imageRow = database.query("SELECT object_key FROM resources WHERE id = ?").get(resource.id);+ expect(await readFile(join(resourcesDirectory, imageRow.object_key)))+ .toEqual(Buffer.from(await smallImage.arrayBuffer()));+ }+const file = new Uint8Array(8 * 1024 * 1024 + 3);file.fill(7);file.set([1, 2, 3], file.byteLength - 3);diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsxindex 11427d4c..31a5cbe0 100644--- a/apps/web/src/components/EditorPane.tsx+++ b/apps/web/src/components/EditorPane.tsx@@ -71,6 +71,7 @@ import {createImageUploadPlaceholder,removeImageUploadPlaceholder,waitForImageSourceReady,+ updateImageUploadPlaceholder,} from "./editor/image-upload-placeholder";import {clampResourceInsertionTarget,@@ -193,7 +194,7 @@ import {isAttachmentLinkHref,} from "@/lib/editor-external-link";import { insertAiDraftAtTextCursor } from "@/lib/ai-draft-insertion";-import { createFileBatchQueue, processFilesSequentially } from "@/lib/file-batch";+import { createFileBatchQueue, processFileUploadBatch } from "@/lib/file-batch";import { MEMO_ID_REMAPPED_EVENT, MEMO_SYNC_ACKNOWLEDGED_EVENT } from "@/lib/sync-events";import { useStandaloneMobileEditor } from "@/hooks/useStandaloneMobileEditor";import { statusSettleMotion } from "@/lib/motion";@@ -987,12 +988,13 @@ const RichEditorPane = ({const targetMemoId = currentMemo.id;const interactionVersionAtRequest = editorCanvasInteractionVersionRef.current;const placeholderPosition = currentEditor.state.selection.from;- const imagePlaceholders = files+ const imagePlaceholderByFile = new Map(files.filter((file) => SUPPORTED_PASTE_IMAGE_TYPES.has(file.type))- .map((file) => createImageUploadPlaceholder(+ .map((file) => [file, createImageUploadPlaceholder(file,t("editor.uploadState.imagePreparing"),- ));+ )] as const));+ const imagePlaceholders = [...imagePlaceholderByFile.values()];imagePlaceholders.forEach((placeholder) => {addImageUploadPlaceholder(currentEditor, placeholder, placeholderPosition);});@@ -1011,14 +1013,25 @@ const RichEditorPane = ({// Rapid consecutive pastes otherwise race with the same stale cursor.const insertionTarget = getResourceInsertionTarget(insertionEditor.state.selection);setImageUploadState("uploading");+ const imageReadiness: Promise<void>[] = [];- const results = await processFilesSequentially(files, async (file) => {+ const results = await processFileUploadBatch(files, async (file) => {const isImage = SUPPORTED_PASTE_IMAGE_TYPES.has(file.type);const shouldCompress = isImage && imageCompressionEnabledRef.current;+ const placeholder = imagePlaceholderByFile.get(file);+ if (placeholder) updateImageUploadPlaceholder(editorRef.current, placeholder,+ t(shouldCompress ? "editor.uploadState.imageCompressing" : "editor.uploadState.uploading"));setImageUploadState(shouldCompress ? "compressing" : "uploading");- const uploadFile = shouldCompress ? (await compressImageForUpload(file)).file : file;-+ const preparedFile = shouldCompress ? (await compressImageForUpload(file)).file : file;+ if (placeholder) updateImageUploadPlaceholder(editorRef.current, placeholder,+ t("editor.uploadState.waitingToUpload"));+ return preparedFile;+ }, async (uploadFile, file) => {+ const isImage = SUPPORTED_PASTE_IMAGE_TYPES.has(file.type);+ const placeholder = imagePlaceholderByFile.get(file);setImageUploadState("uploading");+ if (placeholder) updateImageUploadPlaceholder(editorRef.current, placeholder,+ t("editor.uploadState.uploading"));let resource: {kind: "image" | "attachment";filename: string | null;@@ -1041,6 +1054,9 @@ const RichEditorPane = ({url: `edgeever-staged://${staged.id}`,};}+ if (resource.kind === "image") {+ imageReadiness.push(waitForImageSourceReady(resource.url));+ }return resource;});@@ -1048,10 +1064,7 @@ const RichEditorPane = ({if (successfulResults.length > 0) {void queryClient.invalidateQueries({ queryKey: ["resources"] });}-- await Promise.all(successfulResults.map(({ value: resource }) =>- resource.kind === "image" ? waitForImageSourceReady(resource.url) : Promise.resolve()- ));+ await Promise.all(imageReadiness);const activeEditor = editorRef.current;if (memoRef.current?.id !== targetMemoId || !isEditorReady(activeEditor)) {diff --git a/apps/web/src/components/editor/image-upload-placeholder.ts b/apps/web/src/components/editor/image-upload-placeholder.tsindex 1cf048aa..b710c9c2 100644--- a/apps/web/src/components/editor/image-upload-placeholder.ts+++ b/apps/web/src/components/editor/image-upload-placeholder.ts@@ -45,6 +45,7 @@ const renderPlaceholder = (placeholder: ImageUploadPlaceholder) => {spinner.setAttribute("aria-hidden", "true");const label = document.createElement("span");+ label.className = "edgeever-image-upload-placeholder__label";label.textContent = placeholder.statusLabel;status.appendChild(spinner);status.appendChild(label);@@ -137,6 +138,20 @@ export const removeImageUploadPlaceholder = (}};+export const updateImageUploadPlaceholder = (+ editor: Editor | null | undefined,+ placeholder: ImageUploadPlaceholder,+ statusLabel: string,+) => {+ placeholder.statusLabel = statusLabel;+ if (!editor || editor.isDestroyed) return;+ // Update the widget in place so its decoded local preview stays mounted.+ const element = editor.view.dom.querySelector(`[data-placeholder-id="${placeholder.id}"]`);+ element?.setAttribute("aria-label", `${statusLabel}: ${placeholder.filename}`);+ const label = element?.querySelector(".edgeever-image-upload-placeholder__label");+ if (label) label.textContent = statusLabel;+};+/** Keep the local preview visible until the persisted image can paint. */export const waitForImageSourceReady = async (source: string, timeoutMs = 4_000) => {if (typeof Image === "undefined") return;diff --git a/apps/web/src/lib/file-batch.test.mjs b/apps/web/src/lib/file-batch.test.mjsindex d58d680c..8248fd96 100644--- a/apps/web/src/lib/file-batch.test.mjs+++ b/apps/web/src/lib/file-batch.test.mjs@@ -1,5 +1,89 @@import { describe, expect, test } from "bun:test";-import { createFileBatchQueue, processFilesSequentially } from "./file-batch.ts";+import { createFileBatchQueue, processFileUploadBatch, processFilesSequentially } from "./file-batch.ts";++const deferred = () => {+ let resolve;+ const promise = new Promise((done) => { resolve = done; });+ return { promise, resolve };+};+const tick = () => new Promise((resolve) => setTimeout(resolve, 0));++test("prepares two files independently of four uploads with bounded buffering", async () => {+ const files = Array.from({ length: 12 }, (_, i) => new File([String(i)], String(i)));+ const preparations = files.map(deferred);+ const uploads = files.map(deferred);+ const startedPreparing = [];+ const startedUploading = [];+ let preparing = 0, uploading = 0, inFlight = 0;+ let maxPreparing = 0, maxUploading = 0, maxInFlight = 0;+ const completion = processFileUploadBatch(files, async (file) => {+ const index = Number(file.name);+ startedPreparing.push(index);+ maxPreparing = Math.max(maxPreparing, ++preparing);+ maxInFlight = Math.max(maxInFlight, ++inFlight);+ await preparations[index].promise;+ preparing--;+ return new File(["compressed"], `${file.name}.webp`);+ }, async (preparedFile, originalFile) => {+ const index = Number(originalFile.name);+ expect(preparedFile.name).toBe(`${originalFile.name}.webp`);+ startedUploading.push(index);+ maxUploading = Math.max(maxUploading, ++uploading);+ await uploads[index].promise;+ uploading--;+ inFlight--;+ return `uploaded:${originalFile.name}`;+ });++ await tick();+ expect(startedPreparing).toEqual([0, 1]);+ preparations[0].resolve(); preparations[1].resolve();+ await tick();+ expect(startedUploading).toEqual([0, 1]);+ expect(startedPreparing).toEqual([0, 1, 2, 3]);+ preparations[2].resolve(); preparations[3].resolve();+ await tick();+ expect(startedUploading).toEqual([0, 1, 2, 3]);+ expect(startedPreparing).toEqual([0, 1, 2, 3, 4, 5]);+ preparations[4].resolve(); preparations[5].resolve();+ await tick();+ // The stalled network may hold two prepared files, but not the whole batch.+ expect(startedPreparing).toHaveLength(6);+ expect(startedUploading).toHaveLength(4);+ uploads[3].resolve();+ await tick();+ expect(startedPreparing).toHaveLength(7);+ expect(startedUploading).toEqual([0, 1, 2, 3, 4]);++ preparations.forEach(({ resolve }) => resolve());+ uploads.forEach(({ resolve }) => resolve());+ const results = await completion;+ expect(maxPreparing).toBe(2);+ expect(maxUploading).toBe(4);+ expect(maxInFlight).toBe(6);+ expect(results.map(({ file }) => file)).toEqual(files);+ expect(results.map(({ value }) => value)).toEqual(files.map((file) => `uploaded:${file.name}`));+});++test("continues after failures in either phase without losing original file order", async () => {+ const files = Array.from({ length: 10 }, (_, i) => new File([String(i)], String(i)));+ const uploadAttempts = [];+ const results = await processFileUploadBatch(files, async (file) => {+ if (file.name === "0") throw new Error("preparation failed");+ return new File(["compressed"], `${file.name}.webp`);+ }, async (preparedFile, originalFile) => {+ uploadAttempts.push(originalFile.name);+ if (originalFile.name === "2") throw new Error("upload failed");+ return preparedFile.name;+ });+ expect(uploadAttempts).not.toContain("0");+ expect(uploadAttempts).toHaveLength(9);+ expect(results.map(({ file }) => file)).toEqual(files);+ expect(results[0]).toMatchObject({ status: "rejected", reason: new Error("preparation failed") });+ expect(results[2]).toMatchObject({ status: "rejected", reason: new Error("upload failed") });+ expect(results.filter(({ status }) => status === "fulfilled")).toHaveLength(8);+ expect(results[9]).toMatchObject({ status: "fulfilled", value: "9.webp" });+});describe("processFilesSequentially", () => {test("continues after a failed file and preserves selection order", async () => {diff --git a/apps/web/src/lib/file-batch.ts b/apps/web/src/lib/file-batch.tsindex 78518f85..a5de353a 100644--- a/apps/web/src/lib/file-batch.ts+++ b/apps/web/src/lib/file-batch.ts@@ -21,6 +21,31 @@ export const processFilesSequentially = async <T>(return results;};+const FILE_PREPARATION_CONCURRENCY = 2;+const FILE_UPLOAD_CONCURRENCY = 4;++/** Keep the network busy without accumulating an entire batch of compressed blobs. */+export const processFileUploadBatch = async <T>(+ files: File[],+ prepareFile: (file: File) => Promise<File>,+ uploadFile: (preparedFile: File, originalFile: File) => Promise<T>,+): Promise<FileBatchResult<T>[]> => {+ const prepare = pLimit(FILE_PREPARATION_CONCURRENCY);+ const upload = pLimit(FILE_UPLOAD_CONCURRENCY);+ // Four uploads plus two files being prepared or waiting to upload. When the+ // network stalls, stop preparing more files until an upload releases a slot.+ const inFlight = pLimit(FILE_PREPARATION_CONCURRENCY + FILE_UPLOAD_CONCURRENCY);+ return Promise.all(files.map((file) => inFlight(async (): Promise<FileBatchResult<T>> => {+ try {+ const preparedFile = await prepare(() => prepareFile(file));+ const value = await upload(() => uploadFile(preparedFile, file));+ return { file, status: "fulfilled", value };+ } catch (reason) {+ return { file, status: "rejected", reason };+ }+ })));+};+/** Serialize separate paste/drop batches so each reads the post-insert cursor. */export const createFileBatchQueue = () => {const limit = pLimit(1);diff --git a/apps/web/src/lib/image-compression.test.mjs b/apps/web/src/lib/image-compression.test.mjsnew file mode 100644index 00000000..dde6c667--- /dev/null+++ b/apps/web/src/lib/image-compression.test.mjs@@ -0,0 +1,65 @@+import { afterEach, expect, test } from "bun:test";+import { compressImageForUpload } from "./image-compression.ts";++const originalWorker = Object.getOwnPropertyDescriptor(globalThis, "Worker");+afterEach(() => {+ if (originalWorker) Object.defineProperty(globalThis, "Worker", originalWorker);+ else delete globalThis.Worker;+});++const source = () => new File([new Uint8Array(1024)], "截图.png", { type: "image/png", lastModified: 123 });+const mockWorker = (blob) => {+ const state = { terminated: false, message: null };+ globalThis.Worker = class {+ postMessage(message) {+ state.message = message;+ queueMicrotask(() => this.onmessage({ data: { blob } }));+ }+ terminate() { state.terminated = true; }+ };+ return state;+};++test("uses background compression and releases the worker while preserving metadata", async () => {+ const state = mockWorker(new Blob(["webp"], { type: "image/webp" }));+ const file = source();+ const result = await compressImageForUpload(file);+ expect(result.compressed).toBe(true);+ expect(result.file.name).toBe("截图.webp");+ expect(result.file.lastModified).toBe(123);+ expect(result.file.type).toBe("image/webp");+ expect(state.message).toMatchObject({ file, maxEdge: 2560, quality: 0.82 });+ expect(state.terminated).toBe(true);+});++test("keeps the original when encoding increases the file size or returns another format", async () => {+ for (const blob of [new Blob([new Uint8Array(2048)], { type: "image/webp" }), new Blob(["png"], { type: "image/png" }), null]) {+ const state = mockWorker(blob);+ const file = source();+ expect((await compressImageForUpload(file)).file).toBe(file);+ expect(state.terminated).toBe(true);+ }+});++test("does not decode unsupported images or attachments", async () => {+ globalThis.Worker = class { constructor() { throw new Error("must not start"); } };+ const file = new File(["gif"], "animation.gif", { type: "image/gif" });+ expect((await compressImageForUpload(file)).file).toBe(file);+});++test("retains the original when both worker and canvas are unavailable", async () => {+ globalThis.Worker = class { constructor() { throw new Error("unavailable"); } };+ const file = source();+ expect((await compressImageForUpload(file)).file).toBe(file);+});++test("terminates the worker when posting fails and retains a usable original", async () => {+ let terminated = false;+ globalThis.Worker = class {+ postMessage() { throw new Error("cannot clone"); }+ terminate() { terminated = true; }+ };+ const file = source();+ expect((await compressImageForUpload(file)).file).toBe(file);+ expect(terminated).toBe(true);+});diff --git a/apps/web/src/lib/image-compression.ts b/apps/web/src/lib/image-compression.tsindex 03d60061..4bf7ff3b 100644--- a/apps/web/src/lib/image-compression.ts+++ b/apps/web/src/lib/image-compression.ts@@ -17,28 +17,9 @@ export const compressImageForUpload = async (file: File): Promise<ImageCompressi}try {- const image = await loadImage(file);- const width = image.naturalWidth;- const height = image.naturalHeight;-- if (width <= 0 || height <= 0) {- return unchanged(file);- }-- const scale = Math.min(1, MAX_COMPRESSED_IMAGE_EDGE / Math.max(width, height));- const canvas = document.createElement("canvas");- canvas.width = Math.max(1, Math.round(width * scale));- canvas.height = Math.max(1, Math.round(height * scale));-- const context = canvas.getContext("2d", { alpha: true });-- if (!context) {- return unchanged(file);- }-- context.drawImage(image, 0, 0, canvas.width, canvas.height);-- const blob = await canvasToBlob(canvas, COMPRESSED_IMAGE_TYPE, IMAGE_COMPRESSION_QUALITY);+ // Decoding, resizing and WebP encoding must not compete with the editor's+ // painting/input work. Older browsers retain the original canvas fallback.+ const blob = await compressInWorker(file).catch(() => compressOnCanvas(file));if (!blob || blob.type !== COMPRESSED_IMAGE_TYPE || blob.size >= file.size) {return unchanged(file);@@ -58,6 +39,47 @@ export const compressImageForUpload = async (file: File): Promise<ImageCompressi}};+const compressInWorker = (file: File): Promise<Blob | null> => new Promise((resolve, reject) => {+ const worker = new Worker(new URL("./image-compression.worker.ts", import.meta.url), { type: "module" });+ const finish = (blob: Blob | null, error?: Error) => {+ clearTimeout(timeout);+ worker.terminate();+ if (error) reject(error);+ else resolve(blob);+ };+ const timeout = setTimeout(() => finish(null, new Error("Image compression timed out.")), 15_000);+ worker.onmessage = (event: MessageEvent<{ blob: Blob | null; error?: string }>) => {+ finish(event.data.blob, event.data.error ? new Error(event.data.error) : undefined);+ };+ worker.onerror = () => finish(null, new Error("Image compression worker failed."));+ worker.onmessageerror = () => finish(null, new Error("Image compression response could not be read."));+ try {+ worker.postMessage({ file, maxEdge: MAX_COMPRESSED_IMAGE_EDGE, type: COMPRESSED_IMAGE_TYPE, quality: IMAGE_COMPRESSION_QUALITY });+ } catch (error) {+ finish(null, error instanceof Error ? error : new Error(String(error)));+ }+});++const compressOnCanvas = async (file: File) => {+ const image = await loadImage(file);+ const width = image.naturalWidth;+ const height = image.naturalHeight;+ if (width <= 0 || height <= 0) return null;++ const scale = Math.min(1, MAX_COMPRESSED_IMAGE_EDGE / Math.max(width, height));+ const canvas = document.createElement("canvas");+ canvas.width = Math.max(1, Math.round(width * scale));+ canvas.height = Math.max(1, Math.round(height * scale));+ try {+ const context = canvas.getContext("2d", { alpha: true });+ if (!context) return null;+ context.drawImage(image, 0, 0, canvas.width, canvas.height);+ return await canvasToBlob(canvas, COMPRESSED_IMAGE_TYPE, IMAGE_COMPRESSION_QUALITY);+ } finally {+ canvas.width = canvas.height = 0;+ }+};+const unchanged = (file: File): ImageCompressionResult => ({file,compressed: false,diff --git a/apps/web/src/lib/image-compression.worker.ts b/apps/web/src/lib/image-compression.worker.tsnew file mode 100644index 00000000..9aa5b744--- /dev/null+++ b/apps/web/src/lib/image-compression.worker.ts@@ -0,0 +1,31 @@+// This module runs only in a dedicated worker; do not import editor code here.+export {};++self.onmessage = async (event: MessageEvent<{+ file: File;+ maxEdge: number;+ type: string;+ quality: number;+}>) => {+ let bitmap: ImageBitmap | undefined;+ let canvas: OffscreenCanvas | undefined;+ try {+ const { file, maxEdge, type, quality } = event.data;+ bitmap = await createImageBitmap(file);+ const scale = Math.min(1, maxEdge / Math.max(bitmap.width, bitmap.height));+ canvas = new OffscreenCanvas(+ Math.max(1, Math.round(bitmap.width * scale)),+ Math.max(1, Math.round(bitmap.height * scale)),+ );+ const context = canvas.getContext("2d", { alpha: true });+ if (!context) throw new Error("Image canvas is unavailable.");+ context.drawImage(bitmap, 0, 0, canvas.width, canvas.height);+ const blob = await canvas.convertToBlob({ type, quality });+ self.postMessage({ blob });+ } catch (error) {+ self.postMessage({ blob: null, error: error instanceof Error ? error.message : String(error) });+ } finally {+ bitmap?.close();+ if (canvas) canvas.width = canvas.height = 0;+ }+};diff --git a/packages/client/src/index.test.mjs b/packages/client/src/index.test.mjsindex c16b5289..cf9bc60e 100644--- a/packages/client/src/index.test.mjs+++ b/packages/client/src/index.test.mjs@@ -187,7 +187,7 @@ describe("EdgeEver client HTTP contract", () => {test("uploads memo resources as ordered resumable parts", async () => {const calls = [];- const file = new File(["abcdefghij"], "archive.bin", { type: "application/octet-stream" });+ const file = new File(["abcdefghij", new Uint8Array(5 * 1024 * 1024 - 9)], "archive.bin", { type: "application/octet-stream" });const client = createEdgeEverClient({fetch: async (input, init) => {const path = String(input);@@ -196,15 +196,15 @@ describe("EdgeEver client HTTP contract", () => {expect(JSON.parse(init.body)).toEqual({filename: "archive.bin",mimeType: "application/octet-stream",- byteSize: 10,+ byteSize: file.size,});return jsonResponse({upload: {id: "upload_1",resourceId: "res_1",- partSize: 4,+ partSize: 2 * 1024 * 1024,partCount: 3,- byteSize: 10,+ byteSize: file.size,expiresAt: "2026-09-01T00:00:00.000Z",},}, { status: 201 });@@ -227,9 +227,29 @@ describe("EdgeEver client HTTP contract", () => {"/api/v1/resource-uploads/upload_1/parts/3","/api/v1/resource-uploads/upload_1/complete",]);- expect(await calls[1].body.text()).toBe("abcd");- expect(await calls[2].body.text()).toBe("efgh");- expect(await calls[3].body.text()).toBe("ij");+ expect(await calls[1].body.slice(0, 10).text()).toBe("abcdefghij");+ expect(calls.slice(1, 4).map((call) => call.body.size)).toEqual([+ 2 * 1024 * 1024, 2 * 1024 * 1024, 1024 * 1024 + 1,+ ]);+ });++ test("uploads small images in one request and preserves file metadata", async () => {+ const calls = [];+ const client = createEdgeEverClient({+ fetch: async (input, init) => {+ calls.push({ path: String(input), init });+ return jsonResponse({ resource: { id: "image_1" } }, { status: 201 });+ },+ });+ const file = new File(["webp bytes"], "截图.webp", { type: "image/webp" });+ expect((await client.uploadMemoResource("memo/1", file)).resource.id).toBe("image_1");+ expect(calls).toHaveLength(1);+ expect(calls[0].path).toBe("/api/v1/memos/memo%2F1/resources");+ const uploaded = calls[0].init.body.get("file");+ expect(uploaded.name).toBe(file.name);+ expect(uploaded.type).toBe(file.type);+ expect(await uploaded.text()).toBe(await file.text());+ expect(calls[0].init.headers.get("Content-Type")).toBeNull();});test("replaces resource content with a multipart concurrency baseline", async () => {diff --git a/packages/client/src/index.ts b/packages/client/src/index.tsindex 7448ae99..018387e7 100644--- a/packages/client/src/index.ts+++ b/packages/client/src/index.ts@@ -41,6 +41,8 @@ import type {SyncChangesResponse,} from "@edgeever/shared";+const MAX_SINGLE_REQUEST_UPLOAD_BYTES = 5 * 1024 * 1024;+export type EdgeEverClientRequestContext = {path: string;token?: string;@@ -1158,12 +1160,19 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {),uploadMemoResource: (memoId: string, file: Blob | FormData) => {- if (!(file instanceof FormData)) {+ // Small files do not benefit from an upload session's three round trips.+ // Keep large attachments on the bounded-memory, resumable path.+ if (!(file instanceof FormData) && file.size > MAX_SINGLE_REQUEST_UPLOAD_BYTES) {return uploadMemoResourceMultipart(memoId, file);}const form = file instanceof FormData ? file : new FormData();- if (!(file instanceof FormData)) form.append("file", file);- return request<ResourceResponse>(`/api/v1/memos/${memoId}/resources`, {+ if (!(file instanceof FormData)) {+ const filename = "name" in file && typeof file.name === "string" && file.name.trim()+ ? file.name+ : "attachment";+ form.append("file", file, filename);+ }+ return request<ResourceResponse>(`/api/v1/memos/${encodeURIComponent(memoId)}/resources`, {method: "POST",body: form,});diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.tsindex adcc4f7d..544d74ba 100644--- a/packages/shared/src/i18n/en-US.ts+++ b/packages/shared/src/i18n/en-US.ts@@ -1246,6 +1246,7 @@ export const enUS = {fileFailed: "File upload failed",imageCompressing: "Compressing image",imagePreparing: "Processing image",+ waitingToUpload: "Waiting to upload",fileUploading: "Uploading file",},notebookFallback: "Notebook",diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.tsindex 1d7411be..2746e761 100644--- a/packages/shared/src/i18n/zh-CN.ts+++ b/packages/shared/src/i18n/zh-CN.ts@@ -1246,6 +1246,7 @@ export const zhCN = {fileFailed: "文件上传失败",imageCompressing: "图片压缩中",imagePreparing: "正在处理图片",+ waitingToUpload: "等待上传",fileUploading: "文件上传中",},notebookFallback: "笔记本",