Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(media): preserve fallback and gate path reveal
liugaoweib382a931feb7
diff --git a/apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.ts b/apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.tsindex 7f922ab182..0ac817cfd7 100644--- a/apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.ts+++ b/apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.ts@@ -25,12 +25,19 @@ import { createDesktopOnlyConfirmationRequestId } from './desktopOnlyConfirmatio/*** 过户通道:attachments = 媒体文件进总仓;dir = 上行读票据;save_dir = 下行- * 写票据;fs_write = fs 槽写 workdir 文件(会话 permission 为逐条确认档时,+ * 写票据;reveal_path = 把 Host 已安全解析的单个媒体仓路径返回给当前 Agent;+ * fs_write = fs 槽写 workdir 文件(会话 permission 为逐条确认档时,* 意识每次写入前弹卡;同目录本会话批一次,记忆在 fsSlot);workspace =* workspace 槽在会话 workdir 外的目录下创建/复用会话入口(2026-07-25,* 不过户字节,只授权"以此目录为工作区建会话")。*/-export type GhostGrantLane = 'attachments' | 'dir' | 'save_dir' | 'fs_write' | 'workspace';+export type GhostGrantLane =+ | 'attachments'+ | 'dir'+ | 'save_dir'+ | 'reveal_path'+ | 'fs_write'+ | 'workspace';/** 确认卡上逐条展示的过户对象(路径/大小让用户看清自己在授权什么)。 */export interface GhostGrantFileItem {diff --git a/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts b/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.tsindex 7780896148..356908f920 100644--- a/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts+++ b/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts@@ -311,9 +311,9 @@ describe('Cindy Core media invocation state and security boundary', () => {expect(result).toMatchObject({ok: true,status: 'complete',- _xdt_render_image: false,});expect(String(result.hint)).toContain('只嵌入展示一次');+ expect(result).not.toHaveProperty('_xdt_render_image');const [, init] = mocks.outboundFetch.mock.calls[0];expect(mocks.outboundFetch.mock.calls[0][0]).toBe('https://gateway.example.com/images/generations',@@ -326,7 +326,6 @@ 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);diff --git a/apps/desktop/src/main/cindy-media/invocationService.ts b/apps/desktop/src/main/cindy-media/invocationService.tsindex e5a73525c6..105890e945 100644--- a/apps/desktop/src/main/cindy-media/invocationService.ts+++ b/apps/desktop/src/main/cindy-media/invocationService.ts@@ -911,14 +911,11 @@ function completedInvocationResult(invocation: StoredMediaInvocation): Record<stif (!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+ ...(invocation.capability === 'image.generate' || invocation.capability === 'image.edit'? {- _xdt_render_image: false,- hint: '图片不会从工具结果自动重复渲染;请在最终回复中使用返回的 cindy-media:// 地址只嵌入展示一次。',+ hint: '请在最终回复中使用返回的 cindy-media:// 地址只嵌入展示一次;若未嵌入,客户端会用工具结果兜底展示。',}: {}),ok: true,diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.tsindex 79a8c152bf..10fa4a3e1e 100644--- a/apps/desktop/src/main/im/shared/turnRunner.ts+++ b/apps/desktop/src/main/im/shared/turnRunner.ts@@ -2152,9 +2152,8 @@ export function createTurnRunner(* 投递给 streaming handle, 让 finalize 时跟文本里的 markdown 图一起* upload + 拼到卡片上。*- * 这是未采用 Agent 正文内联语义的媒体工具结果旁路。Core 图片结果会用- * `_xdt_render_image:false` 关闭此旁路,由 Agent 最终回复中的 markdown 图片- * 走 materializeTurnLocalImages 送达,避免桌面和 IM 都出现重复图片。+ * 这是媒体工具结果的可靠兜底。Agent 最终回复若也用 markdown 引用了同一张图,+ * materializeTurnLocalImages 会按真实路径去重并清理正文引用,渠道最终只发一份。*/function handleToolResultFullEvent(turn: TurnState, event: AgentEvent): void {const data = event.data as { fullText?: unknown } | null;diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.tsindex e188774de6..a252ffebcb 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts@@ -394,6 +394,7 @@ beforeEach(() => {saveDepositMock.mockClear();liveGrantStateMock.mockReset();liveGrantStateMock.mockReturnValue({ permissionMode: 'auto', remoteHostId: null });+ callCindyMediaMock.mockReset();alsSessionContextMock.mockReset();logWarnMock.mockClear();logInfoMock.mockClear();@@ -1225,6 +1226,67 @@ describe('session-context 宿主铸造', () => {});});+describe('Cindy media 本机路径揭示', () => {+ it('只在用户点击允许后把已解析路径返回给 Agent', async () => {+ const url = `cindy-media://blobs/${'a'.repeat(64)}.png`;+ callCindyMediaMock.mockResolvedValue({+ ok: true,+ url,+ local_path: process.execPath,+ mime_type: 'image/png',+ });++ const result = await makeDeps('codex', 'media-path').callMedia?.({+ action: 'resolve_local_path',+ url,+ });++ expect(confirmRequestMock).toHaveBeenCalledWith(+ 'media-path',+ expect.objectContaining({+ ghostId: 'cindy-media',+ ghostName: 'Cindy Media',+ lane: 'reveal_path',+ items: [+ expect.objectContaining({+ absPath: process.execPath,+ mimeType: 'image/png',+ }),+ ],+ }),+ );+ expect(result).toMatchObject({ ok: true, local_path: process.execPath });+ });++ it('用户拒绝或调用缺少会话语境时不把路径放进工具结果', async () => {+ const url = `cindy-media://blobs/${'b'.repeat(64)}.png`;+ callCindyMediaMock.mockResolvedValue({+ ok: true,+ url,+ local_path: process.execPath,+ mime_type: 'image/png',+ });+ confirmRequestMock.mockResolvedValueOnce({ confirmed: false, allowDirs: false });++ const denied = await makeDeps('claude-code', 'media-path-denied').callMedia?.({+ action: 'resolve_local_path',+ url,+ });+ expect(denied).toMatchObject({ ok: false, errorCode: 'LOCAL_PATH_REVEAL_DENIED' });+ expect(denied).not.toHaveProperty('local_path');++ const noSession = await makeDeps('claude-code', null).callMedia?.({+ action: 'resolve_local_path',+ url,+ });+ expect(noSession).toMatchObject({+ ok: false,+ errorCode: 'LOCAL_PATH_REVEAL_CONFIRM_UNAVAILABLE',+ });+ expect(noSession).not.toHaveProperty('local_path');+ });+});+describe('Full Access 插件文件交接', () => {it.each<TestAgentKind>(['claude-code', 'codex', 'pi'])('%s 的 bypassPermissions 对 workdir 外 dir 自动放行',diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.tsindex 286adb8252..26967cb6d5 100644--- a/apps/desktop/src/main/mcp-integrations/ghost.ts+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts@@ -438,6 +438,66 @@ async function requestGrantConfirm(params: {};}+/**+ * 媒体仓路径揭示必须由 Host-owned 点击确认授权。用户是否在正文里“明确问过”+ * 只能指导 Agent 何时发起,不能作为安全边界;模型本身无法代替用户点按钮。+ */+async function requestMediaPathRevealConfirm(params: {+ sessionId: string | null;+ absPath: string;+ mimeType: string;+}): Promise<{ ok: true } | { ok: false; errorCode: string; message: string }> {+ if (!params.sessionId) {+ return {+ ok: false,+ errorCode: 'LOCAL_PATH_REVEAL_CONFIRM_UNAVAILABLE',+ message: '当前调用没有会话语境,无法让用户确认是否把本机路径返回给 Agent',+ };+ }+ const bridge = getGhostGrantConfirmBridge();+ if (!bridge) {+ return {+ ok: false,+ errorCode: 'LOCAL_PATH_REVEAL_CONFIRM_UNAVAILABLE',+ message: '本机路径确认通道未就绪,请稍后重试',+ };+ }+ let size: number;+ try {+ const stat = fs.statSync(params.absPath);+ if (!stat.isFile()) throw new Error('not a file');+ size = stat.size;+ } catch {+ return {+ ok: false,+ errorCode: 'MEDIA_FILE_NOT_FOUND',+ message: '该受管媒体文件在确认前已不存在',+ };+ }+ const decision = await bridge.request(params.sessionId, {+ ghostId: 'cindy-media',+ ghostName: 'Cindy Media',+ lane: 'reveal_path',+ items: [+ {+ name: path.basename(params.absPath),+ absPath: params.absPath,+ size,+ mimeType: params.mimeType,+ },+ ],+ });+ if (decision.confirmed) return { ok: true };+ return {+ ok: false,+ errorCode: 'LOCAL_PATH_REVEAL_DENIED',+ message:+ decision.reason === 'timeout'+ ? '本机路径确认超时,本次调用已取消;如仍需要,请提醒用户后重试'+ : '用户未允许把本机路径返回给 Agent,不要重试',+ };+}+/*** attachments 的「任意本地路径」预处理:原有三层解析不命中、但输入是真实* 存在的本地媒体文件路径时,按两层策略放行(workdir 内直通记 tool、外部@@ -1254,7 +1314,24 @@ export function getCindyGhostsMcpDeps(callMedia: async (request) => {const result = await callCindyMedia(request);const sessionId = resolveSessionContext()?.sessionId;- if (result.ok !== false && sessionId) {+ if (request.action === 'resolve_local_path' && result.ok !== false) {+ const localPath = typeof result.local_path === 'string' ? result.local_path : '';+ const mimeType = typeof result.mime_type === 'string' ? result.mime_type : '';+ if (!localPath || !mimeType) {+ return {+ ok: false,+ errorCode: 'INTERNAL',+ message: '媒体路径解析结果缺少必要字段',+ };+ }+ const confirmed = await requestMediaPathRevealConfirm({+ sessionId: sessionId ?? null,+ absPath: localPath,+ mimeType,+ });+ if (!confirmed.ok) return confirmed;+ }+ if (request.action !== 'resolve_local_path' && result.ok !== false && sessionId) {// Core 结果返回给当前 Agent 前先同步挂到本会话。后续消息落库钩子仍会// 幂等补账,但不能依赖那个异步时序:Agent 可能紧接着通过// ghost_call.attachments 把结果交给插件。diff --git a/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts b/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.tsindex 30c0bc5886..243694b09f 100644--- a/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts+++ b/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts@@ -1056,6 +1056,38 @@ describe('buildRenderItems — key stability', () => {expect(seg?.key).not.toBe(media?.key);});+ it('uses tool media as fallback and suppresses it only for an inline image in the same turn', () => {+ const url = 'cindy-media://blobs/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.png';+ const firstTool = mkTool('img1', 'image_generate');+ const firstResult = mkResult(+ 'imgr1',+ 'tu-img1',+ JSON.stringify({ xdt_image_url: url }),+ );+ const secondTool = mkTool('img2', 'image_generate');+ const secondResult = mkResult(+ 'imgr2',+ 'tu-img2',+ JSON.stringify({ xdt_image_url: url }),+ );+ const { items } = buildRenderItems([+ mkUser('u1'),+ firstTool,+ firstResult,+ mkAssistant('a1', ``),+ mkUser('u2'),+ secondTool,+ secondResult,+ // 纯文本 URI 不是图片展示,不能压掉可靠兜底;上一轮的 Markdown 也不能跨轮去重。+ mkAssistant('a2', `文件地址:${url}`),+ ]);++ const mediaKeys = items+ .filter((item): item is Extract<RenderItem, { type: 'tool_media' }> => item.type === 'tool_media')+ .map((item) => item.key);+ expect(mediaKeys).toEqual(['media-img2']);+ });+// ── case 7: 末尾混合丢弃类型 + 有效 message,末尾仍是有效 item ──────────// 锁住"删自愈 effect 安全"的论证:渲染窗口下移到 item 轴后,allRenderItems// 末尾永远是有效 item,U2 "末尾窗口全 orphan / 全被丢弃" 死锁不可能复现。diff --git a/apps/desktop/src/renderer/__tests__/markdownMathRendering.test.ts b/apps/desktop/src/renderer/__tests__/markdownMathRendering.test.tsindex 818f405614..5e8cfe4131 100644--- a/apps/desktop/src/renderer/__tests__/markdownMathRendering.test.ts+++ b/apps/desktop/src/renderer/__tests__/markdownMathRendering.test.ts@@ -148,9 +148,8 @@ describe('MarkdownRenderer — math 接线 source contract', () => {// 输入是流式修复层的输出(repairStreamingMarkdown,跟随 streamFade 总开关:// 关闭动效 / reduced-motion / 非流式时 repairedContent === throttledContent// 原引用,与动效引入前的渲染路径逐位一致)。- expect(source).toContain(- 'normalizeMathDelimiters(repairedContent, { preserveLineCount: emitSourceLines })',- );+ expect(source).toContain('normalizeMarkdownRendererContent(repairedContent, emitSourceLines)');+ expect(source).toContain('normalizeMathDelimiters(content, { preserveLineCount })');expect(source).toContain('streamFade ? repairStreamingMarkdown(throttledContent) : throttledContent',);diff --git a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsxindex 11210053c4..1bf99b28ff 100644--- a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx+++ b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx@@ -201,7 +201,7 @@ function isMermaidCodeChild(child: ReactNode): boolean {// remarkHtmlImages(<img> HTML → mdast image)与 remarkLocalPathLinks(正文裸路径// → link)。remarkSessionLinks 产出的 cindy:// 深链带 scheme,被它的判据跳过,// 顺序无关。-const REMARK_PLUGINS: PluggableList = [+export const REMARK_PLUGINS: PluggableList = [[remarkGfm, { singleTilde: false }],remarkCjkFriendly,remarkMath,@@ -211,7 +211,7 @@ const REMARK_PLUGINS: PluggableList = [remarkLocalPathLinks,remarkPreserveRawLocalDestinations,];-const REMARK_PLUGINS_PRIVILEGED: PluggableList = [+export const REMARK_PLUGINS_PRIVILEGED: PluggableList = [[remarkGfm, { singleTilde: false }],remarkCjkFriendly,remarkMath,@@ -242,6 +242,14 @@ const REHYPE_PLUGINS: PluggableList = [rehypeHighlight,rehypeFencedCodeMarker,];++/** MarkdownRenderer 与所有“实际是否渲染”判定共用的输入归一化。 */+export function normalizeMarkdownRendererContent(+ content: string,+ preserveLineCount = false,+): string {+ return normalizeMathDelimiters(content, { preserveLineCount });+}/*** 聊天正文里一切「可点」的行内元素共用这一套外观:**正文色 + 常显下划线**。*@@ -1668,7 +1676,7 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({[throttledContent, streamFade],);const renderedContent = useMemo(- () => normalizeMathDelimiters(repairedContent, { preserveLineCount: emitSourceLines }),+ () => normalizeMarkdownRendererContent(repairedContent, emitSourceLines),[repairedContent, emitSourceLines],);const streamingChunks = useMemo(diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex 3a18791e81..0e4dadbd50 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -46,6 +46,7 @@ import {isPlanUserBoundary,isSubagentParentToolUseId,} from '@cindy/maker-shared/message-render';+import { extractRenderedMarkdownImageTargets } from './markdownImageTargets';// 子代理卡判据只能有一份:此前桌面自带一份只认 Agent/Task/collab:* 的副本,新增 harness// (PI 的 subagent)加进共享判据也到不了 AgentTaskCard,会静默落进普通工具组(codex review)。import { isAgentTaskToolName } from '@cindy/maker-shared/agent-task';@@ -1518,6 +1519,32 @@ export function buildRenderItems(return allMessages.slice(start, end);};+ // Agent 最终正文中的 Markdown 图片是首选排版;tool_result 媒体仍保留为+ // 确定性兜底。只有同一真实 user turn 内确实嵌入了同一 URL,才压掉兜底卡。+ const inlineImageUrlsByTurnStart = new Map<number, ReadonlySet<string>>();+ const recordTurnInlineImages = (lo: number, hi: number): void => {+ if (hi <= lo) return;+ const urls = new Set<string>();+ for (const message of messages.slice(lo, hi)) {+ if (message.role !== 'assistant' || message.systemCardType || message.isStreaming) continue;+ for (const url of extractRenderedMarkdownImageTargets(message.content)) urls.add(url);+ }+ inlineImageUrlsByTurnStart.set(lo, urls);+ };+ let inlineTurnStart = 0;+ for (let index = 0; index <= messages.length; index += 1) {+ const message = messages[index];+ const isBoundary =+ message?.role === 'user' &&+ message.delivery !== 'steer' &&+ !message.isSyntheticTrigger;+ if (isBoundary && index > inlineTurnStart) {+ recordTurnInlineImages(inlineTurnStart, index);+ inlineTurnStart = index;+ }+ if (index === messages.length) recordTurnInlineImages(inlineTurnStart, index);+ }+// ── Pass 0: build toolUseId → tool_result.content lookup ──// Plan/task rendering and regular tool result pairing both need a stable// lookup by vendor toolUseId. Adjacency remains a fallback in Pass 2.@@ -1743,6 +1770,12 @@ export function buildRenderItems(for (const message of originalTurnSlice(lo, hi)) {if (message.role !== 'tool_result' || !isSubagentInternalMessage(message)) continue;for (const item of extractToolResultMedia(message.content)) {+ if (+ item.kind === 'image' &&+ inlineImageUrlsByTurnStart.get(lo)?.has(item.url)+ ) {+ continue;+ }if (seenMediaUrls.has(item.url)) continue;seenMediaUrls.add(item.url);hiddenMedia.push(item);@@ -1964,6 +1997,12 @@ export function buildRenderItems(// 提交消息被 rewind/异 ghost 伪锚)回退今日行为——本调用位置渲染。const collectResultMedia = (result: string): void => {let media = extractToolResultMedia(result);+ const inlineImageUrls = inlineImageUrlsByTurnStart.get(turnStartIdx);+ if (inlineImageUrls?.size) {+ media = media.filter(+ (item) => item.kind !== 'image' || !inlineImageUrls.has(item.url),+ );+ }if (media.length === 0) return;if (isGhostCallToolName(toolName)) {const anchor = extractAnchorCardId(result);diff --git a/apps/desktop/src/renderer/components/chat/__tests__/markdownImageTargets.test.ts b/apps/desktop/src/renderer/components/chat/__tests__/markdownImageTargets.test.tsnew file mode 100644index 0000000000..dd91badefe--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/__tests__/markdownImageTargets.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from 'vitest';+import { extractRenderedMarkdownImageTargets } from '../markdownImageTargets';++describe('extractRenderedMarkdownImageTargets', () => {+ it('collects rendered images and ignores Markdown literals that render as code or raw HTML', () => {+ const url = 'cindy-media://blobs/abc.png';+ expect(+ extractRenderedMarkdownImageTargets([+ ``,+ ``,+ '',+ `\`<!--\` `,+ `\`\``,+ '`multiline code',+ ``,+ '`',+ `$$`,+ `\\(\\)`,+ `\\[\\]`,+ `\\`,+ '<!--',+ ``,+ '-->',+ '```md',+ ``,+ '```',+ ` `,+ '',+ '<div>',+ ``,+ '</div>',+ '',+ '<script>',+ '',+ ``,+ '',+ '</script>',+ '',+ `<img src="${url}/raw-img" alt="raw">`,+ ].join('\n')),+ ).toEqual([url, `${url}/after-inline-code`, `${url}/raw-img`]);+ });+});diff --git a/apps/desktop/src/renderer/components/chat/markdownImageTargets.ts b/apps/desktop/src/renderer/components/chat/markdownImageTargets.tsnew file mode 100644index 0000000000..b2159df1df--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/markdownImageTargets.ts@@ -0,0 +1,28 @@+import type { Image, Root } from 'mdast';+import remarkParse from 'remark-parse';+import { unified } from 'unified';+import { visit } from 'unist-util-visit';+import {+ normalizeMarkdownRendererContent,+ REMARK_PLUGINS_PRIVILEGED,+} from './MarkdownRenderer';++const markdownImageParser = unified()+ .use(remarkParse)+ .use(REMARK_PLUGINS_PRIVILEGED);++/** 与 MarkdownRenderer 同源解析,只返回实际会进入 img renderer 的图片地址。 */+export function extractRenderedMarkdownImageTargets(markdown: string): string[] {+ if (!markdown.includes('![') && !/<img/i.test(markdown)) return [];++ const normalized = normalizeMarkdownRendererContent(markdown);+ const tree = markdownImageParser.runSync(markdownImageParser.parse(normalized)) as Root;+ const urls: string[] = [];+ const seen = new Set<string>();+ visit(tree, 'image', (node: Image) => {+ if (!node.url || seen.has(node.url)) return;+ seen.add(node.url);+ urls.push(node.url);+ });+ return urls;+}diff --git a/apps/desktop/src/renderer/features/cc-agent/GhostGrantConfirmCard.tsx b/apps/desktop/src/renderer/features/cc-agent/GhostGrantConfirmCard.tsxindex adffa5f6ca..53a3e85724 100644--- a/apps/desktop/src/renderer/features/cc-agent/GhostGrantConfirmCard.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/GhostGrantConfirmCard.tsx@@ -66,11 +66,13 @@ export function GhostGrantConfirmCard({ pending, onRespond }: GhostGrantConfirmC? 'ghostGrant.confirm.descriptionAttachments': pending.lane === 'dir'? 'ghostGrant.confirm.descriptionDir'- : pending.lane === 'fs_write'- ? 'ghostGrant.confirm.descriptionFsWrite'- : pending.lane === 'workspace'- ? 'ghostGrant.confirm.descriptionWorkspace'- : 'ghostGrant.confirm.descriptionSaveDir';+ : pending.lane === 'reveal_path'+ ? 'ghostGrant.confirm.descriptionRevealPath'+ : pending.lane === 'fs_write'+ ? 'ghostGrant.confirm.descriptionFsWrite'+ : pending.lane === 'workspace'+ ? 'ghostGrant.confirm.descriptionWorkspace'+ : 'ghostGrant.confirm.descriptionSaveDir';return (<div@@ -82,7 +84,12 @@ export function GhostGrantConfirmCard({ pending, onRespond }: GhostGrantConfirmC<div className="flex items-start justify-between gap-3"><div><p className="text-15 font-semibold leading-tight text-[var(--chat-input-text)]">- {t('ghostGrant.confirm.title', { name: pending.ghostName })}+ {t(+ pending.lane === 'reveal_path'+ ? 'ghostGrant.confirm.titleRevealPath'+ : 'ghostGrant.confirm.title',+ { name: pending.ghostName },+ )}</p><p className="mt-1 text-12 leading-relaxed text-[var(--status-bar-meta)]">{t(descriptionKey)}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex d39b6a1f45..701bef6a6b 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -9727,10 +9727,12 @@"ghostGrant": {"confirm": {"title": "“{{name}}” requests access to your files",+ "titleRevealPath": "Allow the Agent to receive this media file's local path?","count": "{{count}} files","descriptionAttachments": "The files below are outside this session's working directory. If you allow, they will be handed to this plugin (it only receives content fingerprints, never paths).","descriptionDir": "The directory/file below is outside this session's working directory. If you allow, its files will be handed to this plugin for upload (it only receives a one-time ticket, never paths).","descriptionSaveDir": "The directory below is outside this session's working directory. If you allow, this plugin can save downloaded files into it (existing files are never overwritten).",+ "descriptionRevealPath": "The path is returned to the current Agent only after you allow it and will enter the conversation record; paired devices may sync that record. This does not grant any plugin access to the file.","descriptionFsWrite": "This plugin requests to write the files below into the current session's working directory. If you allow, further writes to the same directory in this session won't ask again.","descriptionWorkspace": "This folder is outside this session's working directory. If you allow, Cindy creates an empty session for it in the sidebar (an existing session is reused) without reading any files inside.","dirMeta": "{{count}} files · {{size}}",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 06de50cac3..c29e2a796d 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -9714,10 +9714,12 @@"ghostGrant": {"confirm": {"title": "「{{name}}」がファイルへのアクセスを要求しています",+ "titleRevealPath": "このメディアファイルのローカルパスを Agent に渡しますか?","count": "{{count}} 個のファイル","descriptionAttachments": "以下のファイルは現在のセッションの作業ディレクトリの外にあります。許可すると、このプラグインに渡されます(渡されるのはコンテンツのフィンガープリントのみで、パスは渡されません)。","descriptionDir": "以下のディレクトリ/ファイルは現在のセッションの作業ディレクトリの外にあります。許可すると、その中のファイルがアップロード用にこのプラグインへ渡されます(渡されるのはワンタイムチケットのみで、パスは渡されません)。","descriptionSaveDir": "以下のディレクトリは現在のセッションの作業ディレクトリの外にあります。許可すると、このプラグインがダウンロードしたファイルをここに保存できます(既存ファイルは上書きされません)。",+ "descriptionRevealPath": "このパスは許可後にのみ現在の Agent へ返され、会話履歴に入ります。ペアリング済みデバイスにも同期される場合があります。この操作によってプラグインへファイルの読み取り権限が付与されることはありません。","descriptionFsWrite": "このプラグインは現在のセッションの作業ディレクトリに以下のファイルを書き込もうとしています。許可すると、このセッション中は同じディレクトリへの書き込みは再確認されません。","descriptionWorkspace": "このフォルダは現在のセッションの作業ディレクトリの外にあります。許可すると、Cindy がこのフォルダを作業ディレクトリとする空のセッションをサイドバーに作成します(既にセッションがある場合は再利用)。中のファイルは読み取りません。","dirMeta": "{{count}} 個のファイル · {{size}}",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 271ec38024..3afc556270 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -9714,10 +9714,12 @@"ghostGrant": {"confirm": {"title": "“{{name}}”이(가) 파일 접근을 요청합니다",+ "titleRevealPath": "이 미디어 파일의 로컬 경로를 Agent에 전달할까요?","count": "파일 {{count}}개","descriptionAttachments": "아래 파일은 현재 세션의 작업 디렉터리 밖에 있습니다. 허용하면 이 플러그인에 전달됩니다(콘텐츠 지문만 전달되며 경로는 전달되지 않습니다).","descriptionDir": "아래 디렉터리/파일은 현재 세션의 작업 디렉터리 밖에 있습니다. 허용하면 그 안의 파일이 업로드를 위해 이 플러그인에 전달됩니다(일회용 티켓만 전달되며 경로는 전달되지 않습니다).","descriptionSaveDir": "아래 디렉터리는 현재 세션의 작업 디렉터리 밖에 있습니다. 허용하면 이 플러그인이 다운로드한 파일을 여기에 저장할 수 있습니다(기존 파일은 덮어쓰지 않습니다).",+ "descriptionRevealPath": "이 경로는 허용한 뒤에만 현재 Agent로 반환되며 대화 기록에 남습니다. 페어링된 기기에도 해당 기록이 동기화될 수 있습니다. 이 작업은 플러그인에 파일 읽기 권한을 부여하지 않습니다.","descriptionFsWrite": "이 플러그인이 현재 세션의 작업 디렉터리에 아래 파일을 쓰려고 합니다. 허용하면 이 세션 동안 같은 디렉터리에 대한 이후 쓰기는 다시 묻지 않습니다.","descriptionWorkspace": "이 폴더는 현재 세션의 작업 디렉터리 밖에 있습니다. 허용하면 Cindy가 이 폴더를 작업 디렉터리로 하는 빈 세션을 사이드바에 만듭니다(이미 세션이 있으면 재사용). 폴더 안의 파일은 읽지 않습니다.","dirMeta": "파일 {{count}}개 · {{size}}",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex b8ff79a4a9..337acb7583 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -9706,10 +9706,12 @@"ghostGrant": {"confirm": {"title": "「{{name}}」请求使用你的文件",+ "titleRevealPath": "允许 Agent 获取这个媒体文件的本机路径?","count": "{{count}} 个文件","descriptionAttachments": "以下文件在当前任务的工作目录之外。允许后,这些文件会交给该插件处理(它只拿到内容指纹,拿不到路径)。","descriptionDir": "以下目录/文件在当前任务的工作目录之外。允许后,其中的文件会交给该插件上传(它只拿到一次性票据,拿不到路径)。","descriptionSaveDir": "以下目录在当前任务的工作目录之外。允许后,该插件可以把下载的文件存入其中(不会覆盖已有文件)。",+ "descriptionRevealPath": "该路径只会在你允许后返回给当前 Agent,并进入会话记录;配对设备可能同步到这条记录。此操作不授予插件读取文件的权限。","descriptionFsWrite": "该插件请求在当前任务的工作目录写入以下文件。允许后,本任务内它写同一目录不再询问。","descriptionWorkspace": "该文件夹在当前任务的工作目录之外。允许后,Cindy 会以它为工作目录在侧边栏创建一个空任务(已有任务时直接复用),不会读取其中的文件。","dirMeta": "{{count}} 个文件 · {{size}}",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex cbde914e0a..3eb49f529e 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -9706,10 +9706,12 @@"ghostGrant": {"confirm": {"title": "「{{name}}」請求使用你的檔案",+ "titleRevealPath": "允許 Agent 取得這個媒體檔案的本機路徑?","count": "{{count}} 個檔案","descriptionAttachments": "以下檔案在當前任務的工作目錄之外。允許後,這些檔案會交給該插件處理(它只拿到內容指紋,拿不到路徑)。","descriptionDir": "以下目錄/檔案在當前任務的工作目錄之外。允許後,其中的檔案會交給該插件上傳(它只拿到一次性票據,拿不到路徑)。","descriptionSaveDir": "以下目錄在當前任務的工作目錄之外。允許後,該插件可以把下載的檔案存入其中(不會覆蓋已有檔案)。",+ "descriptionRevealPath": "該路徑只會在你允許後回傳給目前 Agent,並進入對話記錄;配對裝置可能同步該記錄。此操作不授予插件讀取檔案的權限。","descriptionFsWrite": "該插件請求在當前任務的工作目錄寫入以下檔案。允許後,本任務內它寫同一目錄不再詢問。","descriptionWorkspace": "該資料夾在當前任務的工作目錄之外。允許後,Cindy 會以它為工作目錄在側邊欄建立一個空任務(已有任務時直接複用),不會讀取其中的檔案。","dirMeta": "{{count}} 個檔案 · {{size}}",diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 12f16c1b1a..3eb782933d 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -809,11 +809,12 @@ export interface PendingGhostGrantConfirm {ghostName: string;/*** attachments = 媒体文件交给意识;dir = 上传目录/文件;save_dir = 允许意识- * 往目录里存文件;fs_write = 意识申请写工作目录文件(会话 permission 为+ * 往目录里存文件;reveal_path = 允许当前 Agent 获得单个媒体仓本机路径;+ * fs_write = 意识申请写工作目录文件(会话 permission 为* 逐条确认档时逐次弹,同目录本会话批一次);workspace = 意识申请以该目录* 为工作区在侧边栏创建/复用会话入口(不过户字节)。*/- lane: 'attachments' | 'dir' | 'save_dir' | 'fs_write' | 'workspace';+ lane: 'attachments' | 'dir' | 'save_dir' | 'reveal_path' | 'fs_write' | 'workspace';items: Array<{name: string;absPath: string;@@ -14126,6 +14127,7 @@ function parseGhostGrantConfirmRequest(request: {lane !== 'attachments' &&lane !== 'dir' &&lane !== 'save_dir' &&+ lane !== 'reveal_path' &&lane !== 'fs_write' &&lane !== 'workspace')diff --git a/apps/mobile/src/__tests__/messageNormalize.test.ts b/apps/mobile/src/__tests__/messageNormalize.test.tsindex 9159dddc17..b14cdb112a 100644--- a/apps/mobile/src/__tests__/messageNormalize.test.ts+++ b/apps/mobile/src/__tests__/messageNormalize.test.ts@@ -664,6 +664,64 @@ describe('normalizeRemoteMessages', () => {]);});+ it('keeps tool image fallback unless the same turn embeds that URL as Markdown', () => {+ const url = `cindy-media://blobs/${'a'.repeat(64)}.png`;+ const items = normalizeRemoteMessages([+ message({ id: 'u1', role: 'user', content: 'draw one', createdAt: '2026-01-01T00:00:01.000Z' }),+ message({+ id: 'tool-1',+ role: 'tool_use',+ toolUseId: 'tu-1',+ content: { toolUseId: 'tu-1', toolName: 'image_generate', input: {} },+ createdAt: '2026-01-01T00:00:02.000Z',+ }),+ message({+ id: 'result-1',+ role: 'tool_result',+ toolUseId: 'tu-1',+ content: JSON.stringify({ xdt_image_url: url }),+ createdAt: '2026-01-01T00:00:03.000Z',+ }),+ message({+ id: 'steer-1',+ role: 'user',+ content: 'make it warmer',+ agentMeta: { delivery: 'steer' },+ createdAt: '2026-01-01T00:00:03.500Z',+ }),+ message({+ id: 'a1',+ role: 'assistant',+ content: ``,+ createdAt: '2026-01-01T00:00:04.000Z',+ }),+ message({ id: 'u2', role: 'user', content: 'draw again', createdAt: '2026-01-01T00:00:05.000Z' }),+ message({+ id: 'tool-2',+ role: 'tool_use',+ toolUseId: 'tu-2',+ content: { toolUseId: 'tu-2', toolName: 'image_generate', input: {} },+ createdAt: '2026-01-01T00:00:06.000Z',+ }),+ message({+ id: 'result-2',+ role: 'tool_result',+ toolUseId: 'tu-2',+ content: JSON.stringify({ xdt_image_url: url }),+ createdAt: '2026-01-01T00:00:07.000Z',+ }),+ message({+ id: 'a2',+ role: 'assistant',+ content: `文件地址:${url}`,+ createdAt: '2026-01-01T00:00:08.000Z',+ }),+ ]);++ expect(items.find((item) => item.source.id === 'tool-1')?.media).toEqual([]);+ expect(items.find((item) => item.source.id === 'tool-2')?.media).toMatchObject([{ url }]);+ });+it('keeps desktop media action metadata as mobile read-only actions', () => {const items = normalizeRemoteMessages([message({diff --git a/apps/mobile/src/session/messageNormalize.ts b/apps/mobile/src/session/messageNormalize.tsindex 48806f689c..e5427402e0 100644--- a/apps/mobile/src/session/messageNormalize.ts+++ b/apps/mobile/src/session/messageNormalize.ts@@ -11,6 +11,7 @@ import {type MessageNormalizeToolUse,type MessageToolResultPairing,} from '@cindy/maker-shared/message-normalize';+import { collectMobileMarkdownImages } from '@/session/messageMarkdown';import {normalizeAgentTaskTerminalStatus,type AgentTaskTerminalStatus,@@ -416,9 +417,48 @@ export function normalizeRemoteMessages(messages: readonly RemoteMessage[]): Nor});}+ dedupeToolImagesAgainstAssistantMarkdown(result);return result;}+/**+ * 与 Desktop 同口径:Agent 正文内联同一 URL 时由正文负责排版;否则保留+ * tool_result 图片作为可靠兜底。只在同一真实 user turn 内去重。+ */+function dedupeToolImagesAgainstAssistantMarkdown(+ messages: NormalizedRemoteMessage[],+): void {+ const dedupeTurn = (lo: number, hi: number): void => {+ if (hi <= lo) return;+ const inlineUrls = new Set<string>();+ for (const message of messages.slice(lo, hi)) {+ if (message.kind !== 'assistant') continue;+ for (const image of collectMobileMarkdownImages(message.body)) inlineUrls.add(image.url);+ }+ if (inlineUrls.size === 0) return;+ for (const message of messages.slice(lo, hi)) {+ if (message.kind !== 'tool' || !message.media?.length) continue;+ message.media = message.media.filter(+ (item) => item.kind !== 'image' || !inlineUrls.has(item.url),+ );+ }+ };++ let turnStart = 0;+ for (let index = 0; index <= messages.length; index += 1) {+ const message = messages[index];+ const isBoundary =+ message?.kind === 'user' &&+ !message.isSyntheticTrigger &&+ message.source.agentMeta?.delivery !== 'steer';+ if (isBoundary && index > turnStart) {+ dedupeTurn(turnStart, index);+ turnStart = index;+ }+ if (index === messages.length) dedupeTurn(turnStart, index);+ }+}+function toolResultContentToPreview(content: unknown): string {const compacted = parseToolResultCompactionMarker(content);if (!compacted) return contentToPreview(content);diff --git a/docs/dev-rules/media-storage-and-protocols.md b/docs/dev-rules/media-storage-and-protocols.mdindex f9d308cf20..76621a3f86 100644--- a/docs/dev-rules/media-storage-and-protocols.md+++ b/docs/dev-rules/media-storage-and-protocols.md@@ -53,8 +53,12 @@- `cindy-media://` 的 scheme privilege 和 handler 只在现有集中入口注册。不要为单一功能新增媒体协议;确需改变协议能力时,同时按 Electron 安全规则审查 CSP、fetch、Range、路径校验和 Renderer 暴露面。-- 不把媒体仓绝对路径直接暴露给 Renderer、插件或远端。跨边界传递使用托管 URL、受控- grant/deposit/ledger,或已有上传与远程媒体服务。+- 默认不把媒体仓绝对路径直接暴露给 Renderer、插件或远端。跨边界传递使用托管 URL、+ 受控 grant/deposit/ledger,或已有上传与远程媒体服务。+- 唯一的路径揭示例外是:用户明确询问某个受管媒体地址在本机的存储位置时,Host 先用+ 安全解析器核验为现存普通文件,再通过 Host-owned 确认卡展示精确单文件路径;只有用户+ 点击允许后,路径才可返回当前 Agent 并进入会话记录(因此也可能同步到用户的配对设备)。+ 提示词或 Agent 自报“用户已同意”不能替代该确认,也不能借此给插件或远端开放文件读取。- `xdt-image://`、`xdt-video://`、`xdt-model://` 和 `userData/cc-agent/` 是冻结的历史兼容层。可以读取已有地址,不得新增写入路径、扩展生命周期或把新功能接回旧仓。- 删除或清理历史目录必须走已有的显式名单、复验和用户确认流程;不得新增任意diff --git a/packages/cindy-tools/src/ghost/mcpServer.ts b/packages/cindy-tools/src/ghost/mcpServer.tsindex c705fe4525..1fa209ac12 100644--- a/packages/cindy-tools/src/ghost/mcpServer.ts+++ b/packages/cindy-tools/src/ghost/mcpServer.ts@@ -102,7 +102,7 @@ const D_MEDIA = ["插件已返回用户配置的 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;不要猜路径或扫描磁盘。",+ "展示、改图和附件交接都直接使用 cindy-media:// / xdt-image:// / xdt-video:// 受管地址,不需要本地路径。仅当用户明确询问文件存储位置或本地路径时,才调用 resolve_local_path 并原样传入 url;Host 会要求用户点击确认后才返回路径。不要猜路径或扫描磁盘。","模型 id、endpoint、Authorization 和 wire model 均由 Host 管理,不要写进 body,不要猜测或覆盖。","Guide 缺失、能力不匹配或当前客户端不支持协议时,结果会带稳定 errorCode、retryable、outcomeKnown 和 allowedActions;可按 allowedActions 换模型、改用其它已授权工具或仍存在的旧链路,不要把 INTERNAL 当成协议能力结论。","prepare 返回的 invocation_id 是一次性付费提交令牌;request 超时或返回 SUBMISSION_OUTCOME_UNKNOWN 时不要自动重提,以免重复扣费。",@@ -1302,7 +1302,7 @@ export function createCindyGhostsMcpServer(.string().max(4096).optional()- .describe("resolve_local_path 时必填;原样传入 cindy-media://、xdt-image:// 或 xdt-video:// 受管地址。仅在用户明确询问本地存储路径时使用"),+ .describe("resolve_local_path 时必填;原样传入 cindy-media://、xdt-image:// 或 xdt-video:// 受管地址。仅在用户明确询问本地存储路径时使用,Host 会要求用户点击确认"),invocation_id: z.string().max(128)