Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(im): 在聊天记录中展示发图工具已发送的图片
Dash076365b545d2
diff --git a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.tsindex ee69f96647..52e2216034 100644--- a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts@@ -3824,6 +3824,13 @@ describe('extractToolResultMediaUrls 的兜底账本回落(xdt_media_produced)',expect(extractToolResultMediaUrls(text)).toEqual([IMG]);});+ // Unit: image send tools now return visible media; hook collection must not+ // send that image again. The existing render sentinel also hid it in chat.+ it('does not forward an image already delivered by its sending tool', () => {+ const text = JSON.stringify({ ok: true, xdt_image_urls: [IMG], _xdt_forward_media: false });+ expect(extractToolResultMediaUrls(text)).toEqual([]);+ });+it('_xdt_render_image:false 哨兵优先,全部不外发', () => {const text = JSON.stringify({ ok: true, xdt_media_produced: [IMG], _xdt_render_image: false });expect(extractToolResultMediaUrls(text)).toEqual([]);diff --git a/apps/desktop/src/main/hook-control/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.tsindex caf0c6fd05..f97ddee2eb 100644--- a/apps/desktop/src/main/hook-control/session-runner.ts+++ b/apps/desktop/src/main/hook-control/session-runner.ts@@ -442,13 +442,14 @@ export function extractToolResultMediaUrls(toolResultText: string, provider?: stxdt_video_urls?: unknown;xdt_media_produced?: unknown;_xdt_render_image?: unknown;+ _xdt_forward_media?: unknown;};try {parsed = JSON.parse(toolResultText);} catch {return [];}- if (parsed._xdt_render_image === false) return [];+ if (parsed._xdt_render_image === false || parsed._xdt_forward_media === false) return [];const urls: string[] = [];if (typeof parsed.xdt_image_url === 'string' && isRenderableImageUrl(parsed.xdt_image_url)) {urls.push(parsed.xdt_image_url);diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.tsindex b5ad1c07f4..5550e499b5 100644--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts@@ -698,7 +698,9 @@ describe('turnRunner 渠道任务后台结果回传', () => {next.emit({ type: 'done', data: {} });});- it.each(['rich-card', 'chunked-text'] as const)('%s 回传纯工具图片并去重,不依赖最终正文', async (kind) => {+ // Unit: sent-image results stay visible in chat without being auto-sent a+ // second time. Previously only generated-image collection was covered here.+ it.each(['rich-card', 'chunked-text'] as const)('%s 回传新工具图片并去重,跳过工具已经发送的图片', async (kind) => {const stub = streamingHandleStub();mocks.slackIm.startStreamingText.mockResolvedValue(stub);if (kind === 'chunked-text') {@@ -710,6 +712,10 @@ describe('turnRunner 渠道任务后台结果回传', () => {runner.attachSessionOutput(h.session, 'U1', undefined, 'other-task');const absPath = path.resolve('generated.png');mocks.resolveXdtImageUrl.mockReturnValue({ absPath });+ h.emit({ type: 'tool_result_full', data: {+ fullText: JSON.stringify({ xdt_image_urls: ['xdt-image://already-sent'], _xdt_forward_media: false }),+ } });+ expect(mocks.resolveXdtImageUrl).not.toHaveBeenCalled();const event: AgentEvent = { type: 'tool_result_full', data: {fullText: JSON.stringify({ xdt_image_url: 'xdt-image://generated' }),} };diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.tsindex 2b4e0580ac..f878cc1801 100644--- a/apps/desktop/src/main/im/shared/turnRunner.ts+++ b/apps/desktop/src/main/im/shared/turnRunner.ts@@ -2841,13 +2841,14 @@ export function createTurnRunner(xdt_video_urls?: unknown;xdt_media_produced?: unknown;_xdt_render_image?: unknown;+ _xdt_forward_media?: unknown;};try {parsed = JSON.parse(toolResultText);} catch {return [];}- if (parsed._xdt_render_image === false) return [];+ if (parsed._xdt_render_image === false || parsed._xdt_forward_media === false) return [];// 双协议:历史 xdt-image + 当前 cindy-media// art/mivo/codex 生成图的地址形态;只认老协议会让 IM 端"画了图看不到")。const isManagedImageUrl = (u: string): boolean =>diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.tsindex 2e5c43a520..0647c413c2 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts@@ -1,4 +1,5 @@import type { SessionSendResult } from '@cindy/maker-core';+import path from 'node:path';import { afterEach, describe, expect, it, vi } from 'vitest';const mockState = vi.hoisted(() => ({@@ -21,6 +22,7 @@ const mockState = vi.hoisted(() => ({_sessionInstanceId: string | undefined,) => ({ ok: true as const })),capturedProvidersConfig: null as null | Record<string, unknown>,+ publishImage: vi.fn(),afterSelectCompanion: null as null | (() => void),personalFeishu: {getOwnerOpenId: () => 'ou_personal',@@ -99,6 +101,8 @@ vi.mock('../cindyProxyMedia.js', () => ({getCindyProxyMediaService: () => ({ mcp: {} }),}));+vi.mock('../../cindy-media/publishImage.js', () => ({ publishImage: mockState.publishImage }));+vi.mock('../../maker-host/session-search.js', () => ({searchSessionsFn: vi.fn(),}));@@ -137,7 +141,7 @@ import {import { createDesktopMcpProviders } from '../mcp-providers.js';import { createDbClient } from '../../localDb/client/DbClient.js';import { clearCurrentDbClient, setCurrentDbClient } from '../../localDb/client/current.js';-import type { FeishuBotMcpHostDeps } from '@cindy/mcps';+import type { FeishuBotMcpHostDeps, CreateLiziMcpProvidersOptions } from '@cindy/mcps';import { beginAppSessionBoundary, commitVolatileAppSession } from '../../appSessionState.js';const botCapabilities = {@@ -191,6 +195,41 @@ function createCollabService(overrides: Record<string, ReturnType<typeof vi.fn>>}describe('collab send outcome semantics', () => {+ // Unit: exercise the real provider callback with the existing media importer+ // as its boundary. Missing sent-image previews and stale-task publication were+ // not covered by the channel transport tests.+ it.each(['ready', 'unavailable', 'non-image', 'remote'] as const)('prepares outbound chat images with task ownership: %s', async (state) => {+ mockState.publishImage.mockReset().mockResolvedValue(state === 'unavailable'+ ? { ok: false, errorCode: 'MEDIA_PUBLISH_FAILED' }+ : { ok: true, url: `cindy-media://blobs/${'a'.repeat(64)}.png` });+ let live = true;+ createDesktopMcpProviders({+ botCapabilities, getMakerMemoryManager: vi.fn(), lspPool: {} as never,+ pluginRegistry: { isEnabled: () => true, getPlugins: () => [] } as never,+ invokeRemote: vi.fn(), getLiveSessionGrantState: () => live ? {} as never : null,+ });+ const prepare = mockState.capturedProvidersConfig!.prepareOutboundImage as NonNullable<CreateLiziMcpProvidersOptions['prepareOutboundImage']>;+ const source = path.join(path.sep, 'task', state === 'non-image' ? 'report.pdf' : 'photo.png');+ const prepared = await prepare(source, { agentKind: 'codex', workingDir: path.dirname(source),+ sessionId: 'image-task', sessionInstanceId: 'runtime', ...(state === 'remote' ? { remoteHostId: 'ssh-host' } : {}) });+ if (state === 'non-image' || state === 'remote') {+ expect(mockState.publishImage).not.toHaveBeenCalled();+ expect(prepared.path).toBe(source);+ expect(prepared.url).toBeUndefined();+ return;+ }+ expect(mockState.publishImage).toHaveBeenCalledWith(source,+ { sessionId: 'image-task', workingDir: path.dirname(source) },+ expect.objectContaining({ isCurrent: expect.any(Function), authorize: expect.any(Function) }));+ if (state === 'ready') {+ expect(prepared).toMatchObject({ url: `cindy-media://blobs/${'a'.repeat(64)}.png`,+ path: path.resolve(mockState.userDataDir, 'cindy-media', 'blobs', 'aa', `${'a'.repeat(64)}.png`) });+ } else expect(prepared).toMatchObject({ path: source, errorCode: 'MEDIA_PUBLISH_FAILED' });+ prepared.assertCurrent!();+ live = false;+ expect(prepared.assertCurrent).toThrow('SESSION_SCOPE_CHANGED');+ });+afterEach(() => {mockState.logger.warn.mockClear();mockState.logger.info.mockClear();diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/telegramBotMcpServer.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/telegramBotMcpServer.test.tsindex a984ba7ccd..13734caadc 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/telegramBotMcpServer.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/telegramBotMcpServer.test.ts@@ -13,7 +13,7 @@ import {type TelegramToolScope,type TelegramToolTransport,} from '../../im/shared/channelToolScope';-import { createTelegramBotMcpServer, TELEGRAM_DOWNLOAD_SUBDIR } from '../telegramBotMcpServer';+import { createTelegramBotMcpServer, TELEGRAM_DOWNLOAD_SUBDIR, type TelegramBotMcpDeps } from '../telegramBotMcpServer';vi.mock('../../logger.js', () => ({createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),@@ -105,12 +105,13 @@ function ownerDmScope(t: FakeTransport): TelegramToolScope {async function withServer(scope: TelegramToolScope | null,run: (call: (name: string, args?: Record<string, unknown>) => Promise<Record<string, unknown>>) => Promise<void>,- options: { workingDir?: string; contextInstanceId?: string } = {},+ options: { workingDir?: string; contextInstanceId?: string; prepareOutboundImage?: TelegramBotMcpDeps['prepareOutboundImage'] } = {},) {const release = scope? beginChannelToolScope({ sessionId: 's-1', sessionInstanceId: 'i-1', scope }): null;const server = createTelegramBotMcpServer({+ prepareOutboundImage: options.prepareOutboundImage,getSessionContext: () => ({agentKind: 'claude-code',workingDir: options.workingDir ?? '/tmp/task',@@ -139,6 +140,28 @@ afterEach(() => {});describe('cindy_telegram_bot scope gate', () => {+ // Unit: the real send_media handler must expose local sent photos in chat;+ // existing media tests covered only transport and file permission behavior.+ it('returns a local photo preview while URL and file-id sends retain their existing behavior', async () => {+ const t = fakeTransport();+ const source = path.join(os.tmpdir(), 'photo.png');+ const stored = path.join(os.tmpdir(), 'stored.png');+ const url = `cindy-media://blobs/${'a'.repeat(64)}.png`;+ const prepareOutboundImage = vi.fn(async () => ({ path: stored, url }));+ await withServer(ownerDmScope(t), async (call) => {+ expect(await call('send_media', { kind: 'photo', path: source, caption: 'design' })).toMatchObject({+ ok: true, xdt_image_urls: [url], _xdt_forward_media: false,+ });+ expect(t.sendMedia).toHaveBeenCalledExactlyOnceWith('123', { kind: 'photo', absPath: stored, caption: 'design' });+ for (const input of [{ url: 'https://example.test/photo.png' }, { file_id: 'photo-id' }]) {+ const sent = await call('send_media', { kind: 'photo', ...input });+ expect(sent.ok).toBe(true);+ expect(sent.xdt_image_urls).toBeUndefined();+ }+ expect(prepareOutboundImage).toHaveBeenCalledExactlyOnceWith(source);+ }, { prepareOutboundImage });+ });+it('fails closed without an active scope, and when the session instance changed', async () => {await withServer(null, async (call) => {const r = await call('send_text', { text: 'hi' });diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.tsindex 9366675040..9faeb703c6 100644--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts@@ -13,7 +13,7 @@ import { listProjects, renameProject, removeProject } from './projectManagement.import { activeOwnerScopeKey, getActiveAppSession, isAppSessionBoundaryPending } from '../appSessionState.js';import type { createBotCapabilityService } from '../maker-ipc/botCapabilityService.js';import { routineTools } from '../routines/service.js';-import { join as pathJoin } from 'node:path';+import { join as pathJoin, extname } from 'node:path';import { and, eq, inArray } from 'drizzle-orm';import {@@ -22,6 +22,7 @@ import {setSessionPathAuthorizer,type LiziMcpProvider,type LiziMcpSessionContext,+ type PreparedOutboundImage,type LspServerPool,type XdtHelperMcpDeps,type SshHostSnapshotLike,@@ -334,9 +335,44 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMcreturn result;};+ const prepareOutboundImage = async (sourcePath: string, context: LiziMcpSessionContext): Promise<PreparedOutboundImage> => {+ const owner = getActiveAppSession();+ const scope = readChannelToolScope(context);+ const { mimeForExt, resolveSafe } = await import('../cindy-media/blobStore.js');+ if (!mimeForExt(extname(sourcePath).toLowerCase())?.startsWith('image/')) return { path: sourcePath };+ const { sessionId, sessionInstanceId, workingDir } = context;+ if (!sessionId || !sessionInstanceId || !workingDir || context.remoteHostId) {+ return { path: sourcePath, errorCode: 'IMAGE_PREVIEW_UNAVAILABLE' };+ }+ const isCurrent = () => {+ const current = getActiveAppSession();+ return !isAppSessionBoundaryPending()+ && current.dataOwnerId === owner.dataOwnerId && current.generation === owner.generation+ && !!deps.getLiveSessionGrantState?.(sessionId, sessionInstanceId)+ && (!scope || readChannelToolScope(context) === scope);+ };+ const assertCurrent = () => { if (!isCurrent()) throw new Error('SESSION_SCOPE_CHANGED'); };+ try {+ const { publishImage } = await import('../cindy-media/publishImage.js');+ const image = await publishImage(sourcePath, { sessionId, workingDir }, {+ isCurrent,+ authorize: (path) => authorizeDesktopSessionPath({+ ...context, sessionId, sessionInstanceId, path, toolName: 'outbound_image', operation: 'read',+ }, deps.getLiveSessionGrantState),+ });+ // Send the immutable snapshot, so later edits/deletion cannot change chat history.+ return image.ok === true && typeof image.url === 'string'+ ? { path: resolveSafe(image.url).absPath, url: image.url, assertCurrent }+ : { path: sourcePath, errorCode: typeof image.errorCode === 'string' ? image.errorCode : 'IMAGE_PREVIEW_UNAVAILABLE', assertCurrent };+ } catch {+ return { path: sourcePath, errorCode: 'IMAGE_PREVIEW_UNAVAILABLE', assertCurrent };+ }+ };+const providers = createLiziMcpProviders({// 先传完整内置列表;按会话启停由下面的 isEnabled 包装处理。enabled: BUILTIN_LIZI_MCP_IDS,+ prepareOutboundImage,android: getAndroidMcpDeps({isAndroidAutomationEnabled: (context) =>// Codex provider presence is the bridge-creation enablement snapshot.@@ -1324,6 +1360,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMcname: 'cindy_telegram_bot',instance: createTelegramBotMcpServer({getSessionContext: () => resolveLiziMcpSessionContext(ctx),+ prepareOutboundImage: (path) => prepareOutboundImage(path, resolveLiziMcpSessionContext(ctx)),}),}),});diff --git a/apps/desktop/src/main/mcp-integrations/telegramBotMcpServer.ts b/apps/desktop/src/main/mcp-integrations/telegramBotMcpServer.tsindex 58bc6e1cb8..3aa097e592 100644--- a/apps/desktop/src/main/mcp-integrations/telegramBotMcpServer.ts+++ b/apps/desktop/src/main/mcp-integrations/telegramBotMcpServer.ts@@ -25,7 +25,7 @@ import path from 'node:path';import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';-import type { LiziMcpSessionContext } from '@cindy/mcps';+import { sendFileWithImagePreview, type LiziMcpSessionContext, type PrepareOutboundImage } from '@cindy/mcps';import { TELEGRAM_OUTBOUND_MEDIA, TelegramApiError, type TgMessage } from '@cindy/im';import { createLogger } from '../logger.js';@@ -38,6 +38,7 @@ const log = createLogger('mcp/cindy_telegram_bot');export interface TelegramBotMcpDeps {getSessionContext(): LiziMcpSessionContext;+ prepareOutboundImage?: PrepareOutboundImage;}/** 任何人都不能经 Agent 调的方法: 抢长轮询 / 改 webhook / 注销 bot。 */@@ -290,15 +291,21 @@ export function createTelegramBotMcpServer(deps: TelegramBotMcpDeps): McpServer}}try {- const sent = await scope.im.sendMedia(scope.laneUserId, {- kind: kind as keyof typeof TELEGRAM_OUTBOUND_MEDIA,- ...(uploadPath ? { absPath: uploadPath } : {}),- ...(url ? { url } : {}),- ...(file_id ? { fileId: file_id } : {}),- ...(caption ? { caption } : {}),- ...(reply_to_message_id ? { replyToMessageId: reply_to_message_id } : {}),- });- return result({ ok: true, messageId: sent.messageId, kind, ...(absPath ? { file: path.basename(absPath) } : {}) });+ const send = async (filePath?: string) => {+ const sent = await scope.im.sendMedia(scope.laneUserId, {+ kind: kind as keyof typeof TELEGRAM_OUTBOUND_MEDIA,+ ...(filePath ? { absPath: filePath } : {}),+ ...(url ? { url } : {}),+ ...(file_id ? { fileId: file_id } : {}),+ ...(caption ? { caption } : {}),+ ...(reply_to_message_id ? { replyToMessageId: reply_to_message_id } : {}),+ });+ return { ok: true, messageId: sent.messageId };+ };+ const sent = uploadPath && kind === 'photo'+ ? await sendFileWithImagePreview(uploadPath, undefined, deps.prepareOutboundImage, send)+ : await send(uploadPath);+ return result({ ...sent, kind, ...(absPath ? { file: path.basename(absPath) } : {}) });} catch (err) {return failure(err, TELEGRAM_OUTBOUND_MEDIA[kind as keyof typeof TELEGRAM_OUTBOUND_MEDIA]?.method ?? 'sendMedia');}@@ -514,4 +521,3 @@ export function createTelegramBotMcpServer(deps: TelegramBotMcpDeps): McpServer/** 测试用: 下载目录名(与 download_file 同源)。 */export const TELEGRAM_DOWNLOAD_SUBDIR = DOWNLOAD_SUBDIR;-diff --git a/docs/dev-rules/media-storage-and-protocols.md b/docs/dev-rules/media-storage-and-protocols.mdindex fc478775ed..19d2e25b4d 100644--- a/docs/dev-rules/media-storage-and-protocols.md+++ b/docs/dev-rules/media-storage-and-protocols.md@@ -277,6 +277,20 @@## 多端与远程+- 发图工具同时交付渠道与 Cindy 聊天(2026-10-27):本地图片通过宿主的+ `prepareOutboundImage` 复用 `publishImage` 入仓,渠道发送同一个不可变副本。成功结果返回+ 既有 `xdt_image_urls`,Desktop / Mobile 按现有工具产物入口在聊天流中直接展示;不要求+ 模型再调用导入工具或在最终回复补贴图片。外发成功的结果同时带 `_xdt_forward_media: false`,+ 个人 IM 与官方 hook 的工具媒体收集器跳过自动转发,该标记不影响聊天展示。+ `sendFileWithImagePreview` 为具名发送工具提供共用适配;已接飞书/Lark 的 `send_file`、+ `send_file_to_user`,微信 `send_file_to_user`,Telegram `send_media` 的本地 `photo`。+ 普通文件、Telegram URL / file_id 与任意底层 `call_api` 保持既有行为,不推测媒体字节。+ 新字段为可选返回字段,旧工具和未注入宿主回调的调用保持原样,旧客户端仍识别既有图片字段。+ 预览准备失败不把渠道发送成功改报失败:结果保留真实回执并附 `imagePreviewError`;渠道发送+ 失败不声明已交付图片。图片入仓后发送失败的任务引用沿用任务删除清理,不增加重发/恢复队列。+ 不回填旧记录、不重放渠道发送;模型另行在正文引用图片仍遵守既有 Markdown 出站规则。+ 回归见 `feishuBotLaneTools.test.ts`、`providersFeishuRouting.test.ts`、`wechatMcpServer.test.ts`、+ `telegramBotMcpServer.test.ts`、`collabSendOutcome.test.ts` 与两个渠道 runner 的媒体收集测试。- 将已有截图或本地图片保存为持久受管附件时,Agent 使用 Core `media(action: "import_image", path)`:Host按当前任务文件权限读取,在当前媒体仓入库并登记任务引用,再返回 `xdt_image_urls`。工作目录外路径复用现有授权,SSH 任务不得回退读取控制端同名文件。返回成功仅表示diff --git a/docs/product-rules/telegram-bot-parity.md b/docs/product-rules/telegram-bot-parity.mdindex dd93610ab2..3093a9c0fe 100644--- a/docs/product-rules/telegram-bot-parity.md+++ b/docs/product-rules/telegram-bot-parity.md@@ -11,6 +11,12 @@ Cindy 有两个 Telegram bot,用户看到的是同一个产品:两者是**两套架构**,不是同一份代码的两个开关。所以"统一"不等于"让两条代码路径长得一样",而是:**能同源的同源;不能同源的,差异必须写在这张表里、有裁决、有理由。**+2026-10-27 发图工具的聊天留存:个人 bot 的 `send_media(kind: photo, path)` 复用+`sendFileWithImagePreview` 返回持久图片,Cindy 电脑与手机的聊天流直接展示。+该工具仍只属于个人/伙伴 bot 的当前轮次,官方 bot 不新增直通发送入口。+两侧工具媒体收集器都识别 `_xdt_forward_media: false`,避免把工具已发送的图片自动再发一次。+Telegram URL / file_id 的发送保持原样;本次不新增下载或历史补发。+2026-10-17 群触发与空回复:默认召唤模式下,仅提到显示名(包括句首的「Cindy 赞助」)不触发。个人 bot 保留显式 `@显示名` 的兼容入口;平台提及、回复 bot、命令及用户主动开启的全响应模式沿用原有规则。Telegram 成功轮次没有正文和附件时不补发「空回复」或diff --git a/packages/lizi-mcps/src/__tests__/feishuBotLaneTools.test.ts b/packages/lizi-mcps/src/__tests__/feishuBotLaneTools.test.tsindex ce11ed316f..9adff5ce47 100644--- a/packages/lizi-mcps/src/__tests__/feishuBotLaneTools.test.ts+++ b/packages/lizi-mcps/src/__tests__/feishuBotLaneTools.test.ts@@ -9,6 +9,7 @@ import { join } from 'node:path';import { Client } from '@modelcontextprotocol/sdk/client/index.js';import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';import { describe, expect, it, vi } from 'vitest';+import { extractPayloadToolResultMedia } from '@cindy/maker-shared/payload-summary';import { createFeishuBotMcpServer } from '../cindy_feishuBotMcpServer';import type { FeishuBotLaneScope, FeishuBotLaneTransport } from '../types.js';@@ -58,12 +59,13 @@ function scopeOf(im: FeishuBotLaneTransport, overrides: Partial<FeishuBotLaneSco};}-async function harness(getLaneScope?: () => FeishuBotLaneScope | null) {+async function harness(getLaneScope?: () => FeishuBotLaneScope | null, extra: Record<string, unknown> = {}) {const server = createFeishuBotMcpServer({getChatId: () => 'oc_here',sendFile: vi.fn(async () => ({ ok: true })),sendMessage: vi.fn(async () => ({ ok: true, messageId: 'om_x' })),...(getLaneScope ? { getLaneScope } : {}),+ ...extra,});const [clientTx, serverTx] = InMemoryTransport.createLinkedPair();const client = new Client({ name: 'feishu-lane-test', version: '0.0.0' });@@ -79,6 +81,55 @@ async function harness(getLaneScope?: () => FeishuBotLaneScope | null) {}describe('cindy_feishu_bot 轮次内直通工具', () => {+ // Regression: sent design screenshots were only visible in Feishu. These unit+ // cases exercise both real MCP entry points; previous tests only checked send receipts.+ it.each(['send_file', 'send_file_to_user'])('%s returns the sent image for chat without forwarding it again', async (name) => {+ const im = fakeTransport();+ const source = join(tmpdir(), 'design.png');+ const stored = join(tmpdir(), 'managed-design.png');+ const url = `cindy-media://blobs/${'a'.repeat(64)}.png`;+ const sendFile = vi.fn(async () => ({ ok: true, messageId: 'om_file' }));+ const h = await harness(() => scopeOf(im), {+ sendFile,+ prepareOutboundImage: async () => ({ path: stored, url }),+ });+ try {+ const res = name === 'send_file'+ ? await h.call(name, { path: source })+ : await h.call('call_tool', { name, args: { absPath: source } });+ expect(res.payload).toMatchObject({ ok: true, xdt_image_urls: [url], _xdt_forward_media: false });+ expect(extractPayloadToolResultMedia(JSON.stringify(res.payload))).toEqual([+ expect.objectContaining({ kind: 'image', url }),+ ]);+ const transport = name === 'send_file' ? im.sendFile : sendFile;+ expect(transport).toHaveBeenCalledExactlyOnceWith(name === 'send_file' ? 'g/oc_here' : 'oc_here', stored, 'design.png');+ } finally { await h.close(); }+ });++ it.each(['throw', 'unavailable', 'send-failed', 'scope-changed'] as const)('keeps image preview and channel delivery outcomes distinct: %s', async (mode) => {+ const im = fakeTransport({ sendFile: vi.fn(async () => mode === 'send-failed'+ ? { ok: false, reason: 'UPLOAD_FAIL' } : { ok: true, messageId: 'om_file' }) });+ const source = join(tmpdir(), 'design.png');+ const h = await harness(() => scopeOf(im), {+ prepareOutboundImage: async () => {+ if (mode === 'throw') throw new Error('preview failure');+ if (mode === 'unavailable') return { path: source, errorCode: 'MEDIA_READ_FAILED' };+ return { path: source, url: `cindy-media://blobs/${'b'.repeat(64)}.png`,+ assertCurrent: () => { if (mode === 'scope-changed') throw new Error('SESSION_SCOPE_CHANGED'); } };+ },+ });+ try {+ const { payload } = await h.call('send_file', { path: source });+ expect(payload.ok).toBe(mode === 'throw' || mode === 'unavailable');+ expect(payload.xdt_image_urls).toBeUndefined();+ if (mode === 'throw' || mode === 'unavailable') {+ expect(payload).toMatchObject({ messageId: 'om_file', imagePreviewError: expect.any(String) });+ expect(im.sendFile).toHaveBeenCalledExactlyOnceWith('g/oc_here', source, undefined);+ } else if (mode === 'scope-changed') expect(im.sendFile).not.toHaveBeenCalled();+ else expect(payload.errorCode).toBe('UPLOAD_FAIL');+ } finally { await h.close(); }+ });+it('未注入作用域读取器时 server 形态不变(只有 list_tools / call_tool)', async () => {const h = await harness();expect((await h.client.listTools()).tools.map((t) => t.name).sort()).toEqual(['call_tool', 'list_tools']);diff --git a/packages/lizi-mcps/src/__tests__/providersFeishuRouting.test.ts b/packages/lizi-mcps/src/__tests__/providersFeishuRouting.test.tsindex d36d1a8b50..e1ce01624a 100644--- a/packages/lizi-mcps/src/__tests__/providersFeishuRouting.test.ts+++ b/packages/lizi-mcps/src/__tests__/providersFeishuRouting.test.ts@@ -1,13 +1,16 @@import { describe, expect, it, vi } from 'vitest';import { createLiziMcpProviders } from '../providers.js';+import type { CreateLiziMcpProvidersOptions } from '../providers.js';import { runWithLiziMcpSessionContext } from '../session-context.js';import type { FeishuBotMcpHostDeps } from '../types.js';-function setup(getOwnerOpenId: FeishuBotMcpHostDeps['getOwnerOpenId'] = async () => 'ou_owner') {+function setup(getOwnerOpenId: FeishuBotMcpHostDeps['getOwnerOpenId'] = async () => 'ou_owner',+ prepareOutboundImage?: CreateLiziMcpProvidersOptions['prepareOutboundImage']) {const sendMessage = vi.fn(async () => ({ ok: true, messageId: 'om_notification' }));const sendFile = vi.fn(async () => ({ ok: true, messageId: 'om_file' }));const provider = createLiziMcpProviders({feishuBot: { getOwnerOpenId, sendFile, sendMessage },+ prepareOutboundImage,}).find((candidate) => candidate.name === 'cindy_feishu_bot')!;const config = provider.toClaudeSdkConfig({ agentKind: 'codex', workingDir: '' }) as {instance: { _registeredTools: Record<string, { handler: (args: unknown) => Promise<unknown> }> };@@ -22,6 +25,19 @@ function setup(getOwnerOpenId: FeishuBotMcpHostDeps['getOwnerOpenId'] = async ()}describe('Feishu notification session attribution', () => {+ // Unit: media must be pinned to the invoking task, not the shared bridge's+ // empty factory context. Prior routing tests did not exercise image preparation.+ it('prepares sent images using each live caller on the shared bridge', async () => {+ const prepare = vi.fn(async (path: string) => ({ path, url: `cindy-media://blobs/${'a'.repeat(64)}.png` }));+ const { callFile } = setup(undefined, prepare);+ await Promise.all(['image-task-a', 'image-task-b'].map((sessionId) => runWithLiziMcpSessionContext(+ { agentKind: 'codex', workingDir: '/tmp/task', sessionId }, callFile,+ )));+ for (const sessionId of ['image-task-a', 'image-task-b']) {+ expect(prepare).toHaveBeenCalledWith('/tmp/report.txt', expect.objectContaining({ sessionId }));+ }+ });+// #6439: worker DB owner lookup is asynchronous. The real MCP handler must// pass a resolved recipient to both send paths, never a Promise (unit tier).it('awaits the owner before sending a file', async () => {diff --git a/packages/lizi-mcps/src/__tests__/wechatMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/wechatMcpServer.test.tsindex 8c232260d6..096d53fbfb 100644--- a/packages/lizi-mcps/src/__tests__/wechatMcpServer.test.ts+++ b/packages/lizi-mcps/src/__tests__/wechatMcpServer.test.ts@@ -64,6 +64,10 @@ describe('cindy_wechat proactive routing', () => {const absPath = path.join(workingDir, 'preview.png');await fs.writeFile(absPath, 'png-bytes');const sendFile = vi.fn(async () => ({ ok: true, messageId: 'media-1' }));+ // Sent-image regression: retain the prepared image in the tool result for chat.+ // Unit; the existing recipient/path test previously only checked the channel receipt.+ const stored = path.join(workingDir, 'stored.png');+ const url = `cindy-media://blobs/${'a'.repeat(64)}.png`;const server = createWechatMcpServer({getActivePeerIdForSession: () => null,getMostRecentPeerId: () => 'peer-history',@@ -71,6 +75,7 @@ describe('cindy_wechat proactive routing', () => {sendMessage: vi.fn(),sendFile,workingDir,+ prepareOutboundImage: async () => ({ path: stored, url }),});const [clientTx, serverTx] = InMemoryTransport.createLinkedPair();const client = new Client({ name: 'wechat-test', version: '0.0.0' });@@ -83,8 +88,11 @@ describe('cindy_wechat proactive routing', () => {args: { absPath, displayName: 'result.png' },},});- expect(sendFile).toHaveBeenCalledWith('peer-session', await fs.realpath(absPath), 'result.png');+ expect(sendFile).toHaveBeenCalledWith('peer-session', stored, 'result.png');expect(JSON.stringify(call)).toContain('media-1');+ expect(JSON.parse((call.content as Array<{ text: string }>)[0]!.text)).toMatchObject({+ xdt_image_urls: [url], _xdt_forward_media: false,+ });} finally {await client.close();await server.close();diff --git a/packages/lizi-mcps/src/cindy_feishuBotLaneTools.ts b/packages/lizi-mcps/src/cindy_feishuBotLaneTools.tsindex 37d19976a9..c8c9d4781c 100644--- a/packages/lizi-mcps/src/cindy_feishuBotLaneTools.ts+++ b/packages/lizi-mcps/src/cindy_feishuBotLaneTools.ts@@ -25,6 +25,7 @@ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';import type { FeishuBotLaneScope } from './types.js';+import { sendFileWithImagePreview, type PrepareOutboundImage } from './outboundImage.js';const TEXT_MAX_CHARS = 30_000;const EMOJI_TYPE_RE = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;@@ -208,6 +209,7 @@ async function pinCallApiTarget(export function registerFeishuLaneTools(server: McpServer,getLaneScope: () => FeishuBotLaneScope | null,+ prepareOutboundImage?: PrepareOutboundImage,): void {const replyArg = z.string()@@ -291,11 +293,12 @@ export function registerFeishuLaneTools(sendPath = real;}try {- const sent = await scope.im.sendFile(scope.laneUserId, sendPath, display_name);+ const sent = await sendFileWithImagePreview(sendPath, display_name, prepareOutboundImage,+ (file, name) => scope.im.sendFile(scope.laneUserId, file, name));if (!sent.ok) {return result({ ok: false, errorCode: sent.reason ?? 'SEND_FAILED', error: sent.reason ?? 'unknown' }, true);}- return result({ ok: true, ...(sent.messageId ? { messageId: sent.messageId } : {}) });+ return result({ ...sent });} catch (err) {return failure(err, 'send_file');}diff --git a/packages/lizi-mcps/src/cindy_feishuBotMcpServer.ts b/packages/lizi-mcps/src/cindy_feishuBotMcpServer.tsindex 6d14bacbf3..419c32bba8 100644--- a/packages/lizi-mcps/src/cindy_feishuBotMcpServer.ts+++ b/packages/lizi-mcps/src/cindy_feishuBotMcpServer.ts@@ -21,6 +21,7 @@import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';import { jsonObjectArg } from './json-object-arg.js';+import { sendFileWithImagePreview, type PrepareOutboundImage } from './outboundImage.js';import { FeishuBotToolRegistry, type FeishuBotToolResult } from './cindy_feishuBotToolRegistry';import { registerFeishuLaneTools } from './cindy_feishuBotLaneTools.js';@@ -103,6 +104,7 @@ const RULES: Record<string, string> = {};* interface omits the host-only accessor and adds the resolved closure.*/export type FeishuBotMcpDeps = Omit<FeishuBotMcpHostDeps, 'getOwnerOpenId' | 'readLaneScope'> & {+ prepareOutboundImage?: PrepareOutboundImage;/*** 当前 tool-call 的飞书逐轮作用域(provider 闭包从 session ctx 解出);null 表示本轮* 不是由飞书消息触发或轮次已结束,轮次内工具一律 fail closed。缺省(未注入)时不注册@@ -175,7 +177,8 @@ function registerSendFileToUser();}- const result = await deps.sendFile(chatId, absPath, displayName);+ const result = await sendFileWithImagePreview(absPath, displayName, deps.prepareOutboundImage,+ (file, name) => deps.sendFile(chatId, file, name));if (!result.ok) {const codeMap: Record<string, string> = {@@ -198,7 +201,7 @@ function registerSendFileToUser(}return buildJsonResult({- ok: true,+ ...result,sent: {absPath,displayName: result.reason ?? displayName,@@ -384,7 +387,7 @@ export function createFeishuBotMcpServer(deps: FeishuBotMcpDeps): McpServer {registerListToolsEntry(server, registry, d);registerCallToolEntry(server, registry, d);// 飞书轮次内的直通工具(顶层具名注册,审批策略能按工具名分档;只在宿主注入作用域读取器时出现)。- if (deps.getLaneScope) registerFeishuLaneTools(server, deps.getLaneScope);+ if (deps.getLaneScope) registerFeishuLaneTools(server, deps.getLaneScope, deps.prepareOutboundImage);return server;}diff --git a/packages/lizi-mcps/src/cindy_wechatMcpServer.ts b/packages/lizi-mcps/src/cindy_wechatMcpServer.tsindex 96173e7ebf..d6c96e1629 100644--- a/packages/lizi-mcps/src/cindy_wechatMcpServer.ts+++ b/packages/lizi-mcps/src/cindy_wechatMcpServer.ts@@ -5,11 +5,13 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';import type { WechatBotMcpHostDeps } from './types.js';+import { sendFileWithImagePreview, type PrepareOutboundImage } from './outboundImage.js';const MAX_MESSAGE_CHARS = 30_000;const MAX_DISPLAY_NAME_CHARS = 180;type WechatMcpDeps = WechatBotMcpHostDeps & {+ prepareOutboundImage?: PrepareOutboundImage;getPeerId: () => Promise<string | null> | string | null;workingDir?: string;};@@ -120,11 +122,11 @@ async function sendFileToUser(deps: WechatMcpDeps, args: Record<string, unknown>}try {- const sent = await deps.sendFile(peerId, safePath, parsed.data.displayName);+ const sent = await sendFileWithImagePreview(safePath, parsed.data.displayName, deps.prepareOutboundImage,+ (file, name) => deps.sendFile(peerId, file, name));if (sent.ok) {return result({- ok: true,- messageId: sent.messageId,+ ...sent,sent: {displayName: parsed.data.displayName ?? path.basename(safePath),},diff --git a/packages/lizi-mcps/src/index.ts b/packages/lizi-mcps/src/index.tsindex dfce342bad..1cec32a348 100644--- a/packages/lizi-mcps/src/index.ts+++ b/packages/lizi-mcps/src/index.ts@@ -10,6 +10,7 @@ export const VERSION = '0.0.0';export * from './types.js';export * from './providers.js';+export * from './outboundImage.js';export type { ToolCallAuthorization, ToolCallAuthorizer } from './tool-call-authority.js';// feishu/ OpenAPI MCP 模块已于 2026-07-22 整体退役:能力早已迁入插件diff --git a/packages/lizi-mcps/src/outboundImage.ts b/packages/lizi-mcps/src/outboundImage.tsnew file mode 100644index 0000000000..df22f5b55f--- /dev/null+++ b/packages/lizi-mcps/src/outboundImage.ts@@ -0,0 +1,38 @@+import path from 'node:path';++/** Host-owned snapshot: the channel and chat must use the same image bytes. */+export interface PreparedOutboundImage {+ path: string;+ url?: string;+ errorCode?: string;+ assertCurrent?: () => void;+}++export type PrepareOutboundImage = (sourcePath: string) => Promise<PreparedOutboundImage>;++/** Add the existing chat media contract to a file-send tool's own receipt. */+export async function sendFileWithImagePreview<T extends { ok: boolean }>(+ sourcePath: string,+ displayName: string | undefined,+ prepare: PrepareOutboundImage | undefined,+ send: (filePath: string, name?: string) => Promise<T>,+): Promise<T & { xdt_image_urls?: string[]; _xdt_forward_media?: false; imagePreviewError?: string }> {+ let image: PreparedOutboundImage;+ try {+ image = await prepare?.(sourcePath) ?? { path: sourcePath };+ } catch {+ // Preview preparation must not turn a working channel send into a failure.+ image = { path: sourcePath, errorCode: 'IMAGE_PREVIEW_UNAVAILABLE' };+ }+ image.assertCurrent?.();+ const sent = await send(image.path, displayName ?? (image.path !== sourcePath ? path.basename(sourcePath) : undefined));+ return {+ ...sent,+ ...(sent.ok && image.url ? {+ xdt_image_urls: [image.url],+ // The tool already sent this image. Only surface it in Cindy's chat.+ _xdt_forward_media: false as const,+ } : {}),+ ...(sent.ok && image.errorCode ? { imagePreviewError: image.errorCode } : {}),+ };+}diff --git a/packages/lizi-mcps/src/providers.ts b/packages/lizi-mcps/src/providers.tsindex cd7cc42a0b..e6d9692f4e 100644--- a/packages/lizi-mcps/src/providers.ts+++ b/packages/lizi-mcps/src/providers.ts@@ -30,12 +30,15 @@ import { createBrowserMcpServer } from './browser/index.js';import { createComputerMcpServer } from './computer/index.js';import { createAndroidMcpServer } from './android/index.js';import { resolveLiziMcpSessionContext } from './session-context.js';+import type { PreparedOutboundImage } from './outboundImage.js';export interface CreateLiziMcpProvidersOptions {/*** Optional allow-list. Omit to enable every MCP whose deps were supplied.*/enabled?: readonly LiziMcpId[];+ /** Optional host image snapshot for outbound tools; resolve the caller per invocation. */+ prepareOutboundImage?: (path: string, context: LiziMcpSessionContext) => Promise<PreparedOutboundImage>;android?: AndroidMcpDeps;/** Browser automation tools. Host injects the neutral runtime implementation. */browser?: BrowserMcpDeps;@@ -252,6 +255,9 @@ export function createLiziMcpProviders(type: 'sdk',name: 'cindy_feishu_bot',instance: createFeishuBotMcpServer({+ prepareOutboundImage: opts.prepareOutboundImage+ ? (path) => opts.prepareOutboundImage!(path, resolveLiziMcpSessionContext(ctx))+ : undefined,// 每个 host dep 都带上当前 tool-call 的 session:宿主据此选出这一轮真正要// 出站的 bot(个人设置页那份,或触发本轮的伙伴自有连接)。getChatId: async () => {@@ -291,6 +297,9 @@ export function createLiziMcpProviders(name: 'cindy_wechat',instance: createWechatMcpServer({...opts.wechatBot!,+ prepareOutboundImage: opts.prepareOutboundImage+ ? (path) => opts.prepareOutboundImage!(path, resolveLiziMcpSessionContext(ctx))+ : undefined,getPeerId: async () => {const current = resolveLiziMcpSessionContext(ctx);return (