Skip to content

Commit 1687c67

Browse files
committed
refactor: dedupe media understanding provider helpers
1 parent 045010b commit 1687c67

12 files changed

Lines changed: 324 additions & 364 deletions
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import type { OpenClawConfig } from "../config/types.js";
2+
import { normalizeMediaProviderId } from "./provider-id.js";
3+
4+
type ConfigProvider = NonNullable<
5+
NonNullable<NonNullable<OpenClawConfig["models"]>["providers"]>[string]
6+
>;
7+
8+
type ConfigProviderModel = NonNullable<ConfigProvider["models"]>[number];
9+
10+
function hasImageCapableModel(providerCfg: ConfigProvider): boolean {
11+
const models = providerCfg.models ?? [];
12+
return models.some(
13+
(model: ConfigProviderModel) => Array.isArray(model?.input) && model.input.includes("image"),
14+
);
15+
}
16+
17+
export function resolveImageCapableConfigProviderIds(cfg?: OpenClawConfig): string[] {
18+
const configProviders = cfg?.models?.providers;
19+
if (!configProviders || typeof configProviders !== "object") {
20+
return [];
21+
}
22+
23+
const providerIds: string[] = [];
24+
for (const [providerKey, providerCfg] of Object.entries(configProviders)) {
25+
if (!providerKey?.trim() || !hasImageCapableModel(providerCfg)) {
26+
continue;
27+
}
28+
providerIds.push(normalizeMediaProviderId(providerKey));
29+
}
30+
return providerIds;
31+
}

‎src/media-understanding/media-understanding-misc.test.ts‎

