Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(media): expose managed paths without duplicate images

liugaowei0436efd557ff
diff --git a/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts b/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts
index 5e629b9df5..7780896148 100644
--- a/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts
+++ b/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts
@@ -26,6 +26,9 @@ const mocks = vi.hoisted(() => ({
outboundFetch: vi.fn(),
ingestMedia: vi.fn(),
readBlob: vi.fn(),
+ resolveBlob: vi.fn(),
+ resolveLegacyImage: vi.fn(),
+ resolveLegacyVideo: vi.fn(),
db: {
owner: 'media-user-0',
drizzle: { owner: 'media-user-0' },
@@ -92,10 +95,16 @@ vi.mock('../providerMediaRuntime.js', () => ({
vi.mock('../ingest.js', () => ({ ingestMedia: mocks.ingestMedia }));
vi.mock('../blobStore.js', () => ({
readFile: mocks.readBlob,
+ parseBlobUrl: (url: string) => {
+ const match = /^cindy-media:\/\/blobs\/([0-9a-f]{64})(\.[a-z0-9]+)$/.exec(url);
+ return match ? { hash: match[1], ext: match[2] } : null;
+ },
+ resolveSafe: mocks.resolveBlob,
supportedMime: (mime: string) =>
['image/png', 'video/mp4', 'audio/mpeg'].includes(mime),
}));
-vi.mock('../../imageCacheStore.js', () => ({ resolveSafe: vi.fn() }));
+vi.mock('../../imageCacheStore.js', () => ({ resolveSafe: mocks.resolveLegacyImage }));
+vi.mock('../../videoCacheStore.js', () => ({ resolveSafe: mocks.resolveLegacyVideo }));
vi.mock('../../logger.js', () => ({
createLogger: () => ({ warn: vi.fn(), info: vi.fn(), debug: vi.fn(), error: vi.fn() }),
}));
@@ -239,10 +248,43 @@ describe('Cindy Core media invocation state and security boundary', () => {
url: `cindy-media://blobs/${'a'.repeat(64)}.png`,
});
mocks.readBlob.mockReset();
+ mocks.resolveBlob.mockReset().mockReturnValue({
+ absPath: process.execPath,
+ mimeType: 'image/png',
+ hash: 'a'.repeat(64),
+ });
+ mocks.resolveLegacyImage.mockReset().mockReturnValue({
+ absPath: process.execPath,
+ mimeType: 'image/jpeg',
+ });
+ mocks.resolveLegacyVideo.mockReset().mockReturnValue({
+ absPath: process.execPath,
+ mimeType: 'video/mp4',
+ });
mocks.recover.mockClear();
mocks.prune.mockClear();
});
+ it('把当前及历史受管媒体地址解析为本机文件路径', async () => {
+ const cases = [
+ [`cindy-media://blobs/${'a'.repeat(64)}.png`, 'image/png'],
+ ['xdt-image://session-1/image.jpg', 'image/jpeg'],
+ ['xdt-video://lizi-art-media-videos/video.mp4', 'video/mp4'],
+ ] as const;
+
+ for (const [url, mimeType] of cases) {
+ await expect(callCindyMedia({ action: 'resolve_local_path', url })).resolves.toEqual({
+ ok: true,
+ url,
+ local_path: process.execPath,
+ mime_type: mimeType,
+ });
+ }
+ await expect(
+ callCindyMedia({ action: 'resolve_local_path', url: 'xdt-audio://local/?path=/tmp/a.mp3' }),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'INVALID_INPUT' });
+ });
+
it('按 modelId 取 Guide、覆盖 body.model,并以一次性 invocation 完成同步结果入仓', async () => {
mocks.guide.mockResolvedValue(
resolvedGuide(
@@ -266,7 +308,12 @@ describe('Cindy Core media invocation state and security boundary', () => {
body: { prompt: 'cat', model: 'agent-must-not-control-this' },
});
- expect(result).toMatchObject({ ok: true, status: 'complete' });
+ expect(result).toMatchObject({
+ ok: true,
+ status: 'complete',
+ _xdt_render_image: false,
+ });
+ expect(String(result.hint)).toContain('只嵌入展示一次');
const [, init] = mocks.outboundFetch.mock.calls[0];
expect(mocks.outboundFetch.mock.calls[0][0]).toBe(
'https://gateway.example.com/images/generations',
@@ -279,6 +326,7 @@ describe('Cindy Core media invocation state and security boundary', () => {
ok: true,
status: 'complete',
xdt_image_urls: [`cindy-media://blobs/${'a'.repeat(64)}.png`],
+ _xdt_render_image: false,
});
expect(mocks.outboundFetch).toHaveBeenCalledTimes(1);
expect(mocks.ingestMedia).toHaveBeenCalledTimes(1);
@@ -996,11 +1044,13 @@ describe('Cindy Core media invocation state and security boundary', () => {
await expect(
callCindyMedia({ action: 'request', invocationId, body: { content: [] } }),
).resolves.toMatchObject({ ok: true, status: 'pending' });
- await expect(callCindyMedia({ action: 'poll', invocationId })).resolves.toMatchObject({
+ const completed = await callCindyMedia({ action: 'poll', invocationId });
+ expect(completed).toMatchObject({
ok: true,
status: 'complete',
xdt_video_urls: [`cindy-media://blobs/${'b'.repeat(64)}.mp4`],
});
+ expect(completed).not.toHaveProperty('_xdt_render_image');
expect(mocks.outboundFetch.mock.calls[1][0]).toBe(
'https://gateway.example.com/video/tasks/task-1',
);
diff --git a/apps/desktop/src/main/cindy-media/invocationService.ts b/apps/desktop/src/main/cindy-media/invocationService.ts
index d301a38bcd..e5a73525c6 100644
--- a/apps/desktop/src/main/cindy-media/invocationService.ts
+++ b/apps/desktop/src/main/cindy-media/invocationService.ts
@@ -15,6 +15,7 @@ import { GHOST_IMAGE_ASPECT_RATIOS, type GhostImageAspectRatio } from '../../sha
import { getAppCapabilities } from '../appCapabilities.js';
import * as authManager from '../authManager.js';
import * as imageCacheStore from '../imageCacheStore.js';
+import * as videoCacheStore from '../videoCacheStore.js';
import { createLogger } from '../logger.js';
import { ServerApiError } from '../serverApiClient.js';
import { getCurrentDbClientUserId, getDbClient } from '../localDb/client/current.js';
@@ -910,8 +911,16 @@ function completedInvocationResult(invocation: StoredMediaInvocation): Record<st
if (!media || typeof media !== 'object' || Array.isArray(media)) {
throw new MediaInvocationError('MEDIA_RESULT_INVALID', '已完成调用保存的媒体结果不合法');
}
+ const agentControlsImageRendering =
+ invocation.capability === 'image.generate' || invocation.capability === 'image.edit';
return {
...(media as Record<string, unknown>),
+ ...(agentControlsImageRendering
+ ? {
+ _xdt_render_image: false,
+ hint: '图片不会从工具结果自动重复渲染;请在最终回复中使用返回的 cindy-media:// 地址只嵌入展示一次。',
+ }
+ : {}),
ok: true,
status: 'complete',
invocation_id: invocation.id,
@@ -1680,6 +1689,41 @@ export async function callCindyMedia(
request: CindyMediaToolRequest,
): Promise<Record<string, unknown>> {
try {
+ if (request.action === 'resolve_local_path') {
+ let resolved: { absPath: string; mimeType: string };
+ try {
+ if (request.url.startsWith('cindy-media://')) {
+ if (!blobStore.parseBlobUrl(request.url)) throw new Error('invalid cindy-media url');
+ resolved = blobStore.resolveSafe(request.url);
+ } else if (request.url.startsWith('xdt-image://')) {
+ resolved = imageCacheStore.resolveSafe(request.url);
+ } else if (request.url.startsWith('xdt-video://')) {
+ resolved = videoCacheStore.resolveSafe(request.url);
+ } else {
+ return failure(
+ 'INVALID_INPUT',
+ 'url 必须是 cindy-media://、xdt-image:// 或 xdt-video:// 受管地址',
+ );
+ }
+ } catch {
+ return failure(
+ 'MEDIA_REFERENCE_INVALID',
+ '受管媒体地址不合法或无法解析',
+ );
+ }
+ try {
+ const stat = await fs.stat(resolved.absPath);
+ if (!stat.isFile()) throw new Error('not a file');
+ } catch {
+ return failure('MEDIA_FILE_NOT_FOUND', '该受管媒体文件在本机已不存在');
+ }
+ return {
+ ok: true,
+ url: request.url,
+ local_path: resolved.absPath,
+ mime_type: resolved.mimeType,
+ };
+ }
if (request.action === 'list_models') {
const capability = request.capability as MediaCapability | undefined;
const availability = await listExecutableMediaModels(
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts
index 78c2424c2f..79a8c152bf 100644
--- a/apps/desktop/src/main/im/shared/turnRunner.ts
+++ b/apps/desktop/src/main/im/shared/turnRunner.ts
@@ -2152,9 +2152,9 @@ export function createTurnRunner(
* 投递给 streaming handle, 让 finalize 时跟文本里的 markdown 图一起
* upload + 拼到卡片上。
*
- * 这是 IM 端"画了图却看不到"的修复入口 — art image_generate 工具按设计
- * 不让模型在文本里嵌 xdt-image markdown (避免 desktop 渲染重复), 所以 IM
- * 端拿不到图的唯一通路就是从这里 sidechannel 把图 URL 接走。
+ * 这是未采用 Agent 正文内联语义的媒体工具结果旁路。Core 图片结果会用
+ * `_xdt_render_image:false` 关闭此旁路,由 Agent 最终回复中的 markdown 图片
+ * 走 materializeTurnLocalImages 送达,避免桌面和 IM 都出现重复图片。
*/
function handleToolResultFullEvent(turn: TurnState, event: AgentEvent): void {
const data = event.data as { fullText?: unknown } | null;
diff --git a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts b/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
index 588176996d..376dbf38db 100644
--- a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
+++ b/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
@@ -1152,6 +1152,18 @@ describe("cindy · media MCP 边界", () => {
expect(parsePayload(result)).toMatchObject({ ok: true, status: "prepared" });
});
+ it("把受管媒体地址交给 Host 按需解析本地路径", async () => {
+ const url = `cindy-media://blobs/${"a".repeat(64)}.png`;
+ const callMedia = vi.fn(async () => ({ ok: true, local_path: "/media/a.png" }));
+ const result = await handleMedia(fakeDeps({ callMedia }), {
+ action: "resolve_local_path",
+ url,
+ });
+
+ expect(callMedia).toHaveBeenCalledWith({ action: "resolve_local_path", url });
+ expect(parsePayload(result)).toMatchObject({ ok: true, local_path: "/media/a.png" });
+ });
+
it("在进入 Host 前拒绝缺失字段和未知 capability", async () => {
const callMedia = vi.fn(async () => ({ ok: true }));
expect(
@@ -1170,6 +1182,13 @@ describe("cindy · media MCP 边界", () => {
}),
),
).toMatchObject({ ok: false, errorCode: "INVALID_INPUT" });
+ expect(
+ parsePayload(
+ await handleMedia(fakeDeps({ callMedia }), {
+ action: "resolve_local_path",
+ }),
+ ),
+ ).toMatchObject({ ok: false, errorCode: "INVALID_INPUT" });
expect(callMedia).not.toHaveBeenCalled();
});
});
diff --git a/packages/cindy-tools/src/ghost/mcpServer.ts b/packages/cindy-tools/src/ghost/mcpServer.ts
index d1de67436b..c705fe4525 100644
--- a/packages/cindy-tools/src/ghost/mcpServer.ts
+++ b/packages/cindy-tools/src/ghost/mcpServer.ts
@@ -101,6 +101,8 @@ const D_MEDIA = [
"媒体生成必须由当前 Agent 通过本工具发起;插件面板和插件沙箱代码不得直接提交生成请求。",
"插件已返回用户配置的 model_id/provider_id 时必须原样传给 prepare,再按目标 capability 走 prepare → request;provider_id 用于区分不同 Provider 下的同名模型。没有已配置模型时,先用 list_models 查询。Gateway 模型的 prepare 会由 Server 根据 model_id 返回 Guide,并在 Guide 不存在或不支持该 capability 时明确报错。",
"异步任务的 request 返回 pending 时,再按 recommended_poll_after_ms 调 poll;同步任务会直接返回 xdt_image_urls / xdt_video_urls。",
+ "Core 图片完成结果由当前 Agent 控制呈现:在最终回复中用返回的受管地址只嵌入展示一次,不要同时重复口播或再次附同一图片。",
+ "展示、改图和附件交接都直接使用 cindy-media:// / xdt-image:// / xdt-video:// 受管地址,不需要本地路径。仅当用户明确询问文件存储位置或本地路径时,才调用 resolve_local_path 并原样传入 url;不要猜路径或扫描磁盘。",
"模型 id、endpoint、Authorization 和 wire model 均由 Host 管理,不要写进 body,不要猜测或覆盖。",
"Guide 缺失、能力不匹配或当前客户端不支持协议时,结果会带稳定 errorCode、retryable、outcomeKnown 和 allowedActions;可按 allowedActions 换模型、改用其它已授权工具或仍存在的旧链路,不要把 INTERNAL 当成协议能力结论。",
"prepare 返回的 invocation_id 是一次性付费提交令牌;request 超时或返回 SUBMISSION_OUTCOME_UNKNOWN 时不要自动重提,以免重复扣费。",
@@ -546,8 +548,9 @@ const MEDIA_CAPABILITIES = new Set<CindyMediaCapability>([
export async function handleMedia(
deps: CindyGhostsMcpDeps,
input: {
- action: "list_models" | "prepare" | "request" | "poll";
+ action: "list_models" | "resolve_local_path" | "prepare" | "request" | "poll";
capability?: CindyMediaCapability;
+ url?: string;
provider_id?: string;
model_id?: string;
invocation_id?: string;
@@ -577,6 +580,21 @@ export async function handleMedia(
action: "list_models",
...(input.capability ? { capability: input.capability } : {}),
});
+ } else if (input.action === "resolve_local_path") {
+ if (!input.url) {
+ return textResult(
+ {
+ ok: false,
+ errorCode: "INVALID_INPUT",
+ message: "resolve_local_path 必须提供 url。",
+ },
+ true,
+ );
+ }
+ result = await deps.callMedia({
+ action: "resolve_local_path",
+ url: input.url,
+ });
} else if (input.action === "prepare") {
if (!input.model_id || !input.capability) {
return textResult(
@@ -1259,7 +1277,7 @@ export function createCindyGhostsMcpServer(
D_MEDIA,
{
action: z
- .enum(["list_models", "prepare", "request", "poll"])
+ .enum(["list_models", "resolve_local_path", "prepare", "request", "poll"])
.describe("要执行的媒体调用阶段"),
capability: z
.enum([
@@ -1280,6 +1298,11 @@ export function createCindyGhostsMcpServer(
.max(128)
.optional()
.describe("prepare 时可选;插件或 list_models 返回 provider_id 时必须原样传入,以区分同名模型的执行来源"),
+ url: z
+ .string()
+ .max(4096)
+ .optional()
+ .describe("resolve_local_path 时必填;原样传入 cindy-media://、xdt-image:// 或 xdt-video:// 受管地址。仅在用户明确询问本地存储路径时使用"),
invocation_id: z
.string()
.max(128)
diff --git a/packages/cindy-tools/src/types.ts b/packages/cindy-tools/src/types.ts
index 4c89a4710f..be0466e67e 100644
--- a/packages/cindy-tools/src/types.ts
+++ b/packages/cindy-tools/src/types.ts
@@ -334,6 +334,7 @@ export type CindyMediaCapability =
/** 当前 Agent 专用的永久 media 工具与 Host 之间的稳定请求面。插件运行时代码不调用。 */
export type CindyMediaToolRequest =
| { action: 'list_models'; capability?: CindyMediaCapability }
+ | { action: 'resolve_local_path'; url: string }
| {
action: 'prepare';
/** 精确执行来源;插件配置返回 providerId 时必须原样传入。 */