Skip to content

Commit 2adbdd7

Browse files
authored
fix(gateway): preserve managed media lifecycle outcomes (#124048)
1 parent 1e91253 commit 2adbdd7

13 files changed

Lines changed: 319 additions & 35 deletions

‎src/auto-reply/reply-payload.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,8 @@ export type ReplyDeliveryContext = {
152152
replyToMode: ReplyToMode;
153153
};
154154

155-
const REPLY_MEDIA_FAILURE_WARNING = "⚠️ Media failed.";
155+
const REPLY_MEDIA_FAILURE_WARNING =
156+
"⚠️ Media failed. Try sending a smaller supported file or a different format.";
156157

157158
/** Appends the standard media failure warning without duplicating it. */
158159
export function appendReplyMediaFailureWarning(text: string | undefined): string {

‎src/auto-reply/reply/agent-runner-payloads.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -347,7 +347,7 @@ describe("buildReplyPayloads media filter integration", () => {
347347

348348
expect(replyPayloads).toHaveLength(2);
349349
expectFields(replyPayloads[0], {
350-
text: "keep text\n⚠️ Media failed.",
350+
text: "keep text\n⚠️ Media failed. Try sending a smaller supported file or a different format.",
351351
mediaUrl: undefined,
352352
mediaUrls: undefined,
353353
audioAsVoice: false,
@@ -1063,7 +1063,7 @@ describe("buildReplyPayloads media filter integration", () => {
10631063

10641064
expect(replyPayloads).toHaveLength(1);
10651065
expectFields(replyPayloads[0], {
1066-
text: "⚠️ Media failed.",
1066+
text: "⚠️ Media failed. Try sending a smaller supported file or a different format.",
10671067
mediaUrl: undefined,
10681068
mediaUrls: undefined,
10691069
audioAsVoice: false,

‎src/auto-reply/reply/reply-delivery.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -419,7 +419,7 @@ describe("createBlockReplyDeliveryHandler", () => {
419419
applyReplyToMode: (payload) => payload,
420420
normalizeMediaPaths: async (payload) => ({
421421
...payload,
422-
text: "⚠️ Media failed.",
422+
text: "⚠️ Media failed. Try sending a smaller supported file or a different format.",
423423
mediaUrl: absPath,
424424
mediaUrls: [absPath],
425425
}),

‎src/auto-reply/reply/reply-media-paths.test.ts‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,9 @@ describe("createReplyMediaPathNormalizer", () => {
200200
path.join("/tmp/sandboxes/session-1", "out", "photo.png"),
201201
5 * 1024 * 1024,
202202
);
203-
expect(result.text).toBe("⚠️ Media failed.");
203+
expect(result.text).toBe(
204+
"⚠️ Media failed. Try sending a smaller supported file or a different format.",
205+
);
204206
});
205207

206208
it.each([
@@ -432,7 +434,9 @@ describe("createReplyMediaPathNormalizer", () => {
432434
mediaUrls: ["./out/missing.png"],
433435
});
434436

435-
expect(result.text).toBe("WA_MEDIA_DM_07\n⚠️ Media failed.");
437+
expect(result.text).toBe(
438+
"WA_MEDIA_DM_07\n⚠️ Media failed. Try sending a smaller supported file or a different format.",
439+
);
436440
expectNoMedia(result);
437441
});
438442

@@ -445,7 +449,9 @@ describe("createReplyMediaPathNormalizer", () => {
445449
mediaUrls: ["./out/missing.png", "https://example.com/ok.png"],
446450
});
447451

448-
expect(result.text).toBe("Here is the surviving attachment\n⚠️ Media failed.");
452+
expect(result.text).toBe(
453+
"Here is the surviving attachment\n⚠️ Media failed. Try sending a smaller supported file or a different format.",
454+
);
449455
expectMedia(result, "https://example.com/ok.png", ["https://example.com/ok.png"]);
450456
});
451457

@@ -457,7 +463,9 @@ describe("createReplyMediaPathNormalizer", () => {
457463
mediaUrls: ["./out/missing.png"],
458464
});
459465

460-
expect(result.text).toBe("⚠️ Media failed.");
466+
expect(result.text).toBe(
467+
"⚠️ Media failed. Try sending a smaller supported file or a different format.",
468+
);
461469
expectNoMedia(result);
462470
});
463471

‎src/gateway/managed-image-actions.e2e.test.ts‎

Lines changed: 72 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
import fs from "node:fs/promises";
22
import path from "node:path";
3-
import { describe, expect, test } from "vitest";
3+
import { describe, expect, test, vi } from "vitest";
44
import { readImageProbeFromHeader } from "../media/image-ops.js";
55
import {
6+
cleanupManagedOutgoingMediaRecords,
67
createManagedOutgoingMediaBlocks,
78
MANAGED_OUTGOING_IMAGE_ARTIFACT_ID_PREFIX,
89
} from "./managed-image-attachments.js";
10+
import { readManagedImageRecord } from "./managed-image-record-store.js";
911
import { connectGatewayClient, disconnectGatewayClient } from "./test-helpers.e2e.js";
1012
import {
1113
installGatewayTestHooks,
@@ -114,6 +116,23 @@ describe("managed image actions Gateway E2E", () => {
114116
expect(rootFull.headers.get("content-type")).toBe("image/png");
115117
expect(Buffer.from(await rootFull.arrayBuffer())).toEqual(source);
116118

119+
const partial = await fetch(fullUrl, { headers: { Range: "bytes=3-10" } });
120+
expect(partial.status).toBe(206);
121+
expect(partial.headers.get("content-range")).toBe(`bytes 3-10/${source.byteLength}`);
122+
expect(Buffer.from(await partial.arrayBuffer())).toEqual(source.subarray(3, 11));
123+
124+
const head = await fetch(fullUrl, { method: "HEAD" });
125+
expect(head.status).toBe(200);
126+
expect(head.headers.get("content-length")).toBe(String(source.byteLength));
127+
expect((await head.arrayBuffer()).byteLength).toBe(0);
128+
129+
const unsatisfiable = await fetch(fullUrl, {
130+
headers: { Range: `bytes=${source.byteLength}-` },
131+
});
132+
expect(unsatisfiable.status).toBe(416);
133+
expect(unsatisfiable.headers.get("content-range")).toBe(`bytes */${source.byteLength}`);
134+
expect((await unsatisfiable.arrayBuffer()).byteLength).toBe(0);
135+
117136
fullUrl.pathname = `/rosita${fullUrl.pathname}`;
118137

119138
const full = await fetch(fullUrl);
@@ -137,8 +156,59 @@ describe("managed image actions Gateway E2E", () => {
137156
});
138157
expect(authenticated.status).toBe(200);
139158
expect(Buffer.from(await authenticated.arrayBuffer())).toEqual(source);
140-
} finally {
159+
160+
const wrongIdentity = new URL(fullUrl);
161+
wrongIdentity.pathname = wrongIdentity.pathname.replace(
162+
/\/[0-9a-f-]+\/full$/u,
163+
"/22222222-2222-4222-8222-222222222222/full",
164+
);
165+
const wrong = await fetch(wrongIdentity, {
166+
headers: { Authorization: `Bearer ${GATEWAY_TOKEN}` },
167+
});
168+
expect(wrong.status).toBe(404);
169+
expect(await wrong.text()).toBe("not found");
170+
171+
vi.useFakeTimers({ toFake: ["Date"] });
172+
vi.setSystemTime(Date.parse(download.expiresAt ?? "") + 1);
173+
try {
174+
const expired = await fetch(fullUrl);
175+
expect(expired.status).toBe(401);
176+
expect(await expired.text()).toContain("unauthorized");
177+
} finally {
178+
vi.useRealTimers();
179+
}
180+
141181
await disconnectGatewayClient(client);
182+
const afterDisconnect = await fetch(fullUrl);
183+
expect(afterDisconnect.status).toBe(200);
184+
expect(Buffer.from(await afterDisconnect.arrayBuffer())).toEqual(source);
185+
186+
const record = readManagedImageRecord(
187+
artifactId.slice(MANAGED_OUTGOING_IMAGE_ARTIFACT_ID_PREFIX.length),
188+
stateDir,
189+
);
190+
if (!record) {
191+
throw new Error("managed image record disappeared before cleanup");
192+
}
193+
const originalPath = path.join(
194+
record.original.mediaRoot,
195+
record.original.mediaSubdir,
196+
record.original.mediaId,
197+
);
198+
const cleanup = await cleanupManagedOutgoingMediaRecords({
199+
stateDir,
200+
sessionKey: SESSION_KEY,
201+
forceDeleteSessionRecords: true,
202+
});
203+
expect(cleanup).toMatchObject({ deletedRecordCount: 1, deletedFileCount: 1 });
204+
expect(readManagedImageRecord(record.attachmentId, stateDir)).toBeNull();
205+
await expect(fs.access(originalPath)).rejects.toMatchObject({ code: "ENOENT" });
206+
207+
const afterCleanup = await fetch(fullUrl);
208+
expect(afterCleanup.status).toBe(404);
209+
expect(await afterCleanup.text()).toBe("not found");
210+
} finally {
211+
await disconnectGatewayClient(client).catch(() => {});
142212
}
143213
},
144214
{ serverOptions: { auth: { mode: "token", token: GATEWAY_TOKEN } } },

‎src/gateway/managed-image-attachments.test.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import { withEnvAsync } from "../test-utils/env.js";
2727
import {
2828
attachManagedImageRecordToMessage,
2929
insertManagedImageRecord,
30+
listManagedImageRecordEntries,
3031
MANAGED_OUTGOING_ORIGINALS_SUBDIR,
3132
readManagedImageRecord,
3233
} from "./managed-image-record-store.js";
@@ -912,6 +913,34 @@ describe("handleManagedOutgoingImageHttpRequest", () => {
912913
expect(authorizeGatewayHttpRequestOrReplyMock).toHaveBeenCalledTimes(1);
913914
});
914915

916+
it("keeps a managed audio filename stable in artifact downloads", async () => {
917+
const { attachmentId, sessionKey } = await createFixture(stateDir, {
918+
filename: "meeting-note.mp3",
919+
contentType: "audio/mpeg",
920+
body: Buffer.from([0xff, 0xfb, 0x90, 0x00]),
921+
});
922+
const canonicalPath = `/api/chat/media/outgoing/${encodeURIComponent(sessionKey)}/${attachmentId}/full`;
923+
loadSessionEntryMock.mockReturnValue({
924+
storePath: path.join(stateDir, "sessions.sqlite"),
925+
entry: { sessionId: "sess-1" },
926+
});
927+
readSessionMessagesMock.mockResolvedValue([
928+
{
929+
role: "assistant",
930+
content: [{ type: "audio", url: canonicalPath, openUrl: canonicalPath }],
931+
__openclaw: { id: "msg-1" },
932+
},
933+
]);
934+
935+
const download = await resolveManagedOutgoingImageArtifactDownload({
936+
sessionKey,
937+
artifactId: `${MANAGED_OUTGOING_MEDIA_ARTIFACT_ID_PREFIX}${attachmentId}`,
938+
stateDir,
939+
});
940+
941+
expect(download?.title).toBe("meeting-note.mp3");
942+
});
943+
915944
it("serves a bounded thumbnail through the full-image artifact ticket", async () => {
916945
const source = createSolidPngBuffer(640, 320, { r: 24, g: 64, b: 128 });
917946
const { attachmentId, sessionKey } = await createFixture(stateDir, { body: source });
@@ -1370,6 +1399,28 @@ describe("createManagedOutgoingImageBlocks", () => {
13701399
});
13711400
});
13721401

1402+
it("does not publish a record when playback inspection fails", async () => {
1403+
const sourcePath = path.join(stateDir, "workspace", "voice.mp3");
1404+
await fs.mkdir(path.dirname(sourcePath), { recursive: true });
1405+
await fs.writeFile(sourcePath, Buffer.from([0xff, 0xfb, 0x90, 0x00]));
1406+
resolvePlaybackModeForSourceMock.mockRejectedValueOnce(
1407+
new Error("synthetic playback inspection failure"),
1408+
);
1409+
1410+
const blocks = await createManagedOutgoingImageBlocks({
1411+
sessionKey: "agent:main:main",
1412+
mediaUrls: [sourcePath],
1413+
stateDir,
1414+
localRoots: [path.dirname(sourcePath)],
1415+
allowLocalNonImage: true,
1416+
continueOnPrepareError: true,
1417+
});
1418+
1419+
expect(blocks).toEqual([]);
1420+
expect(listManagedImageRecordEntries({ stateDir })).toEqual([]);
1421+
await expectPathMissing(path.join(stateDir, "media", "outgoing", "originals"));
1422+
});
1423+
13731424
it.each(["audio", "video"] as const)("caps managed %s data URLs by media kind", async (kind) => {
13741425
const maxBytes = maxBytesForKind(kind);
13751426
const contentType = kind === "audio" ? "audio/mpeg" : "video/mp4";

‎src/gateway/managed-image-attachments.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1202,7 +1202,7 @@ async function resolveManagedOutgoingMediaArtifactDownloadForRecord(
12021202
artifactId: buildManagedOutgoingArtifactId(record.attachmentId, kind),
12031203
sessionKey: record.sessionKey,
12041204
type: kind,
1205-
title: record.alt,
1205+
title: kind === "image" ? record.alt : (record.original.filename ?? record.alt),
12061206
...(record.original.contentType ? { mimeType: record.original.contentType } : {}),
12071207
...(record.original.sizeBytes != null ? { sizeBytes: record.original.sizeBytes } : {}),
12081208
url: `${canonicalUrl}?${params.toString()}`,
@@ -1504,7 +1504,6 @@ export async function createManagedOutgoingMediaBlocks(params: {
15041504
: attachmentMetadata?.name?.trim() || label,
15051505
},
15061506
};
1507-
insertManagedImageRecord(record, stateDir);
15081507
let playback: "native" | "transcode" | undefined;
15091508
if (mediaKind === "audio" || mediaKind === "video") {
15101509
const opened = await openLocalFileSafely({ filePath: savedOriginal.path });
@@ -1522,6 +1521,7 @@ export async function createManagedOutgoingMediaBlocks(params: {
15221521
}
15231522
}
15241523
const block = buildManagedMediaBlock(record, playback);
1524+
insertManagedImageRecord(record, stateDir);
15251525
const durationMs = asNonNegativeFiniteNumber(attachmentMetadata?.durationMs);
15261526
const width = asNonNegativeFiniteNumber(attachmentMetadata?.width);
15271527
const height = asNonNegativeFiniteNumber(attachmentMetadata?.height);
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
import { expectErrorDetails, expectFields } from "./artifacts.test-support.js";
3+
4+
const hoisted = vi.hoisted(() => ({
5+
loadSessionEntry: vi.fn(),
6+
resolveManagedArtifactDownload: vi.fn(),
7+
resolveManagedUrlDownload: vi.fn(),
8+
visitSessionMessagesAsync: vi.fn(),
9+
}));
10+
11+
vi.mock("../session-utils.js", async () => {
12+
const actual = await vi.importActual<typeof import("../session-utils.js")>("../session-utils.js");
13+
return {
14+
...actual,
15+
loadGatewaySessionEntryReadOnly: hoisted.loadSessionEntry,
16+
};
17+
});
18+
19+
vi.mock("../session-transcript-readers.js", async () => {
20+
const actual = await vi.importActual<typeof import("../session-transcript-readers.js")>(
21+
"../session-transcript-readers.js",
22+
);
23+
return { ...actual, visitSessionMessagesAsync: hoisted.visitSessionMessagesAsync };
24+
});
25+
26+
vi.mock("../managed-image-attachments.js", async () => {
27+
const actual = await vi.importActual<typeof import("../managed-image-attachments.js")>(
28+
"../managed-image-attachments.js",
29+
);
30+
return {
31+
...actual,
32+
resolveManagedOutgoingMediaArtifactDownload: hoisted.resolveManagedArtifactDownload,
33+
resolveManagedOutgoingMediaUrlDownload: hoisted.resolveManagedUrlDownload,
34+
};
35+
});
36+
37+
const { artifactsHandlers } = await import("./artifacts.js");
38+
39+
describe("managed artifact lifecycle", () => {
40+
beforeEach(() => {
41+
vi.clearAllMocks();
42+
hoisted.loadSessionEntry.mockReturnValue({
43+
storePath: "/tmp/sessions.sqlite",
44+
entry: { sessionId: "sess-main" },
45+
});
46+
hoisted.resolveManagedArtifactDownload.mockResolvedValue(null);
47+
hoisted.visitSessionMessagesAsync.mockImplementation(async (_scope, visit) => {
48+
visit(
49+
{
50+
role: "assistant",
51+
content: [
52+
{
53+
type: "image",
54+
artifactId: "artifact_managed_image_11111111-1111-4111-8111-111111111111",
55+
url: "/api/chat/media/outgoing/agent%3Amain%3Amain/22222222-2222-4222-8222-222222222222/full",
56+
},
57+
],
58+
__openclaw: { seq: 2 },
59+
},
60+
2,
61+
);
62+
return 1;
63+
});
64+
});
65+
66+
it("does not retarget a stale managed artifact id through a different block URL", async () => {
67+
const artifactId = "artifact_managed_image_11111111-1111-4111-8111-111111111111";
68+
const calls: Array<{ ok: boolean; error?: unknown }> = [];
69+
70+
await artifactsHandlers["artifacts.download"]?.({
71+
req: { type: "req", id: "download", method: "artifacts.download", params: {} },
72+
params: { sessionKey: "agent:main:main", artifactId },
73+
client: null,
74+
isWebchatConnect: () => false,
75+
respond: (ok, _payload, error) => calls.push({ ok, error }),
76+
context: { getRuntimeConfig: () => ({}) } as never,
77+
});
78+
79+
expect(calls[0]?.ok).toBe(false);
80+
expectFields(expectErrorDetails(calls), { type: "artifact_not_found", artifactId });
81+
expect(hoisted.resolveManagedUrlDownload).not.toHaveBeenCalled();
82+
expect(hoisted.visitSessionMessagesAsync).not.toHaveBeenCalled();
83+
});
84+
});

0 commit comments

Comments
 (0)