Lines changed: 63 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,29 @@ describe("media understanding scope", () => {
2525

2626
const originalFetch = globalThis.fetch;
2727

28+
async function withLocalAttachmentCache(
29+
prefix: string,
30+
run: (params: {
31+
cache: MediaAttachmentCache;
32+
attachmentPath: string;
33+
canonicalAttachmentPath: string;
34+
}) => Promise<void>,
35+
) {
36+
await withTempDir({ prefix }, async (base) => {
37+
const allowedRoot = path.join(base, "allowed");
38+
const attachmentPath = path.join(allowedRoot, "voice-note.m4a");
39+
await fs.mkdir(allowedRoot, { recursive: true });
40+
await fs.writeFile(attachmentPath, "ok");
41+
const canonicalAttachmentPath = await fs.realpath(attachmentPath).catch(() => attachmentPath);
42+
43+
const cache = new MediaAttachmentCache([{ index: 0, path: attachmentPath }], {
44+
localPathRoots: [allowedRoot],
45+
});
46+
47+
await run({ cache, attachmentPath, canonicalAttachmentPath });
48+
});
49+
}
50+
2851
describe("media understanding attachments SSRF", () => {
2952
afterEach(() => {
3053
globalThis.fetch = originalFetch;
@@ -45,16 +68,7 @@ describe("media understanding attachments SSRF", () => {
4568
});
4669

4770
it("reads local attachments inside configured roots", async () => {
48-
await withTempDir({ prefix: "openclaw-media-cache-allowed-" }, async (base) => {
49-
const allowedRoot = path.join(base, "allowed");
50-
const attachmentPath = path.join(allowedRoot, "voice-note.m4a");
51-
await fs.mkdir(allowedRoot, { recursive: true });
52-
await fs.writeFile(attachmentPath, "ok");
53-
54-
const cache = new MediaAttachmentCache([{ index: 0, path: attachmentPath }], {
55-
localPathRoots: [allowedRoot],
56-
});
57-
71+
await withLocalAttachmentCache("openclaw-media-cache-allowed-", async ({ cache }) => {
5872
const result = await cache.getBuffer({ attachmentIndex: 0, maxBytes: 1024, timeoutMs: 1000 });
5973
expect(result.buffer.toString()).toBe("ok");
6074
});
@@ -111,63 +125,51 @@ describe("media understanding attachments SSRF", () => {
111125
});
112126

113127
it("enforces maxBytes after reading local attachments", async () => {
114-
await withTempDir({ prefix: "openclaw-media-cache-max-bytes-" }, async (base) => {
115-
const allowedRoot = path.join(base, "allowed");
116-
const attachmentPath = path.join(allowedRoot, "voice-note.m4a");
117-
await fs.mkdir(allowedRoot, { recursive: true });
118-
await fs.writeFile(attachmentPath, "ok");
119-
const canonicalAttachmentPath = await fs.realpath(attachmentPath).catch(() => attachmentPath);
120-
121-
const cache = new MediaAttachmentCache([{ index: 0, path: attachmentPath }], {
122-
localPathRoots: [allowedRoot],
123-
});
124-
const originalOpen = fs.open.bind(fs);
125-
const openSpy = vi.spyOn(fs, "open");
126-
127-
openSpy.mockImplementation(async (filePath, flags) => {
128-
const handle = await originalOpen(filePath, flags);
129-
const candidatePath = await fs.realpath(String(filePath)).catch(() => String(filePath));
130-
if (candidatePath !== canonicalAttachmentPath) {
131-
return handle;
132-
}
133-
const mockedHandle = handle as typeof handle & {
134-
readFile: typeof handle.readFile;
135-
};
136-
mockedHandle.readFile = (async () => Buffer.alloc(2048, 1)) as typeof handle.readFile;
137-
return mockedHandle;
138-
});
139-
140-
await expect(
141-
cache.getBuffer({ attachmentIndex: 0, maxBytes: 1024, timeoutMs: 1000 }),
142-
).rejects.toThrow(/exceeds maxBytes 1024/i);
143-
});
128+
await withLocalAttachmentCache(
129+
"openclaw-media-cache-max-bytes-",
130+
async ({ cache, canonicalAttachmentPath }) => {
131+
const originalOpen = fs.open.bind(fs);
132+
const openSpy = vi.spyOn(fs, "open");
133+
134+
openSpy.mockImplementation(async (filePath, flags) => {
135+
const handle = await originalOpen(filePath, flags);
136+
const candidatePath = await fs.realpath(String(filePath)).catch(() => String(filePath));
137+
if (candidatePath !== canonicalAttachmentPath) {
138+
return handle;
139+
}
140+
const mockedHandle = handle as typeof handle & {
141+
readFile: typeof handle.readFile;
142+
};
143+
mockedHandle.readFile = (async () => Buffer.alloc(2048, 1)) as typeof handle.readFile;
144+
return mockedHandle;
145+
});
146+
147+
await expect(
148+
cache.getBuffer({ attachmentIndex: 0, maxBytes: 1024, timeoutMs: 1000 }),
149+
).rejects.toThrow(/exceeds maxBytes 1024/i);
150+
},
151+
);
144152
});
145153

146154
it("opens local attachments with nofollow on posix", async () => {
147155
if (process.platform === "win32") {
148156
return;
149157
}
150-
await withTempDir({ prefix: "openclaw-media-cache-flags-" }, async (base) => {
151-
const allowedRoot = path.join(base, "allowed");
152-
const attachmentPath = path.join(allowedRoot, "voice-note.m4a");
153-
await fs.mkdir(allowedRoot, { recursive: true });
154-
await fs.writeFile(attachmentPath, "ok");
155-
const canonicalAttachmentPath = await fs.realpath(attachmentPath).catch(() => attachmentPath);
156-
157-
const cache = new MediaAttachmentCache([{ index: 0, path: attachmentPath }], {
158-
localPathRoots: [allowedRoot],
159-
});
160-
const openSpy = vi.spyOn(fs, "open");
161-
162-
await cache.getBuffer({ attachmentIndex: 0, maxBytes: 1024, timeoutMs: 1000 });
163-
164-
expect(openSpy).toHaveBeenCalled();
165-
const [openedPath, openedFlags] = openSpy.mock.calls[0] ?? [];
166-
expect(await fs.realpath(String(openedPath)).catch(() => String(openedPath))).toBe(
167-
canonicalAttachmentPath,
168-
);
169-
expect(openedFlags).toBe(fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
170-
});
158+
await withLocalAttachmentCache(
159+
"openclaw-media-cache-flags-",
160+
async ({ cache, canonicalAttachmentPath }) => {
161+
const openSpy = vi.spyOn(fs, "open");
162+
163+
await cache.getBuffer({ attachmentIndex: 0, maxBytes: 1024, timeoutMs: 1000 });
164+
165+
expect(openSpy).toHaveBeenCalled();
166+
const [openedPath, openedFlags] = openSpy.mock.calls[0] ?? [];
167+
expect(await fs.realpath(String(openedPath)).catch(() => String(openedPath))).toBe(
168+
canonicalAttachmentPath,
169+
);
170+
expect(openedFlags).toBe(fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
171+
},
172+
);
171173
});
172174

173175
it("rejects local attachments when canonicalization fails", async () => {

‎src/media-understanding/media-understanding-url-fallback.test.ts‎

Lines changed: 70 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -14,97 +14,86 @@ vi.mock("../media/fetch.js", async () => {
1414
};
1515
});
1616

17+
async function withBlockedLocalAttachmentFallback(
18+
prefix: string,
19+
run: (params: { cache: MediaAttachmentCache; fallbackUrl: string }) => Promise<void>,
20+
) {
21+
await withTempDir({ prefix }, async (base) => {
22+
const allowedRoot = path.join(base, "allowed");
23+
const attachmentPath = path.join(allowedRoot, "voice-note.m4a");
24+
const fallbackUrl = "https://example.com/fallback.jpg";
25+
await fs.mkdir(allowedRoot, { recursive: true });
26+
await fs.writeFile(attachmentPath, "ok");
27+
28+
const cache = new MediaAttachmentCache(
29+
[{ index: 0, path: attachmentPath, url: fallbackUrl, mime: "image/jpeg" }],
30+
{
31+
localPathRoots: [allowedRoot],
32+
},
33+
);
34+
const originalRealpath = fs.realpath.bind(fs);
35+
fetchRemoteMediaMock.mockResolvedValue({
36+
buffer: Buffer.from("fallback-buffer"),
37+
contentType: "image/jpeg",
38+
fileName: "fallback.jpg",
39+
});
40+
41+
vi.spyOn(fs, "realpath").mockImplementation(async (candidatePath) => {
42+
if (String(candidatePath) === attachmentPath) {
43+
throw new Error("EACCES");
44+
}
45+
return await originalRealpath(candidatePath);
46+
});
47+
48+
await run({ cache, fallbackUrl });
49+
});
50+
}
51+
1752
describe("media understanding attachment URL fallback", () => {
1853
afterEach(() => {
1954
vi.restoreAllMocks();
2055
fetchRemoteMediaMock.mockReset();
2156
});
2257

2358
it("getPath falls back to URL fetch when local path is blocked", async () => {
24-
await withTempDir({ prefix: "openclaw-media-cache-getpath-url-fallback-" }, async (base) => {
25-
const allowedRoot = path.join(base, "allowed");
26-
const attachmentPath = path.join(allowedRoot, "voice-note.m4a");
27-
const fallbackUrl = "https://example.com/fallback.jpg";
28-
await fs.mkdir(allowedRoot, { recursive: true });
29-
await fs.writeFile(attachmentPath, "ok");
30-
31-
const cache = new MediaAttachmentCache(
32-
[{ index: 0, path: attachmentPath, url: fallbackUrl, mime: "image/jpeg" }],
33-
{
34-
localPathRoots: [allowedRoot],
35-
},
36-
);
37-
const originalRealpath = fs.realpath.bind(fs);
38-
fetchRemoteMediaMock.mockResolvedValue({
39-
buffer: Buffer.from("fallback-buffer"),
40-
contentType: "image/jpeg",
41-
fileName: "fallback.jpg",
42-
});
43-
44-
vi.spyOn(fs, "realpath").mockImplementation(async (candidatePath) => {
45-
if (String(candidatePath) === attachmentPath) {
46-
throw new Error("EACCES");
59+
await withBlockedLocalAttachmentFallback(
60+
"openclaw-media-cache-getpath-url-fallback-",
61+
async ({ cache, fallbackUrl }) => {
62+
const result = await cache.getPath({
63+
attachmentIndex: 0,
64+
maxBytes: 1024,
65+
timeoutMs: 1000,
66+
});
67+
// getPath should fall through to getBuffer URL fetch, write a temp file,
68+
// and return a path to that temp file instead of throwing.
69+
expect(result.path).toBeTruthy();
70+
expect(fetchRemoteMediaMock).toHaveBeenCalledTimes(1);
71+
expect(fetchRemoteMediaMock).toHaveBeenCalledWith(
72+
expect.objectContaining({ url: fallbackUrl, maxBytes: 1024 }),
73+
);
74+
// Clean up the temp file
75+
if (result.cleanup) {
76+
await result.cleanup();
4777
}
48-
return await originalRealpath(candidatePath);
49-
});
50-
51-
const result = await cache.getPath({
52-
attachmentIndex: 0,
53-
maxBytes: 1024,
54-
timeoutMs: 1000,
55-
});
56-
// getPath should fall through to getBuffer URL fetch, write a temp file,
57-
// and return a path to that temp file instead of throwing.
58-
expect(result.path).toBeTruthy();
59-
expect(fetchRemoteMediaMock).toHaveBeenCalledTimes(1);
60-
expect(fetchRemoteMediaMock).toHaveBeenCalledWith(
61-
expect.objectContaining({ url: fallbackUrl, maxBytes: 1024 }),
62-
);
63-
// Clean up the temp file
64-
if (result.cleanup) {
65-
await result.cleanup();
66-
}
67-
});
78+
},
79+
);
6880
});
6981

7082
it("falls back to URL fetch when local attachment canonicalization fails", async () => {
71-
await withTempDir({ prefix: "openclaw-media-cache-url-fallback-" }, async (base) => {
72-
const allowedRoot = path.join(base, "allowed");
73-
const attachmentPath = path.join(allowedRoot, "voice-note.m4a");
74-
const fallbackUrl = "https://example.com/fallback.jpg";
75-
await fs.mkdir(allowedRoot, { recursive: true });
76-
await fs.writeFile(attachmentPath, "ok");
77-
78-
const cache = new MediaAttachmentCache(
79-
[{ index: 0, path: attachmentPath, url: fallbackUrl, mime: "image/jpeg" }],
80-
{
81-
localPathRoots: [allowedRoot],
82-
},
83-
);
84-
const originalRealpath = fs.realpath.bind(fs);
85-
fetchRemoteMediaMock.mockResolvedValue({
86-
buffer: Buffer.from("fallback-buffer"),
87-
contentType: "image/jpeg",
88-
fileName: "fallback.jpg",
89-
});
90-
91-
vi.spyOn(fs, "realpath").mockImplementation(async (candidatePath) => {
92-
if (String(candidatePath) === attachmentPath) {
93-
throw new Error("EACCES");
94-
}
95-
return await originalRealpath(candidatePath);
96-
});
97-
98-
const result = await cache.getBuffer({
99-
attachmentIndex: 0,
100-
maxBytes: 1024,
101-
timeoutMs: 1000,
102-
});
103-
expect(result.buffer.toString()).toBe("fallback-buffer");
104-
expect(fetchRemoteMediaMock).toHaveBeenCalledTimes(1);
105-
expect(fetchRemoteMediaMock).toHaveBeenCalledWith(
106-
expect.objectContaining({ url: fallbackUrl, maxBytes: 1024 }),
107-
);
108-
});
83+
await withBlockedLocalAttachmentFallback(
84+
"openclaw-media-cache-url-fallback-",
85+
async ({ cache, fallbackUrl }) => {
86+
const result = await cache.getBuffer({
87+
attachmentIndex: 0,
88+
maxBytes: 1024,
89+
timeoutMs: 1000,
90+
});
91+
expect(result.buffer.toString()).toBe("fallback-buffer");
92+
expect(fetchRemoteMediaMock).toHaveBeenCalledTimes(1);
93+
expect(fetchRemoteMediaMock).toHaveBeenCalledWith(
94+
expect.objectContaining({ url: fallbackUrl, maxBytes: 1024 }),
95+
);
96+
},
97+
);
10998
});
11099
});

0 commit comments

Comments
 (0)