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
Move note attachment transcription to direct client processing
tianma-if916b1b35e83a
diff --git a/apps/api/src/ai-routes.test.mjs b/apps/api/src/ai-routes.test.mjsindex 14099540..09ba0699 100644--- a/apps/api/src/ai-routes.test.mjs+++ b/apps/api/src/ai-routes.test.mjs@@ -123,7 +123,7 @@ describe("AI route contracts", () => {expect(JSON.stringify(await saved.json())).not.toContain("secret");const transcript = await app.request(- "/api/v1/memos/missing/resources/missing/transcribe",+ "/api/v1/memos/missing/resources/missing/transcription-target",{ method: "POST" },databaseEnvironment,);@@ -131,7 +131,7 @@ describe("AI route contracts", () => {const scopedApp = createApp({ currentAuth: { ...auth, kind: "agent", scopes: ["read:resources"] } });const denied = await scopedApp.request(- "/api/v1/memos/missing/resources/missing/transcribe",+ "/api/v1/memos/missing/resources/missing/transcription-target",{ method: "POST" },databaseEnvironment,);diff --git a/apps/api/src/ai-routes.ts b/apps/api/src/ai-routes.tsindex 3ea07537..23c4678d 100644--- a/apps/api/src/ai-routes.ts+++ b/apps/api/src/ai-routes.ts@@ -68,7 +68,7 @@ import {} from "./video-outline";import { encryptSecret } from "./secret-encryption";import { listTagSummaries } from "./tag-service";-import { transcribeNoteResource } from "./resource-transcription";+import { prepareNoteResourceTranscription } from "./resource-transcription";type AiRouteDependencies = {isDemoMode: (environment: Bindings) => boolean;@@ -252,21 +252,21 @@ export const registerAiRoutes = (app: Hono<AppEnv>, dependencies: AiRouteDependereturn context.json(await readTranscriptionSettings(context, dependencies));});- app.post("/api/v1/memos/:memoId/resources/:resourceId/transcribe", async (context) => {- const denied = requireScopes(context, "read:resources", "ai:generate");+ app.post("/api/v1/memos/:memoId/resources/:resourceId/transcription-target", async (context) => {+ const denied = requireUser(context);if (denied) return denied;if (dependencies.isDemoMode(context.env)) {return forbidden(context, "Speech transcription is unavailable in demo mode.");}try {- return context.json(await transcribeNoteResource(+ const target = await prepareNoteResourceTranscription(context.env,getWorkspaceId(context),context.req.param("memoId"),context.req.param("resourceId"),- fetch,- context.req.raw.signal,- ));+ );+ context.header("Cache-Control", "no-store");+ return context.json(target);} catch (error) {return withAiError(context, error, "ai_transcription_failed");}diff --git a/apps/api/src/resource-transcription.test.mjs b/apps/api/src/resource-transcription.test.mjsindex cd640e82..b68b0a7a 100644--- a/apps/api/src/resource-transcription.test.mjs+++ b/apps/api/src/resource-transcription.test.mjs@@ -1,14 +1,14 @@import { describe, expect, test } from "bun:test";import { resolvePrimaryAiCredentialEncryptionKey } from "./ai-service.ts";import { encryptSecret } from "./secret-encryption.ts";-import { isTranscribableAttachment, transcribeNoteResource } from "./resource-transcription.ts";+import { isTranscribableAttachment, prepareNoteResourceTranscription } from "./resource-transcription.ts";const makeEnvironment = async (resource) => {const env = {EDGE_EVER_AUTH_PASSWORD: "test-password-long-enough",storage: {resources: {- get: async () => ({ body: new Blob(["audio bytes"]).stream() }),+ get: async () => { throw new Error("The instance must not read media bytes"); },},db: {prepare: (sql) => ({@@ -21,7 +21,6 @@ const makeEnvironment = async (resource) => {base_url: "https://speech.example/v1",api_key_encrypted: await encryptSecret("secret-token", resolvePrimaryAiCredentialEncryptionKey(env)),};- if (sql.includes("FROM object_storage_configs")) return { id: "builtin", provider: "builtin" };return null;},}),@@ -51,25 +50,21 @@ describe("note attachment transcription boundary", () => {expect(isTranscribableAttachment({ ...resource, kind: "image" })).toBe(false);});- test("rejects an attachment from another note before reading it", async () => {+ test("rejects an attachment from another note before returning credentials", async () => {const env = await makeEnvironment(resource);- await expect(transcribeNoteResource(env, "ws_one", "memo_other", "res_one", () => {- throw new Error("Provider must not be called");- })).rejects.toMatchObject({ code: "resource_not_found", status: 404 });+ await expect(prepareNoteResourceTranscription(env, "ws_one", "memo_other", "res_one"))+ .rejects.toMatchObject({ code: "resource_not_found", status: 404 });});- test("sends only the note attachment to the configured model and returns text", async () => {+ test("returns a direct model target without reading or forwarding media", async () => {const env = await makeEnvironment(resource);- const calls = [];- const result = await transcribeNoteResource(env, "ws_one", "memo_one", "res_one", async (url, init) => {- calls.push({ url, init });- return Response.json({ text: " Meeting notes. " });+ const result = await prepareNoteResourceTranscription(env, "ws_one", "memo_one", "res_one");+ expect(result).toEqual({+ baseUrl: "https://speech.example/v1",+ modelId: "whisper-1",+ apiKey: "secret-token",+ resourceId: "res_one",+ filename: "meeting.mp4",});- expect(result).toEqual({ text: "Meeting notes.", resourceId: "res_one", filename: "meeting.mp4" });- expect(calls).toHaveLength(1);- expect(calls[0].url).toBe("https://speech.example/v1/audio/transcriptions");- expect(calls[0].init.headers.Authorization).toBe("Bearer secret-token");- expect(calls[0].init.body.get("model")).toBe("whisper-1");- expect((await calls[0].init.body.get("file").text())).toBe("audio bytes");});});diff --git a/apps/api/src/resource-transcription.ts b/apps/api/src/resource-transcription.tsindex 4e0ee377..1c2bc3a9 100644--- a/apps/api/src/resource-transcription.ts+++ b/apps/api/src/resource-transcription.ts@@ -1,11 +1,8 @@import { AppError } from "./app-error";import { prepareAiTranscriptionCredentials } from "./ai-service";-import { resolveObjectStorage } from "./object-storage";import { getResourceRow } from "./resource-service";import type { Bindings } from "./api-context";-export const MAX_TRANSCRIPTION_BYTES = 24 * 1024 * 1024;-const SUPPORTED_EXTENSIONS = new Set(["flac", "mp3", "mp4", "mpeg", "mpga", "m4a", "ogg", "wav", "webm"]);export const isTranscribableAttachment = (resource: {@@ -20,13 +17,11 @@ export const isTranscribableAttachment = (resource: {return mime.startsWith("audio/") || mime === "video/mp4" || mime === "video/webm";};-export const transcribeNoteResource = async (+export const prepareNoteResourceTranscription = async (env: Bindings,workspaceId: string,memoId: string,resourceId: string,- fetchImpl: typeof fetch = fetch,- abortSignal?: AbortSignal,) => {const resource = await getResourceRow(env.storage.db, workspaceId, resourceId);if (!resource || resource.memo_id !== memoId) {@@ -35,45 +30,19 @@ export const transcribeNoteResource = async (if (!isTranscribableAttachment(resource)) {throw new AppError("unsupported_media_type", "Choose an audio or MP4/WebM video attachment.", 415);}- if (resource.byte_size < 1 || resource.byte_size > MAX_TRANSCRIPTION_BYTES) {- throw new AppError("audio_too_large", "The attachment must be 24 MiB or smaller.", 413);+ if (resource.byte_size < 1) {+ throw new AppError("empty_audio", "The attachment is empty.", 413);}const credentials = await prepareAiTranscriptionCredentials(env.storage.db, workspaceId, env);if (!credentials.enabled) {throw new AppError("ai_transcription_not_configured", "Choose a default speech model first.", 409);}- const source = await resolveObjectStorage(env, resource.storage_config_id);- const object = await source.store.get(resource.object_key);- if (!object) throw new AppError("resource_not_found", "Attachment bytes are unavailable.", 404);- const bytes = await new Response(object.body).arrayBuffer();- if (bytes.byteLength < 1 || bytes.byteLength > MAX_TRANSCRIPTION_BYTES) {- throw new AppError("audio_too_large", "The attachment must be 24 MiB or smaller.", 413);- }-- const body = new FormData();- body.set("model", credentials.modelId);- body.set("file", new File([bytes], resource.filename || "recording.mp3", {- type: resource.mime_type || "application/octet-stream",- }));- let response: Response;- try {- response = await fetchImpl(`${credentials.baseUrl}/audio/transcriptions`, {- method: "POST",- headers: { Authorization: `Bearer ${credentials.apiKey}` },- body,- signal: abortSignal- ? AbortSignal.any([abortSignal, AbortSignal.timeout(180_000)])- : AbortSignal.timeout(180_000),- });- } catch {- throw new AppError("ai_transcription_failed", "The speech service could not be reached.", 502);- }- if (!response.ok) {- throw new AppError("ai_transcription_failed", `The speech service returned HTTP ${response.status}.`, 502);- }- const result = await response.json().catch(() => null) as { text?: unknown } | null;- const text = typeof result?.text === "string" ? result.text.trim() : "";- if (!text) throw new AppError("empty_transcript", "The speech service returned no transcript.", 502);- return { text, resourceId, filename: resource.filename ?? "" };+ return {+ baseUrl: credentials.baseUrl,+ modelId: credentials.modelId,+ apiKey: credentials.apiKey,+ resourceId,+ filename: resource.filename ?? "",+ };};diff --git a/apps/desktop/src/main/ai-direct.mjs b/apps/desktop/src/main/ai-direct.mjsindex 32eeff42..95d10ade 100644--- a/apps/desktop/src/main/ai-direct.mjs+++ b/apps/desktop/src/main/ai-direct.mjs@@ -1,4 +1,5 @@const MAX_BODY_BYTES = 12 * 1024 * 1024;+const MAX_AUDIO_REQUEST_BYTES = 25_000_000;const MAX_CONCURRENT = 2;const blockedHost = (hostname) => {@@ -28,7 +29,15 @@ export const createAiDirectRuntime = ({ fetchImpl = fetch, maxConcurrent = MAX_C}if (!input || typeof input !== "object") throw new Error("Invalid AI provider request.");if ((input.method ?? "POST") !== "POST") throw new Error("AI provider requests must use POST.");- if (typeof input.body !== "string" || Buffer.byteLength(input.body) > MAX_BODY_BYTES) {+ const binaryBody = input.bodyBytes instanceof Uint8Array+ ? input.bodyBytes+ : input.bodyBytes instanceof ArrayBuffer ? new Uint8Array(input.bodyBytes) : null;+ if (input.bodyBytes != null && !binaryBody) {+ throw new Error("Invalid binary AI provider request body.");+ }+ if (binaryBody+ ? binaryBody.byteLength > MAX_AUDIO_REQUEST_BYTES+ : typeof input.body !== "string" || Buffer.byteLength(input.body) > MAX_BODY_BYTES) {throw new Error("AI provider request body is too large.");}const url = validateAiProviderUrl(input.url);@@ -41,6 +50,12 @@ export const createAiDirectRuntime = ({ fetchImpl = fetch, maxConcurrent = MAX_Cheaders[key] = value;}}+ if (binaryBody && (+ !url.pathname.endsWith("/audio/transcriptions")+ || !Object.entries(headers).some(([key, value]) => key.toLowerCase() === "content-type" && /^multipart\/form-data;\s*boundary=/i.test(value))+ )) {+ throw new Error("Binary AI requests must be multipart speech transcriptions.");+ }if (active.size >= maxConcurrent || active.has(requestId)) throw new Error("Too many AI provider requests.");const controller = new AbortController();active.set(requestId, controller);@@ -48,7 +63,7 @@ export const createAiDirectRuntime = ({ fetchImpl = fetch, maxConcurrent = MAX_Cconst response = await fetchImpl(url.href, {method: "POST",headers,- body: input.body,+ body: binaryBody ?? input.body,redirect: "error",signal: controller.signal,});diff --git a/apps/desktop/src/main/ai-direct.test.mjs b/apps/desktop/src/main/ai-direct.test.mjsindex 74ecb984..842c9f6b 100644--- a/apps/desktop/src/main/ai-direct.test.mjs+++ b/apps/desktop/src/main/ai-direct.test.mjs@@ -45,6 +45,47 @@ test("desktop AI provider transport rejects private hosts and GET", async () =>}, { onData() {}, onEnd() {}, onError() {} })).rejects.toThrow(/POST/);});+test("desktop AI transport sends multipart audio bytes directly to the speech provider", async () => {+ let received;+ const runtime = createAiDirectRuntime({+ fetchImpl: async (url, init) => {+ received = { url, body: init.body, headers: init.headers };+ return Response.json({ text: "recognized" });+ },+ });+ const form = new FormData();+ form.set("model", "whisper-1");+ form.set("file", new File(["audio bytes"], "clip.mp3", { type: "audio/mpeg" }));+ const request = new Request("https://speech.example/v1/audio/transcriptions", { method: "POST", body: form });+ const headers = Object.fromEntries(request.headers);+ const bodyBytes = new Uint8Array(await request.arrayBuffer());+ const result = await new Promise((resolve, reject) => {+ let text = "";+ runtime.open("speech-12345", {+ url: request.url,+ method: "POST",+ headers,+ body: "",+ bodyBytes,+ }, {+ onData: (bytes) => { text += new TextDecoder().decode(bytes); },+ onEnd: () => resolve(text),+ onError: reject,+ }).catch(reject);+ });+ expect(received.url).toBe("https://speech.example/v1/audio/transcriptions");+ expect(received.body).toBeInstanceOf(Uint8Array);+ expect(received.headers["content-type"]).toMatch(/^multipart\/form-data; boundary=/);+ expect(JSON.parse(result).text).toBe("recognized");+ await expect(runtime.open("speech-invalid", {+ url: "https://speech.example/v1/chat/completions",+ method: "POST",+ headers,+ body: "",+ bodyBytes: new Uint8Array([1]),+ }, { onData() {}, onEnd() {}, onError() {} })).rejects.toThrow(/multipart speech/);+});+test("desktop preload and main process expose the AI provider stream pair", async () => {const [main, preload] = await Promise.all([Bun.file(new URL("./index.mjs", import.meta.url)).text(),diff --git a/apps/web/package.json b/apps/web/package.jsonindex d007b26f..40216f64 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -31,6 +31,7 @@"html-to-image": "^1.11.13","lowlight": "^3.3.0","lucide-react": "1.21.0",+ "mediabunny": "^1.61.3","mermaid": "^11.16.0","motion": "^12.43.0","nanoid": "^6.0.1",diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsxindex 06ac7ccf..3938137d 100644--- a/apps/web/src/components/EditorPane.tsx+++ b/apps/web/src/components/EditorPane.tsx@@ -503,6 +503,7 @@ const RichEditorPane = ({filename: string;text: string;loading: boolean;+ completedSegments: number;error: string | null;} | null>(null);const attachmentTranscriptAbortRef = useRef<AbortController | null>(null);@@ -3136,9 +3137,15 @@ const RichEditorPane = ({const controller = new AbortController();attachmentTranscriptAbortRef.current = controller;hideResourceMenu();- setAttachmentTranscript({ memoId: currentMemoId, filename: target.filename, text: "", loading: true, error: null });+ setAttachmentTranscript({ memoId: currentMemoId, filename: target.filename, text: "", loading: true, completedSegments: 0, error: null });try {- const result = await api.transcribeNoteResource(currentMemoId, target.resourceId, controller.signal);+ const { transcribeNoteResource } = await import("@/lib/transcribe-note-resource");+ const result = await transcribeNoteResource(currentMemoId, target.resourceId, controller.signal, (completedSegments) => {+ if (attachmentTranscriptAbortRef.current !== controller) return;+ setAttachmentTranscript((current) => current?.memoId === currentMemoId && current.filename === target.filename+ ? { ...current, completedSegments }+ : current);+ });if (attachmentTranscriptAbortRef.current !== controller) return;setAttachmentTranscript((current) => current?.memoId === currentMemoId && current.filename === target.filename? { ...current, text: result.text, loading: false }@@ -4412,6 +4419,7 @@ const RichEditorPane = ({filename={attachmentTranscript?.filename ?? ""}text={attachmentTranscript?.text ?? ""}loading={attachmentTranscript?.loading ?? false}+ completedSegments={attachmentTranscript?.completedSegments ?? 0}error={attachmentTranscript?.error ?? null}canInsert={Boolean(editor && editor.isEditable && !effectiveReadOnly && !useMarkdownSourceEditor && !useMobilePlainTextEditor)}onOpenChange={(open) => {diff --git a/apps/web/src/components/dialogs/AttachmentTranscriptDialog.tsx b/apps/web/src/components/dialogs/AttachmentTranscriptDialog.tsxindex 238c6906..d25a3608 100644--- a/apps/web/src/components/dialogs/AttachmentTranscriptDialog.tsx+++ b/apps/web/src/components/dialogs/AttachmentTranscriptDialog.tsx@@ -8,6 +8,7 @@ export const AttachmentTranscriptDialog = ({filename,text,loading,+ completedSegments,error,canInsert,onOpenChange,@@ -17,6 +18,7 @@ export const AttachmentTranscriptDialog = ({filename: string;text: string;loading: boolean;+ completedSegments: number;error: string | null;canInsert: boolean;onOpenChange: (open: boolean) => void;@@ -31,7 +33,9 @@ export const AttachmentTranscriptDialog = ({<DialogTitle>{t("speechTranscription.resultTitle")}</DialogTitle></DialogHeader><p className="break-all text-xs text-slate-500">{filename}</p>- {loading ? <p className="text-sm" role="status">{t("speechTranscription.recognizing")}</p> : null}+ {loading ? <p className="text-sm" role="status">{completedSegments > 0+ ? t("speechTranscription.recognizingProgress", { count: completedSegments })+ : t("speechTranscription.recognizing")}</p> : null}{error ? <p className="text-sm text-rose-600" role="alert">{error}</p> : null}{text ? (<>diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex 5f5487be..4dcb9571 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -247,9 +247,16 @@ const desktopProviderFetch: typeof fetch = async (input, init) => {new Headers(init?.headers).forEach((value, key) => {headers[key] = value;});+ let bodyBytes: Uint8Array | undefined;+ if (init?.body instanceof FormData) {+ const multipart = new Request(url, { method: init.method ?? "POST", headers, body: init.body });+ multipart.headers.forEach((value, key) => { headers[key] = value; });+ bodyBytes = new Uint8Array(await multipart.arrayBuffer());+ }const requestId = crypto.randomUUID();const pending: Array<{ type: "data" | "end" | "error"; bytes?: ArrayBuffer | Uint8Array; message?: string }> = [];let streamController: ReadableStreamDefaultController<Uint8Array> | null = null;+ let cleanup = () => {};const stop = bridge.onAiProviderStreamChunk((id, chunk) => {if (id !== requestId) return;if (!streamController) {@@ -257,12 +264,19 @@ const desktopProviderFetch: typeof fetch = async (input, init) => {return;}if (chunk.type === "data") streamController.enqueue(toUint8Array(chunk.bytes));- else if (chunk.type === "end") streamController.close();- else streamController.error(new Error(chunk.message || "AI provider request failed."));+ else {+ if (chunk.type === "end") streamController.close();+ else streamController.error(new Error(chunk.message || "AI provider request failed."));+ cleanup();+ }});const abort = () => {bridge.cancelAiProviderStream(requestId);+ cleanup();+ };+ cleanup = () => {stop();+ init?.signal?.removeEventListener("abort", abort);};init?.signal?.addEventListener("abort", abort, { once: true });try {@@ -271,14 +285,19 @@ const desktopProviderFetch: typeof fetch = async (input, init) => {method: init?.method,headers,body: typeof init?.body === "string" ? init.body : "",+ ...(bodyBytes ? { bodyBytes } : {}),});const body = new ReadableStream<Uint8Array>({start(controller) {streamController = controller;for (const chunk of pending) {if (chunk.type === "data") controller.enqueue(toUint8Array(chunk.bytes));- else if (chunk.type === "end") controller.close();- else controller.error(new Error(chunk.message || "AI provider request failed."));+ else {+ if (chunk.type === "end") controller.close();+ else controller.error(new Error(chunk.message || "AI provider request failed."));+ cleanup();+ break;+ }}pending.length = 0;},@@ -288,7 +307,7 @@ const desktopProviderFetch: typeof fetch = async (input, init) => {});return new Response(body, { status: opened.status, headers: opened.headers });} catch (error) {- stop();+ cleanup();throw error;}};@@ -298,6 +317,10 @@ const desktopAiDirectEnabled = Boolean(|| (typeof window !== "undefined" && window.edgeeverDesktop?.openAiProviderStream),);+/** Direct client-to-provider transport. Browser CORS failures are surfaced to the caller. */+export const directProviderFetch: typeof fetch = (input, init) =>+ desktopAiDirectEnabled ? desktopProviderFetch(input, init) : fetch(input, init);+const client = createEdgeEverClient({baseUrl: getConfiguredDesktopApiBaseUrl,token: getDesktopSessionToken,diff --git a/apps/web/src/lib/fixtures/transcription-audio.mp3 b/apps/web/src/lib/fixtures/transcription-audio.mp3new file mode 100644index 00000000..dd731bdeBinary files /dev/null and b/apps/web/src/lib/fixtures/transcription-audio.mp3 differdiff --git a/apps/web/src/lib/fixtures/transcription-video.mp4 b/apps/web/src/lib/fixtures/transcription-video.mp4new file mode 100644index 00000000..4b2b84b5Binary files /dev/null and b/apps/web/src/lib/fixtures/transcription-video.mp4 differdiff --git a/apps/web/src/lib/fixtures/transcription-video.webm b/apps/web/src/lib/fixtures/transcription-video.webmnew file mode 100644index 00000000..bf5484cfBinary files /dev/null and b/apps/web/src/lib/fixtures/transcription-video.webm differdiff --git a/apps/web/src/lib/plugins/plugin-host.ts b/apps/web/src/lib/plugins/plugin-host.tsindex 2fab93ee..9c2b01d3 100644--- a/apps/web/src/lib/plugins/plugin-host.ts+++ b/apps/web/src/lib/plugins/plugin-host.ts@@ -1086,7 +1086,8 @@ export class EdgeEverPluginHost {assertPermission(manifest, 'ai:generate');assertPermission(manifest, 'resources:read');lifetime.signal.throwIfAborted();- const result = await api.transcribeNoteResource(noteId, resourceId, lifetime.signal);+ const { transcribeNoteResource } = await import("@/lib/transcribe-note-resource");+ const result = await transcribeNoteResource(noteId, resourceId, lifetime.signal);lifetime.signal.throwIfAborted();return result;},diff --git a/apps/web/src/lib/transcribe-note-resource.test.mjs b/apps/web/src/lib/transcribe-note-resource.test.mjsnew file mode 100644index 00000000..3f7d4934--- /dev/null+++ b/apps/web/src/lib/transcribe-note-resource.test.mjs@@ -0,0 +1,83 @@+import { describe, expect, test } from "bun:test";+import { readFile } from "node:fs/promises";+import { fileURLToPath } from "node:url";+import { ALL_FORMATS, BufferSource, Input } from "mediabunny";+import { extractAudioParts, transcribePreparedAudioParts } from "./transcribe-note-resource.ts";++const fixturePath = fileURLToPath(new URL("./fixtures/transcription-video.mp4", import.meta.url));++describe("client-side note media preparation", () => {+ test("extracts audio from video and produces independently readable segments", async () => {+ const video = new Uint8Array(await readFile(fixturePath));+ const ranges = [];+ const parts = [];+ for await (const part of extractAudioParts(+ video.byteLength,+ async (start, end) => {+ ranges.push([start, end]);+ return video.slice(start, end);+ },+ undefined,+ { maxChunkSeconds: 0.7 },+ )) parts.push(part);++ expect(ranges.length).toBeGreaterThan(0);+ expect(parts.length).toBeGreaterThan(1);+ for (const part of parts) {+ expect(part.type).toStartWith("audio/");+ expect(part.size).toBeLessThan(video.byteLength);+ const input = new Input({ formats: ALL_FORMATS, source: new BufferSource(await part.arrayBuffer()) });+ expect(await input.canRead()).toBe(true);+ expect(await input.getPrimaryAudioTrack()).not.toBeNull();+ expect(await input.getPrimaryVideoTrack()).toBeNull();+ input.dispose();+ }+ });++ test.each([+ ["transcription-audio.mp3", "audio/mpeg"],+ ["transcription-video.webm", "audio/webm"],+ ])("handles %s without sending video frames", async (name, expectedMime) => {+ const bytes = new Uint8Array(await readFile(fileURLToPath(new URL(`./fixtures/${name}`, import.meta.url))));+ const parts = [];+ for await (const part of extractAudioParts(bytes.byteLength, async (start, end) => bytes.slice(start, end))) {+ parts.push(part);+ }+ expect(parts).toHaveLength(1);+ expect(parts[0].type).toBe(expectedMime);+ const input = new Input({ formats: ALL_FORMATS, source: new BufferSource(await parts[0].arrayBuffer()) });+ expect(await input.getPrimaryAudioTrack()).not.toBeNull();+ expect(await input.getPrimaryVideoTrack()).toBeNull();+ input.dispose();+ });++ test("sends each prepared segment directly to the configured speech endpoint", async () => {+ const requests = [];+ const completed = [];+ async function* parts() {+ yield new File(["first"], "first.mp3", { type: "audio/mpeg" });+ yield new File(["second"], "second.mp3", { type: "audio/mpeg" });+ }+ const text = await transcribePreparedAudioParts(+ { baseUrl: "https://speech.example/v1", modelId: "whisper-1", apiKey: "secret" },+ parts(),+ async (url, init) => {+ requests.push({ url, init });+ return Response.json({ text: `segment ${requests.length}` });+ },+ undefined,+ (count) => completed.push(count),+ );+ expect(text).toBe("segment 1\n\nsegment 2");+ expect(completed).toEqual([1, 2]);+ expect(requests.map(({ url }) => url)).toEqual([+ "https://speech.example/v1/audio/transcriptions",+ "https://speech.example/v1/audio/transcriptions",+ ]);+ for (const { init } of requests) {+ expect(init.headers.Authorization).toBe("Bearer secret");+ expect(init.body.get("model")).toBe("whisper-1");+ expect(init.body.get("file")).toBeInstanceOf(File);+ }+ });+});diff --git a/apps/web/src/lib/transcribe-note-resource.ts b/apps/web/src/lib/transcribe-note-resource.tsnew file mode 100644index 00000000..99c4ff88--- /dev/null+++ b/apps/web/src/lib/transcribe-note-resource.ts@@ -0,0 +1,210 @@+import {+ ALL_FORMATS,+ BufferTarget,+ CustomSource,+ EncodedAudioPacketSource,+ EncodedPacket,+ EncodedPacketSink,+ FlacOutputFormat,+ Input,+ Mp3OutputFormat,+ Mp4OutputFormat,+ Output,+ WavOutputFormat,+ WebMOutputFormat,+ type AudioCodec,+ type OutputFormat,+} from "mediabunny";+import { api, directProviderFetch } from "./api";++const MAX_SOURCE_BYTES = 1024 * 1024 * 1024;+const MAX_PROVIDER_FILE_BYTES = 24_000_000;+const MAX_CHUNK_PAYLOAD_BYTES = 20_000_000;+const MAX_CHUNK_SECONDS = 600;+const MAX_CHUNKS = 64;++const formatForCodec = (codec: AudioCodec): OutputFormat | null => {+ const format: OutputFormat | null = codec === "aac" ? new Mp4OutputFormat()+ : codec === "mp3" ? new Mp3OutputFormat()+ : codec === "opus" || codec === "vorbis" ? new WebMOutputFormat()+ : codec === "flac" ? new FlacOutputFormat()+ : codec.startsWith("pcm-") ? new WavOutputFormat()+ : null;+ return format?.getSupportedAudioCodecs().includes(codec) ? format : null;+};++const audioFileInfo = (format: OutputFormat) => {+ if (format instanceof Mp4OutputFormat) return { extension: ".m4a", mimeType: "audio/mp4" };+ if (format instanceof WebMOutputFormat) return { extension: ".webm", mimeType: "audio/webm" };+ return { extension: format.fileExtension, mimeType: format.mimeType };+};++const attachmentPath = (resourceId: string) => `/api/v1/resources/${encodeURIComponent(resourceId)}/blob`;++export async function* extractAudioParts(+ size: number,+ readRange: (start: number, end: number) => Promise<Uint8Array>,+ signal?: AbortSignal,+ limits: { maxChunkPayloadBytes?: number; maxChunkSeconds?: number } = {},+): AsyncGenerator<File> {+ if (!Number.isSafeInteger(size) || size < 1 || size > MAX_SOURCE_BYTES) {+ throw new Error("The attachment is unavailable or exceeds the 1 GiB upload limit.");+ }+ const input = new Input({+ formats: ALL_FORMATS,+ source: new CustomSource({+ getSize: () => size,+ maxCacheSize: 4 * 1024 * 1024,+ prefetchProfile: "network",+ read: async (start, end) => {+ signal?.throwIfAborted();+ const bytes = await readRange(start, end);+ if (bytes.byteLength !== end - start) throw new Error("The attachment read was incomplete.");+ return bytes;+ },+ }),+ });++ try {+ if (!await input.canRead()) throw new Error("This audio or video format cannot be read on this device.");+ const track = await input.getPrimaryAudioTrack();+ const codec = await track?.getCodec();+ const decoderConfig = await track?.getDecoderConfig();+ if (!track || !codec || !decoderConfig) throw new Error("The attachment has no supported audio track.");+ const format = formatForCodec(codec);+ if (!format) throw new Error("The attachment's audio codec cannot be sent to the speech service.");+ const fileInfo = audioFileInfo(format);++ let output: Output<OutputFormat, BufferTarget> | null = null;+ let source: EncodedAudioPacketSource | null = null;+ let chunkStart = 0;+ let payloadBytes = 0;+ let chunkCount = 0;++ const startChunk = async (timestamp: number) => {+ output = new Output({ format, target: new BufferTarget() });+ source = new EncodedAudioPacketSource(codec);+ output.addAudioTrack(source);+ await output.start();+ chunkStart = timestamp;+ payloadBytes = 0;+ };+ const finishChunk = async (): Promise<File> => {+ if (!output) throw new Error("No audio segment to finish.");+ await output.finalize();+ const buffer = output.target.buffer;+ if (!buffer || !buffer.byteLength || buffer.byteLength > MAX_PROVIDER_FILE_BYTES) {+ throw new Error("An audio segment exceeds the speech service's file limit.");+ }+ chunkCount += 1;+ if (chunkCount > MAX_CHUNKS) throw new Error(`The recording exceeds the ${MAX_CHUNKS}-segment transcription limit.`);+ return new File([buffer], `transcription-${chunkCount}${fileInfo.extension}`, { type: fileInfo.mimeType });+ };++ for await (const packet of new EncodedPacketSink(track).packets()) {+ signal?.throwIfAborted();+ if (!output) await startChunk(packet.timestamp);+ if (payloadBytes > 0 && (+ payloadBytes + packet.byteLength > (limits.maxChunkPayloadBytes ?? MAX_CHUNK_PAYLOAD_BYTES)+ || packet.timestamp - chunkStart >= (limits.maxChunkSeconds ?? MAX_CHUNK_SECONDS)+ )) {+ yield await finishChunk();+ await startChunk(packet.timestamp);+ }+ if (packet.byteLength > (limits.maxChunkPayloadBytes ?? MAX_CHUNK_PAYLOAD_BYTES)) {+ throw new Error("An audio packet exceeds the speech service's file limit.");+ }+ const relativePacket = new EncodedPacket(+ packet.data,+ packet.type,+ Math.max(0, packet.timestamp - chunkStart),+ packet.duration,+ packet.sequenceNumber,+ packet.byteLength,+ packet.sideData,+ );+ await source!.add(relativePacket, payloadBytes === 0 ? { decoderConfig } : undefined);+ payloadBytes += packet.byteLength;+ }+ if (!output) throw new Error("The attachment contains no audio data.");+ yield await finishChunk();+ } finally {+ input.dispose();+ }+}++export async function transcribeNoteResource(+ memoId: string,+ resourceId: string,+ signal?: AbortSignal,+ onProgress?: (completedSegments: number) => void,+): Promise<{ text: string; resourceId: string; filename: string }> {+ const target = await api.prepareNoteResourceTranscription(memoId, resourceId, signal);+ const path = attachmentPath(resourceId);+ const probe = await api.getResourceResponse(path, { headers: { Range: "bytes=0-0" }, signal });+ const match = /^bytes 0-0\/(\d+)$/.exec(probe.headers.get("Content-Range") ?? "");+ await probe.body?.cancel();+ const size = Number(match?.[1]);+ if (probe.status !== 206 || !Number.isSafeInteger(size) || size < 1 || size > MAX_SOURCE_BYTES) {+ throw new Error("The attachment is unavailable or exceeds the 1 GiB upload limit.");+ }+ const readRange = async (start: number, end: number) => {+ const response = await api.getResourceResponse(path, {+ headers: { Range: `bytes=${start}-${end - 1}` },+ signal,+ });+ if (response.status !== 206) {+ await response.body?.cancel();+ throw new Error("The attachment server did not return the requested byte range.");+ }+ return new Uint8Array(await response.arrayBuffer());+ };+ const text = await transcribePreparedAudioParts(+ target,+ extractAudioParts(size, readRange, signal),+ directProviderFetch,+ signal,+ onProgress,+ );+ return { text, resourceId, filename: target.filename };+}++export async function transcribePreparedAudioParts(+ target: { baseUrl: string; modelId: string; apiKey: string },+ parts: AsyncIterable<File>,+ providerFetch: typeof fetch,+ signal?: AbortSignal,+ onProgress?: (completedSegments: number) => void,+): Promise<string> {+ const transcripts: string[] = [];+ for await (const file of parts) {+ signal?.throwIfAborted();+ const form = new FormData();+ form.set("model", target.modelId);+ form.set("file", file);+ let response: Response;+ try {+ response = await providerFetch(`${target.baseUrl}/audio/transcriptions`, {+ method: "POST",+ headers: { Authorization: `Bearer ${target.apiKey}` },+ body: form,+ redirect: "error",+ signal: signal+ ? AbortSignal.any([signal, AbortSignal.timeout(180_000)])+ : AbortSignal.timeout(180_000),+ });+ } catch {+ if (signal?.aborted) signal.throwIfAborted();+ throw new Error(typeof window !== "undefined" && window.edgeeverDesktop?.isAvailable+ ? "Could not reach the speech provider directly. Check the provider URL and network connection."+ : "Could not reach the speech provider directly. Check its browser CORS policy or network connection.");+ }+ if (!response.ok) throw new Error(`The speech provider returned HTTP ${response.status}.`);+ const result = await response.json().catch(() => null) as { text?: unknown } | null;+ const text = typeof result?.text === "string" ? result.text.trim() : "";+ if (!text) throw new Error("The speech provider returned no transcript.");+ transcripts.push(text);+ onProgress?.(transcripts.length);+ }+ return transcripts.join("\n\n");+}diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.tsindex 167b9093..7d3e3c08 100644--- a/apps/web/src/vite-env.d.ts+++ b/apps/web/src/vite-env.d.ts@@ -33,6 +33,7 @@ interface EdgeEverDesktopBridge {method?: string;headers?: Record<string, string>;body: string;+ bodyBytes?: Uint8Array;}): Promise<{ status: number; headers: Record<string, string> }>;cancelAiProviderStream(requestId: string): void;onAiProviderStreamChunk(callback: (requestId: string, chunk: {diff --git a/bun.lock b/bun.lockindex f07094f8..667f8a10 100644--- a/bun.lock+++ b/bun.lock@@ -252,6 +252,7 @@"html-to-image": "^1.11.13","lowlight": "^3.3.0","lucide-react": "1.21.0",+ "mediabunny": "^1.61.3","mermaid": "^11.16.0","motion": "^12.43.0","nanoid": "^6.0.1",@@ -1580,6 +1581,10 @@"@types/debug": ["@types/[email protected]", "", { "dependencies": { "@types/ms": "*" } }, "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw=="],+ "@types/dom-mediacapture-transform": ["@types/[email protected]", "", { "dependencies": { "@types/dom-webcodecs": "*" } }, "sha512-d7/QsLRwF864A5mgIM/YrfiglHoYn7zgCcAoJgW404r+2DwnNr7EBbLnCWpmOMgH8y0te73L1AV6H1bmauaWFw=="],++ "@types/dom-webcodecs": ["@types/[email protected]", "", {}, "sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ=="],+"@types/estree": ["@types/[email protected]", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="],"@types/estree-jsx": ["@types/[email protected]", "", { "dependencies": { "@types/estree": "*" } }, "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg=="],@@ -3120,6 +3125,8 @@"measury": ["[email protected]", "", {}, "sha512-YS9nhEbFECQzM9V7kyYylASFwpMyajeRvVnpmfRnhZZwbl9AfpBW+C/o7YwmIQLjK8XFzPHt0OGR7GwqoDuWjA=="],+ "mediabunny": ["[email protected]", "", { "dependencies": { "@types/dom-mediacapture-transform": "^0.1.11", "@types/dom-webcodecs": "0.1.13" } }, "sha512-kUqLKVXQVwHR62GkOJxYosAmXERJbqnXBgJDTtRlxHEYviVkMg/Evhl9XN6kedqS5LP1tV4kFKyzY/V4a4ofow=="],+"memoize-one": ["[email protected]", "", {}, "sha512-zYiwtZUcYyXKo/np96AGZAckk+FWWsUdJ3cHGGmld7+AhvcWmQyGCYUh1hc4Q/pkOhb65dQR/pqCyK0cOaHz4Q=="],"merge-options": ["[email protected]", "", { "dependencies": { "is-plain-obj": "^2.1.0" } }, "sha512-2Sug1+knBjkaMsMgf1ctR1Ujx+Ayku4EdJN4Z+C2+JzoeF7A3OZ9KM2GY0CpQS51NR61LTurMJrRKPhSs3ZRTQ=="],diff --git a/docs/plugin-development.md b/docs/plugin-development.mdindex 03335adf..05563c88 100644--- a/docs/plugin-development.md+++ b/docs/plugin-development.md@@ -604,7 +604,7 @@ const transcript = await context.ai.transcribeResource(noteId, resourceId);`system` is limited to 8,000 characters and `prompt` to 90,000. `maxOutputTokens` must be a positive integer and defaults to 3,000 when omitted; the host does not impose a maximum output-token value. Generation is limited to 120 seconds. The model or provider may impose its own limit or reject a request based on available credits. The backend requires an interactive user session, disables AI in public demo mode, and redacts provider errors. AI calls have a four-request per-workspace guard in each backend instance; this is not a distributed quota. Model charges follow the configured provider. Plugin deactivation aborts outstanding calls.-`transcribeResource` accepts only audio or video attachments already uploaded to a note in the current workspace, up to 24 MiB. The instance reads the attachment and sends it to the user's configured speech model service. The plugin receives text and decides how to display or save it. This API does not resolve URLs, download third-party media, or expose speech model credentials to plugins.+`transcribeResource` accepts only audio or video attachments already uploaded to a note in the current workspace. The client reads the attachment in ranges through the existing resource API, extracts its audio track, and splits it into audio segments of at most 24 MB, then sends them directly to the user's configured speech model service. The instance validates attachment ownership and gives the signed-in client the model configuration; it does not extract or convert audio or relay provider requests. Browser calls require provider CORS support; the desktop main process calls the provider locally. The plugin receives text and decides how to display or save it. This API does not resolve URLs, download third-party media, or expose speech model credentials to plugins.The default `network.fetch(url, init)` transport is a trusted browser request. It accepts arbitrary HTTP/HTTPS destinations, methods, bodies, request headers such as `Authorization`, and the requested browser credential mode. It remains subject to the runtime browser's CORS and cookie policy. `networkHosts` is legacy descriptive metadata and is not a security boundary. To read a cross-origin public feed or API without credentials, explicitly select `transport: "public"`; listing `network` and `network:public` remains useful disclosure but is optional.diff --git a/docs/plugin-development.zh-CN.md b/docs/plugin-development.zh-CN.mdindex f9eff901..ff7f73f1 100644--- a/docs/plugin-development.zh-CN.md+++ b/docs/plugin-development.zh-CN.md@@ -604,7 +604,7 @@ const transcript = await context.ai.transcribeResource(noteId, resourceId);`system` 最多 8,000 字符,`prompt` 最多 90,000 字符。`maxOutputTokens` 必须是正整数,省略时默认 3,000;宿主不设置输出 token 的最大值。生成最长 120 秒。模型或供应商可能有自己的限制,也可能因可用额度不足拒绝请求。后端要求交互式用户会话,公开演示模式禁用 AI,供应商错误脱敏。每个后端实例对每工作区的 AI 调用设置四路并发保护,不是分布式配额。模型费用沿用已配置供应商的计费;停用插件会中止其调用。-`transcribeResource` 仅识别当前工作区笔记中已上传、大小不超过 24 MiB 的音视频附件;实例读取附件并发送给用户配置的语音模型服务。插件拿到文本后自行决定如何展示或写入笔记。它不解析 URL、不下载第三方媒体,也不向插件返回语音模型密钥。+`transcribeResource` 仅识别当前工作区笔记中已上传的音视频附件;客户端经原有资源接口分段读取附件、提取音轨并切成不超过 24 MB 的音频片段,直接发送到用户配置的语音模型服务。实例校验附件归属并把模型配置交给已登录客户端,不提取或转换音轨,也不转发模型请求。浏览器直连要求模型服务支持跨域请求;桌面端从本机主进程直连。插件拿到文本后自行决定如何展示或写入笔记。它不解析 URL、不下载第三方媒体,也不向插件返回语音模型密钥。默认的 `network.fetch(url, init)` 是受信任的浏览器请求,可以访问任意 HTTP/HTTPS 地址,使用任意方法、正文、`Authorization` 等请求头以及调用方指定的浏览器凭据模式;它仍受所在运行时的 CORS 与 Cookie 策略约束。`networkHosts` 仅为兼容旧版保留,不是安全边界。需要无凭据读取跨域公开订阅或 API 时,显式选择 `transport: "public"` 即可;列出 `network` 和 `network:public` 仍有助于披露用途,但不是必需条件:diff --git a/docs/video-clip-spec.md b/docs/video-clip-spec.mdindex ebc3d3ab..68a05855 100644--- a/docs/video-clip-spec.md+++ b/docs/video-clip-spec.md@@ -6,7 +6,7 @@ Supported pages are ordinary YouTube videos and Shorts, and ordinary Bilibili vi## Speech transcription for note attachments-Users can explicitly transcribe an audio or MP4/WebM video attachment already uploaded to a note. A workspace configures an OpenAI-compatible speech provider and default model. The API accepts only a note ID and an attachment ID belonging to that note; it does not accept a media URL. Attachments are limited to 24 MiB, and provider credentials remain encrypted on the instance. The EdgeEver instance reads the attachment and sends it to the configured `/audio/transcriptions` service. The result is shown for copying or insertion into the current note. Plugins can use the same capability through `context.ai.transcribeResource(noteId, resourceId)`.+Users can explicitly transcribe an audio or MP4/WebM video attachment already uploaded to a note. A workspace configures an OpenAI-compatible speech provider and default model. The API accepts only a note ID and an attachment ID belonging to that note; it does not accept a media URL. The instance validates attachment ownership and gives the signed-in client the current speech model URL, name, and credential; the credential is encrypted at rest on the instance. The web/desktop client reads the attachment in ranges through the existing resource API, extracts its audio track locally, and splits it by size or duration. The client sends each audio segment of at most 24 MB directly to the configured `/audio/transcriptions` service. The instance serves the original attachment bytes but does not extract or convert audio or relay provider requests. Browser calls require the provider to support cross-origin requests and put the credential in the current browser session; the desktop main process calls the provider locally. The result is shown for copying or insertion into the current note. Plugins can use the same client-side capability through `context.ai.transcribeResource(noteId, resourceId)` but do not receive provider credentials. Attachments remain subject to the normal upload limit; unreadable formats or audio tracks return an error.## Withdrawn external media retrieval design: technical notes@@ -22,7 +22,7 @@ The following records an unreleased external media retrieval design for possible- The proposed design checked an HTTPS source against a platform allowlist, then used yt-dlp locally to select only the best audio track, without saving video. It limited known duration to roughly 30 minutes, audio to roughly 24 MiB, and both download and transcription time. Temporary audio was deleted after the job. Resource limits do not grant copyright permission.- The standalone yt-dlp executable came from its releases and was checked against SHA-256; the desktop client checked for updates in the background. Optional `--cookies-from-browser` reused a local browser session, with the browser choice stored only on that device. This widened the range of accessible media; local execution did not establish permission from a platform or rights holder.-- The old design let an authenticated desktop client obtain speech credentials and send audio directly to the chosen OpenAI-compatible `/audio/transcriptions` endpoint. Current attachment transcription sends media from the EdgeEver instance, so the old claim that audio bypasses the note server no longer applies.+- The old design let an authenticated desktop client obtain speech credentials and send audio directly to the chosen OpenAI-compatible `/audio/transcriptions` endpoint. Current attachment transcription also calls the provider directly from the client, but accepts only uploaded attachments belonging to the current note; it does not revive external media retrieval or the old job mechanism.- Segments with timestamps became transcript links back to the source; a plain-text-only response became a text block. Failures recorded error codes without writing API tokens to diagnostics.Any future revival should first establish content rights, platform terms, target markets, and the transcription provider's data handling, then redesign the entry point and verification scope. The retrieval path above should not simply be re-enabled.diff --git a/docs/video-clip-spec.zh-CN.md b/docs/video-clip-spec.zh-CN.mdindex ed086904..41fb07b9 100644--- a/docs/video-clip-spec.zh-CN.md+++ b/docs/video-clip-spec.zh-CN.md@@ -6,7 +6,7 @@## 笔记附件语音识别-用户可以在已上传到笔记的音频或 MP4/WebM 视频附件上主动选择「转录」。工作区配置 OpenAI 兼容语音模型和默认模型;API 仅接受笔记 ID 与归属该笔记的附件 ID,不接受媒体 URL。支持的附件不超过 24 MiB,模型凭据由实例加密保存。附件由 EdgeEver 实例读取并发送到用户配置的 `/audio/transcriptions` 服务;识别文本先展示给用户,可复制或插入当前笔记。插件可通过 `context.ai.transcribeResource(noteId, resourceId)` 调用同一能力。+用户可以在已上传到笔记的音频或 MP4/WebM 视频附件上主动选择「转录」。工作区配置 OpenAI 兼容语音模型和默认模型;API 仅接受笔记 ID 与归属该笔记的附件 ID,不接受媒体 URL。实例校验附件归属,并把当前语音模型地址、名称及凭据交给已登录客户端;凭据在实例上加密保存。Web/桌面客户端经原有资源接口分段读取附件,在本机提取音轨并按大小或时长切段,由客户端把每段不超过 24 MB 的音频直接发送到用户配置的 `/audio/transcriptions` 服务。实例只提供原有附件字节,不提取或转换音轨,也不转发模型请求。Web 浏览器中的直连要求模型服务支持跨域请求,并会使模型凭据进入当前浏览器会话;桌面端由本机主进程直接请求模型服务。识别文本先展示给用户,可复制或插入当前笔记。插件可通过 `context.ai.transcribeResource(noteId, resourceId)` 调用同一客户端能力,但不会拿到模型凭据。附件仍受普通上传上限约束;无法读取的媒体格式或音轨会明确报错。## 已撤回的外部媒体抓取方案:技术备忘@@ -22,7 +22,7 @@- 原方案按平台白名单验证 HTTPS 来源,在本机调用 yt-dlp 只选最优音轨,不保存视频;限制已知时长约 30 分钟、音频约 24 MiB、下载和识别超时。任务结束后清理临时音频。大小和时长限制只减少资源占用,不构成版权授权。- yt-dlp 独立可执行文件从其发布页取得,并核对 SHA-256;桌面端后台检查版本。可选的 `--cookies-from-browser` 会复用本机浏览器登录状态,浏览器选择仅存在本机。这会扩大可获取的媒体范围,因此不能把「本地执行」等同于获得平台或权利人许可。-- 原方案让已登录桌面端领取语音模型凭据,并把音频直接发送到用户配置的 OpenAI 兼容 `/audio/transcriptions` 接口。当前附件转录改由实例发送媒体,不能沿用原方案中「音频不经过笔记服务器」的说明。+- 原方案让已登录桌面端领取语音模型凭据,并把音频直接发送到用户配置的 OpenAI 兼容 `/audio/transcriptions` 接口。当前附件转录也由客户端直连模型服务,但只处理已上传且归属当前笔记的附件;不恢复外部媒体抓取或旧任务机制。- 模型返回分段时间戳时生成可点回原片的实录;仅返回全文时写入普通文本。任务失败记录错误码,不把 API Token 写入诊断信息。若未来重新考虑,应先明确内容授权、平台条款、目标市场和识别服务的数据处理方式,再重新设计入口与验证范围;不能直接恢复上述抓取链路。diff --git a/packages/client/src/index.ts b/packages/client/src/index.tsindex 8ccc4a48..a0dc2383 100644--- a/packages/client/src/index.ts+++ b/packages/client/src/index.ts@@ -952,9 +952,9 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {body: JSON.stringify({ modelConfigId }),}),- transcribeNoteResource: (memoId: string, resourceId: string, signal?: AbortSignal) =>- request<{ text: string; resourceId: string; filename: string }>(- `/api/v1/memos/${encodeURIComponent(memoId)}/resources/${encodeURIComponent(resourceId)}/transcribe`,+ prepareNoteResourceTranscription: (memoId: string, resourceId: string, signal?: AbortSignal) =>+ request<{ baseUrl: string; modelId: string; apiKey: string; resourceId: string; filename: string }>(+ `/api/v1/memos/${encodeURIComponent(memoId)}/resources/${encodeURIComponent(resourceId)}/transcription-target`,{ method: "POST", signal },),diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.tsindex 99aea6b9..cee4a01e 100644--- a/packages/shared/src/i18n/en-US.ts+++ b/packages/shared/src/i18n/en-US.ts@@ -1210,11 +1210,12 @@ export const enUS = {statusOff: "Off",resultTitle: "Transcript",recognizing: "Transcribing media…",+ recognizingProgress: "Transcribing… {{count}} audio segments complete.",recognizeFailed: "Transcription failed",copy: "Copy text",copied: "Copied",insertIntoNote: "Insert into note",- attachmentNotice: "Only audio and video attachments already uploaded to notes can be transcribed (up to 24 MiB). The attachment is sent through your EdgeEver instance to the model service you configured.",+ attachmentNotice: "Only audio and video attachments already uploaded to notes can be transcribed. Audio is extracted and split on your device (up to 24 MB per segment), then sent directly from the client to your configured model service. The model key is given to the current signed-in client; browser calls also require provider CORS support.",},aiPrompts: {title: "Prompt library",diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.tsindex 9ca16041..df829983 100644--- a/packages/shared/src/i18n/ja.ts+++ b/packages/shared/src/i18n/ja.ts@@ -1210,11 +1210,12 @@ export const ja = {statusOff: "無効",resultTitle: "文字起こし結果",recognizing: "文字起こし中…",+ recognizingProgress: "文字起こし中…音声の {{count}} セグメントが完了しました。",recognizeFailed: "文字起こしに失敗しました",copy: "テキストをコピー",copied: "コピーしました",insertIntoNote: "ノートに挿入",- attachmentNotice: "ノートにアップロード済みの音声・動画添付ファイルのみ文字起こしできます(最大 24 MiB)。添付ファイルは EdgeEver インスタンスを経由して設定したモデルサービスに送信されます。",+ attachmentNotice: "ノートにアップロード済みの音声・動画添付ファイルのみ文字起こしできます。音声は端末上で抽出・分割され(各部分は最大 24 MB)、クライアントから設定したモデルサービスへ直接送信されます。モデルキーは現在ログイン中のクライアントに渡され、ブラウザーからの通信には提供元の CORS 対応も必要です。",},aiPrompts: {title: "プロンプトライブラリ",diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.tsindex 3b6c1047..3e711150 100644--- a/packages/shared/src/i18n/pl.ts+++ b/packages/shared/src/i18n/pl.ts@@ -1210,11 +1210,12 @@ export const pl = {statusOff: "Wyłączone",resultTitle: "Transkrypcja",recognizing: "Trwa transkrypcja…",+ recognizingProgress: "Trwa transkrypcja… Ukończono {{count}} segmentów dźwięku.",recognizeFailed: "Transkrypcja nie powiodła się",copy: "Kopiuj tekst",copied: "Skopiowano",insertIntoNote: "Wstaw do notatki",- attachmentNotice: "Transkrypcja działa tylko dla plików audio i wideo już dodanych do notatek (do 24 MiB). Załącznik jest wysyłany przez instancję EdgeEver do skonfigurowanej usługi modelu.",+ attachmentNotice: "Transkrypcja działa tylko dla plików audio i wideo dodanych do notatek. Dźwięk jest wyodrębniany i dzielony na urządzeniu (do 24 MB na segment), a następnie wysyłany bezpośrednio z klienta do skonfigurowanej usługi modelu. Klucz modelu trafia do aktualnie zalogowanego klienta; przeglądarka wymaga też obsługi CORS przez dostawcę.",},aiPrompts: {title: "Biblioteka promptów",diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.tsindex 79fa231e..5ad94b5f 100644--- a/packages/shared/src/i18n/zh-CN.ts+++ b/packages/shared/src/i18n/zh-CN.ts@@ -1210,11 +1210,12 @@ export const zhCN = {statusOff: "未开启",resultTitle: "语音识别结果",recognizing: "正在识别音视频…",+ recognizingProgress: "正在转写,已完成 {{count}} 段音频…",recognizeFailed: "语音识别失败",copy: "复制文本",copied: "已复制",insertIntoNote: "插入笔记",- attachmentNotice: "仅识别笔记内已上传的音视频附件(不超过 24 MiB)。识别时附件会经 EdgeEver 实例发送到您配置的模型服务。",+ attachmentNotice: "仅转写笔记内已上传的音视频附件。音轨在本机提取并分段(每段不超过 24 MB),由客户端直接发送到您配置的模型服务。模型密钥会交给当前已登录客户端;浏览器直连还需模型服务支持跨域请求。",},aiPrompts: {title: "指令库",