Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(plugin): 增加非阻塞 AI 图标预检 (#1514)
nanacocac094ec7fb0
diff --git a/apps/desktop/eslint.config.mjs b/apps/desktop/eslint.config.mjsindex 2082c6e426..541a16e2ae 100644--- a/apps/desktop/eslint.config.mjs+++ b/apps/desktop/eslint.config.mjs@@ -18,6 +18,7 @@ export default tseslint.config('src/main/localDb/**/*.{ts,tsx}','src/main/watcher-host/**/*.{ts,tsx}','src/main/workdir-probe-host/**/*.{ts,tsx}',+ 'src/main/mcp-integrations/forgeIconConversionHost.ts','src/main/cindy-brain/nodeRuntimeBroker.ts','src/main/__spike__/**/*.{ts,tsx}',],diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.tsindex 6e7acf9269..cedb601081 100644--- a/apps/desktop/forge.config.ts+++ b/apps/desktop/forge.config.ts@@ -1348,6 +1348,13 @@ const config: ForgeConfig = {// 大通讯录 JSON/gzip/crypto 隔离在线程中,避免阻塞 Electron main。target: 'preload',},+ {+ entry: 'src/main/mcp-integrations/forgeIconConversionProcess.ts',+ config: 'vite.forge-icon-conversion-process.config.ts',+ // Sharp/libvips 转换在一次性 utility process 中执行;超时可 kill,+ // 不把不可取消的 native 任务留在 Electron main。+ target: 'preload',+ },{entry: 'src/main/watcher-host/watcherHostProcess.ts',config: 'vite.watcher-host.config.ts',diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex b32e78c380..036ef5cb18 100644--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@ -7,6 +7,8 @@ import JSZip from 'jszip';import {GHOST_MANIFEST_FILE,GHOST_LOCALE_MAX_BYTES,+ GHOST_ICON_MAX_BYTES,+ GHOST_INSTALL_MANIFEST_MAX_BYTES,GHOST_SKILL_MD_MAX_BYTES,ghostLocalePathFor,ghostIconMimeType,@@ -34,12 +36,7 @@ import { checkSkillMdConsistency } from './skillSlot.js';export const MAX_BASIC_CINDY_FILE_BYTES = 8 * 1024 * 1024;export const MAX_NODE_CINDY_FILE_BYTES = 128 * 1024 * 1024;/** 身份卡本身只应是小 JSON;先限流读取,避免在识别包类型前被单文件撑爆内存。 */-const MAX_GHOST_MANIFEST_BYTES = 256 * 1024;-/**- * icon 文件大小上限。icon 以 data URL 形态随 ghosts:list(sendSync)下发,- * 上限同时保护装载与首帧同步 IPC 的载荷体积。- */-const MAX_GHOST_ICON_BYTES = 512 * 1024; // 512 KB+const MAX_GHOST_MANIFEST_BYTES = GHOST_INSTALL_MANIFEST_MAX_BYTES;/** 解压后总大小/条目数上限;Node 包允许携带已打包 CLI,但仍有硬闸。 */export const MAX_BASIC_UNCOMPRESSED_BYTES = 32 * 1024 * 1024;export const MAX_NODE_UNCOMPRESSED_BYTES = 256 * 1024 * 1024;@@ -236,7 +233,7 @@ export class GhostManager {// statSync 后再 readFileSync 是两次独立打开:并发方可在其间把 icon 换成// 指向宿主任意文件的链接,字节会被包成 dataURL 经 IPC 送进 Renderer。// 单句柄限量闸拒链接、限大小;containWithin 堵中间目录链接。- const bytes = readBoundedFileNoFollowSync(iconPath, MAX_GHOST_ICON_BYTES, {+ const bytes = readBoundedFileNoFollowSync(iconPath, GHOST_ICON_MAX_BYTES, {containWithin: fs.realpathSync(dir),});if (bytes === null) {@@ -527,14 +524,14 @@ export class GhostManager {try {iconData = await readZipEntryBufferWithLimit(iconEntry,- MAX_GHOST_ICON_BYTES,+ GHOST_ICON_MAX_BYTES,'icon',);} catch {return {rejection: {code: 'file-invalid',- reason: `icon 过大(上限 ${MAX_GHOST_ICON_BYTES} 字节)`,+ reason: `icon 过大(上限 ${GHOST_ICON_MAX_BYTES} 字节)`,},};}diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.tsindex c68d4e4499..c87d09c4e2 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts@@ -5,6 +5,7 @@* 规则 23:全部路径在 os.tmpdir 下,收尾清理。*/+import crypto from 'node:crypto';import fs from 'node:fs';import JSZip from 'jszip';import os from 'node:os';@@ -21,6 +22,8 @@ import {type ForgeScaffoldTemplate,} from '../forge';import { GhostManager } from '../GhostManager';+import { GHOST_SIGNATURE_FILE, signGhostPackage } from '../ghostSignature';+import { GHOST_INSTALL_MANIFEST_MAX_BYTES } from '../../../shared/ghost';const canSymlink = (() => {const probeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-forge-symlink-probe-'));@@ -91,6 +94,159 @@ describe('packGhostDir', () => {await fs.promises.rm(r.cindyPath, { force: true });});+ it('iconPng 仅覆盖包内图标与清单快照,不改写插件源码', async () => {+ const dir = await makeSrcDir({+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),+ 'main.js': '// brain',+ });+ const iconPng = Buffer.from(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=',+ 'base64',+ );++ const packed = await packGhostDir(dir, { iconPng });+ expect(packed.ok, JSON.stringify(packed)).toBe(true);+ if (!packed.ok) return;+ const zip = await JSZip.loadAsync(await fs.promises.readFile(packed.cindyPath));+ expect(JSON.parse(await zip.file('ghost.json')!.async('string'))).toMatchObject({+ icon: 'assets/icon.png',+ });+ expect(await zip.file('assets/icon.png')!.async('nodebuffer')).toEqual(iconPng);++ expect(JSON.parse(await fs.promises.readFile(path.join(dir, 'ghost.json'), 'utf8'))).not.toHaveProperty(+ 'icon',+ );+ await expect(fs.promises.stat(path.join(dir, 'assets/icon.png'))).rejects.toMatchObject({+ code: 'ENOENT',+ });++ const manager = new GhostManager({ getRootDir: () => path.join(workDir, 'ghosts') });+ const inspected = await manager.inspect(packed.cindyPath);+ expect('manifest' in inspected, JSON.stringify(inspected)).toBe(true);+ });++ it('iconPng 超过安装器 512 KiB 上限时在打包期拒绝', async () => {+ const dir = await makeSrcDir({+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),+ 'main.js': '// brain',+ });++ await expect(packGhostDir(dir, { iconPng: Buffer.alloc(512 * 1024 + 1) })).resolves.toMatchObject({+ ok: false,+ errorCode: 'TOO_LARGE',+ });+ });++ it('已签名源码使用 iconPng 时拒绝 overlay,避免生成验签必失败的包', async () => {+ const originalIcon = Buffer.from(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=',+ 'base64',+ );+ const manifest = { ...GOOD_MANIFEST, icon: 'assets/icon.png' };+ const dir = await makeSrcDir({+ 'ghost.json': JSON.stringify(manifest),+ 'main.js': '// brain',+ });+ await fs.promises.mkdir(path.join(dir, 'assets'), { recursive: true });+ await fs.promises.writeFile(path.join(dir, 'assets/icon.png'), originalIcon);++ const sourceZip = new JSZip();+ sourceZip.file('ghost.json', JSON.stringify(manifest));+ sourceZip.file('main.js', '// brain');+ sourceZip.file('assets/icon.png', originalIcon);+ const { privateKey } = crypto.generateKeyPairSync('ed25519');+ const signed = await signGhostPackage(+ await sourceZip.generateAsync({ type: 'nodebuffer' }),+ { publisherName: 'Forge Test Publisher', privateKey },+ );+ const signedZip = await JSZip.loadAsync(signed);+ const signatureBytes = await signedZip.file(GHOST_SIGNATURE_FILE)!.async('nodebuffer');+ await fs.promises.writeFile(path.join(dir, GHOST_SIGNATURE_FILE), signatureBytes);++ await expect(packGhostDir(dir, { iconPng: Buffer.from('replacement') })).resolves.toMatchObject({+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: expect.stringContaining('已签名插件不能使用 AI 图标覆盖'),+ });++ const fallback = await packGhostDir(dir);+ expect(fallback.ok, JSON.stringify(fallback)).toBe(true);+ if (!fallback.ok) return;+ const fallbackZip = await JSZip.loadAsync(await fs.promises.readFile(fallback.cindyPath));+ expect(await fallbackZip.file('assets/icon.png')!.async('nodebuffer')).toEqual(originalIcon);+ expect(await fallbackZip.file(GHOST_SIGNATURE_FILE)!.async('nodebuffer')).toEqual(signatureBytes);++ const manager = new GhostManager({ getRootDir: () => path.join(workDir, 'ghosts') });+ expect(await manager.inspect(fallback.cindyPath)).toMatchObject({+ trust: { publisherSigned: true },+ });+ });++ it('无效清单传 iconPng 仍返回 MANIFEST_INVALID,不被 overlay 改造成其它形状', async () => {+ const dir = await makeSrcDir({+ 'ghost.json': 'null',+ 'main.js': '// brain',+ });++ await expect(packGhostDir(dir, { iconPng: Buffer.from('png') })).resolves.toMatchObject({+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ });+ });++ it('icon overlay 后清单超过安装器上限时在打包期拒绝', async () => {+ // 用未知字段填充到上限附近:validator 会忽略它,但安装器仍必须按实际+ // ghost.json 字节数限流。overlay 只能写紧凑 JSON,并且写入 zip 前再复核。+ const emptyExtraBytes = Buffer.byteLength(+ `${JSON.stringify({ ...GOOD_MANIFEST, extra: '' })}\n`,+ 'utf8',+ );+ const manifest = {+ ...GOOD_MANIFEST,+ extra: 'x'.repeat(GHOST_INSTALL_MANIFEST_MAX_BYTES - emptyExtraBytes - 4),+ };+ const originalBytes = Buffer.byteLength(`${JSON.stringify(manifest)}\n`, 'utf8');+ expect(originalBytes).toBeLessThanOrEqual(GHOST_INSTALL_MANIFEST_MAX_BYTES);+ const dir = await makeSrcDir({+ 'ghost.json': JSON.stringify(manifest),+ 'main.js': '// brain',+ });++ await expect(packGhostDir(dir, { iconPng: Buffer.from('png') })).resolves.toMatchObject({+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: expect.stringContaining('合成后超过安装器'),+ });+ });++ it('assets/icon.png 已被目录占用时拒绝 icon overlay', async () => {+ const dir = await makeSrcDir({+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),+ 'main.js': '// brain',+ });+ await fs.promises.mkdir(path.join(dir, 'assets/icon.png'), { recursive: true });++ await expect(packGhostDir(dir, { iconPng: Buffer.from('png') })).resolves.toMatchObject({+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: expect.stringContaining('目标路径已被源码目录占用'),+ });+ });++ it('assets/icon.png 子路径已被目录占用时拒绝 icon overlay', async () => {+ const dir = await makeSrcDir({+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),+ 'main.js': '// brain',+ 'assets/icon.png/child.txt': 'occupied',+ });++ await expect(packGhostDir(dir, { iconPng: Buffer.from('png') })).resolves.toMatchObject({+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: expect.stringContaining('目标路径已被源码目录占用'),+ });+ });+it('打包进 zip 的 ghost.json 是校验时的快照,并发改写不生效(防 TOCTOU)', async () => {const dir = await makeSrcDir({'ghost.json': JSON.stringify(GOOD_MANIFEST),@@ -760,6 +916,39 @@ describe('FORGE_GUIDE', () => {expect(FORGE_GUIDE).toContain(marker);}});++ it('打包前仅轻提醒一次图标选择,AI 生成有固定提示词且失败不阻塞', () => {+ for (const marker of [+ '没有明确替换它生成的占位图',+ '轻提醒一次',+ '使用用户当前对话语言',+ '使用 AI 生成(推荐)',+ '上传图片',+ '同步把',+ 'ghost.json',+ 'icon',+ '使用默认图标(跳过)',+ '聊天模型解耦',+ '不要因为用户正在使用 GLM',+ 'Create a polished square app icon for a Cindy plugin named "{{name}}"',+ 'Purpose: {{one-sentence purpose}}',+ 'No text, letters, numbers',+ 'Output a 1024×1024 PNG',+ '只尝试一次',+ '超时或失败时不要重试',+ 'xdt_image_url',+ 'xdt_image_urls',+ 'selectedImageUrl',+ 'icon_source: selectedImageUrl',+ 'pack 也会自动回退默认图标',+ 'pack 会保留原图标和原签名',+ '跳过与使用默认是同一个选择',+ '不要用 AI 仿制商标',+ '使用官方品牌图标',+ ]) {+ expect(FORGE_GUIDE).toContain(marker);+ }+ });});describe('packGhostDir · skill 槽', () => {diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex f0d484f14b..2741303881 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -19,6 +19,8 @@ import path from 'node:path';import JSZip from 'jszip';import {+ GHOST_ICON_MAX_BYTES,+ GHOST_INSTALL_MANIFEST_MAX_BYTES,GHOST_MANIFEST_FILE,GHOST_SKILL_MD_MAX_BYTES,validateGhostManifest,@@ -29,6 +31,7 @@ import {readBoundedFileNoFollow,} from '../utils/readBoundedFile.js';import { validateGhostLocaleResourcesInDirectory } from './ghostLocaleFiles.js';+import { GHOST_SIGNATURE_FILE } from './ghostSignature.js';import { checkSkillMdConsistency } from './skillSlot.js';/** 与 GhostManager 装入侧同一量级的上限(打包侧提前拦,fail fast)。 */@@ -38,6 +41,7 @@ const MAX_BASIC_TOTAL_BYTES = 32 * 1024 * 1024;const MAX_NODE_TOTAL_BYTES = 256 * 1024 * 1024;const MAX_BASIC_CINDY_BYTES = 8 * 1024 * 1024;const MAX_NODE_CINDY_BYTES = 128 * 1024 * 1024;+const FORGE_AI_ICON_PATH = 'assets/icon.png';/** 打包时跳过的目录/文件(源码目录里的开发残留,不属于意识本体)。 */function shouldSkip(name: string): boolean {@@ -558,6 +562,7 @@ async function buildGhostPackage(* 对账也发现不了)。锚点必须来自上游的既有结论,不能在下游重新发明。*/expectedRealDir?: string,+ options?: { iconPng?: Buffer },): Promise<// manifestRaw = 校验前的原始清单对象。作者期严格校验(见 firstGhostAuthoringIssue)// 需要它来看见「作者写了但被校验器按未登记字段忽略掉」的内容——校验后的@@ -618,10 +623,36 @@ async function buildGhostPackage(message: `${GHOST_MANIFEST_FILE} 缺失或不是合法 JSON:${err instanceof Error ? err.message : String(err)}`,};}+ const iconPng = options?.iconPng;+ if (iconPng !== undefined) {+ if (iconPng.byteLength === 0 || iconPng.byteLength > GHOST_ICON_MAX_BYTES) {+ return {+ ok: false,+ errorCode: 'TOO_LARGE',+ message: `AI 图标体积必须在 1–${GHOST_ICON_MAX_BYTES} 字节之间`,+ };+ }+ // 无效清单先交给正式 validator,避免 overlay 把 null/数组等输入改造成+ // 另一种形状、掩盖原始 MANIFEST_INVALID。只有普通对象才写入快照。+ if (typeof manifestRaw === 'object' && manifestRaw !== null && !Array.isArray(manifestRaw)) {+ // icon_source 是打包期 overlay:源码仍保留 scaffold 占位图,只有用户+ // 确认生成成功的这一包替换图标。清单快照也同步指向固定安全路径。+ manifestRaw = { ...manifestRaw, icon: FORGE_AI_ICON_PATH };+ // 采用紧凑 JSON,避免仅为 overlay 重排空白就把清单推过安装侧上限。+ manifestBytes = Buffer.from(`${JSON.stringify(manifestRaw)}\n`, 'utf-8');+ }+ }const v = validateGhostManifest(manifestRaw);if (!v.ok) {return { ok: false, errorCode: 'MANIFEST_INVALID', message: `清单不合格:${v.reason}` };}+ if (manifestBytes.byteLength > GHOST_INSTALL_MANIFEST_MAX_BYTES) {+ return {+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: `${GHOST_MANIFEST_FILE} 合成后超过安装器 ${GHOST_INSTALL_MANIFEST_MAX_BYTES} 字节上限`,+ };+ }const manifest = v.manifest;// 2) locale 资源必须真实、可解析且提供的条目合法(缺译回退原文,不拒)。@@ -740,6 +771,40 @@ async function buildGhostPackage(};const tooLarge = await walk(dir, '');if (tooLarge) return tooLarge;+ // AI icon overlay changes both the manifest snapshot and the icon bytes. A+ // source tree carrying a publisher/reviewer signature cannot be modified+ // here without re-signing, so let the host fall back to the original icon+ // package instead of producing a package that installation must reject.+ const signatureEntry = files.find((file) => file.rel === GHOST_SIGNATURE_FILE);+ if (iconPng !== undefined && signatureEntry) {+ return {+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: '已签名插件不能使用 AI 图标覆盖;请保留原图标,或先修改源码图标再由正式发布流水线重新签名',+ };+ }+ const foldedAiIconPath = FORGE_AI_ICON_PATH.toLowerCase();+ const iconSourceEntry = files.find((file) => file.rel.toLowerCase() === foldedAiIconPath);+ const iconPathOccupiedByDirectory = [...seenPackPaths].some(+ (rel) => rel === foldedAiIconPath || rel.startsWith(`${foldedAiIconPath}/`),+ );+ if (iconPng !== undefined && iconPathOccupiedByDirectory && !iconSourceEntry) {+ return {+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: `AI 图标目标路径已被源码目录占用:${FORGE_AI_ICON_PATH}`,+ };+ }+ if (iconPng !== undefined && iconSourceEntry && iconSourceEntry.rel !== FORGE_AI_ICON_PATH) {+ return {+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: `AI 图标目标路径与源码中的大小写冲突:${iconSourceEntry.rel}`,+ };+ }+ if (iconPng !== undefined && !iconSourceEntry && files.length + 1 > maxFiles) {+ return { ok: false, errorCode: 'TOO_LARGE', message: `文件过多(上限 ${maxFiles} 个)` };+ }// 5) 生成 zip buffer。文件收集在此之前完成 + shouldSkip 跳过 *.cindy,// 产物自身不会进包;写盘位置由调用方决定(packGhostDir 进源码目录,@@ -754,6 +819,8 @@ async function buildGhostPackage(let content: Buffer;if (f.rel === GHOST_MANIFEST_FILE) {content = manifestBytes;+ } else if (iconPng !== undefined && f.rel === FORGE_AI_ICON_PATH) {+ content = iconPng;} else {let bytes: Buffer | null;try {@@ -773,8 +840,26 @@ async function buildGhostPackage(content = bytes;}packedBytes += content.byteLength;+ if (packedBytes > maxTotalBytes) {+ return {+ ok: false,+ errorCode: 'TOO_LARGE',+ message: `总体积超上限(${maxTotalBytes} 字节)`,+ };+ }zip.file(f.rel, content);}+ if (iconPng !== undefined && !iconSourceEntry) {+ packedBytes += iconPng.byteLength;+ if (packedBytes > maxTotalBytes) {+ return {+ ok: false,+ errorCode: 'TOO_LARGE',+ message: `总体积超上限(${maxTotalBytes} 字节)`,+ };+ }+ zip.file(FORGE_AI_ICON_PATH, iconPng);+ }const buf = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });const maxCindyBytes = manifest.node ? MAX_NODE_CINDY_BYTES : MAX_BASIC_CINDY_BYTES;if (buf.byteLength > maxCindyBytes) {@@ -804,8 +889,11 @@ async function buildGhostPackage(* 同名覆盖——同 id 同版本重打包语义上就是同一个包),用户在自己的意识目录里* 就能拿到成品;出错返回结构化分类,agent 按 message 修源码即可,不抛异常。*/-export async function packGhostDir(dir: string): Promise<ForgePackResult> {- const built = await buildGhostPackage(dir);+export async function packGhostDir(+ dir: string,+ options?: { iconPng?: Buffer },+): Promise<ForgePackResult> {+ const built = await buildGhostPackage(dir, undefined, options);if (!built.ok) return built;const authoringIssue = firstGhostAuthoringIssue(built.manifestRaw);if (authoringIssue) {@@ -3037,6 +3125,42 @@ if (r.ok && r.confirmed) {## 7. 打包与测试+### 7.1 打包前轻量确认图标++准备调用 \`ghost_forge_pack\` 前检查一次图标。如果清单没有 \`icon\`,或者本次用了+\`ghost_forge_scaffold\` 且没有明确替换它生成的占位图,就视为图标尚未配置。此时只+**轻提醒一次**,不要把图标变成验收门槛,也不要擅自开始耗时的图片生成。提示与选项+使用用户当前对话语言:++- **使用 AI 生成(推荐)**:仅在用户选择后,调用当前可用的图片生成能力;它与当前+ 聊天模型解耦,不要因为用户正在使用 GLM、Claude 等文本模型而切换聊天模型。把插件+ 展示名与一句话用途填入下面模板后原样注入,不要临场追加文字、品牌或复杂场景:++ \`\`\`text+ Create a polished square app icon for a Cindy plugin named "{{name}}". Purpose: {{one-sentence purpose}}. Show one clear, original visual metaphor for that purpose. Use a clean geometric composition, a restrained natural color palette, high contrast, and a centered subject with generous safe padding so it remains readable at 32–48 px. Use one symbol only on a simple solid or transparent background. No text, letters, numbers, UI mockups, scenes, baked-in rounded corners, trademarks, copied brand shapes, watermarks, heavy gradients, inner shadows, or photorealism. Output a 1024×1024 PNG.+ \`\`\`++ 只尝试一次。图片能力不可用、超时或失败时不要重试,直接调用+ \`ghost_forge_pack({ dir })\`,保留占位图/宿主默认图标继续打包,不让图标阻塞用户。+ 生成成功后,从图片工具结果的 \`xdt_image_url\` 取单张地址;如果结果只有+ \`xdt_image_urls\`,取数组第一项(例如 \`const selectedImageUrl = result.xdt_image_url ?? result.xdt_image_urls?.[0]\`)。+ 仅当它是 \`cindy-media://\` 地址时,才把它原样交给+ \`ghost_forge_pack({ dir, icon_source: selectedImageUrl })\`;主机会转成 1024×1024 PNG 并+ 嵌入安装包。icon_source 处理失败时 pack 也会自动回退默认图标,不要再发起第二次生成。+ 如果源码根目录已有 \`cindy-signatures.json\`,pack 会保留原图标和原签名,不做 AI+ 图标覆盖;任何文件变更都必须交给发布流水线重新签名,不能静默降级信任等级。+- **上传图片**:让用户提供图片,保存到 \`assets/icon.png\`,并同步把+ \`ghost.json\` 的 \`icon\` 字段设为 \`assets/icon.png\` 后继续;不要要求用户先把图片+ 处理成圆角,宿主负责最终显示形态。+- **使用默认图标(跳过)**:立即继续打包;scaffold 项目保留占位图,未使用 scaffold+ 的项目可以省略 \`icon\`,由宿主显示默认图标。跳过与使用默认是同一个选择。++如果插件明确对应现有品牌或服务(如 X/Twitter、Notion),不要用 AI 仿制商标。将推荐+项改为“使用官方品牌图标”,只从品牌官网、官方开发者文档或官方媒体资源中查询并设置;+来源不可靠或获取失败时同样回退上传/默认,不延长创建流程。++### 7.2 打包、安装与验证+1. 新插件先调 \`ghost_forge_scaffold\` 生成骨架,或把已有源码放在用户工作目录下的一个文件夹里(如 \`my-ghost/\`);脚手架目标必须是新目录,绝不覆盖已有文件;2. 调 \`ghost_forge_pack({ dir: '<绝对路径>' })\`——校验 + 打包 + 弹装入确认框;diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/forgeIconConversion.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/forgeIconConversion.test.tsnew file mode 100644index 0000000000..e1097d145f--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/__tests__/forgeIconConversion.test.ts@@ -0,0 +1,340 @@+import { EventEmitter } from 'node:events';++import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ createForgeIconConverter,+ type ForgeIconConversionChildLike,+} from '../forgeIconConversion.js';+import type { ForgeIconConversionRequest } from '../forgeIconConversionProtocol.js';++class FakeConversionChild extends EventEmitter implements ForgeIconConversionChildLike {+ pid: number | undefined;+ readonly processPid: number;+ alive = true;+ readonly posted: unknown[] = [];+ readonly kill = vi.fn(() => true);++ constructor(pid: number) {+ super();+ this.pid = pid;+ this.processPid = pid;+ }++ postMessage(message: unknown): void {+ this.posted.push(message);+ }++ request(): ForgeIconConversionRequest {+ return this.posted[0] as ForgeIconConversionRequest;+ }++ exit(code = 0): void {+ this.alive = false;+ this.pid = undefined;+ this.emit('exit', code);+ }+}++function isPidAlive(...children: FakeConversionChild[]) {+ return (pid: number): boolean =>+ children.some((child) => child.processPid === pid && child.alive);+}++afterEach(() => {+ vi.useRealTimers();+});++describe('createForgeIconConverter', () => {+ it('返回隔离进程产出的合规 PNG,并终止一次性进程', async () => {+ const child = new FakeConversionChild(101);+ const convert = createForgeIconConverter({+ fork: () => child,+ isPidAlive: isPidAlive(child),+ });++ const result = convert('/tmp/icon.png');+ const request = child.request();+ expect(request).toMatchObject({+ kind: 'convert',+ absPath: '/tmp/icon.png',+ timeoutSeconds: 5,+ });+ child.emit('message', {+ kind: 'result',+ id: request.id,+ ok: true,+ png: new Uint8Array(Buffer.from('png')),+ });++ await expect(result).resolves.toEqual(Buffer.from('png'));+ expect(child.kill).toHaveBeenCalledTimes(1);++ // The slot remains occupied until the utility process has actually exited.+ await expect(convert('/tmp/overlap.png')).rejects.toThrow('转换繁忙');+ child.exit(0);+ });++ it('超时会 kill 隔离进程;锁由 exit 释放,不依赖 Sharp promise settle', async () => {+ vi.useFakeTimers();+ const first = new FakeConversionChild(102);+ const second = new FakeConversionChild(103);+ const fork = vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second);+ const convert = createForgeIconConverter({+ fork,+ isPidAlive: isPidAlive(first, second),+ });++ const slow = convert('/tmp/slow.png');+ const slowExpectation = expect(slow).rejects.toThrow('转换超时');+ await vi.advanceTimersByTimeAsync(5_000);+ await slowExpectation;+ expect(first.kill).toHaveBeenCalledTimes(1);++ await expect(convert('/tmp/busy.png')).rejects.toThrow('转换繁忙');+ expect(fork).toHaveBeenCalledTimes(1);++ first.exit(0);+ const next = convert('/tmp/next.png');+ const request = second.request();+ second.emit('message', {+ kind: 'result',+ id: request.id,+ ok: true,+ png: new Uint8Array(Buffer.from('next')),+ });+ await expect(next).resolves.toEqual(Buffer.from('next'));+ expect(fork).toHaveBeenCalledTimes(2);+ second.exit(0);+ });++ it('error 没有后续 exit 时,旧进程存活则保持繁忙,确认死亡后恢复', async () => {+ vi.useFakeTimers();+ const first = new FakeConversionChild(104);+ const second = new FakeConversionChild(105);+ const fork = vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second);+ const probePid = vi.fn(isPidAlive(first, second));+ const convert = createForgeIconConverter({+ fork,+ terminationGraceMs: 100,+ isPidAlive: probePid,+ });++ const failed = convert('/tmp/error.png');+ first.emit('error', 'FatalError', 'forge-icon', 'diagnostic report');+ await expect(failed).rejects.toThrow('转换进程异常');++ // 模拟 error 后没有 exit:当前请求已 fail-fast,隔离窗口内不允许+ // 第二个转换进程与旧进程并发。+ await expect(convert('/tmp/next-after-error.png')).rejects.toThrow('转换繁忙');+ expect(fork).toHaveBeenCalledTimes(1);++ await vi.advanceTimersByTimeAsync(100);+ expect(first.kill).toHaveBeenCalledTimes(2);+ await expect(convert('/tmp/still-busy-after-error.png')).rejects.toThrow('转换繁忙');++ // Electron 在进程结束后会把 pid 清空;converter 必须继续使用 kill 前+ // 保存的最后一个有效 PID,不能因当前属性变成 undefined 而永久占槽。+ first.pid = undefined;+ first.alive = false;+ await vi.advanceTimersByTimeAsync(1_000);+ expect(probePid).toHaveBeenCalledWith(104);+ const next = convert('/tmp/next-after-error-recovered.png');+ const request = second.request();+ // 旧实例迟到的 exit 不能清掉已经启动的新一代 active 槽位。+ first.exit(1);+ await expect(convert('/tmp/overlap-after-old-exit.png')).rejects.toThrow('转换繁忙');+ expect(fork).toHaveBeenCalledTimes(2);+ second.emit('message', {+ kind: 'result',+ id: request.id,+ ok: true,+ png: new Uint8Array(Buffer.from('next')),+ });+ await expect(next).resolves.toEqual(Buffer.from('next'));+ expect(fork).toHaveBeenCalledTimes(2);+ second.exit(0);+ });++ it('成功回执后 error 没有 exit 时,旧进程存活则保持繁忙,确认死亡后恢复', async () => {+ vi.useFakeTimers();+ const first = new FakeConversionChild(106);+ const second = new FakeConversionChild(107);+ const fork = vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second);+ const convert = createForgeIconConverter({+ fork,+ terminationGraceMs: 100,+ isPidAlive: isPidAlive(first, second),+ });++ const firstResult = convert('/tmp/success-then-error.png');+ const firstRequest = first.request();+ first.emit('message', {+ kind: 'result',+ id: firstRequest.id,+ ok: true,+ png: new Uint8Array(Buffer.from('first')),+ });+ await expect(firstResult).resolves.toEqual(Buffer.from('first'));+ first.emit('error', 'FatalError', 'forge-icon', 'diagnostic report');++ await expect(convert('/tmp/next-after-late-error.png')).rejects.toThrow('转换繁忙');+ expect(fork).toHaveBeenCalledTimes(1);++ await vi.advanceTimersByTimeAsync(100);+ expect(first.kill).toHaveBeenCalledTimes(2);+ await expect(convert('/tmp/still-busy-after-late-error.png')).rejects.toThrow('转换繁忙');++ first.alive = false;+ await vi.advanceTimersByTimeAsync(1_000);+ const next = convert('/tmp/next-after-late-error-recovered.png');+ const nextRequest = second.request();+ first.exit(1);+ second.emit('message', {+ kind: 'result',+ id: nextRequest.id,+ ok: true,+ png: new Uint8Array(Buffer.from('next')),+ });+ await expect(next).resolves.toEqual(Buffer.from('next'));+ expect(fork).toHaveBeenCalledTimes(2);+ second.exit(0);+ });++ it('kill 抛错且没有 exit 时,无法确认死亡则继续 quarantine', async () => {+ vi.useFakeTimers();+ const first = new FakeConversionChild(111);+ first.kill.mockImplementation(() => {+ throw new Error('kill unavailable');+ });+ const second = new FakeConversionChild(112);+ const fork = vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second);+ const convert = createForgeIconConverter({+ fork,+ timeoutMs: 50,+ terminationGraceMs: 100,+ isPidAlive: isPidAlive(first, second),+ });++ const failed = convert('/tmp/kill-throws.png');+ const failedExpectation = expect(failed).rejects.toThrow('转换超时');+ await vi.advanceTimersByTimeAsync(50);+ await failedExpectation;+ await vi.advanceTimersByTimeAsync(100);+ expect(first.kill).toHaveBeenCalledTimes(2);+ await expect(convert('/tmp/still-busy-after-kill-throws.png')).rejects.toThrow('转换繁忙');++ first.alive = false;+ await vi.advanceTimersByTimeAsync(1_000);+ const next = convert('/tmp/next-after-kill-throws.png');+ const request = second.request();+ second.emit('message', {+ kind: 'result',+ id: request.id,+ ok: true,+ png: new Uint8Array(Buffer.from('next')),+ });+ await expect(next).resolves.toEqual(Buffer.from('next'));+ second.exit(0);+ });++ it('探活返回未知错误时 fail-closed,直到收到 exit 才释放', async () => {+ vi.useFakeTimers();+ const first = new FakeConversionChild(113);+ const second = new FakeConversionChild(114);+ const fork = vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second);+ const isPidAliveUnknown = vi.fn(() => {+ throw Object.assign(new Error('permission denied'), { code: 'EPERM' });+ });+ const convert = createForgeIconConverter({+ fork,+ terminationGraceMs: 100,+ isPidAlive: isPidAliveUnknown,+ });++ const firstResult = convert('/tmp/unknown-liveness.png');+ const firstRequest = first.request();+ first.emit('message', {+ kind: 'result',+ id: firstRequest.id,+ ok: true,+ png: new Uint8Array(Buffer.from('first')),+ });+ await expect(firstResult).resolves.toEqual(Buffer.from('first'));+ await vi.advanceTimersByTimeAsync(2_000);+ await expect(convert('/tmp/still-busy-after-unknown-liveness.png')).rejects.toThrow('转换繁忙');++ first.exit(0);+ const next = convert('/tmp/next-after-unknown-liveness.png');+ const nextRequest = second.request();+ second.emit('message', {+ kind: 'result',+ id: nextRequest.id,+ ok: true,+ png: new Uint8Array(Buffer.from('next')),+ });+ await expect(next).resolves.toEqual(Buffer.from('next'));+ second.exit(0);+ });++ it('kill 返回 false 且没有 exit 时,确认死亡后才恢复', async () => {+ vi.useFakeTimers();+ const first = new FakeConversionChild(108);+ first.kill.mockReturnValue(false);+ const second = new FakeConversionChild(109);+ const fork = vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second);+ const convert = createForgeIconConverter({+ fork,+ timeoutMs: 50,+ terminationGraceMs: 100,+ isPidAlive: isPidAlive(first, second),+ });++ const failed = convert('/tmp/kill-false.png');+ const failedExpectation = expect(failed).rejects.toThrow('转换超时');+ await vi.advanceTimersByTimeAsync(50);+ await failedExpectation;++ // kill 返回 false 不能证明旧进程已经退出;即使首轮窗口到期,仍保持单飞。+ await expect(convert('/tmp/next-after-kill-false.png')).rejects.toThrow('转换繁忙');+ expect(fork).toHaveBeenCalledTimes(1);++ await vi.advanceTimersByTimeAsync(100);+ expect(first.kill).toHaveBeenCalledTimes(2);+ await expect(convert('/tmp/still-busy-after-kill-false.png')).rejects.toThrow('转换繁忙');++ first.alive = false;+ await vi.advanceTimersByTimeAsync(1_000);+ const next = convert('/tmp/next-after-kill-false-recovered.png');+ const request = second.request();+ second.emit('message', {+ kind: 'result',+ id: request.id,+ ok: true,+ png: new Uint8Array(Buffer.from('next')),+ });+ await expect(next).resolves.toEqual(Buffer.from('next'));+ expect(fork).toHaveBeenCalledTimes(2);+ second.exit(0);+ });++ it('转换结果超过安装器上限时回退失败', async () => {+ const child = new FakeConversionChild(110);+ const convert = createForgeIconConverter({+ fork: () => child,+ isPidAlive: isPidAlive(child),+ });+ const result = convert('/tmp/large.png');+ const request = child.request();+ child.emit('message', {+ kind: 'result',+ id: request.id,+ ok: true,+ png: new Uint8Array(512 * 1024 + 1),+ });++ await expect(result).rejects.toThrow('转换结果必须在');+ expect(child.kill).toHaveBeenCalledTimes(1);+ child.exit(1);+ });+});diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/forgeIconConversionPackaging.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/forgeIconConversionPackaging.test.tsnew file mode 100644index 0000000000..11c43d6363--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/__tests__/forgeIconConversionPackaging.test.ts@@ -0,0 +1,35 @@+import fs from 'node:fs';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++const desktopRoot = path.resolve(process.cwd());++describe('Forge icon conversion process packaging contract', () => {+ it('将 Sharp 转换器打成独立 utility-process bundle', () => {+ const forge = fs.readFileSync(path.join(desktopRoot, 'forge.config.ts'), 'utf8');+ const wiring = fs.readFileSync(+ path.join(desktopRoot, 'src/main/mcp-integrations/forgeIconConversionHost.ts'),+ 'utf8',+ );++ expect(forge).toContain(+ "entry: 'src/main/mcp-integrations/forgeIconConversionProcess.ts'",+ );+ expect(forge).toContain("config: 'vite.forge-icon-conversion-process.config.ts'");+ expect(forge).toContain("target: 'preload'");+ expect(wiring).toContain("path.join(__dirname, 'forgeIconConversionProcess.js')");+ expect(wiring).toContain('utilityProcess.fork');+ });++ it('不向转换进程继承完整环境或宿主 cwd', () => {+ const wiring = fs.readFileSync(+ path.join(desktopRoot, 'src/main/mcp-integrations/forgeIconConversionHost.ts'),+ 'utf8',+ );++ expect(wiring).toContain('const env: NodeJS.ProcessEnv = {}');+ expect(wiring).not.toContain('...process.env');+ expect(wiring).toContain('cwd: os.tmpdir()');+ });+});diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/forgeIconConversionProcess.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/forgeIconConversionProcess.test.tsnew file mode 100644index 0000000000..b1071ade17--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/__tests__/forgeIconConversionProcess.test.ts@@ -0,0 +1,43 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import sharp from 'sharp';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { GHOST_ICON_MAX_BYTES } from '../../../shared/ghost.js';+import { convertForgeIconFile } from '../forgeIconConversionProcess.js';++let workDir: string;++beforeEach(async () => {+ workDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-forge-icon-test-'));+});++afterEach(async () => {+ await fs.promises.rm(workDir, { recursive: true, force: true });+});++describe('convertForgeIconFile', () => {+ it('真实 Sharp 路径输出 1024×1024 且满足安装器字节上限', async () => {+ const input = path.join(workDir, 'input.png');+ await sharp({+ create: {+ width: 64,+ height: 32,+ channels: 4,+ background: { r: 20, g: 120, b: 200, alpha: 1 },+ },+ })+ .png()+ .toFile(input);++ const output = await convertForgeIconFile(input, 5);+ const metadata = await sharp(output).metadata();++ expect(metadata.format).toBe('png');+ expect(metadata.width).toBe(1024);+ expect(metadata.height).toBe(1024);+ expect(output.byteLength).toBeLessThanOrEqual(GHOST_ICON_MAX_BYTES);+ });+});diff --git a/apps/desktop/src/main/mcp-integrations/forgeIconConversion.ts b/apps/desktop/src/main/mcp-integrations/forgeIconConversion.tsnew file mode 100644index 0000000000..663aab1087--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/forgeIconConversion.ts@@ -0,0 +1,272 @@+import { randomUUID } from 'node:crypto';++import { GHOST_ICON_MAX_BYTES } from '../../shared/ghost.js';+import type {+ ForgeIconConversionRequest,+ ForgeIconConversionResponse,+} from './forgeIconConversionProtocol.js';++export const FORGE_ICON_CONVERT_TIMEOUT_MS = 5_000;+/**+ * 失败后首轮等待 utility process 回收的有界隔离窗口。调用方在请求失败时+ * 已经立即回退默认图标;窗口只保护后续转换不与旧 native 任务重叠。+ */+export const FORGE_ICON_CONVERT_TERMINATION_GRACE_MS = 1_000;+/** 首轮回收窗口内的 PID 探活间隔。 */+export const FORGE_ICON_CONVERT_TERMINATION_POLL_MS = 100;+/** 无法确认死亡时的低频 quarantine 探活间隔。 */+export const FORGE_ICON_CONVERT_QUARANTINE_POLL_MS = 1_000;++export interface ForgeIconConversionChildLike {+ pid?: number;+ postMessage(message: unknown): void;+ on(event: 'message', listener: (message: unknown) => void): void;+ on(event: 'exit', listener: (code: number) => void): void;+ on(event: 'error', listener: (type: string, location: string, report: string) => void): void;+ kill(): boolean;+}++interface ForgeIconConverterOptions {+ fork: () => ForgeIconConversionChildLike;+ timeoutMs?: number;+ maxOutputBytes?: number;+ terminationGraceMs?: number;+ /** 测试可注入;生产默认使用 process.kill(pid, 0)。 */+ isPidAlive?: (pid: number) => boolean;+}++interface ActiveForgeIconConversion {+ child: ForgeIconConversionChildLike;+ id: string;+ settled: boolean;+ lastKnownPid?: number;+ timer?: ReturnType<typeof setTimeout>;+ terminationTimer?: ReturnType<typeof setTimeout>;+ terminationStartedAt?: number;+ terminationEscalated?: boolean;+}++/**+ * 一次只运行一个隔离转换进程;繁忙时直接回退默认图标,不排队。+ * Sharp/libvips 不在 Electron main 内运行:wall-clock 超时会 kill 整个 utility+ * process,锁由子进程 exit 或确认 PID 已死亡后释放,不依赖可能永不 settle 的+ * native promise。若系统无法确认 PID 已死亡,进入低频 quarantine,宁可继续+ * 回退默认图标,也不与仍可能存活的旧 native 任务并发。+ */+export function createForgeIconConverter(options: ForgeIconConverterOptions) {+ const timeoutMs = options.timeoutMs ?? FORGE_ICON_CONVERT_TIMEOUT_MS;+ const maxOutputBytes = options.maxOutputBytes ?? GHOST_ICON_MAX_BYTES;+ const terminationGraceMs = Math.max(+ 1,+ options.terminationGraceMs ?? FORGE_ICON_CONVERT_TERMINATION_GRACE_MS,+ );+ const isPidAlive = options.isPidAlive ?? defaultIsPidAlive;+ const nativeTimeoutSeconds = Math.max(1, Math.ceil(timeoutMs / 1000));+ let active: ActiveForgeIconConversion | null = null;++ return async function convertForgeIconToPng(absPath: string): Promise<Buffer> {+ if (active) throw new Error('AI 图标转换繁忙,已使用默认图标');++ let child: ForgeIconConversionChildLike;+ try {+ child = options.fork();+ } catch (error) {+ throw new Error(`AI 图标转换进程启动失败:${errorMessage(error)}`);+ }++ const initialPid = child.pid;+ const state: ActiveForgeIconConversion = {+ child,+ id: randomUUID(),+ settled: false,+ lastKnownPid: isValidPid(initialPid) ? initialPid : undefined,+ };+ active = state;++ return new Promise<Buffer>((resolve, reject) => {+ const clearTimer = (): void => {+ if (state.timer !== undefined) {+ clearTimeout(state.timer);+ state.timer = undefined;+ }+ };+ const clearTerminationTimer = (): void => {+ if (state.terminationTimer !== undefined) {+ clearTimeout(state.terminationTimer);+ state.terminationTimer = undefined;+ }+ };+ const release = (): void => {+ clearTerminationTimer();+ if (active === state) active = null;+ };+ const rememberPid = (): number | undefined => {+ const currentPid = child.pid;+ if (isValidPid(currentPid)) state.lastKnownPid = currentPid;+ return state.lastKnownPid;+ };+ const childIsKnownDead = (): boolean => {+ const pid = rememberPid();+ if (pid === undefined) return false;+ try {+ return !isPidAlive(pid);+ } catch {+ // 探活失败时按 alive/unknown 处理,避免与仍可能存活的旧进程并发。+ return false;+ }+ };+ const scheduleTerminationPoll = (delayMs: number): void => {+ if (active !== state) return;+ clearTerminationTimer();+ state.terminationTimer = setTimeout(() => {+ state.terminationTimer = undefined;+ pollTermination();+ }, delayMs);+ state.terminationTimer.unref?.();+ };+ const pollTermination = (): void => {+ if (active !== state) return;+ if (childIsKnownDead()) {+ // 只有明确确认 PID 已不存在时,才能在缺失 exit 事件的情况下释放+ // 单飞槽;这也避免 PID 被复用时误判旧进程已结束。+ release();+ return;+ }++ const startedAt = state.terminationStartedAt ?? Date.now();+ const elapsedMs = Date.now() - startedAt;+ if (elapsedMs < terminationGraceMs) {+ scheduleTerminationPoll(+ Math.min(FORGE_ICON_CONVERT_TERMINATION_POLL_MS, terminationGraceMs - elapsedMs),+ );+ return;+ }++ if (!state.terminationEscalated) {+ state.terminationEscalated = true;+ try {+ // 首轮窗口仍存活时再 best-effort kill 一次;不直接按 PID 发信号,+ // 避免 PID reuse 误杀无关进程。+ child.kill();+ } catch {+ // 继续 quarantine,直到 exit 或探活明确确认 PID 已死亡。+ }+ }+ scheduleTerminationPoll(FORGE_ICON_CONVERT_QUARANTINE_POLL_MS);+ };+ const requestTermination = (): void => {+ if (state.terminationStartedAt !== undefined) return;+ state.terminationStartedAt = Date.now();+ // Electron 会在进程结束后把 child.pid 清空;kill 前保存最后一次有效值,+ // 即使 exit 事件丢失,后续探活仍能确认旧进程已经消失。+ rememberPid();+ try {+ child.kill();+ } catch {+ // 仍进入有界隔离窗口;当前请求已经失败,后续调用暂时走默认图标回退。+ }+ pollTermination();+ };+ const complete = (operation: () => void): void => {+ if (state.settled) return;+ state.settled = true;+ clearTimer();+ // Keep the slot occupied until exit or a confirmed-dead PID. The response+ // can arrive just before the process is reaped; releasing here could start+ // a second Sharp process while the first one is shutting down.+ requestTermination();+ operation();+ };+ const failAndTerminate = (error: Error): void => {+ if (state.settled) return;+ state.settled = true;+ clearTimer();+ // 超时/请求失败时不能在 kill 请求后立刻释放:先等 Electron 确认 exit+ // 或 PID 已死亡,防止旧 native 任务尚未停止时立刻启动第二个子进程。+ // 当前请求已经立即拒绝,由上层回退默认图标。+ requestTermination();+ reject(error);+ };++ child.on('message', (message) => {+ const response = parseForgeIconConversionResponse(message, state.id);+ if (!response) return;+ if (!response.ok) {+ complete(() => reject(new Error(response.error)));+ return;+ }+ const png = Buffer.from(response.png);+ if (png.byteLength === 0 || png.byteLength > maxOutputBytes) {+ complete(() => reject(new Error(`AI 图标转换结果必须在 1–${maxOutputBytes} 字节之间`)));+ return;+ }+ complete(() => resolve(png));+ });+ child.on('error', (type, location) => {+ const error = new Error(`AI 图标转换进程异常:${type}${location ? `(${location})` : ''}`);+ if (!state.settled) failAndTerminate(error);+ // 当前请求已在 failAndTerminate 中立即拒绝;槽位等 exit 或确认 PID+ // 已死亡后释放,防止 error 后旧进程尚未退出时立刻启动第二个进程。+ });+ child.on('exit', (code) => {+ clearTimer();+ release();+ if (state.settled) return;+ state.settled = true;+ reject(new Error(`AI 图标转换进程已退出(${code})`));+ });++ state.timer = setTimeout(() => {+ failAndTerminate(new Error(`AI 图标转换超时(${timeoutMs}ms)`));+ }, timeoutMs);+ state.timer.unref?.();++ const request: ForgeIconConversionRequest = {+ kind: 'convert',+ id: state.id,+ absPath,+ timeoutSeconds: nativeTimeoutSeconds,+ };+ try {+ child.postMessage(request);+ } catch (error) {+ failAndTerminate(new Error(`AI 图标转换请求失败:${errorMessage(error)}`));+ }+ });+ };+}++function defaultIsPidAlive(pid: number): boolean {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ // 只有 ESRCH 能证明 PID 已不存在;EPERM、EINVAL 等未知结果一律+ // 按存活/未知处理,避免在旧 utility process 仍可能运行时启动新进程。+ return (error as NodeJS.ErrnoException).code !== 'ESRCH';+ }+}++function isValidPid(pid: number | undefined): pid is number {+ return typeof pid === 'number' && Number.isSafeInteger(pid) && pid > 0;+}++function parseForgeIconConversionResponse(+ value: unknown,+ expectedId: string,+): ForgeIconConversionResponse | null {+ if (!value || typeof value !== 'object') return null;+ const candidate = value as Partial<ForgeIconConversionResponse>;+ if (candidate.kind !== 'result' || candidate.id !== expectedId) return null;+ if (candidate.ok === false) {+ return typeof candidate.error === 'string' && candidate.error.length > 0+ ? (candidate as Extract<ForgeIconConversionResponse, { ok: false }>)+ : null;+ }+ if (candidate.ok !== true || !(candidate.png instanceof Uint8Array)) return null;+ return candidate as Extract<ForgeIconConversionResponse, { ok: true }>;+}++function errorMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}diff --git a/apps/desktop/src/main/mcp-integrations/forgeIconConversionHost.ts b/apps/desktop/src/main/mcp-integrations/forgeIconConversionHost.tsnew file mode 100644index 0000000000..cad979eae4--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/forgeIconConversionHost.ts@@ -0,0 +1,28 @@+/** Electron wiring for the cancellable Forge icon conversion utility process. */++import os from 'node:os';+import path from 'node:path';+import { utilityProcess } from 'electron';++import type { ForgeIconConversionChildLike } from './forgeIconConversion.js';++export function forkForgeIconConversionHost(): ForgeIconConversionChildLike {+ const env: NodeJS.ProcessEnv = {};+ for (const key of [+ 'PATH',+ 'SystemRoot',+ 'WINDIR',+ 'TMPDIR',+ 'TEMP',+ 'TMP',+ 'LANG',+ 'LC_ALL',+ ] as const) {+ if (process.env[key] !== undefined) env[key] = process.env[key];+ }+ return utilityProcess.fork(path.join(__dirname, 'forgeIconConversionProcess.js'), [], {+ serviceName: 'cindy-forge-icon-converter',+ env,+ cwd: os.tmpdir(),+ });+}diff --git a/apps/desktop/src/main/mcp-integrations/forgeIconConversionProcess.ts b/apps/desktop/src/main/mcp-integrations/forgeIconConversionProcess.tsnew file mode 100644index 0000000000..72dd591614--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/forgeIconConversionProcess.ts@@ -0,0 +1,87 @@+/**+ * 一次性 Forge icon utility-process。Sharp/libvips 完全隔离在本进程中,+ * Electron main 的 5 秒 wall-clock 超时可直接 kill 本进程,不留下后台任务。+ */++import sharp from 'sharp';++import { GHOST_ICON_MAX_BYTES } from '../../shared/ghost.js';+import type {+ ForgeIconConversionRequest,+ ForgeIconConversionResponse,+} from './forgeIconConversionProtocol.js';++const FORGE_ICON_EDGE_PX = 1024;++interface ParentPortLike {+ postMessage(message: unknown): void;+ on(event: 'message', listener: (event: { data: unknown }) => void): void;+}++const parentPort = (process as unknown as { parentPort?: ParentPortLike }).parentPort;++export async function convertForgeIconFile(+ absPath: string,+ timeoutSeconds: number,+): Promise<Buffer> {+ const png = await sharp(absPath, {+ failOn: 'error',+ limitInputPixels: 64 * 1024 * 1024,+ })+ .rotate()+ .resize(FORGE_ICON_EDGE_PX, FORGE_ICON_EDGE_PX, {+ fit: 'cover',+ position: 'centre',+ })+ .png({ compressionLevel: 9, palette: true, colours: 256, effort: 7 })+ .timeout({ seconds: timeoutSeconds })+ .toBuffer();+ if (png.byteLength === 0 || png.byteLength > GHOST_ICON_MAX_BYTES) {+ throw new Error(`AI 图标转换结果必须在 1–${GHOST_ICON_MAX_BYTES} 字节之间`);+ }+ return png;+}++if (parentPort) {+ let started = false;+ parentPort.on('message', (event) => {+ if (started) return;+ const request = parseRequest(event.data);+ if (!request) return;+ started = true;+ void convertForgeIconFile(request.absPath, request.timeoutSeconds)+ .then<ForgeIconConversionResponse, ForgeIconConversionResponse>(+ (png) => ({+ kind: 'result',+ id: request.id,+ ok: true,+ png: new Uint8Array(png),+ }),+ (error) => ({+ kind: 'result',+ id: request.id,+ ok: false,+ error: error instanceof Error ? error.message : String(error),+ }),+ )+ .then((response) => parentPort.postMessage(response));+ });+}++function parseRequest(value: unknown): ForgeIconConversionRequest | null {+ if (!value || typeof value !== 'object') return null;+ const request = value as Partial<ForgeIconConversionRequest>;+ if (+ request.kind !== 'convert' ||+ typeof request.id !== 'string' ||+ request.id.length === 0 ||+ typeof request.absPath !== 'string' ||+ request.absPath.length === 0 ||+ !Number.isInteger(request.timeoutSeconds) ||+ (request.timeoutSeconds ?? 0) < 1 ||+ (request.timeoutSeconds ?? 0) > 3600+ ) {+ return null;+ }+ return request as ForgeIconConversionRequest;+}diff --git a/apps/desktop/src/main/mcp-integrations/forgeIconConversionProtocol.ts b/apps/desktop/src/main/mcp-integrations/forgeIconConversionProtocol.tsnew file mode 100644index 0000000000..ee7a62f1fa--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/forgeIconConversionProtocol.ts@@ -0,0 +1,10 @@+export interface ForgeIconConversionRequest {+ kind: 'convert';+ id: string;+ absPath: string;+ timeoutSeconds: number;+}++export type ForgeIconConversionResponse =+ | { kind: 'result'; id: string; ok: true; png: Uint8Array }+ | { kind: 'result'; id: string; ok: false; error: string };diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.tsindex 1c3201feb9..55e3423b25 100644--- a/apps/desktop/src/main/mcp-integrations/ghost.ts+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts@@ -70,10 +70,17 @@ import * as ledger from '../cindy-media/ledger.js';import { chatAttachmentOrigin } from '../cindy-media/attachmentGrantGate.js';import { resolveGhostAttachmentUrl } from './ghostAttachmentResolve.js';import { ghostSetupInteractionSessionId } from './ghostSetupInteractionSurface.js';+import { createForgeIconConverter } from './forgeIconConversion.js';+import { forkForgeIconConversionHost } from './forgeIconConversionHost.js';import { t } from '../i18n.js';import { createLogger } from '../logger.js';const log = createLogger('mcp/cindy');+const MAX_FORGE_ICON_SOURCE_BYTES = 25 * 1024 * 1024;++const convertForgeIconToPng = createForgeIconConverter({+ fork: forkForgeIconConversionHost,+});/* ────────────────────────────────────────────────────────────────────────* workdir 外过户确认:@@ -1368,8 +1375,42 @@ export function getCindyGhostsMcpDeps(}return result;},- async forgePack({ dir }): Promise<CindyForgePackResult> {- const packed = await packGhostDir(dir);+ async forgePack({ dir, iconSource }): Promise<CindyForgePackResult> {+ let iconPng: Buffer | undefined;+ let iconNote = '';+ if (iconSource !== undefined) {+ try {+ const resolved = blobStore.resolveSafe(iconSource);+ if (!resolved.mimeType.startsWith('image/')) {+ throw new Error('icon_source 不是图片');+ }+ const stat = await fs.promises.stat(resolved.absPath);+ if (!stat.isFile() || stat.size <= 0 || stat.size > MAX_FORGE_ICON_SOURCE_BYTES) {+ throw new Error(`icon_source 体积必须在 1–${MAX_FORGE_ICON_SOURCE_BYTES} 字节之间`);+ }+ iconPng = await convertForgeIconToPng(resolved.absPath);+ iconNote = 'AI 图标已嵌入安装包。';+ } catch (err) {+ iconNote = 'AI 图标处理失败,已保留默认图标并继续打包。';+ log.warn('ghost forge icon fallback', {+ dir,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }++ let packed = await packGhostDir(dir, iconPng ? { iconPng } : undefined);+ // icon overlay 的任何失败都不是打包门槛:用原源码再打一次。若原源码+ // 本身也不合法,则返回原本就会出现的结构化错误。+ if (!packed.ok && iconPng) {+ const fallbackPacked = await packGhostDir(dir);+ if (fallbackPacked.ok) {+ packed = fallbackPacked;+ iconNote = 'AI 图标处理失败,已保留默认图标并继续打包。';+ } else {+ return fallbackPacked;+ }+ }if (!packed.ok) return packed;// 与双击 .cindy 同一条转交通道:renderer 弹标准确认框(同 id 已装则// 自动转"更新 vX → vY"),用户点头才真装。@@ -1381,7 +1422,7 @@ export function getCindyGhostsMcpDeps(id: packed.manifest.id,name: packed.manifest.name,version: packed.manifest.version,- note: '已打包并弹出装入/更新确认框,请告知用户在应用内确认(装入默认沉睡)。',+ note: `${iconNote}已打包并弹出装入/更新确认框,请告知用户在应用内确认(装入默认沉睡)。`,};},logger: log,diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 6fd9def267..153f5c8367 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -21,6 +21,12 @@ import { DEFAULT_LOCALE, SUPPORTED_LOCALES, type SupportedLocale } from './local/** 清单文件名(zip 根部)。 */export const GHOST_MANIFEST_FILE = 'ghost.json';+/**+ * 安装器读取包内 ghost.json 的硬上限。源码目录的发现/预读取可以使用更宽的+ * 安全预算,但最终写进 .cindy 的清单必须落在这个上限内。+ */+export const GHOST_INSTALL_MANIFEST_MAX_BYTES = 256 * 1024;+/** 意识文件扩展名。 */export const CINDY_FILE_EXT = '.cindy';@@ -1875,6 +1881,12 @@ const GHOST_ICON_MIME_BY_EXT: Record<string, string> = {'.gif': 'image/gif',};+/**+ * icon 字节上限。icon 会以 data URL 形态同步下发给 Renderer,因此安装、+ * 本地读取与 Forge overlay 必须共用同一硬顶,避免“能打包但不能安装”。+ */+export const GHOST_ICON_MAX_BYTES = 512 * 1024;+/** icon 路径 → mime;扩展名不在白名单返回 null(即校验不通过)。 */export function ghostIconMimeType(p: string): string | null {const dot = p.lastIndexOf('.');diff --git a/apps/desktop/vite.forge-icon-conversion-process.config.ts b/apps/desktop/vite.forge-icon-conversion-process.config.tsnew file mode 100644index 0000000000..12addf4483--- /dev/null+++ b/apps/desktop/vite.forge-icon-conversion-process.config.ts@@ -0,0 +1,17 @@+import { defineConfig } from 'vite';++export default defineConfig({+ resolve: {+ conditions: ['node'],+ mainFields: ['module', 'jsnext:main', 'jsnext'],+ },+ build: {+ rollupOptions: {+ // sharp 是原生 N-API 模块,随 packaged app 的 runtime deps 按平台解析。+ external: ['sharp'],+ output: {+ inlineDynamicImports: true,+ },+ },+ },+});diff --git a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts b/packages/cindy-tools/src/__tests__/ghostMcp.test.tsindex 66e4845c17..5418af1cc7 100644--- a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts+++ b/packages/cindy-tools/src/__tests__/ghostMcp.test.ts@@ -1066,6 +1066,47 @@ describe("cindy_ghosts · ghost_forge(锻造)", () => {errorCode: "MANIFEST_INVALID",});});++ it("forge_pack 仅在传入时把 icon_source 映射给 host", async () => {+ const requests: Array<{ dir: string; iconSource?: string }> = [];+ const deps = fakeDeps({+ forgePack: async (request) => {+ requests.push(request);+ return {+ ok: true,+ cindyPath: "/src/my-ghost/my-ghost-1.0.0.cindy",+ id: "my-ghost",+ name: "My Ghost",+ version: "1.0.0",+ note: "packed",+ };+ },+ });++ await handleForgePack(deps, {+ dir: "/src/my-ghost",+ icon_source: `cindy-media://blobs/${"a".repeat(64)}.png`,+ });+ await handleForgePack(deps, { dir: "/src/default" });++ expect(requests).toEqual([+ {+ dir: "/src/my-ghost",+ iconSource: `cindy-media://blobs/${"a".repeat(64)}.png`,+ },+ { dir: "/src/default" },+ ]);+ });++ it("forge_pack 描述明确图片工具结果字段", () => {+ const server = createCindyGhostsMcpServer(fakeDeps()) as unknown as {+ _registeredTools: Record<string, { description?: string } | undefined>;+ };+ const description = server._registeredTools.ghost_forge_pack?.description ?? "";+ expect(description).toContain("xdt_image_url");+ expect(description).toContain("xdt_image_urls");+ expect(description).toContain("icon_source");+ });});describe("formatGhostRoster(花名册快照:语义召回数据源)", () => {diff --git a/packages/cindy-tools/src/ghost/mcpServer.ts b/packages/cindy-tools/src/ghost/mcpServer.tsindex 1c083f9608..238aec414a 100644--- a/packages/cindy-tools/src/ghost/mcpServer.ts+++ b/packages/cindy-tools/src/ghost/mcpServer.ts@@ -89,7 +89,9 @@ const D_GHOST_FORGE_PACK = ["把一个插件源码目录校验并打包成 .cindy,随后主机会弹出装入确认框(同 id 已装则显示",'"更新 vX → vY")——装不装永远由用户在弹窗上决定,本工具不会私自装入。',"dir 传源码目录的绝对路径(目录里须有 ghost.json;打包自动跳过 .git / node_modules /",- "隐藏文件 / *.cindy)。失败返回结构化错误(MANIFEST_INVALID 等,message 带具体原因),",+ "隐藏文件 / *.cindy)。仅当用户明确选择 AI 生成图标时,可把图片工具结果的",+ "xdt_image_url 取单张地址;若只有 xdt_image_urls 则取数组第一项,再把得到的 cindy-media:// 地址传给 icon_source;主机会 best-effort 嵌入,失败保留默认图标继续打包。",+ "失败返回结构化错误(MANIFEST_INVALID 等,message 带具体原因),","按 message 修正源码后重新打包即可。打包成功 ≠ 已装入:告知用户去点确认框。",].join("\n");@@ -699,10 +701,13 @@ export async function handleForgeScaffold(/** ghost_forge_pack 的 handler 主体(导出供单测)。 */export async function handleForgePack(deps: CindyGhostsMcpDeps,- input: { dir: string },+ input: { dir: string; icon_source?: string },): Promise<McpTextResult> {try {- const result = await deps.forgePack({ dir: input.dir });+ const result = await deps.forgePack({+ dir: input.dir,+ ...(input.icon_source !== undefined ? { iconSource: input.icon_source } : {}),+ });if (!result.ok) {deps.logger?.warn("ghost_forge_pack rejected", {dir: input.dir,@@ -830,6 +835,12 @@ export function createCindyGhostsMcpServer(D_GHOST_FORGE_PACK,{dir: z.string().describe("插件源码目录的绝对路径(目录里须有 ghost.json)"),+ icon_source: z+ .string()+ .optional()+ .describe(+ "可选;仅当用户明确选择 AI 生成图标时,传图片工具结果的 xdt_image_url,或 xdt_image_urls 数组第一项(cindy-media:// 地址);失败会保留默认图标继续打包",+ ),},async (input) => handleForgePack(deps, input),);diff --git a/packages/cindy-tools/src/types.ts b/packages/cindy-tools/src/types.tsindex 7c84ad5c0d..8ae9c5a7b0 100644--- a/packages/cindy-tools/src/types.ts+++ b/packages/cindy-tools/src/types.ts@@ -287,7 +287,14 @@ export interface CindyGhostsMcpDeps {* 装入(同 id 已装则更新)确认框——装不装永远由用户决定,agent 只能* 递到用户面前。*/- forgePack(request: { dir: string }): Promise<CindyForgePackResult>;+ forgePack(request: {+ dir: string;+ /**+ * 用户明确选择 AI 图标后,由图片工具返回的 cindy-media 地址。Host+ * best-effort 把它嵌入包内;失败保留源码里的默认图标,不阻塞打包。+ */+ iconSource?: string;+ }): Promise<CindyForgePackResult>;logger?: {info: (msg: string, meta?: Record<string, unknown>) => void;warn: (msg: string, meta?: Record<string, unknown>) => void;