Skip to content

Commit 5708157

Browse files
authored
perf(media): avoid intermediate multipart upload copies (#135162)
* perf(media): avoid intermediate multipart upload copies * perf(media): remove remaining upload adapter copies
1 parent e44c4b8 commit 5708157

23 files changed

Lines changed: 64 additions & 45 deletions

‎docs/plugins/sdk-provider-plugins.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -927,6 +927,12 @@ catalog, API-key auth, and dynamic model resolution.
927927
`openclaw/plugin-sdk/provider-http`. The helper normalizes upload
928928
filenames, including AAC uploads that need an M4A-style filename for
929929
compatible transcription APIs.
930+
931+
Official plugins can use the private `blob-runtime` helper
932+
`bufferToBlobPart(buffer)` for other multipart uploads. Pass it directly to
933+
`new Blob(...)` to preserve the Buffer range without an intermediate copy;
934+
shared backing is copied when needed. Construct the Blob before awaiting
935+
other work so it snapshots the bytes immediately.
930936
</Tab>
931937
<Tab title="Realtime voice">
932938
Consumers can pass candidate provider IDs as the optional second argument

‎docs/plugins/sdk-subpaths.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,7 @@ Use `isLoopbackHost(host)` when a plugin must accept only the local machine. It
343343
| `plugin-sdk/fetch-runtime` | Private-local after July 2026; Wrapped fetch, proxy, EnvHttpProxyAgent option, and pinned lookup helpers |
344344
| `plugin-sdk/proxy-capture` | Debug proxy capture configuration, SQLite-backed capture storage, HTTP/WebSocket capture events, and capture lifecycle helpers |
345345
| `plugin-sdk/runtime-fetch` | Private-local after July 2026; Dispatcher-aware runtime fetch without proxy/guarded-fetch imports |
346+
| `plugin-sdk/blob-runtime` | Private official-plugin runtime; Exact Buffer views for synchronous Blob construction |
346347
| `plugin-sdk/inline-image-data-url-runtime` | Private-local after July 2026; Inline image data URL sanitizer and signature sniffing helpers without the broad media runtime surface |
347348
| `plugin-sdk/response-limit-runtime` | Private-local after July 2026; Byte-, idle-, and deadline-bounded response-body readers without the broad media runtime surface |
348349
| `plugin-sdk/session-binding-runtime` | Private-local after July 2026; Current conversation binding state without configured binding routing or pairing stores |

‎extensions/clickclack/src/http-client.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
* Thin ClickClack REST/websocket client used by gateway, resolver, and outbound
33
* delivery code.
44
*/
5+
import { bufferToBlobPart } from "openclaw/plugin-sdk/blob-runtime";
56
import { redactToolPayloadText } from "openclaw/plugin-sdk/logging-core";
67
import {
78
readProviderJsonResponse,
@@ -474,10 +475,7 @@ export function createClickClackClient(options: ClientOptions) {
474475
nonce?: string;
475476
}): Promise<ClickClackUpload> => {
476477
const form = new FormData();
477-
const bytes: Uint8Array<ArrayBuffer> =
478-
params.buffer.buffer instanceof ArrayBuffer
479-
? new Uint8Array(params.buffer.buffer, params.buffer.byteOffset, params.buffer.byteLength)
480-
: Uint8Array.from(params.buffer);
478+
const bytes = bufferToBlobPart(params.buffer);
481479
form.append("file", new Blob([bytes], { type: params.contentType }), params.filename);
482480
const query = new URLSearchParams({ workspace_id: params.workspaceId });
483481
if (params.nonce) {

‎extensions/comfy/workflow-runtime.ts‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Comfy plugin module implements workflow runtime behavior.
22
import { randomInt } from "node:crypto";
33
import fs from "node:fs/promises";
4+
import { bufferToBlobPart } from "openclaw/plugin-sdk/blob-runtime";
45
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
56
import { resolveGeneratedMediaMaxBytes } from "openclaw/plugin-sdk/media-generation-runtime";
67
import { extensionForMime } from "openclaw/plugin-sdk/media-mime";
@@ -390,12 +391,6 @@ function resolveFileExtension(params: { fileName?: string; mimeType?: string }):
390391
return fileName.slice(dotIndex + 1);
391392
}
392393

393-
function toBlobBytes(buffer: Buffer): ArrayBuffer {
394-
const arrayBuffer = new ArrayBuffer(buffer.byteLength);
395-
new Uint8Array(arrayBuffer).set(buffer);
396-
return arrayBuffer;
397-
}
398-
399394
async function uploadInputImage(params: {
400395
baseUrl: string;
401396
headers: Headers;
@@ -409,7 +404,7 @@ async function uploadInputImage(params: {
409404
const form = new FormData();
410405
form.set(
411406
"image",
412-
new Blob([toBlobBytes(params.image.buffer)], { type: params.image.mimeType }),
407+
new Blob([bufferToBlobPart(params.image.buffer)], { type: params.image.mimeType }),
413408
normalizeOptionalString(params.image.fileName) ||
414409
`input.${resolveFileExtension({ mimeType: params.image.mimeType })}`,
415410
);

‎extensions/deepinfra/image-generation-provider.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Deepinfra provider module implements model/runtime integration.
2+
import { bufferToBlobPart } from "openclaw/plugin-sdk/blob-runtime";
23
import {
34
createOpenAiCompatibleImageGenerationProvider,
45
imageSourceUploadFileName,
@@ -82,7 +83,7 @@ export function buildDeepInfraImageGenerationProvider(options?: {
8283
const mimeType = normalizeOptionalString(image.mimeType) ?? "image/png";
8384
form.append(
8485
"image",
85-
new Blob([new Uint8Array(image.buffer)], { type: mimeType }),
86+
new Blob([bufferToBlobPart(image.buffer)], { type: mimeType }),
8687
imageSourceUploadFileName({ image, index: 0 }),
8788
);
8889
return { kind: "multipart", form };

‎extensions/feishu/src/client.ts‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import type { Agent } from "node:https";
33
import { createRequire } from "node:module";
44
import * as Lark from "@larksuiteoapi/node-sdk";
5+
import { bufferToBlobPart } from "openclaw/plugin-sdk/blob-runtime";
56
import { isRecord } from "openclaw/plugin-sdk/channel-secret-basic-runtime";
67
import {
78
readPluginPackageVersion,
@@ -130,12 +131,6 @@ function stringifyMultipartFieldValue(value: unknown): string | undefined {
130131
}
131132
}
132133

133-
function bufferToBlobPart(value: Buffer): Uint8Array<ArrayBuffer> {
134-
const bytes = new Uint8Array(value.byteLength);
135-
bytes.set(value);
136-
return bytes;
137-
}
138-
139134
function normalizeMultipartUploadData<D>(
140135
opts: Lark.HttpRequestOptions<D>,
141136
): Lark.HttpRequestOptions<D> {

‎extensions/line/src/rich-menu.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Line plugin module implements rich menu behavior.
22
import { messagingApi } from "@line/bot-sdk";
3+
import { bufferToBlobPart } from "openclaw/plugin-sdk/blob-runtime";
34
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
45
import { getAgentScopedMediaLocalRoots } from "openclaw/plugin-sdk/media-local-roots";
56
import { mimeTypeFromFilePath } from "openclaw/plugin-sdk/media-mime";
@@ -124,9 +125,8 @@ export async function uploadRichMenuImage(
124125
? "image/png"
125126
: "image/jpeg";
126127

127-
const imageBytes = new ArrayBuffer(media.buffer.byteLength);
128-
new Uint8Array(imageBytes).set(media.buffer);
129-
await blobClient.setRichMenuImage(richMenuId, new Blob([imageBytes], { type: contentType }));
128+
const blob = new Blob([bufferToBlobPart(media.buffer)], { type: contentType });
129+
await blobClient.setRichMenuImage(richMenuId, blob);
130130

131131
if (opts.verbose) {
132132
logVerbose(`line: uploaded image to rich menu ${richMenuId}`);

‎extensions/litellm/image-generation-provider.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { isIP } from "node:net";
2+
import { bufferToBlobPart } from "openclaw/plugin-sdk/blob-runtime";
23
// Litellm provider module implements model/runtime integration.
34
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
45
import {
@@ -135,7 +136,7 @@ export function buildLitellmImageGenerationProvider(): ImageGenerationProvider {
135136
const mimeType = normalizeOptionalString(image.mimeType) ?? "image/png";
136137
form.append(
137138
partName,
138-
new Blob([new Uint8Array(image.buffer)], { type: mimeType }),
139+
new Blob([bufferToBlobPart(image.buffer)], { type: mimeType }),
139140
imageSourceUploadFileName({ image, index }),
140141
);
141142
}

‎extensions/mattermost/src/channel.send-loopback.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ describe("Mattermost send action loopback", () => {
198198
setMattermostRuntime(createPluginRuntimeMock());
199199
loadOutboundMediaFromUrl.mockReset();
200200
loadOutboundMediaFromUrl.mockResolvedValueOnce({
201-
buffer: Buffer.from("unnamed-image"),
201+
buffer: Buffer.from("!unnamed-image?").subarray(1, -1),
202202
contentType: "image/png",
203203
kind: "image",
204204
});
@@ -233,5 +233,6 @@ describe("Mattermost send action loopback", () => {
233233
expect(uploads).toHaveLength(1);
234234
expect(uploads[0]).toContain('filename="upload.png"');
235235
expect(uploads[0]).toContain("Content-Type: image/png");
236+
expect(uploads[0]).toContain("\r\n\r\nunnamed-image\r\n");
236237
});
237238
});

‎extensions/mattermost/src/mattermost/client.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Mattermost plugin module implements client behavior.
2+
import { bufferToBlobPart } from "openclaw/plugin-sdk/blob-runtime";
23
import { createChannelPartialDeliveryError } from "openclaw/plugin-sdk/channel-inbound";
34
import { collectErrorGraphCandidates } from "openclaw/plugin-sdk/error-runtime";
45
import { buildTimeoutAbortSignal } from "openclaw/plugin-sdk/extension-shared";
@@ -694,10 +695,7 @@ export async function uploadMattermostFile(
694695
): Promise<MattermostFileInfo> {
695696
const form = new FormData();
696697
const fileName = normalizeOptionalString(params.fileName) ?? "upload";
697-
const bytes = Uint8Array.from(params.buffer);
698-
const blob = params.contentType
699-
? new Blob([bytes], { type: params.contentType })
700-
: new Blob([bytes]);
698+
const blob = new Blob([bufferToBlobPart(params.buffer)], { type: params.contentType });
701699
form.append("files", blob, fileName);
702700
form.append("channel_id", params.channelId);
703701

0 commit comments

Comments
 (0)