Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(ios-simulator): add plugin host capability and native recovery
JiangJiahao1b5534f2b503
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex f6276bc7e5..26aa33188f 100644--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@ -9,6 +9,7 @@ import {GHOST_LOCALE_MAX_BYTES,GHOST_ICON_MAX_BYTES,GHOST_INSTALL_MANIFEST_MAX_BYTES,+ GHOST_SLOTS,GHOST_SKILL_MD_MAX_BYTES,ghostLocalePathFor,ghostIconMimeType,@@ -22,10 +23,7 @@ import {type GhostTrustInfo,type InstalledGhost,} from '../../shared/ghost.js';-import {- verifyGhostZipSignatures,- type GhostTrustRegistry,-} from './ghostSignature.js';+import { verifyGhostZipSignatures, type GhostTrustRegistry } from './ghostSignature.js';import {readBoundedFileFollowLinks,readBoundedFileNoFollowSync,@@ -75,6 +73,7 @@ export interface GhostManagerOptions {export type InstallRejection =| { code: 'source-not-found'; reason: string }| { code: 'file-invalid'; reason: string }+ | { code: 'host-unsupported'; reason: string }| { code: 'already-installed'; reason: string }| { code: 'not-installed'; reason: string }| { code: 'command-conflict'; reason: string }@@ -85,6 +84,31 @@ export type UninstallRejection =| { code: 'not-installed'; reason: string }| { code: 'io'; reason: string };+/**+ * 区分“包本身坏了”和“包使用了更新版 Cindy 才认识的契约”。+ *+ * 这里只收窄识别两个可证明是 Host 版本差异的形状:未来 schemaVersion,或+ * 字符串形态的未知 capability slot。其它畸形输入仍交给完整 manifest 校验,+ * 不能借友好提示放松安装安全边界。+ */+export function ghostManifestHostUnsupportedReason(raw: unknown): string | null {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;+ const record = raw as Record<string, unknown>;+ if (+ typeof record.schemaVersion === 'number' &&+ Number.isInteger(record.schemaVersion) &&+ record.schemaVersion > 2+ ) {+ return `插件使用了更新的清单格式(schemaVersion ${record.schemaVersion})`;+ }+ if (!Array.isArray(record.slots)) return null;+ const supported = new Set<string>([...GHOST_SLOTS, 'model']);+ const unknown = [+ ...new Set(record.slots.filter((slot): slot is string => typeof slot === 'string')),+ ].filter((slot) => !supported.has(slot));+ return unknown.length > 0 ? `插件需要当前 Cindy 尚不支持的能力:${unknown.join(' / ')}` : null;+}+/*** 意识仓库的 main 端管理者:一个意识一个子目录(rootDir/<id>/),目录即事实。*@@ -173,7 +197,9 @@ export class GhostManager {const localePath = ghostLocalePathFor(manifest, requestedLocale);if (!localePath) return runtimeManifest;const fallbackPath = manifest.locales?.en;- const candidates = [...new Set([localePath, fallbackPath].filter((value): value is string => Boolean(value)))];+ const candidates = [+ ...new Set([localePath, fallbackPath].filter((value): value is string => Boolean(value))),+ ];for (const candidatePath of candidates) {try {const absPath = path.join(dir, ...candidatePath.split('/'));@@ -208,7 +234,10 @@ export class GhostManager {* 启用 / 停用一张意识。停用不删任何东西,只在安装目录里放一个 `.disabled`* 标记文件(目录即事实:打开文件夹一眼可见);启用即删掉标记。幂等。*/- async setEnabled(id: string, enabled: boolean): Promise<{ ok: true } | { rejection: UninstallRejection }> {+ async setEnabled(+ id: string,+ enabled: boolean,+ ): Promise<{ ok: true } | { rejection: UninstallRejection }> {if (!isValidGhostId(id)) {return { rejection: { code: 'invalid-id', reason: '非法意识 id' } };}@@ -224,7 +253,9 @@ export class GhostManager {await fs.promises.writeFile(marker, '');}} catch (err) {- return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };+ return {+ rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },+ };}this.options.log?.info('ghost enabled state changed', { id, enabled });this.options.onChanged?.(this.list());@@ -246,7 +277,10 @@ export class GhostManager {containWithin: fs.realpathSync(dir),});if (bytes === null) {- this.options.log?.warn('ghost icon skipped: missing or oversize', { dir, icon: manifest.icon });+ this.options.log?.warn('ghost icon skipped: missing or oversize', {+ dir,+ icon: manifest.icon,+ });return null;}return buildIconDataUrl(manifest.icon, bytes);@@ -270,7 +304,8 @@ export class GhostManager {typeof raw.publisherSigned !== 'boolean' ||typeof raw.publisherVerified !== 'boolean' ||typeof raw.reviewed !== 'boolean'- ) return null;+ )+ return null;const trust: GhostTrustInfo = {level: raw.level as GhostTrustInfo['level'],publisherSigned: raw.publisherSigned,@@ -279,15 +314,17 @@ export class GhostManager {...(typeof raw.publisherName === 'string' ? { publisherName: raw.publisherName } : {}),...(typeof raw.publisherKeyId === 'string' ? { publisherKeyId: raw.publisherKeyId } : {}),...(typeof raw.reviewerName === 'string' ? { reviewerName: raw.reviewerName } : {}),- ...(typeof raw.unknownReviewer === 'boolean' ? { unknownReviewer: raw.unknownReviewer } : {}),+ ...(typeof raw.unknownReviewer === 'boolean'+ ? { unknownReviewer: raw.unknownReviewer }+ : {}),};const approval = raw.approvedAtResourceProvider;const approvedAtResourceProviderTool =- approval- && typeof approval === 'object'- && !Array.isArray(approval)- && Object.keys(approval).length === 1- && typeof (approval as Record<string, unknown>).tool === 'string'+ approval &&+ typeof approval === 'object' &&+ !Array.isArray(approval) &&+ Object.keys(approval).length === 1 &&+ typeof (approval as Record<string, unknown>).tool === 'string'? (approval as Record<string, string>).tool: undefined;return {@@ -304,9 +341,7 @@ export class GhostManager {* 零副作用。「装意识前弹确认」(README 安全原则)的数据来源 —— 三个装入* 入口(设置页 / 拖入 / 双击)都先 inspect 给用户看明白,确认后才 install。*/- async inspect(- lizFilePath: string,- ): Promise<+ async inspect(lizFilePath: string): Promise<| {manifest: GhostManifest;/** 包内原始清单,仅供 Main 安全比较。 */@@ -329,9 +364,7 @@ export class GhostManager {}/** 装入的前半程(读文件 / 解包 / 校验清单),inspect 与 install 共用。 */- private async parse(- lizFilePath: string,- ): Promise<+ private async parse(lizFilePath: string): Promise<| {manifest: GhostManifest;canonicalManifest: GhostManifest;@@ -362,7 +395,9 @@ export class GhostManager {if ((err as NodeJS.ErrnoException).code === 'ENOENT') {return { rejection: { code: 'source-not-found', reason: '文件不存在' } };}- return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };+ return {+ rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },+ };}// 2) 解析 zip + 找 ghost.json(容忍"压缩时多包了一层文件夹"的常见做法)@@ -378,7 +413,10 @@ export class GhostManager {}if (allEntries.length > MAX_NODE_ZIP_ENTRIES) {return {- rejection: { code: 'file-invalid', reason: `压缩包条目过多:${allEntries.length}(上限 ${MAX_NODE_ZIP_ENTRIES})` },+ rejection: {+ code: 'file-invalid',+ reason: `压缩包条目过多:${allEntries.length}(上限 ${MAX_NODE_ZIP_ENTRIES})`,+ },};}// 检查/签名/保留文件对账都按原始条目名,解压却按 canonical 路径落盘;@@ -430,21 +468,31 @@ export class GhostManager {}const manifestEntry = zip.file(`${prefix}${GHOST_MANIFEST_FILE}`);if (!manifestEntry) {- return { rejection: { code: 'file-invalid', reason: `压缩包根部缺少 ${GHOST_MANIFEST_FILE}` } };+ return {+ rejection: { code: 'file-invalid', reason: `压缩包根部缺少 ${GHOST_MANIFEST_FILE}` },+ };}// 3) 校验清单let manifestRaw: unknown;try {manifestRaw = JSON.parse(- (await readZipEntryBufferWithLimit(- manifestEntry,- MAX_GHOST_MANIFEST_BYTES,- GHOST_MANIFEST_FILE,- )).toString('utf8'),+ (+ await readZipEntryBufferWithLimit(+ manifestEntry,+ MAX_GHOST_MANIFEST_BYTES,+ GHOST_MANIFEST_FILE,+ )+ ).toString('utf8'),);} catch {- return { rejection: { code: 'file-invalid', reason: `${GHOST_MANIFEST_FILE} 不是合法 JSON` } };+ return {+ rejection: { code: 'file-invalid', reason: `${GHOST_MANIFEST_FILE} 不是合法 JSON` },+ };+ }+ const hostUnsupportedReason = ghostManifestHostUnsupportedReason(manifestRaw);+ if (hostUnsupportedReason) {+ return { rejection: { code: 'host-unsupported', reason: hostUnsupportedReason } };}const v = validateGhostManifest(manifestRaw);if (!v.ok) {@@ -461,7 +509,10 @@ export class GhostManager {const maxEntries = v.manifest.node ? MAX_NODE_ZIP_ENTRIES : MAX_BASIC_ZIP_ENTRIES;if (allEntries.length > maxEntries) {return {- rejection: { code: 'file-invalid', reason: `压缩包条目过多:${allEntries.length}(上限 ${maxEntries})` },+ rejection: {+ code: 'file-invalid',+ reason: `压缩包条目过多:${allEntries.length}(上限 ${maxEntries})`,+ },};}if (v.manifest.node && !zip.file(`${prefix}${v.manifest.node.entry}`)) {@@ -489,11 +540,13 @@ export class GhostManager {let localeRaw: unknown;try {localeRaw = JSON.parse(- (await readZipEntryBufferWithLimit(- localeEntry,- GHOST_LOCALE_MAX_BYTES,- `locale ${localePath}`,- )).toString('utf8'),+ (+ await readZipEntryBufferWithLimit(+ localeEntry,+ GHOST_LOCALE_MAX_BYTES,+ `locale ${localePath}`,+ )+ ).toString('utf8'),);} catch {return {@@ -553,16 +606,15 @@ export class GhostManager {const iconEntry = zip.file(`${prefix}${v.manifest.icon}`);if (!iconEntry) {return {- rejection: { code: 'file-invalid', reason: `清单声明了 icon,但压缩包内缺少 ${v.manifest.icon}` },+ rejection: {+ code: 'file-invalid',+ reason: `清单声明了 icon,但压缩包内缺少 ${v.manifest.icon}`,+ },};}let iconData: Buffer;try {- iconData = await readZipEntryBufferWithLimit(- iconEntry,- GHOST_ICON_MAX_BYTES,- 'icon',- );+ iconData = await readZipEntryBufferWithLimit(iconEntry, GHOST_ICON_MAX_BYTES, 'icon');} catch {return {rejection: {@@ -583,7 +635,10 @@ export class GhostManager {const skillEntry = zip.file(`${prefix}${relPath}`);if (!skillEntry) {return {- rejection: { code: 'file-invalid', reason: `skill 条目声明了 ${skillItem.dir},但压缩包内缺少 ${relPath}` },+ rejection: {+ code: 'file-invalid',+ reason: `skill 条目声明了 ${skillItem.dir},但压缩包内缺少 ${relPath}`,+ },};}let skillMd: Buffer;@@ -604,7 +659,10 @@ export class GhostManager {const consistencyError = checkSkillMdConsistency(skillMd.toString('utf8'), skillItem);if (consistencyError) {return {- rejection: { code: 'file-invalid', reason: `skill 条目 ${skillItem.dir}:${consistencyError}` },+ rejection: {+ code: 'file-invalid',+ reason: `skill 条目 ${skillItem.dir}:${consistencyError}`,+ },};}}@@ -669,7 +727,10 @@ export class GhostManager {}// 5) 解压到 staging(zip-slip / zip bomb 防御),全过才切正式目录- const stagingDir = path.join(root, `.cindy-installing-${manifest.id}-${crypto.randomBytes(4).toString('hex')}`);+ const stagingDir = path.join(+ root,+ `.cindy-installing-${manifest.id}-${crypto.randomBytes(4).toString('hex')}`,+ );try {// 初始沉睡:标记在 staging 阶段就位,rename 后首个广播即沉睡态,// 不存在"先启用一帧再熄灯"的跳变(规则 7)。@@ -686,7 +747,9 @@ export class GhostManager {if (err instanceof InstallExtractError) {return { rejection: { code: 'file-invalid', reason: err.message } };}- return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };+ return {+ rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },+ };}const ghost: InstalledGhost = {@@ -732,7 +795,9 @@ export class GhostManager {const root = this.options.getRootDir();const finalDir = path.join(root, manifest.id);if (!(await pathExists(finalDir))) {- return { rejection: { code: 'not-installed', reason: `意识 ${manifest.id} 未装入,无从更新` } };+ return {+ rejection: { code: 'not-installed', reason: `意识 ${manifest.id} 未装入,无从更新` },+ };}// 延续当前唤醒/沉睡状态。const enabled = !fs.existsSync(path.join(finalDir, DISABLED_MARKER_FILE));@@ -772,7 +837,9 @@ export class GhostManager {if (err instanceof InstallExtractError) {return { rejection: { code: 'file-invalid', reason: err.message } };}- return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };+ return {+ rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },+ };}// 换目录:旧版先挪去备份位,新版 rename 失败即滚回,保证任何时刻都有一份完整版本在位。@@ -780,14 +847,18 @@ export class GhostManager {await fs.promises.rename(finalDir, backupDir);} catch (err) {await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {});- return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };+ return {+ rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },+ };}try {await fs.promises.rename(stagingDir, finalDir);} catch (err) {await fs.promises.rename(backupDir, finalDir).catch(() => {});await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {});- return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };+ return {+ rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },+ };}await fs.promises.rm(backupDir, { recursive: true, force: true }).catch(() => {});@@ -838,9 +909,13 @@ export class GhostManager {}await fs.promises.writeFile(path.join(stagingDir, TRUST_METADATA_FILE),- `${JSON.stringify({- ...opts.trust,- }, null, 2)}\n`,+ `${JSON.stringify(+ {+ ...opts.trust,+ },+ null,+ 2,+ )}\n`,);}@@ -869,7 +944,9 @@ export class GhostManager {try {await fs.promises.rm(dir, { recursive: true, force: true });} catch (err) {- return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };+ return {+ rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },+ };}this.options.log?.info('ghost uninstalled', { id });if (options.notify !== false) this.options.onChanged?.(this.list());diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex 354e6f5898..e9cd54c104 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@ -82,11 +82,11 @@ async function makeCindy(return out;}-async function expectRejection(- result: Awaited<ReturnType<GhostManager['install']>>,- code: string,-): Promise<void> {- expect('rejection' in result, JSON.stringify(result)).toBe(true);+async function expectRejection(result: unknown, code: string): Promise<void> {+ expect(+ typeof result === 'object' && result !== null && 'rejection' in result,+ JSON.stringify(result),+ ).toBe(true);expect((result as { rejection: { code: string } }).rejection.code).toBe(code);}@@ -101,11 +101,12 @@ describe('GhostManager · install', () => {'zh-CN': 'locales/zh-CN.json',},};- const locale = (name: string, description: string, toolDescription: string) => JSON.stringify({- name,- description,- tools: { do_thing: { description: toolDescription } },- });+ const locale = (name: string, description: string, toolDescription: string) =>+ JSON.stringify({+ name,+ description,+ tools: { do_thing: { description: toolDescription } },+ });const cindy = await makeCindy('localized.cindy', manifest, {'locales/en.json': locale('English name', 'English description', 'English tool'),'locales/zh-CN.json': locale('中文名称', '中文说明', '中文工具'),@@ -143,10 +144,11 @@ describe('GhostManager · install', () => {name: 'Base name',locales: { en: 'locales/en.json' },};- const locale = (name: string) => JSON.stringify({- name,- tools: { do_thing: { description: 'Localized tool' } },- });+ const locale = (name: string) =>+ JSON.stringify({+ name,+ tools: { do_thing: { description: 'Localized tool' } },+ });const cindy = await makeCindy('localized-symlink.cindy', manifest, {'locales/en.json': locale('Packaged name'),});@@ -171,7 +173,10 @@ describe('GhostManager · install', () => {const outsideLocalesDir = path.join(workDir, 'outside-locales');await fs.promises.rm(localesDir, { recursive: true, force: true });await fs.promises.mkdir(outsideLocalesDir);- await fs.promises.writeFile(path.join(outsideLocalesDir, 'en.json'), locale('Outside parent name'));+ await fs.promises.writeFile(+ path.join(outsideLocalesDir, 'en.json'),+ locale('Outside parent name'),+ );await fs.promises.symlink(outsideLocalesDir,localesDir,@@ -242,13 +247,14 @@ describe('GhostManager · install', () => {const installed = await manager.install(cindy);const metadataPath = path.join(rootDir, 'hello', '.cindy-trust.json');- const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8')) as Record<string, unknown>;+ const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8')) as Record<+ string,+ unknown+ >;delete metadata.approvedAtResourceProvider;await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);- expect(manager.list()[0].manifest.tools).toEqual([- { name: 'do_thing', description: '做点事' },- ]);+ expect(manager.list()[0].manifest.tools).toEqual([{ name: 'do_thing', description: '做点事' }]);metadata.approvedAtResourceProvider = { tool: 'other_tool' };await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);@@ -283,7 +289,10 @@ describe('GhostManager · install', () => {});it('源文件不存在 → source-not-found', async () => {- await expectRejection(await manager.install(path.join(workDir, 'nope.cindy')), 'source-not-found');+ await expectRejection(+ await manager.install(path.join(workDir, 'nope.cindy')),+ 'source-not-found',+ );});it('不是 zip 的文件 → file-invalid', async () => {@@ -377,7 +386,10 @@ describe('GhostManager · install', () => {it('重复装入同 id → already-installed,原安装不受影响', async () => {await manager.install(await makeCindy('a.cindy', goodManifest()));onChanged.mockClear();- await expectRejection(await manager.install(await makeCindy('b.cindy', goodManifest())), 'already-installed');+ await expectRejection(+ await manager.install(await makeCindy('b.cindy', goodManifest())),+ 'already-installed',+ );expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);expect(onChanged).not.toHaveBeenCalled();});@@ -389,7 +401,9 @@ describe('GhostManager · install', () => {'command-conflict',);expect(fs.existsSync(path.join(rootDir, 'beta'))).toBe(false); // 半点不落盘- const ok = await manager.install(await makeCindy('c.cindy', chipManifestWithCommand('gamma', '画图')));+ const ok = await manager.install(+ await makeCindy('c.cindy', chipManifestWithCommand('gamma', '画图')),+ );expect('ghost' in ok).toBe(true);expect(manager.list().map((g) => g.manifest.id)).toEqual(['alpha', 'gamma']);});@@ -566,10 +580,7 @@ describe('GhostManager · inspect(只验不装)', () => {const expectedPackageSha256 = (inspected as { packageSha256: string }).packageSha256;await makeCindy('swap.cindy', goodManifest(), { 'payload.txt': 'after' });- await expectRejection(- await manager.install(cindy, { expectedPackageSha256 }),- 'file-invalid',- );+ await expectRejection(await manager.install(cindy, { expectedPackageSha256 }), 'file-invalid');expect(fs.existsSync(rootDir)).toBe(false);});@@ -579,6 +590,28 @@ describe('GhostManager · inspect(只验不装)', () => {const result = await manager.inspect(bad);expect((result as { rejection: { code: string } }).rejection.code).toBe('file-invalid');});++ it('未来 schema 或未知字符串 capability → 插件合法但当前 Host 不支持', async () => {+ const futureSchema = await makeCindy('future-schema.cindy', {+ ...goodManifest(),+ schemaVersion: 3,+ });+ await expectRejection(await manager.inspect(futureSchema), 'host-unsupported');++ const futureCapability = await makeCindy('future-capability.cindy', {+ ...goodManifest(),+ slots: ['tool', 'future-host-capability'],+ });+ await expectRejection(await manager.inspect(futureCapability), 'host-unsupported');+ });++ it('slot 形状畸形仍按非法文件拒绝,友好提示不放松安全校验', async () => {+ const malformed = await makeCindy('malformed-slot.cindy', {+ ...goodManifest(),+ slots: ['tool', { name: 'future-host-capability' }],+ });+ await expectRejection(await manager.inspect(malformed), 'file-invalid');+ });});describe('GhostManager · author / icon(身份卡展示字段)', () => {@@ -595,7 +628,9 @@ describe('GhostManager · author / icon(身份卡展示字段)', () => {expect('manifest' in inspected).toBe(true);const ok = inspected as { manifest: { author?: string }; iconDataUrl?: string };expect(ok.manifest.author).toBe('Lizi');- expect(ok.iconDataUrl).toBe(`data:image/png;base64,${Buffer.from('PNGDATA').toString('base64')}`);+ expect(ok.iconDataUrl).toBe(+ `data:image/png;base64,${Buffer.from('PNGDATA').toString('base64')}`,+ );const result = await manager.install(cindy);expect('ghost' in result).toBe(true);@@ -620,7 +655,9 @@ describe('GhostManager · author / icon(身份卡展示字段)', () => {it.runIf(process.platform !== 'win32')('已装目录 icon 被换成指向目录外的符号链接 → list 降级为无图标,不外泄目标字节',async () => {- const cindy = await makeCindy('icon3.cindy', iconManifest(), { 'assets/icon.png': 'PNGDATA' });+ const cindy = await makeCindy('icon3.cindy', iconManifest(), {+ 'assets/icon.png': 'PNGDATA',+ });await manager.install(cindy);// 装完后把 icon 换成指向插件目录外一个私密文件的符号链接:statSync 会// 跟随链接对目标判 isFile/大小 → 通过,再 readFileSync 目标字节 → 经@@ -662,7 +699,11 @@ describe('GhostManager · update(原位换版)', () => {await manager.install(await makeCindy('v1.cindy', goodManifest(), { 'old.txt': 'v1' }));onChanged.mockClear();- const v2 = await makeCindy('v2.cindy', { ...goodManifest(), version: '2.0.0' }, { 'new.txt': 'v2' });+ const v2 = await makeCindy(+ 'v2.cindy',+ { ...goodManifest(), version: '2.0.0' },+ { 'new.txt': 'v2' },+ );const result = await manager.update(v2);expect('ghost' in result, JSON.stringify(result)).toBe(true);const { ghost } = result as { ghost: InstalledGhost };@@ -678,18 +719,25 @@ describe('GhostManager · update(原位换版)', () => {it('唤醒状态延续:沉睡中更新仍沉睡,唤醒中更新仍唤醒', async () => {await manager.install(await makeCindy('v1.cindy', goodManifest()), { initiallyEnabled: false });- const r1 = await manager.update(await makeCindy('v2.cindy', { ...goodManifest(), version: '2.0.0' }));+ const r1 = await manager.update(+ await makeCindy('v2.cindy', { ...goodManifest(), version: '2.0.0' }),+ );expect((r1 as { ghost: InstalledGhost }).ghost.enabled).toBe(false);expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);await manager.setEnabled('hello', true);- const r2 = await manager.update(await makeCindy('v3.cindy', { ...goodManifest(), version: '3.0.0' }));+ const r2 = await manager.update(+ await makeCindy('v3.cindy', { ...goodManifest(), version: '3.0.0' }),+ );expect((r2 as { ghost: InstalledGhost }).ghost.enabled).toBe(true);expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(false);});it('未装入 → not-installed 拒绝', async () => {- await expectRejection(await manager.update(await makeCindy('a.cindy', goodManifest())), 'not-installed');+ await expectRejection(+ await manager.update(await makeCindy('a.cindy', goodManifest())),+ 'not-installed',+ );});it('指令查重豁免自己,但仍拦别人的指令', async () => {@@ -698,14 +746,20 @@ describe('GhostManager · update(原位换版)', () => {// 自己沿用自己的指令 → 放行。const keep = await manager.update(- await makeCindy('a2.cindy', { ...chipManifestWithCommand('alpha', 'draw'), version: '2.0.0' }),+ await makeCindy('a2.cindy', {+ ...chipManifestWithCommand('alpha', 'draw'),+ version: '2.0.0',+ }),);expect('ghost' in keep, JSON.stringify(keep)).toBe(true);// 新版本改用别人占用的指令 → 拒,且旧版原样在位。await expectRejection(await manager.update(- await makeCindy('a3.cindy', { ...chipManifestWithCommand('alpha', 'paint'), version: '3.0.0' }),+ await makeCindy('a3.cindy', {+ ...chipManifestWithCommand('alpha', 'paint'),+ version: '3.0.0',+ }),),'command-conflict',);diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.tsindex 34b373e727..244aa8bd47 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts@@ -113,9 +113,9 @@ describe('packGhostDir', () => {});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',- );+ 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',});@@ -131,7 +131,9 @@ describe('packGhostDir', () => {'main.js': '// brain',});- await expect(packGhostDir(dir, { iconPng: Buffer.alloc(512 * 1024 + 1) })).resolves.toMatchObject({+ await expect(+ packGhostDir(dir, { iconPng: Buffer.alloc(512 * 1024 + 1) }),+ ).resolves.toMatchObject({ok: false,errorCode: 'TOO_LARGE',});@@ -155,26 +157,30 @@ describe('packGhostDir', () => {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 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 图标覆盖'),- });+ 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);+ 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({@@ -254,18 +260,23 @@ describe('packGhostDir', () => {});// 模拟"校验通过后、写入 zip 前"目录被并发改写:保 id/version,偷加权限声明。// 若打包时重读磁盘,包里的 manifest 会与返回值(安装侧审阅比对的依据)分叉。- const tampered = JSON.stringify({ ...GOOD_MANIFEST, slots: ['tool', 'network'], network: { allow: ['x.test'] } });+ const tampered = JSON.stringify({+ ...GOOD_MANIFEST,+ slots: ['tool', 'network'],+ network: { allow: ['x.test'] },+ });const realRead = fs.promises.readFile;let ghostReads = 0;- const spy = vi- .spyOn(fs.promises, 'readFile')- .mockImplementation(((target: unknown, ...rest: unknown[]) => {- if (String(target).endsWith('ghost.json')) {- ghostReads += 1;- if (ghostReads > 1) return Promise.resolve(Buffer.from(tampered));- }- return (realRead as (...args: unknown[]) => unknown)(target, ...rest);- }) as typeof fs.promises.readFile);+ const spy = vi.spyOn(fs.promises, 'readFile').mockImplementation(((+ target: unknown,+ ...rest: unknown[]+ ) => {+ if (String(target).endsWith('ghost.json')) {+ ghostReads += 1;+ if (ghostReads > 1) return Promise.resolve(Buffer.from(tampered));+ }+ return (realRead as (...args: unknown[]) => unknown)(target, ...rest);+ }) as typeof fs.promises.readFile);try {const r = await packGhostDir(dir);expect(r.ok, JSON.stringify(r)).toBe(true);@@ -281,20 +292,23 @@ describe('packGhostDir', () => {}});- it.skipIf(!canSymlink)('ghost.json 为符号链接 → MANIFEST_INVALID(与市场发现/安装同一把闸)', async () => {- // 符号链接:目标是合法清单也不放行——“符号链接一律不穿透”覆盖身份卡本身,- // 否则打包输入目录里一根链接就能把目录外的文件读进打包管道。- const outside = path.join(workDir, 'outside-ghost.json');- await fs.promises.writeFile(outside, JSON.stringify(GOOD_MANIFEST));- const linked = path.join(workDir, 'src-linked');- await fs.promises.mkdir(linked, { recursive: true });- await fs.promises.symlink(outside, path.join(linked, 'ghost.json'));- await fs.promises.writeFile(path.join(linked, 'main.js'), '// brain');- expect(await packGhostDir(linked)).toMatchObject({- ok: false,- errorCode: 'MANIFEST_INVALID',- });- });+ it.skipIf(!canSymlink)(+ 'ghost.json 为符号链接 → MANIFEST_INVALID(与市场发现/安装同一把闸)',+ async () => {+ // 符号链接:目标是合法清单也不放行——“符号链接一律不穿透”覆盖身份卡本身,+ // 否则打包输入目录里一根链接就能把目录外的文件读进打包管道。+ const outside = path.join(workDir, 'outside-ghost.json');+ await fs.promises.writeFile(outside, JSON.stringify(GOOD_MANIFEST));+ const linked = path.join(workDir, 'src-linked');+ await fs.promises.mkdir(linked, { recursive: true });+ await fs.promises.symlink(outside, path.join(linked, 'ghost.json'));+ await fs.promises.writeFile(path.join(linked, 'main.js'), '// brain');+ expect(await packGhostDir(linked)).toMatchObject({+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ });+ },+ );it('ghost.json 超限 → MANIFEST_INVALID(与市场发现/安装同一把闸)', async () => {// 超限:JSON 本身合法(合法清单 + 尾随空白撑体积),必须在读取层按大小拒,@@ -354,20 +368,13 @@ describe('packGhostDir', () => {await fs.promises.mkdir(staged, { recursive: true });const pluginDir = path.join(staged, 'alpha');await fs.promises.mkdir(pluginDir, { recursive: true });- await fs.promises.writeFile(- path.join(pluginDir, 'ghost.json'),- JSON.stringify(GOOD_MANIFEST),- );+ await fs.promises.writeFile(path.join(pluginDir, 'ghost.json'), JSON.stringify(GOOD_MANIFEST));await fs.promises.writeFile(path.join(pluginDir, 'main.js'), '// brain');// 调用方(安装管道)校验时拿到的规范根。const expectedRealDir = await fs.promises.realpath(pluginDir);// 校验之后被换成指向外部目录的链接(外部目录留着同样的 ghost.json)。await fs.promises.rm(pluginDir, { recursive: true, force: true });- await fs.promises.symlink(- await fs.promises.realpath(outside),- pluginDir,- directoryLinkType,- );+ await fs.promises.symlink(await fs.promises.realpath(outside), pluginDir, directoryLinkType);const dest = path.join(workDir, 'out.cindy');const r = await packGhostDirToFile(pluginDir, dest, expectedRealDir);@@ -450,11 +457,12 @@ describe('packGhostDir', () => {ja: 'locales/ja.json',},};- const locale = (name: string, description: string, tool: string) => JSON.stringify({- name,- description,- tools: { do_thing: { description: tool } },- });+ const locale = (name: string, description: string, tool: string) =>+ JSON.stringify({+ name,+ description,+ tools: { do_thing: { description: tool } },+ });const dir = await makeSrcDir({'ghost.json': JSON.stringify(manifest),'main.js': '// brain',@@ -597,13 +605,16 @@ describe('scaffoldGhostDir', () => {'生成 %s 模板,随后可以直接打包并通过装入检查',async (template) => {const dir = path.join(workDir, template);- const result = await scaffoldGhostDir({- dir,- template,- id: `demo-${template}`,- name: `演示 ${template}`,- description: `${template} 起步插件`,- }, { sessionWorkdir: workDir });+ const result = await scaffoldGhostDir(+ {+ dir,+ template,+ id: `demo-${template}`,+ name: `演示 ${template}`,+ description: `${template} 起步插件`,+ },+ { sessionWorkdir: workDir },+ );expect(result, JSON.stringify(result)).toMatchObject({ ok: true, dir, template });if (!result.ok) return;expect(result.files).toContain('ghost.json');@@ -648,23 +659,29 @@ describe('scaffoldGhostDir', () => {await fs.promises.mkdir(existing);await fs.promises.writeFile(path.join(existing, 'keep.txt'), 'keep me');expect(- await scaffoldGhostDir({- dir: existing,- template: 'plain',- id: 'existing',- name: 'Existing',- }, { sessionWorkdir: workDir }),+ await scaffoldGhostDir(+ {+ dir: existing,+ template: 'plain',+ id: 'existing',+ name: 'Existing',+ },+ { sessionWorkdir: workDir },+ ),).toMatchObject({ ok: false, errorCode: 'TARGET_EXISTS' });expect(await fs.promises.readFile(path.join(existing, 'keep.txt'), 'utf8')).toBe('keep me');const invalid = path.join(workDir, 'invalid');expect(- await scaffoldGhostDir({- dir: invalid,- template: 'plain',- id: 'INVALID_ID',- name: 'Invalid',- }, { sessionWorkdir: workDir }),+ await scaffoldGhostDir(+ {+ dir: invalid,+ template: 'plain',+ id: 'INVALID_ID',+ name: 'Invalid',+ },+ { sessionWorkdir: workDir },+ ),).toMatchObject({ ok: false, errorCode: 'INVALID_INPUT' });await expect(fs.promises.stat(invalid)).rejects.toMatchObject({ code: 'ENOENT' });});@@ -679,12 +696,15 @@ describe('scaffoldGhostDir', () => {return;}expect(- await scaffoldGhostDir({- dir: path.join(workDir, 'out', 'plugin'),- template: 'plain',- id: 'escape',- name: 'Escape',- }, { sessionWorkdir: workDir }),+ await scaffoldGhostDir(+ {+ dir: path.join(workDir, 'out', 'plugin'),+ template: 'plain',+ id: 'escape',+ name: 'Escape',+ },+ { sessionWorkdir: workDir },+ ),).toMatchObject({ ok: false, errorCode: 'INVALID_INPUT' });await expect(fs.promises.stat(path.join(outside, 'plugin'))).rejects.toMatchObject({code: 'ENOENT',@@ -713,9 +733,7 @@ describe('FORGE_GUIDE', () => {}sections.set(current, size);for (const [header, bytes] of sections) {- expect(bytes, `${header} 超出分章安全体量,请拆小节`).toBeLessThanOrEqual(- CHAPTER_BYTE_LIMIT,- );+ expect(bytes, `${header} 超出分章安全体量,请拆小节`).toBeLessThanOrEqual(CHAPTER_BYTE_LIMIT);}});@@ -751,7 +769,7 @@ describe('FORGE_GUIDE', () => {// 2026-08-04 文本转向量(cindy.embed.text):作者最容易踩的是"换模型 =// 换向量空间",手册必须讲到 model + dim 要跟向量一起存。'embed_text',- "\"embed\": [\"text\"]",+ '"embed": ["text"]','inputType','dimensions',// 上下文化(voyage-context-*):二维 documents 与三层 documentEmbeddings 是@@ -869,8 +887,8 @@ describe('FORGE_GUIDE', () => {'minimize','最小化为浮动气泡',// 2026-07-25 skill 槽:随包捆绑 Agent Skills,声明一致性 + 全局作用域披露。- // 卡槽总数标记随 workspace 槽合入更新为十五个。- '十五个卡槽',+ // 卡槽总数标记随 ios-simulator 槽合入更新为十八个。+ '十八个卡槽','捆绑 Agent Skills(skill 槽)','skill.items','SKILL.md',@@ -882,6 +900,10 @@ describe('FORGE_GUIDE', () => {'创建工作区会话(workspace 槽)','cindy.workspace',"kind: 'ensure-session'",+ // 2026-08-06 iOS Simulator 插件能力:只读脱敏状态与 Host 面板入口。+ '内置 iOS 模拟器(ios-simulator 槽)',+ 'cindy.iosSimulator.request',+ 'pluginVideo/pluginInput 都是 false',// 2026-07-28 图标与官方仓门禁(#809):§1/§2 的 icon 字段说明、// §8.1 官方插件仓的四语言 locale 与 assets/icon.png 惯例。'"icon": "assets/icon.png"',diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostDevRuntimeContract.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostDevRuntimeContract.test.tsindex a18d0ed7c5..c92a0341c4 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostDevRuntimeContract.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostDevRuntimeContract.test.ts@@ -10,17 +10,22 @@ describe('dev-only plugin QA call boundary', () => {'utf8',);const preload = fs.readFileSync(path.resolve(process.cwd(), 'src/preload/preload.ts'), 'utf8');- const devOnlyStart = main.indexOf("if (!app.isPackaged) {");- const handlerStart = main.indexOf("ipcMain.handle('ghosts:dev-runtime'", devOnlyStart);- const handlerEnd = main.indexOf("\n });", handlerStart);+ const devOnlyStart = main.indexOf('if (!app.isPackaged) {');+ const handlerNameStart = main.indexOf("'ghosts:dev-runtime'", devOnlyStart);+ const handlerStart = main.lastIndexOf('ipcMain.handle(', handlerNameStart);+ const handlerEnd = main.indexOf('\n );', handlerNameStart);const handler = main.slice(handlerStart, handlerEnd);expect(devOnlyStart).toBeGreaterThanOrEqual(0);+ expect(handlerNameStart).toBeGreaterThan(devOnlyStart);expect(handlerStart).toBeGreaterThan(devOnlyStart);+ expect(handlerEnd).toBeGreaterThan(handlerNameStart);expect(handler).toContain('assertTrustedAppRendererEvent(event)');expect(handler).toContain("case 'call'");expect(handler).toContain('getGhostPipeDispatcher().callGhostTool');- expect(preload).toContain("ipcRenderer.invoke('ghosts:dev-runtime', 'call', id, { tool, args })");- expect(preload).not.toContain("devCall: (channel:");+ expect(preload).toContain(+ "ipcRenderer.invoke('ghosts:dev-runtime', 'call', id, { tool, args })",+ );+ expect(preload).not.toContain('devCall: (channel:');});});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/iosSimulatorSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/iosSimulatorSlot.test.tsnew file mode 100644index 0000000000..ef5cc6a1d3--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/iosSimulatorSlot.test.ts@@ -0,0 +1,270 @@+import { describe, expect, it, vi } from 'vitest';++import type { GhostIOSSimulatorStatusProbeResult, InstalledGhost } from '../../../shared/ghost';+import {+ GHOST_IOS_SIMULATOR_OPEN_MIN_INTERVAL_MS,+ GHOST_IOS_SIMULATOR_STATUS_CACHE_MS,+ GhostIOSSimulatorSlot,+ type IOSSimulatorSlotDeps,+ type IOSSimulatorSlotFocusContext,+} from '../iosSimulatorSlot';++function simulatorGhost(options: { enabled?: boolean; slots?: string[] } = {}): InstalledGhost {+ return {+ manifest: {+ schemaVersion: 2,+ id: 'ios-simulator',+ name: 'iOS Simulator',+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ slots: options.slots ?? ['ios-simulator'],+ },+ dir: '/fake/ios-simulator',+ enabled: options.enabled ?? true,+ } as InstalledGhost;+}++function readyStatus(): GhostIOSSimulatorStatusProbeResult {+ return {+ ok: true,+ status: {+ environment: {+ platform: 'darwin',+ supported: true,+ ready: true,+ xcodeVersion: '26.0',+ availableDeviceCount: 2,+ },+ instances: [+ {+ instanceId: 'instance-a',+ simulatorName: 'iPhone 17 Pro',+ generation: 1,+ lifecycleState: 'ready',+ healthState: 'healthy',+ },+ ],+ routeStatuses: [+ {+ instanceId: 'instance-a',+ generation: 1,+ stream: { adapter: 'native-sidecar', encoding: 'h264', state: 'active' },+ input: { adapter: 'native-sidecar', state: 'active' },+ },+ ],+ },+ };+}++function sameContext(+ left: IOSSimulatorSlotFocusContext | null,+ right: IOSSimulatorSlotFocusContext,+): boolean {+ return (+ left?.sessionId === right.sessionId &&+ left.windowWebContentsId === right.windowWebContentsId &&+ left.revision === right.revision+ );+}++function makeSlot(overrides: Partial<IOSSimulatorSlotDeps> = {}) {+ let clock = 0;+ let revision = 1;+ let context: IOSSimulatorSlotFocusContext | null = {+ sessionId: 'session-a',+ windowWebContentsId: 101,+ revision,+ };+ const deps: IOSSimulatorSlotDeps = {+ getGhost: () => simulatorGhost(),+ focusedContext: () => context,+ isContextCurrent: (candidate) => sameContext(context, candidate),+ getStatus: vi.fn(async () => readyStatus()),+ focusViewer: vi.fn(() => true),+ now: () => clock,+ ...overrides,+ };+ return {+ slot: new GhostIOSSimulatorSlot(deps),+ deps,+ advance: (milliseconds: number) => {+ clock += milliseconds;+ },+ setContext: (sessionId: string | null, windowWebContentsId = 101) => {+ revision += 1;+ context = sessionId ? { sessionId, windowWebContentsId, revision } : null;+ },+ context: () => context,+ };+}++describe('GhostIOSSimulatorSlot', () => {+ it('requires the explicit slot and an enabled plugin', async () => {+ const noSlot = makeSlot({ getGhost: () => simulatorGhost({ slots: ['panel'] }) });+ await expect(+ noSlot.slot.handleRequest('ios-simulator', { kind: 'status' }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });++ const disabled = makeSlot({ getGhost: () => simulatorGhost({ enabled: false }) });+ await expect(+ disabled.slot.handleRequest('ios-simulator', { kind: 'status' }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });+ });++ it('reports the fixed low-bandwidth capability contract without a focused task', async () => {+ const test = makeSlot();+ test.setContext(null);+ await expect(+ test.slot.handleRequest('ios-simulator', { kind: 'capabilities' }),+ ).resolves.toEqual({+ ok: true,+ apiVersion: 1,+ kind: 'capabilities',+ capabilities: {+ status: true,+ openHostPanel: true,+ pluginVideo: false,+ pluginInput: false,+ },+ });+ });++ it('derives task identity from Host focus and exposes only the redacted status DTO', async () => {+ const { slot, deps } = makeSlot();+ const result = await slot.handleRequest('ios-simulator', { kind: 'status' });+ expect(deps.getStatus).toHaveBeenCalledWith('session-a');+ expect(result).toEqual({+ ok: true,+ apiVersion: 1,+ kind: 'status',+ status: (readyStatus() as Extract<GhostIOSSimulatorStatusProbeResult, { ok: true }>).status,+ });+ const serialized = JSON.stringify(result);+ expect(serialized).not.toContain('session-a');+ expect(serialized).not.toContain('simulatorUdid');+ expect(serialized).not.toContain('sourceFingerprint');+ expect(serialized).not.toContain('lease');+ expect(serialized).not.toContain('deviceGrants');+ expect(serialized).not.toContain('mutationStates');+ });++ it('rejects caller-supplied identity, unknown operations, and malformed instance IDs', async () => {+ const { slot, deps } = makeSlot();+ await expect(+ slot.handleRequest('ios-simulator', { kind: 'status', sessionId: 'forged-session' }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'INVALID_REQUEST' });+ await expect(+ slot.handleRequest('ios-simulator', { kind: 'stream-frames' }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'INVALID_REQUEST' });+ await expect(+ slot.handleRequest('ios-simulator', { kind: 'open-panel', instanceId: ' '.repeat(2) }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'INVALID_REQUEST' });+ expect(deps.getStatus).not.toHaveBeenCalled();+ });++ it('opens only a current-task instance and can open an unbound Host panel', async () => {+ const test = makeSlot();+ const initialContext = test.context();+ await expect(+ test.slot.handleRequest('ios-simulator', {+ kind: 'open-panel',+ instanceId: 'instance-a',+ }),+ ).resolves.toEqual({+ ok: true,+ apiVersion: 1,+ kind: 'open-panel',+ instanceId: 'instance-a',+ });+ expect(test.deps.focusViewer).toHaveBeenCalledWith(initialContext, 'instance-a');++ test.advance(GHOST_IOS_SIMULATOR_OPEN_MIN_INTERVAL_MS);+ await expect(test.slot.handleRequest('ios-simulator', { kind: 'open-panel' })).resolves.toEqual(+ { ok: true, apiVersion: 1, kind: 'open-panel' },+ );+ expect(test.deps.focusViewer).toHaveBeenCalledWith(initialContext, undefined);++ test.advance(GHOST_IOS_SIMULATOR_OPEN_MIN_INTERVAL_MS);+ await expect(+ test.slot.handleRequest('ios-simulator', { kind: 'open-panel', instanceId: 'foreign' }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'INSTANCE_NOT_OWNED' });+ });++ it('rate-limits opening before doing another Host status probe', async () => {+ const test = makeSlot();+ expect((await test.slot.handleRequest('ios-simulator', { kind: 'open-panel' })).ok).toBe(true);+ const callsAfterFirstOpen = vi.mocked(test.deps.getStatus).mock.calls.length;+ test.advance(GHOST_IOS_SIMULATOR_OPEN_MIN_INTERVAL_MS - 1);+ await expect(+ test.slot.handleRequest('ios-simulator', { kind: 'open-panel' }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'RATE_LIMITED' });+ expect(test.deps.getStatus).toHaveBeenCalledTimes(callsAfterFirstOpen);+ });++ it('single-flights and briefly caches read-only status probes', async () => {+ let resolveStatus!: (value: GhostIOSSimulatorStatusProbeResult) => void;+ const deferred = new Promise<GhostIOSSimulatorStatusProbeResult>((resolve) => {+ resolveStatus = resolve;+ });+ const getStatus = vi.fn(() => deferred);+ const test = makeSlot({ getStatus });+ const first = test.slot.handleRequest('ios-simulator', { kind: 'status' });+ const second = test.slot.handleRequest('ios-simulator', { kind: 'status' });+ expect(getStatus).toHaveBeenCalledTimes(1);+ resolveStatus(readyStatus());+ await expect(first).resolves.toMatchObject({ ok: true, kind: 'status' });+ await expect(second).resolves.toMatchObject({ ok: true, kind: 'status' });++ await test.slot.handleRequest('ios-simulator', { kind: 'status' });+ expect(getStatus).toHaveBeenCalledTimes(1);+ test.advance(GHOST_IOS_SIMULATOR_STATUS_CACHE_MS);+ await test.slot.handleRequest('ios-simulator', { kind: 'status' });+ expect(getStatus).toHaveBeenCalledTimes(2);+ });++ it('fails closed if task/window context changes while status is in flight', async () => {+ let resolveStatus!: (value: GhostIOSSimulatorStatusProbeResult) => void;+ const test = makeSlot({+ getStatus: vi.fn(+ () =>+ new Promise<GhostIOSSimulatorStatusProbeResult>((resolve) => {+ resolveStatus = resolve;+ }),+ ),+ });+ const pending = test.slot.handleRequest('ios-simulator', {+ kind: 'open-panel',+ instanceId: 'instance-a',+ });+ test.setContext('session-b', 202);+ test.setContext('session-a', 101);+ resolveStatus(readyStatus());+ await expect(pending).resolves.toMatchObject({ ok: false, errorCode: 'HOST_NOT_READY' });+ expect(test.deps.focusViewer).not.toHaveBeenCalled();+ });++ it('fails closed for no active task, Host errors, and missing windows', async () => {+ const noTask = makeSlot();+ noTask.setContext(null);+ await expect(+ noTask.slot.handleRequest('ios-simulator', { kind: 'status' }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'HOST_NOT_READY' });++ const statusError = makeSlot({+ getStatus: vi.fn(async (): Promise<GhostIOSSimulatorStatusProbeResult> => ({+ ok: false,+ errorCode: 'UNSUPPORTED_SESSION_KIND',+ message: 'Remote tasks are not supported.',+ })),+ });+ await expect(+ statusError.slot.handleRequest('ios-simulator', { kind: 'status' }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'UNSUPPORTED_SESSION_KIND' });++ const noWindow = makeSlot({ focusViewer: vi.fn(() => false) });+ await expect(+ noWindow.slot.handleRequest('ios-simulator', { kind: 'open-panel' }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'HOST_NOT_READY' });+ });+});diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex b780ee2c4a..ccab365ad7 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -1159,7 +1159,7 @@ key、未知字段、原清单没有的条目、类型或长度不合格、文node secretBindings key、setup kv key——都不能使用 \`__proto__\`、\`constructor\` 或\`prototype\`;这些名称是宿主保留键,打包时会直接拒绝。-十六个卡槽:\`tool\`(注册工具给 AI)、\`cindy\`(请 Cindy 本体代办:出图/改图/快问快答,+十八个卡槽:\`tool\`(注册工具给 AI)、\`cindy\`(请 Cindy 本体代办:出图/改图/快问快答,见 §4 与 §4.0.2)、\`agent\`(让当前 Agent 开始一个普通用户回合,或派活取回结果,见 §4.11 / §4.11.1)、\`panel\`(常驻面板)、\`card\`(聊天卡片:自绘工具调用的过程与结果,见 §4.5)、\`subscribe\`(旁听会话@@ -1173,7 +1173,8 @@ Node 工作进程或 stdio MCP,见 §4.12)、\`session-context\`(派活时主机用户亲选即授权,见 §4.14)、\`preview\`(请主机在右侧栏内置浏览器打开白名单网站的预览标签,见 §4.15)、\`skill\`(捆绑 Agent Skills:随包 SKILL.md 技能,启用后Claude Code 与 Codex 都能发现,见 §4.16)、\`workspace\`(请主机为项目目录在-侧边栏创建/复用会话入口,见 §4.17)。+侧边栏创建/复用会话入口,见 §4.17)、\`ios-simulator\`(读取当前台前任务的+公开 iOS 模拟器状态并打开 Host 内置控制面板,见 §4.19)。**agent 能力详单**:在 \`slots\` 加 \`"agent"\`,默认只允许在用户真实点击你的聊天卡片后发起一次 Agent 回合;这一档不写配套字段。若确实需要没有当次点击也能@@ -3170,7 +3171,7 @@ SKILL.md 硬规则(打包与装入双侧强制,任一不满足直接拒):信任与作用域(如实告知用户,也请作者自重):- 技能指令由**主 Agent 以用户全部权限执行**,对所有项目、所有会话生效,- **不受插件沙箱约束**——这是十五个卡槽里信任面最高的能力,装入确认框会把+ **不受插件沙箱约束**——这是十八个卡槽里信任面最高的能力,装入确认框会把每个技能置顶逐条列出;- 技能跟随插件的**全局**启用状态:仅在某个工作目录停用插件**不会**隐藏技能,只有全局停用或卸载才撤链(本期只有全局作用域);@@ -3268,6 +3269,53 @@ if (r.ok && r.confirmed) {工作区干不干净)确认前后都要自己再查一遍**——用户点确认和你真动手之间,世界可能已经变了。+## 4.19 内置 iOS 模拟器(ios-simulator 槽)++要给插件提供内置 iOS 模拟器的状态入口或工作流面板时,声明 \`ios-simulator\` 槽。+电子脑只能读取**当前台前任务**的公开状态,并请求主机打开 Cindy 自己的模拟器面板:++标准产品形态只需 \`skill + ios-simulator\`:Host 会在任务右侧栏提供手动入口,+Agent 通过 Skill 调 Host MCP。不要为了重复同一状态再声明 \`panel\`;插件停靠面板的关闭+语义是停用整份插件,不适合作为模拟器 viewer 的替身。只有确实存在 Host viewer 没有的独立+工作流 UI 时才额外声明 panel。++\`\`\`js+const caps = await cindy.iosSimulator.request({ kind: 'capabilities' });+// caps.apiVersion === 1;pluginVideo/pluginInput 都是 false++const current = await cindy.iosSimulator.request({ kind: 'status' });+if (current.ok) {+ const instances = current.status.instances;+ const routeStatuses = current.status.routeStatuses || [];+}++const opened = await cindy.iosSimulator.request({+ kind: 'open-panel',+ // 可选:只能填上面 status 返回、且仍属于当前任务的 instanceId+ instanceId: current.ok ? current.status.instances[0]?.instanceId : undefined+});+\`\`\`++规则与红线:++- 请求里**没有 sessionId**。台前任务由 Host 现查;自造 \`sessionId\`、其它未知字段+ 或跨任务 instanceId 都会拒绝。切到非任务页、远程/SSH 任务或任务失效时 fail closed;+- \`status\` 只返回环境是否就绪、可用设备数量、公开实例状态和当前 stream/input 路线。+ 它不续租、不启动 driver,也不返回 UDID、路径、授权、诊断或 ownership 信息;+- 本槽不是模拟器运行时:WDA、Native Sidecar、H.264、Native HID、生命周期、恢复与+ fallback 仍由 Cindy Host 独占。插件拿不到视频帧、viewer lease、触控入口、进程句柄、+ artifact 路径或 Xcode 私有诊断;+- \`open-panel\` 只打开/聚焦 Host 既有面板。没有绑定实例时可省略 instanceId,让用户+ 在 Host 面板里选择设备;连续请求会限速;+- panel.html 保持零桥。面板要使用本槽时,按 §5 先 \`/wake\`,再用同源+ BroadcastChannel 把请求交给 main.js,由 main.js 调 \`cindy.iosSimulator.request\`;+- Agent 构建、安装、启动与 UI 操作继续调用 Host 注册的 \`cindy_ios_simulator\` MCP。+ 插件 Skill 可以编排这套工作流,但不要用 shell 打开外部 Simulator.app,也不要重复+ 打包一份 WDA/Sidecar;+- 本能力仅存在于带该槽的 Cindy Desktop。当前 Host 遇到未来 schema 或未知 capability+ slot 时会把包识别为“需要更新 Cindy”,而不是误报插件非法。已发布的旧 Host 无法追改;+ Skill 在 MCP 不存在时仍必须引导用户升级 Cindy,不要降级成 shell 或 Node 替代实现。+## 5. 面板(panel.html/css/js)- 显示形态由 \`panel.position\` 决定:\`left\`(缺省)= 停靠主聊天窗左侧的常驻diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 2ce259c111..871f3a5683 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -1,4 +1,12 @@-import { app, BrowserWindow, dialog, ipcMain, safeStorage, shell, type WebContents } from 'electron';+import {+ app,+ BrowserWindow,+ dialog,+ ipcMain,+ safeStorage,+ shell,+ type WebContents,+} from 'electron';import fs from 'node:fs';import path from 'node:path';import { isDeepStrictEqual } from 'node:util';@@ -82,11 +90,7 @@ import {setGhostWakeHandler,} from './runtime/electronSandboxAdapter.js';import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';-import {- createGhostKvStore,- removeGhostKvBestEffort,- type GhostKvStore,-} from './ghostKvStore.js';+import { createGhostKvStore, removeGhostKvBestEffort, type GhostKvStore } from './ghostKvStore.js';import {evaluateGhostSetupAssessment,handleGhostSetupStatusRequest,@@ -149,7 +153,13 @@ import { GhostCardService, parseCardHeightReport } from './cardService.js';import { GhostCardActionDispatcher } from './cardActionDispatch.js';import { GhostSessionActivityTracker } from './ghostSessionActivity.js';import { sanitizeGhostCardHtml } from './cardSanitizer.js';-import { getGhostCard, listGhostCardsBySession, reassignGhostCards, updateGhostCardHeight, upsertGhostCard } from './cardStoreDb.js';+import {+ getGhostCard,+ listGhostCardsBySession,+ reassignGhostCards,+ updateGhostCardHeight,+ upsertGhostCard,+} from './cardStoreDb.js';import { updateMessageContent } from '../localDb/ipc/messages.js';import { runAssistantReplyHook } from './assistantReplyHook.js';import { submitAndAwaitVideo } from '../cindy-proxy-media/video/run.js';@@ -174,6 +184,8 @@ import { recordGhostPickedDir } from './pickGrantsStore.js';import { GhostPreviewSlot } from './previewSlot.js';import { GhostScheduleSlot, isMainShellWindowUrl } from './scheduleSlot.js';import { GhostWorkspaceSlot, type WorkspaceSessionService } from './workspaceSlot.js';+import { GhostIOSSimulatorSlot, type IOSSimulatorSlotFocusContext } from './iosSimulatorSlot.js';+import { getIOSSimulatorPluginStatus } from '../mcp-integrations/ios-simulator.js';import type { GhostTrustRegistry } from './ghostSignature.js';import { GhostNotifySlot, sanitizeGhostNoticeText } from './notifySlot.js';import { GhostBadgeSlot } from './badgeSlot.js';@@ -184,10 +196,7 @@ import {readGhostUnread,type GhostUnreadEntry,} from './ghostUnreadStore.js';-import {- isGhostUnreadProjectable,- selectRevokedGhostUnreadIds,-} from './ghostUnreadProjection.js';+import { isGhostUnreadProjectable, selectRevokedGhostUnreadIds } from './ghostUnreadProjection.js';import { GhostConfirmSlot } from './confirmSlot.js';import {getGhostConfirmDialogBridge,@@ -200,10 +209,7 @@ import {loadConnectionAudienceResolver,type ConnectionAudienceResolver,} from './connectionAudienceResolver.js';-import {- ConnectionTokenProvider,- type IssuedConnectionToken,-} from './connectionTokenProvider.js';+import { ConnectionTokenProvider, type IssuedConnectionToken } from './connectionTokenProvider.js';import { GhostFsSlot } from './fsSlot.js';import { getGhostGrantConfirmBridge } from './ghostGrantConfirmBridge.js';import { getSessionFsSnapshot } from '../localDb/ipc/sessions.js';@@ -300,10 +306,7 @@ import {createLegacyGhostRecoveryIpcHandlers,} from './legacyGhostRecoveryIpc.js';import type { LegacyGhostRecoveryStatus } from '../../shared/legacyGhostRecovery.js';-import {- isDataOwnerPushStamp,- type DataOwnerPushStamp,-} from '../../shared/dataOwnerPush.js';+import { isDataOwnerPushStamp, type DataOwnerPushStamp } from '../../shared/dataOwnerPush.js';/*** 意识仓库的进程级单例 + IPC 注册。@@ -331,10 +334,7 @@ function getGhostOwnerPushStamp(): DataOwnerPushStamp | undefined {}}-function isSameGhostOwnerStamp(- a: DataOwnerPushStamp,- b: DataOwnerPushStamp,-): boolean {+function isSameGhostOwnerStamp(a: DataOwnerPushStamp, b: DataOwnerPushStamp): boolean {return a.dataOwnerId === b.dataOwnerId && a.ownerGeneration === b.ownerGeneration;}@@ -514,9 +514,7 @@ async function retryLegacyGhostRecoveryForActiveSession(): Promise<LegacyGhostReif (!authorizedStatus.canRetry) return authorizedStatus;const existingGhosts = getGhostManager().list();- const existingGhostById = new Map(- existingGhosts.map((ghost) => [ghost.manifest.id, ghost]),- );+ const existingGhostById = new Map(existingGhosts.map((ghost) => [ghost.manifest.id, ghost]));const existingGhostDirs = new Map(existingGhosts.map((ghost) => [ghost.manifest.id, ghost.dir]),);@@ -531,10 +529,9 @@ async function retryLegacyGhostRecoveryForActiveSession(): Promise<LegacyGhostReapp.getPath('userData'),);const excludedBuiltinIds = new Set(- listLegacyGhostTombstoneRoots(- expectedOwner.dataOwnerId,- app.getPath('userData'),- ).flatMap((root) => readBuiltinTombstones(root)),+ listLegacyGhostTombstoneRoots(expectedOwner.dataOwnerId, app.getPath('userData')).flatMap(+ (root) => readBuiltinTombstones(root),+ ),);const reservedBuiltinCommands = new Set(listEligibleBuiltinCommands(@@ -560,10 +557,7 @@ async function retryLegacyGhostRecoveryForActiveSession(): Promise<LegacyGhostRe});}}- const restoreGhostRuntimes = (- ghost: InstalledGhost,- stopped: StoppedActiveGhost,- ): void => {+ const restoreGhostRuntimes = (ghost: InstalledGhost, stopped: StoppedActiveGhost): void => {spawnIfResident(ghost);if (stopped.browserRuntimeRunning &&@@ -631,10 +625,7 @@ async function retryLegacyGhostRecoveryForActiveSession(): Promise<LegacyGhostReconst movedGhostIds = new Set<string>();for (const ghost of restoredBeforeReconcile) {const previousDir = existingGhostDirs.get(ghost.manifest.id);- if (- previousDir !== undefined &&- path.resolve(previousDir) !== path.resolve(ghost.dir)- ) {+ if (previousDir !== undefined && path.resolve(previousDir) !== path.resolve(ghost.dir)) {movedGhostIds.add(ghost.manifest.id);getGhostRuntime().stop(ghost.manifest.id);getGhostNodeRuntimeBroker().stop(ghost.manifest.id);@@ -642,15 +633,14 @@ async function retryLegacyGhostRecoveryForActiveSession(): Promise<LegacyGhostRe}const builtinReconcileSucceeded =result.deferredReason !== 'concurrent-live-instances' &&- await scheduleBuiltinReconcile('legacy-recovery');+ (await scheduleBuiltinReconcile('legacy-recovery'));if (shouldAbort()) return getLegacyGhostRecoveryStatusForActiveSession();const ghosts = getGhostManager().list();for (const ghost of ghosts) {const previousDir = existingGhostDirs.get(ghost.manifest.id);const relocatedExistingGhost =movedGhostIds.has(ghost.manifest.id) ||- (previousDir !== undefined &&- path.resolve(previousDir) !== path.resolve(ghost.dir));+ (previousDir !== undefined && path.resolve(previousDir) !== path.resolve(ghost.dir));if (relocatedExistingGhost) ensureGhostProtocolRegistered(ghost);const stopped = stoppedActiveGhosts.get(ghost.manifest.id);if (relocatedExistingGhost && stopped) {@@ -678,9 +668,9 @@ export function isGhostAvailableForActiveSession(id: string): boolean {}function availableGhosts(): InstalledGhost[] {- return getGhostManager().list().filter((ghost) =>- isGhostAvailableForActiveSession(ghost.manifest.id),- );+ return getGhostManager()+ .list()+ .filter((ghost) => isGhostAvailableForActiveSession(ghost.manifest.id));}function projectGhostForRenderer(ghost: InstalledGhost): InstalledGhost {@@ -709,7 +699,11 @@ function projectGhostForRenderer(ghost: InstalledGhost): InstalledGhost {function findAvailableGhost(id: string): InstalledGhost | null {if (!isGhostAvailableForActiveSession(id)) return null;- return getGhostManager().list().find((ghost) => ghost.manifest.id === id) ?? null;+ return (+ getGhostManager()+ .list()+ .find((ghost) => ghost.manifest.id === id) ?? null+ );}function requireGhostAvailableForActiveSession(id: string): void {@@ -827,7 +821,8 @@ function cleanupRetiredGhostData(id: string): void {removeGhostSecrets(id);} catch (err) {log.warn('retired ghost secret cleanup failed', {- id, error: err instanceof Error ? err.message : String(err),+ id,+ error: err instanceof Error ? err.message : String(err),});}for (const target of [@@ -840,7 +835,9 @@ function cleanupRetiredGhostData(id: string): void {log.info('retired ghost data removed', { id, target });} catch (err) {log.warn('retired ghost data cleanup failed', {- id, target, error: err instanceof Error ? err.message : String(err),+ id,+ target,+ error: err instanceof Error ? err.message : String(err),});}}@@ -860,7 +857,9 @@ function migrateGhostKvOnRename(fromId: string, toId: string): void {log.info('ghost kv migrated after builtin rename', { fromId, toId });} catch (err) {log.warn('ghost kv migrate failed', {- fromId, toId, error: err instanceof Error ? err.message : String(err),+ fromId,+ toId,+ error: err instanceof Error ? err.message : String(err),});}}@@ -881,10 +880,7 @@ async function reconcileBuiltinGhosts(reason: string): Promise<void> {clearBuiltinTombstone(brainRootDir(), fromId, log);log.info('builtin ghost tombstone carried over rename', { fromId, toId });}- renameDisabledCarry.set(- toId,- fs.existsSync(path.join(brainRootDir(), fromId, '.disabled')),- );+ renameDisabledCarry.set(toId, fs.existsSync(path.join(brainRootDir(), fromId, '.disabled')));}// "播种进行中"胶囊提示:只在真的动手(装/覆盖/回收)时亮起,no-op 对账// 不闪(onApplyStart 整轮至多一次);结束广播放 finally,异常也不留悬挂提示。@@ -920,7 +916,9 @@ async function reconcileBuiltinGhosts(reason: string): Promise<void> {for (const [fromId, toId] of RENAMED_BUILTIN_GHOSTS) {void reassignGhostCards(fromId, toId).catch((err) =>log.warn('ghost card reassign failed', {- fromId, toId, error: err instanceof Error ? err.message : String(err),+ fromId,+ toId,+ error: err instanceof Error ? err.message : String(err),}),);migrateGhostKvOnRename(fromId, toId);@@ -938,11 +936,17 @@ async function reconcileBuiltinGhosts(reason: string): Promise<void> {log.info('builtin ghost disabled state carried over rename', { id: manifest.id });} catch (err) {log.warn('builtin ghost disabled carry failed', {- id: manifest.id, error: err instanceof Error ? err.message : String(err),+ id: manifest.id,+ error: err instanceof Error ? err.message : String(err),});}}- if (outcome.installed.length === 0 && outcome.updated.length === 0 && outcome.removed.length === 0) return;+ if (+ outcome.installed.length === 0 &&+ outcome.updated.length === 0 &&+ outcome.removed.length === 0+ )+ return;log.info('builtin ghost reconcile applied changes', {reason,installed: outcome.installed.map((m) => m.id),@@ -962,7 +966,10 @@ async function reconcileBuiltinGhosts(reason: string): Promise<void> {if (docked) {const applied = store.setLayout(docked);if ('rejection' in applied) {- log.warn('builtin ghost panel dock rejected', { id: manifest.id, reason: applied.rejection });+ log.warn('builtin ghost panel dock rejected', {+ id: manifest.id,+ reason: applied.rejection,+ });}}// 登录触发的对账装上常驻意识时,这里就是它的点火时机(启动那趟扫描早过了)。@@ -1082,7 +1089,10 @@ let agentSlotSingleton: GhostAgentSlot | null = null;export function getGhostAgentSlot(): GhostAgentSlot {if (!agentSlotSingleton) {agentSlotSingleton = new GhostAgentSlot({- getGhost: (id) => getGhostManager().list().find((g) => g.manifest.id === id) ?? null,+ getGhost: (id) =>+ getGhostManager()+ .list()+ .find((g) => g.manifest.id === id) ?? null,log,});}@@ -1100,7 +1110,10 @@ let errandSlotSingleton: GhostErrandSlot | null = null;export function getGhostErrandSlot(): GhostErrandSlot {if (!errandSlotSingleton) {errandSlotSingleton = new GhostErrandSlot({- getGhost: (id) => getGhostManager().list().find((g) => g.manifest.id === id) ?? null,+ getGhost: (id) =>+ getGhostManager()+ .list()+ .find((g) => g.manifest.id === id) ?? null,// wait 模式的署名单在途期间替管子那头的 tool-call 续命(同 cindy 槽契约)。holdPipeCall: (ghostId, callId, budgetMs) =>getGhostPipeDispatcher().holdCall(ghostId, callId, budgetMs),@@ -1118,7 +1131,11 @@ export function setGhostErrandRunner(runner: GhostErrandRunner | null): void {/** 插件展示名(errand 会话默认标题等宿主侧使用;未装返回 null)。 */export function getInstalledGhostName(id: string): string | null {- return getGhostManager().list().find((g) => g.manifest.id === id)?.manifest.name ?? null;+ return (+ getGhostManager()+ .list()+ .find((g) => g.manifest.id === id)?.manifest.name ?? null+ );}let nodeRuntimeBrokerSingleton: GhostNodeRuntimeBroker | null = null;@@ -1127,7 +1144,10 @@ let nodeRuntimeBrokerSingleton: GhostNodeRuntimeBroker | null = null;export function getGhostNodeRuntimeBroker(): GhostNodeRuntimeBroker {if (!nodeRuntimeBrokerSingleton) {nodeRuntimeBrokerSingleton = new GhostNodeRuntimeBroker({- getGhost: (id) => getGhostManager().list().find((g) => g.manifest.id === id) ?? null,+ getGhost: (id) =>+ getGhostManager()+ .list()+ .find((g) => g.manifest.id === id) ?? null,readSecret: (ghostId, secretKey) => readGhostSecret(ghostId, secretKey),sendToGhost: (ghostId, payload) => {sendToGhostLogic(ghostId, payload);@@ -1219,8 +1239,7 @@ export function getGhostCardActionDispatcher(): GhostCardActionDispatcher {getGhostAgentSlot().issueUserActionToken(ghostId, sessionId),// 呼吸起点:点击成功投递即把该会话标为"意识活动中"(结束由 card-update// state / TTL 收口)。- onActivityStart: (key, sessionId) =>- getGhostSessionActivityTracker().begin(key, sessionId),+ onActivityStart: (key, sessionId) => getGhostSessionActivityTracker().begin(key, sessionId),now: () => Date.now(),log,});@@ -1266,10 +1285,14 @@ export function getGhostSubscriptionGateway(): GhostSubscriptionGateway {},now: () => Date.now(),onHookFused: (ghost, ownerStamp) => {- broadcastGhostWindowPush(GHOST_HOOK_FUSED_CHANNEL, {- ghostId: ghost.manifest.id,- name: ghost.manifest.name,- }, isDataOwnerPushStamp(ownerStamp) ? ownerStamp : undefined);+ broadcastGhostWindowPush(+ GHOST_HOOK_FUSED_CHANNEL,+ {+ ghostId: ghost.manifest.id,+ name: ghost.manifest.name,+ },+ isDataOwnerPushStamp(ownerStamp) ? ownerStamp : undefined,+ );},log,});@@ -1349,14 +1372,8 @@ type PendingActivityRequest = {export function createGhostSessionTap(sessionId: string): {handleEvent(ev: MinimalAgentEvent & { turnOrigin?: { kind?: string } }): void;interactionObserver: {- onStart(- request: PendingActivityRequest,- route?: { origin?: { kind?: string } },- ): void;- onEnd(- request: PendingActivityRequest,- route?: { origin?: { kind?: string } },- ): void;+ onStart(request: PendingActivityRequest, route?: { origin?: { kind?: string } }): void;+ onEnd(request: PendingActivityRequest, route?: { origin?: { kind?: string } }): void;};dispose(): void;} {@@ -1382,10 +1399,7 @@ export function createGhostSessionTap(sessionId: string): {});});- const applyActivity = (- phase: 'start' | 'end',- request: PendingActivityRequest,- ): void => {+ const applyActivity = (phase: 'start' | 'end', request: PendingActivityRequest): void => {if (!activity) {pending.push({ type: 'activity', phase, request });return;@@ -1556,11 +1570,13 @@ export async function screenGhostUserMessage(): Promise<GhostScreenResult> {const ownerStamp = getGhostOwnerPushStamp();try {- const hasHookGhost = availableGhosts()- .some((g) => g.enabled && g.manifest.subscribe?.hooks?.includes('will-user-message'));+ const hasHookGhost = availableGhosts().some(+ (g) => g.enabled && g.manifest.subscribe?.hooks?.includes('will-user-message'),+ );if (!hasHookGhost) return { action: 'allow' };// retry(DB 未就绪)也放行:拦截是尽力而为的旁路,fail-open 不挡发送。- if ((await isGhostEligibleSession(sessionId)).outcome !== 'eligible') return { action: 'allow' };+ if ((await isGhostEligibleSession(sessionId)).outcome !== 'eligible')+ return { action: 'allow' };const result = await getGhostSubscriptionGateway().screenUserMessage({ sessionId, text },ownerStamp,@@ -1606,18 +1622,22 @@ export function broadcastGhostMessageRewritten(payload: {/** 是否有启用的意识声明了 will-assistant-message(出口钩子快路径同步守卫)。 */export function hasEnabledGhostAssistantHook(): boolean {- return availableGhosts()- .some((g) => g.enabled && g.manifest.subscribe?.hooks?.includes('will-assistant-message'));+ return availableGhosts().some(+ (g) => g.enabled && g.manifest.subscribe?.hooks?.includes('will-assistant-message'),+ );}/** 广播:AI 回复被出口钩子改写(renderer 气泡静默换文本)。 */-function broadcastGhostAssistantRewritten(payload: {- sessionId: string;- clientId: string;- ghostId: string;- ghostName: string;- text: string;-}, ownerStamp?: DataOwnerPushStamp): void {+function broadcastGhostAssistantRewritten(+ payload: {+ sessionId: string;+ clientId: string;+ ghostId: string;+ ghostName: string;+ text: string;+ },+ ownerStamp?: DataOwnerPushStamp,+): void {broadcastGhostWindowPush(GHOST_ASSISTANT_REWRITTEN_CHANNEL, payload, ownerStamp);}@@ -1649,7 +1669,10 @@ async function applyGhostAssistantRenderCard(if (ownerStamp !== undefined && !isGhostOwnerStampCurrent(ownerStamp)) return;const sanitized = sanitizeGhostCardHtml(card.html);if (!sanitized.ok) {- log.warn('ghost assistant render card rejected by sanitizer', { sessionId, reason: sanitized.reason });+ log.warn('ghost assistant render card rejected by sanitizer', {+ sessionId,+ reason: sanitized.reason,+ });return;}const heightRaw =@@ -1699,14 +1722,19 @@ async function applyGhostAssistantRenderCard(* 阻塞 turn 结束记账;真实 deps 装配在此,核心编排在 assistantReplyHook.ts。* clientId = 本轮 assistant 消息持久化 id(consumeLastAssistantPersistId 取得)。*/-export function runGhostAssistantReplyHook(sessionId: string, clientId: string, text: string): void {+export function runGhostAssistantReplyHook(+ sessionId: string,+ clientId: string,+ text: string,+): void {const ownerStamp = getGhostOwnerPushStamp();const isCurrent = () => isGhostOwnerStampCurrent(ownerStamp);void runAssistantReplyHook({isCurrent,hasHook: hasEnabledGhostAssistantHook,- isEligible: async (sid) => isCurrent() && (await isGhostEligibleSession(sid)).outcome === 'eligible',+ isEligible: async (sid) =>+ isCurrent() && (await isGhostEligibleSession(sid)).outcome === 'eligible',screen: async (sid, t) => {if (!isCurrent()) return { action: 'allow' as const };const result = await getGhostSubscriptionGateway().screenAssistantMessage(@@ -1721,8 +1749,7 @@ export function runGhostAssistantReplyHook(sessionId: string, clientId: string,},applyRenderCard: (sid, cid, cardArg) =>applyGhostAssistantRenderCard(sid, cid, cardArg, ownerStamp),- broadcastRewritten: (payload) =>- broadcastGhostAssistantRewritten(payload, ownerStamp),+ broadcastRewritten: (payload) => broadcastGhostAssistantRewritten(payload, ownerStamp),setPending: (sid, cid, pending) =>broadcastGhostAssistantPending(sid, cid, pending, ownerStamp),log,@@ -1745,8 +1772,9 @@ export function notifyGhostSessionEvent(void (async () => {try {// 快路径:没人订 session topic 就不查 DB(纯内存判断,调用方零负担)。- const hasSubscriber = availableGhosts()- .some((g) => g.enabled && g.manifest.subscribe?.topics?.includes('session'));+ const hasSubscriber = availableGhosts().some(+ (g) => g.enabled && g.manifest.subscribe?.topics?.includes('session'),+ );if (!hasSubscriber) return;// 投递范围与 turn 事件同口径:只投用户主会话(retry 视为不投,// 生命周期事件不值得重试机制)。@@ -1754,9 +1782,10 @@ export function notifyGhostSessionEvent(if (info.outcome !== 'eligible') return;// switched 的调用方(renderer 路由上报)只有 sessionId,workdir 从资格// 查询顺手补上,与 created/archived 的载荷形状对齐。- const payload = data.workdir === undefined && info.workdir !== undefined- ? { ...data, workdir: info.workdir }- : data;+ const payload =+ data.workdir === undefined && info.workdir !== undefined+ ? { ...data, workdir: info.workdir }+ : data;getGhostSubscriptionGateway().publish('session',kind === 'created'@@ -1784,6 +1813,109 @@ export function noteGhostSessionFocused(sessionId: string | null): void {ghostSessionFocusTracker.note(sessionId);}+type GhostWindowSessionFocus = {+ sessionId: string | null;+ revision: number;+};++const ghostSessionFocusByWebContents = new Map<number, GhostWindowSessionFocus>();+const ghostSessionFocusTrackedWebContents = new Set<number>();+let ghostSessionFocusRevision = 0;++function noteGhostWindowSessionFocused(sender: WebContents, sessionId: string | null): void {+ const previous = ghostSessionFocusByWebContents.get(sender.id);+ if (previous?.sessionId === sessionId) return;+ ghostSessionFocusRevision += 1;+ ghostSessionFocusByWebContents.set(sender.id, {+ sessionId,+ revision: ghostSessionFocusRevision,+ });+ if (!ghostSessionFocusTrackedWebContents.has(sender.id)) {+ ghostSessionFocusTrackedWebContents.add(sender.id);+ sender.once('destroyed', () => {+ ghostSessionFocusByWebContents.delete(sender.id);+ ghostSessionFocusTrackedWebContents.delete(sender.id);+ });+ }+ noteGhostSessionFocused(sessionId);+}++function mainShellWindows(): BrowserWindow[] {+ return BrowserWindow.getAllWindows().filter(+ (window) => !window.isDestroyed() && isMainShellWindowUrl(window.webContents.getURL()),+ );+}++function focusedIOSSimulatorContext(): IOSSimulatorSlotFocusContext | null {+ const candidates = mainShellWindows();+ const focused = BrowserWindow.getFocusedWindow();+ const focusedMainShell =+ focused && !focused.isDestroyed() && candidates.includes(focused) ? focused : null;+ // 主壳窗在前台时只认它自己的任务;它在非任务页时不能借用另一窗口的任务。+ const eligible = focusedMainShell+ ? [focusedMainShell]+ : candidates.filter((window) => {+ const focus = ghostSessionFocusByWebContents.get(window.webContents.id);+ return Boolean(focus?.sessionId);+ });+ // 独立插件窗没有可信 opener/task 绑定;只有唯一候选时才允许回落,多窗歧义 fail closed。+ if (eligible.length !== 1) return null;+ const window = eligible[0]!;+ const focus = ghostSessionFocusByWebContents.get(window.webContents.id);+ if (!focus?.sessionId) return null;+ return {+ sessionId: focus.sessionId,+ windowWebContentsId: window.webContents.id,+ revision: focus.revision,+ };+}++function isIOSSimulatorContextCurrent(context: IOSSimulatorSlotFocusContext): boolean {+ const current = focusedIOSSimulatorContext();+ return (+ current?.sessionId === context.sessionId &&+ current.windowWebContentsId === context.windowWebContentsId &&+ current.revision === context.revision+ );+}++let iosSimulatorSlotSingleton: GhostIOSSimulatorSlot | null = null;++/**+ * 插件只获知脱敏状态并可请求当前主窗口打开 Host 面板。实际视频、输入、+ * 生命周期与 fallback 均留在 iOS Simulator Host,不经插件逻辑页中转。+ */+export function getGhostIOSSimulatorSlot(): GhostIOSSimulatorSlot {+ if (!iosSimulatorSlotSingleton) {+ iosSimulatorSlotSingleton = new GhostIOSSimulatorSlot({+ getGhost: findAvailableGhost,+ focusedContext: focusedIOSSimulatorContext,+ isContextCurrent: isIOSSimulatorContextCurrent,+ getStatus: getIOSSimulatorPluginStatus,+ focusViewer: (context, instanceId) => {+ if (!isIOSSimulatorContextCurrent(context)) return false;+ const window = mainShellWindows().find(+ (candidate) => candidate.webContents.id === context.windowWebContentsId,+ );+ if (!window) return false;+ try {+ if (window.isDestroyed() || window.webContents.isDestroyed()) return false;+ window.webContents.send('maker:ios-simulator:focus-request', {+ sessionId: context.sessionId,+ ...(instanceId ? { instanceId } : {}),+ userInitiated: false,+ });+ return true;+ } catch {+ return false;+ }+ },+ log,+ });+ }+ return iosSimulatorSlotSingleton;+}+let cindySlotSingleton: GhostCindySlot | null = null;let networkSlotSingleton: GhostNetworkSlot | null = null;let notifySlotSingleton: GhostNotifySlot | null = null;@@ -1802,7 +1934,9 @@ function getPluginMarketLedger(): PluginMarketLedger {/** Read the locale-independent manifest digest from the installed package. */function readInstalledGhostManifestDigest(ghostId: string): string | null {- const ghost = getGhostManager().list().find((candidate) => candidate.manifest.id === ghostId);+ const ghost = getGhostManager()+ .list()+ .find((candidate) => candidate.manifest.id === ghostId);if (!ghost) return null;try {const bytes = readBoundedFileNoFollowSync(@@ -1833,9 +1967,7 @@ function getConnectionAudienceResolver(): ConnectionAudienceResolver {return connectionAudienceResolverSingleton;}-function resolveConnectionAudienceForGhost(- ghostId: string,-): ConnectionAudienceResolution | null {+function resolveConnectionAudienceForGhost(ghostId: string): ConnectionAudienceResolution | null {const state = getAuthState();const user = state.isAuthenticated ? state.user : null;if (!user) return null;@@ -1883,7 +2015,11 @@ const hostNoticeLastAt = new Map<string, number>();*/export function broadcastGhostHostNotice(ghostId: string,- notice: { textKey: GhostHostNoticeKey; textArgs?: Record<string, string>; tone?: 'info' | 'success' | 'warning' | 'error' },+ notice: {+ textKey: GhostHostNoticeKey;+ textArgs?: Record<string, string>;+ tone?: 'info' | 'success' | 'warning' | 'error';+ },): void {const ghost = findAvailableGhost(ghostId);if (!ghost) return; // 卸载竞态:意识已不在,提示无从署名,静默丢@@ -1956,7 +2092,12 @@ export function sendToTrustedAppWindows(channel: string, payload: unknown): voidsendGhostTrustedWindowPush(channel, payload);}-function broadcastGhostBadge(payload: { ghostId: string; unread: boolean; summary?: string; at?: number }): void {+function broadcastGhostBadge(payload: {+ ghostId: string;+ unread: boolean;+ summary?: string;+ at?: number;+}): void {sendToTrustedAppWindows(GHOST_BADGE_CHANNEL, payload);}@@ -1989,7 +2130,9 @@ function visibleGhostUnread(): GhostUnreadEntry[] {// 磁盘扫描,而本函数服务的是**同步** ghosts:unread(首屏渲染路径),// 足以卡住启动(codex review)。const available = new Map(availableGhosts().map((ghost) => [ghost.manifest.id, ghost]));- return entries.filter((entry) => isGhostUnreadProjectable(available.get(entry.ghostId) ?? null));+ return entries.filter((entry) =>+ isGhostUnreadProjectable(available.get(entry.ghostId) ?? null),+ );} catch (error) {log.warn('ghost unread 读取失败', {error: error instanceof Error ? error.message : String(error),@@ -2208,7 +2351,10 @@ export function getGhostWorkspaceSlot(): GhostWorkspaceSlot {const win = BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0];if (!win || win.isDestroyed()) throw new Error('没有可挂靠的宿主窗口');// main 侧 t() 只插值 {{appName}},插件名在调用点替换(与 pick 槽同做法)。- const message = t('settings.ghosts.workspace.dialogMessage').replaceAll('{{name}}', ghostName);+ const message = t('settings.ghosts.workspace.dialogMessage').replaceAll(+ '{{name}}',+ ghostName,+ );const result = await dialog.showOpenDialog(win, {title: t('settings.ghosts.workspace.dialogTitle'),message: purpose ? `${message}\n${purpose}` : message,@@ -2237,7 +2383,10 @@ export function getGhostWorkspaceSlot(): GhostWorkspaceSlot {},isInsideWorkdir: (dirAbs, workdirAbs) => {try {- return isPathInsideDir(fs.realpathSync.native(workdirAbs), fs.realpathSync.native(dirAbs));+ return isPathInsideDir(+ fs.realpathSync.native(workdirAbs),+ fs.realpathSync.native(dirAbs),+ );} catch {return false;}@@ -2374,10 +2523,7 @@ function getCatalogMediaConfig(kind: CindyCapabilityKind): CindyMediaCatalogConf// 停用过滤:用户在 设置 → 模型供应商 停用的媒体模型 / 供应商不进候选清单// (与对话模型的准入口径同源,见 model-disable-store)。const access = readModelDisableOverrides();- const catalog = projectProviderCatalogForBuildRegion(- getActiveCatalog(),- CURRENT_CINDY_REGION,- );+ const catalog = projectProviderCatalogForBuildRegion(getActiveCatalog(), CURRENT_CINDY_REGION);return deriveCindyMediaConfig(catalog.providers,kind,@@ -2405,7 +2551,9 @@ function getCatalogMediaConfig(kind: CindyCapabilityKind): CindyMediaCatalogConf: (providerId) => providerId !== 'xd' || getAppCapabilities().canUseCindyGateway,// 编辑就绪过滤:仅支持生成的来源(supportsEdit: false)的模型不进编辑清单,// 防用户把该型号钉到 image.edit 偏好后在 editImage 路径拿到确定性 400。- kind === 'image' ? (providerId) => getImageChannelRegistry().isProviderEditReady(providerId) : undefined,+ kind === 'image'+ ? (providerId) => getImageChannelRegistry().isProviderEditReady(providerId)+ : undefined,);} catch (err) {// 目录读取异常 = 拿不到可用性证明,同「空清单」处理(不静默顶一份旧名单)。@@ -2416,9 +2564,12 @@ function getCatalogMediaConfig(kind: CindyCapabilityKind): CindyMediaCatalogConf}}-const getCatalogImageConfig = (): ReturnType<typeof getCatalogMediaConfig> => getCatalogMediaConfig('image');-const getCatalogVideoConfig = (): ReturnType<typeof getCatalogMediaConfig> => getCatalogMediaConfig('video');-const getCatalogEmbedConfig = (): ReturnType<typeof getCatalogMediaConfig> => getCatalogMediaConfig('embed');+const getCatalogImageConfig = (): ReturnType<typeof getCatalogMediaConfig> =>+ getCatalogMediaConfig('image');+const getCatalogVideoConfig = (): ReturnType<typeof getCatalogMediaConfig> =>+ getCatalogMediaConfig('video');+const getCatalogEmbedConfig = (): ReturnType<typeof getCatalogMediaConfig> =>+ getCatalogMediaConfig('embed');/*** 派发前重查(PR #744 review 第二十轮):cindySlot 从白名单校验到实际下单之间隔着@@ -2574,25 +2725,31 @@ function getImageChannelRegistry(): ImageChannelRegistry {...(aspectRatio ? { size: GHOST_ASPECT_TO_GATEWAY_SIZE[aspectRatio] } : {}),}),});- registry.register('xai', createXaiImageChannel({- hasOAuthLogin: () => hasGrokOAuthLogin(),- getAccessToken: () => getGrokAccessToken(),- getOwnerScopeKey: () => activeOwnerScopeKey(),- isOwnerBoundaryPending: () => isAppSessionBoundaryPending(),- fetchImplementation: ((url, init) => outboundFetch(url as string, init)) as typeof fetch,- beforeDispatch: (model) => assertMediaModelStillEnabled('image', model),- onAuthRejected: (failure) => invalidateXaiBridgeAuth(failure),- }));+ registry.register(+ 'xai',+ createXaiImageChannel({+ hasOAuthLogin: () => hasGrokOAuthLogin(),+ getAccessToken: () => getGrokAccessToken(),+ getOwnerScopeKey: () => activeOwnerScopeKey(),+ isOwnerBoundaryPending: () => isAppSessionBoundaryPending(),+ fetchImplementation: ((url, init) => outboundFetch(url as string, init)) as typeof fetch,+ beforeDispatch: (model) => assertMediaModelStillEnabled('image', model),+ onAuthRejected: (failure) => invalidateXaiBridgeAuth(failure),+ }),+ );// Gemini(BYO API key,generateContent wire):ready = key 已配置。停用轴// 派发前重查经 beforeDispatch 注入(与 xd 通道的 cindyProxyMedia beforeDispatch// 同语义 —— xd 的挂在网关客户端装配处,gemini 的挂在这里)。- registry.register('gemini', createGeminiImageChannel({- getApiKey: () => getProviderSecretStore().get('gemini'),- // googleapis 境外端点经 outboundFetch 吃系统代理:main 的裸 fetch 不读系统- // 代理设置,代理软件非 TUN 模式下会直连失败(xd 网关域名境内直连,不注)。- fetchImplementation: ((url, init) => outboundFetch(url as string, init)) as typeof fetch,- beforeDispatch: (model) => assertMediaModelStillEnabled('image', model),- }));+ registry.register(+ 'gemini',+ createGeminiImageChannel({+ getApiKey: () => getProviderSecretStore().get('gemini'),+ // googleapis 境外端点经 outboundFetch 吃系统代理:main 的裸 fetch 不读系统+ // 代理设置,代理软件非 TUN 模式下会直连失败(xd 网关域名境内直连,不注)。+ fetchImplementation: ((url, init) => outboundFetch(url as string, init)) as typeof fetch,+ beforeDispatch: (model) => assertMediaModelStillEnabled('image', model),+ }),+ );// OpenAI public Images API(BYO 平台 key):与 xd 网关同 wire,整个客户端复用,// 只换 baseUrl/品牌话术/凭证读取。ChatGPT/Codex 订阅走下方独立的 hosted-tool// 通道;目录 id 带 openai/ 前缀,public API 适配层剥前缀。@@ -2608,8 +2765,7 @@ function getImageChannelRegistry(): ImageChannelRegistry {editPath: '/v1/images/edits',},brandLabel: 'OpenAI',- missingKeyMessage:- 'OpenAI 图像 API key 未配置,请到「设置 → 模型供应商 → OpenAI」填入后重试',+ missingKeyMessage: 'OpenAI 图像 API key 未配置,请到「设置 → 模型供应商 → OpenAI」填入后重试',beforeDispatch: (model) => assertMediaModelStillEnabled('image', `openai/${model}`),});const stripOpenaiPrefix = (id: string) =>@@ -2634,7 +2790,9 @@ function getImageChannelRegistry(): ImageChannelRegistry {? openaiImagesClient.generateImage({model: stripOpenaiPrefix(params.model),prompt: params.prompt,- ...(params.aspectRatio ? { size: GHOST_ASPECT_TO_GATEWAY_SIZE[params.aspectRatio] } : {}),+ ...(params.aspectRatio+ ? { size: GHOST_ASPECT_TO_GATEWAY_SIZE[params.aspectRatio] }+ : {}),}): codexImagesClient.generateImage(params),editImage: (params) =>@@ -2643,7 +2801,9 @@ function getImageChannelRegistry(): ImageChannelRegistry {model: stripOpenaiPrefix(params.model),prompt: params.prompt,imagePaths: params.imagePaths,- ...(params.aspectRatio ? { size: GHOST_ASPECT_TO_GATEWAY_SIZE[params.aspectRatio] } : {}),+ ...(params.aspectRatio+ ? { size: GHOST_ASPECT_TO_GATEWAY_SIZE[params.aspectRatio] }+ : {}),}): codexImagesClient.editImage(params),});@@ -2728,7 +2888,13 @@ export function getGhostCindySlot(): GhostCindySlot {readImageFileAsDataUri,refMode,);- return await runGhostVideo({ alias: model, prompt, imageDataUris, refMode, ...videoParams });+ return await runGhostVideo({+ alias: model,+ prompt,+ imageDataUris,+ refMode,+ ...videoParams,+ });} catch (err) {humanizeImageChannelError(err);}@@ -2756,9 +2922,8 @@ export function getGhostCindySlot(): GhostCindySlot {// 不归「聊天嵌入」开关独占 —— 那个开关关着时 host 不启动,直接取 service 必抛// not-started,已授权的 embed_text 全变 INTERNAL(PR #1707 review)。这里打标// 成"插件向量 consumer 在用"并按需懒启动。- const { ensureEmbeddingServiceForPluginVector } = await import(- '../embedding-host/index.js'- );+ const { ensureEmbeddingServiceForPluginVector } =+ await import('../embedding-host/index.js');// 白名单已在 slot 层校验过,这里是纵深防御:目录里出现了 embedding catalog// 不认识的 id(两边不同步)时早失败,而不是把不认识的 id 发去网关。if (!isKnownEmbeddingModel(model)) {@@ -2776,9 +2941,8 @@ export function getGhostCindySlot(): GhostCindySlot {},// 上下文化嵌入(voyage-context-* 索引侧):同上,只是 input 按文档分组。embedDocuments: async ({ documents, model, inputType, dimensions, timeoutMs }) => {- const { ensureEmbeddingServiceForPluginVector } = await import(- '../embedding-host/index.js'- );+ const { ensureEmbeddingServiceForPluginVector } =+ await import('../embedding-host/index.js');if (!isKnownEmbeddingModel(model)) {throw new Error(`未知的向量模型 ${model}(不在 embedding catalog 内)`);}@@ -2830,7 +2994,8 @@ export function getGhostCindySlot(): GhostCindySlot {// 管子续命挂钩:同步视频代办(署名单)在途期间替 tool-call 续命,// 免得分钟级生成被管子 330s 基础窗口掐掉(任务后台继续烧钱、结果作废)。// ghostId 由派发器配对验身:冒用他人在途 callId 不能续命/收短别人的卷。- holdPipeCall: (ghostId, callId, budgetMs) => getGhostPipeDispatcher().holdCall(ghostId, callId, budgetMs),+ holdPipeCall: (ghostId, callId, budgetMs) =>+ getGhostPipeDispatcher().holdCall(ghostId, callId, budgetMs),releasePipeCall: (ghostId, callId) => getGhostPipeDispatcher().releaseCall(ghostId, callId),// 视频型号预期耗时(registry 登记值;hold 预算与异步受理返回共用)。// registry 缺席/型号查无 → null,cindySlot 用自己的缺省。@@ -2845,10 +3010,7 @@ export function getGhostCindySlot(): GhostCindySlot {},resolveOwnedMedia: async (ghostId, hash, ownerScopeKey) => {const assertOwnerScopeCurrent = (): void => {- if (- isAppSessionBoundaryPending() ||- activeOwnerScopeKey() !== ownerScopeKey- ) {+ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== ownerScopeKey) {throw new Error('媒体任务期间账号已切换,本次结果已丢弃');}};@@ -2875,10 +3037,7 @@ export function getGhostCindySlot(): GhostCindySlot {},saveGhostMedia: async ({ ghostId, buffer, mimeType, ownerScopeKey, label, callId }) => {const assertOwnerScopeCurrent = (): void => {- if (- isAppSessionBoundaryPending() ||- activeOwnerScopeKey() !== ownerScopeKey- ) {+ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== ownerScopeKey) {throw new Error('媒体任务期间账号已切换,本次结果已丢弃');}};@@ -2924,12 +3083,14 @@ export function getGhostCindySlot(): GhostCindySlot {buffer,mimeType,isCache: false,- refs: [{- refKind: 'ghost-deposit',- refId: ghostId,- originKind: 'user',- ...(label ? { label } : {}),- }],+ refs: [+ {+ refKind: 'ghost-deposit',+ refId: ghostId,+ originKind: 'user',+ ...(label ? { label } : {}),+ },+ ],});return {url: r.url,@@ -3058,7 +3219,9 @@ function getGhostConnectionManager(): GhostConnectionManager {let ghostSetupKvStore: GhostKvStore | null = null;/** 默认 OAuth 账号的授权面陈旧建议;只返回首个凭证槽,保持 envelope 有界。 */-function getGhostOauthReauthSuggest(runtimeManifest: GhostManifest): GhostSetupReauthSuggest | undefined {+function getGhostOauthReauthSuggest(+ runtimeManifest: GhostManifest,+): GhostSetupReauthSuggest | undefined {const oauthManager = getGhostOauthAccountManager();return findGhostOauthReauthSuggest(runtimeManifest, (secretKey, decl) =>oauthManager.defaultMissingScopes(runtimeManifest.id, secretKey, decl),@@ -3102,8 +3265,7 @@ export function getGhostSetupAssessment(ghostId: string): GhostSetupAssessment {revision: getGhostSetupChangeBus().currentRevision(ghostId),strict: true,additionalGroups: assessGhostHostSetupRequirements(runtimeManifest, {- clientConfigReady: (configId) =>- configId === 'model-provider' && isModelAccessReady(),+ clientConfigReady: (configId) => configId === 'model-provider' && isModelAccessReady(),}),},);@@ -3258,13 +3420,15 @@ export function getGhostNetworkSlot(): GhostNetworkSlot {buffer,mimeType,isCache: false,- refs: [{- refKind: 'ghost-gallery',- refId: ghostId,- originKind: 'ghost',- originId: ghostId,- ...(label ? { label } : {}),- }],+ refs: [+ {+ refKind: 'ghost-gallery',+ refId: ghostId,+ originKind: 'ghost',+ originId: ghostId,+ ...(label ? { label } : {}),+ },+ ],});recordGhostCallMedia(ghostId, callId, r.url);return { url: r.url, hash: r.hash, ext: r.ext };@@ -3311,9 +3475,7 @@ export function getGhostNetworkSlot(): GhostNetworkSlot {// 时取第一个)。每单现查现读,设置页增删下一单即生效。connections: {hostsFor: (ghostId) => {- const decls =- findAvailableGhost(ghostId)?.manifest.network- ?.connections ?? [];+ const decls = findAvailableGhost(ghostId)?.manifest.network?.connections ?? [];const mgr = getGhostConnectionManager();const hosts: string[] = [];for (const decl of decls) {@@ -3324,9 +3486,7 @@ export function getGhostNetworkSlot(): GhostNetworkSlot {return hosts;},tokenFor: (ghostId, hostname) => {- const decls =- findAvailableGhost(ghostId)?.manifest.network- ?.connections ?? [];+ const decls = findAvailableGhost(ghostId)?.manifest.network?.connections ?? [];const mgr = getGhostConnectionManager();for (const decl of decls) {const token = mgr.resolveTokenByHost(ghostId, decl.key, hostname);@@ -3386,7 +3546,10 @@ export function getGhostFsSlot(): GhostFsSlot {function rejectReservedGhostId(id: string): void {if (!app.isPackaged) return;if (!isOfficialGhostId(id)) return;- throwIpcError('GHOST_ID_RESERVED', `id "${id}" 使用了官方保留前缀(cindy- / filo- / xd-),用户通道不可装入`);+ throwIpcError(+ 'GHOST_ID_RESERVED',+ `id "${id}" 使用了官方保留前缀(cindy- / filo- / xd-),用户通道不可装入`,+ );}/**@@ -3405,7 +3568,9 @@ export function rejectReservedGhostIdForCustomMarket(id: string): void {*/function rejectUnauthorizedTokenBroker(manifest: GhostManifest): void {if (isOfficialGhostId(manifest.id)) return;- const brokered = (manifest.network?.secrets ?? []).some((s) => s.oauth?.tokenBroker !== undefined);+ const brokered = (manifest.network?.secrets ?? []).some(+ (s) => s.oauth?.tokenBroker !== undefined,+ );if (!brokered) return;throwIpcError('GHOST_FILE_INVALID',@@ -3420,6 +3585,8 @@ function throwInstallError(rejection: InstallRejection): never {throwIpcError('NOT_FOUND', rejection.reason);case 'file-invalid':throwIpcError('GHOST_FILE_INVALID', rejection.reason);+ case 'host-unsupported':+ throwIpcError('GHOST_HOST_UNSUPPORTED', rejection.reason);case 'already-installed':throwIpcError('ALREADY_EXISTS', rejection.reason);case 'not-installed':@@ -3471,9 +3638,7 @@ async function installAndDockLocked(// "立即开启"才带电;沉睡态面板不渲染、总机不列、沙箱不拉起。const result = await manager.install(lizFilePath, {initiallyEnabled: opts.enable ?? false,- ...(opts.expectedPackageSha256- ? { expectedPackageSha256: opts.expectedPackageSha256 }- : {}),+ ...(opts.expectedPackageSha256 ? { expectedPackageSha256: opts.expectedPackageSha256 } : {}),});if ('rejection' in result) throwInstallError(result.rejection);// 纵深防御:调用方给错 id 意味着刚才那把锁上在了错误的键上(等于没上锁)。@@ -3494,7 +3659,10 @@ async function installAndDockLocked(const applied = store.setLayout(docked);if ('rejection' in applied) {// 停靠失败不阻断装入(意识本体已就绪);记日志供排查。- log.warn('ghost panel dock rejected', { id: result.ghost.manifest.id, reason: applied.rejection });+ log.warn('ghost panel dock rejected', {+ id: result.ghost.manifest.id,+ reason: applied.rejection,+ });}}// 常驻意识(launch: resident)且装入即开启:立刻拉起电子脑。@@ -3557,10 +3725,7 @@ async function installOrUpdateMarketGhostPackageLocked(inspected.canonicalManifest.id !== expected.ghostId ||inspected.canonicalManifest.version !== expected.version) {- throwIpcError(- 'GHOST_FILE_INVALID',- '下载包清单与市场 Release 不一致',- );+ throwIpcError('GHOST_FILE_INVALID', '下载包清单与市场 Release 不一致');}requireGhostAvailableForActiveSession(expected.ghostId);/**@@ -3579,9 +3744,7 @@ async function installOrUpdateMarketGhostPackageLocked(*/const installed = manager.list().find((ghost) => ghost.manifest.id === expected.ghostId);if (expected.reviewedManifest) {- const installedBaseline = installed- ? ghostPermissionBaselineKey(installed.manifest)- : null;+ const installedBaseline = installed ? ghostPermissionBaselineKey(installed.manifest) : null;// 真实包复核的批准必须始终绑定当时那份包与已装权限面,不能只在// 当前仍存在来源清单差异时才校验。否则两次请求间包字节发生变化、// 新包恰好不再多权限时,会绕过旧批准的 SHA/基线绑定直接落位。@@ -3679,9 +3842,7 @@ async function installOrUpdateMarketGhostPackageLocked(}type GhostUninstallLedgerCompletion = () => Promise<void>;-type GhostUninstallLedgerPreparer = (- ghostId: string,-) => GhostUninstallLedgerCompletion | null;+type GhostUninstallLedgerPreparer = (ghostId: string) => GhostUninstallLedgerCompletion | null;let prepareGhostUninstallLedgerCompletion: GhostUninstallLedgerPreparer | null = null;@@ -3689,9 +3850,7 @@ let prepareGhostUninstallLedgerCompletion: GhostUninstallLedgerPreparer | null =* 由 Plugin Market 在 IPC 注册期注入账本桥接,保持 cindy-brain 不反向依赖* 市场服务。preparer 在卸载开始前捕获 owner,返回的 completion 只在卸载成功后执行。*/-export function setGhostUninstallLedgerPreparer(- preparer: GhostUninstallLedgerPreparer,-): void {+export function setGhostUninstallLedgerPreparer(preparer: GhostUninstallLedgerPreparer): void {prepareGhostUninstallLedgerCompletion = preparer;}@@ -3816,18 +3975,21 @@ function spawnIfResident(ghost: InstalledGhost): void {// Node 常驻档与浏览器电子脑的 launch:resident 是两份独立声明、两项独立// 权限。Node 默认按需;只有明确声明 resident 才在这里提前点火。if (ghost.manifest.node?.lifecycle === 'resident') {- void getGhostNodeRuntimeBroker().startResident(ghost).catch((err) => {- log.warn('resident ghost node spawn error', {- id: ghost.manifest.id,- error: err instanceof Error ? err.message : String(err),+ void getGhostNodeRuntimeBroker()+ .startResident(ghost)+ .catch((err) => {+ log.warn('resident ghost node spawn error', {+ id: ghost.manifest.id,+ error: err instanceof Error ? err.message : String(err),+ });});- });}if (ghost.manifest.launch !== 'resident') return;void getGhostRuntime().spawn(ghost).then((r) => {- if (!r.ok) log.warn('resident ghost spawn failed', { id: ghost.manifest.id, reason: r.reason });+ if (!r.ok)+ log.warn('resident ghost spawn failed', { id: ghost.manifest.id, reason: r.reason });}).catch((err) => {// spawn 已把可预期失败折叠成返回值;这里兜住意外异常,常驻点火绝不@@ -3877,8 +4039,7 @@ export function registerGhostIpc(): void {log,});ghostSetupKvStore = ghostKv;- const ghostInstalled = (ghostId: string): boolean =>- findAvailableGhost(ghostId) !== null;+ const ghostInstalled = (ghostId: string): boolean => findAvailableGhost(ghostId) !== null;setGhostKvStore({read: (ghostId) => (ghostInstalled(ghostId) ? ghostKv.read(ghostId) : {}),write: (ghostId, value) => {@@ -3902,10 +4063,7 @@ export function registerGhostIpc(): void {// Host 派生与 oauth(主机托管授权)都没有"用户填值"这回事,// 不进 /secrets 收单键集(oauth 的 client 凭证走 /oauth 端点)。.filter(- (s) =>- s.source !== 'login-email'- && s.source !== 'oauth'- && s.source !== 'oidc-token',+ (s) => s.source !== 'login-email' && s.source !== 'oauth' && s.source !== 'oidc-token',).map((s) => s.key).concat(nodeSecretDecls.map((s) => s.key));@@ -3915,9 +4073,7 @@ export function registerGhostIpc(): void {const identitySecretKeys = networkSecretDecls.filter((s) => s.source === 'login-email').map((s) => s.key);- const managedSecretDecls = networkSecretDecls.filter(- (s) => s.source === 'oidc-token',- );+ const managedSecretDecls = networkSecretDecls.filter((s) => s.source === 'oidc-token');const connectionResolution =managedSecretDecls.length > 0? (() => {@@ -4019,8 +4175,7 @@ export function registerGhostIpc(): void {// 受信确认:main 侧系统模态(对照 bootstrap 的 moveToApplications 弹窗// 用法),默认落在「取消」上防误触;意识名从在装清单现查。confirmAddHost: async (declLabel, host) => {- const ghostName =- findAvailableGhost(ghostId)?.manifest.name ?? ghostId;+ const ghostName = findAvailableGhost(ghostId)?.manifest.name ?? ghostId;// main 迷你 i18n 只内置 {{appName}} 插值,其余变量按其约定在调用点// 自行 replace(对照 bootstrap 菜单的用法)。const { response } = await dialog.showMessageBox({@@ -4068,222 +4223,238 @@ export function registerGhostIpc(): void {// 的显式例外——作者声明过、装入确认框摊过牌)。刻意排在首次对账之后,新// 播种的常驻意识同一趟点火;后续对账装上的由 reconcile 自己点火。const activateGhostsAndMigrateLegacyAccounts = (): void => {- for (const ghost of manager.list()) spawnIfResident(ghost);- const activeOwnerId = getActiveAppSession().dataOwnerId;- const canMigrateLegacyAccounts =- getAppCapabilities().canUseCindyAccountServices &&- activeOwnerId !== null &&- hasLegacyOwnerNamespaceClaim(activeOwnerId);- // 老 Google 集成 → Filo Google 意识的一次性搬账(lizi_google 退役配套):- // filoCurrent 档案的账号同 client、refresh token 通用,直接迁入意识- // 保险库;意识侧已有账号或老存储不存在时为 no-op(模块内幂等)。- if (- canMigrateLegacyAccounts &&- manager.list().some((g) => g.manifest.id === FILO_GOOGLE_GHOST_ID)- ) {- try {- const legacyDir = path.join(app.getPath('userData'), 'safe-storage');- const migrated = migrateFiloGoogleAccounts({- readLegacyManifest: () => {- try {- const raw = JSON.parse(- fs.readFileSync(path.join(legacyDir, 'google_accounts.json'), 'utf-8'),- ) as { accounts?: unknown };- if (!Array.isArray(raw.accounts)) return null;- return { accounts: raw.accounts as LegacyGoogleAccountRow[] };- } catch {- return null;- }- },- readLegacyRefreshToken: (accountId) => {- try {- if (!safeStorage.isEncryptionAvailable()) return null;- const file = path.join(legacyDir, `google_account_refresh_token_${accountId}.enc`);- if (!fs.existsSync(file)) return null;- return safeStorage.decryptString(Buffer.from(fs.readFileSync(file, 'utf-8'), 'base64'));- } catch {- return null;- }- },- vault: {- read: (ghostId, storageKey) => readGhostSecret(ghostId, storageKey),- store: (ghostId, storageKey, value) => storeGhostSecret(ghostId, storageKey, value),- remove: (ghostId, storageKey) => removeGhostSecret(ghostId, storageKey),- },- log,+ for (const ghost of manager.list()) spawnIfResident(ghost);+ const activeOwnerId = getActiveAppSession().dataOwnerId;+ const canMigrateLegacyAccounts =+ getAppCapabilities().canUseCindyAccountServices &&+ activeOwnerId !== null &&+ hasLegacyOwnerNamespaceClaim(activeOwnerId);+ // 老 Google 集成 → Filo Google 意识的一次性搬账(lizi_google 退役配套):+ // filoCurrent 档案的账号同 client、refresh token 通用,直接迁入意识+ // 保险库;意识侧已有账号或老存储不存在时为 no-op(模块内幂等)。+ if (+ canMigrateLegacyAccounts &&+ manager.list().some((g) => g.manifest.id === FILO_GOOGLE_GHOST_ID)+ ) {+ try {+ const legacyDir = path.join(app.getPath('userData'), 'safe-storage');+ const migrated = migrateFiloGoogleAccounts({+ readLegacyManifest: () => {+ try {+ const raw = JSON.parse(+ fs.readFileSync(path.join(legacyDir, 'google_accounts.json'), 'utf-8'),+ ) as { accounts?: unknown };+ if (!Array.isArray(raw.accounts)) return null;+ return { accounts: raw.accounts as LegacyGoogleAccountRow[] };+ } catch {+ return null;+ }+ },+ readLegacyRefreshToken: (accountId) => {+ try {+ if (!safeStorage.isEncryptionAvailable()) return null;+ const file = path.join(legacyDir, `google_account_refresh_token_${accountId}.enc`);+ if (!fs.existsSync(file)) return null;+ return safeStorage.decryptString(+ Buffer.from(fs.readFileSync(file, 'utf-8'), 'base64'),+ );+ } catch {+ return null;+ }+ },+ vault: {+ read: (ghostId, storageKey) => readGhostSecret(ghostId, storageKey),+ store: (ghostId, storageKey, value) => storeGhostSecret(ghostId, storageKey, value),+ remove: (ghostId, storageKey) => removeGhostSecret(ghostId, storageKey),+ },+ log,+ });+ if (migrated > 0) {+ getGhostSetupChangeBus().emit(FILO_GOOGLE_GHOST_ID, {+ source: 'oauth',+ ref: FILO_GOOGLE_SECRET_KEY,});- if (migrated > 0) {- getGhostSetupChangeBus().emit(FILO_GOOGLE_GHOST_ID, {- source: 'oauth',- ref: FILO_GOOGLE_SECRET_KEY,- });- }- } catch (err) {- log.warn('filo-google 搬账意外失败(不阻断启动)', { err: err instanceof Error ? err.message : String(err) });}+ } catch (err) {+ log.warn('filo-google 搬账意外失败(不阻断启动)', {+ err: err instanceof Error ? err.message : String(err),+ });}- // 老 Jira/Confluence 集成 → XD Atlassian 意识的一次性搬账(lizi_jira /- // lizi_confluence 退役配套):老 rt 与 server broker 同一 Atlassian 应用,- // tokenBroker 模式走同一 broker 刷新,令牌通用;幂等语义同上。- if (- canMigrateLegacyAccounts &&- manager.list().some((g) => g.manifest.id === XD_ATLASSIAN_GHOST_ID)- ) {- try {- const legacyDir = path.join(app.getPath('userData'), 'safe-storage');- const migrated = migrateAtlassianAccounts({- readLegacyRefreshToken: () => {- try {- if (!safeStorage.isEncryptionAvailable()) return null;- const file = path.join(legacyDir, LEGACY_JIRA_RT_FILE);- if (!fs.existsSync(file)) return null;- return safeStorage.decryptString(Buffer.from(fs.readFileSync(file, 'utf-8'), 'base64'));- } catch {- return null;- }- },- readLegacyConnection: () => {- try {- const raw = JSON.parse(- fs.readFileSync(path.join(legacyDir, LEGACY_JIRA_CONNECTION_FILE), 'utf-8'),- ) as { email?: unknown };- return { email: typeof raw.email === 'string' ? raw.email : null };- } catch {- return null;- }- },- vault: {- read: (ghostId, storageKey) => readGhostSecret(ghostId, storageKey),- store: (ghostId, storageKey, value) => storeGhostSecret(ghostId, storageKey, value),- remove: (ghostId, storageKey) => removeGhostSecret(ghostId, storageKey),- },- log,+ }+ // 老 Jira/Confluence 集成 → XD Atlassian 意识的一次性搬账(lizi_jira /+ // lizi_confluence 退役配套):老 rt 与 server broker 同一 Atlassian 应用,+ // tokenBroker 模式走同一 broker 刷新,令牌通用;幂等语义同上。+ if (+ canMigrateLegacyAccounts &&+ manager.list().some((g) => g.manifest.id === XD_ATLASSIAN_GHOST_ID)+ ) {+ try {+ const legacyDir = path.join(app.getPath('userData'), 'safe-storage');+ const migrated = migrateAtlassianAccounts({+ readLegacyRefreshToken: () => {+ try {+ if (!safeStorage.isEncryptionAvailable()) return null;+ const file = path.join(legacyDir, LEGACY_JIRA_RT_FILE);+ if (!fs.existsSync(file)) return null;+ return safeStorage.decryptString(+ Buffer.from(fs.readFileSync(file, 'utf-8'), 'base64'),+ );+ } catch {+ return null;+ }+ },+ readLegacyConnection: () => {+ try {+ const raw = JSON.parse(+ fs.readFileSync(path.join(legacyDir, LEGACY_JIRA_CONNECTION_FILE), 'utf-8'),+ ) as { email?: unknown };+ return { email: typeof raw.email === 'string' ? raw.email : null };+ } catch {+ return null;+ }+ },+ vault: {+ read: (ghostId, storageKey) => readGhostSecret(ghostId, storageKey),+ store: (ghostId, storageKey, value) => storeGhostSecret(ghostId, storageKey, value),+ remove: (ghostId, storageKey) => removeGhostSecret(ghostId, storageKey),+ },+ log,+ });+ if (migrated > 0) {+ getGhostSetupChangeBus().emit(XD_ATLASSIAN_GHOST_ID, {+ source: 'oauth',+ ref: XD_ATLASSIAN_SECRET_KEY,});- if (migrated > 0) {- getGhostSetupChangeBus().emit(XD_ATLASSIAN_GHOST_ID, {- source: 'oauth',- ref: XD_ATLASSIAN_SECRET_KEY,- });- }- } catch (err) {- log.warn('xd-atlassian 搬账意外失败(不阻断启动)', { err: err instanceof Error ? err.message : String(err) });}+ } catch (err) {+ log.warn('xd-atlassian 搬账意外失败(不阻断启动)', {+ err: err instanceof Error ? err.message : String(err),+ });}- // 老 Slack 官方 MCP → cindy-slack 意识的搬账已随意识退役删除- // (2026-07-19 Slack 能力并轨 hook 通道;存量意识凭证由- // RETIRED_BUILTIN_GHOSTS 对账清理)。- // 老 GitHub 集成 → GitHub 意识(cindy-github)的一次性搬账(lizi_github 退役配套):- // PAT 直接迁入意识 user 凭证槽;仅迁 github.com 连接(意识白名单静态- // 钉死 github.com,GHE token 迁了也只会 401);幂等语义同上。- if (- canMigrateLegacyAccounts &&- manager.list().some((g) => g.manifest.id === CINDY_GITHUB_GHOST_ID)- ) {- try {- const legacyDir = path.join(app.getPath('userData'), 'safe-storage');- const migrated = migrateGithubAccounts({- readLegacyToken: () => {- try {- if (!safeStorage.isEncryptionAvailable()) return null;- const file = path.join(legacyDir, LEGACY_GITHUB_TOKEN_FILE);- if (!fs.existsSync(file)) return null;- return safeStorage.decryptString(Buffer.from(fs.readFileSync(file, 'utf-8'), 'base64'));- } catch {- return null;- }- },- readLegacyConnection: () => {- try {- const raw = JSON.parse(- fs.readFileSync(path.join(legacyDir, LEGACY_GITHUB_CONNECTION_FILE), 'utf-8'),- ) as { host?: unknown };- return { host: typeof raw.host === 'string' ? raw.host : null };- } catch {- return null;- }- },- vault: {- read: (ghostId, storageKey) => readGhostSecret(ghostId, storageKey),- store: (ghostId, storageKey, value) => storeGhostSecret(ghostId, storageKey, value),- },- log,+ }+ // 老 Slack 官方 MCP → cindy-slack 意识的搬账已随意识退役删除+ // (2026-07-19 Slack 能力并轨 hook 通道;存量意识凭证由+ // RETIRED_BUILTIN_GHOSTS 对账清理)。+ // 老 GitHub 集成 → GitHub 意识(cindy-github)的一次性搬账(lizi_github 退役配套):+ // PAT 直接迁入意识 user 凭证槽;仅迁 github.com 连接(意识白名单静态+ // 钉死 github.com,GHE token 迁了也只会 401);幂等语义同上。+ if (+ canMigrateLegacyAccounts &&+ manager.list().some((g) => g.manifest.id === CINDY_GITHUB_GHOST_ID)+ ) {+ try {+ const legacyDir = path.join(app.getPath('userData'), 'safe-storage');+ const migrated = migrateGithubAccounts({+ readLegacyToken: () => {+ try {+ if (!safeStorage.isEncryptionAvailable()) return null;+ const file = path.join(legacyDir, LEGACY_GITHUB_TOKEN_FILE);+ if (!fs.existsSync(file)) return null;+ return safeStorage.decryptString(+ Buffer.from(fs.readFileSync(file, 'utf-8'), 'base64'),+ );+ } catch {+ return null;+ }+ },+ readLegacyConnection: () => {+ try {+ const raw = JSON.parse(+ fs.readFileSync(path.join(legacyDir, LEGACY_GITHUB_CONNECTION_FILE), 'utf-8'),+ ) as { host?: unknown };+ return { host: typeof raw.host === 'string' ? raw.host : null };+ } catch {+ return null;+ }+ },+ vault: {+ read: (ghostId, storageKey) => readGhostSecret(ghostId, storageKey),+ store: (ghostId, storageKey, value) => storeGhostSecret(ghostId, storageKey, value),+ },+ log,+ });+ if (migrated > 0) {+ getGhostSetupChangeBus().emit(CINDY_GITHUB_GHOST_ID, {+ source: 'secret',+ ref: CINDY_GITHUB_SECRET_KEY,});- if (migrated > 0) {- getGhostSetupChangeBus().emit(CINDY_GITHUB_GHOST_ID, {- source: 'secret',- ref: CINDY_GITHUB_SECRET_KEY,- });- }- } catch (err) {- log.warn('cindy-github 搬账意外失败(不阻断启动)', { err: err instanceof Error ? err.message : String(err) });}+ } catch (err) {+ log.warn('cindy-github 搬账意外失败(不阻断启动)', {+ err: err instanceof Error ? err.message : String(err),+ });}- // 老 GitLab 集成 → Cindy GitLab 意识(cindy-gitlab)的一次性搬账- // (lizi_gitlab 退役配套):PAT + 实例地址迁入意识多连接声明- // (gitlab_conn)并设为默认;仅迁 https 且不带端口的实例(意识出网- // 仅 https、连接白名单只认裸域,迁了也打不通);幂等语义同上。- if (- canMigrateLegacyAccounts &&- manager.list().some((g) => g.manifest.id === CINDY_GITLAB_GHOST_ID)- ) {- try {- const legacyDir = path.join(app.getPath('userData'), 'safe-storage');- const migrated = migrateGitlabAccounts({- readLegacyToken: () => {- try {- if (!safeStorage.isEncryptionAvailable()) return null;- const file = path.join(legacyDir, LEGACY_GITLAB_TOKEN_FILE);- if (!fs.existsSync(file)) return null;- return safeStorage.decryptString(Buffer.from(fs.readFileSync(file, 'utf-8'), 'base64'));- } catch {- return null;- }- },- legacyTokenExists: () => {- try {- return fs.existsSync(path.join(legacyDir, LEGACY_GITLAB_TOKEN_FILE));- } catch {- return false;- }- },- readLegacyConnection: () => {- try {- const raw = JSON.parse(- fs.readFileSync(path.join(legacyDir, LEGACY_GITLAB_CONNECTION_FILE), 'utf-8'),- ) as { baseUrl?: unknown; username?: unknown };- return {- baseUrl: typeof raw.baseUrl === 'string' ? raw.baseUrl : null,- username: typeof raw.username === 'string' ? raw.username : null,- };- } catch {- return null;- }- },- manager: getGhostConnectionManager(),- log,+ }+ // 老 GitLab 集成 → Cindy GitLab 意识(cindy-gitlab)的一次性搬账+ // (lizi_gitlab 退役配套):PAT + 实例地址迁入意识多连接声明+ // (gitlab_conn)并设为默认;仅迁 https 且不带端口的实例(意识出网+ // 仅 https、连接白名单只认裸域,迁了也打不通);幂等语义同上。+ if (+ canMigrateLegacyAccounts &&+ manager.list().some((g) => g.manifest.id === CINDY_GITLAB_GHOST_ID)+ ) {+ try {+ const legacyDir = path.join(app.getPath('userData'), 'safe-storage');+ const migrated = migrateGitlabAccounts({+ readLegacyToken: () => {+ try {+ if (!safeStorage.isEncryptionAvailable()) return null;+ const file = path.join(legacyDir, LEGACY_GITLAB_TOKEN_FILE);+ if (!fs.existsSync(file)) return null;+ return safeStorage.decryptString(+ Buffer.from(fs.readFileSync(file, 'utf-8'), 'base64'),+ );+ } catch {+ return null;+ }+ },+ legacyTokenExists: () => {+ try {+ return fs.existsSync(path.join(legacyDir, LEGACY_GITLAB_TOKEN_FILE));+ } catch {+ return false;+ }+ },+ readLegacyConnection: () => {+ try {+ const raw = JSON.parse(+ fs.readFileSync(path.join(legacyDir, LEGACY_GITLAB_CONNECTION_FILE), 'utf-8'),+ ) as { baseUrl?: unknown; username?: unknown };+ return {+ baseUrl: typeof raw.baseUrl === 'string' ? raw.baseUrl : null,+ username: typeof raw.username === 'string' ? raw.username : null,+ };+ } catch {+ return null;+ }+ },+ manager: getGhostConnectionManager(),+ log,+ });+ if (migrated > 0) {+ getGhostSetupChangeBus().emit(CINDY_GITLAB_GHOST_ID, {+ source: 'connection',+ ref: CINDY_GITLAB_CONNECTION_KEY,});- if (migrated > 0) {- getGhostSetupChangeBus().emit(CINDY_GITLAB_GHOST_ID, {- source: 'connection',- ref: CINDY_GITLAB_CONNECTION_KEY,- });- }- } catch (err) {- log.warn('cindy-gitlab 搬账意外失败(不阻断启动)', { err: err instanceof Error ? err.message : String(err) });}+ } catch (err) {+ log.warn('cindy-gitlab 搬账意外失败(不阻断启动)', {+ err: err instanceof Error ? err.message : String(err),+ });}+ }};void app.whenReady().then(() => {void scheduleBuiltinReconcile('startup');- builtinReconcileChain = builtinReconcileChain.then(- activateGhostsAndMigrateLegacyAccounts,- );+ builtinReconcileChain = builtinReconcileChain.then(activateGhostsAndMigrateLegacyAccounts);onAuthStateChange(() => {// Login/logout, Membership switches, and refresh integration all cross// an auth notification boundary. Discard every short-lived Connection// assertion so a late request can never reuse the previous identity.connectionTokenProviderSingleton?.clearAll();+ // 当前任务绑定属于窗口内的 owner 上下文,切账号/会员身份后不得沿用旧快照。+ ghostSessionFocusByWebContents.clear();if (!getAppCapabilities().canUseCindyAccountServices) suspendCindyAccountGhosts();// Even when provisioning itself is a no-op, the renderer and agent// roster must immediately reflect the new session capability set.@@ -4292,9 +4463,7 @@ export function registerGhostIpc(): void {// 会留在账号 B 的插件入口与卡片上(跨账号残留)。broadcastGhostUnreadSnapshot();void scheduleBuiltinReconcile('auth-change');- builtinReconcileChain = builtinReconcileChain.then(- activateGhostsAndMigrateLegacyAccounts,- );+ builtinReconcileChain = builtinReconcileChain.then(activateGhostsAndMigrateLegacyAccounts);});});@@ -4331,7 +4500,8 @@ export function registerGhostIpc(): void {// 拒因只进日志,恒回 ok,与 tool-result 同纪律不给沙箱探测面)。if (type === 'tool-progress') {const outcome = getGhostPipeDispatcher().handleToolProgress(id, payload);- if (!outcome.accepted) log.warn('ghost tool-progress rejected', { id, reason: outcome.reason });+ if (!outcome.accepted)+ log.warn('ghost tool-progress rejected', { id, reason: outcome.reason });return { ok: true };}// host-request = 读取宿主公开上下文;不要求卡槽,只返回构建 region,@@ -4381,6 +4551,11 @@ export function registerGhostIpc(): void {if (type === 'workspace-request') {return getGhostWorkspaceSlot().handleRequest(id, payload);}+ // ios-simulator-request = 当前任务的脱敏只读状态与 Host 面板入口。+ // 视频帧、输入与 Sidecar 进程均不跨插件边界;任务身份由 Host 窗口绑定。+ if (type === 'ios-simulator-request') {+ return getGhostIOSSimulatorSlot().handleRequest(id, payload);+ }// preview-request = 右侧栏开预览标签(preview 槽):URL 必须命中身份卡// preview.hosts 白名单;守门/限速在 previewSlot,落地在 renderer。if (type === 'preview-request') {@@ -4430,7 +4605,12 @@ export function registerGhostIpc(): void {// 非布尔的 confirmed 在桥里一律按"没同意"兜底,不给靠畸形回包骗到同意的路。ipcMain.handle('ghosts:confirm:resolve', async (_event, raw: unknown) => {const p = raw as { requestId?: unknown; confirmed?: unknown } | null;- if (!p || typeof p.requestId !== 'string' || p.requestId.length === 0 || p.requestId.length > 128) {+ if (+ !p ||+ typeof p.requestId !== 'string' ||+ p.requestId.length === 0 ||+ p.requestId.length > 128+ ) {throwIpcError('INVALID_PARAMS', 'requestId must be a non-empty string');}const bridge = getGhostConfirmDialogBridge();@@ -4459,8 +4639,13 @@ export function registerGhostIpc(): void {// 会话切换上报(订阅槽①;renderer MainLayout 路由 effect 单向 send,无返回):// 非法载荷按 null(切去非会话页)处理,去重与资格门都在 noteGhostSessionFocused 之后。- ipcMain.on('ghosts:session-focused', (_event, sessionId: unknown) => {- noteGhostSessionFocused(typeof sessionId === 'string' && sessionId.length > 0 ? sessionId : null);+ ipcMain.on('ghosts:session-focused', (event, sessionId: unknown) => {+ assertTrustedAppRendererEvent(event);+ const normalizedSessionId =+ typeof sessionId === 'string' && sessionId.trim().length > 0 && sessionId.trim().length <= 128+ ? sessionId.trim()+ : null;+ noteGhostWindowSessionFocused(event.sender, normalizedSessionId);});// 会话批量取卡(卡槽③;宿主 renderer 会话打开时一次性灌 byCallId)。查询型@@ -4500,11 +4685,14 @@ export function registerGhostIpc(): void {// 交互卡(v2)按钮点击回传(宿主受信桥 → 校验归属 → 唤醒意识 → 管子下发// card-action)。fire-and-forget:恒回 { ok } 给 renderer(reason 仅日志),// 派发器内部永不抛;意识随后自绘 card-update 换新卡走既有回放路径。- ipcMain.handle('ghosts:card:action', async (event, callId: unknown, actionId: unknown, prompt?: unknown) => {- assertTrustedAppRendererEvent(event);- const r = await getGhostCardActionDispatcher().dispatch(callId, actionId, prompt);- return { ok: r.ok };- });+ ipcMain.handle(+ 'ghosts:card:action',+ async (event, callId: unknown, actionId: unknown, prompt?: unknown) => {+ assertTrustedAppRendererEvent(event);+ const r = await getGhostCardActionDispatcher().dispatch(callId, actionId, prompt);+ return { ok: r.ok };+ },+ );ipcMain.on('ghosts:list', (event) => {event.returnValue = { ghosts: availableGhosts().map(projectGhostForRenderer) };@@ -4691,66 +4879,78 @@ export function registerGhostIpc(): void {disabled: typeof workdir === 'string' ? listDisabledGhostIdsForWorkdir(workdir) : [],};});- ipcMain.handle('ghosts:workdir-prefs:set', (_event, workdir: unknown, ghostId: unknown, disabled: unknown) => {- if (typeof workdir !== 'string' || workdir.trim().length === 0) {- throwIpcError('INVALID_PARAMS', 'workdir must be a non-empty string');- }- if (typeof ghostId !== 'string' || ghostId.trim().length === 0) {- throwIpcError('INVALID_PARAMS', 'ghostId must be a non-empty string');- }- if (typeof disabled !== 'boolean') {- throwIpcError('INVALID_PARAMS', 'disabled must be a boolean');- }- const wasDisabled = isGhostDisabledForWorkdir(ghostId, workdir);- const next = setGhostDisabledForWorkdir(workdir, ghostId, disabled);- // A setup card may already be waiting for this plugin in the affected- // project. Wake all waiters for the plugin; each one revalidates its own- // captured workdir and only the matching scope is rejected.- if (wasDisabled !== disabled) {- getGhostSetupChangeBus().emit(ghostId, { source: 'workdir_policy' });- }- // 生效面变了(新会话花名册 / $ 菜单),借 ghosts:changed 通知所有窗口- // 重拉——载荷仍是完整已装清单,消费方按需再 sendSync 取目录级清单。- broadcastGhostsChanged(manager.list());- return { disabled: next };- });+ ipcMain.handle(+ 'ghosts:workdir-prefs:set',+ (_event, workdir: unknown, ghostId: unknown, disabled: unknown) => {+ if (typeof workdir !== 'string' || workdir.trim().length === 0) {+ throwIpcError('INVALID_PARAMS', 'workdir must be a non-empty string');+ }+ if (typeof ghostId !== 'string' || ghostId.trim().length === 0) {+ throwIpcError('INVALID_PARAMS', 'ghostId must be a non-empty string');+ }+ if (typeof disabled !== 'boolean') {+ throwIpcError('INVALID_PARAMS', 'disabled must be a boolean');+ }+ const wasDisabled = isGhostDisabledForWorkdir(ghostId, workdir);+ const next = setGhostDisabledForWorkdir(workdir, ghostId, disabled);+ // A setup card may already be waiting for this plugin in the affected+ // project. Wake all waiters for the plugin; each one revalidates its own+ // captured workdir and only the matching scope is rejected.+ if (wasDisabled !== disabled) {+ getGhostSetupChangeBus().emit(ghostId, { source: 'workdir_policy' });+ }+ // 生效面变了(新会话花名册 / $ 菜单),借 ghosts:changed 通知所有窗口+ // 重拉——载荷仍是完整已装清单,消费方按需再 sendSync 取目录级清单。+ broadcastGhostsChanged(manager.list());+ return { disabled: next };+ },+ );- ipcMain.handle('ghosts:cindy-prefs:set', (_event, ghostId: unknown, capability: unknown, model: unknown) => {- if (typeof ghostId !== 'string' || ghostId.trim().length === 0) {- throwIpcError('INVALID_PARAMS', 'ghostId must be a non-empty string');- }- if (!(CINDY_CAPABILITY_KEYS as readonly string[]).includes(capability as string)) {- throwIpcError('INVALID_PARAMS', `unknown capability: ${String(capability)}`);- }- // 白名单按能力键的**取值域**取,映射由 cindyCapabilityValueDomain 穷举- // (漏一个类目 = 该类目的下拉界面上能选、一选就被别人的白名单拒掉、回滚成- // 一句通用 toast;PR #1707 review)。text.oneshot 的取值是轻量链档位键,- // 不在任何媒体目录里,必须对着 pin 选项校验。- const capKey = capability as CindyCapabilityKey;- const domain = cindyCapabilityValueDomain(capKey);- const allowed: ReadonlyArray<{ id: string; supportsEdit?: boolean }> =- domain === 'utilityChain'- ? utilityModelPinOptions()- : domain === 'video'- ? getCatalogVideoConfig().models- : domain === 'embed'- ? getCatalogEmbedConfig().models- : getCatalogImageConfig().models;- const isEditCap = capKey === 'image.edit';- if (model !== null && !allowed.some((m) => m.id === model && (!isEditCap || m.supportsEdit))) {- throwIpcError('INVALID_PARAMS', 'model must be null or a catalog model of the capability category');- }- const overrides = writeGhostCindyOverride(- ghostId,- capability as CindyCapabilityKey,- model as string | null,- );- getGhostSetupChangeBus().emit(ghostId, {- source: 'host_config',- ref: `cindy-pref:${String(capability)}`,- });- return { overrides };- });+ ipcMain.handle(+ 'ghosts:cindy-prefs:set',+ (_event, ghostId: unknown, capability: unknown, model: unknown) => {+ if (typeof ghostId !== 'string' || ghostId.trim().length === 0) {+ throwIpcError('INVALID_PARAMS', 'ghostId must be a non-empty string');+ }+ if (!(CINDY_CAPABILITY_KEYS as readonly string[]).includes(capability as string)) {+ throwIpcError('INVALID_PARAMS', `unknown capability: ${String(capability)}`);+ }+ // 白名单按能力键的**取值域**取,映射由 cindyCapabilityValueDomain 穷举+ // (漏一个类目 = 该类目的下拉界面上能选、一选就被别人的白名单拒掉、回滚成+ // 一句通用 toast;PR #1707 review)。text.oneshot 的取值是轻量链档位键,+ // 不在任何媒体目录里,必须对着 pin 选项校验。+ const capKey = capability as CindyCapabilityKey;+ const domain = cindyCapabilityValueDomain(capKey);+ const allowed: ReadonlyArray<{ id: string; supportsEdit?: boolean }> =+ domain === 'utilityChain'+ ? utilityModelPinOptions()+ : domain === 'video'+ ? getCatalogVideoConfig().models+ : domain === 'embed'+ ? getCatalogEmbedConfig().models+ : getCatalogImageConfig().models;+ const isEditCap = capKey === 'image.edit';+ if (+ model !== null &&+ !allowed.some((m) => m.id === model && (!isEditCap || m.supportsEdit))+ ) {+ throwIpcError(+ 'INVALID_PARAMS',+ 'model must be null or a catalog model of the capability category',+ );+ }+ const overrides = writeGhostCindyOverride(+ ghostId,+ capability as CindyCapabilityKey,+ model as string | null,+ );+ getGhostSetupChangeBus().emit(ghostId, {+ source: 'host_config',+ ref: `cindy-pref:${String(capability)}`,+ });+ return { overrides };+ },+ );// ── agent 槽派活(errand)每插件配置(插件详情页「AI 代办」卡)──// 读走 sendSync(与 cindy-prefs 同理:详情页首帧同帧渲染);写走 invoke,@@ -4779,9 +4979,7 @@ export function registerGhostIpc(): void {if (typeof lizFilePath !== 'string' || lizFilePath.trim().length === 0) {throwIpcError('INVALID_PARAMS', 'lizFilePath must be a non-empty string');}- const installOpts = opts as- | { enable?: unknown; expectedPackageSha256?: unknown }- | undefined;+ const installOpts = opts as { enable?: unknown; expectedPackageSha256?: unknown } | undefined;const expectedPackageSha256 = installOpts?.expectedPackageSha256;if (typeof expectedPackageSha256 !== 'string' ||@@ -4858,7 +5056,10 @@ export function registerGhostIpc(): void {if (docked) {const applied = store.setLayout(docked);if ('rejection' in applied) {- log.warn('ghost panel dock rejected', { id: result.ghost.manifest.id, reason: applied.rejection });+ log.warn('ghost panel dock rejected', {+ id: result.ghost.manifest.id,+ reason: applied.rejection,+ });}}spawnIfResident(result.ghost); // 常驻意识:换完代码立即用新版本点火@@ -4949,12 +5150,14 @@ export function registerGhostIpc(): void {// 指令查重(同 install/update):与当前已装撞名即拒,排除自身。const commandFold = probe.manifest.command?.toLowerCase();if (commandFold === undefined) return true;- return !manager.list().some(- (g) =>- g.manifest.id !== probe.manifest.id &&- g.manifest.command !== undefined &&- g.manifest.command.toLowerCase() === commandFold,- );+ return !manager+ .list()+ .some(+ (g) =>+ g.manifest.id !== probe.manifest.id &&+ g.manifest.command !== undefined &&+ g.manifest.command.toLowerCase() === commandFold,+ );},});switch (result.status) {@@ -4993,7 +5196,9 @@ export function registerGhostIpc(): void {};} catch (err) {// sendSync 必须回值,否则 renderer 卡死;失败降级空态(fallback data 例外,规则 13)。- log.warn('ghosts:builtin-status failed', { error: err instanceof Error ? err.message : String(err) });+ log.warn('ghosts:builtin-status failed', {+ error: err instanceof Error ? err.message : String(err),+ });event.returnValue = { builtinIds: [], enterpriseIds: [], restorable: [] };}});@@ -5071,63 +5276,63 @@ export function registerGhostIpc(): void {// dev-only 运行时控制通道(QA:能起 / 能停 / 能崩 / 能看状态)。// packaged 版不注册;正式的按需拉起 / 闲置熄灯由上层自动策略负责。if (!app.isPackaged) {- ipcMain.handle('ghosts:dev-runtime', async (event, action: unknown, id: unknown, payload: unknown) => {- assertTrustedAppRendererEvent(event);- if (action === 'status') return { states: runtime.listStates() };- if (typeof id !== 'string' || id.trim().length === 0) {- throwIpcError('INVALID_PARAMS', 'id must be a non-empty string');- }- switch (action) {- case 'spawn': {- requireGhostAvailableForActiveSession(id);- const ghost = findAvailableGhost(id);- if (!ghost) throwIpcError('NOT_FOUND', `未装入意识 ${id}`);- if (!ghost.enabled) throwIpcError('INVALID_PARAMS', `意识 ${id} 处于沉睡态,先唤醒`);- const result = await runtime.spawn(ghost);- if (!result.ok) throwIpcError('INTERNAL', result.reason);- return { state: result.state };+ ipcMain.handle(+ 'ghosts:dev-runtime',+ async (event, action: unknown, id: unknown, payload: unknown) => {+ assertTrustedAppRendererEvent(event);+ if (action === 'status') return { states: runtime.listStates() };+ if (typeof id !== 'string' || id.trim().length === 0) {+ throwIpcError('INVALID_PARAMS', 'id must be a non-empty string');}- case 'stop':- runtime.stop(id);- return { state: runtime.stateOf(id) };- case 'crash':- if (!runtime.crashForTest(id)) throwIpcError('INVALID_PARAMS', `意识 ${id} 不在运行中`);- return { state: runtime.stateOf(id) };- case 'call': {- if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {- throwIpcError('INVALID_PARAMS', 'call payload must be an object');- }- const request = payload as { tool?: unknown; args?: unknown };- if (- typeof request.tool !== 'string' ||- !/^[a-z][a-z0-9_-]{0,63}$/.test(request.tool)- ) {- throwIpcError('INVALID_PARAMS', 'tool must be a valid plugin tool name');+ switch (action) {+ case 'spawn': {+ requireGhostAvailableForActiveSession(id);+ const ghost = findAvailableGhost(id);+ if (!ghost) throwIpcError('NOT_FOUND', `未装入意识 ${id}`);+ if (!ghost.enabled) throwIpcError('INVALID_PARAMS', `意识 ${id} 处于沉睡态,先唤醒`);+ const result = await runtime.spawn(ghost);+ if (!result.ok) throwIpcError('INTERNAL', result.reason);+ return { state: result.state };}- const args = request.args ?? {};- if (!args || typeof args !== 'object' || Array.isArray(args)) {- throwIpcError('INVALID_PARAMS', 'args must be an object');- }- let encodedArgs: string;- try {- encodedArgs = JSON.stringify(args);- } catch {- throwIpcError('INVALID_PARAMS', 'args must be JSON serializable');- }- if (encodedArgs.length > 256 * 1024) {- throwIpcError('INVALID_PARAMS', 'args are too large');+ case 'stop':+ runtime.stop(id);+ return { state: runtime.stateOf(id) };+ case 'crash':+ if (!runtime.crashForTest(id)) throwIpcError('INVALID_PARAMS', `意识 ${id} 不在运行中`);+ return { state: runtime.stateOf(id) };+ case 'call': {+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {+ throwIpcError('INVALID_PARAMS', 'call payload must be an object');+ }+ const request = payload as { tool?: unknown; args?: unknown };+ if (typeof request.tool !== 'string' || !/^[a-z][a-z0-9_-]{0,63}$/.test(request.tool)) {+ throwIpcError('INVALID_PARAMS', 'tool must be a valid plugin tool name');+ }+ const args = request.args ?? {};+ if (!args || typeof args !== 'object' || Array.isArray(args)) {+ throwIpcError('INVALID_PARAMS', 'args must be an object');+ }+ let encodedArgs: string;+ try {+ encodedArgs = JSON.stringify(args);+ } catch {+ throwIpcError('INVALID_PARAMS', 'args must be JSON serializable');+ }+ if (encodedArgs.length > 256 * 1024) {+ throwIpcError('INVALID_PARAMS', 'args are too large');+ }+ requireGhostAvailableForActiveSession(id);+ return getGhostPipeDispatcher().callGhostTool({+ ghostId: id,+ tool: request.tool,+ args: args as Record<string, unknown>,+ });}- requireGhostAvailableForActiveSession(id);- return getGhostPipeDispatcher().callGhostTool({- ghostId: id,- tool: request.tool,- args: args as Record<string, unknown>,- });+ default:+ throwIpcError('INVALID_PARAMS', `未知 action ${JSON.stringify(action)}`);}- default:- throwIpcError('INVALID_PARAMS', `未知 action ${JSON.stringify(action)}`);- }- });+ },+ );}}diff --git a/apps/desktop/src/main/cindy-brain/iosSimulatorSlot.ts b/apps/desktop/src/main/cindy-brain/iosSimulatorSlot.tsnew file mode 100644index 0000000000..bd627852b5--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/iosSimulatorSlot.ts@@ -0,0 +1,222 @@+/**+ * iosSimulatorSlot.ts — 插件的内置 iOS 模拟器能力槽。+ * ---------------------------------------------------------------------------+ * 本槽只提供低带宽、Host-owned 的两件事:+ * 1. 读取当前台前任务的公开模拟器状态;+ * 2. 请求 Host 打开已有的内置模拟器面板。+ *+ * 不跨插件边界传输视频帧、viewer lease、触控、Sidecar 路径或进程句柄。+ * 插件也不能自报 sessionId;任务身份只取 Host 的台前任务快照。实际 WDA / Native+ * 路由、生命周期、恢复和 fallback 继续走既有 iOS Simulator Host。+ */++import {+ GHOST_IOS_SIMULATOR_CAPABILITY_API_VERSION,+ type GhostPipeIOSSimulatorErrorCode,+ type GhostPipeIOSSimulatorResult,+ type GhostIOSSimulatorStatusProbeResult,+ type InstalledGhost,+} from '../../shared/ghost.js';++export const GHOST_IOS_SIMULATOR_OPEN_MIN_INTERVAL_MS = 5_000;+export const GHOST_IOS_SIMULATOR_STATUS_CACHE_MS = 1_000;++/** Host-authenticated foreground context; plugins can neither supply nor alter it. */+export interface IOSSimulatorSlotFocusContext {+ sessionId: string;+ windowWebContentsId: number;+ revision: number;+}++export interface IOSSimulatorSlotDeps {+ getGhost(id: string): InstalledGhost | null;+ focusedContext(): IOSSimulatorSlotFocusContext | null;+ isContextCurrent(context: IOSSimulatorSlotFocusContext): boolean;+ /** Read-only, redacted snapshot; must not reconcile or renew ownership. */+ getStatus(sessionId: string): Promise<GhostIOSSimulatorStatusProbeResult>;+ /** false = 当前没有可承载右侧栏的 Host 窗口。 */+ focusViewer(context: IOSSimulatorSlotFocusContext, instanceId?: string): boolean;+ now?(): number;+ log?: {+ info: (msg: string, meta?: Record<string, unknown>) => void;+ warn: (msg: string, meta?: Record<string, unknown>) => void;+ };+}++function fail(+ errorCode: GhostPipeIOSSimulatorErrorCode,+ message: string,+): GhostPipeIOSSimulatorResult {+ return { ok: false, errorCode, message };+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);+}++function hasOnlyKeys(record: Record<string, unknown>, keys: readonly string[]): boolean {+ const allowed = new Set(keys);+ return Object.keys(record).every((key) => allowed.has(key));+}++export class GhostIOSSimulatorSlot {+ private readonly lastOpenAttemptAt = new Map<string, number>();+ private readonly statusCache = new Map<+ string,+ { capturedAt: number; result: GhostIOSSimulatorStatusProbeResult }+ >();+ private readonly statusInFlight = new Map<string, Promise<GhostIOSSimulatorStatusProbeResult>>();++ constructor(private readonly deps: IOSSimulatorSlotDeps) {}++ private now(): number {+ return this.deps.now?.() ?? Date.now();+ }++ private contextKey(ghostId: string, context: IOSSimulatorSlotFocusContext): string {+ return `${ghostId}:${context.windowWebContentsId}:${context.revision}:${context.sessionId}`;+ }++ private async readStatus(+ ghostId: string,+ context: IOSSimulatorSlotFocusContext,+ ): Promise<GhostIOSSimulatorStatusProbeResult> {+ const key = this.contextKey(ghostId, context);+ const cached = this.statusCache.get(key);+ if (cached && this.now() - cached.capturedAt < GHOST_IOS_SIMULATOR_STATUS_CACHE_MS) {+ return cached.result;+ }+ const existing = this.statusInFlight.get(key);+ if (existing) return existing;+ const pending = this.deps+ .getStatus(context.sessionId)+ .then((result) => {+ this.statusCache.clear();+ this.statusCache.set(key, { capturedAt: this.now(), result });+ return result;+ })+ .finally(() => {+ this.statusInFlight.delete(key);+ });+ this.statusInFlight.set(key, pending);+ return pending;+ }++ async handleRequest(ghostId: string, payload: unknown): Promise<GhostPipeIOSSimulatorResult> {+ const ghost = this.deps.getGhost(ghostId);+ if (!ghost?.enabled || !ghost.manifest.slots.includes('ios-simulator')) {+ return fail(+ 'PERMISSION_DENIED',+ '插件未申请内置 iOS 模拟器权限(ios-simulator 槽),或当前未启用',+ );+ }+ if (!isRecord(payload) || typeof payload.kind !== 'string') {+ return fail('INVALID_REQUEST', 'ios-simulator-request 载荷必须是含 kind 的对象');+ }++ if (payload.kind === 'capabilities') {+ if (!hasOnlyKeys(payload, ['type', 'kind'])) {+ return fail('INVALID_REQUEST', 'capabilities 请求含未知字段');+ }+ return {+ ok: true,+ apiVersion: GHOST_IOS_SIMULATOR_CAPABILITY_API_VERSION,+ kind: 'capabilities',+ capabilities: {+ status: true,+ openHostPanel: true,+ pluginVideo: false,+ pluginInput: false,+ },+ };+ }++ if (payload.kind !== 'status' && payload.kind !== 'open-panel') {+ return fail('INVALID_REQUEST', '未知的内置 iOS 模拟器请求类型');+ }+ if (+ !hasOnlyKeys(+ payload,+ payload.kind === 'status' ? ['type', 'kind'] : ['type', 'kind', 'instanceId'],+ )+ ) {+ return fail('INVALID_REQUEST', `${payload.kind} 请求含未知字段`);+ }++ let instanceId: string | undefined;+ if (payload.kind === 'open-panel' && payload.instanceId !== undefined) {+ if (+ typeof payload.instanceId !== 'string' ||+ payload.instanceId.trim().length === 0 ||+ payload.instanceId.trim().length > 128+ ) {+ return fail('INVALID_REQUEST', 'instanceId 必须是 1–128 字符的字符串');+ }+ instanceId = payload.instanceId.trim();+ }++ const context = this.deps.focusedContext();+ if (!context?.sessionId.trim()) {+ return fail('HOST_NOT_READY', '当前没有打开的 Cindy 任务;先打开一个任务再使用内置模拟器');+ }++ if (payload.kind === 'open-panel') {+ const now = this.now();+ const lastAttemptAt = this.lastOpenAttemptAt.get(ghostId);+ this.lastOpenAttemptAt.set(ghostId, now);+ if (+ lastAttemptAt !== undefined &&+ now - lastAttemptAt < GHOST_IOS_SIMULATOR_OPEN_MIN_INTERVAL_MS+ ) {+ return fail('RATE_LIMITED', '打开内置模拟器的请求太频繁;请稍后重试');+ }+ }++ let probe: GhostIOSSimulatorStatusProbeResult;+ try {+ probe = await this.readStatus(ghostId, context);+ } catch (error) {+ this.deps.log?.warn('ghost ios simulator status failed', {+ ghostId,+ error: error instanceof Error ? error.message : String(error),+ });+ return fail('IOS_SIMULATOR_HOST_ERROR', '无法读取内置模拟器状态;请稍后重试');+ }+ // 防异步查询期间切任务/切窗口;revision 可拦 A → B → A 的 ABA 切换。+ if (!this.deps.isContextCurrent(context)) {+ return fail('HOST_NOT_READY', '当前任务已切换;请刷新模拟器状态后重试');+ }+ if (!probe.ok) return fail(probe.errorCode, probe.message);++ if (payload.kind === 'status') {+ return {+ ok: true,+ apiVersion: GHOST_IOS_SIMULATOR_CAPABILITY_API_VERSION,+ kind: 'status',+ status: probe.status,+ };+ }++ if (instanceId) {+ if (!probe.status.instances.some((instance) => instance.instanceId === instanceId)) {+ return fail('INSTANCE_NOT_OWNED', '该模拟器不属于当前任务;请刷新状态后重试');+ }+ }++ if (!this.deps.focusViewer(context, instanceId)) {+ return fail('HOST_NOT_READY', '当前没有可打开内置模拟器面板的 Cindy 窗口');+ }+ this.deps.log?.info('ghost ios simulator panel requested', {+ ghostId,+ sessionId: context.sessionId,+ windowWebContentsId: context.windowWebContentsId,+ ...(instanceId ? { instanceId } : {}),+ });+ return {+ ok: true,+ apiVersion: GHOST_IOS_SIMULATOR_CAPABILITY_API_VERSION,+ kind: 'open-panel',+ ...(instanceId ? { instanceId } : {}),+ };+ }+}diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.tsindex 324e14fe71..fc1abfeed4 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts@@ -93,6 +93,146 @@ describe('iOS Simulator host', () => {expect(environment).not.toHaveProperty('data.devices.0.availabilityError');});+ it('projects task ownership, resource limits, and safe unavailable-device reasons', async () => {+ const unavailableDevice = {+ ...READY_REPORT.devices[0]!,+ udid: 'E223400C-3148-4BE5-9538-A60FE457EF38',+ name: 'iPhone 16',+ state: 'Shutdown',+ isAvailable: false,+ availabilityError: 'runtime profile not found using "System" match policy',+ runtimeIdentifier: 'com.apple.CoreSimulator.SimRuntime.iOS-18-4',+ runtimeName: 'iOS 18-4',+ runtimeVersion: null,+ };+ const report: IOSSimulatorEnvironmentReport = {+ ...READY_REPORT,+ devices: [READY_REPORT.devices[0]!, unavailableDevice],+ };+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ actor.attach({+ sessionId: 'session-b',+ worktreeRoot: '/tmp/session-b',+ sourceFingerprint: 'fingerprint-b',+ device: READY_REPORT.devices[0]!,+ bootProvenance: 'preexisting',+ });+ const resourceScheduler = testResourceScheduler();+ await resourceScheduler.runStart('running-instance', async () => undefined);+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ resourceScheduler,+ runtime: { inspect: vi.fn(async () => report) },+ getSession: vi.fn(async (id) => localSession(id)),+ });++ const status = await host.getStatus('session-a');++ expect(status).toMatchObject({+ ok: true,+ resource: {+ runningCount: 1,+ softLimit: 2,+ hardLimit: 4,+ maxInstancesPerTask: 4,+ },+ environment: {+ devices: [+ { udid: READY_REPORT.devices[0]!.udid, ownership: 'other-task' },+ {+ udid: unavailableDevice.udid,+ runtimeName: 'iOS 18.4',+ ownership: 'unowned',+ unavailableReason: { code: 'missing-runtime', runtimeName: 'iOS 18.4' },+ },+ ],+ },+ });+ expect(JSON.stringify(status)).not.toContain('runtime profile not found');+ expect(JSON.stringify(status)).not.toContain('availabilityError');+ expect(JSON.stringify(status)).not.toContain('session-b');+ await expect(+ host.callTool(+ 'attach_device',+ { udid: unavailableDevice.udid },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: false, errorCode: 'SIMULATOR_NOT_FOUND' });+ await host.dispose();+ });++ it('projects cached plugin status without reconciling or renewing ownership', async () => {+ const runtimeInspect = vi.fn(async () => READY_REPORT);+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle: {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ },+ });+ const attached = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'private-fingerprint',+ device: READY_REPORT.devices[0]!,+ bootProvenance: 'preexisting',+ });+ const before = actor.getOwned('session-a', attached.instanceId);+ const host = createIOSSimulatorHost({+ actor,+ runtime: { inspect: runtimeInspect },+ getSession: vi.fn(async (id) => localSession(id)),+ });++ const first = await host.getPluginStatus('session-a');+ const second = await host.getPluginStatus('session-a');+ expect(first).toEqual(second);+ expect(first).toMatchObject({+ ok: true,+ status: {+ environment: {+ platform: 'darwin',+ ready: true,+ availableDeviceCount: 1,+ },+ instances: [+ {+ instanceId: attached.instanceId,+ simulatorName: 'iPhone 17 Pro',+ generation: attached.generation,+ },+ ],+ },+ });+ expect(runtimeInspect).toHaveBeenCalledTimes(1);+ const serialized = JSON.stringify(first);+ expect(serialized).not.toContain('session-a');+ expect(serialized).not.toContain('1A9D41E0-E031-4AD0-A8B5-847480802E8E');+ expect(serialized).not.toContain('private-fingerprint');+ expect(serialized).not.toContain('lease');+ expect(serialized).not.toContain('deviceGrants');+ expect(serialized).not.toContain('mutationStates');++ const after = actor.getOwned('session-a', attached.instanceId);+ expect(after.generation).toBe(before.generation);+ expect(after.lease).toEqual(before.lease);+ await host.dispose();+ });+it('keeps build diagnostics host-available without a running simulator instance', async () => {const actor = new IOSSimulatorInstanceActor({store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),@@ -1634,7 +1774,7 @@ describe('iOS Simulator host', () => {data: { stream: { state: 'connecting' } },});expect(driverManager.recoverNativeSidecar).toHaveBeenCalledWith(started.instanceId, {- rearm: true,+ rearm: false,});expect(h264FramePump.setVisible).toHaveBeenLastCalledWith(expect.objectContaining({@@ -1642,6 +1782,17 @@ describe('iOS Simulator host', () => {visible: true,}),);++ await expect(host.setViewerVisibility('session-a', latestRoute, false)).resolves.toMatchObject({+ ok: true,+ });+ nativeAvailable = false;+ await expect(+ host.setViewerVisibility('session-a', latestRoute, true, 'h264'),+ ).resolves.toMatchObject({ ok: true });+ expect(driverManager.recoverNativeSidecar).toHaveBeenLastCalledWith(started.instanceId, {+ rearm: true,+ });});it('stops the embedded viewer when the exact external simulator is shut down', async () => {@@ -2396,6 +2547,15 @@ describe('iOS Simulator host', () => {crashCount: 3,probe: null,lastFailure: 'IOSurface lookup failed at /Users/example/private/SimulatorKit.framework',+ lastTermination: {+ reasonCode: 'process-exit' as const,+ message: 'Native sidecar exited beside /Users/example/private/SimulatorKit.framework',+ exitCode: 23,+ signal: null,+ occurredAt: '2026-07-25T00:00:01.000Z',+ stderrTail:+ 'token=private-value VideoToolbox failed at /Users/example/private/CoreSimulator.framework',+ },admission: nativeAdmission,},})),@@ -2504,6 +2664,13 @@ describe('iOS Simulator host', () => {nativeSidecar: {state: 'parked',lastFailure: 'Native sidecar is unavailable.',+ lastTermination: {+ reasonCode: 'process-exit',+ exitCode: 23,+ signal: null,+ occurredAt: '2026-07-25T00:00:01.000Z',+ stderrTail: 'token=<redacted> VideoToolbox failed at <redacted-path>',+ },admission: {generatedAt: '2026-07-25T00:00:00.000Z',processState: 'parked',@@ -2518,6 +2685,8 @@ describe('iOS Simulator host', () => {});expect(JSON.stringify(capturedState)).not.toContain('/Users/example');expect(JSON.stringify(capturedState)).not.toContain('SimulatorKit.framework');+ expect(JSON.stringify(capturedState)).not.toContain('private-value');+ expect(JSON.stringify(capturedState)).not.toContain('CoreSimulator.framework');const baseline = (screenResult as { ok: true; data: { screenMap: unknown } }).data.screenMap;await expect(host.callTool(diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.tsindex 899ff4565f..e24f420973 100644--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts@@ -77,6 +77,10 @@ import type {IOSSimulatorSessionStatus,} from '../../shared/iosSimulatorIpc.js';import { IOS_SIMULATOR_ROUTE_STATUS_CHANNEL } from '../../shared/iosSimulatorIpc.js';+import type {+ GhostIOSSimulatorStatusProbeResult,+ GhostIOSSimulatorStatusSnapshot,+} from '../../shared/ghost.js';import { createLogger } from '../logger.js';import { desktopSessionStorage } from '../maker-host/session-storage.js';import {@@ -88,11 +92,13 @@ import { compareIOSSimulatorPngBuffers, IOSSimulatorMediaCapture } from './ios-sconst logger = createLogger('mcp/cindy_ios_simulator');const BUILD_DIAGNOSTICS_TTL_MS = 30 * 60_000;+const PLUGIN_ENVIRONMENT_CACHE_MS = 30_000;const MAX_BUILD_DIAGNOSTICS = 32;const MANAGED_BUILD_RESULT_BUNDLE_PATTERN = /^CindyBuild(?:-[0-9a-f-]+)?\.xcresult$/i;const DEFAULT_DEVICE_LIVENESS_INTERVAL_MS = 1_000;const MAX_WDA_VIEWER_FRAMES_PER_SECOND = 20;const MAX_NATIVE_H264_VIEWER_FRAMES_PER_SECOND = 60;+const MAX_INSTANCES_PER_SESSION = 4;interface IOSSimulatorSessionSnapshot {id: string;@@ -176,6 +182,8 @@ export interface IOSSimulatorHost {reconcileOwnership(): Promise<void>;describeTools(sessionId: string): Promise<IOSSimulatorToolAvailabilityReport>;getStatus(sessionId: string): Promise<IOSSimulatorSessionStatus>;+ /** Read-only, redacted plugin projection; never reconciles or renews an ownership lease. */+ getPluginStatus(sessionId: string): Promise<GhostIOSSimulatorStatusProbeResult>;callTool(name: IOSSimulatorMcpToolName,args: Record<string, unknown>,@@ -240,7 +248,7 @@ function createDefaultActor(lifecycle: IOSSimulatorSimctlLifecycle): IOSSimulato);let writeTail = Promise.resolve();const store = new IOSSimulatorOwnershipStore({- maxInstancesPerSession: 4,+ maxInstancesPerSession: MAX_INSTANCES_PER_SESSION,initialInstances: registry.loadSync(),onChange: (instances) => {writeTail = writeTail@@ -455,8 +463,25 @@ function instanceData(instance: IOSSimulatorInstance): { instance: IOSSimulatorPreturn { instance: publicInstance(instance) };}+function displayRuntimeName(device: IOSSimulatorEnvironmentReport['devices'][number]): string {+ const identifierMatch = device.runtimeIdentifier.match(+ /\.SimRuntime\.([A-Za-z]+)-(\d+(?:-\d+)*)$/,+ );+ if (identifierMatch) {+ return `${identifierMatch[1]} ${identifierMatch[2].replace(/-/g, '.')}`;+ }+ return device.runtimeName.replace(+ /^(iOS) (\d+(?:-\d+)+)$/,+ (_match, platform, version) => `${platform} ${String(version).replace(/-/g, '.')}`,+ );+}+function publicEnvironment(environment: IOSSimulatorEnvironmentReport,+ options: {+ sessionId?: string;+ instances?: readonly IOSSimulatorInstance[];+ } = {},): IOSSimulatorPublicEnvironmentReport {const { xcodeSelectPath, runtimes, devices, ...safe } = environment;void xcodeSelectPath;@@ -480,9 +505,35 @@ function publicEnvironment(return safeRuntime;}),devices: devices.map((device) => {- const { availabilityError: _availabilityError, ...safeDevice } = device;- void _availabilityError;- return safeDevice;+ const { availabilityError, ...safeDevice } = device;+ const runtimeAvailabilityError = runtimes.find(+ (runtime) => runtime.identifier === device.runtimeIdentifier,+ )?.availabilityError;+ const owner = options.instances?.find(+ (instance) => instance.simulatorUdid.toUpperCase() === device.udid.toUpperCase(),+ );+ const ownership = options.sessionId+ ? owner?.sessionId === options.sessionId+ ? 'current-task'+ : owner+ ? 'other-task'+ : 'unowned'+ : undefined;+ const unavailableReason = device.isAvailable+ ? undefined+ : [availabilityError, runtimeAvailabilityError].some(+ (detail) => detail && /runtime profile not found/i.test(detail),+ )+ ? ({ code: 'missing-runtime', runtimeName: displayRuntimeName(device) } as const)+ : ({ code: 'device-unavailable' } as const);+ return {+ ...safeDevice,+ ...(unavailableReason?.code === 'missing-runtime'+ ? { runtimeName: unavailableReason.runtimeName }+ : {}),+ ...(ownership ? { ownership } : {}),+ ...(unavailableReason ? { unavailableReason } : {}),+ };}),};}@@ -491,6 +542,10 @@ function publicDriverLogTail(value: string): string {return value.replace(/https?:\/\/[^\s)]+/gi, '<redacted-url>').replace(/(?:\/Users\/|\/private\/var\/|\/tmp\/)[^\s)]+/g, '<redacted-path>')+ .replace(+ /\b(authorization|cookie|password|secret|token)(\s*[:=]\s*)([^\s,;]+)/gi,+ '$1$2<redacted>',+ ).slice(-8_000);}@@ -503,6 +558,15 @@ function publicNativeSidecarDiagnostics(// Sidecar/framework text is an untrusted implementation detail. The// structured probe and admission decision carry the public diagnosis.lastFailure: diagnostics.lastFailure ? 'Native sidecar is unavailable.' : null,+ lastTermination: diagnostics.lastTermination+ ? {+ ...diagnostics.lastTermination,+ message: publicDriverLogTail(diagnostics.lastTermination.message).slice(-2_000),+ stderrTail: diagnostics.lastTermination.stderrTail+ ? publicDriverLogTail(diagnostics.lastTermination.stderrTail)+ : null,+ }+ : null,};}@@ -664,6 +728,12 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Iconst viewerPreferredEncodings = new Map<string, 'jpeg' | 'h264'>();const viewerFallbackReasons = new Map<string, IOSSimulatorPublicRouteReasonCode>();const routeStatusCache = new Map<string, string>();+ let pluginEnvironmentCache: {+ expiresAt: number;+ value: GhostIOSSimulatorStatusSnapshot['environment'];+ } | null = null;+ let pluginEnvironmentInFlight: Promise<GhostIOSSimulatorStatusSnapshot['environment']> | null =+ null;const configuredDeviceLivenessIntervalMs =options.deviceLivenessIntervalMs ?? DEFAULT_DEVICE_LIVENESS_INTERVAL_MS;const deviceLivenessIntervalMs =@@ -1029,7 +1099,8 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): IreasonCode: 'viewer-hidden',};} else if (selectedEncoding === 'h264') {- const routeIsNative = nativeStreamRoute?.selected === 'native-sidecar' && !nativeStreamRoute.fallback;+ const routeIsNative =+ nativeStreamRoute?.selected === 'native-sidecar' && !nativeStreamRoute.fallback;const pumpState = publicRouteState(streamSnapshot?.state ?? null);stream = {adapter: routeIsNative ? 'native-sidecar' : 'wda',@@ -1055,7 +1126,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I// the JPEG pump's live health so reconnecting/disconnected is visible.state: fallback && pumpState === 'idle' ? 'fallback' : pumpState,reasonCode: fallback- ? viewerFallbackReasons.get(instance.instanceId) ?? 'wda-fallback'+ ? (viewerFallbackReasons.get(instance.instanceId) ?? 'wda-fallback'): streamSnapshot?.state === 'disconnected'? 'route-error': 'wda-active',@@ -1153,6 +1224,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Iwindow.webContents.send('maker:ios-simulator:focus-request', {sessionId,instanceId,+ userInitiated: false,});}}@@ -1344,6 +1416,104 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I);}+ function projectPluginEnvironment(+ environment: IOSSimulatorEnvironmentReport,+ ): GhostIOSSimulatorStatusSnapshot['environment'] {+ return {+ platform: environment.platform,+ supported: environment.supported,+ ready: environment.ready,+ xcodeVersion: environment.xcodeVersion,+ availableDeviceCount: environment.devices.filter((device) => device.isAvailable).length,+ };+ }++ async function readPluginEnvironment(): Promise<GhostIOSSimulatorStatusSnapshot['environment']> {+ const now = Date.now();+ if (pluginEnvironmentCache && pluginEnvironmentCache.expiresAt > now) {+ return pluginEnvironmentCache.value;+ }+ if (pluginEnvironmentInFlight) return pluginEnvironmentInFlight;+ pluginEnvironmentInFlight = runtime.inspect().then((environment) => {+ const value = projectPluginEnvironment(environment);+ if (!disposePromise) {+ pluginEnvironmentCache = { value, expiresAt: Date.now() + PLUGIN_ENVIRONMENT_CACHE_MS };+ }+ return value;+ });+ try {+ return await pluginEnvironmentInFlight;+ } finally {+ pluginEnvironmentInFlight = null;+ }+ }++ async function inspectForPlugin(sessionId: string): Promise<GhostIOSSimulatorStatusProbeResult> {+ if (disposePromise) {+ return {+ ok: false,+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',+ message: 'The iOS Simulator host is shutting down.',+ };+ }+ const resolved = await resolveSession(sessionId);+ if (!resolved.ok)+ return { ok: false, errorCode: resolved.errorCode, message: resolved.message };+ try {+ const environment = await readPluginEnvironment();+ if (disposePromise) {+ return {+ ok: false,+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',+ message: 'The iOS Simulator host is shutting down.',+ };+ }+ const instances = actor.list(resolved.sessionId);+ return {+ ok: true,+ status: {+ environment,+ instances: instances.map((instance) => ({+ instanceId: instance.instanceId,+ simulatorName: instance.simulatorName,+ generation: instance.generation,+ lifecycleState: instance.lifecycleState,+ healthState: instance.healthState,+ })),+ routeStatuses: instances.map((instance) => {+ const route = routeStatusForInstance(+ instance,+ driverManager?.get(instance.instanceId) ?? null,+ );+ return {+ instanceId: route.instanceId,+ generation: route.generation,+ stream: {+ adapter: route.stream.adapter,+ encoding: route.stream.encoding,+ state: route.stream.state,+ },+ input: {+ adapter: route.input.adapter,+ state: route.input.state,+ },+ };+ }),+ },+ };+ } catch (error) {+ logger.warn('iOS Simulator plugin status snapshot failed', {+ sessionId: resolved.sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ return {+ ok: false,+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',+ message: 'The iOS Simulator status is temporarily unavailable.',+ };+ }+ }+async function inspectForSession(sessionId: string): Promise<IOSSimulatorSessionStatus> {if (disposePromise) return hostDisposedStatus(sessionId);const resolved = await resolveSession(sessionId);@@ -1361,10 +1531,17 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Ireturn {ok: true,sessionId: resolved.sessionId,- environment: publicEnvironment(environment),+ environment: publicEnvironment(environment, {+ sessionId: resolved.sessionId,+ instances: actor.listAll(),+ }),instances: instances.map(publicInstance),deviceGrants: instances.map((instance) => grantStore.get(instance.simulatorUdid)),mutationStates: instances.map((instance) => actor.mutationState(instance.instanceId)),+ resource: {+ ...resourceScheduler.snapshot(),+ maxInstancesPerTask: MAX_INSTANCES_PER_SESSION,+ },routeStatuses: instances.map((instance) => publishRouteStatusForInstance(instance)),};}@@ -2322,10 +2499,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): IfallbackReason: IOSSimulatorPublicRouteReasonCode = null,): IOSSimulatorFramePumpSnapshot {viewerSessions.set(instance.instanceId, instance.sessionId);- viewerPreferredEncodings.set(- instance.instanceId,- fallbackReason ? 'h264' : preferredEncoding,- );+ viewerPreferredEncodings.set(instance.instanceId, fallbackReason ? 'h264' : preferredEncoding);const nativeDriver = preferredEncoding === 'h264' ? nativeH264Driver(running) : null;if (nativeDriver) {viewerEncodings.set(instance.instanceId, 'h264');@@ -2362,9 +2536,10 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Iconst report = running.driverRouter?.capabilityReport();viewerFallbackReasons.set(instance.instanceId,- fallbackReason ?? (!report || report.nativeSidecar.available === false- ? 'native-sidecar-unavailable'- : 'native-capability-unavailable'),+ fallbackReason ??+ (!report || report.nativeSidecar.available === false+ ? 'native-sidecar-unavailable'+ : 'native-capability-unavailable'),);} else {viewerFallbackReasons.delete(instance.instanceId);@@ -2400,6 +2575,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Ireturn describeToolsForSession(resolved.sessionId);},getStatus: inspectForSession,+ getPluginStatus: inspectForPlugin,async setViewerVisibility(sessionId,route,@@ -2431,6 +2607,11 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I},};}+ // A visible viewer session may retry an optional Native route in the+ // background, but those retries must respect the Sidecar crash budget.+ // Only an explicit close -> reopen starts a new viewer session that may+ // re-arm a parked Sidecar.+ const rearmNativeSidecar = !viewerSessions.has(instance.instanceId);instance = await reconcileLiveDevice(instance);assertHostActive();if (instance.lifecycleState !== 'ready') {@@ -2491,8 +2672,9 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): IdriverManager.recoverNativeSidecar) {running =- (await driverManager.recoverNativeSidecar(instance.instanceId, { rearm: true })) ??- running;+ (await driverManager.recoverNativeSidecar(instance.instanceId, {+ rearm: rearmNativeSidecar,+ })) ?? running;assertHostActive();current = currentReadyGeneration(instance);if (!current) return viewerRouteRefreshResult(currentOwnedInstance(instance));@@ -4218,7 +4400,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Idata: {environment: publicEnvironment(environment),availability,- resource: { runningCount: resourceScheduler.runningCount(), hardLimit: 4 },+ resource: resourceScheduler.snapshot(),instances,recommendedActions,},@@ -4271,10 +4453,10 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Iconst device = environment.devices.find((candidate) => candidate.udid.toUpperCase() === udid,);- if (!device) {+ if (!device || !device.isAvailable) {throw new IOSSimulatorInstanceError('SIMULATOR_NOT_FOUND',- 'The selected iOS Simulator device does not exist.',+ 'The selected iOS Simulator device does not exist or is unavailable.',);}const worktreeRoot = await resolveWorktreeRoot(resolved.session.workDir);@@ -4359,6 +4541,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I}),);routeStatusCache.clear();+ pluginEnvironmentCache = null;})();return disposePromise;},@@ -4373,6 +4556,12 @@ export function getIOSSimulatorSessionStatus(return defaultIOSSimulatorHost.getStatus(sessionId);}+export function getIOSSimulatorPluginStatus(+ sessionId: string,+): Promise<GhostIOSSimulatorStatusProbeResult> {+ return defaultIOSSimulatorHost.getPluginStatus(sessionId);+}+export function callIOSSimulatorHostTool(name: IOSSimulatorMcpToolName,args: Record<string, unknown>,@@ -4431,12 +4620,7 @@ export function setIOSSimulatorViewerStreamProfile(profile: IOSSimulatorStreamProfile,nativeProfile?: IOSSimulatorNativeH264StreamProfileRequest,): Promise<IOSSimulatorHostResult> {- return defaultIOSSimulatorHost.setViewerStreamProfile(- sessionId,- route,- profile,- nativeProfile,- );+ return defaultIOSSimulatorHost.setViewerStreamProfile(sessionId, route, profile, nativeProfile);}export function updateIOSSimulatorViewerTouch(diff --git a/apps/desktop/src/preload/ghostPreload.ts b/apps/desktop/src/preload/ghostPreload.tsindex 691196a572..bf86955c84 100644--- a/apps/desktop/src/preload/ghostPreload.ts+++ b/apps/desktop/src/preload/ghostPreload.ts@@ -31,6 +31,8 @@ import { contextBridge, ipcRenderer } from 'electron';* 的语法糖;URL 白名单守门在主机侧 previewSlot。* - workspace(req):workspace 槽的便捷口——send({type:'workspace-request',* …req}) 的语法糖;目录授权与会话创建守门全在主机侧 workspaceSlot。+ * - iosSimulator.request(req):ios-simulator 槽的便捷口——只能读取当前台前+ * 任务的公开状态并打开 Host 内置面板;不提供帧、输入或 Sidecar 权限。* - confirm(req):confirm 槽的便捷口——send({type:'confirm-request', …req}) 的* 语法糖;主机弹自己那套确认框并把用户的真实点击回给沙箱,资格审/净化/限速/* 单飞/超时兜底全在主机侧 confirmSlot 与 ghostConfirmDialogBridge。@@ -64,7 +66,11 @@ contextBridge.exposeInMainWorld('cindy', {errand: (req: Record<string, unknown>): Promise<unknown> =>ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'agent-errand-request', kind: 'run' }),queryErrand: (req: Record<string, unknown>): Promise<unknown> =>- ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'agent-errand-request', kind: 'query' }),+ ipcRenderer.invoke('ghost-pipe:send', {+ ...req,+ type: 'agent-errand-request',+ kind: 'query',+ }),// 请用户新建一条自动化(agent.schedule 加档):只能**打开预填好的创建面板**,// 建不建由用户在面板上选好模型后亲手保存。{ ok:true } 只表示"请求已被接受并投递",// 既不保证面板真开了(用户正编辑另一个表单时本次草稿会被丢弃),也不表示任务已创建@@ -83,6 +89,10 @@ contextBridge.exposeInMainWorld('cindy', {ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'preview-request' }),workspace: (req: Record<string, unknown>): Promise<unknown> =>ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'workspace-request' }),+ iosSimulator: {+ request: (req: Record<string, unknown>): Promise<unknown> =>+ ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'ios-simulator-request' }),+ },confirm: (req: Record<string, unknown>): Promise<unknown> =>ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'confirm-request' }),});diff --git a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.tsindex 958a639e5d..537e4f7d4c 100644--- a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts+++ b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts@@ -93,13 +93,31 @@ describe('ChatInput session switch focus contract', () => {expect(chatInputSource).toContain('return isInteractiveFocusedElement(activeElement);');});- it('reuses in-composer Plugin placement for routed Use and end-focuses Create with Cindy', () => {+ it('reuses composer entry paths for Plugin commands and Host capabilities', () => {+ const capabilitySelectionBlock = extractBetween(+ chatInputSource,+ 'const handlePluginCapabilitySelect = useCallback(',+ 'const handleVoiceInputPermissionRequired = useCallback',+ );+expect(pluginPageSource).toContain('pendingGhostId: ghost.manifest.id');+ expect(pluginPageSource).toContain('pendingHostCapabilityGhostId: ghost.manifest.id');expect(pluginPageSource.match(/focusAtEnd: true/g)).toHaveLength(1);expect(chatInputSource.match(/placeGhostAtComposerStart\(editor, ghost, installedGhosts\)/g),).toHaveLength(2);expect(chatInputSource).toContain('pendingGhostId: undefined');+ expect(chatInputSource).toContain('pendingHostCapabilityGhostId: undefined');+ expect(+ chatInputSource.match(+ /placeHostCapabilityAtComposerStart\(editor, ghost, installedGhosts\)/g,+ ),+ ).toHaveLength(2);+ expect(capabilitySelectionBlock).toContain(+ 'placeHostCapabilityAtComposerStart(editor, ghost, installedGhosts);',+ );+ expect(capabilitySelectionBlock).not.toContain('sessionId');+ expect(capabilitySelectionBlock).not.toContain('focusIOSSimulatorPanel');expect(chatInputSource).toContain('focusComposerEndNextFrame(editor);');});@@ -126,9 +144,7 @@ describe('ChatInput session switch focus contract', () => {const transitionBegin = chatInputSource.indexOf('makerChatStore.beginRemoteOptimisticComposerTransition(',);- const optimisticClear = chatInputSource.indexOf(- 'if (optimisticallyClearRemoteComposer) {',- );+ const optimisticClear = chatInputSource.indexOf('if (optimisticallyClearRemoteComposer) {');const frozenReferenceHydration = chatInputSource.search(/agentReferences\s*=\s*await resolveSerializedSessionMessageReferencesForSend\(agentReferences\);/,);@@ -162,7 +178,9 @@ describe('ChatInput session switch focus contract', () => {expect(chatInputSource).toContain('latestStorageKeyRef.current === sourceStorageKey &&\n storageKeyForDraftRef.current === sourceStorageKey',);- expect(chatInputSource).toContain('restoreRemoteOptimisticDraft(\n sourceStorageKey,');+ expect(chatInputSource).toContain(+ 'restoreRemoteOptimisticDraft(\n sourceStorageKey,',+ );expect(chatInputSource).toContain('!isDataOwnerGenerationCurrent(dataOwnerAtOptimisticClear)');expect(chatInputSource).toContain('restoreOptimisticallyClearedComposer(clientId, {');expect(chatInputSource).toContain('isRemoteOptimisticDataOwnerBoundaryError(error)');diff --git a/apps/desktop/src/renderer/__tests__/composerChipPresentation.test.tsx b/apps/desktop/src/renderer/__tests__/composerChipPresentation.test.tsxindex c4e1e0e821..6354b45195 100644--- a/apps/desktop/src/renderer/__tests__/composerChipPresentation.test.tsx+++ b/apps/desktop/src/renderer/__tests__/composerChipPresentation.test.tsx@@ -59,6 +59,16 @@ function ComposerHarness({ onEditor }: { onEditor?: (editor: Editor) => void })type: 'mentionChip',attrs: { kind: 'file', label: 'main.ts', path: 'src/main.ts' },},+ {+ type: 'mentionChip',+ attrs: {+ kind: 'plugin-capability',+ label: 'ios-simulator',+ path: 'ios-simulator',+ pluginId: 'ios-simulator',+ sourceLabel: 'iOS Simulator',+ },+ },{ type: 'text', text: ' /skill between ' },{type: 'pastedTextChip',@@ -120,7 +130,7 @@ describe('composer atomic chip presentation', () => {const { container } = render(<ComposerHarness />);const atoms = await waitFor(() => {const renderedAtoms = [- container.querySelector<HTMLElement>('[data-mention-chip]'),+ ...container.querySelectorAll<HTMLElement>('[data-mention-chip]'),container.querySelector<HTMLElement>('[data-pasted-text-chip]'),container.querySelector<HTMLElement>('[data-composer-quote]'),];@@ -141,6 +151,12 @@ describe('composer atomic chip presentation', () => {expect(atom?.querySelector('button')).toBeNull();}expect(container.querySelector('[data-mention-chip][data-kind="slash"]')).toBeNull();+ expect(+ container.querySelector(+ '[data-mention-chip][data-kind="plugin-capability"] svg.lucide-puzzle',+ ),+ ).toBeTruthy();+ expect(container.textContent).toContain('ios-simulator');expect(container.textContent).toContain('/skill');});@@ -189,14 +205,14 @@ describe('composer atomic chip presentation', () => {return activeEditor;});const mention = await waitFor(() => {- const element = container.querySelector<HTMLElement>('[data-mention-chip]');+ const element = container.querySelector<HTMLElement>('[data-mention-chip][data-kind="file"]');if (!element) throw new Error('Mention atom was not rendered');return element;});let mentionPos: number | null = null;editor.state.doc.descendants((node, pos) => {- if (node.type.name !== 'mentionChip') return true;+ if (node.type.name !== 'mentionChip' || node.attrs.kind !== 'file') return true;mentionPos = pos;return false;});@@ -228,9 +244,18 @@ describe('composer atomic chip presentation', () => {const atomOrder: string[] = [];editor.state.doc.descendants((node) => {if (['mentionChip', 'pastedTextChip', 'composerQuote'].includes(node.type.name)) {- atomOrder.push(node.type.name);+ atomOrder.push(+ node.type.name === 'mentionChip'+ ? `${node.type.name}:${String(node.attrs.kind)}`+ : node.type.name,+ );}});- expect(atomOrder).toEqual(['pastedTextChip', 'composerQuote', 'mentionChip']);+ expect(atomOrder).toEqual([+ 'mentionChip:plugin-capability',+ 'pastedTextChip',+ 'composerQuote',+ 'mentionChip:file',+ ]);});});diff --git a/apps/desktop/src/renderer/__tests__/composerHostCapability.test.ts b/apps/desktop/src/renderer/__tests__/composerHostCapability.test.tsnew file mode 100644index 0000000000..9c5b319a2e--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/composerHostCapability.test.ts@@ -0,0 +1,132 @@+// @vitest-environment jsdom++import { Editor } from '@tiptap/core';+import Document from '@tiptap/extension-document';+import Paragraph from '@tiptap/extension-paragraph';+import Text from '@tiptap/extension-text';+import { afterEach, describe, expect, it } from 'vitest';++import { expandGhostCommand } from '@/cindy-brain/ghostCommand';+import {+ expandHostCapabilityInvocation,+ splitHostCapabilityDirective,+} from '@/cindy-brain/hostCapabilityInvocation';+import { serializeEditorContent } from '@/components/new-chat/composerContentSerialization';+import { MentionChipNode } from '@/components/new-chat/MentionChipNode';+import { i18n } from '@/i18n';+import type { InstalledGhost } from '../../shared/ghost';++const editors: Editor[] = [];+const initialLanguage = i18n.language;++function capabilityGhost(): InstalledGhost {+ return {+ manifest: {+ schemaVersion: 2,+ id: 'ios-simulator',+ name: 'iOS Simulator',+ version: '0.2.0',+ kind: 'chip',+ entry: 'main.js',+ slots: ['ios-simulator'],+ },+ dir: '/tmp/ios-simulator',+ enabled: true,+ };+}++function editorWithCapability(path = 'ios-simulator', label = 'iOS Simulator', body = ''): Editor {+ const editor = new Editor({+ extensions: [Document, Paragraph, Text, MentionChipNode],+ content: {+ type: 'doc',+ content: [+ {+ type: 'paragraph',+ content: [+ {+ type: 'mentionChip',+ attrs: {+ kind: 'plugin-capability',+ label,+ path,+ pluginId: 'ios-simulator',+ sourceLabel: 'iOS Simulator',+ },+ },+ ...(body ? [{ type: 'text', text: ` ${body}` }] : []),+ ],+ },+ ],+ },+ });+ editors.push(editor);+ return editor;+}++afterEach(async () => {+ for (const editor of editors.splice(0)) editor.destroy();+ await i18n.changeLanguage(initialLanguage);+});++describe('Host capability composer chip', () => {+ it('serializes as routing metadata rather than an automatic visible prefix', async () => {+ await i18n.changeLanguage('zh-CN');+ const serialized = serializeEditorContent(editorWithCapability());++ expect(serialized.text).toBe('');+ expect(serialized.hostCapability).toEqual({+ capability: 'ios-simulator',+ ghostId: 'ios-simulator',+ name: 'iOS Simulator',+ });+ expect(serialized.mentions).toEqual([]);+ expect(serialized.agentReferences).toEqual([]);+ expect(expandGhostCommand(serialized.text, [capabilityGhost()])).toBe(serialized.text);+ expect(serialized.text).not.toContain('ghost_call');+ });++ it('keeps user text once and appends a parseable Host route without ghost_call routing', () => {+ const serialized = serializeEditorContent(+ editorWithCapability('ios-simulator', 'iOS Simulator', '帮我打开iOS模拟器,调试当前项目'),+ );+ expect(serialized.text).toBe('帮我打开iOS模拟器,调试当前项目');++ const expanded = expandHostCapabilityInvocation(+ serialized.text,+ serialized.hostCapability!,+ '帮我打开 iOS 模拟器。',+ );+ const split = splitHostCapabilityDirective(expanded);+ expect(split?.body).toBe('帮我打开iOS模拟器,调试当前项目');+ expect(split?.directive).toMatchObject({+ kind: 'host-capability',+ capability: 'ios-simulator',+ route: 'cindy_ios_simulator',+ ghostId: 'ios-simulator',+ });+ expect(expanded.match(/帮我打开/g)).toHaveLength(1);+ expect(expanded).toContain('不要通过 ghost_call 调用');+ expect(expanded).not.toContain('必须通过 cindy 总机的 ghost_call');+ });++ it('uses one default prompt when the chip is sent by itself', () => {+ const serialized = serializeEditorContent(editorWithCapability());+ const expanded = expandHostCapabilityInvocation(+ serialized.text,+ serialized.hostCapability!,+ '帮我打开 iOS 模拟器。',+ );+ expect(splitHostCapabilityDirective(expanded)?.body).toBe('帮我打开 iOS 模拟器。');+ });++ it('preserves an unknown future capability as structured metadata', () => {+ expect(+ serializeEditorContent(editorWithCapability('future-capability', 'Future')).hostCapability,+ ).toEqual({+ capability: 'future-capability',+ ghostId: 'ios-simulator',+ name: 'iOS Simulator',+ });+ });+});diff --git a/apps/desktop/src/renderer/__tests__/ghostComposerPlacement.test.ts b/apps/desktop/src/renderer/__tests__/ghostComposerPlacement.test.tsindex dd78e8eb36..d6abbd3476 100644--- a/apps/desktop/src/renderer/__tests__/ghostComposerPlacement.test.ts+++ b/apps/desktop/src/renderer/__tests__/ghostComposerPlacement.test.ts@@ -11,7 +11,11 @@ import {ComposerListItem,ComposerOrderedList,} from '@/components/new-chat/ComposerListNodes';-import { placeGhostAtComposerStart } from '@/components/new-chat/ghostComposerPlacement';+import {+ findHostCapabilityChipMatch,+ placeGhostAtComposerStart,+ placeHostCapabilityAtComposerStart,+} from '@/components/new-chat/ghostComposerPlacement';import { MentionChipNode } from '@/components/new-chat/MentionChipNode';import type { InstalledGhost } from '../../shared/ghost';@@ -35,6 +39,22 @@ function ghost(command: string, id = command, enabled = true): InstalledGhost {};}+function hostCapabilityGhost(id = 'ios-simulator'): InstalledGhost {+ return {+ manifest: {+ schemaVersion: 2,+ id,+ name: 'iOS Simulator',+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ slots: ['ios-simulator'],+ },+ dir: `/tmp/${id}`,+ enabled: true,+ };+}+function editorWith(content: string): Editor {const editor = new Editor({extensions: [Document, Paragraph, Text, MentionChipNode],@@ -86,6 +106,17 @@ describe('placeGhostAtComposerStart', () => {expect(editor.getText()).toBe('$feishu 帮我整理这段内容');});+ it('replaces a Host capability chip instead of stacking Plugin invocations', () => {+ const capability = hostCapabilityGhost();+ const selected = ghost('feishu');+ const editor = editorWith('继续补充需求');+ placeHostCapabilityAtComposerStart(editor, capability, [capability, selected]);++ expect(placeGhostAtComposerStart(editor, selected, [capability, selected])).toBe(true);+ expect(editor.getText()).toBe('$feishu 继续补充需求');+ expect(findHostCapabilityChipMatch(editor.state.doc)).toBeNull();+ });+it('adds a command paragraph before a leading structured list', () => {const editor = new Editor({extensions: [@@ -231,3 +262,49 @@ describe('placeGhostAtComposerStart', () => {expect(editor.getJSON().content?.[1]?.type).toBe('bulletList');});});++describe('placeHostCapabilityAtComposerStart', () => {+ it('prepends an atomic Plugin capability chip and preserves existing text', () => {+ const selected = hostCapabilityGhost();+ const editor = editorWith('帮我调试登录流程');++ expect(placeHostCapabilityAtComposerStart(editor, selected, [selected])).toBe(true);+ const match = findHostCapabilityChipMatch(editor.state.doc);+ expect(match?.attrs).toMatchObject({+ kind: 'plugin-capability',+ label: 'iOS Simulator',+ path: 'ios-simulator',+ pluginId: 'ios-simulator',+ sourceLabel: 'iOS Simulator',+ });+ expect(editor.getText()).toBe(' 帮我调试登录流程');+ expect(editor.state.selection.to).toBe(editor.state.doc.content.size - 1);+ });++ it('replaces an existing command and keeps a single invocation at message start', () => {+ const oldPlugin = ghost('mivo');+ const selected = hostCapabilityGhost();+ const editor = editorWith('$mivo 继续补充需求');++ expect(placeHostCapabilityAtComposerStart(editor, selected, [oldPlugin, selected])).toBe(true);+ expect(findHostCapabilityChipMatch(editor.state.doc)?.attrs.pluginId).toBe('ios-simulator');+ expect(editor.getText()).toBe(' 继续补充需求');+ });++ it('replaces an existing Host capability chip instead of stacking atoms', () => {+ const first = hostCapabilityGhost('ios-simulator-old');+ const selected = hostCapabilityGhost();+ const editor = editorWith('正文');+ placeHostCapabilityAtComposerStart(editor, first, [first, selected]);++ expect(placeHostCapabilityAtComposerStart(editor, selected, [first, selected])).toBe(true);+ let capabilityCount = 0;+ editor.state.doc.descendants((node) => {+ if (node.type.name === 'mentionChip' && node.attrs.kind === 'plugin-capability') {+ capabilityCount += 1;+ }+ });+ expect(capabilityCount).toBe(1);+ expect(findHostCapabilityChipMatch(editor.state.doc)?.attrs.pluginId).toBe('ios-simulator');+ });+});diff --git a/apps/desktop/src/renderer/__tests__/ghostSummonChip.test.tsx b/apps/desktop/src/renderer/__tests__/ghostSummonChip.test.tsxindex 65fbf8cdac..b2a69752e8 100644--- a/apps/desktop/src/renderer/__tests__/ghostSummonChip.test.tsx+++ b/apps/desktop/src/renderer/__tests__/ghostSummonChip.test.tsx@@ -19,6 +19,7 @@ import '@/i18n';import i18n from '@/i18n';import { GhostFulfillmentContext, GhostSummonCard } from '@/components/chat/GhostSummonCard';import type { GhostDirectiveDisplay } from '@/cindy-brain/ghostCommand';+import type { HostCapabilityDirectiveDisplay } from '@/cindy-brain/hostCapabilityInvocation';vi.mock('@/cindy-brain/useInstalledGhosts', () => ({useInstalledGhosts: () => [],@@ -38,6 +39,15 @@ const mentionDirective: GhostDirectiveDisplay = {raw: '[插件提示] 消息提及了插件 XD Feishu(id: xd-feishu)',};+const hostCapabilityDirective: HostCapabilityDirectiveDisplay = {+ kind: 'host-capability',+ capability: 'ios-simulator',+ route: 'cindy_ios_simulator',+ name: 'iOS 模拟器',+ ghostId: 'ios-simulator',+ raw: '[Cindy Host 能力] iOS 模拟器',+};+/** 模拟 prefers-reduced-motion 匹配结果(jsdom 默认无 matchMedia)。 */function stubMatchMedia(matches: boolean) {window.matchMedia = ((query: string) => ({@@ -88,6 +98,20 @@ describe('GhostSummonCard(chip 形态)', () => {expect(screen.getByText('已完成')).toBeTruthy();});+ it('renders Host capability selection as the same annotation without claiming ghost_call', () => {+ const { container } = render(<GhostSummonCard directive={hostCapabilityDirective} running />);+ expect(screen.getByText('iOS 模拟器')).toBeTruthy();+ expect(screen.getByText('已选择')).toBeTruthy();+ expect(screen.queryByText('调用中…')).toBeNull();+ expect(container.querySelector('.animate-\\[spin_2\\.4s_linear_infinite\\]')).toBeNull();+ expect(container.querySelector('svg.lucide-check')).toBeNull();++ fireEvent.click(screen.getByRole('button', { expanded: false }));+ expect(screen.getByText('发送给 Agent 的 Cindy 能力路由')).toBeTruthy();+ expect(screen.getByText('cindy_ios_simulator')).toBeTruthy();+ expect(screen.getByText(/不要通过 ghost_call 调用/)).toBeTruthy();+ });+it('mounts historic messages directly on the closed static frame', () => {const { container } = render(<GhostFulfillmentContext.Provider value={fulfillmentOf('m1', ['xd-feishu'])}>diff --git a/apps/desktop/src/renderer/__tests__/planModeComposerEntry.test.ts b/apps/desktop/src/renderer/__tests__/planModeComposerEntry.test.tsindex d4b9f79498..34b4373e51 100644--- a/apps/desktop/src/renderer/__tests__/planModeComposerEntry.test.ts+++ b/apps/desktop/src/renderer/__tests__/planModeComposerEntry.test.ts@@ -68,6 +68,52 @@ const installedMermaidPlugin: InstalledGhost = {enabled: true,};+const installedIOSSimulatorPlugin: InstalledGhost = {+ manifest: {+ schemaVersion: 2,+ id: 'ios-simulator',+ name: 'iOS Simulator',+ version: '0.2.0',+ kind: 'chip',+ entry: 'main.js',+ slots: ['skill', 'ios-simulator'],+ skill: {+ items: [+ {+ dir: 'skills/cindy-ios-simulator',+ name: 'cindy-ios-simulator',+ description: 'Use the Host-owned iOS Simulator.',+ },+ ],+ },+ },+ dir: '/tmp/ios-simulator',+ enabled: true,+};++const installedSkillOnlyPlugin: InstalledGhost = {+ manifest: {+ schemaVersion: 2,+ id: 'skill-only',+ name: 'Skill only',+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ slots: ['skill'],+ skill: {+ items: [+ {+ dir: 'skills/example',+ name: 'example',+ description: 'Example workflow.',+ },+ ],+ },+ },+ dir: '/tmp/skill-only',+ enabled: true,+};+afterEach(() => {cleanup();vi.clearAllMocks();@@ -292,6 +338,46 @@ describe('ExtraDirsButton 模式菜单项', () => {expect(pluginRow.querySelector('svg.lucide-workflow')).toBeTruthy();expect(pluginRow.querySelector('svg.lucide-package')).toBeNull();});++ it('Host capability 插件可从菜单交给 composer 处理,不伪造 command', () => {+ const onPluginCapabilitySelect = vi.fn();+ render(+ createElement(ExtraDirsButton, {+ extraDirs: [],+ plugins: [installedIOSSimulatorPlugin],+ pluginAvailableIds: new Set(['ios-simulator']),+ onPluginCapabilitySelect,+ }),+ );++ fireEvent.click(screen.getByLabelText('extraDirs.menuAria'));+ const pluginRow = screen.getByRole('button', { name: 'iOS Simulator' });+ expect((pluginRow as HTMLButtonElement).disabled).toBe(false);+ fireEvent.click(pluginRow);+ expect(onPluginCapabilitySelect).toHaveBeenCalledWith(installedIOSSimulatorPlugin);+ });++ it('已停用优先显示停用状态;可用但无直接入口的 Skill 标为 Agent 自动调用', () => {+ const { rerender } = render(+ createElement(ExtraDirsButton, {+ extraDirs: [],+ plugins: [installedIOSSimulatorPlugin],+ pluginAvailableIds: new Set<string>(),+ onPluginCapabilitySelect: vi.fn(),+ }),+ );+ fireEvent.click(screen.getByLabelText('extraDirs.menuAria'));+ expect(screen.getByText('extraDirs.pluginDisabled')).toBeTruthy();++ rerender(+ createElement(ExtraDirsButton, {+ extraDirs: [],+ plugins: [installedSkillOnlyPlugin],+ pluginAvailableIds: new Set(['skill-only']),+ }),+ );+ expect(screen.getByText('extraDirs.pluginAgentInvoked')).toBeTruthy();+ });});describe('PlanModeIndicator 激活 chip', () => {diff --git a/apps/desktop/src/renderer/__tests__/selectionQuoteUserMessage.test.ts b/apps/desktop/src/renderer/__tests__/selectionQuoteUserMessage.test.tsindex 87cbe95ba2..3920f0366e 100644--- a/apps/desktop/src/renderer/__tests__/selectionQuoteUserMessage.test.ts+++ b/apps/desktop/src/renderer/__tests__/selectionQuoteUserMessage.test.ts@@ -27,15 +27,16 @@ describe('SelectionQuoteButton — user message floating action exclusion', () =it('keeps long-message collapse enabled for mixed quote and prose messages', () => {const collapseGuard = userMessageSource.slice(userMessageSource.indexOf('const collapseMeasureEnabled ='),- userMessageSource.indexOf('const { mirrorRef:', userMessageSource.indexOf('const collapseMeasureEnabled =')),+ userMessageSource.indexOf(+ 'const { mirrorRef:',+ userMessageSource.indexOf('const collapseMeasureEnabled ='),+ ),);expect(collapseGuard).not.toContain('inlineQuoteCount === 0');- expect(userMessageSource).toContain(- "longMessageCollapsed && (automationOrigin ? 'line-clamp-3' : 'line-clamp-10')",- );expect(userMessageSource).toMatch(- /\{renderContent\(\n\s+segment\.text,/,+ /longMessageCollapsed\s*&&\s*\(automationOrigin \? 'line-clamp-3' : 'line-clamp-10'\)/,);+ expect(userMessageSource).toMatch(/\{renderContent\(\n\s+segment\.text,/);expect(userMessageSource).toContain('!longMessageCollapsed,');});@@ -45,7 +46,9 @@ describe('SelectionQuoteButton — user message floating action exclusion', () =);expect(buttonSource).toContain("container.dataset.selectionQuoteContext = '';");expect(buttonSource).toContain('readSelectionInStream(true)');- expect(buttonSource).toContain('!allowQuoteDisabled && selectionIntersectsFloatingQuoteDisabledArea');+ expect(buttonSource).toContain(+ '!allowQuoteDisabled && selectionIntersectsFloatingQuoteDisabledArea',+ );});it('keeps the floating action at its intrinsic width near either viewport edge', () => {@@ -69,10 +72,12 @@ describe('SelectionQuoteButton — user message floating action exclusion', () =querySelectorAll: vi.fn(() => [allowed, disabled]),};- expect(selectionIntersectsFloatingQuoteDisabledArea(- range as Pick<Range, 'intersectsNode'>,- container as unknown as Pick<HTMLElement, 'querySelectorAll'>,- )).toBe(true);+ expect(+ selectionIntersectsFloatingQuoteDisabledArea(+ range as Pick<Range, 'intersectsNode'>,+ container as unknown as Pick<HTMLElement, 'querySelectorAll'>,+ ),+ ).toBe(true);expect(range.intersectsNode).toHaveBeenCalledTimes(2);});@@ -80,9 +85,11 @@ describe('SelectionQuoteButton — user message floating action exclusion', () =const range = { intersectsNode: vi.fn(() => false) };const container = { querySelectorAll: vi.fn(() => [{} as Element]) };- expect(selectionIntersectsFloatingQuoteDisabledArea(- range as Pick<Range, 'intersectsNode'>,- container as unknown as Pick<HTMLElement, 'querySelectorAll'>,- )).toBe(false);+ expect(+ selectionIntersectsFloatingQuoteDisabledArea(+ range as Pick<Range, 'intersectsNode'>,+ container as unknown as Pick<HTMLElement, 'querySelectorAll'>,+ ),+ ).toBe(false);});});diff --git a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsxindex ed11267e18..1f02e18194 100644--- a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx+++ b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx@@ -29,6 +29,7 @@ import {PanelRight,Sparkles,ShieldAlert,+ Smartphone,Terminal,Wrench,type LucideIcon,@@ -37,11 +38,7 @@ import { useState, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';import { cn } from '@/lib/utils';-import type {- GhostPermissionDiff,- GhostPermissionItem,- GhostTrustInfo,-} from '../../shared/ghost';+import type { GhostPermissionDiff, GhostPermissionItem, GhostTrustInfo } from '../../shared/ghost';const KIND_ICON: Record<GhostPermissionItem['kind'], LucideIcon> = {cindy: Sparkles, // 与详情页「Cindy 能力」区同款图标@@ -62,6 +59,7 @@ const KIND_ICON: Record<GhostPermissionItem['kind'], LucideIcon> = {preview: AppWindow,skill: GraduationCap,workspace: FolderPlus,+ 'ios-simulator': Smartphone,};function itemIcon(item: GhostPermissionItem): LucideIcon {diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsxindex 7ca1165802..6c34363713 100644--- a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsx+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsx@@ -95,6 +95,16 @@ describe('GhostPermissionList(装入全量清单)', () => {expect(container.innerHTML).toBe('');});+ it('ios-simulator 槽如实披露 Host-owned 控制边界', () => {+ const simulator: GhostManifest = {+ ...chip(),+ slots: [...chip().slots, 'ios-simulator'],+ };+ render(<GhostPermissionList items={ghostPermissionItems(simulator)} />);+ expect(screen.getByText('settings.ghosts.perm.iosSimulator')).toBeTruthy();+ expect(screen.getByText('settings.ghosts.perm.iosSimulatorDetail')).toBeTruthy();+ });+it('network 槽:域名/凭证逐条渲染,code 沙箱说明切分档版', () => {const net: GhostManifest = {...chip(),@@ -247,7 +257,9 @@ describe('GhostUpdateReview(更新确认内容区,两个入口共用)', () => {});it('不自套限高滚动区(高度归共享 ConfirmDialog)', () => {- const { container } = render(<GhostUpdateReview diff={diffGhostPermissionItems(chip(), next())} />);+ const { container } = render(+ <GhostUpdateReview diff={diffGhostPermissionItems(chip(), next())} />,+ );const scrollers = container.querySelectorAll('.overflow-y-auto');expect(scrollers.length).toBe(0);});diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanelTheme.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanelTheme.test.tsindex 9473357c5a..003ff74c88 100644--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanelTheme.test.ts+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanelTheme.test.ts@@ -140,6 +140,20 @@ describe('注入基线 CSS(幽灵 token 防线 + 设置区卡片色对齐)', ());});+ it('面板下发功能性 motion token,插件无需硬编码交互与 spinner 时长', () => {+ withDomStubs(+ () => {+ const css = buildGhostThemeCss();+ expect(css).toContain('--motion-fast: 150ms');+ expect(css).toContain('--motion-spinner-cycle: 1000ms');+ },+ {+ tokenValue: (token) =>+ token === '--motion-fast' ? '150ms' : token === '--motion-spinner-cycle' ? '1000ms' : '',+ },+ );+ });+it('设置区基线:背景 = 宿主设置卡片色(与相邻卡片无缝),fallback --surface', () => {withDomStubs(() => {expect(buildGhostSettingsThemeCss()).toContain(@@ -256,7 +270,9 @@ describe('沙箱页明暗档下发(color-scheme,双模式门槛)', () => {injector.inject();await flush();expect(webview.insertCSS).toHaveBeenCalledTimes(2);- expect(webview.insertCSS).toHaveBeenLastCalledWith(expect.stringContaining('color-scheme: dark;'));+ expect(webview.insertCSS).toHaveBeenLastCalledWith(+ expect.stringContaining('color-scheme: dark;'),+ );});});diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.tsindex 54ad4b184d..a6bc7124cf 100644--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts@@ -11,6 +11,7 @@ import {filterGhostPluginItems,ghostFallbackIconKind,ghostPanelOwnerKey,+ ghostPrimaryAction,marketPresentationForInstalledGhost,nextOpenPanelIdForOwner,sortGhostPluginItemsByRecentUse,@@ -108,6 +109,7 @@ describe('ghostPluginViewModel', () => {enabled: true,canUse: true,tabPanel: false,+ hostCapability: null,},{id: 'lizi-mivo',@@ -117,6 +119,7 @@ describe('ghostPluginViewModel', () => {enabled: true,canUse: true,tabPanel: false,+ hostCapability: null,},{id: 'slack',@@ -126,6 +129,7 @@ describe('ghostPluginViewModel', () => {enabled: true,canUse: true,tabPanel: false,+ hostCapability: null,},] satisfies GhostPluginListItem[];@@ -216,10 +220,27 @@ describe('ghostPluginViewModel', () => {name: 'XD Mivo',enabled: true,canUse: true,+ hostCapability: null,version: '1.5.10',});});+ it('projects the iOS Simulator slot as an explicit Host capability action', () => {+ const item = toGhostPluginListItem(+ installed({+ manifest: manifest({+ command: undefined,+ slots: ['skill', 'ios-simulator'],+ tools: undefined,+ network: undefined,+ }),+ }),+ );++ expect(item.hostCapability).toBe('ios-simulator');+ expect(ghostPrimaryAction(item)).toBe('capability');+ });+it('overlays exact installed market presentation without changing runtime facts', () => {const ghost = installed({iconDataUrl: 'data:image/png;base64,OLD',@@ -364,7 +385,9 @@ describe('plugin panel owner isolation', () => {// A 打开着面板 → 切到 B:必须关掉,不许因为 B 也装了同 id 的插件就留着。expect(nextOpenPanelIdForOwner(a, b, 'ghost-shared')).toBeNull();// 云 → 本地同样算换身份。- expect(nextOpenPanelIdForOwner(a, ghostPanelOwnerKey('local', null), 'ghost-shared')).toBeNull();+ expect(+ nextOpenPanelIdForOwner(a, ghostPanelOwnerKey('local', null), 'ghost-shared'),+ ).toBeNull();// 身份没变则原样保留(别把用户正在用的面板关掉)。expect(nextOpenPanelIdForOwner(a, a, 'ghost-shared')).toBe('ghost-shared');expect(nextOpenPanelIdForOwner(a, a, null)).toBeNull();diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/installErrorKey.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/installErrorKey.test.tsnew file mode 100644index 0000000000..102639c9d6--- /dev/null+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/installErrorKey.test.ts@@ -0,0 +1,12 @@+import { describe, expect, it } from 'vitest';++import { ghostInstallErrorKey } from '../installErrorKey';++describe('ghostInstallErrorKey', () => {+ it('distinguishes a valid plugin that needs a newer Host from an invalid package', () => {+ expect(ghostInstallErrorKey('GHOST_HOST_UNSUPPORTED')).toBe(+ 'settings.ghosts.errors.hostUnsupported',+ );+ expect(ghostInstallErrorKey('GHOST_FILE_INVALID')).toBe('settings.ghosts.errors.fileInvalid');+ });+});diff --git a/apps/desktop/src/renderer/cindy-brain/ghostPanelTheme.ts b/apps/desktop/src/renderer/cindy-brain/ghostPanelTheme.tsindex cdd9171a95..c5a2a3711b 100644--- a/apps/desktop/src/renderer/cindy-brain/ghostPanelTheme.ts+++ b/apps/desktop/src/renderer/cindy-brain/ghostPanelTheme.ts@@ -35,6 +35,10 @@ const GHOST_THEME_TOKENS = [// 滚动条(globals.css 统一规范同源色):意识面板照主机同款画 thumb。'--msg-scrollbar','--msg-scrollbar-hover',+ // 功能性交互与 loading 动画只消费主机设计系统的 motion token;插件面板+ // 不得自行硬编码时长。这里只下发当前面板契约实际需要的两档。+ '--motion-fast',+ '--motion-spinner-cycle',// 工具卡四件套(data-ghost-audio 卡内播放器 1:1 对标基座 ChatAudioCard 的// 配色来源;注册值是 var(--surface-elevated) 这类别名引用,目标 token 也在// 本白名单 → iframe 内 var 链完整解析)。--text-secondary-mid 是diff --git a/apps/desktop/src/renderer/cindy-brain/hostCapabilityInvocation.ts b/apps/desktop/src/renderer/cindy-brain/hostCapabilityInvocation.tsnew file mode 100644index 0000000000..72818c7142--- /dev/null+++ b/apps/desktop/src/renderer/cindy-brain/hostCapabilityInvocation.ts@@ -0,0 +1,115 @@+/**+ * Host capability invocation metadata for user messages.+ *+ * A Host capability Plugin is not a normal command Plugin: selecting it must+ * route the Agent to a Cindy-owned capability and must never synthesize a+ * `ghost_call`. The deterministic suffix below serves two purposes:+ *+ * - it tells the Agent which Host route the user explicitly selected;+ * - it persists enough structured identity for UserMessage to render the same+ * invocation annotation used by command Plugins.+ *+ * Generation and parsing share one exact template. Anything that does not+ * match the complete suffix remains ordinary user text.+ */++import type { GhostDirectiveSegment } from './ghostCommand';++export interface HostCapabilitySelection {+ capability: string;+ ghostId: string;+ name: string;+}++export interface HostCapabilityDirectiveDisplay extends HostCapabilitySelection {+ kind: 'host-capability';+ route: string;+ raw: string;+}++export function routeForHostCapability(capability: string): string {+ return capability === 'ios-simulator' ? 'cindy_ios_simulator' : capability;+}++/** The exact suffix sent to the Agent and shown in the invocation details. */+export function hostCapabilityDirectiveSegments(+ selection: HostCapabilitySelection & { route?: string },+): GhostDirectiveSegment[] {+ const route = selection.route ?? routeForHostCapability(selection.capability);+ return [+ { text: '[Cindy Host 能力] 用户显式选择了「', injected: false },+ { text: selection.name, injected: true },+ { text: '」(capability: ', injected: false },+ { text: selection.capability, injected: true },+ { text: ', plugin id: ', injected: false },+ { text: selection.ghostId, injected: true },+ { text: ', route: ', injected: false },+ { text: route, injected: true },+ {+ text:+ ')。必须使用 Cindy Host 的上述 route 完成本请求;这是 Host 能力,不是普通插件命令,' ++ '不要通过 ghost_call 调用。',+ injected: false,+ },+ ];+}++function buildHostCapabilityDirective(selection: HostCapabilitySelection): string {+ return hostCapabilityDirectiveSegments(selection)+ .map((segment) => segment.text)+ .join('');+}++/**+ * Append Host routing metadata without changing the user's own body.+ * `defaultPrompt` is used only when the capability chip was sent by itself.+ */+export function expandHostCapabilityInvocation(+ text: string,+ selection: HostCapabilitySelection,+ defaultPrompt: string,+): string {+ const body = text.trim() ? text : defaultPrompt;+ const directive = buildHostCapabilityDirective(selection);+ return `${body}\n\n${directive}`;+}++const escapeRegExp = (value: string): string => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');++const P1 = '\u0001';+const P2 = '\u0002';+const P3 = '\u0003';+const P4 = '\u0004';++const HOST_CAPABILITY_DIRECTIVE_RE = new RegExp(+ `\\n\\n(${escapeRegExp(+ hostCapabilityDirectiveSegments({ capability: P1, name: P2, ghostId: P3, route: P4 })+ .map((segment) => segment.text)+ .join(''),+ )+ .replace(P1, '([^,)]+?)')+ .replace(P2, '(.+?)')+ .replace(P3, '([^,)]+?)')+ .replace(P4, '([^,)]+?)')})$`,+);++/** Split a complete persisted Host capability suffix from the visible body. */+export function splitHostCapabilityDirective(+ content: string,+): { body: string; directive: HostCapabilityDirectiveDisplay } | null {+ const match = HOST_CAPABILITY_DIRECTIVE_RE.exec(content);+ if (!match) return null;+ return {+ body: content.slice(0, match.index),+ directive: {+ kind: 'host-capability',+ raw: match[1],+ // Capture groups follow placeholder occurrence in the template: name+ // appears before capability even though their constants are P2 / P1.+ name: match[2],+ capability: match[3],+ ghostId: match[4],+ route: match[5],+ },+ };+}diff --git a/apps/desktop/src/renderer/cindy-brain/installErrorKey.ts b/apps/desktop/src/renderer/cindy-brain/installErrorKey.tsindex 9d079f58fc..e8cc60bae8 100644--- a/apps/desktop/src/renderer/cindy-brain/installErrorKey.ts+++ b/apps/desktop/src/renderer/cindy-brain/installErrorKey.ts@@ -7,6 +7,8 @@ export function ghostInstallErrorKey(code: string | undefined): string {switch (code) {case 'GHOST_FILE_INVALID':return 'settings.ghosts.errors.fileInvalid';+ case 'GHOST_HOST_UNSUPPORTED':+ return 'settings.ghosts.errors.hostUnsupported';case 'ALREADY_EXISTS':return 'settings.ghosts.errors.alreadyInstalled';case 'GHOST_COMMAND_CONFLICT':diff --git a/apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx b/apps/desktop/src/renderer/components/chat/GhostSummonCard.tsxindex 138e771047..4a7d50cb10 100644--- a/apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx+++ b/apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx@@ -42,6 +42,10 @@ import {type GhostDirectiveDisplay,type GhostDirectiveSegment,} from '@/cindy-brain/ghostCommand';+import {+ hostCapabilityDirectiveSegments,+ type HostCapabilityDirectiveDisplay,+} from '@/cindy-brain/hostCapabilityInvocation';import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';/**@@ -61,8 +65,7 @@ export const GhostFulfillmentContext = createContext<ReadonlyMap<string, Readonl* 它不是"追加文本的解析结果",只是渲染层的展示形态。*/export type GhostSummonDisplay =- | GhostDirectiveDisplay- | { kind: 'semantic'; ghostIds: string[] };+ GhostDirectiveDisplay | HostCapabilityDirectiveDisplay | { kind: 'semantic'; ghostIds: string[] };/** 展开区正文:按来源双色渲染分段(injected = 意识注入值,高亮)。 */function DirectiveSegments({@@ -272,16 +275,17 @@ export function GhostSummonCard({: [];if (directive.kind === 'mention' && fulfilled.length === 0) {- const soloIcon = directive.ghosts.length === 1 ? iconByGhostId(directive.ghosts[0].ghostId) : null;- const names = directive.ghosts- .map((g) => g.name)- .join(t('chat.ghostSummon.listSeparator'));+ const soloIcon =+ directive.ghosts.length === 1 ? iconByGhostId(directive.ghosts[0].ghostId) : null;+ const names = directive.ghosts.map((g) => g.name).join(t('chat.ghostSummon.listSeparator'));return (<div className="flex max-w-full flex-col items-end gap-1.5"><buttontype="button"aria-expanded={expanded}- title={t(expanded ? 'chat.ghostSummon.collapseAria' : 'chat.ghostSummon.mentionExpandAria')}+ title={t(+ expanded ? 'chat.ghostSummon.collapseAria' : 'chat.ghostSummon.mentionExpandAria',+ )}onClick={() => setExpanded((v) => !v)}className={cn('inline-flex max-w-full cursor-pointer items-center gap-1.5',@@ -310,10 +314,7 @@ export function GhostSummonCard({className="max-w-full rounded-[12px] border px-3 py-2"style={{ borderColor: 'var(--border-default)' }}>- <div- className="mb-1.5 text-xs leading-[1.5]"- style={{ color: 'var(--text-tertiary)' }}- >+ <div className="mb-1.5 text-xs leading-[1.5]" style={{ color: 'var(--text-tertiary)' }}>{t('chat.ghostSummon.legend')}</div><DirectiveSegments@@ -327,23 +328,26 @@ export function GhostSummonCard({);}- // ── 标注行形态:硬指令 / 软提示被兑现 / 语义自主召唤(三者完全同形态)──+ // ── 标注行形态:普通插件调用与 Host capability 共用外观,路由语义分开──const isCommand = directive.kind === 'command';+ const isHostCapability = directive.kind === 'host-capability';// 标注承载的意识:硬指令固定一个;兑现态取被真实召唤的子集;semantic 只有// ghostId,名字/指令词从已装清单实时解析(已卸下回退 ghostId)。// 多意识时名字并列、法阵取第一个。const cardGhosts: Array<{ name: string; ghostId: string; command?: string }> = isCommand? [{ name: directive.name, ghostId: directive.ghostId, command: directive.command }]- : directive.kind === 'mention'- ? fulfilled- : directive.ghostIds.map((id) => {- const g = installedGhosts.find((x) => x.manifest.id === id);- return {- name: g?.manifest.name ?? id,- ghostId: id,- ...(g?.manifest.command ? { command: g.manifest.command } : {}),- };- });+ : isHostCapability+ ? [{ name: directive.name, ghostId: directive.ghostId }]+ : directive.kind === 'mention'+ ? fulfilled+ : directive.ghostIds.map((id) => {+ const g = installedGhosts.find((x) => x.manifest.id === id);+ return {+ name: g?.manifest.name ?? id,+ ghostId: id,+ ...(g?.manifest.command ? { command: g.manifest.command } : {}),+ };+ });// 兜底:空清单不渲(semantic 由 UserMessage 保证非空,此处防御性短路)。if (cardGhosts.length === 0) return null;// 命中已装意识时取实时安装态(头像/版本号);已卸下则都不显示,@@ -363,18 +367,26 @@ export function GhostSummonCard({// 展开区改为如实说明(segments = null)。const segments = isCommand? commandDirectiveSegments(directive)- : directive.kind === 'mention'- ? mentionDirectiveSegments(directive.ghosts)- : null;+ : isHostCapability+ ? hostCapabilityDirectiveSegments(directive)+ : directive.kind === 'mention'+ ? mentionDirectiveSegments(directive.ghosts)+ : null;// 状态文字对齐兑现事实:mention 兑现态/semantic 由构造保证真调过;硬指令// 查兑现关联,AI 最终没调的只说「已完成」,不替 AI 撒谎。- const anyFulfilled =- !isCommand || cardGhosts.some((g) => Boolean(fulfilledIds?.has(g.ghostId)));- const statusText = running- ? t('chat.ghostSummon.status.running')- : anyFulfilled- ? t('chat.ghostSummon.status.called')- : t('chat.ghostSummon.status.done');+ const anyFulfilled = isHostCapability+ ? false+ : !isCommand || cardGhosts.some((g) => Boolean(fulfilledIds?.has(g.ghostId)));+ // Host capability selection is not a ghost_call fulfillment event. Until+ // Host MCP fulfillment is tracked separately, report only the fact we know:+ // the user selected this route. Do not show a success tick or "已调用".+ const statusText = isHostCapability+ ? t('chat.ghostSummon.status.selected')+ : running+ ? t('chat.ghostSummon.status.running')+ : anyFulfilled+ ? t('chat.ghostSummon.status.called')+ : t('chat.ghostSummon.status.done');return (<div className={cn('max-w-full', className)}>@@ -386,9 +398,11 @@ export function GhostSummonCard({? 'chat.ghostSummon.collapseAria': isCommand? 'chat.ghostSummon.expandAria'- : directive.kind === 'mention'- ? 'chat.ghostSummon.mentionExpandAria'- : 'chat.ghostSummon.semanticExpandAria',+ : isHostCapability+ ? 'chat.ghostSummon.hostCapabilityExpandAria'+ : directive.kind === 'mention'+ ? 'chat.ghostSummon.mentionExpandAria'+ : 'chat.ghostSummon.semanticExpandAria',)}onClick={() => setExpanded((v) => !v)}className={cn(@@ -399,7 +413,7 @@ export function GhostSummonCard({><SummonSealiconDataUrl={installedGhost?.iconDataUrl ?? null}- running={running}+ running={isHostCapability ? false : running}fulfilled={anyFulfilled}/><span@@ -444,21 +458,24 @@ export function GhostSummonCard({)}{segments ? (<>- <div- className="mb-1 text-xs font-medium"- style={{ color: 'var(--text-tertiary)' }}- >+ <div className="mb-1 text-xs font-medium" style={{ color: 'var(--text-tertiary)' }}>{t(isCommand? 'chat.ghostSummon.directiveLabel'- : 'chat.ghostSummon.mentionDirectiveLabel',+ : isHostCapability+ ? 'chat.ghostSummon.hostCapabilityDirectiveLabel'+ : 'chat.ghostSummon.mentionDirectiveLabel',)}</div><divclassName="mb-1.5 text-xs leading-[1.5]"style={{ color: 'var(--text-tertiary)' }}>- {t('chat.ghostSummon.legend')}+ {t(+ isHostCapability+ ? 'chat.ghostSummon.hostCapabilityLegend'+ : 'chat.ghostSummon.legend',+ )}</div><DirectiveSegmentssegments={segments}@@ -468,10 +485,7 @@ export function GhostSummonCard({</>) : (/* semantic:没有追加段,如实说明来由(不伪造"指令原文")。 */- <div- className="text-xs leading-[1.5]"- style={{ color: 'var(--text-tertiary)' }}- >+ <div className="text-xs leading-[1.5]" style={{ color: 'var(--text-tertiary)' }}>{t('chat.ghostSummon.semanticNote')}</div>)}diff --git a/apps/desktop/src/renderer/components/chat/UserMessage.tsx b/apps/desktop/src/renderer/components/chat/UserMessage.tsxindex f475fca81c..28c0496967 100644--- a/apps/desktop/src/renderer/components/chat/UserMessage.tsx+++ b/apps/desktop/src/renderer/components/chat/UserMessage.tsx@@ -98,6 +98,7 @@ import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOrimport { insertSessionLinkIntoComposer } from '@/lib/composerActionsBus';import { MENTION_TOKEN_SPLIT, parseMentionToken } from '@/lib/mentionRefFormat';import { parseGhostCommandWord, splitGhostDirective } from '@/cindy-brain/ghostCommand';+import { splitHostCapabilityDirective } from '@/cindy-brain/hostCapabilityInvocation';import {GhostFulfillmentContext,GhostSummonCard,@@ -107,10 +108,7 @@ import { AutomationOriginBadge } from './AutomationOriginBadge';import { UserMessageUrlLink } from './UserMessageUrlLink';import { InlineReferenceChip } from './InlineReferenceChip';import { QuoteChip } from './QuoteChip';-import {- SentAgentReferenceChip,- sentAgentReferenceDisplayLabel,-} from './SentAgentReferenceChip';+import { SentAgentReferenceChip, sentAgentReferenceDisplayLabel } from './SentAgentReferenceChip';import { parseOrcaCommunicationContent, resolveUserDisplayText } from './userMessageDisplayText';/**@@ -548,14 +546,32 @@ function renderContentWithoutPastedText(// A real mention is always preceded by whitespace or sits at line start.const prev = parts[pi - 1];if (prev && prev.length > 0 && !/\s$/.test(prev)) {- nodes.push(...renderTextWithLinks(part, `${li}-${pi}`, onImageClick, sessionId, sessionReferences, interactive));+ nodes.push(+ ...renderTextWithLinks(+ part,+ `${li}-${pi}`,+ onImageClick,+ sessionId,+ sessionReferences,+ interactive,+ ),+ );continue;}// Only render as chip if it looks like a real pathif (!looksLikePath(ref)) {// Not a path — render as plain text- nodes.push(...renderTextWithLinks(part, `${li}-${pi}`, onImageClick, sessionId, sessionReferences, interactive));+ nodes.push(+ ...renderTextWithLinks(+ part,+ `${li}-${pi}`,+ onImageClick,+ sessionId,+ sessionReferences,+ interactive,+ ),+ );continue;}@@ -616,7 +632,9 @@ function renderContentWithoutPastedText(const result = await resolveLocalPathSmart(ref, workingDir);if (result.status === 'multiple') {toast.error(- t('chat.markdownRenderer.duplicateFiles', { count: result.candidates.length }),+ t('chat.markdownRenderer.duplicateFiles', {+ count: result.candidates.length,+ }),);return;}@@ -638,7 +656,16 @@ function renderContentWithoutPastedText();}} else {- nodes.push(...renderTextWithLinks(part, `${li}-${pi}`, onImageClick, sessionId, sessionReferences, interactive));+ nodes.push(+ ...renderTextWithLinks(+ part,+ `${li}-${pi}`,+ onImageClick,+ sessionId,+ sessionReferences,+ interactive,+ ),+ );}}}@@ -850,8 +877,7 @@ export function renderContent(// 也无法选中复制,不能当作查看全文的唯一出口(issue #946)。{...(interactive && onPastedTextChipClick? {- onClick: (event) =>- onPastedTextChipClick(token.text, event.currentTarget),+ onClick: (event) => onPastedTextChipClick(token.text, event.currentTarget),}: {})}/>@@ -917,7 +943,8 @@ export function UserMessage({// Capability gate: 没传 agentKind (调用方未升级) → 默认两者都允许 (兼容旧路径)// 传了 agentKind → 按 capabilities.fork/rewind.supported 决定 icon 显示// renderer 'cc' ↔ maker 'claude-code' 别名映射 (DB / Session 用 'cc', maker IPC 用 'claude-code')- const makerKind: MakerAgentKind = agentKind === 'codex' || agentKind === 'pi' ? agentKind : 'claude-code';+ const makerKind: MakerAgentKind =+ agentKind === 'codex' || agentKind === 'pi' ? agentKind : 'claude-code';// device-link 远程会话:fork/rewind 能力按被控端读(本机会话 deviceId undefined,行为不变)。// 媒体来源(device/ssh)用于把附件/文件预览 URL 改写到 cindy-remote-media://(入方向媒体)。// 取自 ChatSessionFileContext(MessageStream 顶层订阅式构造,deviceId 迟到注册时@@ -981,7 +1008,10 @@ export function UserMessage({// 对不上模板按普通文本原样显示)。copy / fork / rewind / 编辑预填全部用// 剥离后的正文——这些路径重发都走发送期再展开,带着旧指令会叠加双份。// orca / hook 消息不经意识展开,跳过解析。- const ghostSplit = orcaCommunication || hookSource ? null : splitGhostDirective(displayContent);+ const ghostSplit =+ orcaCommunication || hookSource+ ? null+ : (splitGhostDirective(displayContent) ?? splitHostCapabilityDirective(displayContent));const ghostDirective = ghostSplit?.directive ?? null;const ghostBody = ghostSplit?.body ?? displayContent;// quotesEncoded 消息按正文顺序解析全部引用块,支持引用与回复交错。@@ -1084,11 +1114,7 @@ export function UserMessage({const collapseMeasureBody = useMemo(() =>bubbleBody === ghostBody- ? projectSentInlinePlainText(- displayBubbleBody,- bubblePastedRanges,- bubbleAgentReferences,- )+ ? projectSentInlinePlainText(displayBubbleBody, bubblePastedRanges, bubbleAgentReferences): displayBubbleBody,[bubbleAgentReferences, bubbleBody, bubblePastedRanges, displayBubbleBody, ghostBody],);@@ -1507,7 +1533,8 @@ export function UserMessage({<divclassName={cn('min-w-0 whitespace-pre-wrap [overflow-wrap:anywhere]',- longMessageCollapsed && (automationOrigin ? 'line-clamp-3' : 'line-clamp-10'),+ longMessageCollapsed &&+ (automationOrigin ? 'line-clamp-3' : 'line-clamp-10'),)}>{quoteSegments.map((segment, index) =>@@ -1584,7 +1611,8 @@ export function UserMessage({<divclassName={cn('whitespace-pre-wrap [overflow-wrap:anywhere]',- longMessageCollapsed && (automationOrigin ? 'line-clamp-3' : 'line-clamp-10'),+ longMessageCollapsed &&+ (automationOrigin ? 'line-clamp-3' : 'line-clamp-10'),)}>{longMessageCollapseddiff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex dd7cba7b22..4da407b6d2 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -113,7 +113,6 @@ import {} from './effortChangeQueue';import { captureComposerSendSnapshot, isComposerSendSnapshotCurrent } from './composerSendSnapshot';import { useRemoteSessionConnection } from '@/features/cc-agent/hooks/useRemoteSessionConnection';-import {confirmAgentSwitchRisk,isAgentSwitchResponseFresh,@@ -137,7 +136,12 @@ import {import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';import { PermissionSelector } from './PermissionSelector';import { ExtraDirsButton, type CollaborationMenuConfig } from './ExtraDirsButton';-import { focusComposerEndNextFrame, placeGhostAtComposerStart } from './ghostComposerPlacement';+import {+ focusComposerEndNextFrame,+ hostCapabilityForGhost,+ placeGhostAtComposerStart,+ placeHostCapabilityAtComposerStart,+} from './ghostComposerPlacement';import { NewGoalDialog } from './NewGoalDialog';import { PlanModeIndicator } from './PlanModeIndicator';import { PendingQueuePanel } from './PendingQueuePanel';@@ -149,6 +153,7 @@ import {findGhostByCommand,parseGhostCommandWord,} from '@/cindy-brain/ghostCommand';+import { expandHostCapabilityInvocation } from '@/cindy-brain/hostCapabilityInvocation';import { filterGhostsForWorkdir } from '@/cindy-brain/ghostWorkdirFilter';import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';import {@@ -2196,6 +2201,11 @@ export function ChatInput({attachments: existing?.attachments ?? [],quotes: existing?.quotes ?? [],browserComments: existing?.browserComments ?? [],+ ...(existing?.pendingGhostId ? { pendingGhostId: existing.pendingGhostId } : {}),+ ...(existing?.pendingHostCapabilityGhostId+ ? { pendingHostCapabilityGhostId: existing.pendingHostCapabilityGhostId }+ : {}),+ ...(existing?.focusAtEnd ? { focusAtEnd: true } : {}),},{ silent: true },);@@ -2385,33 +2395,26 @@ export function ChatInput({);const pluginAvailableIds = useMemo(() =>- new Set(- ghostsForCommand- .filter((ghost) => ghost.enabled && ghost.manifest.command)- .map((ghost) => ghost.manifest.id),- ),+ new Set(ghostsForCommand.filter((ghost) => ghost.enabled).map((ghost) => ghost.manifest.id)),[ghostsForCommand],);- const atPluginItems = useMemo<AtResourceItem[]>(- () => {- // device-link 远程会话的插件运行在被控端;控制端清单既不代表远端- // 已安装状态,选择后也无法用本地 InstalledGhost 解析并插入命令。- if (deviceLinkDeviceId) return [];- return pluginsForMenu- .filter((ghost) => pluginAvailableIds.has(ghost.manifest.id) && ghost.manifest.command)- .map((ghost) => ({- type: 'plugin-command',- name: ghost.manifest.name,- relPath: ghost.manifest.command!,- pluginId: ghost.manifest.id,- ...(ghost.iconDataUrl ? { iconDataUrl: ghost.iconDataUrl } : {}),- sourceLabel: ghost.manifest.command!,- _nameLower: `${ghost.manifest.name} ${ghost.manifest.command}`.toLowerCase(),- _relPathLower: `${ghost.manifest.command} ${ghost.manifest.id}`.toLowerCase(),- }));- },- [deviceLinkDeviceId, pluginsForMenu, pluginAvailableIds],- );+ const atPluginItems = useMemo<AtResourceItem[]>(() => {+ // device-link 远程会话的插件运行在被控端;控制端清单既不代表远端+ // 已安装状态,选择后也无法用本地 InstalledGhost 解析并插入命令。+ if (deviceLinkDeviceId) return [];+ return pluginsForMenu+ .filter((ghost) => pluginAvailableIds.has(ghost.manifest.id) && ghost.manifest.command)+ .map((ghost) => ({+ type: 'plugin-command',+ name: ghost.manifest.name,+ relPath: ghost.manifest.command!,+ pluginId: ghost.manifest.id,+ ...(ghost.iconDataUrl ? { iconDataUrl: ghost.iconDataUrl } : {}),+ sourceLabel: ghost.manifest.command!,+ _nameLower: `${ghost.manifest.name} ${ghost.manifest.command}`.toLowerCase(),+ _relPathLower: `${ghost.manifest.command} ${ghost.manifest.id}`.toLowerCase(),+ }));+ }, [deviceLinkDeviceId, pluginsForMenu, pluginAvailableIds]);useEffect(() => {setGhostCommandRoster(editor, ghostsForCommand);}, [editor, ghostsForCommand]);@@ -2422,6 +2425,15 @@ export function ChatInput({},[editor, installedGhosts],);+ const handlePluginCapabilitySelect = useCallback(+ (ghost: (typeof pluginsForMenu)[number]) => {+ if (remoteHostId || deviceLinkDeviceId || !ghost.manifest.slots.includes('ios-simulator'))+ return;+ if (!editor || editor.isDestroyed) return;+ placeHostCapabilityAtComposerStart(editor, ghost, installedGhosts);+ },+ [deviceLinkDeviceId, editor, installedGhosts, remoteHostId],+ );const handleVoiceInputPermissionRequired = useCallback(async () => {const confirmed = await confirmDialog({@@ -2903,6 +2915,11 @@ export function ChatInput({attachments: existing?.attachments ?? [],quotes: existing?.quotes ?? [],browserComments: existing?.browserComments ?? [],+ ...(existing?.pendingGhostId ? { pendingGhostId: existing.pendingGhostId } : {}),+ ...(existing?.pendingHostCapabilityGhostId+ ? { pendingHostCapabilityGhostId: existing.pendingHostCapabilityGhostId }+ : {}),+ ...(existing?.focusAtEnd ? { focusAtEnd: true } : {}),},{ silent: true },);@@ -3114,9 +3131,9 @@ export function ChatInput({}, [editor, storageKey]);// Plugin page routed entry: wait until the editor has hydrated its existing- // draft, then reuse the exact same insertion/focus path as the in-composer- // `$` / `+` selectors. This preserves body text and replaces an existing- // Plugin command instead of treating the command as prefilled plain text.+ // draft, then reuse the same placement path as the in-composer selectors.+ // Command and Host-capability Plugins intentionally use separate handoff+ // fields because only commands expand through `ghost_call`.useEffect(() => {if (!editor || !storageKey || !hasHydratedRef.current) return;const draft = getComposerDraft(storageKey);@@ -3140,6 +3157,23 @@ export function ChatInput({return;}+ if (draft.pendingHostCapabilityGhostId) {+ const ghost = ghostsForCommand.find(+ (candidate) => candidate.manifest.id === draft.pendingHostCapabilityGhostId,+ );+ saveComposerDraft(+ storageKey,+ {+ ...draft,+ pendingHostCapabilityGhostId: undefined,+ focusAtEnd: false,+ },+ { silent: true },+ );+ if (ghost) placeHostCapabilityAtComposerStart(editor, ghost, installedGhosts);+ return;+ }+if (!draft.focusAtEnd) return;saveComposerDraft(storageKey,@@ -3185,6 +3219,11 @@ export function ChatInput({attachments: existing?.attachments ?? [],quotes: existing?.quotes ?? [],browserComments: next,+ ...(existing?.pendingGhostId ? { pendingGhostId: existing.pendingGhostId } : {}),+ ...(existing?.pendingHostCapabilityGhostId+ ? { pendingHostCapabilityGhostId: existing.pendingHostCapabilityGhostId }+ : {}),+ ...(existing?.focusAtEnd ? { focusAtEnd: true } : {}),},{ silent: true },);@@ -3278,9 +3317,7 @@ export function ChatInput({);// ── Slash / At panel state ─────────────────────────────────────────- const trigger: TriggerState = editor- ? detectTrigger(editor)- : { kind: 'none' };+ const trigger: TriggerState = editor ? detectTrigger(editor) : { kind: 'none' };// Slash commands — palette refactor 后改成 loadAllCommands 一次性拉三源(desktop +// agent-builtin + agent-skill); 内部并发, mergeCommands 按优先级合并去重。@@ -3408,9 +3445,10 @@ export function ChatInput({if (atScanSeqRef.current !== seq || !partial.success) return;setAtState((prev) => ({kind: 'ready',- items: preservePreviousItems && prev.kind === 'ready'- ? mergeAtResourceItems(prev.items, [...atPluginItems, ...partial.items])- : [...atPluginItems, ...partial.items],+ items:+ preservePreviousItems && prev.kind === 'ready'+ ? mergeAtResourceItems(prev.items, [...atPluginItems, ...partial.items])+ : [...atPluginItems, ...partial.items],truncated: partial.truncated || (prev.kind === 'ready' && prev.truncated),searching: true,}));@@ -3439,7 +3477,15 @@ export function ChatInput({setAtState({ kind: 'error', message: m });});},- [workingDir, paletteAgentKind, isRemoteSession, sessionId, deviceLinkDeviceId, t, atPluginItems],+ [+ workingDir,+ paletteAgentKind,+ isRemoteSession,+ sessionId,+ deviceLinkDeviceId,+ t,+ atPluginItems,+ ],);const atQuery = trigger.kind === 'at' ? trigger.query : '';@@ -3455,9 +3501,10 @@ export function ChatInput({const filteredAt = useMemo(() => {if (!atQuery && trigger.kind !== 'at') return [];if (atState.kind !== 'ready') return [];- const items = workingDir && localAttachmentPickerEnabled- ? [AT_FILE_PICKER_RESOURCE, ...atState.items]- : atState.items;+ const items =+ workingDir && localAttachmentPickerEnabled+ ? [AT_FILE_PICKER_RESOURCE, ...atState.items]+ : atState.items;return filterAtResources(items, atQuery);}, [atState, atQuery, trigger.kind, workingDir, localAttachmentPickerEnabled]);@@ -3482,13 +3529,14 @@ export function ChatInput({if (normalizedQuery === atLastScanQueryRef.current) return;atLastScanQueryRef.current = normalizedQuery;const seq = ++atScanSeqRef.current;- setAtState((prev) => prev.kind === 'ready'- ? { ...prev, searching: true }- : prev);- atQueryScanTimerRef.current = window.setTimeout(() => {- atQueryScanTimerRef.current = null;- runAtScan(normalizedQuery, seq);- }, normalizedQuery ? 200 : 0);+ setAtState((prev) => (prev.kind === 'ready' ? { ...prev, searching: true } : prev));+ atQueryScanTimerRef.current = window.setTimeout(+ () => {+ atQueryScanTimerRef.current = null;+ runAtScan(normalizedQuery, seq);+ },+ normalizedQuery ? 200 : 0,+ );return () => {if (atQueryScanTimerRef.current !== null) {window.clearTimeout(atQueryScanTimerRef.current);@@ -3521,8 +3569,7 @@ export function ChatInput({}, [trigger, suppressedSlashAt, suppressedAtAt]);const slashOpen = trigger.kind === 'slash' && suppressedSlashAt !== trigger.from;- const atOpen =- trigger.kind === 'at' && !isRemoteSession && suppressedAtAt !== trigger.from;+ const atOpen = trigger.kind === 'at' && !isRemoteSession && suppressedAtAt !== trigger.from;useEffect(() => {if (!slashOpen) return;@@ -3683,13 +3730,16 @@ export function ChatInput({workingDir ? { defaultPath: workingDir } : undefined,);if (!picked.success || !picked.path || !picked.kind) return;- if (!isAtResourceInsertTargetCurrent(- editor,- editorRef.current,- originDoc,- originStorageKey,- currentStorageKeyRef.current,- )) return;+ if (+ !isAtResourceInsertTargetCurrent(+ editor,+ editorRef.current,+ originDoc,+ originStorageKey,+ currentStorageKeyRef.current,+ )+ )+ return;const nativeResource = createAtResourceFromNativePath(picked.path,picked.kind,@@ -3841,20 +3891,58 @@ export function ChatInput({}serializedContent = serializeEditorContent(editor);}- let {- text: editorText,+ const {+ text: serializedEditorText,mentions,hasQuotes,- agentReferences,+ agentReferences: serializedAgentReferences,pastedTextRanges,slashCommandRanges,+ hostCapability: serializedHostCapability,} = serializedContent;+ let editorText = serializedEditorText;+ let agentReferences = serializedAgentReferences;const attachmentsForSend = optimisticallyClearRemoteComposer? attachmentsBeforeOptimisticClear: [...latestAttachmentsRef.current];const commentsForSend = optimisticallyClearRemoteComposer? commentsBeforeOptimisticClear: [...browserCommentsRef.current];+ // Resolve the structured capability atom against the current enabled,+ // workdir-scoped Plugin roster. Draft data is presentation state only;+ // it cannot grant a Host route after the Plugin is disabled/uninstalled.+ const eligibleGhosts = filterGhostsForWorkdir(+ installedGhostsRef.current,+ workingDirRef.current,+ );+ const hostCapabilityGhost = serializedHostCapability+ ? (eligibleGhosts.find(+ (candidate) =>+ candidate.manifest.id === serializedHostCapability.ghostId &&+ hostCapabilityForGhost(candidate) === serializedHostCapability.capability,+ ) ?? null)+ : null;+ if (serializedHostCapability && !hostCapabilityGhost) {+ toast.warning(t('newChat.pluginSetup.error.TARGET_UNAVAILABLE'));+ return;+ }+ const hostCapability =+ serializedHostCapability && hostCapabilityGhost+ ? {+ capability: serializedHostCapability.capability,+ ghostId: hostCapabilityGhost.manifest.id,+ name: hostCapabilityGhost.manifest.name,+ }+ : null;+ // A capability chip is metadata, not an automatic visible prefix. Use+ // the localized default only when the user sent the chip by itself;+ // otherwise preserve their body byte-for-byte and avoid duplication.+ if (hostCapability && !editorText.trim()) {+ editorText =+ hostCapability.capability === 'ios-simulator'+ ? t('rightSidebar.iosSimulator.startPrompt')+ : hostCapability.name;+ }// composerQuote 在其正文位置序列化成 markdown blockquote,支持引用与回复交错。// browser-comment-chip:页面评论序列化为 `# Browser comments:` 段拼在正文后// (截图在下方并入 filesToSend,与文本块里的 "attached as a labeled image"@@ -3943,15 +4031,19 @@ export function ChatInput({// 追加"必须走 cindy 总机"的机器指令;未命中原样发送。// 读取 useInstalledGhosts 的最新窗口级快照。ghosts:changed 会原子更新// 该快照;发送路径无需同步 IPC,仍按当前工作目录执行同一禁用判定。- const eligibleGhosts = filterGhostsForWorkdir(- installedGhostsRef.current,- workingDirRef.current,- );const ghostCommandWord = parseGhostCommandWord(text);- const usedGhost = ghostCommandWord- ? findGhostByCommand(eligibleGhosts, ghostCommandWord)- : null;- const textToSend = expandGhostCommand(text, eligibleGhosts);+ const usedGhost = hostCapabilityGhost+ ? hostCapabilityGhost+ : ghostCommandWord+ ? findGhostByCommand(eligibleGhosts, ghostCommandWord)+ : null;+ const textToSend = hostCapability+ ? expandHostCapabilityInvocation(+ text,+ hostCapability,+ t('rightSidebar.iosSimulator.startPrompt'),+ )+ : expandGhostCommand(text, eligibleGhosts);const sendSnapshot = captureComposerSendSnapshot(editor.getJSON(),latestAttachmentsRef.current,@@ -4083,6 +4175,11 @@ export function ChatInput({attachments: [...next.attachments],quotes: existing?.quotes ?? [],browserComments: [...next.browserComments],+ ...(existing?.pendingGhostId ? { pendingGhostId: existing.pendingGhostId } : {}),+ ...(existing?.pendingHostCapabilityGhostId+ ? { pendingHostCapabilityGhostId: existing.pendingHostCapabilityGhostId }+ : {}),+ ...(existing?.focusAtEnd ? { focusAtEnd: true } : {}),},{ silent: true, preserveRemoteOptimisticRecovery: true },);@@ -4996,10 +5093,7 @@ export function ChatInput({// model-only 不改变当前生效来源;effort 能力也必须按该来源精确解析,避免同 id 的// 内置模型档位穿进 BYOM。恢复优先级:模型预设 > 旧 per-model 记忆 > 沿用当前 > 模型默认。- const { efforts, defaultEffort } = resolveModelEfforts(- newModelId,- effectiveSourceId,- );+ const { efforts, defaultEffort } = resolveModelEfforts(newModelId, effectiveSourceId);const providerEffort =modelMemory && currentModelAgentKind && effectiveSourceId? modelMemory.getEffort(currentModelAgentKind, effectiveSourceId, newModelId)@@ -6262,6 +6356,9 @@ export function ChatInput({plugins={pluginsForMenu}pluginAvailableIds={pluginAvailableIds}onPluginSelect={handlePluginSelect}+ onPluginCapabilitySelect={+ !remoteHostId && !deviceLinkDeviceId ? handlePluginCapabilitySelect : undefined+ }onChange={onExtraDirsChange}onNewGoal={inSessionGoalEnabled || onNewGoaldiff --git a/apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx b/apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsxindex 8878c2df17..a6327dfce4 100644--- a/apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx@@ -5,7 +5,7 @@* - 添加文件、图片或视频→ 复用 composer 既有附件管线。* - 新建目标(`onNewGoal` 提供时显示;仅会话中,父组件按 sessionId 决定)→ 打开 NewGoalDialog。* - 计划模式 / 协同模式→ 与新建目标同级的模式入口。- * - 已安装 Plugin:选择后由 ChatInput 把 command 放到消息开头,保留正文并聚焦末尾。+ * - 已安装 Plugin:command 插件写入正文;Host capability 插件写入能力 Chip。* - 附加只读引用目录(Claude vendor;`onChange` 提供时显示)→ 列表 / 添加。** 创建时和 session 中途共用同一组件:父组件传 onChange 决定目录持久化路径:@@ -80,12 +80,14 @@ export interface ExtraDirsButtonProps {planMode?: { enabled: boolean; onToggle: (next: boolean) => void };/** 协同模式入口;与新建目标、计划模式同级显示在「+」菜单。 */collaboration?: CollaborationMenuConfig;- /** 已安装 Plugin 清单;无指令或未生效项仍展示,但不可选。 */+ /** 已安装 Plugin 清单;无指令、无 Host 入口或未生效项仍展示,但不可选。 */plugins?: readonly InstalledGhost[];- /** 当前会话范围内可直接使用的 Plugin id;未命中项保留展示但置灰。 */+ /** 当前会话范围内已启用的 Plugin id;未命中项保留展示但置灰。 */pluginAvailableIds?: ReadonlySet<string>;/** 选择后由 ChatInput 把 Plugin command 放到正文开头并把光标落到全文末尾。 */onPluginSelect?: (ghost: InstalledGhost) => void;+ /** 选择 Host capability 插件后交给 ChatInput 写入能力 Chip。 */+ onPluginCapabilitySelect?: (ghost: InstalledGhost) => void;disabled?: boolean;/** 窄容器下把 trigger 字号/图标各压一档,默认 false。 */dense?: boolean;@@ -152,6 +154,7 @@ export function ExtraDirsButton({plugins = [],pluginAvailableIds,onPluginSelect,+ onPluginCapabilitySelect,disabled,dense = false,visualVariant = 'default',@@ -277,7 +280,9 @@ export function ExtraDirsButton({/>)}<Tip- text={count === 0 ? t('extraDirs.tooltipEmpty') : t('extraDirs.tooltipCount', { count })}+ text={+ count === 0 ? t('extraDirs.tooltipEmpty') : t('extraDirs.tooltipCount', { count })+ }side="top"><button@@ -303,10 +308,7 @@ export function ExtraDirsButton({)}aria-label={t('extraDirs.menuAria')}>- <Plus- size={isCreateAgentVariant ? 11 : dense ? 14 : 14}- className="shrink-0"- />+ <Plus size={isCreateAgentVariant ? 11 : dense ? 14 : 14} className="shrink-0" />{count > 0 && hasReferenceDirs && (<spanclassName={cn(@@ -348,233 +350,239 @@ export function ExtraDirsButton({</>)}- {/* 新建目标(仅会话中;点击关菜单并由父组件打开 NewGoalDialog) */}- {onNewGoal && (- <button- type="button"- onClick={() => {- setOpen(false);- onNewGoal();- }}- className={cn(- 'flex w-full items-center gap-2 rounded-[8px] px-3 py-2',- 'transition-colors hover:bg-[var(--model-item-hover)]',- )}- >- <Target size={14} className="shrink-0 text-[var(--model-item-text)]" />- <span className="text-[13px] text-[var(--model-item-text)]">- {t('goal.newGoalMenuItem')}- </span>- </button>- )}+ {/* 新建目标(仅会话中;点击关菜单并由父组件打开 NewGoalDialog) */}+ {onNewGoal && (+ <button+ type="button"+ onClick={() => {+ setOpen(false);+ onNewGoal();+ }}+ className={cn(+ 'flex w-full items-center gap-2 rounded-[8px] px-3 py-2',+ 'transition-colors hover:bg-[var(--model-item-hover)]',+ )}+ >+ <Target size={14} className="shrink-0 text-[var(--model-item-text)]" />+ <span className="text-[13px] text-[var(--model-item-text)]">+ {t('goal.newGoalMenuItem')}+ </span>+ </button>+ )}- {/* 计划模式 toggle(与「新建目标」同级):勾选态右侧打勾;点击切换并关菜单。 */}- {planMode && (- <button- type="button"- role="menuitemcheckbox"- aria-checked={planMode.enabled}- onClick={() => {- setOpen(false);- planMode.onToggle(!planMode.enabled);- }}- className={cn(- 'flex w-full items-center gap-2 rounded-[8px] px-3 py-2',- 'transition-colors hover:bg-[var(--model-item-hover)]',- )}- >- <ClipboardList size={14} className="shrink-0 text-[var(--model-item-text)]" />- <span className="min-w-0 flex-1 truncate text-left text-[13px] text-[var(--model-item-text)]">- {t('planMode.menuItem')}- </span>- {planMode.enabled && (- <Check size={13} className="shrink-0 text-[var(--model-item-check)]" />- )}- </button>- )}+ {/* 计划模式 toggle(与「新建目标」同级):勾选态右侧打勾;点击切换并关菜单。 */}+ {planMode && (+ <button+ type="button"+ role="menuitemcheckbox"+ aria-checked={planMode.enabled}+ onClick={() => {+ setOpen(false);+ planMode.onToggle(!planMode.enabled);+ }}+ className={cn(+ 'flex w-full items-center gap-2 rounded-[8px] px-3 py-2',+ 'transition-colors hover:bg-[var(--model-item-hover)]',+ )}+ >+ <ClipboardList size={14} className="shrink-0 text-[var(--model-item-text)]" />+ <span className="min-w-0 flex-1 truncate text-left text-[13px] text-[var(--model-item-text)]">+ {t('planMode.menuItem')}+ </span>+ {planMode.enabled && (+ <Check size={13} className="shrink-0 text-[var(--model-item-check)]" />+ )}+ </button>+ )}- {/* 协同模式与目标/计划同级。开启态保留 Thinking Orange,右侧对勾表示当前状态。 */}- {collaboration && (- <Tip- text={collaborationPolicyDisabled ? collaboration.disabledReason : null}- side="right"- >- <span className="block">- <button- type="button"- role="menuitemcheckbox"- aria-checked={collaboration.enabled}- aria-label={collaborationAriaLabel}- aria-disabled={- collaborationPolicyDisabled && !collaborationRetryable ? true : undefined- }- disabled={disabled || (collaborationPolicyDisabled && !collaborationRetryable)}- onClick={handleCollaborationActivate}+ {/* 协同模式与目标/计划同级。开启态保留 Thinking Orange,右侧对勾表示当前状态。 */}+ {collaboration && (+ <Tip text={collaborationPolicyDisabled ? collaboration.disabledReason : null} side="right">+ <span className="block">+ <button+ type="button"+ role="menuitemcheckbox"+ aria-checked={collaboration.enabled}+ aria-label={collaborationAriaLabel}+ aria-disabled={+ collaborationPolicyDisabled && !collaborationRetryable ? true : undefined+ }+ disabled={disabled || (collaborationPolicyDisabled && !collaborationRetryable)}+ onClick={handleCollaborationActivate}+ className={cn(+ 'flex w-full items-center gap-2 rounded-[8px] px-3 py-2',+ 'transition-colors hover:bg-[var(--model-item-hover)]',+ collaboration.enabled && 'bg-[var(--model-item-hover)]',+ (disabled || collaborationPolicyDisabled) && 'opacity-50',+ (disabled || (collaborationPolicyDisabled && !collaborationRetryable)) &&+ 'cursor-not-allowed',+ )}+ >+ <UsersRound+ size={14}className={cn(- 'flex w-full items-center gap-2 rounded-[8px] px-3 py-2',- 'transition-colors hover:bg-[var(--model-item-hover)]',- collaboration.enabled && 'bg-[var(--model-item-hover)]',- (disabled || collaborationPolicyDisabled) && 'opacity-50',- (disabled || (collaborationPolicyDisabled && !collaborationRetryable)) &&- 'cursor-not-allowed',+ 'shrink-0',+ collaboration.enabled+ ? 'text-[var(--warning-accent)]'+ : 'text-[var(--model-item-text)]',+ )}+ />+ <span+ className={cn(+ 'min-w-0 flex-1 truncate text-left text-[13px]',+ collaboration.enabled+ ? 'font-medium text-[var(--warning-accent)]'+ : 'text-[var(--model-item-text)]',)}>- <UsersRound- size={14}+ {t('newChat.collaboration.modeLabel')}+ </span>+ {collaboration.enabled && (+ <Check size={13} className="shrink-0 text-[var(--model-item-check)]" />+ )}+ </button>+ </span>+ </Tip>+ )}++ {plugins.length > 0 && (+ <>+ {(onNewGoal || planMode || collaboration) && (+ <div className="my-1 h-px bg-[var(--model-dropdown-border)]" />+ )}+ <div className="px-2 pb-1 pt-1 text-[12px] text-[var(--model-trigger-text)] opacity-70">+ {t('extraDirs.pluginsTitle')}+ </div>+ <div+ role="list"+ aria-label={t('extraDirs.pluginsTitle')}+ className="morph-panel-list-scroll plugin-motion-root -mr-2 max-h-[200px] overflow-y-auto [scrollbar-gutter:stable]"+ >+ {plugins.map((ghost) => {+ const availableInScope = pluginAvailableIds+ ? pluginAvailableIds.has(ghost.manifest.id)+ : ghost.enabled;+ const hasHostCapabilityEntry = ghost.manifest.slots.includes('ios-simulator');+ const selectable = Boolean(+ availableInScope &&+ ((ghost.manifest.command && onPluginSelect) ||+ (hasHostCapabilityEntry && onPluginCapabilitySelect)),+ );+ return (+ <button+ key={ghost.manifest.id}+ type="button"+ disabled={!selectable}+ onClick={() => {+ setOpen(false);+ if (ghost.manifest.command) {+ onPluginSelect?.(ghost);+ } else if (hasHostCapabilityEntry) {+ onPluginCapabilitySelect?.(ghost);+ }+ }}className={cn(- 'shrink-0',- collaboration.enabled- ? 'text-[var(--warning-accent)]'- : 'text-[var(--model-item-text)]',+ 'flex w-full items-center gap-2 rounded-[8px] px-3 py-2 text-left',+ 'transition-colors hover:bg-[var(--model-item-hover)]',+ 'disabled:cursor-not-allowed disabled:opacity-45',)}- />- <span+ >+ <GhostPluginIcon+ iconDataUrl={ghost.iconDataUrl}+ iconId={ghost.manifest.id}+ iconName={ghost.manifest.name}+ size="menu"+ />+ <span className="min-w-0 flex-1 truncate text-left text-[13px] text-[var(--model-item-text)]">+ {ghost.manifest.name}+ </span>+ {!selectable ? (+ <span className="shrink-0 text-[12px] text-[var(--model-trigger-text)] opacity-70">+ {t(+ !availableInScope+ ? 'extraDirs.pluginDisabled'+ : ghost.manifest.slots.includes('skill')+ ? 'extraDirs.pluginAgentInvoked'+ : 'extraDirs.pluginNoCommand',+ )}+ </span>+ ) : null}+ </button>+ );+ })}+ </div>+ </>+ )}++ {/* 引用目录段:Claude 与 Codex 共用;未接 onChange 时不暴露空操作入口。 */}+ {hasReferenceDirs && (+ <>+ {(onNewGoal || planMode || collaboration || plugins.length > 0) && (+ <div className="my-1 h-px bg-[var(--model-dropdown-border)]" />+ )}++ <div className="px-2 pb-1 pt-1 text-[12px] text-[var(--model-trigger-text)] opacity-70">+ {t('extraDirs.sectionTitle')}+ </div>++ {count > 0 ? (+ <div role="list" aria-label="Extra reference directories" className="mb-1">+ {extraDirs.map((p) => (+ <div+ key={p}className={cn(- 'min-w-0 flex-1 truncate text-left text-[13px]',- collaboration.enabled- ? 'font-medium text-[var(--warning-accent)]'- : 'text-[var(--model-item-text)]',+ 'group flex items-center gap-2 rounded-[8px] px-3 py-2',+ 'hover:bg-[var(--model-item-hover)]',)}>- {t('newChat.collaboration.modeLabel')}- </span>- {collaboration.enabled && (- <Check size={13} className="shrink-0 text-[var(--model-item-check)]" />- )}- </button>- </span>- </Tip>- )}-- {plugins.length > 0 && (- <>- {(onNewGoal || planMode || collaboration) && (- <div className="my-1 h-px bg-[var(--model-dropdown-border)]" />- )}- <div className="px-2 pb-1 pt-1 text-[12px] text-[var(--model-trigger-text)] opacity-70">- {t('extraDirs.pluginsTitle')}- </div>- <div- role="list"- aria-label={t('extraDirs.pluginsTitle')}- className="morph-panel-list-scroll plugin-motion-root -mr-2 max-h-[200px] overflow-y-auto [scrollbar-gutter:stable]"- >- {plugins.map((ghost) => {- const availableInScope = pluginAvailableIds- ? pluginAvailableIds.has(ghost.manifest.id)- : ghost.enabled;- const selectable = Boolean(- availableInScope && ghost.manifest.command && onPluginSelect,- );- return (+ <FolderPlus+ size={14}+ className="shrink-0 text-[var(--model-item-text)] opacity-60"+ />+ <Tip text={p} mono side="top">+ <span className="min-w-0 flex-1 truncate text-left text-[13px] text-[var(--model-item-text)]">+ {basename(p)}+ </span>+ </Tip><button- key={ghost.manifest.id}type="button"- disabled={!selectable}- onClick={() => {- setOpen(false);- onPluginSelect?.(ghost);- }}+ onClick={() => void handleRemove(p)}className={cn(- 'flex w-full items-center gap-2 rounded-[8px] px-3 py-2 text-left',- 'transition-colors hover:bg-[var(--model-item-hover)]',- 'disabled:cursor-not-allowed disabled:opacity-45',+ 'rounded-full p-1 opacity-0 transition-opacity',+ 'hover:bg-[var(--model-item-hover)]',+ 'group-hover:opacity-70 hover:!opacity-100',)}+ aria-label={t('extraDirs.remove', { name: basename(p) })}>- <GhostPluginIcon- iconDataUrl={ghost.iconDataUrl}- iconId={ghost.manifest.id}- iconName={ghost.manifest.name}- size="menu"- />- <span className="min-w-0 flex-1 truncate text-left text-[13px] text-[var(--model-item-text)]">- {ghost.manifest.name}- </span>- {!selectable ? (- <span className="shrink-0 text-[12px] text-[var(--model-trigger-text)] opacity-70">- {t(- ghost.manifest.command- ? 'extraDirs.pluginDisabled'- : 'extraDirs.pluginNoCommand',- )}- </span>- ) : null}+ <X size={12} className="text-[var(--model-item-text)]" /></button>- );- })}+ </div>+ ))}</div>- </>- )}-- {/* 引用目录段:Claude 与 Codex 共用;未接 onChange 时不暴露空操作入口。 */}- {hasReferenceDirs && (- <>- {(onNewGoal || planMode || collaboration || plugins.length > 0) && (- <div className="my-1 h-px bg-[var(--model-dropdown-border)]" />- )}-- <div className="px-2 pb-1 pt-1 text-[12px] text-[var(--model-trigger-text)] opacity-70">- {t('extraDirs.sectionTitle')}+ ) : (+ <div className="px-3 py-2 text-[12px] text-[var(--model-item-text)] opacity-50">+ {t('extraDirs.empty')}</div>+ )}- {count > 0 ? (- <div role="list" aria-label="Extra reference directories" className="mb-1">- {extraDirs.map((p) => (- <div- key={p}- className={cn(- 'group flex items-center gap-2 rounded-[8px] px-3 py-2',- 'hover:bg-[var(--model-item-hover)]',- )}- >- <FolderPlus- size={14}- className="shrink-0 text-[var(--model-item-text)] opacity-60"- />- <Tip text={p} mono side="top">- <span className="min-w-0 flex-1 truncate text-left text-[13px] text-[var(--model-item-text)]">- {basename(p)}- </span>- </Tip>- <button- type="button"- onClick={() => void handleRemove(p)}- className={cn(- 'rounded-full p-1 opacity-0 transition-opacity',- 'hover:bg-[var(--model-item-hover)]',- 'group-hover:opacity-70 hover:!opacity-100',- )}- aria-label={t('extraDirs.remove', { name: basename(p) })}- >- <X size={12} className="text-[var(--model-item-text)]" />- </button>- </div>- ))}- </div>- ) : (- <div className="px-3 py-2 text-[12px] text-[var(--model-item-text)] opacity-50">- {t('extraDirs.empty')}- </div>+ <button+ type="button"+ onClick={() => void handleAdd()}+ disabled={atLimit}+ className={cn(+ 'flex w-full items-center gap-2 rounded-[8px] px-3 py-2',+ 'transition-colors',+ 'hover:bg-[var(--model-item-hover)]',+ 'disabled:cursor-not-allowed disabled:opacity-50',)}-- <button- type="button"- onClick={() => void handleAdd()}- disabled={atLimit}- className={cn(- 'flex w-full items-center gap-2 rounded-[8px] px-3 py-2',- 'transition-colors',- 'hover:bg-[var(--model-item-hover)]',- 'disabled:cursor-not-allowed disabled:opacity-50',- )}- >- <FolderPlus size={14} className="shrink-0 text-[var(--model-item-text)]" />- <span className="text-[13px] text-[var(--model-item-text)]">- {atLimit ? t('extraDirs.atLimit', { max: MAX_EXTRA_DIRS }) : t('extraDirs.add')}- </span>- </button>- </>- )}+ >+ <FolderPlus size={14} className="shrink-0 text-[var(--model-item-text)]" />+ <span className="text-[13px] text-[var(--model-item-text)]">+ {atLimit ? t('extraDirs.atLimit', { max: MAX_EXTRA_DIRS }) : t('extraDirs.add')}+ </span>+ </button>+ </>+ )}</MorphPopover>);}diff --git a/apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx b/apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsxindex b11d40f1fe..440ee1d989 100644--- a/apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx+++ b/apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx@@ -20,6 +20,8 @@ import {} from 'lucide-react';import { InlineReferenceChip } from '@/components/chat/InlineReferenceChip';+import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';+import { GhostPluginIcon } from '@/features/plugin/GhostPluginIcon';import { parseSessionDeepLinkHref } from '@/lib/deepLink';import { resolvePastedSessionMessageText } from './sessionLinkPaste';@@ -35,7 +37,8 @@ export interface MentionChipAttrs {| 'project'| 'browser-tab'| 'desktop-window'- | 'plugin-resource';+ | 'plugin-resource'+ | 'plugin-capability';/** Visible basename, Agent name, command, conversation title/message or project name. */label: string;/** Serialization path/deep-link. */@@ -49,6 +52,8 @@ export interface MentionChipAttrs {sourceLabel?: string;/** Plugin-provided one-line resource summary. */sourceDescription?: string;+ /** Host-verified Plugin identity for a Host capability invocation chip. */+ pluginId?: string;}function displayLabel(attrs: MentionChipAttrs): string {@@ -58,6 +63,7 @@ function displayLabel(attrs: MentionChipAttrs): string {}function MentionIcon({ attrs }: { attrs: MentionChipAttrs }) {+ if (attrs.kind === 'plugin-capability') return <PluginCapabilityIcon attrs={attrs} />;if (attrs.kind === 'slash') return null;if (attrs.kind === 'file') return <File aria-hidden />;if (attrs.kind === 'dir') return <Folder aria-hidden />;@@ -73,13 +79,35 @@ function MentionIcon({ attrs }: { attrs: MentionChipAttrs }) {);}+function PluginCapabilityIcon({ attrs }: { attrs: MentionChipAttrs }) {+ const installedGhosts = useInstalledGhosts();+ const pluginId = attrs.pluginId?.trim() || attrs.label;+ const ghost = installedGhosts.find((candidate) => candidate.manifest.id === pluginId);++ return (+ <GhostPluginIcon+ iconDataUrl={ghost?.iconDataUrl}+ iconId={pluginId}+ iconName={ghost?.manifest.name ?? attrs.sourceLabel ?? attrs.label}+ size="mini"+ />+ );+}+function MentionChipNodeView({ node, selected }: NodeViewProps) {const attrs = node.attrs as MentionChipAttrs;const label = displayLabel(attrs).replace(/\s+/g, ' ').trim();- const [tooltip, setTooltip] = useState(displayLabel(attrs));+ const initialTooltip =+ attrs.kind === 'plugin-capability' && attrs.sourceLabel+ ? attrs.sourceLabel+ : displayLabel(attrs);+ const [tooltip, setTooltip] = useState(initialTooltip);useEffect(() => {- const fallback = displayLabel(attrs);+ const fallback =+ attrs.kind === 'plugin-capability' && attrs.sourceLabel+ ? attrs.sourceLabel+ : displayLabel(attrs);const target = attrs.kind === 'session' ? parseSessionDeepLinkHref(attrs.path) : null;if (!target?.messageClientId) {setTooltip(fallback);@@ -96,7 +124,7 @@ function MentionChipNodeView({ node, selected }: NodeViewProps) {return () => {cancelled = true;};- }, [attrs.kind, attrs.label, attrs.path]);+ }, [attrs.kind, attrs.label, attrs.path, attrs.sourceLabel]);return (<NodeViewWrapper@@ -110,6 +138,7 @@ function MentionChipNodeView({ node, selected }: NodeViewProps) {data-agent-text-truncated={attrs.agentTextTruncated ? 'true' : undefined}data-source-label={attrs.sourceLabel}data-source-description={attrs.sourceDescription}+ data-plugin-id={attrs.pluginId}data-drag-handle=""draggable={true}contentEditable={false}@@ -169,32 +198,34 @@ export const MentionChipNode = Node.create<Record<string, never>, Record<string,agentText: {default: undefined,parseHTML: (element) => element.getAttribute('data-agent-text'),- renderHTML: (attrs) => (- typeof attrs.agentText === 'string' ? { 'data-agent-text': attrs.agentText } : {}- ),+ renderHTML: (attrs) =>+ typeof attrs.agentText === 'string' ? { 'data-agent-text': attrs.agentText } : {},},agentTextTruncated: {default: undefined,parseHTML: (element) => element.getAttribute('data-agent-text-truncated') === 'true',- renderHTML: (attrs) => (- attrs.agentTextTruncated ? { 'data-agent-text-truncated': 'true' } : {}- ),+ renderHTML: (attrs) =>+ attrs.agentTextTruncated ? { 'data-agent-text-truncated': 'true' } : {},},sourceLabel: {default: undefined,parseHTML: (element) => element.getAttribute('data-source-label'),- renderHTML: (attrs) => (- typeof attrs.sourceLabel === 'string' ? { 'data-source-label': attrs.sourceLabel } : {}- ),+ renderHTML: (attrs) =>+ typeof attrs.sourceLabel === 'string' ? { 'data-source-label': attrs.sourceLabel } : {},},sourceDescription: {default: undefined,parseHTML: (element) => element.getAttribute('data-source-description'),- renderHTML: (attrs) => (+ renderHTML: (attrs) =>typeof attrs.sourceDescription === 'string'? { 'data-source-description': attrs.sourceDescription }- : {}- ),+ : {},+ },+ pluginId: {+ default: undefined,+ parseHTML: (element) => element.getAttribute('data-plugin-id'),+ renderHTML: (attrs) =>+ typeof attrs.pluginId === 'string' ? { 'data-plugin-id': attrs.pluginId } : {},},};},@@ -210,7 +241,8 @@ export const MentionChipNode = Node.create<Record<string, never>, Record<string,'data-mention-chip': '','aria-label': displayLabel(attrs),class: FALLBACK_CHIP_CLASS,- style: 'color: var(--text-primary); user-select: none; -webkit-user-select: none; -webkit-user-drag: element;',+ style:+ 'color: var(--text-primary); user-select: none; -webkit-user-select: none; -webkit-user-drag: element;',draggable: 'true',contenteditable: 'false',});@@ -277,11 +309,10 @@ const ICON_PATHS: Record<Exclude<MentionChipAttrs['kind'], 'slash'>, string[]> ='M8 21h8','M12 17v4',],- 'plugin-resource': [- 'M12 22v-5',- 'M9 8V2',- 'M15 8V2',- 'M18 8v5a6 6 0 0 1-12 0V8Z',+ 'plugin-resource': ['M12 22v-5', 'M9 8V2', 'M15 8V2', 'M18 8v5a6 6 0 0 1-12 0V8Z'],+ 'plugin-capability': [+ 'M18 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2Z',+ 'M9 18h6',],};diff --git a/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts b/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.tsindex cdb8c9ec6f..1590802359 100644--- a/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts+++ b/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts@@ -38,6 +38,12 @@ export interface SerializedComposerContent {agentReferences: AgentInputReference[];pastedTextRanges: PastedTextRange[];slashCommandRanges: SlashCommandRange[];+ /** Host capability atoms are routing metadata, not visible prompt text. */+ hostCapability?: {+ capability: string;+ ghostId: string;+ name: string;+ };}type OrderedMarker = '.' | ')' | '、';@@ -103,18 +109,21 @@ function serializeComposerDocument(const mentions: MentionedResource[] = [];const seenMentions = new Set<string>();let hasQuotes = false;+ let hostCapability: SerializedComposerContent['hostCapability'];const addMention = (attrs: MentionChipAttrs) => {// Slash commands and deep links are represented in the wire text but are// not filesystem resources.if (- attrs.kind === 'slash'- || attrs.kind === 'session'- || attrs.kind === 'project'- || attrs.kind === 'browser-tab'- || attrs.kind === 'desktop-window'- || attrs.kind === 'plugin-resource'- ) return;+ attrs.kind === 'slash' ||+ attrs.kind === 'session' ||+ attrs.kind === 'project' ||+ attrs.kind === 'browser-tab' ||+ attrs.kind === 'desktop-window' ||+ attrs.kind === 'plugin-resource' ||+ attrs.kind === 'plugin-capability'+ )+ return;const key = `${attrs.kind}:${attrs.path}`;if (seenMentions.has(key)) return;seenMentions.add(key);@@ -178,12 +187,10 @@ function serializeComposerDocument(// in the current text block preserves the list marker. Put the// encoded quote on its own continuation lines so history parsing// can still recognize the private marker and source metadata.- const continuationPrefix =- continuationIndent || ' '.repeat(expandedIndentWidth(prefix));+ const continuationPrefix = continuationIndent || ' '.repeat(expandedIndentWidth(prefix));const quoteLines = quoteText.split('\n');const hasContinuationLine =- continuationAfterQuote === null &&- buffer.endsWith(`\n${continuationPrefix}`);+ continuationAfterQuote === null && buffer.endsWith(`\n${continuationPrefix}`);const quoteSeparator =continuationAfterQuote !== null ? '\n\n' : hasContinuationLine ? '' : '\n';buffer += `${quoteSeparator}${quoteLines@@ -215,8 +222,7 @@ function serializeComposerDocument(: child.type.name === 'pastedTextChip'? String((child.attrs as PastedTextChipAttrs).text ?? ''): '';- const alreadyIndented =- child.isText && childText.startsWith(continuationAfterQuote);+ const alreadyIndented = child.isText && childText.startsWith(continuationAfterQuote);const textAfterIndent = alreadyIndented? childText.slice(continuationAfterQuote.length): childText;@@ -280,7 +286,10 @@ function serializeComposerDocument(return;}if (attrs.kind === 'browser-tab') {- const label = attrs.label.replace(/\s+/g, ' ').trim().replace(/([\\\[\]])/g, '\\$1');+ const label = attrs.label+ .replace(/\s+/g, ' ')+ .trim()+ .replace(/([[\]\\])/g, '\\$1');const wire = `[${label || 'Browser tab'}](${attrs.path})`;const start = buffer.length;buffer += wire;@@ -299,7 +308,10 @@ function serializeComposerDocument(return;}if (attrs.kind === 'desktop-window') {- const label = attrs.label.replace(/\s+/g, ' ').trim().replace(/([\\\[\]])/g, '\\$1');+ const label = attrs.label+ .replace(/\s+/g, ' ')+ .trim()+ .replace(/([[\]\\])/g, '\\$1');const wire = `[${label || 'Desktop window'}](${attrs.path})`;const start = buffer.length;buffer += wire;@@ -318,8 +330,23 @@ function serializeComposerDocument(}return;}+ if (attrs.kind === 'plugin-capability') {+ // The chip is a structured routing atom. Keeping it out of the+ // visible body prevents an automatic start sentence from being+ // duplicated when the user types their own request after the chip.+ // ChatInput adds a localized default only for chip-only sends.+ hostCapability ??= {+ capability: attrs.path,+ ghostId: attrs.pluginId || attrs.path,+ name: attrs.sourceLabel || attrs.label,+ };+ return;+ }if (attrs.kind === 'plugin-resource') {- const label = attrs.label.replace(/\s+/g, ' ').trim().replace(/([\\\[\]])/g, '\\$1');+ const label = attrs.label+ .replace(/\s+/g, ' ')+ .trim()+ .replace(/([[\]\\])/g, '\\$1');const wire = `[${label || 'Plugin resource'}](${attrs.path})`;const start = buffer.length;buffer += wire;@@ -468,9 +495,7 @@ function serializeComposerDocument(})();const inlineLiteralContinuation =inlineQuoteOffset !== null- ? literalListContinuationPrefix(- node.textBetween(0, inlineQuoteOffset, '\n', '\uFFFC'),- )+ ? literalListContinuationPrefix(node.textBetween(0, inlineQuoteOffset, '\n', '\uFFFC')): null;if (inlineLiteralContinuation) {serializeParagraph(node, nodeOffset, '', inlineLiteralContinuation);@@ -491,6 +516,7 @@ function serializeComposerDocument(...serializeComposerContentBlocksWithRanges(blocks, { preserveTrailingWhitespace }),mentions,hasQuotes,+ ...(hostCapability ? { hostCapability } : {}),};}@@ -559,9 +585,7 @@ export function serializeEditorSlice(editor: Editor | null, slice: Slice): strin// A partial selection keeps the source list's attrs but may omit earlier// siblings. Shift the copied ordered-list start to the selected item.const copiedStart =- sourceList && sourceIndex !== null- ? Number(sourceList.attrs.start) + sourceIndex- : null;+ sourceList && sourceIndex !== null ? Number(sourceList.attrs.start) + sourceIndex : null;if (copiedStart !== null) {let firstContentPosition: number | null = null;replaced.descendants((node, position) => {@@ -571,9 +595,8 @@ export function serializeEditorSlice(editor: Editor | null, slice: Slice): strin}return firstContentPosition === null;});- let orderedListPosition: number | null = firstContentPosition === null- ? firstOrderedList?.position ?? null- : null;+ let orderedListPosition: number | null =+ firstContentPosition === null ? (firstOrderedList?.position ?? null) : null;if (firstContentPosition !== null) {const $firstContent = replaced.resolve(firstContentPosition);for (let depth = $firstContent.depth; depth > 0; depth -= 1) {@@ -586,12 +609,10 @@ export function serializeEditorSlice(editor: Editor | null, slice: Slice): strinconst node = replaced.nodeAt(orderedListPosition);if (node) {const replacedState = EditorState.create({ schema: editor.state.schema, doc: replaced });- replaced = replacedState.tr- .setNodeMarkup(orderedListPosition, node.type, {- ...node.attrs,- start: copiedStart,- })- .doc;+ replaced = replacedState.tr.setNodeMarkup(orderedListPosition, node.type, {+ ...node.attrs,+ start: copiedStart,+ }).doc;}}}diff --git a/apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts b/apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.tsindex d50f32425c..1c35c6b6e5 100644--- a/apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts+++ b/apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts@@ -9,9 +9,56 @@*/import type { Editor } from '@tiptap/core';+import { Fragment, type Node as PMNode } from '@tiptap/pm/model';import type { InstalledGhost } from '../../../shared/ghost';import { findGhostCommandMatch } from './GhostCommandDecoration';+import type { MentionChipAttrs } from './MentionChipNode';++export const IOS_SIMULATOR_HOST_CAPABILITY = 'ios-simulator' as const;+export type ComposerHostCapability = typeof IOS_SIMULATOR_HOST_CAPABILITY;++export interface HostCapabilityChipMatch {+ from: number;+ to: number;+ attrs: MentionChipAttrs;+}++export function hostCapabilityForGhost(ghost: InstalledGhost): ComposerHostCapability | null {+ return ghost.manifest.slots.includes(IOS_SIMULATOR_HOST_CAPABILITY)+ ? IOS_SIMULATOR_HOST_CAPABILITY+ : null;+}++/**+ * Find a Host capability atom only when it is the first non-whitespace+ * composer content. This mirrors the message-start contract used by Plugin+ * commands and keeps replacement deterministic across empty paragraphs.+ */+export function findHostCapabilityChipMatch(doc: PMNode): HostCapabilityChipMatch | null {+ let paragraphPosition = 0;+ for (let paragraphIndex = 0; paragraphIndex < doc.childCount; paragraphIndex += 1) {+ const paragraph = doc.child(paragraphIndex);+ if (paragraph.type.name !== 'paragraph') return null;+ let childPosition = paragraphPosition + 1;+ for (let childIndex = 0; childIndex < paragraph.childCount; childIndex += 1) {+ const child = paragraph.child(childIndex);+ if (child.isText) {+ if (/\S/u.test(child.text ?? '')) return null;+ } else if (child.type.name === 'mentionChip') {+ const attrs = child.attrs as MentionChipAttrs;+ return attrs.kind === 'plugin-capability'+ ? { from: childPosition, to: childPosition + child.nodeSize, attrs }+ : null;+ } else if (child.type.name !== 'hardBreak') {+ return null;+ }+ childPosition += child.nodeSize;+ }+ paragraphPosition += paragraph.nodeSize;+ }+ return null;+}/** Match popover selection timing: close first, then focus the final editable position. */export function focusComposerEndNextFrame(editor: Editor): void {@@ -32,10 +79,28 @@ export function placeGhostAtComposerStart(// 替换识别看完整已安装命令集:旧 Plugin 即使已停用或被当前// 工作目录禁用,它在草稿头的 `$old` 仍应被新选择替换。能否发送// 仍由可用 roster / 发送期闸门单独决定。- const match = findGhostCommandMatch(doc, [...installedRoster], { includeDisabled: true });+ const capabilityMatch = findHostCapabilityChipMatch(doc);+ const match = capabilityMatch+ ? null+ : findGhostCommandMatch(doc, [...installedRoster], { includeDisabled: true });const transaction = editor.state.tr;- if (match) {+ if (capabilityMatch) {+ const nextCharacter =+ capabilityMatch.to < doc.content.size+ ? doc.textBetween(+ capabilityMatch.to,+ Math.min(capabilityMatch.to + 1, doc.content.size),+ '\n',+ '\n',+ )+ : '';+ transaction.insertText(+ `$${command}${nextCharacter && /\s/u.test(nextCharacter) ? '' : ' '}`,+ capabilityMatch.from,+ capabilityMatch.to,+ );+ } else if (match) {const nextCharacter =match.to < doc.content.size? doc.textBetween(match.to, Math.min(match.to + 1, doc.content.size), '\n', '\n')@@ -52,10 +117,65 @@ export function placeGhostAtComposerStart(} else {const paragraphType = editor.state.schema.nodes.paragraph;if (!paragraphType) return false;- transaction.insert(- 0,- paragraphType.create(null, editor.state.schema.text(`$${command} `)),- );+ transaction.insert(0, paragraphType.create(null, editor.state.schema.text(`$${command} `)));+ }+ }++ editor.view.dispatch(transaction);+ focusComposerEndNextFrame(editor);+ return true;+}++/**+ * Place a Host-owned capability as an atomic Plugin chip. Its document attrs+ * contain identity only; serialization maps the capability to a Host-owned+ * prompt and never routes through `expandGhostCommand` / `ghost_call`.+ */+export function placeHostCapabilityAtComposerStart(+ editor: Editor,+ ghost: InstalledGhost,+ installedRoster: readonly InstalledGhost[],+): boolean {+ const capability = hostCapabilityForGhost(ghost);+ if (!capability || editor.isDestroyed || !editor.isEditable) return false;++ const attrs: MentionChipAttrs = {+ kind: 'plugin-capability',+ // Host capabilities have no `$command`; use the localized Plugin name for+ // presentation while keeping the stable id in `pluginId` for routing.+ label: ghost.manifest.name,+ path: capability,+ pluginId: ghost.manifest.id,+ sourceLabel: ghost.manifest.name,+ };+ const node = editor.state.schema.nodes.mentionChip.create(attrs);+ const { doc } = editor.state;+ const capabilityMatch = findHostCapabilityChipMatch(doc);+ const commandMatch = capabilityMatch+ ? null+ : findGhostCommandMatch(doc, [...installedRoster], { includeDisabled: true });+ const match = capabilityMatch ?? commandMatch;+ const transaction = editor.state.tr;++ if (match) {+ const nextCharacter =+ match.to < doc.content.size+ ? doc.textBetween(match.to, Math.min(match.to + 1, doc.content.size), '\n', '\n')+ : '';+ const replacement =+ nextCharacter && /\s/u.test(nextCharacter)+ ? Fragment.from(node)+ : Fragment.fromArray([node, editor.state.schema.text(' ')]);+ transaction.replaceWith(match.from, match.to, replacement);+ } else {+ const content = Fragment.fromArray([node, editor.state.schema.text(' ')]);+ const firstBlock = doc.firstChild;+ if (firstBlock?.isTextblock) {+ transaction.insert(1, content);+ } else {+ const paragraphType = editor.state.schema.nodes.paragraph;+ if (!paragraphType) return false;+ transaction.insert(0, paragraphType.create(null, content));}}diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsxindex ebed5d4767..5f5f008e72 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx@@ -34,6 +34,7 @@ import {PanelLeft,PanelRight,Radio,+ Smartphone,Sparkles,Terminal,Trash2,@@ -78,7 +79,7 @@ interface GhostPluginDetailViewProps {enabledOverride?: boolean;onBack: () => void;onToggle: (enabled: boolean) => void;- /** 主动作:面板型「使用」(打开面板)/ 指令型「对话」;纯工具型不渲染主按钮。 */+ /** 主动作:面板型「使用」/ 指令或 Host 能力型「对话」;纯工具型不渲染主按钮。 */onUse: () => void;/** 头部更新 CTA:市场有新版本时走市场更新确认流。 */onUpdate: () => void;@@ -112,6 +113,7 @@ const PERMISSION_ICON: Record<GhostPermissionItem['kind'], LucideIcon> = {pick: FolderOpen,preview: AppWindow,skill: GraduationCap,+ 'ios-simulator': Smartphone,workspace: FolderPlus,};@@ -163,7 +165,10 @@ export function GhostPluginDetailView({const enabled = enabledOverride ?? detail.enabled;const primaryAction = ghostPrimaryAction(detail);const primaryEnabled =- enabled && (primaryAction === 'panel' || (primaryAction === 'command' && detail.canUse));+ enabled &&+ (primaryAction === 'panel' ||+ primaryAction === 'capability' ||+ (primaryAction === 'command' && detail.canUse));const cindyCapabilities = detail.cindyCapabilities;const hasConfiguration = detail.hasSettingsUi || cindyCapabilities.length > 0 || detail.hasErrand;const summary = ghostPluginSummary(detail.description, detail.id);@@ -290,7 +295,7 @@ export function GhostPluginDetailView({'disabled:cursor-not-allowed disabled:opacity-40 disabled:active:scale-100',)}>- {primaryAction === 'command' ? (+ {primaryAction === 'command' || primaryAction === 'capability' ? (<MessageCircle size={14} aria-hidden="true" />) : null}{t(diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsxindex 62338ca7a7..a9ad408c27 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx@@ -991,7 +991,10 @@ export function GhostPluginPage() {const handleUseGhost = useCallback(async (id: string, displayName: string) => {const ghost = ghosts.find((candidate) => candidate.manifest.id === id);- if (!ghost?.manifest.command) return;+ if (!ghost) return;+ const opensIOSSimulator = ghost.manifest.slots.includes('ios-simulator');+ if (!ghost.manifest.command && !opensIOSSimulator) return;+ const usesHostCapabilityEntry = !ghost.manifest.command && opensIOSSimulator;// 使用前置门:点击时现查配置就绪度(main 侧确定性判定),未就绪先// 弹窗引导去配置。查询失败不拦——运行期 networkSlot 仍会兜底报错,// 这里拦不住只是少了一次前置提醒,不能因此把能用的插件挡在门外。@@ -1019,7 +1022,9 @@ export function GhostPluginPage() {attachments: existing?.attachments ?? [],quotes: existing?.quotes ?? [],browserComments: existing?.browserComments ?? [],- pendingGhostId: ghost.manifest.id,+ ...(ghost.manifest.command ? { pendingGhostId: ghost.manifest.id } : {}),+ ...(usesHostCapabilityEntry ? { pendingHostCapabilityGhostId: ghost.manifest.id } : {}),+ focusAtEnd: existing?.focusAtEnd === true,});resetDraftWorkspaceTargets();navigate('/cc-agent/new');@@ -1027,15 +1032,15 @@ export function GhostPluginPage() {[confirm, ghosts, navigate, openGhostConfiguration, t],);- /** 卡片/详情主动作分发:面板型开页面内面板,指令型起对话,工具型进管理。 */+ /** 卡片/详情主动作分发:面板型开页面内面板,指令/Host 能力型起对话,工具型进管理。 */const handlePrimaryAction = useCallback(- (item: Pick<GhostPluginListItem, 'id' | 'name' | 'tabPanel' | 'canUse'>) => {+ (item: Pick<GhostPluginListItem, 'id' | 'name' | 'tabPanel' | 'canUse' | 'hostCapability'>) => {const action = ghostPrimaryAction(item);if (action === 'panel') {setOpenPanelId(item.id);return;}- if (action === 'command') {+ if (action === 'command' || action === 'capability') {void handleUseGhost(item.id, item.name);return;}@@ -1775,9 +1780,7 @@ export function MarketPluginCard({const unavailable = busy || item.installState === 'conflict';const conflictDescriptionId = useId();const conflictDescription =- item.installState === 'conflict'- ? t('settings.ghosts.market.conflictDescription')- : undefined;+ item.installState === 'conflict' ? t('settings.ghosts.market.conflictDescription') : undefined;return (<articleclassName={cn(@@ -2041,7 +2044,7 @@ export function GhostPluginCard({ariaLabel={t('settings.ghosts.page.useAria', { name: item.name })}/>);- } else if (primary === 'command') {+ } else if (primary === 'command' || primary === 'capability') {primaryControl = (<CardPillButtononClick={onPrimary}diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsxindex 479f1c12b0..a2d76cbf1f 100644--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx@@ -55,6 +55,7 @@ const commandPlugin: GhostPluginListItem = {enabled: true,canUse: true,tabPanel: false,+ hostCapability: null,};const panelPlugin: GhostPluginListItem = {@@ -71,6 +72,13 @@ const toolPlugin: GhostPluginListItem = {canUse: false,};+const simulatorPlugin: GhostPluginListItem = {+ ...toolPlugin,+ id: 'ios-simulator',+ name: 'iOS Simulator',+ hostCapability: 'ios-simulator',+};+const marketPlugin: PluginMarketItem = {pluginId: 'release-google-calendar',ghostId: 'google-calendar',@@ -114,6 +122,15 @@ describe('GhostPluginCard', () => {expect(onPrimary).toHaveBeenCalledTimes(1);});+ it('offers a conversation entry for a Host capability plugin', () => {+ const onPrimary = vi.fn();+ render(<GhostPluginCard item={simulatorPlugin} onPrimary={onPrimary} onManage={vi.fn()} />);++ fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.page.chatAria' }));+ expect(onPrimary).toHaveBeenCalledTimes(1);+ expect(screen.queryByText('settings.ghosts.page.agentInvoked')).toBeNull();+ });+it('routes the manage icon to detail without firing the primary action', () => {const onPrimary = vi.fn();const onManage = vi.fn();@@ -412,9 +429,7 @@ describe('MarketPluginCard', () => {expect((cardBody as HTMLButtonElement).disabled).toBe(true);expect(cardBody.className).toContain('cursor-not-allowed');expect(cardBody.className).not.toContain('cursor-wait');- const conflictDescription = screen.getByText(- 'settings.ghosts.market.conflictDescription',- );+ const conflictDescription = screen.getByText('settings.ghosts.market.conflictDescription');expect(conflictDescription.id).toBeTruthy();expect(cardBody.getAttribute('aria-describedby')).toBe(conflictDescription.id);const conflictAction = screen.getByRole('button', {diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsxindex 6113ca0422..b5fc5220d4 100644--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx@@ -105,6 +105,7 @@ const detail: GhostPluginDetail = {enabled: true,canUse: true,tabPanel: false,+ hostCapability: null,author: 'XD',contents: ['code'],permissions: [],@@ -222,6 +223,35 @@ describe('Ghost plugin detail sections', () => {expect(detailActions?.className).toContain('flex-nowrap');});+ it('renders an enabled Host capability as a conversation action', () => {+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ },+ );+ const onUse = vi.fn();+ render(+ <GhostPluginDetailView+ ghost={null}+ detail={{ ...detail, canUse: false, hostCapability: 'ios-simulator' }}+ panelStatus={null}+ onBack={vi.fn()}+ onToggle={vi.fn()}+ onUse={onUse}+ onUpdate={vi.fn()}+ onUpdateFromFile={vi.fn()}+ onUninstall={vi.fn()}+ toggleDisabled={false}+ />,+ );++ fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.detail.chatAction' }));+ expect(onUse).toHaveBeenCalledTimes(1);+ });+it('routes a projected detail icon failure to market recovery', () => {vi.stubGlobal('ResizeObserver',diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginStateCopy.test.ts b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginStateCopy.test.tsnew file mode 100644index 0000000000..7761ee1486--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginStateCopy.test.ts@@ -0,0 +1,37 @@+/**+ * Regression coverage for Plugin lifecycle wording in the Chinese UI.+ * [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md+ */++import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';++import { describe, expect, it } from 'vitest';++const zhCommon = JSON.parse(+ readFileSync(+ resolve(__dirname, '..', '..', '..', 'i18n', 'locales', 'zh-CN', 'common.json'),+ 'utf8',+ ),+) as {+ extraDirs: { pluginDisabled: string };+ settings: {+ ghosts: {+ disabledTag: string;+ enableAria: string;+ toast: { installedAsleep: string };+ detail: { customSlotAsleep: string; disabledLabel: string };+ };+ };+};++describe('Ghost Plugin lifecycle wording', () => {+ it('describes a reversible disabled state instead of implying incompatibility', () => {+ expect(zhCommon.extraDirs.pluginDisabled).toBe('已停用');+ expect(zhCommon.settings.ghosts.disabledTag).toBe('已停用');+ expect(zhCommon.settings.ghosts.detail.disabledLabel).toBe('已停用');+ expect(zhCommon.settings.ghosts.enableAria).toContain('启用');+ expect(zhCommon.settings.ghosts.toast.installedAsleep).toContain('可随时在此启用');+ expect(zhCommon.settings.ghosts.detail.customSlotAsleep).toContain('启用后');+ });+});diff --git a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.tsindex 142590423d..a7570fe8d4 100644--- a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts+++ b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts@@ -36,24 +36,28 @@ export interface GhostPluginListItem {canUse: boolean;/** 声明了插件页内独占面板(panel.position:'tab'),主动作为「使用」(打开面板)。 */tabPanel: boolean;+ /** 声明了由 Host 承载、但可从插件 UI 主动进入的能力。 */+ hostCapability: 'ios-simulator' | null;trust?: GhostTrustInfo;iconDataUrl?: string;}/**- * 卡片主动作的三分法(与设计稿一致):+ * 卡片主动作的四分法:* - `panel`:有页签面板 → 「使用」直接打开面板;* - `command`:只有 $指令 → 「对话」把指令插进输入框起话题;+ * - `capability`:Host 承载的能力 → 「对话」进入该能力的工作流;* - `manage`:纯工具型(Agent 对话中自动调用)→ 无主按钮,点卡片进管理页。* 停靠形态(left/right)的面板由布局树承载,不算 panel 主动作。*/-export type GhostPrimaryAction = 'panel' | 'command' | 'manage';+export type GhostPrimaryAction = 'panel' | 'command' | 'capability' | 'manage';export function ghostPrimaryAction(- item: Pick<GhostPluginListItem, 'tabPanel' | 'canUse'>,+ item: Pick<GhostPluginListItem, 'tabPanel' | 'canUse' | 'hostCapability'>,): GhostPrimaryAction {if (item.tabPanel) return 'panel';if (item.canUse) return 'command';+ if (item.hostCapability) return 'capability';return 'manage';}export interface GhostPluginDetail extends GhostPluginListItem {@@ -142,9 +146,7 @@ export function filterGhostPluginItems<T extends GhostPluginListItem>(): T[] {const normalizedQuery = query.trim().toLocaleLowerCase();return items.filter((item) =>- `${item.name} ${item.description} ${item.id}`- .toLocaleLowerCase()- .includes(normalizedQuery),+ `${item.name} ${item.description} ${item.id}`.toLocaleLowerCase().includes(normalizedQuery),);}@@ -252,6 +254,7 @@ export function toGhostPluginListItem(enabled: ghost.enabled,canUse: Boolean(manifest.command),tabPanel: manifest.panel?.position === 'tab',+ hostCapability: manifest.slots.includes('ios-simulator') ? 'ios-simulator' : null,trust: ghost.trust ?? {level: 'unverified',publisherSigned: false,@@ -275,7 +278,7 @@ export function toGhostPluginDetail(return {...listItem,trust: listItem.trust!,- author: presentation ? presentation.author : manifest.author ?? null,+ author: presentation ? presentation.author : (manifest.author ?? null),contents: ghostContentKeys(manifest),permissions: ghostPermissionItems(manifest),tools: manifest.tools ?? [],diff --git a/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx b/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsxindex 7eb4f87699..26acecf3d0 100644--- a/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx@@ -39,6 +39,8 @@ interface AddTabDropdownProps {* dropdown 改 trailing 文案为"已打开"并维持 enabled(点击 = host 切到现有)。*/existingKinds?: ReadonlySet<TabKindId>;+ /** Host viewer is a public surface only while the product plugin is enabled. */+ iosSimulatorAvailable?: boolean;}// Phase 1 硬编码。Phase 2 之后由 plugin registry 自动汇总。@@ -89,7 +91,13 @@ const MENU_ITEMS: TabKindMenuMeta[] = [},];-export function AddTabDropdown({ anchorRef, onClose, onSelect, existingKinds }: AddTabDropdownProps) {+export function AddTabDropdown({+ anchorRef,+ onClose,+ onSelect,+ existingKinds,+ iosSimulatorAvailable = false,+}: AddTabDropdownProps) {const { t } = useTranslation();const ref = useRef<HTMLDivElement | null>(null);// 定位:portal 到 body + fixed,按 anchor rect 摆位。原实现是「+」wrapper 内的@@ -186,8 +194,11 @@ export function AddTabDropdown({ anchorRef, onClose, onSelect, existingKinds }:};}, [anchorRef, onClose]);- const enabled = MENU_ITEMS.filter((m) => m.enabled).sort((a, b) => a.order - b.order);- const coming = MENU_ITEMS.filter((m) => !m.enabled).sort((a, b) => a.order - b.order);+ const visibleItems = MENU_ITEMS.filter(+ (item) => item.kind !== 'ios-simulator' || iosSimulatorAvailable,+ );+ const enabled = visibleItems.filter((m) => m.enabled).sort((a, b) => a.order - b.order);+ const coming = visibleItems.filter((m) => !m.enabled).sort((a, b) => a.order - b.order);return createPortal(<divdiff --git a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsxindex 02c9d56c76..8d37c3a258 100644--- a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx@@ -51,6 +51,12 @@ import './plugins';import { initRsbBrowserBridge } from './lib/rsbBrowserBridge';import { initIOSSimulatorFocusBridge } from './lib/iosSimulatorFocusBridge';import { initPopupRouter, setPopupFallbackSession } from './lib/popupRouter';+import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';+import {+ isIOSSimulatorPluginAvailable,+ mergeIOSSimulatorVisibleTabOrder,+ projectIOSSimulatorTabs,+} from './iosSimulatorPluginAvailability';const log = createLogger('rightSidebar.shell');/**@@ -155,6 +161,11 @@ export function RightSidebarShell({? CHROME_ACTIONS_GEOMETRY.clusterWidth: 0;const { t } = useTranslation();+ const installedGhosts = useInstalledGhosts();+ const iosSimulatorPluginAvailable = useMemo(+ () => isIOSSimulatorPluginAvailable(installedGhosts),+ [installedGhosts],+ );// RSB browser bridge (Phase 2):在 Shell 整个生命周期内只 init 一次。bridge 内部// 自带 idempotent guard,strict-mode 双 effect / 重复挂载都安全。bridge 绑定@@ -199,8 +210,64 @@ export function RightSidebarShell({});}, [sessionId]);- const tabs = bucket.tabs;- const activeTabId = bucket.activeTabId;+ const projectedTabs = useMemo(+ () => projectIOSSimulatorTabs(bucket.tabs, bucket.activeTabId, iosSimulatorPluginAvailable),+ [bucket.activeTabId, bucket.tabs, iosSimulatorPluginAvailable],+ );+ const tabs = projectedTabs.tabs;+ const activeTabId = projectedTabs.activeTabId;++ // If a now-hidden simulator tab owned the active marker, move the persisted+ // marker to a visible tab (or null). The simulator tab itself remains stored+ // and returns when the plugin is enabled again.+ useEffect(() => {+ if (!bucket.hydrated || !sessionId || bucket.activeTabId === activeTabId) return;+ void setActiveTab(sessionId, activeTabId).catch((err) => {+ log.error('hidden simulator active-tab reconciliation failed', {+ sessionId,+ activeTabId,+ err,+ });+ });+ }, [activeTabId, bucket.activeTabId, bucket.hydrated, sessionId]);++ const prevTabCountRef = useRef<number | null>(null);+ useEffect(() => {+ prevTabCountRef.current = null;+ }, [sessionId]);++ // A historical simulator-only bucket must not leave an empty public sidebar+ // open before the plugin is installed. Preserve the hidden tab, but collapse+ // the shell each time the user/session makes it visible in this state.+ const hiddenOnlyCollapseRef = useRef<string | null>(null);+ useEffect(() => {+ if (!shellVisible) {+ hiddenOnlyCollapseRef.current = null;+ return;+ }+ const shouldCollapse =+ bucket.hydrated &&+ bucket.tabs.length > 0 &&+ tabs.length === 0 &&+ bucket.tabs.some((tab) => tab.kind === 'ios-simulator') &&+ !iosSimulatorPluginAvailable &&+ prevTabCountRef.current === null;+ if (!shouldCollapse || !sessionId) {+ hiddenOnlyCollapseRef.current = null;+ return;+ }+ if (hiddenOnlyCollapseRef.current === sessionId) return;+ hiddenOnlyCollapseRef.current = sessionId;+ onAllTabsClosed?.();+ }, [+ bucket.hydrated,+ bucket.tabs,+ iosSimulatorPluginAvailable,+ onAllTabsClosed,+ sessionId,+ shellVisible,+ tabs.length,+ ]);// 面板收束(2026-08):插件页签不再注册进右侧栏。历史会话里持久化的// `ghost:*` tab 是旧形态残留,发现即静默关闭 —— 这些 kind 已无渲染方,@@ -225,10 +292,6 @@ export function RightSidebarShell({// - hydrated 后首帧 prev===null 不触发(区分"刚加载出来就是空"与"关到空");// - 展开一个本就 0-tab 的 session 也不会被立刻折叠,用户仍能在 EmptyState 加 tab。// sessionId 变化时重置计数,避免"切到一个空 session"被误判成"关空"。- const prevTabCountRef = useRef<number | null>(null);- useEffect(() => {- prevTabCountRef.current = null;- }, [sessionId]);useEffect(() => {if (!bucket.hydrated) return; // 未 hydrate 的空数组不算"关空"const prev = prevTabCountRef.current;@@ -244,6 +307,10 @@ export function RightSidebarShell({log.warn('handleAdd ignored: sessionId is null', { kind });return;}+ if (kind === 'ios-simulator' && !iosSimulatorPluginAvailable) {+ log.warn('handleAdd ignored: iOS Simulator plugin is unavailable');+ return;+ }const plugin = getTabKind(kind);// Plugin 未注册的 kind(早期 Phase 还没接的 web-browser / terminal):// 仍允许建 tab,但 TabBody 会落到 PlaceholderBody。用户体感上点了「+」总有@@ -260,7 +327,7 @@ export function RightSidebarShell({log.error('handleAdd failed', { sessionId, kind, err });});},- [sessionId],+ [iosSimulatorPluginAvailable, sessionId],);const handleClose = useCallback(@@ -286,11 +353,16 @@ export function RightSidebarShell({const handleReorder = useCallback((orderedIds: string[]) => {if (!sessionId) return;- void reorderTabs(sessionId, orderedIds).catch((err) => {+ const fullOrder = mergeIOSSimulatorVisibleTabOrder(+ bucket.tabs,+ orderedIds,+ iosSimulatorPluginAvailable,+ );+ void reorderTabs(sessionId, fullOrder).catch((err) => {log.error('handleReorder failed', { sessionId, orderedIds, err });});},- [sessionId],+ [bucket.tabs, iosSimulatorPluginAvailable, sessionId],);const handleCycleTab = useCallback(@@ -330,7 +402,7 @@ export function RightSidebarShell({const handleCloseOthers = useCallback(async (keepTabId: string) => {if (!sessionId) return;- const targets = bucket.tabs.filter((t) => t.id !== keepTabId).map((t) => t.id);+ const targets = tabs.filter((t) => t.id !== keepTabId).map((t) => t.id);for (const tabId of targets) {try {await closeTab(sessionId, tabId);@@ -340,13 +412,13 @@ export function RightSidebarShell({}}},- [sessionId, bucket.tabs],+ [sessionId, tabs],);// 右键菜单"关闭所有":关掉本 session 的全部 tab。const handleCloseAll = useCallback(async () => {if (!sessionId) return;- const targets = bucket.tabs.map((t) => t.id);+ const targets = tabs.map((t) => t.id);for (const tabId of targets) {try {await closeTab(sessionId, tabId);@@ -355,7 +427,7 @@ export function RightSidebarShell({break;}}- }, [sessionId, bucket.tabs]);+ }, [sessionId, tabs]);// popup 路由已挪到窗口级常驻模块(lib/popupRouter.ts):订阅不随 Shell 生命// 周期,用户离开聊天视图 / main 端归属等待期间 route 切换都不再丢 popup。@@ -448,6 +520,7 @@ export function RightSidebarShell({onCloseAll={handleCloseAll}pillVariant="chip"addButtonWrapperClassName="h-[30px]"+ iosSimulatorAvailable={iosSimulatorPluginAvailable}/>{/* 右端两态(M2,2026-07-09 Lizi 口径修订):- 贴右(默认)/ maximize 撑满:MainLayout 的 mac 浮层按钮钉在窗口@@ -496,6 +569,7 @@ export function RightSidebarShell({onCloseOthers={handleCloseOthers}onCloseAll={handleCloseAll}chromeWindowDrag={chromeWindowDrag}+ iosSimulatorAvailable={iosSimulatorPluginAvailable}/>)}<div className="relative flex min-h-0 flex-1 flex-col overflow-hidden bg-[var(--panel-bg)]">@@ -603,8 +677,7 @@ function PluginBodyHost({onVisibilityChange: () => {// Phase 4/5 真消费(webview mute / 暂停媒体);v1 noop。},- setCloseInterceptor: (interceptor) =>- setTabCloseInterceptor(tab.id, interceptor),+ setCloseInterceptor: (interceptor) => setTabCloseInterceptor(tab.id, interceptor),}),[sessionId, workdir, remoteHostId, deviceLinkDeviceId, tab.id],);diff --git a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsxindex ba2f376e97..fb1eaffe98 100644--- a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx@@ -85,6 +85,8 @@ interface TabBarProps {* "拖面板"手势面(窗口拖拽区收不到鼠标事件,二者物理互斥;拖窗走左栏顶行);* detached 子窗口等其它宿主不传,默认 true 维持经典拖窗行为。 */chromeWindowDrag?: boolean;+ /** Whether the installed product plugin currently exposes the Host viewer. */+ iosSimulatorAvailable?: boolean;}interface TabStripProps {@@ -114,6 +116,8 @@ interface TabStripProps {*/addButtonWrapperClassName?: string;addButtonClassName?: string;+ /** Whether the installed product plugin currently exposes the Host viewer. */+ iosSimulatorAvailable?: boolean;}const KIND_ICON: Record<BuiltinTabKindId, LucideIcon> = {@@ -194,6 +198,7 @@ export function TabBar({onCloseAll,onDetach,chromeWindowDrag = true,+ iosSimulatorAvailable = false,}: TabBarProps) {const { t } = useTranslation();@@ -218,6 +223,7 @@ export function TabBar({onCloseAll={onCloseAll}addButtonWrapperClassName="h-[36px]"addButtonClassName="mt-[3px]"+ iosSimulatorAvailable={iosSimulatorAvailable}/>{/* Right: window controls. 仅 showWindowControls=true(Win 端)时渲染;@@ -277,6 +283,7 @@ export function TabStrip({pillVariant = 'flush',addButtonWrapperClassName,addButtonClassName,+ iosSimulatorAvailable = false,}: TabStripProps) {const { t } = useTranslation();const reducedMotion = useReducedMotion();@@ -432,6 +439,7 @@ export function TabStrip({setDropdownOpen(false);}}existingKinds={existingKinds}+ iosSimulatorAvailable={iosSimulatorAvailable}/>)}</div>diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/TabBar.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/__tests__/TabBar.test.tsxindex bf55b26d01..4212f1840e 100644--- a/apps/desktop/src/renderer/features/right-sidebar/__tests__/TabBar.test.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/TabBar.test.tsx@@ -39,6 +39,7 @@ function renderStrip(overrides?: {onClose?: () => void;onActivate?: () => void;onReorder?: (orderedIds: string[]) => void;+ iosSimulatorAvailable?: boolean;}) {const onClose = vi.fn(overrides?.onClose);const onActivate = vi.fn(overrides?.onActivate);@@ -51,11 +52,38 @@ function renderStrip(overrides?: {onClose={onClose}onReorder={onReorder}onAdd={vi.fn()}+ iosSimulatorAvailable={overrides?.iosSimulatorAvailable}/>,);return { onClose, onActivate, onReorder };}+describe('TabStrip iOS Simulator plugin gate', () => {+ it('does not expose the Host viewer before the product plugin is enabled', () => {+ renderStrip();+ fireEvent.click(screen.getByRole('button', { name: 'rightSidebar.tabs.addAria' }));+ expect(screen.queryByText('rightSidebar.tabs.kinds.iosSimulator')).toBeNull();+ });++ it('exposes the Host viewer menu item for the enabled product plugin', () => {+ renderStrip({ iosSimulatorAvailable: true });+ const addButton = screen.getByRole('button', { name: 'rightSidebar.tabs.addAria' });+ vi.spyOn(addButton.parentElement as HTMLElement, 'getBoundingClientRect').mockReturnValue({+ x: 20,+ y: 20,+ top: 20,+ right: 44,+ bottom: 44,+ left: 20,+ width: 24,+ height: 24,+ toJSON: () => ({}),+ });+ fireEvent.click(addButton);+ expect(screen.getByText('rightSidebar.tabs.kinds.iosSimulator')).toBeTruthy();+ });+});+afterEach(() => cleanup());describe('TabStrip 中键关闭 tab', () => {diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/iosSimulatorPluginAvailability.test.ts b/apps/desktop/src/renderer/features/right-sidebar/__tests__/iosSimulatorPluginAvailability.test.tsnew file mode 100644index 0000000000..ed20dd42c7--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/iosSimulatorPluginAvailability.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it } from 'vitest';++import type { InstalledGhost } from '../../../../shared/ghost';+import {+ isIOSSimulatorPluginAvailable,+ mergeIOSSimulatorVisibleTabOrder,+ projectIOSSimulatorTabs,+} from '../iosSimulatorPluginAvailability';+import type { TabState } from '../types';++function ghost(id: string, enabled: boolean, slots: string[]): InstalledGhost {+ return {+ enabled,+ manifest: { id, slots },+ } as unknown as InstalledGhost;+}++const TABS: TabState[] = [+ { id: 'file-a', kind: 'file-browser', state: null },+ { id: 'sim-a', kind: 'ios-simulator', state: { instanceId: 'instance-a' } },+ { id: 'web-a', kind: 'web-browser', state: null },+ { id: 'sim-b', kind: 'ios-simulator', state: { instanceId: 'instance-b' } },+];++describe('iOS Simulator plugin availability', () => {+ it('requires an enabled plugin with the capability slot', () => {+ expect(isIOSSimulatorPluginAvailable([])).toBe(false);+ expect(isIOSSimulatorPluginAvailable([ghost('ios-simulator', false, ['ios-simulator'])])).toBe(+ false,+ );+ expect(isIOSSimulatorPluginAvailable([ghost('ios-simulator', true, ['panel'])])).toBe(false);+ expect(isIOSSimulatorPluginAvailable([ghost('another-plugin', true, ['ios-simulator'])])).toBe(+ true,+ );+ expect(+ isIOSSimulatorPluginAvailable([ghost('ios-simulator', true, ['panel', 'ios-simulator'])]),+ ).toBe(true);+ });++ it('hides persisted simulator tabs and selects a visible active fallback', () => {+ expect(projectIOSSimulatorTabs(TABS, 'sim-a', false)).toEqual({+ tabs: [TABS[0], TABS[2]],+ activeTabId: 'file-a',+ });+ expect(projectIOSSimulatorTabs([TABS[1], TABS[3]], 'sim-a', false)).toEqual({+ tabs: [],+ activeTabId: null,+ });+ expect(projectIOSSimulatorTabs(TABS, 'sim-a', true)).toEqual({+ tabs: TABS,+ activeTabId: 'sim-a',+ });+ });++ it('merges visible reordering without moving or deleting hidden simulator slots', () => {+ expect(mergeIOSSimulatorVisibleTabOrder(TABS, ['web-a', 'file-a'], false)).toEqual([+ 'web-a',+ 'sim-a',+ 'file-a',+ 'sim-b',+ ]);+ expect(mergeIOSSimulatorVisibleTabOrder(TABS, ['web-a'], false)).toEqual(+ TABS.map((tab) => tab.id),+ );+ });+});diff --git a/apps/desktop/src/renderer/features/right-sidebar/iosSimulatorPluginAvailability.ts b/apps/desktop/src/renderer/features/right-sidebar/iosSimulatorPluginAvailability.tsnew file mode 100644index 0000000000..77dfe8dc96--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/iosSimulatorPluginAvailability.ts@@ -0,0 +1,68 @@+import type { InstalledGhost } from '../../../shared/ghost';+import type { TabState } from './types';++/**+ * The Host owns the simulator runtime and viewer implementation, while the+ * public product surface is contributed by the installed plugin. Fail closed:+ * only an enabled plugin that explicitly declares the capability slot can+ * expose the Host viewer. The slot, rather than one package id, is the Host+ * contract so an approved replacement provider follows the same gate.+ */+export function isIOSSimulatorPluginAvailable(ghosts: readonly InstalledGhost[]): boolean {+ return ghosts.some(+ ({ enabled, manifest }) => enabled === true && manifest.slots.includes('ios-simulator'),+ );+}++function isHiddenSimulatorTab(tab: TabState, pluginAvailable: boolean): boolean {+ return tab.kind === 'ios-simulator' && !pluginAvailable;+}++/**+ * Hide persisted Host viewer tabs while the plugin is absent or asleep, but do+ * not delete their state. Re-enabling/reinstalling the plugin restores them in+ * place, matching the plugin layout-preservation contract.+ */+export function projectIOSSimulatorTabs(+ tabs: readonly TabState[],+ activeTabId: string | null,+ pluginAvailable: boolean,+): { tabs: TabState[]; activeTabId: string | null } {+ const visibleTabs = pluginAvailable+ ? [...tabs]+ : tabs.filter((tab) => !isHiddenSimulatorTab(tab, pluginAvailable));+ const visibleActiveTabId = visibleTabs.some((tab) => tab.id === activeTabId)+ ? activeTabId+ : (visibleTabs[0]?.id ?? null);+ return { tabs: visibleTabs, activeTabId: visibleActiveTabId };+}++/**+ * `reorderTabs` requires every persisted tab id. When simulator tabs are+ * hidden, merge the visible ordering back into the full list while preserving+ * each hidden slot instead of accidentally deleting or moving hidden state.+ */+export function mergeIOSSimulatorVisibleTabOrder(+ allTabs: readonly TabState[],+ orderedVisibleIds: readonly string[],+ pluginAvailable: boolean,+): string[] {+ if (pluginAvailable) return [...orderedVisibleIds];++ const visibleTabs = allTabs.filter((tab) => !isHiddenSimulatorTab(tab, pluginAvailable));+ const expectedIds = new Set(visibleTabs.map((tab) => tab.id));+ if (+ orderedVisibleIds.length !== visibleTabs.length ||+ new Set(orderedVisibleIds).size !== orderedVisibleIds.length ||+ orderedVisibleIds.some((id) => !expectedIds.has(id))+ ) {+ return allTabs.map((tab) => tab.id);+ }++ let visibleIndex = 0;+ return allTabs.map((tab) =>+ isHiddenSimulatorTab(tab, pluginAvailable)+ ? tab.id+ : (orderedVisibleIds[visibleIndex++] ?? tab.id),+ );+}diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/iosSimulatorFocusBridge.test.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/iosSimulatorFocusBridge.test.tsindex 30fe5ea744..6a3f2d02fd 100644--- a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/iosSimulatorFocusBridge.test.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/iosSimulatorFocusBridge.test.ts@@ -8,7 +8,13 @@ type Bucket = {};let bucket: Bucket = { tabs: [], activeTabId: null };-let focusListener: ((request: { sessionId: string; instanceId: string }) => void) | null = null;+let focusListener:+ ((request: { sessionId: string; instanceId?: string; userInitiated?: boolean }) => void) | null =+ null;+let installedGhosts: Array<{+ enabled: boolean;+ manifest: { id: string; slots: string[] };+}> = [];vi.mock('@/lib/secondaryWindow', () => ({ isSecondaryWindow: () => false }));vi.mock('../../store', () => ({@@ -19,10 +25,14 @@ vi.mock('../../store', () => ({setActiveTab: vi.fn(async () => undefined),}));vi.mock('../sidebarCommands', () => ({ requestRightSidebarVisibility: vi.fn() }));+vi.mock('@/cindy-brain/useInstalledGhosts', () => ({+ readInstalledGhostsSnapshot: () => installedGhosts,+}));import { addTab, ensureHydrated, patchTabState, setActiveTab } from '../../store';import {_resetIOSSimulatorFocusBridgeForTests,+ focusIOSSimulatorPanel,initIOSSimulatorFocusBridge,} from '../iosSimulatorFocusBridge';import { requestRightSidebarVisibility } from '../sidebarCommands';@@ -32,6 +42,12 @@ describe('iOS Simulator focus bridge', () => {vi.clearAllMocks();_resetIOSSimulatorFocusBridgeForTests();bucket = { tabs: [], activeTabId: null };+ installedGhosts = [+ {+ enabled: true,+ manifest: { id: 'ios-simulator', slots: ['ios-simulator'] },+ },+ ];focusListener = null;Object.defineProperty(window, 'electronAPI', {configurable: true,@@ -50,6 +66,29 @@ describe('iOS Simulator focus bridge', () => {});});+ it('ignores focus requests while the product plugin is absent or disabled', async () => {+ installedGhosts = [];+ initIOSSimulatorFocusBridge();+ focusListener?.({ sessionId: 'session-a', instanceId: 'instance-a' });+ await Promise.resolve();+ await Promise.resolve();++ expect(ensureHydrated).not.toHaveBeenCalled();+ expect(addTab).not.toHaveBeenCalled();+ expect(requestRightSidebarVisibility).not.toHaveBeenCalled();++ installedGhosts = [+ {+ enabled: false,+ manifest: { id: 'ios-simulator', slots: ['ios-simulator'] },+ },+ ];+ focusListener?.({ sessionId: 'session-a', instanceId: 'instance-a' });+ await Promise.resolve();+ await Promise.resolve();+ expect(ensureHydrated).not.toHaveBeenCalled();+ });+it('creates and reveals a simulator tab for the launched instance', async () => {initIOSSimulatorFocusBridge();focusListener?.({ sessionId: 'session-a', instanceId: 'instance-a' });@@ -62,6 +101,30 @@ describe('iOS Simulator focus bridge', () => {expect(ensureHydrated).toHaveBeenCalledWith('session-a');expect(requestRightSidebarVisibility).toHaveBeenCalledWith('open', {sessionId: 'session-a',+ userInitiated: true,+ });+ });++ it('creates an unbound simulator tab for a Host capability launcher', async () => {+ initIOSSimulatorFocusBridge();+ focusListener?.({ sessionId: 'session-a', userInitiated: false });++ await vi.waitFor(() => {+ expect(addTab).toHaveBeenCalledWith('session-a', 'ios-simulator', {});+ });+ expect(requestRightSidebarVisibility).toHaveBeenCalledWith('open', {+ sessionId: 'session-a',+ userInitiated: false,+ });+ });++ it('direct plugin entry shares the same Host viewer path', async () => {+ await focusIOSSimulatorPanel({ sessionId: 'session-a', userInitiated: true });++ expect(addTab).toHaveBeenCalledWith('session-a', 'ios-simulator', {});+ expect(requestRightSidebarVisibility).toHaveBeenCalledWith('open', {+ sessionId: 'session-a',+ userInitiated: true,});});diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/iosSimulatorFocusBridge.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/iosSimulatorFocusBridge.tsindex 60ad595648..8b939f4417 100644--- a/apps/desktop/src/renderer/features/right-sidebar/lib/iosSimulatorFocusBridge.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/iosSimulatorFocusBridge.ts@@ -4,6 +4,8 @@ import { createLogger } from '@/lib/logger';import { isSecondaryWindow } from '@/lib/secondaryWindow';import { addTab, ensureHydrated, getBucket, patchTabState, setActiveTab } from '../store';import { requestRightSidebarVisibility } from './sidebarCommands';+import { readInstalledGhostsSnapshot } from '@/cindy-brain/useInstalledGhosts';+import { isIOSSimulatorPluginAvailable } from '../iosSimulatorPluginAvailability';const log = createLogger('rightSidebar.iosSimulatorFocus');@@ -11,28 +13,40 @@ let initialized = false;let teardown: (() => void) | null = null;let operationTail: Promise<void> = Promise.resolve();-async function focusSimulator(request: IOSSimulatorFocusRequest): Promise<void> {+/**+ * Open the Host-owned simulator viewer for an exact task.+ *+ * The Agent bridge and direct plugin entry share this path so both obey the+ * same enabled-plugin gate and singleton-tab behavior.+ */+export async function focusIOSSimulatorPanel(request: IOSSimulatorFocusRequest): Promise<void> {+ if (!isIOSSimulatorPluginAvailable(readInstalledGhostsSnapshot())) return;const sessionId = request.sessionId.trim();- const instanceId = request.instanceId.trim();- if (!sessionId || !instanceId) return;+ const instanceId = request.instanceId?.trim() ?? '';+ if (!sessionId) return;await ensureHydrated(sessionId);const bucket = getBucket(sessionId);- const exact = bucket.tabs.find(- (tab) =>- tab.kind === 'ios-simulator' &&- (tab.state as { instanceId?: unknown } | null)?.instanceId === instanceId,- );+ const exact = instanceId+ ? bucket.tabs.find(+ (tab) =>+ tab.kind === 'ios-simulator' &&+ (tab.state as { instanceId?: unknown } | null)?.instanceId === instanceId,+ )+ : undefined;const existing = exact ?? bucket.tabs.find((tab) => tab.kind === 'ios-simulator');if (existing) {- if (!exact) {+ if (instanceId && !exact) {await patchTabState(sessionId, existing.id, () => ({ instanceId }));}await setActiveTab(sessionId, existing.id);} else {- await addTab(sessionId, 'ios-simulator', { instanceId });+ await addTab(sessionId, 'ios-simulator', instanceId ? { instanceId } : {});}- requestRightSidebarVisibility('open', { sessionId });+ requestRightSidebarVisibility('open', {+ sessionId,+ userInitiated: request.userInitiated ?? true,+ });}/** Main-to-renderer bridge that reveals an exact simulator after it becomes viewable. */@@ -46,7 +60,7 @@ export function initIOSSimulatorFocusBridge(): () => void {teardown = window.electronAPI.maker.iosSimulator.onFocusRequest((request) => {operationTail = operationTail.catch(() => undefined)- .then(() => focusSimulator(request))+ .then(() => focusIOSSimulatorPanel(request)).catch((error) => {log.warn('Unable to focus the iOS Simulator pane', error);});diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsxindex 42f0c0de79..7ed9c1bcf2 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx@@ -8,6 +8,7 @@ import {import {AlertTriangle,CheckCircle2,+ ChevronDown,House,Keyboard,Loader2,@@ -34,6 +35,7 @@ import type {} from '@cindy/ios-simulator-runtime';import type {IOSSimulatorPublicInstance,+ IOSSimulatorPublicDevice,IOSSimulatorPublicViewport,IOSSimulatorPublicRouteStatus,IOSSimulatorSessionStatus,@@ -60,6 +62,32 @@ type StreamProfileName = StandardStreamProfileName | 'experimental60';type StreamProfile = { framesPerSecond: number; jpegQuality: number; scalingPercent: number };type NativeStreamProfile = { framesPerSecond: number; scalingPercent: number };+function actionErrorI18nKey(errorCode: string): string {+ switch (errorCode) {+ case 'SIMULATOR_ATTACHED_ELSEWHERE':+ return 'rightSidebar.iosSimulator.errors.attachedElsewhere';+ case 'SESSION_INSTANCE_LIMIT_REACHED':+ return 'rightSidebar.iosSimulator.errors.taskLimitReached';+ case 'RESOURCE_LIMIT_REACHED':+ return 'rightSidebar.iosSimulator.errors.resourceLimitReached';+ case 'MEMORY_PRESSURE':+ return 'rightSidebar.iosSimulator.errors.memoryPressure';+ case 'SIMULATOR_NOT_FOUND':+ return 'rightSidebar.iosSimulator.errors.deviceNotFound';+ case 'LEASE_EXPIRED':+ case 'STALE_GENERATION':+ return 'rightSidebar.iosSimulator.errors.deviceStateChanged';+ default:+ return 'rightSidebar.iosSimulator.operationErrorWithRecovery';+ }+}++function unavailableDeviceReasonKey(device: IOSSimulatorPublicDevice): string {+ return device.unavailableReason?.code === 'missing-runtime'+ ? 'rightSidebar.iosSimulator.missingRuntime'+ : 'rightSidebar.iosSimulator.deviceUnavailable';+}+const WDA_STREAM_PROFILES: Record<StandardStreamProfileName, StreamProfile> = {low: { framesPerSecond: 5, jpegQuality: 25, scalingPercent: 50 },balanced: { framesPerSecond: 10, jpegQuality: 45, scalingPercent: 70 },@@ -251,11 +279,14 @@ export function IOSSimulatorTabBody({}: IOSSimulatorTabBodyProps) {const { t } = useTranslation();const [status, setStatus] = useState<IOSSimulatorSessionStatus | null>(null);- const [routeStatuses, setRouteStatuses] = useState<Record<string, IOSSimulatorPublicRouteStatus>>({});+ const [routeStatuses, setRouteStatuses] = useState<Record<string, IOSSimulatorPublicRouteStatus>>(+ {},+ );const [transportError, setTransportError] = useState(false);const [actionError, setActionError] = useState<string | null>(null);const [refreshing, setRefreshing] = useState(false);const [operation, setOperation] = useState<Operation>(null);+ const [unavailableDevicesExpanded, setUnavailableDevicesExpanded] = useState(false);const [frameUrl, setFrameUrl] = useState<string | null>(null);const [framePresentation, setFramePresentation] = useState<'jpeg' | 'h264' | null>(null);const [presentationRouteKey, setPresentationRouteKey] = useState<string | null>(null);@@ -328,29 +359,26 @@ export function IOSSimulatorTabBody({[replaceFrameUrl],);- const markFramePresented = useCallback(- (routeKey: string, presentation: 'jpeg' | 'h264') => {- const now = performance.now();- if (fpsWindowRef.current.startedAt === 0) fpsWindowRef.current.startedAt = now;- fpsWindowRef.current.frames += 1;- const elapsed = now - fpsWindowRef.current.startedAt;- if (elapsed >= 1_000) {- setStreamFps((fpsWindowRef.current.frames * 1_000) / elapsed);- fpsWindowRef.current = { startedAt: now, frames: 0 };- }- if (frameFreshnessTimerRef.current !== null) {- window.clearTimeout(frameFreshnessTimerRef.current);- }- setPresentationRouteKey(routeKey);- setFramePresentation(presentation);- setFrameFresh(true);- frameFreshnessTimerRef.current = window.setTimeout(() => {- frameFreshnessTimerRef.current = null;- setFrameFresh(false);- }, FRAME_FRESHNESS_TIMEOUT_MS);- },- [],- );+ const markFramePresented = useCallback((routeKey: string, presentation: 'jpeg' | 'h264') => {+ const now = performance.now();+ if (fpsWindowRef.current.startedAt === 0) fpsWindowRef.current.startedAt = now;+ fpsWindowRef.current.frames += 1;+ const elapsed = now - fpsWindowRef.current.startedAt;+ if (elapsed >= 1_000) {+ setStreamFps((fpsWindowRef.current.frames * 1_000) / elapsed);+ fpsWindowRef.current = { startedAt: now, frames: 0 };+ }+ if (frameFreshnessTimerRef.current !== null) {+ window.clearTimeout(frameFreshnessTimerRef.current);+ }+ setPresentationRouteKey(routeKey);+ setFramePresentation(presentation);+ setFrameFresh(true);+ frameFreshnessTimerRef.current = window.setTimeout(() => {+ frameFreshnessTimerRef.current = null;+ setFrameFresh(false);+ }, FRAME_FRESHNESS_TIMEOUT_MS);+ }, []);const refresh = useCallback(async () => {const requestVersion = ++requestVersionRef.current;@@ -400,12 +428,17 @@ export function IOSSimulatorTabBody({const environment = status?.ok ? status.environment : null;const instances = status?.ok ? status.instances : [];+ const resource = status?.ok ? (status.resource ?? null) : null;+ const maxInstancesPerTask = resource?.maxInstancesPerTask ?? 4;+ const availableDevices = environment?.devices.filter((device) => device.isAvailable) ?? [];+ const unavailableDevices = environment?.devices.filter((device) => !device.isAvailable) ?? [];+ const globalHardLimitReached = Boolean(resource && resource.runningCount >= resource.hardLimit);const attachedInstance =instances.find((instance) => instance.instanceId === state.instanceId) ?? instances[0] ?? null;const viewerRouteKey = attachedInstance? `${attachedInstance.instanceId}:${attachedInstance.generation}`: null;- const routeStatus = viewerRouteKey ? routeStatuses[viewerRouteKey] ?? null : null;+ const routeStatus = viewerRouteKey ? (routeStatuses[viewerRouteKey] ?? null) : null;currentRouteStatusRef.current = routeStatus;const nativeH264Selected = Boolean(routeStatus?.stream.adapter === 'native-sidecar' && routeStatus.stream.encoding === 'h264',@@ -441,11 +474,7 @@ export function IOSSimulatorTabBody({viewerRouteKey && presentationRouteKey === viewerRouteKey && framePresentation !== null,);const viewerInteractive = Boolean(- viewerVisible &&- streamState === 'streaming' &&- presentationMatchesRoute &&- frameFresh &&- !busy,+ viewerVisible && streamState === 'streaming' && presentationMatchesRoute && frameFresh && !busy,);const streamRouteLabel =routeStatus?.stream.adapter === 'native-sidecar' && routeStatus.stream.encoding === 'h264'@@ -465,14 +494,21 @@ export function IOSSimulatorTabBody({const inputRouteStateLabel = routeStatus? t(`rightSidebar.iosSimulator.route.state.${routeStatus.input.state}`): t('rightSidebar.iosSimulator.route.state.detecting');+ const formatActionError = useCallback(+ (result: Extract<IOSSimulatorToolResponse, { ok: false }>) =>+ t(actionErrorI18nKey(result.errorCode), {+ hardLimit: resource?.hardLimit ?? 4,+ taskLimit: maxInstancesPerTask,+ }),+ [maxInstancesPerTask, resource?.hardLimit, t],+ );useEffect(() => {const gate = nativeRecoveryGateRef.current;if (gate.routeKey !== viewerRouteKey) resetNativeRecoveryGate(gate, viewerRouteKey);const nativeActive = Boolean(- (routeStatus?.stream.adapter === 'native-sidecar' &&- routeStatus.stream.state === 'active') ||- (routeStatus?.input.adapter === 'native-sidecar' && routeStatus.input.state === 'active'),+ (routeStatus?.stream.adapter === 'native-sidecar' && routeStatus.stream.state === 'active') ||+ (routeStatus?.input.adapter === 'native-sidecar' && routeStatus.input.state === 'active'),);if (nativeActive && !isRecoverableNativeFallback(routeStatus)) {resetNativeRecoveryGate(gate, viewerRouteKey);@@ -618,8 +654,8 @@ export function IOSSimulatorTabBody({const now = performance.now();if (gate.inFlight || now < gate.retryAfter) return null;gate.inFlight = true;- gate.attemptCount += 1;- gate.retryAfter = now + nativeRecoveryBackoff(gate.attemptCount);+ const attemptCount = gate.attemptCount + 1;+ gate.attemptCount = attemptCount;try {return await window.electronAPI.maker.iosSimulator.setViewerVisibility({...route,@@ -627,8 +663,14 @@ export function IOSSimulatorTabBody({preferredEncoding: 'h264',});} finally {- if (nativeRecoveryGateRef.current.routeKey === routeKey) {- nativeRecoveryGateRef.current.inFlight = false;+ const currentGate = nativeRecoveryGateRef.current;+ if (+ currentGate.routeKey === routeKey &&+ currentGate.inFlight &&+ currentGate.attemptCount === attemptCount+ ) {+ currentGate.inFlight = false;+ currentGate.retryAfter = performance.now() + nativeRecoveryBackoff(attemptCount);}}};@@ -770,6 +812,16 @@ export function IOSSimulatorTabBody({});acceptViewerResult(recovered);}+ if (stream?.state !== 'disconnected') {+ // Keep presenting the healthy WDA/JPEG fallback while an optional+ // Sidecar recovery runs independently. The per-route gate prevents+ // parallel attempts and applies bounded exponential backoff.+ void attemptNativeRecovery()+ .then((recovered) => {+ if (recovered?.ok) acceptViewerResult(recovered);+ })+ .catch(() => undefined);+ }} catch {disconnectViewer();} finally {@@ -869,7 +921,7 @@ export function IOSSimulatorTabBody({args,});if (!result.ok) {- setActionError(result.message);+ setActionError(formatActionError(result));return;}const instance = resultInstance(result);@@ -877,12 +929,12 @@ export function IOSSimulatorTabBody({else if (instance) ctx.patchState({ instanceId: instance.instanceId });await refresh();} catch {- setActionError(t('rightSidebar.iosSimulator.operationError'));+ setActionError(t('rightSidebar.iosSimulator.operationErrorWithRecovery'));} finally {setOperation(null);}},- [ctx, refresh, t],+ [ctx, formatActionError, refresh, t],);const setAgentControl = useCallback(async () => {@@ -895,14 +947,14 @@ export function IOSSimulatorTabBody({instanceId: attachedInstance.instanceId,decision: grant?.agentControl === 'allowed' ? 'denied' : 'allowed',});- if (!result.ok) setActionError(result.message);+ if (!result.ok) setActionError(formatActionError(result));else await refresh();} catch {- setActionError(t('rightSidebar.iosSimulator.operationError'));+ setActionError(t('rightSidebar.iosSimulator.operationErrorWithRecovery'));} finally {setOperation(null);}- }, [attachedInstance, ctx.sessionId, grant?.agentControl, refresh, t]);+ }, [attachedInstance, ctx.sessionId, formatActionError, grant?.agentControl, refresh, t]);const setMutationControl = useCallback(async () => {if (!attachedInstance) return;@@ -914,17 +966,17 @@ export function IOSSimulatorTabBody({...routeFor(attachedInstance),paused: !mutation?.agentPaused,});- if (!result.ok) setActionError(result.message);+ if (!result.ok) setActionError(formatActionError(result));else {const nextMutation = resultMutation(result);if (nextMutation) setLiveMutation(nextMutation);}} catch {- setActionError(t('rightSidebar.iosSimulator.operationError'));+ setActionError(t('rightSidebar.iosSimulator.operationErrorWithRecovery'));} finally {setOperation(null);}- }, [attachedInstance, ctx.sessionId, mutation?.agentPaused, t]);+ }, [attachedInstance, ctx.sessionId, formatActionError, mutation?.agentPaused, t]);const sendStreamProfile = useCallback(async (@@ -964,15 +1016,15 @@ export function IOSSimulatorTabBody({if (result && !result.ok) {setStreamProfile(previous);streamProfileRef.current = previous;- setActionError(result.message);+ setActionError(formatActionError(result));}} catch {setStreamProfile(previous);streamProfileRef.current = previous;- setActionError(t('rightSidebar.iosSimulator.operationError'));+ setActionError(t('rightSidebar.iosSimulator.operationErrorWithRecovery'));}},- [attachedInstance, nativeH264Active, sendStreamProfile, streamProfile, t],+ [attachedInstance, formatActionError, nativeH264Active, sendStreamProfile, streamProfile, t],);useEffect(() => {@@ -1028,10 +1080,17 @@ export function IOSSimulatorTabBody({return;void sendStreamProfile(streamProfileRef.current, true).then((result) => {- if (result && !result.ok) setActionError(result.message);+ if (result && !result.ok) setActionError(formatActionError(result));}).catch(() => undefined);- }, [attachedInstance, nativeH264Active, nativeH264Selected, sendStreamProfile, viewerRouteKey]);+ }, [+ attachedInstance,+ formatActionError,+ nativeH264Active,+ nativeH264Selected,+ sendStreamProfile,+ viewerRouteKey,+ ]);const beginInteractiveFrameRate = useCallback(() => {if (profileRestoreTimerRef.current !== null) {@@ -1101,18 +1160,18 @@ export function IOSSimulatorTabBody({}}if (!result.ok) {- setActionError(result.message);+ setActionError(formatActionError(result));return false;}return true;} catch {- setActionError(t('rightSidebar.iosSimulator.operationError'));+ setActionError(t('rightSidebar.iosSimulator.operationErrorWithRecovery'));return false;} finally {setInteractionBusy(false);}},- [attachedInstance, ctx.sessionId, refresh, t, viewerInteractive],+ [attachedInstance, ctx.sessionId, formatActionError, refresh, t, viewerInteractive],);const pointerRatio = useCallback(@@ -1496,7 +1555,7 @@ export function IOSSimulatorTabBody({role="alert"className="rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-3 text-[12px] text-[var(--text-primary)]">- {actionError} {t('rightSidebar.iosSimulator.retryHint')}+ {actionError}</div>)}@@ -1697,7 +1756,9 @@ export function IOSSimulatorTabBody({!routeStatus.input.multiTouch && (<><span aria-hidden="true">·</span>- <span>{t('rightSidebar.iosSimulator.route.multiTouchUnavailable')}</span>+ <span>+ {t('rightSidebar.iosSimulator.route.multiTouchUnavailable')}+ </span></>)}</div>@@ -1909,6 +1970,39 @@ export function IOSSimulatorTabBody({</section>)}+ {resource && resource.runningCount >= resource.softLimit && (+ <div+ role="status"+ className="flex items-start gap-2 rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-3"+ >+ <AlertTriangle+ size={14}+ className="mt-0.5 shrink-0 text-[var(--text-secondary)]"+ aria-hidden="true"+ />+ <div className="min-w-0">+ <div className="text-[12px] font-medium text-[var(--text-primary)]">+ {t(+ globalHardLimitReached+ ? 'rightSidebar.iosSimulator.resourceHardLimitTitle'+ : 'rightSidebar.iosSimulator.resourceSoftLimitTitle',+ {+ count: resource.runningCount,+ limit: resource.hardLimit,+ },+ )}+ </div>+ <div className="mt-1 text-[11px] leading-relaxed text-[var(--text-secondary)]">+ {t(+ globalHardLimitReached+ ? 'rightSidebar.iosSimulator.resourceHardLimitDescription'+ : 'rightSidebar.iosSimulator.resourceSoftLimitDescription',+ )}+ </div>+ </div>+ </div>+ )}+<section><h3 className="mb-2 text-[12px] font-medium">{t('rightSidebar.iosSimulator.devicesTitle')}@@ -1917,9 +2011,13 @@ export function IOSSimulatorTabBody({<div className="rounded-xl border border-dashed border-[var(--border-default)] p-4 text-center text-[12px] text-[var(--text-secondary)]">{t('rightSidebar.iosSimulator.noDevices')}</div>+ ) : availableDevices.length === 0 ? (+ <div className="rounded-xl border border-dashed border-[var(--border-default)] p-4 text-center text-[12px] text-[var(--text-secondary)]">+ {t('rightSidebar.iosSimulator.noAvailableDevices')}+ </div>) : (<ul className="space-y-2">- {environment.devices.map((device) => {+ {availableDevices.map((device) => {const boundInstance = instances.find((instance) => instance.simulatorUdid === device.udid,);@@ -1928,13 +2026,26 @@ export function IOSSimulatorTabBody({boundInstance &&attachedInstance.instanceId === boundInstance.instanceId,);+ const connectionBlockReason = boundInstance+ ? null+ : device.ownership === 'other-task'+ ? t('rightSidebar.iosSimulator.deviceInUseByOtherTask')+ : instances.length >= maxInstancesPerTask+ ? t('rightSidebar.iosSimulator.taskDeviceLimitReached', {+ limit: maxInstancesPerTask,+ })+ : globalHardLimitReached && device.state.toLowerCase() === 'booted'+ ? t('rightSidebar.iosSimulator.runningDeviceLimitReached', {+ limit: resource?.hardLimit ?? 4,+ })+ : null;+ const connectionBlockDescriptionId = connectionBlockReason+ ? `${ctx.tabId}-${device.udid}-connection-blocked`+ : undefined;return (<likey={device.udid}- className={cn(- 'rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-3',- !device.isAvailable && 'opacity-60',- )}+ className="rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-3"><div className="flex items-start justify-between gap-3"><div className="min-w-0 flex-1">@@ -1964,19 +2075,117 @@ export function IOSSimulatorTabBody({<ActionButtonlabel={t('rightSidebar.iosSimulator.attachDevice')}icon={Link2}- disabled={busy || !device.isAvailable || instances.length >= 4}+ disabled={busy || Boolean(connectionBlockReason)}+ describedBy={connectionBlockDescriptionId}onClick={() =>void call('attach', 'attach_device', { udid: device.udid })}/>)}</div>+ {connectionBlockReason && (+ <div+ id={connectionBlockDescriptionId}+ className="mt-2 flex items-start gap-1.5 text-[11px] leading-relaxed text-[var(--text-secondary)]"+ >+ <AlertTriangle+ size={12}+ className="mt-0.5 shrink-0"+ aria-hidden="true"+ />+ <span>{connectionBlockReason}</span>+ </div>+ )}</li>);})}</ul>)}</section>++ {unavailableDevices.length > 0 && (+ <section>+ <h3>+ <button+ type="button"+ aria-expanded={unavailableDevicesExpanded}+ aria-controls={`${ctx.tabId}-ios-simulator-unavailable-devices`}+ onClick={() => setUnavailableDevicesExpanded((expanded) => !expanded)}+ className="flex w-full select-none items-center gap-2 rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-3 py-2.5 text-left text-[12px] font-medium text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"+ >+ <AlertTriangle+ size={14}+ className="shrink-0 text-[var(--text-secondary)]"+ aria-hidden="true"+ />+ <span className="min-w-0 flex-1">+ {t('rightSidebar.iosSimulator.unavailableDevicesTitle')}+ </span>+ <span className="rounded-full bg-[var(--surface-chip)] px-2 py-0.5 text-[10px] font-normal text-[var(--text-secondary)]">+ {t('rightSidebar.iosSimulator.unavailableDevicesCount', {+ count: unavailableDevices.length,+ })}+ </span>+ <ChevronDown+ size={14}+ aria-hidden="true"+ className={cn(+ 'shrink-0 text-[var(--text-secondary)] transition-transform motion-reduce:transition-none',+ unavailableDevicesExpanded && 'rotate-180',+ )}+ />+ </button>+ </h3>+ {unavailableDevicesExpanded && (+ <div id={`${ctx.tabId}-ios-simulator-unavailable-devices`} className="mt-2">+ <p className="mb-2 text-[11px] leading-relaxed text-[var(--text-secondary)]">+ {t('rightSidebar.iosSimulator.unavailableDevicesDescription')}+ </p>+ <ul className="space-y-2">+ {unavailableDevices.map((device) => {+ const missingRuntime = device.unavailableReason?.code === 'missing-runtime';+ return (+ <li+ key={device.udid}+ className="rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-3"+ >+ <div className="truncate text-[12px] font-medium">{device.name}</div>+ <div className="mt-1 truncate text-[11px] text-[var(--text-secondary)]">+ {device.runtimeName} · {device.state}+ </div>+ <div className="mt-1 truncate font-mono text-[10px] text-[var(--text-tertiary)]">+ {device.udid}+ </div>+ <div className="mt-2 flex items-start gap-1.5 text-[11px] leading-relaxed text-[var(--text-primary)]">+ <AlertTriangle+ size={12}+ className="mt-0.5 shrink-0 text-[var(--text-secondary)]"+ aria-hidden="true"+ />+ <span>+ {t(unavailableDeviceReasonKey(device), {+ runtime:+ device.unavailableReason?.code === 'missing-runtime'+ ? device.unavailableReason.runtimeName+ : device.runtimeName,+ })}+ </span>+ </div>+ <p className="mt-1 pl-[18px] text-[10px] leading-relaxed text-[var(--text-secondary)]">+ {t(+ missingRuntime+ ? 'rightSidebar.iosSimulator.missingRuntimeHelp'+ : 'rightSidebar.iosSimulator.deviceUnavailableHelp',+ )}+ </p>+ </li>+ );+ })}+ </ul>+ </div>+ )}+ </section>+ )}</>)}</div>@@ -1988,11 +2197,13 @@ function ActionButton({label,icon: Icon,disabled,+ describedBy,onClick,}: {label: string;icon: typeof AlertTriangle;disabled?: boolean;+ describedBy?: string;onClick(): void;}) {return (@@ -2000,6 +2211,7 @@ function ActionButton({type="button"onClick={onClick}disabled={disabled}+ aria-describedby={describedBy}className="inline-flex h-8 shrink-0 select-none items-center gap-1.5 rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)] px-3 text-[11px] text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:cursor-default disabled:opacity-50"><Icon size={12} aria-hidden="true" />diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsxindex f2102decd3..8cc6ebb486 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx@@ -173,15 +173,15 @@ function installStatus(statusValue: IOSSimulatorSessionStatus) {if (routeStatusListener === callback) routeStatusListener = null;};});- const liveTouch = vi.fn(async (- request: IOSSimulatorLiveTouchRequest,- ): Promise<IOSSimulatorToolResponse> => {- void request;- return {- ok: true as const,- data: {},- };- });+ const liveTouch = vi.fn(+ async (request: IOSSimulatorLiveTouchRequest): Promise<IOSSimulatorToolResponse> => {+ void request;+ return {+ ok: true as const,+ data: {},+ };+ },+ );const latestFrame = vi.fn(async (): Promise<IOSSimulatorToolResponse> => ({ok: true,data: { stream: null },@@ -328,6 +328,120 @@ describe('IOSSimulatorTabBody', () => {});});+ it('explains task ownership and folds unavailable devices with a safe reason', async () => {+ installStatus({+ ok: true,+ sessionId: 'session-a',+ instances: [],+ deviceGrants: [],+ mutationStates: [],+ resource: {+ runningCount: 2,+ softLimit: 2,+ hardLimit: 4,+ maxInstancesPerTask: 4,+ },+ environment: {+ platform: 'darwin',+ supported: true,+ ready: true,+ xcodeVersion: 'Xcode 26.4',+ runtimes: [],+ devices: [+ {+ udid: 'DEVICE-UDID-123',+ name: 'iPhone 17 Pro',+ state: 'Booted',+ isAvailable: true,+ ownership: 'other-task',+ runtimeIdentifier: 'com.apple.CoreSimulator.SimRuntime.iOS-26-4',+ runtimeName: 'iOS 26.4',+ runtimeVersion: '26.4',+ deviceTypeIdentifier: null,+ lastBootedAt: null,+ },+ {+ udid: 'UNAVAILABLE-DEVICE-UDID',+ name: 'iPhone 16',+ state: 'Shutdown',+ isAvailable: false,+ ownership: 'unowned',+ unavailableReason: { code: 'missing-runtime', runtimeName: 'iOS 18.4' },+ runtimeIdentifier: 'com.apple.CoreSimulator.SimRuntime.iOS-18-4',+ runtimeName: 'iOS 18-4',+ runtimeVersion: null,+ deviceTypeIdentifier: null,+ lastBootedAt: null,+ },+ ],+ issue: null,+ error: null,+ setupSteps: [],+ },+ });++ render(<IOSSimulatorTabBody state={{ instanceId: null }} ctx={ctx} />);++ await waitFor(() => expect(screen.getByText('iPhone 17 Pro')).toBeTruthy());+ expect(screen.getByText('rightSidebar.iosSimulator.deviceInUseByOtherTask')).toBeTruthy();+ expect(screen.getByText('rightSidebar.iosSimulator.resourceSoftLimitTitle')).toBeTruthy();+ expect(+ (+ screen.getByRole('button', {+ name: 'rightSidebar.iosSimulator.attachDevice',+ }) as HTMLButtonElement+ ).disabled,+ ).toBe(true);+ expect(screen.queryByText('iPhone 16')).toBeNull();++ fireEvent.click(+ screen.getByRole('button', {+ name: /rightSidebar\.iosSimulator\.unavailableDevicesTitle/,+ }),+ );++ expect(screen.getByText('iPhone 16')).toBeTruthy();+ expect(screen.getByText('rightSidebar.iosSimulator.missingRuntime')).toBeTruthy();+ expect(screen.getByText('rightSidebar.iosSimulator.missingRuntimeHelp')).toBeTruthy();+ });++ it('maps an ownership race to an actionable localized error', async () => {+ const statusValue = readyStatus();+ if (!statusValue.ok) throw new Error('Expected a ready simulator status.');+ statusValue.instances = [];+ statusValue.environment.devices = [+ {+ udid: 'DEVICE-UDID-123',+ name: 'iPhone 17 Pro',+ state: 'Shutdown',+ isAvailable: true,+ ownership: 'unowned',+ runtimeIdentifier: 'com.apple.CoreSimulator.SimRuntime.iOS-26-4',+ runtimeName: 'iOS 26.4',+ runtimeVersion: '26.4',+ deviceTypeIdentifier: null,+ lastBootedAt: null,+ },+ ];+ const api = installStatus(statusValue);+ api.call.mockResolvedValueOnce({+ ok: false,+ errorCode: 'SIMULATOR_ATTACHED_ELSEWHERE',+ message: 'The simulator is attached to another Cindy session.',+ });++ render(<IOSSimulatorTabBody state={{ instanceId: null }} ctx={ctx} />);+ await waitFor(() => expect(screen.getByText('iPhone 17 Pro')).toBeTruthy());+ fireEvent.click(screen.getByRole('button', { name: 'rightSidebar.iosSimulator.attachDevice' }));++ await waitFor(() => {+ expect(screen.getByRole('alert').textContent).toBe(+ 'rightSidebar.iosSimulator.errors.attachedElsewhere',+ );+ });+ expect(screen.queryByText(/The simulator is attached/)).toBeNull();+ });+it('shows a localized unsupported state for remote sessions', async () => {installStatus({ok: false,@@ -421,9 +535,7 @@ describe('IOSSimulatorTabBody', () => {},],});- fireEvent.click(- screen.getByRole('button', { name: 'rightSidebar.iosSimulator.refresh' }),- );+ fireEvent.click(screen.getByRole('button', { name: 'rightSidebar.iosSimulator.refresh' }));await waitFor(() => expect(api.status).toHaveBeenCalledTimes(2));expect(screen.getByText('rightSidebar.iosSimulator.route.wdaJpeg')).toBeTruthy();expect(screen.getByText('rightSidebar.iosSimulator.route.nativeHid')).toBeTruthy();@@ -799,9 +911,7 @@ describe('IOSSimulatorTabBody', () => {await waitFor(() => {expect(screen.getByText('rightSidebar.iosSimulator.route.nativeH264')).toBeTruthy();});- act(() =>- api.emitRouteStatus({ ...nativeFallback, updatedAt: '2026-08-06T00:00:03.000Z' }),- );+ act(() => api.emitRouteStatus({ ...nativeFallback, updatedAt: '2026-08-06T00:00:03.000Z' }));await waitFor(() => {expect(screen.getByText('rightSidebar.iosSimulator.route.wdaJpeg')).toBeTruthy();});@@ -813,9 +923,7 @@ describe('IOSSimulatorTabBody', () => {await waitFor(() => {expect(screen.getByText('rightSidebar.iosSimulator.route.nativeH264')).toBeTruthy();});- act(() =>- api.emitRouteStatus({ ...nativeFallback, updatedAt: '2026-08-06T00:00:05.000Z' }),- );+ act(() => api.emitRouteStatus({ ...nativeFallback, updatedAt: '2026-08-06T00:00:05.000Z' }));await waitFor(() => {expect(screen.getByText('rightSidebar.iosSimulator.route.wdaJpeg')).toBeTruthy();});@@ -823,6 +931,84 @@ describe('IOSSimulatorTabBody', () => {await waitFor(() => expect(nativeRecoveryRequests()).toHaveLength(3));});+ it('recovers Native in the background while keeping a healthy WDA frame visible', async () => {+ installFakeH264DecoderRuntime();+ const instance = readyInstance();+ const statusValue = readyStatus(instance);+ if (!statusValue.ok) throw new Error('Expected a ready simulator status.');+ const nativeActive: IOSSimulatorRouteStatusPush = {+ sessionId: 'session-a',+ instanceId: instance.instanceId,+ generation: instance.generation,+ updatedAt: '2026-08-06T00:00:00.000Z',+ stream: {+ adapter: 'native-sidecar',+ encoding: 'h264',+ state: 'active',+ reasonCode: 'native-active',+ },+ input: {+ adapter: 'native-sidecar',+ state: 'active',+ continuous: true,+ multiTouch: true,+ reasonCode: 'native-active',+ },+ };+ statusValue.routeStatuses = [nativeActive];+ const api = installStatus(statusValue);+ api.setViewerVisibility.mockResolvedValue({+ ok: true,+ data: {+ stream: {+ instanceId: instance.instanceId,+ generation: instance.generation,+ state: 'connecting',+ reconnectAttempt: 0,+ latestFrame: null,+ },+ },+ });+ api.latestFrame.mockResolvedValue(streamingJpegResult());+ const rendered = render(+ <IOSSimulatorTabBody+ state={{ instanceId: instance.instanceId }}+ ctx={ctx}+ active+ shellVisible+ />,+ );++ await waitFor(() => expect(rendered.container.querySelector('img')).toBeTruthy());+ api.setViewerVisibility.mockClear();+ act(() =>+ api.emitRouteStatus({+ ...nativeActive,+ updatedAt: '2026-08-06T00:00:01.000Z',+ stream: {+ adapter: 'wda',+ encoding: 'jpeg',+ state: 'fallback',+ reasonCode: 'native-stream-disconnected',+ },+ input: {+ adapter: 'wda',+ state: 'fallback',+ continuous: false,+ multiTouch: false,+ reasonCode: 'native-sidecar-unavailable',+ },+ }),+ );++ await waitFor(() =>+ expect(api.setViewerVisibility).toHaveBeenCalledWith(+ expect.objectContaining({ visible: true, preferredEncoding: 'h264' }),+ ),+ );+ expect(rendered.container.querySelector('img')).toBeTruthy();+ });+it('does not retry an explicit H.264 decoder fallback when returning foreground', async () => {installFakeH264DecoderRuntime();let visibilityState: DocumentVisibilityState = 'visible';@@ -1237,15 +1423,14 @@ describe('IOSSimulatorTabBody', () => {const api = installStatus(readyStatus());api.setViewerVisibility.mockResolvedValue(streamingJpegResult());api.latestFrame.mockResolvedValue(streamingJpegResult());- api.liveTouch.mockImplementation(- async (request): Promise<IOSSimulatorToolResponse> =>- request.phase === 'move'- ? {+ api.liveTouch.mockImplementation(async (request): Promise<IOSSimulatorToolResponse> =>+ request.phase === 'move'+ ? {ok: false,- errorCode: 'IOS_SIMULATOR_HOST_ERROR',- message: 'The native move failed.',- }- : { ok: true, data: {} },+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',+ message: 'The native move failed.',+ }+ : { ok: true, data: {} },);const rendered = render(<IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,@@ -1374,15 +1559,17 @@ describe('IOSSimulatorTabBody', () => {api.latestFrame.mockImplementation(() => new Promise<IOSSimulatorToolResponse>(() => {}));let expireFreshness: (() => void) | null = null;const originalSetTimeout = window.setTimeout.bind(window);- vi.spyOn(window, 'setTimeout').mockImplementation(- ((handler: TimerHandler, timeout?: number, ...args: unknown[]) => {- if (timeout === 3_000 && typeof handler === 'function') {- expireFreshness = () => handler(...args);- return 30_001;- }- return originalSetTimeout(handler, timeout, ...args);- }) as typeof window.setTimeout,- );+ vi.spyOn(window, 'setTimeout').mockImplementation(((+ handler: TimerHandler,+ timeout?: number,+ ...args: unknown[]+ ) => {+ if (timeout === 3_000 && typeof handler === 'function') {+ expireFreshness = () => handler(...args);+ return 30_001;+ }+ return originalSetTimeout(handler, timeout, ...args);+ }) as typeof window.setTimeout);const rendered = render(<IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,diff --git a/apps/desktop/src/renderer/hooks/useAttachments.ts b/apps/desktop/src/renderer/hooks/useAttachments.tsindex b1275bc176..d9260c4d3f 100644--- a/apps/desktop/src/renderer/hooks/useAttachments.ts+++ b/apps/desktop/src/renderer/hooks/useAttachments.ts@@ -279,6 +279,9 @@ export function useAttachments(sessionId?: string, draftKey?: string): UseAttachquotes: existing?.quotes ?? [],browserComments: existing?.browserComments ?? [],...(existing?.pendingGhostId ? { pendingGhostId: existing.pendingGhostId } : {}),+ ...(existing?.pendingHostCapabilityGhostId+ ? { pendingHostCapabilityGhostId: existing.pendingHostCapabilityGhostId }+ : {}),...(existing?.focusAtEnd ? { focusAtEnd: true } : {}),},{ silent: true },@@ -353,6 +356,9 @@ export function useAttachments(sessionId?: string, draftKey?: string): UseAttachquotes: existing?.quotes ?? [],browserComments: existing?.browserComments ?? [],...(existing?.pendingGhostId ? { pendingGhostId: existing.pendingGhostId } : {}),+ ...(existing?.pendingHostCapabilityGhostId+ ? { pendingHostCapabilityGhostId: existing.pendingHostCapabilityGhostId }+ : {}),...(existing?.focusAtEnd ? { focusAtEnd: true } : {}),},{ silent: true },@@ -407,6 +413,9 @@ export function useAttachments(sessionId?: string, draftKey?: string): UseAttachquotes: existing?.quotes ?? [],browserComments: existing?.browserComments ?? [],...(existing?.pendingGhostId ? { pendingGhostId: existing.pendingGhostId } : {}),+ ...(existing?.pendingHostCapabilityGhostId+ ? { pendingHostCapabilityGhostId: existing.pendingHostCapabilityGhostId }+ : {}),...(existing?.focusAtEnd ? { focusAtEnd: true } : {}),},{ silent: true },diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 99f10f4055..bc7c396677 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -3467,6 +3467,8 @@"sessionContextDetail": "Shares only location facts (session ID and project folder path) while it works for the current session — no file contents, and no file access is granted.","preview": "Can open preview pages from the sites below in the sidebar browser","previewDetail": "Only the sites listed below can be opened; every page it opens is attributed to this plugin.",+ "iosSimulator": "Can view the current task's embedded iOS Simulator status and open its controls",+ "iosSimulatorDetail": "The Cindy Host still owns simulator lifecycle, WDA, Native Sidecar, video, and input. The plugin receives no frame bytes, input privileges, native Helper access, or IDs from other tasks.","nodeChildSpawn": "Its Node program can ask the host to start declared sub-processes from its package","nodeChildSpawnDetail": "Only JS files declared inside its own package can be started (same local permissions as the main program); arbitrary commands cannot be executed. Sub-processes are closed together when the plugin is disabled or exits.","skill": "Adds the skill \"{{name}}\" to your AI assistants",@@ -3481,6 +3483,7 @@},"errors": {"fileInvalid": "Not a valid .cindy plugin file",+ "hostUnsupported": "This plugin needs Cindy capabilities that this version does not provide. Update Cindy, then install it again.","alreadyInstalled": "This plugin is already installed","commandConflict": "Its command conflicts with an installed plugin. Uninstall the other one or rename the command.","idReserved": "This id uses the reserved official prefix cindy-; it is only available to plugins bundled with the app",@@ -3582,7 +3585,8 @@"slotBadge": "Unread badge","slotFs": "File writing","slotSkill": "Agent skills",- "slotWorkspace": "Workspace sessions"+ "slotWorkspace": "Workspace sessions",+ "slotIOSSimulator": "Embedded iOS Simulator"},"commandPaletteTag": "Plugin command","updateConfirm": {@@ -4392,6 +4396,7 @@},"iosSimulator": {"title": "iOS Simulator",+ "startPrompt": "Open the iOS Simulator for me.","description": "Inspect the Xcode environment and simulators available to this local session.","refresh": "Refresh","checking": "Checking",@@ -4407,6 +4412,14 @@"instancesCount": "{{count}} ready","openDevice": "Open Device","noDevices": "No iPhone or iPad simulators were found.",+ "noAvailableDevices": "No connectable iPhone or iPad simulators were found.",+ "unavailableDevicesTitle": "Unavailable Devices",+ "unavailableDevicesCount": "{{count}}",+ "unavailableDevicesDescription": "These devices cannot be connected right now. Review the reason, resolve it, then refresh the status.",+ "missingRuntime": "{{runtime}} Runtime is missing",+ "missingRuntimeHelp": "Install the matching Runtime in Xcode, then refresh the status.",+ "deviceUnavailable": "Xcode marks this device as unavailable",+ "deviceUnavailableHelp": "Check or recreate the simulator in Xcode, then refresh the status.","booted": "Booted","shutdown": "Shutdown","runtime": "Runtime",@@ -4423,6 +4436,22 @@"disableAgentControl": "Disable Agent Control","operationError": "Cindy could not complete the simulator operation.","retryHint": "Refresh the status and try again.",+ "operationErrorWithRecovery": "Cindy could not complete the simulator operation. Refresh the status and try again.",+ "deviceInUseByOtherTask": "Another Cindy task is using this device. Choose another device, or disconnect it from the original task first.",+ "taskDeviceLimitReached": "This task already has {{limit}} connected devices. Disconnect one before connecting another device.",+ "runningDeviceLimitReached": "Cindy is already running {{limit}} simulators. Stop one before connecting this booted device.",+ "resourceSoftLimitTitle": "{{count}} simulators are currently running",+ "resourceSoftLimitDescription": "Before starting more devices, Cindy checks system memory. Existing devices stay active if a new start is blocked.",+ "resourceHardLimitTitle": "Concurrent simulator limit reached ({{limit}})",+ "resourceHardLimitDescription": "Stop a running simulator before starting another device.",+ "errors": {+ "attachedElsewhere": "Another Cindy task is using this device. Choose another device, or disconnect it from the original task first.",+ "taskLimitReached": "This task can connect up to {{taskLimit}} devices. Disconnect one and try again.",+ "resourceLimitReached": "Cindy has reached the concurrent simulator limit ({{hardLimit}}). Stop a simulator and try again.",+ "memoryPressure": "System memory pressure is too high to start another simulator. Stop a simulator or try again later.",+ "deviceNotFound": "The selected device no longer exists. Refresh the status and choose another device.",+ "deviceStateChanged": "The device state changed. Refresh the status and try again."+ },"streamAlt": "Live simulator view for {{device}}","waitingForFrame": "The live view will appear here when connected.","viewerStoppedTitle": "Simulator stopped",@@ -6165,13 +6194,17 @@"mention": "Plugin mentioned · {{names}}","mentionExpandAria": "Show the hint appended for the model","mentionDirectiveLabel": "Hint appended for the model",+ "hostCapabilityExpandAria": "Show the selected Cindy capability route",+ "hostCapabilityDirectiveLabel": "Cindy capability route sent to the agent",+ "hostCapabilityLegend": "Highlighted = current selection · the rest is Cindy's fixed routing text","semanticExpandAria": "Show how this plugin was used","semanticNote": "The AI used this plugin on its own based on the meaning of your message; no machine directive was appended to it.","listSeparator": ", ","status": {"running": "Calling…","called": "Called",- "done": "Finished"+ "done": "Finished",+ "selected": "Selected"}},"userMessage": {@@ -8602,6 +8635,7 @@"addFiles": "Add files, images, or videos…","pluginsTitle": "Installed Plugins","pluginDisabled": "Disabled",+ "pluginAgentInvoked": "Used automatically by Agent","pluginNoCommand": "Not available here","sectionTitle": "Reference directories (read-only)","empty": "No reference directories yet",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex a8321a4039..9dc5eba2a9 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -3466,6 +3466,8 @@"sessionContextDetail": "現在のセッションのために動作するときだけ、場所の情報(セッション ID とプロジェクトフォルダのパス)を伝えます。ファイルの内容は含まれず、ファイルへのアクセス権も与えられません。","preview": "以下のサイトのプレビューページをサイドバーのブラウザで開けます","previewDetail": "開けるのは下に列挙されたサイトだけです。ページを開くたびに、どのプラグインが開いたかが表示されます。",+ "iosSimulator": "現在のタスクの内蔵 iOS シミュレータ状態を確認し、操作パネルを開けます",+ "iosSimulatorDetail": "シミュレータのライフサイクル、WDA、Native Sidecar、映像、入力は引き続き Cindy Host が管理します。プラグインはフレームデータ、入力権限、ネイティブ Helper、ほかのタスク ID を取得できません。","nodeChildSpawn": "Node プログラムは、パッケージ内で申告済みのサブプロセスの起動をホストに依頼できます","nodeChildSpawnDetail": "起動できるのは自身のパッケージ内で申告済みの JS ファイルだけです(メインプログラムと同じローカル権限)。任意のコマンドは実行できません。プラグインの無効化や終了時にはサブプロセスも一緒に閉じられます。","skill": "AI アシスタントにスキル「{{name}}」を追加します",@@ -3480,6 +3482,7 @@},"errors": {"fileInvalid": "有効な .cindy プラグインファイルではありません",+ "hostUnsupported": "このプラグインには、現在のバージョンでは提供されていない Cindy の機能が必要です。Cindy を更新してから、もう一度インストールしてください。","alreadyInstalled": "このプラグインは既にインストールされています","commandConflict": "コマンドがインストール済みのプラグインと重複しています。先に相手をアンインストールするか、コマンド名を変更してください。","idReserved": "この id は公式予約プレフィックス cindy- を使用しています。アプリに同梱されたプラグインのみ使用できます",@@ -3581,7 +3584,8 @@"slotBadge": "未読バッジ","slotFs": "ファイル書き込み","slotSkill": "エージェントスキル",- "slotWorkspace": "ワークスペースセッション"+ "slotWorkspace": "ワークスペースセッション",+ "slotIOSSimulator": "内蔵 iOS シミュレータ"},"commandPaletteTag": "プラグインコマンド","updateConfirm": {@@ -4390,6 +4394,7 @@},"iosSimulator": {"title": "iOS シミュレータ",+ "startPrompt": "iOS シミュレータを開いてください。","description": "このローカルセッションで使用できる Xcode 環境とシミュレータを確認します。","refresh": "更新","checking": "確認中",@@ -4405,6 +4410,14 @@"instancesCount": "{{count}} 台準備完了","openDevice": "デバイスを開く","noDevices": "iPhone または iPad シミュレータが見つかりません。",+ "noAvailableDevices": "接続できる iPhone または iPad シミュレータがありません。",+ "unavailableDevicesTitle": "使用できないデバイス",+ "unavailableDevicesCount": "{{count}} 台",+ "unavailableDevicesDescription": "これらのデバイスは現在接続できません。理由を確認して問題を解決した後、状態を更新してください。",+ "missingRuntime": "{{runtime}} Runtime がありません",+ "missingRuntimeHelp": "対応する Runtime を Xcode でインストールしてから、状態を更新してください。",+ "deviceUnavailable": "Xcode でこのデバイスが使用不可になっています",+ "deviceUnavailableHelp": "Xcode でシミュレータを確認または再作成してから、状態を更新してください。","booted": "起動中","shutdown": "停止中","runtime": "ランタイム",@@ -4421,6 +4434,22 @@"disableAgentControl": "Agent の操作を無効化","operationError": "Cindy はシミュレータの操作を完了できませんでした。","retryHint": "状態を更新してから、もう一度お試しください。",+ "operationErrorWithRecovery": "Cindy はシミュレータの操作を完了できませんでした。状態を更新してから、もう一度お試しください。",+ "deviceInUseByOtherTask": "別の Cindy タスクがこのデバイスを使用しています。別のデバイスを選ぶか、元のタスクで先に接続を解除してください。",+ "taskDeviceLimitReached": "現在のタスクには {{limit}} 台のデバイスが接続されています。1 台の接続を解除してから、別のデバイスを接続してください。",+ "runningDeviceLimitReached": "Cindy はすでに {{limit}} 台のシミュレータを同時に実行しています。1 台を停止してから、この起動済みデバイスを接続してください。",+ "resourceSoftLimitTitle": "現在 {{count}} 台のシミュレータを実行中です",+ "resourceSoftLimitDescription": "さらにデバイスを起動する前に、Cindy がシステムメモリを確認します。起動できない場合も、既存のデバイスはそのまま動作します。",+ "resourceHardLimitTitle": "同時実行の上限({{limit}} 台)に達しました",+ "resourceHardLimitDescription": "実行中のシミュレータを 1 台停止してから、新しいデバイスを起動してください。",+ "errors": {+ "attachedElsewhere": "別の Cindy タスクがこのデバイスを使用しています。別のデバイスを選ぶか、元のタスクで先に接続を解除してください。",+ "taskLimitReached": "このタスクには最大 {{taskLimit}} 台のデバイスを接続できます。1 台の接続を解除してから、もう一度お試しください。",+ "resourceLimitReached": "Cindy はシミュレータの同時実行上限({{hardLimit}} 台)に達しています。1 台を停止してから、もう一度お試しください。",+ "memoryPressure": "システムのメモリ負荷が高いため、シミュレータを追加で起動できません。1 台を停止するか、しばらくしてからもう一度お試しください。",+ "deviceNotFound": "選択したデバイスは存在しません。状態を更新して、別のデバイスを選んでください。",+ "deviceStateChanged": "デバイスの状態が変わりました。状態を更新してから、もう一度お試しください。"+ },"streamAlt": "{{device}} のライブシミュレータ画面","waitingForFrame": "接続されると、ここにライブ画面が表示されます。","viewerStoppedTitle": "シミュレータは停止しました",@@ -6163,13 +6192,17 @@"mention": "プラグインに言及 · {{names}}","mentionExpandAria": "モデルに追加されたヒントを表示","mentionDirectiveLabel": "モデルに追加されたヒント",+ "hostCapabilityExpandAria": "選択した Cindy 機能のルートを表示",+ "hostCapabilityDirectiveLabel": "Agent に送信された Cindy 機能ルート",+ "hostCapabilityLegend": "ハイライト = 現在の選択 · それ以外は Cindy の固定ルート説明","semanticExpandAria": "この呼び出しの説明を表示","semanticNote": "AI がメッセージの意味に基づいてこのプラグインを自律的に呼び出しました。このメッセージに機械指示は追加されていません。","listSeparator": "、","status": {"running": "呼び出し中…","called": "呼び出し済み",- "done": "完了"+ "done": "完了",+ "selected": "選択済み"}},"userMessage": {@@ -8589,6 +8622,7 @@"addFiles": "ファイル、画像、動画を追加…","pluginsTitle": "インストール済みプラグイン","pluginDisabled": "無効",+ "pluginAgentInvoked": "Agent が自動で使用","pluginNoCommand": "ここでは使用できません","sectionTitle": "参照ディレクトリ(読み取り専用)","empty": "参照ディレクトリはまだありません",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 374c14d07e..9779853b79 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -3466,6 +3466,8 @@"sessionContextDetail": "현재 세션을 위해 작동할 때만 위치 정보(세션 ID와 프로젝트 폴더 경로)를 전달합니다. 파일 내용은 포함되지 않으며 파일 접근 권한도 부여되지 않습니다.","preview": "아래 사이트의 미리보기 페이지를 사이드바 브라우저에서 열 수 있습니다","previewDetail": "아래에 나열된 사이트만 열 수 있으며, 페이지를 열 때마다 어떤 플러그인이 열었는지 표시됩니다.",+ "iosSimulator": "현재 작업의 내장 iOS 시뮬레이터 상태를 확인하고 제어 패널을 열 수 있습니다",+ "iosSimulatorDetail": "시뮬레이터 수명 주기, WDA, Native Sidecar, 영상과 입력은 계속 Cindy Host가 관리합니다. 플러그인은 프레임 데이터, 입력 권한, 네이티브 Helper 또는 다른 작업 ID를 받을 수 없습니다.","nodeChildSpawn": "Node 프로그램이 패키지에 신고된 하위 프로세스 시작을 호스트에 요청할 수 있습니다","nodeChildSpawnDetail": "자신의 패키지 안에 신고된 JS 파일만 시작할 수 있으며(메인 프로그램과 동일한 로컬 권한), 임의의 명령은 실행할 수 없습니다. 플러그인이 비활성화되거나 종료되면 하위 프로세스도 함께 종료됩니다.","skill": "AI 어시스턴트에 스킬 \"{{name}}\"을(를) 추가합니다",@@ -3480,6 +3482,7 @@},"errors": {"fileInvalid": "유효한 .cindy 플러그인 파일이 아닙니다",+ "hostUnsupported": "이 플러그인에는 현재 버전에서 제공하지 않는 Cindy 기능이 필요합니다. Cindy를 업데이트한 후 다시 설치하세요.","alreadyInstalled": "이 플러그인은 이미 설치되어 있습니다","commandConflict": "명령어가 설치된 플러그인과 충돌합니다. 먼저 상대를 제거하거나 명령어 이름을 변경하세요.","idReserved": "이 id는 공식 예약 접두사 cindy-를 사용합니다. 앱에 내장된 플러그인만 사용할 수 있습니다",@@ -3581,7 +3584,8 @@"slotBadge": "읽지 않음 배지","slotFs": "파일 쓰기","slotSkill": "에이전트 스킬",- "slotWorkspace": "워크스페이스 세션"+ "slotWorkspace": "워크스페이스 세션",+ "slotIOSSimulator": "내장 iOS 시뮬레이터"},"commandPaletteTag": "플러그인 명령","updateConfirm": {@@ -4390,6 +4394,7 @@},"iosSimulator": {"title": "iOS 시뮬레이터",+ "startPrompt": "iOS 시뮬레이터를 열어 주세요.","description": "이 로컬 세션에서 사용할 수 있는 Xcode 환경과 시뮬레이터를 확인합니다.","refresh": "새로 고침","checking": "확인 중",@@ -4405,6 +4410,14 @@"instancesCount": "{{count}}개 준비됨","openDevice": "기기 열기","noDevices": "iPhone 또는 iPad 시뮬레이터를 찾지 못했습니다.",+ "noAvailableDevices": "연결할 수 있는 iPhone 또는 iPad 시뮬레이터가 없습니다.",+ "unavailableDevicesTitle": "사용할 수 없는 기기",+ "unavailableDevicesCount": "{{count}}대",+ "unavailableDevicesDescription": "현재 연결할 수 없는 기기입니다. 원인을 확인하고 해결한 후 상태를 새로 고치세요.",+ "missingRuntime": "{{runtime}} Runtime이 없습니다",+ "missingRuntimeHelp": "해당 Runtime을 Xcode에서 설치한 후 상태를 새로 고치세요.",+ "deviceUnavailable": "Xcode에서 이 기기를 사용할 수 없는 상태로 표시했습니다",+ "deviceUnavailableHelp": "Xcode에서 시뮬레이터를 확인하거나 다시 생성한 후 상태를 새로 고치세요.","booted": "부팅됨","shutdown": "종료됨","runtime": "런타임",@@ -4421,6 +4434,22 @@"disableAgentControl": "Agent 제어 사용 중지","operationError": "Cindy가 시뮬레이터 작업을 완료하지 못했습니다.","retryHint": "상태를 새로 고친 후 다시 시도하세요.",+ "operationErrorWithRecovery": "Cindy가 시뮬레이터 작업을 완료하지 못했습니다. 상태를 새로 고친 후 다시 시도하세요.",+ "deviceInUseByOtherTask": "다른 Cindy 작업에서 이 기기를 사용 중입니다. 다른 기기를 선택하거나 기존 작업에서 먼저 연결을 해제하세요.",+ "taskDeviceLimitReached": "현재 작업에 {{limit}}대의 기기가 연결되어 있습니다. 한 대의 연결을 해제한 후 다른 기기를 연결하세요.",+ "runningDeviceLimitReached": "Cindy에서 이미 {{limit}}대의 시뮬레이터를 동시에 실행 중입니다. 한 대를 중지한 후 이 부팅된 기기를 연결하세요.",+ "resourceSoftLimitTitle": "현재 {{count}}대의 시뮬레이터가 실행 중입니다",+ "resourceSoftLimitDescription": "기기를 더 시작하기 전에 Cindy가 시스템 메모리를 확인합니다. 새 시작이 차단되어도 기존 기기는 계속 실행됩니다.",+ "resourceHardLimitTitle": "동시 실행 한도({{limit}}대)에 도달했습니다",+ "resourceHardLimitDescription": "실행 중인 시뮬레이터 한 대를 중지한 후 새 기기를 시작하세요.",+ "errors": {+ "attachedElsewhere": "다른 Cindy 작업에서 이 기기를 사용 중입니다. 다른 기기를 선택하거나 기존 작업에서 먼저 연결을 해제하세요.",+ "taskLimitReached": "이 작업에는 최대 {{taskLimit}}대의 기기를 연결할 수 있습니다. 한 대의 연결을 해제한 후 다시 시도하세요.",+ "resourceLimitReached": "Cindy의 시뮬레이터 동시 실행 한도({{hardLimit}}대)에 도달했습니다. 한 대를 중지한 후 다시 시도하세요.",+ "memoryPressure": "시스템 메모리 압력이 높아 시뮬레이터를 더 시작할 수 없습니다. 한 대를 중지하거나 나중에 다시 시도하세요.",+ "deviceNotFound": "선택한 기기가 더 이상 존재하지 않습니다. 상태를 새로 고치고 다른 기기를 선택하세요.",+ "deviceStateChanged": "기기 상태가 변경되었습니다. 상태를 새로 고친 후 다시 시도하세요."+ },"streamAlt": "{{device}}의 실시간 시뮬레이터 화면","waitingForFrame": "연결되면 실시간 화면이 여기에 표시됩니다.","viewerStoppedTitle": "시뮬레이터가 중지됨",@@ -6163,13 +6192,17 @@"mention": "플러그인 언급 · {{names}}","mentionExpandAria": "모델에 추가된 힌트 보기","mentionDirectiveLabel": "모델에 추가된 힌트",+ "hostCapabilityExpandAria": "선택한 Cindy 기능 경로 보기",+ "hostCapabilityDirectiveLabel": "Agent에 전송된 Cindy 기능 경로",+ "hostCapabilityLegend": "강조 표시 = 현재 선택 · 나머지는 Cindy의 고정 경로 설명","semanticExpandAria": "이 호출에 대한 설명 보기","semanticNote": "AI가 메시지의 의미를 바탕으로 이 플러그인을 스스로 호출했습니다. 이 메시지에는 기계 지시문이 추가되지 않았습니다.","listSeparator": ", ","status": {"running": "호출 중…","called": "호출됨",- "done": "완료됨"+ "done": "완료됨",+ "selected": "선택됨"}},"userMessage": {@@ -8589,6 +8622,7 @@"addFiles": "파일, 이미지 또는 동영상 추가…","pluginsTitle": "설치된 플러그인","pluginDisabled": "비활성화됨",+ "pluginAgentInvoked": "Agent가 자동으로 사용","pluginNoCommand": "여기에서 사용할 수 없음","sectionTitle": "참조 디렉터리(읽기 전용)","empty": "아직 참조 디렉터리가 없습니다",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 455e372a77..d219bfdd71 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -3315,9 +3315,9 @@"retry": "重试恢复","retrying": "正在恢复…"},- "disabledTag": "未生效",- "projectDisabledTag": "本项目未生效",- "projectSwitchLockedTip": "该插件已在全局停用;请先切回「全局」视图开启",+ "disabledTag": "已停用",+ "projectDisabledTag": "本项目已停用",+ "projectSwitchLockedTip": "该插件已在全局停用;请先切回「全局」视图启用","projectBanner": {"title": "正在配置项目「{{name}}」","desc": "开关只影响此项目:关闭的插件在该项目中不可用",@@ -3325,10 +3325,10 @@},"scopePicker": {"global": "全局(默认)",- "ariaLabel": "选择插件生效范围",+ "ariaLabel": "选择插件启用范围","browse": "选择其它目录…"},- "enableAria": "使 {{name}} 生效",+ "enableAria": "启用 {{name}}","uninstall": "卸载","uninstallConfirm": {"title": "卸载「{{name}}」?",@@ -3347,7 +3347,7 @@"toast": {"installed": "已安装「{{name}}」","uninstalled": "已卸载「{{name}}」",- "installedAsleep": "已安装「{{name}}」(未生效,可在此开启)",+ "installedAsleep": "已安装「{{name}}」(已停用,可随时在此启用)","updated": "「{{name}}」已更新到 v{{version}}","exported": "已导出「{{name}}」的 .cindy 文件","exportFailed": "导出「{{name}}」失败,请重试",@@ -3466,6 +3466,8 @@"sessionContextDetail": "只在它为当前任务干活时告知位置信息(任务编号与项目文件夹路径),不包含文件内容,也不因此获得文件访问权。","preview": "可在右侧栏浏览器中打开以下网站的预览页面","previewDetail": "只能打开下方列出的网站;每次打开都会提示是哪个插件打开的。",+ "iosSimulator": "可查看当前任务的内置 iOS 模拟器状态并打开控制面板",+ "iosSimulatorDetail": "模拟器生命周期、WDA、Native Sidecar、画面与输入仍由 Cindy 主机管理;插件拿不到画面字节、输入权限、原生 Helper 或其它任务的编号。","nodeChildSpawn": "Node 程序可请宿主再启动包内申报过的子进程","nodeChildSpawnDetail": "只能启动它自己包里申报过的 JS 文件(与主程序同样的本机权限),不能执行任意命令;插件停用或退出时子进程一并关闭。","skill": "为 AI 助手添加技能「{{name}}」",@@ -3480,6 +3482,7 @@},"errors": {"fileInvalid": "不是合法的 .cindy 插件文件",+ "hostUnsupported": "这个插件需要当前版本尚未提供的 Cindy 能力。请先升级 Cindy,再重新安装。","alreadyInstalled": "这个插件已经安装","commandConflict": "它的指令和已装插件撞名了,先卸载占用方或让作者改名","idReserved": "该 id 使用了官方保留前缀 cindy-,仅随应用内置的插件可用",@@ -3488,7 +3491,7 @@"updateIdMismatch": "所选文件是插件「{{id}}」,与当前插件「{{expected}}」不一致"},"detail": {- "enable": "生效",+ "enable": "启用","backToList": "返回插件列表","infoTitle": "详细信息","infoId": "标识",@@ -3512,7 +3515,7 @@"infoContents": "包含","infoVersion": "版本","updateTitle": "更新版本",- "updateDesc": "选择新的 .cindy 文件原位替换;生效状态与面板位置保持不变。",+ "updateDesc": "选择新的 .cindy 文件原位替换;启用状态与面板位置保持不变。","cindyPrefs": {"title": "Cindy 能力","desc": "这个插件申请的每项 Cindy 代办能力,可单独指定用哪个模型;默认跟随系统(自带 Proxy)。",@@ -3542,14 +3545,14 @@"toolsTitle": "Tools","permissionsTitle": "权限","infoDescription": "描述",- "customSlotAsleep": "插件未生效,生效后这里将显示它的设置界面。",+ "customSlotAsleep": "插件已停用,启用后这里将显示它的设置界面。","descriptionExpand": "展开","descriptionCollapse": "收起","useAction": "使用","chatAction": "对话","enabledLabel": "已启用","disabledLabel": "已停用",- "useDisabled": "请先开启插件",+ "useDisabled": "请先启用插件","moreActions": "更多插件操作","updateFromFile": "从 .cindy 文件更新…","exportPackage": "导出 .cindy 文件…",@@ -3581,7 +3584,8 @@"slotBadge": "未读角标","slotFs": "写文件","slotSkill": "Agent 技能",- "slotWorkspace": "工作区任务"+ "slotWorkspace": "工作区任务",+ "slotIOSSimulator": "内置 iOS 模拟器"},"commandPaletteTag": "插件指令","updateConfirm": {@@ -4390,6 +4394,7 @@},"iosSimulator": {"title": "iOS 模拟器",+ "startPrompt": "帮我打开 iOS 模拟器。","description": "查看当前本地任务可用的 Xcode 环境和模拟器设备。","refresh": "刷新","checking": "正在检查",@@ -4405,6 +4410,14 @@"instancesCount": "{{count}} 台就绪","openDevice": "打开设备","noDevices": "未找到 iPhone 或 iPad 模拟器。",+ "noAvailableDevices": "没有可连接的 iPhone 或 iPad 模拟器。",+ "unavailableDevicesTitle": "不可用设备",+ "unavailableDevicesCount": "{{count}} 台",+ "unavailableDevicesDescription": "这些设备当前不能连接。查看原因并按提示修复后,再刷新状态。",+ "missingRuntime": "缺少 {{runtime}} Runtime",+ "missingRuntimeHelp": "请在 Xcode 中安装对应 Runtime,然后刷新状态。",+ "deviceUnavailable": "Xcode 已将此设备标记为不可用",+ "deviceUnavailableHelp": "请在 Xcode 中检查或重新创建该模拟器,然后刷新状态。","booted": "已启动","shutdown": "已关机","runtime": "运行时",@@ -4421,6 +4434,22 @@"disableAgentControl": "停用 Agent 控制","operationError": "Cindy 无法完成模拟器操作。","retryHint": "请刷新状态后重试。",+ "operationErrorWithRecovery": "Cindy 无法完成模拟器操作。请刷新状态后重试。",+ "deviceInUseByOtherTask": "另一个 Cindy 任务正在使用此设备。请选择其他设备,或先在原任务中断开它。",+ "taskDeviceLimitReached": "当前任务已连接 {{limit}} 台设备。请先断开一台,再连接其他设备。",+ "runningDeviceLimitReached": "Cindy 已同时运行 {{limit}} 台模拟器。请先停止一台,再连接此已启动设备。",+ "resourceSoftLimitTitle": "当前正在运行 {{count}} 台模拟器",+ "resourceSoftLimitDescription": "继续启动更多设备时,Cindy 会先检查系统内存;不足时会保留现有设备并阻止新启动。",+ "resourceHardLimitTitle": "已达到同时运行上限({{limit}} 台)",+ "resourceHardLimitDescription": "请先停止一台正在运行的模拟器,再启动新设备。",+ "errors": {+ "attachedElsewhere": "另一个 Cindy 任务正在使用此设备。请选择其他设备,或先在原任务中断开它。",+ "taskLimitReached": "当前任务最多连接 {{taskLimit}} 台设备。请先断开一台再重试。",+ "resourceLimitReached": "Cindy 已达到同时运行上限({{hardLimit}} 台)。请先停止一台模拟器再重试。",+ "memoryPressure": "系统内存压力较高,暂时无法启动更多模拟器。请先停止一台模拟器,或稍后重试。",+ "deviceNotFound": "所选设备已不存在。请刷新状态并选择其他设备。",+ "deviceStateChanged": "设备状态已变化。请刷新状态后重试。"+ },"streamAlt": "{{device}} 的实时模拟器画面","waitingForFrame": "画面连接后会显示在这里。","viewerStoppedTitle": "模拟器已停止",@@ -6163,13 +6192,17 @@"mention": "提及插件 · {{names}}","mentionExpandAria": "查看追加给模型的提示原文","mentionDirectiveLabel": "追加给模型的提示",+ "hostCapabilityExpandAria": "查看所选 Cindy 能力的路由说明",+ "hostCapabilityDirectiveLabel": "发送给 Agent 的 Cindy 能力路由",+ "hostCapabilityLegend": "高亮 = 当前选择 · 其余为 Cindy 固定路由说明","semanticExpandAria": "查看本次调用说明","semanticNote": "AI 根据消息语义自主调用了这个插件;本条消息未追加任何机器指令。","listSeparator": "、","status": {"running": "调用中…","called": "已调用",- "done": "已完成"+ "done": "已完成",+ "selected": "已选择"}},"userMessage": {@@ -8588,7 +8621,8 @@"tooltipCount": "{{count}} 个附加引用目录","addFiles": "添加文件、图片或视频…","pluginsTitle": "已安装的插件",- "pluginDisabled": "未生效",+ "pluginDisabled": "已停用",+ "pluginAgentInvoked": "Agent 自动调用","pluginNoCommand": "不可直接使用","sectionTitle": "引用目录(只读)","empty": "还没有引用目录",diff --git a/apps/desktop/src/renderer/lib/__tests__/providerModelEfforts.test.ts b/apps/desktop/src/renderer/lib/__tests__/providerModelEfforts.test.tsindex 0bc9542d97..741d3fdee4 100644--- a/apps/desktop/src/renderer/lib/__tests__/providerModelEfforts.test.ts+++ b/apps/desktop/src/renderer/lib/__tests__/providerModelEfforts.test.ts@@ -145,8 +145,8 @@ describe('resolveProviderModelEfforts', () => {expect(source.slice(agentSwitchStart, agentSwitchEnd)).toContain('resolveModelEfforts(\n newModelId,\n providerId,\n targetAgentKind,\n )',);- expect(source.slice(modelChangeStart, modelChangeEnd)).toContain(- 'resolveModelEfforts(\n newModelId,\n effectiveSourceId,\n )',+ expect(source.slice(modelChangeStart, modelChangeEnd)).toMatch(+ /resolveModelEfforts\(\s*newModelId,\s*effectiveSourceId\s*\)/,);expect(source.slice(providerChangeStart, providerChangeEnd)).toContain('{ effort: eff, fastMode: restoredFast }',diff --git a/apps/desktop/src/renderer/lib/composerDraftStore.ts b/apps/desktop/src/renderer/lib/composerDraftStore.tsindex 8116797382..9da79d36b3 100644--- a/apps/desktop/src/renderer/lib/composerDraftStore.ts+++ b/apps/desktop/src/renderer/lib/composerDraftStore.ts@@ -56,6 +56,12 @@ export interface ComposerDraft {attachments: AttachedFile[];/** Plugin-page handoff consumed by ChatInput after its editor hydration. */pendingGhostId?: string;+ /**+ * Host-capability Plugin handoff. Kept separate from `pendingGhostId`+ * because command Plugins expand through `ghost_call`, while capability+ * Plugins are represented by a trusted composer atom and stay Host-owned.+ */+ pendingHostCapabilityGhostId?: string;/*** One-shot routed-entry intent: hydrate this draft, then place the caret at* the final editable position. ChatInput consumes and clears the flag so a@@ -586,6 +592,9 @@ export function saveComposerTextAfterAsyncTransition(quotes: existing?.quotes ?? [],browserComments: existing?.browserComments ?? [],...(existing?.pendingGhostId ? { pendingGhostId: existing.pendingGhostId } : {}),+ ...(existing?.pendingHostCapabilityGhostId+ ? { pendingHostCapabilityGhostId: existing.pendingHostCapabilityGhostId }+ : {}),...(existing?.focusAtEnd ? { focusAtEnd: true } : {}),},{ silent: true, preserveRemoteOptimisticRecovery: true },@@ -628,6 +637,9 @@ export function restoreRemoteOptimisticDraft(quotes: [],browserComments: currentComments,...(existing?.pendingGhostId ? { pendingGhostId: existing.pendingGhostId } : {}),+ ...(existing?.pendingHostCapabilityGhostId+ ? { pendingHostCapabilityGhostId: existing.pendingHostCapabilityGhostId }+ : {}),...(existing?.focusAtEnd ? { focusAtEnd: true } : {}),};const rememberBatchSnapshot = (draft: ComposerDraft): void => {diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.tsindex b17bb53c9d..88c9082ebd 100644--- a/apps/desktop/src/shared/__tests__/ghost.test.ts+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts@@ -89,7 +89,18 @@ describe('ghost · id 规则', () => {});it('非法:大写/下划线/路径字符/连字符开头/超长/非字符串', () => {- for (const id of ['Hello', 'a_b', '../evil', 'a/b', 'a\\b', '-abc', '', 'x'.repeat(33), 42, null]) {+ for (const id of [+ 'Hello',+ 'a_b',+ '../evil',+ 'a/b',+ 'a\\b',+ '-abc',+ '',+ 'x'.repeat(33),+ 42,+ null,+ ]) {expect(isValidGhostId(id), String(id)).toBe(false);}});@@ -133,7 +144,9 @@ describe('ghost · 清单校验', () => {return result.manifest;};const installed = makeToolManifest([{ name: 'gen_image', description: 'Generate images' }]);- const reviewed = makeToolManifest([{ name: 'gen_image', description: 'Projected description' }]);+ const reviewed = makeToolManifest([+ { name: 'gen_image', description: 'Projected description' },+ ]);const samePackage = makeToolManifest([{ name: 'gen_image', description: 'Generate images' }]);const expandedPackage = makeToolManifest([{ name: 'gen_image', description: 'Generate images' },@@ -146,14 +159,10 @@ describe('ghost · 清单校验', () => {expect(unreviewedGhostPermissionItems(reviewed, installed, samePackage)).toEqual([]);expect(unreviewedGhostPermissionItems(reviewed, installed, expandedPackage).map((item) => item.key),- ).toEqual([- 'tool:edit_image',- ]);+ ).toEqual(['tool:edit_image']);expect(unreviewedGhostPermissionItems(reviewed, installed, changedPackage).map((item) => item.key),- ).toEqual([- 'tool:gen_image',- ]);+ ).toEqual(['tool:gen_image']);});it('全字段合法清单通过,并按已知字段收窄输出', () => {@@ -222,7 +231,9 @@ describe('ghost · 清单校验', () => {expect(validateGhostManifest({ ...goodManifest(), panel: 'not-object' }).ok).toBe(false);// html 必填(declaration 时代的静态 body 面板已随单形态定案移除)expect(validateGhostManifest({ ...goodManifest(), panel: { title: 'X' } }).ok).toBe(false);- expect(validateGhostManifest({ ...goodManifest(), panel: { title: 'X', body: '正文' } }).ok).toBe(false);+ expect(+ validateGhostManifest({ ...goodManifest(), panel: { title: 'X', body: '正文' } }).ok,+ ).toBe(false);expect(withPanel({ title: '' }).ok).toBe(false);expect(withPanel({ title: 'x'.repeat(65) }).ok).toBe(false);expect(withPanel({ minWidth: 119 }).ok).toBe(false);@@ -242,23 +253,29 @@ describe('ghost · 清单校验', () => {validateGhostManifest({ ...goodManifest(), panel: { html: 'panel.html', ...panel } });// 合法:关掉 maximize / detach / 空对象(= 全默认) / 显式 true / 双键并存const off = withPanel({ systemButtons: { maximize: false } });- expect(off.ok && (off as { ok: true; manifest: GhostManifest }).manifest.panel?.systemButtons).toEqual({+ expect(+ off.ok && (off as { ok: true; manifest: GhostManifest }).manifest.panel?.systemButtons,+ ).toEqual({maximize: false,});const detachOff = withPanel({ systemButtons: { detach: false } });expect(- detachOff.ok && (detachOff as { ok: true; manifest: GhostManifest }).manifest.panel?.systemButtons,+ detachOff.ok &&+ (detachOff as { ok: true; manifest: GhostManifest }).manifest.panel?.systemButtons,).toEqual({ detach: false });const bothOff = withPanel({ systemButtons: { maximize: false, detach: false } });expect(- bothOff.ok && (bothOff as { ok: true; manifest: GhostManifest }).manifest.panel?.systemButtons,+ bothOff.ok &&+ (bothOff as { ok: true; manifest: GhostManifest }).manifest.panel?.systemButtons,).toEqual({ maximize: false, detach: false });const minimizeOff = withPanel({ systemButtons: { minimize: false } });expect(minimizeOff.ok &&(minimizeOff as { ok: true; manifest: GhostManifest }).manifest.panel?.systemButtons,).toEqual({ minimize: false });- const allOff = withPanel({ systemButtons: { maximize: false, detach: false, minimize: false } });+ const allOff = withPanel({+ systemButtons: { maximize: false, detach: false, minimize: false },+ });expect(allOff.ok && (allOff as { ok: true; manifest: GhostManifest }).manifest.panel?.systemButtons,).toEqual({ maximize: false, detach: false, minimize: false });@@ -304,30 +321,42 @@ describe('ghost · 清单校验', () => {expect(valid.ok).toBe(true);expect(valid.ok && valid.manifest.locales?.en).toBe('locales/en.json');- expect(validateGhostManifest({- ...goodManifest(),- locales: { 'zh-CN': 'locales/zh-CN.json' },- }).ok).toBe(false);- expect(validateGhostManifest({- ...goodManifest(),- locales: { en: '../en.json' },- }).ok).toBe(false);- expect(validateGhostManifest({- ...goodManifest(),- locales: { en: 'locales/en.json', fr: 'locales/fr.json' },- }).ok).toBe(false);- expect(validateGhostManifest({- ...goodManifest(),- locales: { en: 'locales/en.json', ja: 'locales/en.json' },- }).ok).toBe(false);- expect(validateGhostManifest({- ...goodManifest(),- locales: { en: 'locales/en.json', ja: 'Locales/EN.json' },- }).ok).toBe(false);- expect(validateGhostManifest({- ...goodManifest(),- locales: { en: 'GHOST.JSON' },- }).ok).toBe(false);+ expect(+ validateGhostManifest({+ ...goodManifest(),+ locales: { 'zh-CN': 'locales/zh-CN.json' },+ }).ok,+ ).toBe(false);+ expect(+ validateGhostManifest({+ ...goodManifest(),+ locales: { en: '../en.json' },+ }).ok,+ ).toBe(false);+ expect(+ validateGhostManifest({+ ...goodManifest(),+ locales: { en: 'locales/en.json', fr: 'locales/fr.json' },+ }).ok,+ ).toBe(false);+ expect(+ validateGhostManifest({+ ...goodManifest(),+ locales: { en: 'locales/en.json', ja: 'locales/en.json' },+ }).ok,+ ).toBe(false);+ expect(+ validateGhostManifest({+ ...goodManifest(),+ locales: { en: 'locales/en.json', ja: 'Locales/EN.json' },+ }).ok,+ ).toBe(false);+ expect(+ validateGhostManifest({+ ...goodManifest(),+ locales: { en: 'GHOST.JSON' },+ }).ok,+ ).toBe(false);});it('locale 选择完全跟随宿主,插件不支持或宿主值未知时固定回退英文', () => {@@ -381,26 +410,29 @@ describe('ghost · 清单校验', () => {});expect(parsed.ok).toBe(true);if (!parsed.ok) return;- const resource = validateGhostManifestLocaleResource({- name: 'Localized',- description: 'Localized description',- whenToUse: 'Localized routing',- tools: {- beta: { description: 'Localized beta' },- alpha: {- description: 'Localized alpha',- parameters: {- '': { title: 'Localized arguments' },- '/properties/query': {- title: 'Localized query',- description: 'Localized query description',+ const resource = validateGhostManifestLocaleResource(+ {+ name: 'Localized',+ description: 'Localized description',+ whenToUse: 'Localized routing',+ tools: {+ beta: { description: 'Localized beta' },+ alpha: {+ description: 'Localized alpha',+ parameters: {+ '': { title: 'Localized arguments' },+ '/properties/query': {+ title: 'Localized query',+ description: 'Localized query description',+ },+ '/properties/mode/oneOf/0': { title: 'Localized fast mode' },+ '/properties/mode/oneOf/1': { title: 'Localized safe mode' },},- '/properties/mode/oneOf/0': { title: 'Localized fast mode' },- '/properties/mode/oneOf/1': { title: 'Localized safe mode' },},},},- }, parsed.manifest);+ parsed.manifest,+ );expect(resource.ok).toBe(true);if (!resource.ok) return;expect(resolveGhostManifestLocale(parsed.manifest, resource.resource)).toMatchObject({@@ -419,10 +451,7 @@ describe('ghost · 清单校验', () => {description: 'Localized query description',},mode: {- oneOf: [- { title: 'Localized fast mode' },- { title: 'Localized safe mode' },- ],+ oneOf: [{ title: 'Localized fast mode' }, { title: 'Localized safe mode' }],},},},@@ -432,10 +461,13 @@ describe('ghost · 清单校验', () => {});// 部分翻译是合法状态:只翻 alpha 的 description(不翻参数、不翻 beta),// 缺失条目解析时回退原文。- const partial = validateGhostManifestLocaleResource({- name: 'Partial',- tools: { alpha: { description: 'Only alpha' } },- }, parsed.manifest);+ const partial = validateGhostManifestLocaleResource(+ {+ name: 'Partial',+ tools: { alpha: { description: 'Only alpha' } },+ },+ parsed.manifest,+ );expect(partial.ok, JSON.stringify(partial)).toBe(true);if (!partial.ok) return;expect(resolveGhostManifestLocale(parsed.manifest, partial.resource)).toMatchObject({@@ -460,17 +492,28 @@ describe('ghost · 清单校验', () => {if (!empty.ok) return;expect(resolveGhostManifestLocale(parsed.manifest, empty.resource)).toMatchObject({name: 'Base',- tools: [{ name: 'alpha', description: 'Base alpha' }, { name: 'beta', description: 'Base beta' }],+ tools: [+ { name: 'alpha', description: 'Base alpha' },+ { name: 'beta', description: 'Base beta' },+ ],});// 参数翻译允许只覆盖部分 pointer,未覆盖的回退。- const partialParams = validateGhostManifestLocaleResource({- tools: {- alpha: {- description: 'Localized alpha',- parameters: { '/properties/query': { title: 'Localized query', description: 'Localized query description' } },+ const partialParams = validateGhostManifestLocaleResource(+ {+ tools: {+ alpha: {+ description: 'Localized alpha',+ parameters: {+ '/properties/query': {+ title: 'Localized query',+ description: 'Localized query description',+ },+ },+ },},},- }, parsed.manifest);+ parsed.manifest,+ );expect(partialParams.ok, JSON.stringify(partialParams)).toBe(true);if (!partialParams.ok) return;expect(resolveGhostManifestLocale(parsed.manifest, partialParams.resource)).toMatchObject({@@ -479,30 +522,59 @@ describe('ghost · 清单校验', () => {name: 'alpha',parameters: {title: 'Base arguments',- properties: { query: { title: 'Localized query', description: 'Localized query description' } },+ properties: {+ query: { title: 'Localized query', description: 'Localized query description' },+ },},},{ name: 'beta', description: 'Base beta' },],});// 翻译错位仍是硬错误:未知工具 / 未知 pointer / 未知字段 / 提供了条目却缺 description。- expect(validateGhostManifestLocaleResource({- tools: { gamma: { description: 'No such tool' } },- }, parsed.manifest).ok).toBe(false);- expect(validateGhostManifestLocaleResource({- tools: { alpha: { description: 'x', parameters: { '/properties/nope': { title: 'x' } } } },- }, parsed.manifest).ok).toBe(false);- expect(validateGhostManifestLocaleResource({- tools: { beta: { description: 'x', parameters: { '': { title: 'x' } } } },- }, parsed.manifest).ok).toBe(false);- expect(validateGhostManifestLocaleResource({- tools: { alpha: {} },- }, parsed.manifest).ok).toBe(false);- expect(validateGhostManifestLocaleResource({- description: 'x',- whenToUse: 'x',- extra: 'x',- }, parsed.manifest).ok).toBe(false);+ expect(+ validateGhostManifestLocaleResource(+ {+ tools: { gamma: { description: 'No such tool' } },+ },+ parsed.manifest,+ ).ok,+ ).toBe(false);+ expect(+ validateGhostManifestLocaleResource(+ {+ tools: {+ alpha: { description: 'x', parameters: { '/properties/nope': { title: 'x' } } },+ },+ },+ parsed.manifest,+ ).ok,+ ).toBe(false);+ expect(+ validateGhostManifestLocaleResource(+ {+ tools: { beta: { description: 'x', parameters: { '': { title: 'x' } } } },+ },+ parsed.manifest,+ ).ok,+ ).toBe(false);+ expect(+ validateGhostManifestLocaleResource(+ {+ tools: { alpha: {} },+ },+ parsed.manifest,+ ).ok,+ ).toBe(false);+ expect(+ validateGhostManifestLocaleResource(+ {+ description: 'x',+ whenToUse: 'x',+ extra: 'x',+ },+ parsed.manifest,+ ).ok,+ ).toBe(false);});it('locale 资源覆盖宿主持有的面板、凭证、连接与 setup 标签;标签可部分提供', () => {@@ -517,28 +589,34 @@ describe('ghost · 清单校验', () => {panel: { title: 'Base panel', html: 'panel.html' },network: {hosts: ['api.example.com'],- secrets: [{- key: 'api_key',- label: 'Base API key',- hint: 'Base secret hint',- inject: { header: 'Authorization', format: 'Bearer {value}' },- }],- connections: [{- key: 'instance',- label: 'Base instance',- hint: 'Base connection hint',- inject: { header: 'Authorization', format: 'Bearer {value}' },- }],+ secrets: [+ {+ key: 'api_key',+ label: 'Base API key',+ hint: 'Base secret hint',+ inject: { header: 'Authorization', format: 'Bearer {value}' },+ },+ ],+ connections: [+ {+ key: 'instance',+ label: 'Base instance',+ hint: 'Base connection hint',+ inject: { header: 'Authorization', format: 'Bearer {value}' },+ },+ ],},node: {entry: 'node/worker.cjs',protocol: 'json-rpc-stdio',- secretBindings: [{- key: 'worker_key',- label: 'Base worker key',- hint: 'Base worker hint',- methods: ['run'],- }],+ secretBindings: [+ {+ key: 'worker_key',+ label: 'Base worker key',+ hint: 'Base worker hint',+ methods: ['run'],+ },+ ],},setup: {requires: [{ anyOf: [{ kv: 'default_repo', label: 'Base repository' }] }],@@ -546,62 +624,76 @@ describe('ghost · 清单校验', () => {});expect(parsed.ok).toBe(true);if (!parsed.ok) return;- const resource = validateGhostManifestLocaleResource({- name: 'Localized',- panel: { title: 'Localized panel' },- network: {- secrets: {- api_key: { label: 'Localized API key', hint: 'Localized secret hint' },- },- connections: {- instance: { label: 'Localized instance', hint: 'Localized connection hint' },+ const resource = validateGhostManifestLocaleResource(+ {+ name: 'Localized',+ panel: { title: 'Localized panel' },+ network: {+ secrets: {+ api_key: { label: 'Localized API key', hint: 'Localized secret hint' },+ },+ connections: {+ instance: { label: 'Localized instance', hint: 'Localized connection hint' },+ },},- },- node: {- secretBindings: {- worker_key: { label: 'Localized worker key', hint: 'Localized worker hint' },+ node: {+ secretBindings: {+ worker_key: { label: 'Localized worker key', hint: 'Localized worker hint' },+ },},- },- setup: {- kv: {- default_repo: { label: 'Localized repository' },+ setup: {+ kv: {+ default_repo: { label: 'Localized repository' },+ },},},- }, parsed.manifest);+ parsed.manifest,+ );expect(resource.ok).toBe(true);if (!resource.ok) return;expect(resolveGhostManifestLocale(parsed.manifest, resource.resource)).toMatchObject({panel: { title: 'Localized panel' },network: {- secrets: [{- key: 'api_key',- label: 'Localized API key',- hint: 'Localized secret hint',- }],- connections: [{- key: 'instance',- label: 'Localized instance',- hint: 'Localized connection hint',- }],+ secrets: [+ {+ key: 'api_key',+ label: 'Localized API key',+ hint: 'Localized secret hint',+ },+ ],+ connections: [+ {+ key: 'instance',+ label: 'Localized instance',+ hint: 'Localized connection hint',+ },+ ],},node: {- secretBindings: [{- key: 'worker_key',- label: 'Localized worker key',- hint: 'Localized worker hint',- }],+ secretBindings: [+ {+ key: 'worker_key',+ label: 'Localized worker key',+ hint: 'Localized worker hint',+ },+ ],},setup: {- requires: [{- anyOf: [{ kind: 'kv', key: 'default_repo', label: 'Localized repository' }],- }],+ requires: [+ {+ anyOf: [{ kind: 'kv', key: 'default_repo', label: 'Localized repository' }],+ },+ ],},});// 只翻面板标题、不翻凭证/连接/kv 也合法,缺失标签回退原文。- const panelOnly = validateGhostManifestLocaleResource({- name: 'Partial labels',- panel: { title: 'Localized panel' },- }, parsed.manifest);+ const panelOnly = validateGhostManifestLocaleResource(+ {+ name: 'Partial labels',+ panel: { title: 'Localized panel' },+ },+ parsed.manifest,+ );expect(panelOnly.ok, JSON.stringify(panelOnly)).toBe(true);if (!panelOnly.ok) return;expect(resolveGhostManifestLocale(parsed.manifest, panelOnly.resource)).toMatchObject({@@ -611,12 +703,17 @@ describe('ghost · 清单校验', () => {connections: [{ key: 'instance', label: 'Base instance' }],},node: { secretBindings: [{ key: 'worker_key', label: 'Base worker key' }] },- setup: { requires: [{ anyOf: [{ kind: 'kv', key: 'default_repo', label: 'Base repository' }] }] },+ setup: {+ requires: [{ anyOf: [{ kind: 'kv', key: 'default_repo', label: 'Base repository' }] }],+ },});// 提供的标签条目 label 必填、hint 可省(缺 hint 回退原文);未知 key 仍拒。- const labelNoHint = validateGhostManifestLocaleResource({- network: { secrets: { api_key: { label: 'Localized API key' } } },- }, parsed.manifest);+ const labelNoHint = validateGhostManifestLocaleResource(+ {+ network: { secrets: { api_key: { label: 'Localized API key' } } },+ },+ parsed.manifest,+ );expect(labelNoHint.ok, JSON.stringify(labelNoHint)).toBe(true);if (!labelNoHint.ok) return;expect(resolveGhostManifestLocale(parsed.manifest, labelNoHint.resource)).toMatchObject({@@ -624,15 +721,30 @@ describe('ghost · 清单校验', () => {secrets: [{ key: 'api_key', label: 'Localized API key', hint: 'Base secret hint' }],},});- expect(validateGhostManifestLocaleResource({- network: { secrets: { nope: { label: 'x' } } },- }, parsed.manifest).ok).toBe(false);- expect(validateGhostManifestLocaleResource({- network: { secrets: { api_key: { hint: 'hint without label' } } },- }, parsed.manifest).ok).toBe(false);- expect(validateGhostManifestLocaleResource({- setup: { kv: { default_repo: { label: 'x', hint: 'kv 未声明 hint' } } },- }, parsed.manifest).ok).toBe(false);+ expect(+ validateGhostManifestLocaleResource(+ {+ network: { secrets: { nope: { label: 'x' } } },+ },+ parsed.manifest,+ ).ok,+ ).toBe(false);+ expect(+ validateGhostManifestLocaleResource(+ {+ network: { secrets: { api_key: { hint: 'hint without label' } } },+ },+ parsed.manifest,+ ).ok,+ ).toBe(false);+ expect(+ validateGhostManifestLocaleResource(+ {+ setup: { kv: { default_repo: { label: 'x', hint: 'kv 未声明 hint' } } },+ },+ parsed.manifest,+ ).ok,+ ).toBe(false);});it('locale 外部 key 累加器使用无原型字典,JSON 自有 __proto__ 属性不会丢失', () => {@@ -654,8 +766,12 @@ describe('ghost · 清单校验', () => {expect(resource.ok).toBe(true);if (!resource.ok) return;expect(Object.getPrototypeOf(resource.resource.setup?.kv)).toBeNull();- expect(Object.prototype.hasOwnProperty.call(resource.resource.setup?.kv, '__proto__')).toBe(true);- expect(resolveGhostManifestLocale(manifest, resource.resource).setup?.requires[0]?.anyOf[0]).toEqual({+ expect(Object.prototype.hasOwnProperty.call(resource.resource.setup?.kv, '__proto__')).toBe(+ true,+ );+ expect(+ resolveGhostManifestLocale(manifest, resource.resource).setup?.requires[0]?.anyOf[0],+ ).toEqual({kind: 'kv',key: '__proto__',label: 'Localized label',@@ -664,9 +780,13 @@ describe('ghost · 清单校验', () => {it('icon:可选包内相对路径,扩展名白名单;非法路径/扩展名 → 拒', () => {const base = validateGhostManifest({ ...goodManifest(), icon: 'assets/icon.png' });- expect(base.ok && (base as { ok: true; manifest: GhostManifest }).manifest.icon).toBe('assets/icon.png');+ expect(base.ok && (base as { ok: true; manifest: GhostManifest }).manifest.icon).toBe(+ 'assets/icon.png',+ );const chip = validateGhostManifest({ ...goodChipManifest(), icon: 'icon.webp' });- expect(chip.ok && (chip as { ok: true; manifest: GhostManifest }).manifest.icon).toBe('icon.webp');+ expect(chip.ok && (chip as { ok: true; manifest: GhostManifest }).manifest.icon).toBe(+ 'icon.webp',+ );// 大小写不敏感的扩展名expect(validateGhostManifest({ ...goodManifest(), icon: 'ICON.PNG' }).ok).toBe(true);for (const icon of ['../evil.png', '/abs.png', 'a\\b.png', 'icon.svg', 'icon.js', 'icon', 42]) {@@ -699,8 +819,12 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {it('slots 必填非空、只认已知卡槽、不许重复', () => {expect(validateGhostManifest({ ...goodChipManifest(), slots: undefined }).ok).toBe(false);expect(validateGhostManifest({ ...goodChipManifest(), slots: [] }).ok).toBe(false);- expect(validateGhostManifest({ ...goodChipManifest(), slots: ['panel', 'filesystem'] }).ok).toBe(false);- expect(validateGhostManifest({ ...goodChipManifest(), slots: ['model', 'model'] }).ok).toBe(false);+ expect(+ validateGhostManifest({ ...goodChipManifest(), slots: ['panel', 'filesystem'] }).ok,+ ).toBe(false);+ expect(validateGhostManifest({ ...goodChipManifest(), slots: ['model', 'model'] }).ok).toBe(+ false,+ );const noPanel = goodChipManifest();noPanel.slots = ['subscribe', 'tool', 'card', 'model'];noPanel.tools = [{ name: 'do_thing', description: '做点事' }];@@ -932,12 +1056,12 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {expect(withNode({ entry: 'node/a.txt', protocol: 'json-rpc-stdio' }).ok).toBe(false);expect(withNode({ entry: 'node/a.mjs', protocol: 'json-rpc-stdio' }).ok).toBe(false);expect(withNode({ entry: 'node/a.cjs', protocol: 'stdio' }).ok).toBe(false);- expect(- withNode({ entry: 'node/a.cjs', protocol: 'json-rpc-stdio', command: 'node' }).ok,- ).toBe(false);- expect(- withNode({ entry: 'node/a.cjs', protocol: 'json-rpc-stdio', args: ['--x'] }).ok,- ).toBe(false);+ expect(withNode({ entry: 'node/a.cjs', protocol: 'json-rpc-stdio', command: 'node' }).ok).toBe(+ false,+ );+ expect(withNode({ entry: 'node/a.cjs', protocol: 'json-rpc-stdio', args: ['--x'] }).ok).toBe(+ false,+ );expect(withNode({entry: 'node/a.cjs',@@ -947,7 +1071,9 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {}).ok,).toBe(false);expect(withNode({ entry: 'node/a.cjs', protocol: 'json-rpc-stdio' }, ['panel']).ok).toBe(false);- expect(validateGhostManifest({ ...goodChipManifest(), slots: ['panel', 'node'] }).ok).toBe(false);+ expect(validateGhostManifest({ ...goodChipManifest(), slots: ['panel', 'node'] }).ok).toBe(+ false,+ );});it('node.secretBindings 逐方法声明保险库凭证并生成单独权限项', () => {@@ -1102,17 +1228,24 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {const withTools = (slots: string[], tools: unknown) =>validateGhostManifest({ ...goodChipManifest(), slots, tools });// 成对:有 tool 槽必须有 tools,反之亦然- expect(validateGhostManifest({ ...goodChipManifest(), slots: ['panel', 'tool'] }).ok).toBe(false);+ expect(validateGhostManifest({ ...goodChipManifest(), slots: ['panel', 'tool'] }).ok).toBe(+ false,+ );expect(withTools(['panel'], [{ name: 'x', description: 'y' }]).ok).toBe(false);// 合法- expect(withTools(['panel', 'tool'], [{ name: 'gen_image', description: '生成图片' }]).ok).toBe(true);+ expect(withTools(['panel', 'tool'], [{ name: 'gen_image', description: '生成图片' }]).ok).toBe(+ true,+ );// 名字非法 / 重名 / 描述空 / 超 16 条expect(withTools(['panel', 'tool'], [{ name: 'Bad', description: 'y' }]).ok).toBe(false);expect(- withTools(['panel', 'tool'], [- { name: 'a', description: 'y' },- { name: 'a', description: 'z' },- ]).ok,+ withTools(+ ['panel', 'tool'],+ [+ { name: 'a', description: 'y' },+ { name: 'a', description: 'z' },+ ],+ ).ok,).toBe(false);expect(withTools(['panel', 'tool'], [{ name: 'a', description: '' }]).ok).toBe(false);expect(@@ -1153,14 +1286,7 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {slots: ['panel', 'tool'],tools: [{ name: 'search_issues', description: '只读搜索议题' }],};- for (const legacyValue of [- null,- true,- 'legacy',- [],- {},- { label: 'Issues' },- ]) {+ for (const legacyValue of [null, true, 'legacy', [], {}, { label: 'Issues' }]) {const result = validateGhostManifest({...base,atResourceProvider: legacyValue,@@ -1171,12 +1297,14 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {it('@ 资源入口复用 tool 槽,不新增硬白名单 slot', () => {expect(GHOST_SLOTS).not.toContain('at-resource');- expect(validateGhostManifest({- ...goodChipManifest(),- slots: ['panel', 'tool', 'at-resource'],- tools: [{ name: 'search_issues', description: '只读搜索议题' }],- atResourceProvider: { tool: 'search_issues' },- }).ok).toBe(false);+ expect(+ validateGhostManifest({+ ...goodChipManifest(),+ slots: ['panel', 'tool', 'at-resource'],+ tools: [{ name: 'search_issues', description: '只读搜索议题' }],+ atResourceProvider: { tool: 'search_issues' },+ }).ok,+ ).toBe(false);});it('@ 资源入口复用原工具执行权,但作为新增调用入口单独披露', () => {@@ -1207,58 +1335,83 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {};for (const key of reservedKeys) {- expect(validateGhostManifest(withoutPanel({- ...goodManifest(),- slots: ['tool'],- tools: [{ name: key, description: 'Reserved tool' }],- })).ok, `tool ${key}`).toBe(false);+ expect(+ validateGhostManifest(+ withoutPanel({+ ...goodManifest(),+ slots: ['tool'],+ tools: [{ name: key, description: 'Reserved tool' }],+ }),+ ).ok,+ `tool ${key}`,+ ).toBe(false);- expect(validateGhostManifest({- ...goodManifest(),- settingsHtml: 'settings.html',- slots: ['panel', 'network'],- network: {- hosts: ['api.example.com'],- secrets: [{- key,- label: 'Reserved secret',- inject: { header: 'Authorization', format: 'Bearer {value}' },- }],- },- }).ok, `network secret ${key}`).toBe(false);+ expect(+ validateGhostManifest({+ ...goodManifest(),+ settingsHtml: 'settings.html',+ slots: ['panel', 'network'],+ network: {+ hosts: ['api.example.com'],+ secrets: [+ {+ key,+ label: 'Reserved secret',+ inject: { header: 'Authorization', format: 'Bearer {value}' },+ },+ ],+ },+ }).ok,+ `network secret ${key}`,+ ).toBe(false);- expect(validateGhostManifest({- ...goodManifest(),- settingsHtml: 'settings.html',- slots: ['panel', 'network'],- network: {- hosts: [],- connections: [{- key,- label: 'Reserved connection',- inject: { header: 'Authorization', format: 'Bearer {value}' },- }],- },- }).ok, `network connection ${key}`).toBe(false);+ expect(+ validateGhostManifest({+ ...goodManifest(),+ settingsHtml: 'settings.html',+ slots: ['panel', 'network'],+ network: {+ hosts: [],+ connections: [+ {+ key,+ label: 'Reserved connection',+ inject: { header: 'Authorization', format: 'Bearer {value}' },+ },+ ],+ },+ }).ok,+ `network connection ${key}`,+ ).toBe(false);- expect(validateGhostManifest({- ...goodManifest(),- settingsHtml: 'settings.html',- slots: ['panel', 'node'],- node: {- entry: 'node/worker.cjs',- protocol: 'json-rpc-stdio',- secretBindings: [{ key, label: 'Reserved node secret', methods: ['run'] }],- },- }).ok, `node secret ${key}`).toBe(false);+ expect(+ validateGhostManifest({+ ...goodManifest(),+ settingsHtml: 'settings.html',+ slots: ['panel', 'node'],+ node: {+ entry: 'node/worker.cjs',+ protocol: 'json-rpc-stdio',+ secretBindings: [{ key, label: 'Reserved node secret', methods: ['run'] }],+ },+ }).ok,+ `node secret ${key}`,+ ).toBe(false);- expect(validateGhostManifest(JSON.parse(JSON.stringify({- ...goodManifest(),- settingsHtml: 'settings.html',- setup: {- requires: [{ anyOf: [{ kv: key, label: 'Reserved setup value' }] }],- },- }))).ok, `setup kv ${key}`).toBe(false);+ expect(+ validateGhostManifest(+ JSON.parse(+ JSON.stringify({+ ...goodManifest(),+ settingsHtml: 'settings.html',+ setup: {+ requires: [{ anyOf: [{ kv: key, label: 'Reserved setup value' }] }],+ },+ }),+ ),+ ).ok,+ `setup kv ${key}`,+ ).toBe(false);}});@@ -1289,8 +1442,12 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {});it('settingsHtml 可选,给了必须是安全相对路径', () => {- expect(validateGhostManifest({ ...goodChipManifest(), settingsHtml: 'settings.html' }).ok).toBe(true);- expect(validateGhostManifest({ ...goodChipManifest(), settingsHtml: '../s.html' }).ok).toBe(false);+ expect(validateGhostManifest({ ...goodChipManifest(), settingsHtml: 'settings.html' }).ok).toBe(+ true,+ );+ expect(validateGhostManifest({ ...goodChipManifest(), settingsHtml: '../s.html' }).ok).toBe(+ false,+ );});});@@ -1547,7 +1704,10 @@ describe('ghost · model → cindy 旧名兼容(2026-07-11 更名)', () => {});expect(both.ok && both.manifest.cindy).toEqual({ image: ['generate', 'edit'] });- const dup = validateGhostManifest({ ...goodChipManifest(), slots: ['panel', 'model', 'cindy'] });+ const dup = validateGhostManifest({+ ...goodChipManifest(),+ slots: ['panel', 'model', 'cindy'],+ });expect(dup.ok).toBe(false);});});@@ -1580,13 +1740,15 @@ describe('ghost · subscribe 订阅详单校验(卡槽①,2026-07-12)', () => {it('未知主题/钩子/空对象/空数组/无槽有详单一律拒', () => {expect(validateGhostManifest(withSub({ topics: ['messages'] })).ok).toBe(false);- expect(validateGhostManifest(withSub({ hooks: ['will-tool-call'] }, { launch: 'resident' })).ok).toBe(false);+ expect(+ validateGhostManifest(withSub({ hooks: ['will-tool-call'] }, { launch: 'resident' })).ok,+ ).toBe(false);expect(validateGhostManifest(withSub({})).ok).toBe(false);expect(validateGhostManifest(withSub({ topics: [] })).ok).toBe(false);expect(validateGhostManifest(withSub({ topics: ['turn', 'turn'] })).ok).toBe(false);- expect(- validateGhostManifest({ ...goodManifest(), subscribe: { topics: ['turn'] } }).ok,- ).toBe(false); // slots 没含 subscribe+ expect(validateGhostManifest({ ...goodManifest(), subscribe: { topics: ['turn'] } }).ok).toBe(+ false,+ ); // slots 没含 subscribe});it('有槽无详单允许装入(零事件,老包语义)', () => {@@ -1623,7 +1785,9 @@ describe('ghost · subscribe 订阅详单校验(卡槽①,2026-07-12)', () => {'subscribe:topics:activity',);expect(- ghostPermissionItems(withActivity.manifest).find((i) => i.key === 'subscribe:topics:activity'),+ ghostPermissionItems(withActivity.manifest).find(+ (i) => i.key === 'subscribe:topics:activity',+ ),).toMatchObject({ labelKey: 'subscribeActivity', detailKey: 'subscribeActivityDetail' });// 存量插件更新时新增 activity 必须被权限扩张检测抓到(plugin-market 要求复核)。@@ -1632,9 +1796,9 @@ describe('ghost · subscribe 订阅详单校验(卡槽①,2026-07-12)', () => {// 只动 turn / session 的存量插件权限清单不 churn(批准状态不受影响)。expect(diffGhostPermissionItems(turnOnly.manifest, turnAndSession.manifest).added).toEqual([]);- expect(ghostPermissionItems(turnAndSession.manifest).filter((i) => i.kind === 'subscribe')).toEqual(- ghostPermissionItems(turnOnly.manifest).filter((i) => i.kind === 'subscribe'),- );+ expect(+ ghostPermissionItems(turnAndSession.manifest).filter((i) => i.kind === 'subscribe'),+ ).toEqual(ghostPermissionItems(turnOnly.manifest).filter((i) => i.kind === 'subscribe'));// 取消订阅 activity 应报为 removed。expect(@@ -1667,10 +1831,7 @@ describe('ghost · subscribe 订阅详单校验(卡槽①,2026-07-12)', () => {expect(noResident.ok).toBe(false); // resident 要求 key 在 hooks 非空,自动覆盖新钩子const both = validateGhostManifest(- withSub(- { hooks: ['will-user-message', 'will-assistant-message'] },- { launch: 'resident' },- ),+ withSub({ hooks: ['will-user-message', 'will-assistant-message'] }, { launch: 'resident' }),);expect(both.ok).toBe(true);if (both.ok) {@@ -1702,7 +1863,10 @@ describe('ghost · description(自我介绍)', () => {expect(chip.ok && chip.manifest.description).toBe('画图小助手');for (const bad of ['', ' ', 'x'.repeat(301), 42]) {- expect(validateGhostManifest({ ...goodManifest(), description: bad }).ok, JSON.stringify(bad)).toBe(false);+ expect(+ validateGhostManifest({ ...goodManifest(), description: bad }).ok,+ JSON.stringify(bad),+ ).toBe(false);}});});@@ -1735,7 +1899,11 @@ describe('ghost · panel.position 校验', () => {expect(tab.ok && tab.manifest.panel?.position).toBe('tab');// 页签没有拖缝宽度语义:带停靠专属字段必须明确拒绝,不静默忽略(规则 9)。- for (const extra of [{ minWidth: 240 }, { defaultFraction: 0.2 }, { minWidth: 240, defaultFraction: 0.2 }]) {+ for (const extra of [+ { minWidth: 240 },+ { defaultFraction: 0.2 },+ { minWidth: 240, defaultFraction: 0.2 },+ ]) {const v = validateGhostManifest({...goodManifest(),panel: { title: 'Hello', html: 'panel.html', position: 'tab', ...extra },@@ -1751,7 +1919,9 @@ describe('ghost · whenToUse(语义召回线索)', () => {const chip = validateGhostManifest({ ...goodChipManifest(), whenToUse: '需要出图时找我' });expect(chip.ok && chip.manifest.whenToUse).toBe('需要出图时找我');expect(validateGhostManifest({ ...goodChipManifest(), whenToUse: '' }).ok).toBe(false);- expect(validateGhostManifest({ ...goodChipManifest(), whenToUse: 'x'.repeat(301) }).ok).toBe(false);+ expect(validateGhostManifest({ ...goodChipManifest(), whenToUse: 'x'.repeat(301) }).ok).toBe(+ false,+ );});});@@ -1809,16 +1979,21 @@ describe('ghost · cindy 详单 video 类目', () => {});it('权限清单推导:video 详单产出对应权限项(确认框自动吃到)', () => {- const v = validateGhostManifest(withCindy({ image: ['generate'], video: ['generate', 'edit'] }));+ const v = validateGhostManifest(+ withCindy({ image: ['generate'], video: ['generate', 'edit'] }),+ );expect(v.ok).toBe(true);if (!v.ok) return;- const keys = ghostPermissionItems(v.manifest).filter((i) => i.kind === 'cindy').map((i) => i.key);+ const keys = ghostPermissionItems(v.manifest)+ .filter((i) => i.kind === 'cindy')+ .map((i) => i.key);expect(keys).toEqual(['cindy:image.generate', 'cindy:video.generate', 'cindy:video.edit']);- const labels = ghostPermissionItems(v.manifest).filter((i) => i.kind === 'cindy').map((i) => i.labelKey);+ const labels = ghostPermissionItems(v.manifest)+ .filter((i) => i.kind === 'cindy')+ .map((i) => i.labelKey);expect(labels).toContain('cindyVideoGenerate');expect(labels).toContain('cindyVideoEdit');});-});describe('ghost · 逐项权限清单', () => {@@ -1852,7 +2027,12 @@ describe('ghost · 逐项权限清单', () => {'code',]);const tool = items.find((i) => i.key === 'tool:gen_image');- expect(tool).toMatchObject({ kind: 'tool', labelKey: 'tool', labelArgs: { name: 'gen_image' }, detail: '出图' });+ expect(tool).toMatchObject({+ kind: 'tool',+ labelKey: 'tool',+ labelArgs: { name: 'gen_image' },+ detail: '出图',+ });const panel = items.find((i) => i.kind === 'panel');expect(panel).toMatchObject({ labelKey: 'panelLeft', labelArgs: { title: '画廊' } });expect(items.find((i) => i.kind === 'code')).toMatchObject({ detailKey: 'codeDetail' });@@ -1874,7 +2054,10 @@ describe('ghost · 逐项权限清单', () => {expect(items[0]).toMatchObject({ labelKey: 'panelLeft', labelArgs: { title: '说明书' } });// 页签形态在确认框同样逐项如实展示(labelKey 独立成 panelTab)。- const tabbed = ghostPermissionItems({ ...plain, panel: { html: 'panel.html', position: 'tab' } });+ const tabbed = ghostPermissionItems({+ ...plain,+ panel: { html: 'panel.html', position: 'tab' },+ });expect(tabbed.map((i) => i.key)).toEqual(['panel:tab', 'code']);expect(tabbed[0]).toMatchObject({ labelKey: 'panelTab', labelArgs: { title: '说明书' } });@@ -1935,12 +2118,29 @@ describe('ghost · setup 就绪声明校验(使用前置检查,2026-07-21)', ()network: {hosts: ['api.example.com'],secrets: [- { key: 'api_key_a', label: 'Key A', inject: { header: 'Authorization', format: 'Bearer {value}' } },- { key: 'api_key_b', label: 'Key B', inject: { header: 'Authorization', format: 'Bearer {value}' } },- { key: 'mail_ident', label: '登录身份', source: 'login-email', inject: { header: 'X-User', format: '{value}' } },+ {+ key: 'api_key_a',+ label: 'Key A',+ inject: { header: 'Authorization', format: 'Bearer {value}' },+ },+ {+ key: 'api_key_b',+ label: 'Key B',+ inject: { header: 'Authorization', format: 'Bearer {value}' },+ },+ {+ key: 'mail_ident',+ label: '登录身份',+ source: 'login-email',+ inject: { header: 'X-User', format: '{value}' },+ },],connections: [- { key: 'inst_conn', label: '实例连接', inject: { header: 'PRIVATE-TOKEN', format: '{value}' } },+ {+ key: 'inst_conn',+ label: '实例连接',+ inject: { header: 'PRIVATE-TOKEN', format: '{value}' },+ },],},};@@ -1960,8 +2160,18 @@ describe('ghost · setup 就绪声明校验(使用前置检查,2026-07-21)', ()if (!result.ok) return;expect(result.manifest.setup).toEqual({requires: [- { anyOf: [{ kind: 'secret', key: 'api_key_a' }, { kind: 'secret', key: 'api_key_b' }] },- { anyOf: [{ kind: 'connection', key: 'inst_conn' }, { kind: 'kv', key: 'default_repo', label: '默认仓库' }] },+ {+ anyOf: [+ { kind: 'secret', key: 'api_key_a' },+ { kind: 'secret', key: 'api_key_b' },+ ],+ },+ {+ anyOf: [+ { kind: 'connection', key: 'inst_conn' },+ { kind: 'kv', key: 'default_repo', label: '默认仓库' },+ ],+ },],});});@@ -2060,7 +2270,9 @@ describe('ghost · setup 就绪声明校验(使用前置检查,2026-07-21)', ()const optOut = validateGhostManifest({ ...setupBase(), setup: { requires: [] } });expect(optOut.ok).toBe(true);if (optOut.ok) expect(optOut.manifest.setup).toEqual({ requires: [] });- expect(validateGhostManifest({ ...setupBase(), setup: { requires: [{ anyOf: [] }] } }).ok).toBe(false);+ expect(validateGhostManifest({ ...setupBase(), setup: { requires: [{ anyOf: [] }] } }).ok).toBe(+ false,+ );});});@@ -2122,9 +2334,20 @@ describe('ghost · network 域名条目格式与匹配', () => {it('非法条目:裸 TLD/单段/IP/端口/路径/协议/大写/中缀通配', () => {for (const p of [- 'com', '*.com', 'localhost', '127.0.0.1', 'api.example.com:8080',- 'api.example.com/v1', 'https://api.example.com', 'API.Example.com',- 'a.*.example.com', 'api.*.com', '', 42, null, '-bad.example.com',+ 'com',+ '*.com',+ 'localhost',+ '127.0.0.1',+ 'api.example.com:8080',+ 'api.example.com/v1',+ 'https://api.example.com',+ 'API.Example.com',+ 'a.*.example.com',+ 'api.*.com',+ '',+ 42,+ null,+ '-bad.example.com',]) {expect(isValidGhostNetworkHostPattern(p), String(p)).toBe(false);}@@ -2161,19 +2384,28 @@ describe('ghost · network 详单校验', () => {it('hosts 合法放行并归一化(小写化/去首尾空白)', () => {const r = validateGhostManifest(withNet({ hosts: [' API.Search.Brave.com ', '*.tavily.com'] }));expect(r.ok).toBe(true);- if (r.ok) expect(r.manifest.network).toEqual({ hosts: ['api.search.brave.com', '*.tavily.com'] });+ if (r.ok)+ expect(r.manifest.network).toEqual({ hosts: ['api.search.brave.com', '*.tavily.com'] });});it('hosts 缺失/空/超上限/重复/非法条目一律拒', () => {expect(validateGhostManifest(withNet({})).ok).toBe(false);expect(validateGhostManifest(withNet({ hosts: [] })).ok).toBe(false);- expect(validateGhostManifest(withNet({ hosts: Array.from({ length: 9 }, (_, i) => `h${i}.example.com`) })).ok).toBe(false);- expect(validateGhostManifest(withNet({ hosts: ['a.example.com', 'A.Example.com'] })).ok).toBe(false);+ expect(+ validateGhostManifest(+ withNet({ hosts: Array.from({ length: 9 }, (_, i) => `h${i}.example.com`) }),+ ).ok,+ ).toBe(false);+ expect(validateGhostManifest(withNet({ hosts: ['a.example.com', 'A.Example.com'] })).ok).toBe(+ false,+ );expect(validateGhostManifest(withNet({ hosts: ['localhost'] })).ok).toBe(false);});it('成对约束:有详单必有槽;有槽无详单允许装入(零能力)', () => {- expect(validateGhostManifest({ ...goodManifest(), network: { hosts: ['api.example.com'] } }).ok).toBe(false);+ expect(+ validateGhostManifest({ ...goodManifest(), network: { hosts: ['api.example.com'] } }).ok,+ ).toBe(false);const bare = validateGhostManifest({ ...goodManifest(), slots: ['panel', 'network'] });expect(bare.ok).toBe(true);if (bare.ok) expect(bare.manifest.network).toBeUndefined();@@ -2194,8 +2426,15 @@ describe('ghost · network 详单校验', () => {withNet({ hosts: ['api.example.com'], secrets: [{ ...goodSecret(), url }] });const ok = validateGhostManifest(withUrl('https://example.com/settings/keys'));expect(ok.ok).toBe(true);- if (ok.ok) expect(ok.manifest.network?.secrets?.[0]?.url).toBe('https://example.com/settings/keys');- for (const bad of ['http://example.com/keys', 'https://user:[email protected]/', 'not-a-url', '', 42]) {+ if (ok.ok)+ expect(ok.manifest.network?.secrets?.[0]?.url).toBe('https://example.com/settings/keys');+ for (const bad of [+ 'http://example.com/keys',+ 'https://user:[email protected]/',+ 'not-a-url',+ '',+ 42,+ ]) {expect(validateGhostManifest(withUrl(bad)).ok, String(bad)).toBe(false);}});@@ -2315,7 +2554,12 @@ describe('ghost · network 详单校验', () => {const ok = validateGhostManifest(withNet({hosts: ['api.brave.com', 'api.tavily.com'],- secrets: [{ ...goodSecret(), inject: { header: 'X-Token', format: '{value}', hosts: ['api.brave.com'] } }],+ secrets: [+ {+ ...goodSecret(),+ inject: { header: 'X-Token', format: '{value}', hosts: ['api.brave.com'] },+ },+ ],}),);expect(ok.ok).toBe(true);@@ -2323,7 +2567,12 @@ describe('ghost · network 详单校验', () => {const outside = validateGhostManifest(withNet({hosts: ['api.brave.com'],- secrets: [{ ...goodSecret(), inject: { header: 'X-Token', format: '{value}', hosts: ['api.other.com'] } }],+ secrets: [+ {+ ...goodSecret(),+ inject: { header: 'X-Token', format: '{value}', hosts: ['api.other.com'] },+ },+ ],}),);expect(outside.ok).toBe(false);@@ -2331,7 +2580,12 @@ describe('ghost · network 详单校验', () => {const literal = validateGhostManifest(withNet({hosts: ['*.tavily.com'],- secrets: [{ ...goodSecret(), inject: { header: 'X-Token', format: '{value}', hosts: ['api.tavily.com'] } }],+ secrets: [+ {+ ...goodSecret(),+ inject: { header: 'X-Token', format: '{value}', hosts: ['api.tavily.com'] },+ },+ ],}),);expect(literal.ok).toBe(false);@@ -2352,20 +2606,24 @@ describe('ghost · network 详单校验', () => {const full = validateGhostManifest(withNet({hosts: ['api.example.com'],- secrets: [{- ...goodSecret(),- exchange: {- ...exchange,- contentType: 'application/x-www-form-urlencoded',- tokenPath: 'data.token',- ttlSeconds: 86400,+ secrets: [+ {+ ...goodSecret(),+ exchange: {+ ...exchange,+ contentType: 'application/x-www-form-urlencoded',+ tokenPath: 'data.token',+ ttlSeconds: 86400,+ },},- }],+ ],}),);expect(full.ok).toBe(true);if (full.ok) {- expect(full.manifest.network?.secrets?.[0]?.exchange?.contentType).toBe('application/x-www-form-urlencoded');+ expect(full.manifest.network?.secrets?.[0]?.exchange?.contentType).toBe(+ 'application/x-www-form-urlencoded',+ );expect(full.manifest.network?.secrets?.[0]?.exchange?.ttlSeconds).toBe(86400);}});@@ -2419,13 +2677,19 @@ describe('ghost · network 详单校验', () => {expect(keys).toContain('network:host:*.tavily.com');expect(keys).toContain('network:secret:api_token');const secretItem = items.find((i) => i.key === 'network:secret:api_token');- expect(secretItem).toMatchObject({ kind: 'network', labelKey: 'networkSecret', labelArgs: { name: 'Example API Token' } });+ expect(secretItem).toMatchObject({+ kind: 'network',+ labelKey: 'networkSecret',+ labelArgs: { name: 'Example API Token' },+ });const code = items.find((i) => i.key === 'code');expect(code?.detailKey).toBe('codeDetailNetwork');// 无 network 槽的意识维持原说明const plain = validateGhostManifest(goodManifest());if (plain.ok) {- expect(ghostPermissionItems(plain.manifest).find((i) => i.key === 'code')?.detailKey).toBe('codeDetail');+ expect(ghostPermissionItems(plain.manifest).find((i) => i.key === 'code')?.detailKey).toBe(+ 'codeDetail',+ );}});@@ -2550,7 +2814,9 @@ describe('ghost · network 多连接声明(connections)', () => {});it('合法声明放行并归一化(hint/maxConnections 透传;未声明的可选字段不落清单)', () => {- const r = validateGhostManifest(withNet({ hosts: ['api.example.com'], connections: [goodConn()] }));+ const r = validateGhostManifest(+ withNet({ hosts: ['api.example.com'], connections: [goodConn()] }),+ );expect(r.ok, r.ok ? '' : r.reason).toBe(true);if (!r.ok) return;expect(r.manifest.network?.connections).toEqual([@@ -2564,7 +2830,10 @@ describe('ghost · network 多连接声明(connections)', () => {]);// 可选字段缺省不落清单(权限 diff 不 churn)。const minimal = validateGhostManifest(- withNet({ hosts: ['api.example.com'], connections: [{ key: 'gl', label: 'GL', inject: { header: 'X-T', format: '{value}' } }] }),+ withNet({+ hosts: ['api.example.com'],+ connections: [{ key: 'gl', label: 'GL', inject: { header: 'X-T', format: '{value}' } }],+ }),);expect(minimal.ok).toBe(true);if (!minimal.ok) return;@@ -2586,7 +2855,10 @@ describe('ghost · network 多连接声明(connections)', () => {it('声明了 connections 必须同时声明 settingsHtml(没人收地址和 token)', () => {const r = validateGhostManifest(- withNet({ hosts: ['api.example.com'], connections: [goodConn()] }, { settingsHtml: undefined }),+ withNet(+ { hosts: ['api.example.com'], connections: [goodConn()] },+ { settingsHtml: undefined },+ ),);expect(r.ok).toBe(false);expect(!r.ok && r.reason).toContain('settingsHtml');@@ -2614,7 +2886,12 @@ describe('ghost · network 多连接声明(connections)', () => {const withHosts = validateGhostManifest(withNet({hosts: ['api.example.com'],- connections: [{ ...goodConn(), inject: { header: 'X-T', format: '{value}', hosts: ['api.example.com'] } }],+ connections: [+ {+ ...goodConn(),+ inject: { header: 'X-T', format: '{value}', hosts: ['api.example.com'] },+ },+ ],}),);expect(withHosts.ok).toBe(false);@@ -2622,12 +2899,18 @@ describe('ghost · network 多连接声明(connections)', () => {// 协议关键头拒;format 必须恰含一个 {value}。expect(validateGhostManifest(- withNet({ hosts: ['api.example.com'], connections: [{ ...goodConn(), inject: { header: 'Cookie', format: '{value}' } }] }),+ withNet({+ hosts: ['api.example.com'],+ connections: [{ ...goodConn(), inject: { header: 'Cookie', format: '{value}' } }],+ }),).ok,).toBe(false);expect(validateGhostManifest(- withNet({ hosts: ['api.example.com'], connections: [{ ...goodConn(), inject: { header: 'X-T', format: 'no-placeholder' } }] }),+ withNet({+ hosts: ['api.example.com'],+ connections: [{ ...goodConn(), inject: { header: 'X-T', format: 'no-placeholder' } }],+ }),).ok,).toBe(false);});@@ -2646,7 +2929,10 @@ describe('ghost · network 多连接声明(connections)', () => {expect(three.ok).toBe(false);for (const bad of [0, 9, 1.5, '4', Number.NaN]) {const r = validateGhostManifest(- withNet({ hosts: ['api.example.com'], connections: [{ ...goodConn(), maxConnections: bad }] }),+ withNet({+ hosts: ['api.example.com'],+ connections: [{ ...goodConn(), maxConnections: bad }],+ }),);expect(r.ok, String(bad)).toBe(false);}@@ -2659,7 +2945,9 @@ describe('ghost · network 多连接声明(connections)', () => {});it('权限清单:每条连接声明生成一条 networkConnections 条目(带 label 与主机说明)', () => {- const r = validateGhostManifest(withNet({ hosts: ['api.example.com'], connections: [goodConn()] }));+ const r = validateGhostManifest(+ withNet({ hosts: ['api.example.com'], connections: [goodConn()] }),+ );expect(r.ok).toBe(true);if (!r.ok) return;const item = ghostPermissionItems(r.manifest).find((i) => i.key === 'connections:gitlab');@@ -2712,11 +3000,19 @@ describe('ghost · settingsHtml 自绘设置区 + settingsHeight', () => {it('settingsHeight:160/800 边界过,159/801/NaN/字符串拒,归一化透传', () => {for (const h of [160, 360, 800]) {- const r = validateGhostManifest({ ...goodManifest(), settingsHtml: 'settings.html', settingsHeight: h });+ const r = validateGhostManifest({+ ...goodManifest(),+ settingsHtml: 'settings.html',+ settingsHeight: h,+ });expect(r.ok && r.manifest.settingsHeight, String(h)).toBe(h);}for (const h of [159, 801, Number.NaN, Number.POSITIVE_INFINITY, '360', null]) {- const r = validateGhostManifest({ ...goodManifest(), settingsHtml: 'settings.html', settingsHeight: h });+ const r = validateGhostManifest({+ ...goodManifest(),+ settingsHtml: 'settings.html',+ settingsHeight: h,+ });expect(r.ok, String(h)).toBe(false);}});@@ -2734,7 +3030,10 @@ describe('ghost · settingsHtml 自绘设置区 + settingsHeight', () => {it('ghostWebviewEntryPaths:只 panel / 只 settings / 双声明 / 都无 / 同文件去重', () => {const both = validateGhostManifest({ ...goodManifest(), settingsHtml: 'settings.html' });- expect(both.ok && ghostWebviewEntryPaths(both.manifest)).toEqual(['/panel.html', '/settings.html']);+ expect(both.ok && ghostWebviewEntryPaths(both.manifest)).toEqual([+ '/panel.html',+ '/settings.html',+ ]);const panelOnly = validateGhostManifest(goodManifest());expect(panelOnly.ok && ghostWebviewEntryPaths(panelOnly.manifest)).toEqual(['/panel.html']);@@ -2838,8 +3137,17 @@ describe('ghost · 权限清单凭证分档(知情同意面不许说过头话)',network: {hosts: ['api.example.com'],secrets: [- { key: 'user_key', label: 'U', inject: { header: 'Authorization', format: 'Bearer {value}' } },- { key: 'pages_token', label: 'P', source: 'login-email', inject: { header: 'X-Pages-Token', format: 'pages_{value}' } },+ {+ key: 'user_key',+ label: 'U',+ inject: { header: 'Authorization', format: 'Bearer {value}' },+ },+ {+ key: 'pages_token',+ label: 'P',+ source: 'login-email',+ inject: { header: 'X-Pages-Token', format: 'pages_{value}' },+ },],},});@@ -2886,9 +3194,7 @@ describe('ghost · 2026-07-23 通用能力四件套(session-context / pick / pre// 有槽必有详单expect(validateGhostManifest({ ...base, slots: ['panel', 'preview'] }).ok).toBe(false);// 有详单必有槽- expect(- validateGhostManifest({ ...base, preview: { hosts: ['example.com'] } }).ok,- ).toBe(false);+ expect(validateGhostManifest({ ...base, preview: { hosts: ['example.com'] } }).ok).toBe(false);const good = validateGhostManifest({...base,slots: ['panel', 'preview'],@@ -2906,15 +3212,16 @@ describe('ghost · 2026-07-23 通用能力四件套(session-context / pick / preexpect(withPreview({ hosts: ['a.example.com'], extra: 1 }).ok).toBe(false);});- it('session-context / pick / workspace 槽:纯槽声明即可装入,并生成对应权限项', () => {+ it('session-context / pick / workspace / ios-simulator 槽可装入并生成权限项', () => {const r = validateGhostManifest({...goodChipManifest(),- slots: ['panel', 'session-context', 'pick', 'preview', 'workspace'],+ slots: ['panel', 'session-context', 'pick', 'preview', 'workspace', 'ios-simulator'],preview: { hosts: ['example.com'] },});expect(r.ok).toBe(true);if (!r.ok) return;expect(ghostContentKeys(r.manifest)).toContain('slotWorkspace');+ expect(ghostContentKeys(r.manifest)).toContain('slotIOSSimulator');const items = ghostPermissionItems(r.manifest);expect(items).toEqual(expect.arrayContaining([@@ -2936,6 +3243,12 @@ describe('ghost · 2026-07-23 通用能力四件套(session-context / pick / prelabelKey: 'workspace',detailKey: 'workspaceDetail',}),+ expect.objectContaining({+ key: 'ios-simulator',+ kind: 'ios-simulator',+ labelKey: 'iosSimulator',+ detailKey: 'iosSimulatorDetail',+ }),]),);});@@ -2964,7 +3277,8 @@ describe('ghost · 2026-07-23 通用能力四件套(session-context / pick / pre// 未声明详单的清单恒拒const none = validateGhostManifest(goodChipManifest());expect(none.ok).toBe(true);- if (none.ok) expect(ghostPreviewUrlAllowed(none.manifest, 'https://demo.example.dev/')).toBe(false);+ if (none.ok)+ expect(ghostPreviewUrlAllowed(none.manifest, 'https://demo.example.dev/')).toBe(false);});it('deriveGhostSessionContext:证明不了本地就 fail closed', () => {@@ -3067,9 +3381,9 @@ describe('ghost · 宿主代启子进程(node.childSpawn,2026-07-23)', () => {const off = withNode({ entry: 'node/a.cjs', protocol: 'json-rpc-stdio' });expect(off.ok).toBe(true);if (off.ok) {- expect(- ghostPermissionItems(off.manifest).some((i) => i.key === 'node:child-spawn'),- ).toBe(false);+ expect(ghostPermissionItems(off.manifest).some((i) => i.key === 'node:child-spawn')).toBe(+ false,+ );}});@@ -3081,7 +3395,12 @@ describe('ghost · 宿主代启子进程(node.childSpawn,2026-07-23)', () => {entry: 'node/maker.cjs',args: ['__maker-proxy'],}),- ).toEqual({ type: 'spawn-child', reqId: 'r1', entry: 'node/maker.cjs', args: ['__maker-proxy'] });+ ).toEqual({+ type: 'spawn-child',+ reqId: 'r1',+ entry: 'node/maker.cjs',+ args: ['__maker-proxy'],+ });expect(parseGhostNodeChildToHostMessage({ type: 'child-stdin', childId: 'c1', b64: 'aGk=' }),).toEqual({ type: 'child-stdin', childId: 'c1', b64: 'aGk=' });@@ -3096,9 +3415,7 @@ describe('ghost · 宿主代启子进程(node.childSpawn,2026-07-23)', () => {// 畸形:类型不认 / id 形状不对 / args 超条数 / 单参超长 / b64 超帧expect(parseGhostNodeChildToHostMessage(null)).toBeNull();expect(parseGhostNodeChildToHostMessage({ type: 'evil' })).toBeNull();- expect(- parseGhostNodeChildToHostMessage({ type: 'child-kill', childId: 'bad id!' }),- ).toBeNull();+ expect(parseGhostNodeChildToHostMessage({ type: 'child-kill', childId: 'bad id!' })).toBeNull();expect(parseGhostNodeChildToHostMessage({type: 'spawn-child',@@ -3128,17 +3445,17 @@ describe('ghost · 宿主代启子进程(node.childSpawn,2026-07-23)', () => {describe('ghost · skill 槽(捆绑 Agent Skills,2026-07-25)', () => {const withSkill = (skill: unknown, slots: string[] = ['panel', 'skill']) =>validateGhostManifest({ ...goodChipManifest(), slots, skill });- const goodItems = [- { dir: 'skills/foo', name: 'foo', description: '教 Agent 用 foo' },- ];+ const goodItems = [{ dir: 'skills/foo', name: 'foo', description: '教 Agent 用 foo' }];it('槽与详单严格成对;合法声明原样收录', () => {// 有槽必有详单- expect(validateGhostManifest({ ...goodChipManifest(), slots: ['panel', 'skill'] }).ok).toBe(false);+ expect(validateGhostManifest({ ...goodChipManifest(), slots: ['panel', 'skill'] }).ok).toBe(+ false,+ );// 有详单必有槽- expect(- validateGhostManifest({ ...goodChipManifest(), skill: { items: goodItems } }).ok,- ).toBe(false);+ expect(validateGhostManifest({ ...goodChipManifest(), skill: { items: goodItems } }).ok).toBe(+ false,+ );const good = withSkill({ items: goodItems });expect(good.ok).toBe(true);if (good.ok) expect(good.manifest.skill?.items).toEqual(goodItems);@@ -3149,9 +3466,7 @@ describe('ghost · skill 槽(捆绑 Agent Skills,2026-07-25)', () => {expect(withSkill({}).ok).toBe(false);expect(withSkill({ items: goodItems, extra: 1 }).ok).toBe(false);expect(withSkill({ items: ['skills/foo'] }).ok).toBe(false);- expect(- withSkill({ items: [{ ...goodItems[0], scope: 'global' }] }).ok,- ).toBe(false);+ expect(withSkill({ items: [{ ...goodItems[0], scope: 'global' }] }).ok).toBe(false);const five = Array.from({ length: 5 }, (_, i) => ({dir: `skills/s${i}`,name: `s${i}`,@@ -3173,7 +3488,8 @@ describe('ghost · skill 槽(捆绑 Agent Skills,2026-07-25)', () => {});it('name:小写字母数字单连字符分段;禁首尾/连续连字符(链接名 <id>--<name> 的无歧义前提)', () => {- const named = (name: string) => withSkill({ items: [{ dir: 'skills/foo', name, description: 'x' }] });+ const named = (name: string) =>+ withSkill({ items: [{ dir: 'skills/foo', name, description: 'x' }] });expect(named('foo-bar').ok).toBe(true);expect(named('foo2').ok).toBe(true);expect(named('Foo').ok).toBe(false);diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 721c0918c5..b69ac277fe 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -1,6 +1,8 @@import { GHOST_OAUTH_SCOPES_MAX } from '@cindy/plugin-protocol';+import type { IOSSimulatorMcpErrorCode } from '@cindy/mcps';import { findSplitChildByPanelKind, insertRootSplitPane, type Layout } from './layoutTree';import { DEFAULT_LOCALE, SUPPORTED_LOCALES, type SupportedLocale } from './locale';+import type { IOSSimulatorPublicInstance, IOSSimulatorPublicRouteStatus } from './iosSimulatorIpc';/*** 意识(Ghost,.cindy 文件)的清单数据模型与校验 —— main / renderer 共用。@@ -111,6 +113,10 @@ const GHOST_ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;* 即授权(pick 模式,路径不回沙箱),或 tool-call 语境下带在途 callId + 绝对* 路径(目录在该会话 workdir 内自动放行,workdir 外弹确认卡)。远程工作区* v1 一律拒(fail closed)。+ * 'ios-simulator' = 内置 iOS 模拟器(2026-08-06):插件只能读取当前台前任务的+ * 脱敏状态摘要并请求 Host 打开既有模拟器面板。视频帧、输入、viewer lease、+ * UDID、Sidecar 路径/进程与任意 sessionId 均不跨插件边界;实际 WDA / Native+ * 路由、生命周期、恢复与 fallback 仍完全由 Host 管理。*/export const GHOST_SLOTS = ['subscribe',@@ -130,6 +136,7 @@ export const GHOST_SLOTS = ['preview','skill','workspace',+ 'ios-simulator',] as const;export type GhostSlot = (typeof GHOST_SLOTS)[number];@@ -314,9 +321,7 @@ function isChildId(v: unknown): v is string {}/** worker → 主机控制帧的形状校验(主机侧守门用;不合形一律静默丢)。 */-export function parseGhostNodeChildToHostMessage(- raw: unknown,-): GhostNodeChildToHostMessage | null {+export function parseGhostNodeChildToHostMessage(raw: unknown): GhostNodeChildToHostMessage | null {if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;const m = raw as Record<string, unknown>;if (m.type === 'spawn-child') {@@ -556,7 +561,8 @@ export function isValidGhostNetworkHostPattern(p: unknown): p is string {* 作者两者都要就两条都声明,规则不做隐式扩张。*/export function ghostNetworkHostMatches(pattern: string, hostname: string): boolean {- if (pattern.startsWith('*.')) return hostname.endsWith(pattern.slice(1)) && hostname.length > pattern.length - 1;+ if (pattern.startsWith('*.'))+ return hostname.endsWith(pattern.slice(1)) && hostname.length > pattern.length - 1;return hostname === pattern;}@@ -951,7 +957,11 @@ export interface GhostSkillNeeds {* - hostname 必须命中 preview.hosts 声明(逐模式 ghostNetworkHostMatches)。*/export function ghostPreviewUrlAllowed(manifest: GhostManifest, rawUrl: string): boolean {- if (typeof rawUrl !== 'string' || rawUrl.length === 0 || rawUrl.length > GHOST_PREVIEW_URL_MAX_CHARS) {+ if (+ typeof rawUrl !== 'string' ||+ rawUrl.length === 0 ||+ rawUrl.length > GHOST_PREVIEW_URL_MAX_CHARS+ ) {return false;}const hosts = manifest.preview?.hosts ?? [];@@ -986,7 +996,13 @@ export function ghostExternalLinkUrls(manifest: GhostManifest): string[] {* (小写比较;Cookie 也拒——会话粘连语义不给意识)。*/export const GHOST_NETWORK_FORBIDDEN_INJECT_HEADERS: readonly string[] = [- 'host', 'content-length', 'transfer-encoding', 'connection', 'cookie', 'origin', 'referer',+ 'host',+ 'content-length',+ 'transfer-encoding',+ 'connection',+ 'cookie',+ 'origin',+ 'referer',// content-type 由请求语义决定(上传通道的 multipart boundary 依赖它),// 不许被凭证注入声明占用——401 重换/跨域跳转的重注入会砸掉 boundary。'content-type',@@ -1028,8 +1044,7 @@ export const GHOST_SETUP_MAX_STEPS =*/export const GHOST_SETUP_MAX_HOST_STEPS = 8;/** setup interaction/plan transport capacity, including Host-owned steps. */-export const GHOST_SETUP_MAX_INTERACTION_STEPS =- GHOST_SETUP_MAX_STEPS + GHOST_SETUP_MAX_HOST_STEPS;+export const GHOST_SETUP_MAX_INTERACTION_STEPS = GHOST_SETUP_MAX_STEPS + GHOST_SETUP_MAX_HOST_STEPS;/** setup kv 引用的键名形状(意识 /kv 顶层键;点号仅作普通字符,不做路径下钻)。 */export const GHOST_SETUP_KV_KEY_RE = /^[A-Za-z0-9_.-]{1,64}$/;@@ -1076,11 +1091,7 @@ export interface GhostSetupStatus {/** Setup Runtime 暴露给 Agent / Renderer 的需求类型;不包含任何配置值。 */export type GhostSetupRequirementKind =- | 'oauth'- | 'secret'- | 'connection'- | 'plugin_config'- | 'client_config';+ 'oauth' | 'secret' | 'connection' | 'plugin_config' | 'client_config';/** Host 对单条 requirement 的权威判定。 */export type GhostSetupRequirementState = 'missing' | 'expired' | 'satisfied';@@ -1227,8 +1238,7 @@ export type GhostSetupErrorCode = (typeof GHOST_SETUP_ERROR_CODES)[number];/** 不可信 interaction payload 的稳定 Setup 错误码守卫。 */export function isGhostSetupErrorCode(value: unknown): value is GhostSetupErrorCode {return (- typeof value === 'string' &&- (GHOST_SETUP_ERROR_CODES as readonly string[]).includes(value)+ typeof value === 'string' && (GHOST_SETUP_ERROR_CODES as readonly string[]).includes(value));}@@ -1369,11 +1379,14 @@ export interface GhostManifestLocaleResource {name?: string;description?: string;whenToUse?: string;- tools?: Record<string, {- description: string;- /** JSON Pointer → 该参数 schema 节点已有的 title / description 翻译。 */- parameters?: Record<string, { title?: string; description?: string }>;- }>;+ tools?: Record<+ string,+ {+ description: string;+ /** JSON Pointer → 该参数 schema 节点已有的 title / description 翻译。 */+ parameters?: Record<string, { title?: string; description?: string }>;+ }+ >;panel?: { title: string };network?: {secrets?: Record<string, { label: string; hint?: string }>;@@ -1415,11 +1428,7 @@ export interface InstalledGhost {}/** 插件包的来源与审核等级;决定 UI 徽标,不改变运行时 slot 权限。 */-export type GhostTrustLevel =- | 'cindy-official'- | 'reviewed'- | 'verified-publisher'- | 'unverified';+export type GhostTrustLevel = 'cindy-official' | 'reviewed' | 'verified-publisher' | 'unverified';export interface GhostTrustInfo {level: GhostTrustLevel;@@ -1465,6 +1474,7 @@ export function ghostContentKeys(manifest: GhostManifest): string[] {// skill 是信任面最高的内容(给主 Agent 灌指令),详情页必须如实露出。else if (slot === 'skill') keys.push('slotSkill');else if (slot === 'workspace') keys.push('slotWorkspace');+ else if (slot === 'ios-simulator') keys.push('slotIOSSimulator');// 'panel' 槽已由 manifest.panel 覆盖,不重复}return keys;@@ -1490,7 +1500,11 @@ export const GHOST_OFFICIAL_ID_PREFIX = 'cindy-';* ——官方密钥别名按 id 登记,前缀不保留会被第三方抢注蹭钥匙)。* 新增官方前缀在此登记。*/-export const GHOST_OFFICIAL_ID_PREFIXES: readonly string[] = [GHOST_OFFICIAL_ID_PREFIX, 'filo-', 'xd-'];+export const GHOST_OFFICIAL_ID_PREFIXES: readonly string[] = [+ GHOST_OFFICIAL_ID_PREFIX,+ 'filo-',+ 'xd-',+];/** id 是否属于官方保留命名空间。 */export function isOfficialGhostId(id: string): boolean {@@ -1526,7 +1540,26 @@ export interface GhostPermissionItem {/** 稳定键:更新 diff 按它对齐(内容变化视为移除+新增,如面板换边)。 */key: string;/** 图标分组(renderer 按 kind 选图标)。 */- kind: 'cindy' | 'agent' | 'node' | 'tool' | 'command' | 'panel' | 'code' | 'subscribe' | 'card' | 'network' | 'notify' | 'confirm' | 'fs' | 'session-context' | 'pick' | 'preview' | 'skill' | 'workspace';+ kind:+ | 'cindy'+ | 'agent'+ | 'node'+ | 'tool'+ | 'command'+ | 'panel'+ | 'code'+ | 'subscribe'+ | 'card'+ | 'network'+ | 'notify'+ | 'confirm'+ | 'fs'+ | 'session-context'+ | 'pick'+ | 'preview'+ | 'skill'+ | 'workspace'+ | 'ios-simulator';/** i18n key 后缀,消费方拼 `settings.ghosts.perm.<labelKey>`。 */labelKey: string;/** i18n 插值参数(工具名、指令名、面板标题等)。 */@@ -1797,6 +1830,15 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionItdetailKey: 'workspaceDetail',});}+ // 内置模拟器槽只给脱敏状态与 Host 面板入口;视频、输入和进程控制都不授权。+ if (manifest.slots.includes('ios-simulator')) {+ items.push({+ key: 'ios-simulator',+ kind: 'ios-simulator',+ labelKey: 'iosSimulator',+ detailKey: 'iosSimulatorDetail',+ });+ }// session-context 槽:派活时可获知当前会话的项目目录位置(路径信息,// 非文件访问权;node 槽的执行权另行单列)。if (manifest.slots.includes('session-context')) {@@ -1908,8 +1950,7 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionItdetailKey: 'cardExternalLinkDetail',});}- }- else if (slot === 'notify') {+ } else if (slot === 'notify') {items.push({ key: 'notify', kind: 'notify', labelKey: 'notify', detailKey: 'notifyDetail' });}}@@ -1925,11 +1966,21 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionIt// confirm 槽:能请主机弹一个二选一确认框(会打断操作)。装入时如实告知"它会来问",// 决定权仍在用户的点击上——detailKey 的固定说明把这层讲清。if (manifest.slots.includes('confirm')) {- items.push({ key: 'confirm', kind: 'confirm', labelKey: 'confirm', detailKey: 'confirmDetail' });+ items.push({+ key: 'confirm',+ kind: 'confirm',+ labelKey: 'confirm',+ detailKey: 'confirmDetail',+ });}// 常驻模式如实告知(用户要背一个后台进程);on-demand 是默认行为,不列。if (manifest.launch === 'resident') {- items.push({ key: 'resident', kind: 'code', labelKey: 'resident', detailKey: 'residentDetail' });+ items.push({+ key: 'resident',+ kind: 'code',+ labelKey: 'resident',+ detailKey: 'residentDetail',+ });}// 可执行代码的沙箱说明分档:// - 有 node 槽时浏览器沙箱部分仍隔离,但不能再笼统说"无文件无网络"@@ -2058,9 +2109,7 @@ export function isSafeGhostRelativePath(p: unknown): p is string {if (typeof p !== 'string' || p.length === 0 || p.length > 256) return false;if (p.includes('\\')) return false;const segments = p.split('/');- return segments.every(- (seg) => GHOST_PATH_SEGMENT_RE.test(seg) && seg !== '.' && seg !== '..',- );+ return segments.every((seg) => GHOST_PATH_SEGMENT_RE.test(seg) && seg !== '.' && seg !== '..');}/**@@ -2097,7 +2146,9 @@ export function layoutWithGhostPanel(layout: Layout, manifest: GhostManifest): L// 的 pane 是用户布局记忆,本函数只管首次装入,不搬动存量)。const chatIndex =layout.content.type === 'split'- ? layout.content.children.findIndex((c) => c.node.type === 'pane' && c.node.panelKind === 'chat-main')+ ? layout.content.children.findIndex(+ (c) => c.node.type === 'pane' && c.node.panelKind === 'chat-main',+ ): -1;const index = chatIndex < 0 ? 0 : chatIndex;const result = insertRootSplitPane(@@ -2112,7 +2163,8 @@ export function layoutWithGhostPanel(layout: Layout, manifest: GhostManifest): Lreturn result.applied ? result.layout : null;}-export type ManifestValidation = { ok: true; manifest: GhostManifest } | { ok: false; reason: string };+export type ManifestValidation =+ { ok: true; manifest: GhostManifest } | { ok: false; reason: string };const GHOST_MANIFEST_RESERVED_RECORD_KEYS = new Set(['__proto__', 'constructor', 'prototype']);@@ -2131,7 +2183,7 @@ export function ghostLocalePathFor(): string | null {if (!manifest.locales) return null;const supported = (SUPPORTED_LOCALES as readonly string[]).includes(locale ?? '')- ? locale as SupportedLocale+ ? (locale as SupportedLocale): DEFAULT_LOCALE;return manifest.locales[supported] ?? manifest.locales[DEFAULT_LOCALE] ?? null;}@@ -2142,7 +2194,7 @@ export function withGhostResolvedLocale(locale: string | undefined | null,): GhostManifest {const resolvedLocale = (SUPPORTED_LOCALES as readonly string[]).includes(locale ?? '')- ? locale as SupportedLocale+ ? (locale as SupportedLocale): DEFAULT_LOCALE;return { ...manifest, resolvedLocale };}@@ -2151,11 +2203,22 @@ type GhostSchemaLocaleText = { title?: string; description?: string };type GhostSchemaLocaleShape = { title: boolean; description: boolean };const GHOST_SCHEMA_MAP_KEYWORDS = [- 'properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas',+ 'properties',+ 'patternProperties',+ '$defs',+ 'definitions',+ 'dependentSchemas',] as const;const GHOST_SCHEMA_SINGLE_KEYWORDS = [- 'additionalProperties', 'unevaluatedProperties', 'propertyNames', 'items',- 'contains', 'not', 'if', 'then', 'else',+ 'additionalProperties',+ 'unevaluatedProperties',+ 'propertyNames',+ 'items',+ 'contains',+ 'not',+ 'if',+ 'then',+ 'else',] as const;const GHOST_SCHEMA_ARRAY_KEYWORDS = ['allOf', 'anyOf', 'oneOf', 'prefixItems'] as const;@@ -2168,7 +2231,10 @@ function ghostJsonPointerChild(pointer: string, segment: string | number): strinfunction collectGhostSchemaLocaleShape(schema: unknown,pointer = '',- result: Record<string, GhostSchemaLocaleShape> = Object.create(null) as Record<string, GhostSchemaLocaleShape>,+ result: Record<string, GhostSchemaLocaleShape> = Object.create(null) as Record<+ string,+ GhostSchemaLocaleShape+ >,): Record<string, GhostSchemaLocaleShape> {if (!isPlainObject(schema)) return result;const title = typeof schema.title === 'string';@@ -2178,7 +2244,11 @@ function collectGhostSchemaLocaleShape(const children = schema[keyword];if (!isPlainObject(children)) continue;for (const [key, child] of Object.entries(children)) {- collectGhostSchemaLocaleShape(child, ghostJsonPointerChild(ghostJsonPointerChild(pointer, keyword), key), result);+ collectGhostSchemaLocaleShape(+ child,+ ghostJsonPointerChild(ghostJsonPointerChild(pointer, keyword), key),+ result,+ );}}for (const keyword of GHOST_SCHEMA_SINGLE_KEYWORDS) {@@ -2188,7 +2258,11 @@ function collectGhostSchemaLocaleShape(const children = schema[keyword];if (!Array.isArray(children)) continue;children.forEach((child, index) => {- collectGhostSchemaLocaleShape(child, ghostJsonPointerChild(ghostJsonPointerChild(pointer, keyword), index), result);+ collectGhostSchemaLocaleShape(+ child,+ ghostJsonPointerChild(ghostJsonPointerChild(pointer, keyword), index),+ result,+ );});}return result;@@ -2222,20 +2296,24 @@ function resolveGhostSchemaLocale(for (const keyword of GHOST_SCHEMA_SINGLE_KEYWORDS) {const child = schema[keyword];if (!isPlainObject(child)) continue;- result[keyword] = resolveGhostSchemaLocale(child, localized, ghostJsonPointerChild(pointer, keyword));+ result[keyword] = resolveGhostSchemaLocale(+ child,+ localized,+ ghostJsonPointerChild(pointer, keyword),+ );}for (const keyword of GHOST_SCHEMA_ARRAY_KEYWORDS) {const children = schema[keyword];if (!Array.isArray(children)) continue;- result[keyword] = children.map((child, index) => (+ result[keyword] = children.map((child, index) =>isPlainObject(child)? resolveGhostSchemaLocale(child,localized,ghostJsonPointerChild(ghostJsonPointerChild(pointer, keyword), index),)- : child- ));+ : child,+ );}return result;}@@ -2252,7 +2330,14 @@ export function validateGhostManifestLocaleResource(): { ok: true; resource: GhostManifestLocaleResource } | { ok: false; reason: string } {if (!isPlainObject(raw)) return { ok: false, reason: 'locale 文件必须是对象' };const allowedTopLevelFields = new Set([- 'name', 'description', 'whenToUse', 'tools', 'panel', 'network', 'node', 'setup',+ 'name',+ 'description',+ 'whenToUse',+ 'tools',+ 'panel',+ 'network',+ 'node',+ 'setup',]);const unknownTopLevelField = Object.keys(raw).find((field) => !allowedTopLevelFields.has(field));if (unknownTopLevelField) {@@ -2342,7 +2427,9 @@ export function validateGhostManifestLocaleResource(};}const expectedPointers = new Set(parameterPointers);- const unknownPointer = Object.keys(localized.parameters).find((pointer) => !expectedPointers.has(pointer));+ const unknownPointer = Object.keys(localized.parameters).find(+ (pointer) => !expectedPointers.has(pointer),+ );if (unknownPointer) {return {ok: false,@@ -2364,7 +2451,9 @@ export function validateGhostManifestLocaleResource(...(shape.title ? ['title'] : []),...(shape.description ? ['description'] : []),]);- const unknownField = Object.keys(localizedText).find((field) => !allowedFields.has(field));+ const unknownField = Object.keys(localizedText).find(+ (field) => !allowedFields.has(field),+ );if (unknownField) {return {ok: false,@@ -2373,7 +2462,9 @@ export function validateGhostManifestLocaleResource(}if (localizedText.title !== undefined &&- (typeof localizedText.title !== 'string' || localizedText.title.trim().length === 0 || localizedText.title.length > 256)+ (typeof localizedText.title !== 'string' ||+ localizedText.title.trim().length === 0 ||+ localizedText.title.length > 256)) {return {ok: false,@@ -2382,11 +2473,9 @@ export function validateGhostManifestLocaleResource(}if (localizedText.description !== undefined &&- (- typeof localizedText.description !== 'string' ||+ (typeof localizedText.description !== 'string' ||localizedText.description.trim().length === 0 ||- localizedText.description.length > 1024- )+ localizedText.description.length > 1024)) {return {ok: false,@@ -2395,7 +2484,9 @@ export function validateGhostManifestLocaleResource(}parameters[pointer] = {...(typeof localizedText.title === 'string' ? { title: localizedText.title } : {}),- ...(typeof localizedText.description === 'string' ? { description: localizedText.description } : {}),+ ...(typeof localizedText.description === 'string'+ ? { description: localizedText.description }+ : {}),};}}@@ -2418,7 +2509,11 @@ export function validateGhostManifestLocaleResource(if (unknownPanelField) {return { ok: false, reason: `locale.panel 含未知字段 ${JSON.stringify(unknownPanelField)}` };}- if (typeof raw.panel.title !== 'string' || raw.panel.title.trim().length === 0 || raw.panel.title.length > 64) {+ if (+ typeof raw.panel.title !== 'string' ||+ raw.panel.title.trim().length === 0 ||+ raw.panel.title.length > 64+ ) {return { ok: false, reason: 'locale.panel.title 必须是 1–64 字符的非空字符串' };}panel = { title: raw.panel.title };@@ -2428,7 +2523,9 @@ export function validateGhostManifestLocaleResource(rawValue: unknown,fieldPath: string,declarations: ReadonlyArray<{ key: string; hint?: string }>,- ): { ok: true; labels?: Record<string, { label: string; hint?: string }> } | { ok: false; reason: string } => {+ ):+ | { ok: true; labels?: Record<string, { label: string; hint?: string }> }+ | { ok: false; reason: string } => {if (rawValue === undefined) return { ok: true };if (declarations.length === 0) {return { ok: false, reason: `${fieldPath} 不应存在:原 manifest 未声明对应项目` };@@ -2448,7 +2545,8 @@ export function validateGhostManifestLocaleResource(if (!isPlainObject(localized)) {return { ok: false, reason: `${fieldPath}[${JSON.stringify(declaration.key)}] 必须是对象` };}- const allowedFields = declaration.hint !== undefined ? new Set(['label', 'hint']) : new Set(['label']);+ const allowedFields =+ declaration.hint !== undefined ? new Set(['label', 'hint']) : new Set(['label']);const unknownField = Object.keys(localized).find((field) => !allowedFields.has(field));if (unknownField) {return {@@ -2456,7 +2554,11 @@ export function validateGhostManifestLocaleResource(reason: `${fieldPath}[${JSON.stringify(declaration.key)}] 含未知字段 ${JSON.stringify(unknownField)}`,};}- if (typeof localized.label !== 'string' || localized.label.trim().length === 0 || localized.label.length > 64) {+ if (+ typeof localized.label !== 'string' ||+ localized.label.trim().length === 0 ||+ localized.label.length > 64+ ) {return {ok: false,reason: `${fieldPath}[${JSON.stringify(declaration.key)}].label 必须是 1–64 字符的非空字符串`,@@ -2464,7 +2566,9 @@ export function validateGhostManifestLocaleResource(}if (localized.hint !== undefined &&- (typeof localized.hint !== 'string' || localized.hint.trim().length === 0 || localized.hint.length > 200)+ (typeof localized.hint !== 'string' ||+ localized.hint.trim().length === 0 ||+ localized.hint.length > 200)) {return {ok: false,@@ -2493,11 +2597,22 @@ export function validateGhostManifestLocaleResource((field) => field !== 'secrets' && field !== 'connections',);if (unknownNetworkField) {- return { ok: false, reason: `locale.network 含未知字段 ${JSON.stringify(unknownNetworkField)}` };+ return {+ ok: false,+ reason: `locale.network 含未知字段 ${JSON.stringify(unknownNetworkField)}`,+ };}- const secrets = validateLocalizedLabels(raw.network.secrets, 'locale.network.secrets', secretDecls);+ const secrets = validateLocalizedLabels(+ raw.network.secrets,+ 'locale.network.secrets',+ secretDecls,+ );if (!secrets.ok) return secrets;- const connections = validateLocalizedLabels(raw.network.connections, 'locale.network.connections', connectionDecls);+ const connections = validateLocalizedLabels(+ raw.network.connections,+ 'locale.network.connections',+ connectionDecls,+ );if (!connections.ok) return connections;network = {...(secrets.labels !== undefined ? { secrets: secrets.labels } : {}),@@ -2616,7 +2731,8 @@ export function resolveGhostManifestLocale(})),}: {}),- ...(manifest.network.connections !== undefined && resource.network.connections !== undefined+ ...(manifest.network.connections !== undefined &&+ resource.network.connections !== undefined? {connections: manifest.network.connections.map((connection) => ({...connection,@@ -2642,11 +2758,11 @@ export function resolveGhostManifestLocale(? {setup: {requires: manifest.setup.requires.map((group) => ({- anyOf: group.anyOf.map((requirement) => (+ anyOf: group.anyOf.map((requirement) =>requirement.kind === 'kv' && resource.setup!.kv![requirement.key] !== undefined? { ...requirement, label: resource.setup!.kv![requirement.key].label }- : requirement- )),+ : requirement,+ ),})),},}@@ -2662,7 +2778,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {if (!isPlainObject(raw)) return { ok: false, reason: '清单不是对象' };if (raw.schemaVersion !== 2) {- return { ok: false, reason: `schemaVersion 必须是 2,得到 ${JSON.stringify(raw.schemaVersion)}(v1 声明型已于 2026-07-12 移除)` };+ return {+ ok: false,+ reason: `schemaVersion 必须是 2,得到 ${JSON.stringify(raw.schemaVersion)}(v1 声明型已于 2026-07-12 移除)`,+ };}if (!isValidGhostId(raw.id)) {return { ok: false, reason: 'id 必须是 1–32 位小写字母/数字/连字符(不能以连字符开头)' };@@ -2670,13 +2789,20 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {if (typeof raw.name !== 'string' || raw.name.trim().length === 0 || raw.name.length > 64) {return { ok: false, reason: 'name 必须是 1–64 字符的非空字符串' };}- if (typeof raw.version !== 'string' || raw.version.trim().length === 0 || raw.version.length > 32) {+ if (+ typeof raw.version !== 'string' ||+ raw.version.trim().length === 0 ||+ raw.version.length > 32+ ) {return { ok: false, reason: 'version 必须是 1–32 字符的非空字符串' };}// kind 可省略(2026-07-12 晚定案:单形态后字段纯冗余,缺省即 chip);// 写了就必须是 chip——写错值仍拒,不静默纠正(规则 9)。if (raw.kind !== undefined && raw.kind !== 'chip') {- return { ok: false, reason: `kind 必须是 "chip" 或省略(缺省即 chip),得到 ${JSON.stringify(raw.kind)}(意识只有芯片一种形态,declaration 已移除)` };+ return {+ ok: false,+ reason: `kind 必须是 "chip" 或省略(缺省即 chip),得到 ${JSON.stringify(raw.kind)}(意识只有芯片一种形态,declaration 已移除)`,+ };}if (raw.author !== undefined &&@@ -2721,7 +2847,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {!isSafeGhostRelativePath(localePath) ||!localePath.toLowerCase().endsWith('.json')) {- return { ok: false, reason: `locales.${locale} 必须是安装目录内以 .json 结尾的安全相对路径` };+ return {+ ok: false,+ reason: `locales.${locale} 必须是安装目录内以 .json 结尾的安全相对路径`,+ };}const normalizedLocalePath = localePath.toLowerCase();if (nonLocalePathFolds.has(normalizedLocalePath)) {@@ -2740,13 +2869,17 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {}if (raw.description !== undefined &&- (typeof raw.description !== 'string' || raw.description.trim().length === 0 || raw.description.length > 300)+ (typeof raw.description !== 'string' ||+ raw.description.trim().length === 0 ||+ raw.description.length > 300)) {return { ok: false, reason: 'description 必须是 1–300 字符的非空字符串' };}if (raw.whenToUse !== undefined &&- (typeof raw.whenToUse !== 'string' || raw.whenToUse.trim().length === 0 || raw.whenToUse.length > 300)+ (typeof raw.whenToUse !== 'string' ||+ raw.whenToUse.trim().length === 0 ||+ raw.whenToUse.length > 300)) {return { ok: false, reason: 'whenToUse 必须是 1–300 字符的非空字符串' };}@@ -2765,7 +2898,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {if (raw.panel !== undefined) {const p = raw.panel;if (!isPlainObject(p)) return { ok: false, reason: 'panel 必须是对象' };- if (p.title !== undefined && (typeof p.title !== 'string' || p.title.length === 0 || p.title.length > 64)) {+ if (+ p.title !== undefined &&+ (typeof p.title !== 'string' || p.title.length === 0 || p.title.length > 64)+ ) {return { ok: false, reason: 'panel.title 必须是 1–64 字符的字符串' };}// 面板一律由意识自绘(html 必填):declaration 时代的静态 body 面板已随@@ -2775,7 +2911,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {}if (p.minWidth !== undefined &&- (typeof p.minWidth !== 'number' || !Number.isFinite(p.minWidth) || p.minWidth < 120 || p.minWidth > 1200)+ (typeof p.minWidth !== 'number' ||+ !Number.isFinite(p.minWidth) ||+ p.minWidth < 120 ||+ p.minWidth > 1200)) {return { ok: false, reason: 'panel.minWidth 必须是 120–1200 之间的数字' };}@@ -2798,7 +2937,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {const knownButtons = ['maximize', 'detach', 'minimize'];for (const key of Object.keys(sb)) {if (!knownButtons.includes(key)) {- return { ok: false, reason: `panel.systemButtons 只认 ${knownButtons.join(' / ')},未知键:${key}` };+ return {+ ok: false,+ reason: `panel.systemButtons 只认 ${knownButtons.join(' / ')},未知键:${key}`,+ };}if (typeof (sb as Record<string, unknown>)[key] !== 'boolean') {return { ok: false, reason: `panel.systemButtons.${key} 必须是布尔值` };@@ -2817,7 +2959,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {if (p.position !== undefined) {if (p.position === 'top' || p.position === 'bottom') {// 收词但明确拒绝(规则 9 不静默降级):上下停靠等布局引擎嵌套分割就绪后开放。- return { ok: false, reason: 'panel.position 的 top / bottom 暂未支持(排期中),当前可用:left / tab' };+ return {+ ok: false,+ reason: 'panel.position 的 top / bottom 暂未支持(排期中),当前可用:left / tab',+ };}if (p.position === 'right') {// right 退役兼容(见 GHOST_PANEL_POSITIONS 注释):旧包归一化为 left,@@ -2834,7 +2979,9 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {// 页签形态没有拖缝宽度/标准头语义:收词明确拒绝而非静默忽略(规则 9)。if (position === 'tab' &&- (p.minWidth !== undefined || p.defaultFraction !== undefined || p.systemButtons !== undefined)+ (p.minWidth !== undefined ||+ p.defaultFraction !== undefined ||+ p.systemButtons !== undefined)) {return {ok: false,@@ -2867,7 +3014,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {}if (raw.settingsHeight !== undefined) {if (raw.settingsHtml === undefined) {- return { ok: false, reason: '声明了 settingsHeight 但没有 settingsHtml——没有界面就没有高度可言' };+ return {+ ok: false,+ reason: '声明了 settingsHeight 但没有 settingsHtml——没有界面就没有高度可言',+ };}if (typeof raw.settingsHeight !== 'number' ||@@ -2886,7 +3036,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {// 旧名兼容:'model' 静默归一化为 'cindy'(2026-07-11 更名,已装老包不消失)。const name = s === 'model' ? 'cindy' : s;if (typeof name !== 'string' || !(GHOST_SLOTS as readonly string[]).includes(name)) {- return { ok: false, reason: `slots 含未知卡槽 ${JSON.stringify(s)}(可用:${GHOST_SLOTS.join(' / ')})` };+ return {+ ok: false,+ reason: `slots 含未知卡槽 ${JSON.stringify(s)}(可用:${GHOST_SLOTS.join(' / ')})`,+ };}if (slots.includes(name as GhostSlot)) {return { ok: false, reason: `slots 含重复卡槽 ${JSON.stringify(s)}` };@@ -2941,7 +3094,8 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {if (slots.includes('badge') && panel === undefined) {return {ok: false,- reason: 'slots 声明了 "badge" 但缺少 panel——未读点承诺「点开能看到内容」,没有面板的意识点亮了也无处可点',+ reason:+ 'slots 声明了 "badge" 但缺少 panel——未读点承诺「点开能看到内容」,没有面板的意识点亮了也无处可点',};}@@ -2956,18 +3110,30 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {for (const t of raw.tools) {if (!isPlainObject(t)) return { ok: false, reason: 'tools 每项必须是对象' };if (typeof t.name === 'string' && isGhostManifestReservedRecordKey(t.name)) {- return { ok: false, reason: `tools[].name 不允许使用对象保留键名 ${JSON.stringify(t.name)}` };+ return {+ ok: false,+ reason: `tools[].name 不允许使用对象保留键名 ${JSON.stringify(t.name)}`,+ };}if (typeof t.name !== 'string' || !/^[a-z][a-z0-9_-]{0,63}$/.test(t.name)) {- return { ok: false, reason: 'tools[].name 必须是小写字母开头的 1–64 位小写/数字/下划线/连字符' };+ return {+ ok: false,+ reason: 'tools[].name 必须是小写字母开头的 1–64 位小写/数字/下划线/连字符',+ };}- if (seenNames.has(t.name)) return { ok: false, reason: `tools 含重名工具 ${JSON.stringify(t.name)}` };+ if (seenNames.has(t.name))+ return { ok: false, reason: `tools 含重名工具 ${JSON.stringify(t.name)}` };seenNames.add(t.name);- if (typeof t.description !== 'string' || t.description.trim().length === 0 || t.description.length > 1024) {+ if (+ typeof t.description !== 'string' ||+ t.description.trim().length === 0 ||+ t.description.length > 1024+ ) {return { ok: false, reason: 'tools[].description 必须是 1–1024 字符的非空字符串' };}if (t.parameters !== undefined) {- if (!isPlainObject(t.parameters)) return { ok: false, reason: 'tools[].parameters 必须是对象(JSON Schema)' };+ if (!isPlainObject(t.parameters))+ return { ok: false, reason: 'tools[].parameters 必须是对象(JSON Schema)' };try {if (JSON.stringify(t.parameters).length > 16_384) {return { ok: false, reason: 'tools[].parameters 过大(上限 16KB)' };@@ -2979,7 +3145,9 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {tools.push({name: t.name,description: t.description,- ...(t.parameters !== undefined ? { parameters: t.parameters as Record<string, unknown> } : {}),+ ...(t.parameters !== undefined+ ? { parameters: t.parameters as Record<string, unknown> }+ : {}),});}}@@ -3046,7 +3214,11 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {else if (category === 'media') cindy.media = actions as GhostCindyMediaAction[];else if (category === 'text') cindy.text = actions as GhostCindyTextAction[];else if (category === 'embed') cindy.embed = actions as GhostCindyEmbedAction[];- else return { ok: false, reason: `cindy 能力类目 ${JSON.stringify(category)} 尚未接线(主机缺陷)` };+ else+ return {+ ok: false,+ reason: `cindy 能力类目 ${JSON.stringify(category)} 尚未接线(主机缺陷)`,+ };}if (cindy.image === undefined &&@@ -3406,7 +3578,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {preview = { hosts: previewRaw.hosts as string[] };}if (slots.includes('preview') && preview === undefined) {- return { ok: false, reason: 'slots 声明了 "preview" 但缺少 preview 详单(hosts 域名白名单必填)' };+ return {+ ok: false,+ reason: 'slots 声明了 "preview" 但缺少 preview 详单(hosts 域名白名单必填)',+ };}// skill 槽详单:与 slots 含 'skill' **严格成对**(有槽必有详单——捆绑了什么@@ -3417,7 +3592,11 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {let skill: GhostSkillNeeds | undefined;if (raw.skill !== undefined) {if (!isPlainObject(raw.skill)) {- return { ok: false, reason: 'skill 详单必须是对象(如 { "items": [{ "dir": "skills/foo", "name": "foo", "description": "..." }] })' };+ return {+ ok: false,+ reason:+ 'skill 详单必须是对象(如 { "items": [{ "dir": "skills/foo", "name": "foo", "description": "..." }] })',+ };}if (!slots.includes('skill')) {return { ok: false, reason: '声明了 skill 详单但 slots 未包含 "skill"' };@@ -3445,17 +3624,26 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {(key) => key !== 'dir' && key !== 'name' && key !== 'description',);if (unknownItemField !== undefined) {- return { ok: false, reason: `skill.items 条目含不允许的字段 ${JSON.stringify(unknownItemField)}` };+ return {+ ok: false,+ reason: `skill.items 条目含不允许的字段 ${JSON.stringify(unknownItemField)}`,+ };}if (!isSafeGhostRelativePath(itemRaw.dir)) {- return { ok: false, reason: `skill.items[].dir 必须是包内安全相对路径(如 "skills/foo"),得到 ${JSON.stringify(itemRaw.dir)}` };+ return {+ ok: false,+ reason: `skill.items[].dir 必须是包内安全相对路径(如 "skills/foo"),得到 ${JSON.stringify(itemRaw.dir)}`,+ };}if (typeof itemRaw.name !== 'string' ||itemRaw.name.length > GHOST_SKILL_NAME_MAX_CHARS ||!GHOST_SKILL_NAME_RE.test(itemRaw.name)) {- return { ok: false, reason: `skill.items[].name 必须是小写字母/数字加单连字符分段(禁首尾/连续连字符)、长度 1–${GHOST_SKILL_NAME_MAX_CHARS},得到 ${JSON.stringify(itemRaw.name)}` };+ return {+ ok: false,+ reason: `skill.items[].name 必须是小写字母/数字加单连字符分段(禁首尾/连续连字符)、长度 1–${GHOST_SKILL_NAME_MAX_CHARS},得到 ${JSON.stringify(itemRaw.name)}`,+ };}if (typeof itemRaw.description !== 'string' ||@@ -3526,7 +3714,8 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {if (subscribe.hooks !== undefined && raw.launch !== 'resident') {return {ok: false,- reason: '声明了 subscribe.hooks(拦截钩子)必须同时声明 launch: "resident"——拦截要求常驻在场,否则每条消息都要等冷启动',+ reason:+ '声明了 subscribe.hooks(拦截钩子)必须同时声明 launch: "resident"——拦截要求常驻在场,否则每条消息都要等冷启动',};}}@@ -3549,16 +3738,25 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {// 原规则必填 1–8 条(静态域名与动态连接至少有其一)。const hasConnectionDecls = Array.isArray(n.connections) && n.connections.length > 0;if (n.hosts === undefined && !hasConnectionDecls) {- return { ok: false, reason: `network.hosts 必须是 1–${GHOST_NETWORK_MAX_HOSTS} 条的数组(仅声明了 network.connections 时才可缺省)` };+ return {+ ok: false,+ reason: `network.hosts 必须是 1–${GHOST_NETWORK_MAX_HOSTS} 条的数组(仅声明了 network.connections 时才可缺省)`,+ };}- if (n.hosts !== undefined && (!Array.isArray(n.hosts) || n.hosts.length > GHOST_NETWORK_MAX_HOSTS)) {+ if (+ n.hosts !== undefined &&+ (!Array.isArray(n.hosts) || n.hosts.length > GHOST_NETWORK_MAX_HOSTS)+ ) {return { ok: false, reason: `network.hosts 必须是 1–${GHOST_NETWORK_MAX_HOSTS} 条的数组` };}if (Array.isArray(n.hosts) && n.hosts.length === 0 && !hasConnectionDecls) {- return { ok: false, reason: `network.hosts 必须是 1–${GHOST_NETWORK_MAX_HOSTS} 条的数组(仅声明了 network.connections 时才允许为空)` };+ return {+ ok: false,+ reason: `network.hosts 必须是 1–${GHOST_NETWORK_MAX_HOSTS} 条的数组(仅声明了 network.connections 时才允许为空)`,+ };}const hosts: string[] = [];- for (const h of (Array.isArray(n.hosts) ? n.hosts : [])) {+ for (const h of Array.isArray(n.hosts) ? n.hosts : []) {if (typeof h !== 'string' || !isValidGhostNetworkHostPattern(h.trim().toLowerCase())) {return {ok: false,@@ -3573,18 +3771,31 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {}let secrets: GhostSecretDecl[] | undefined;if (n.secrets !== undefined) {- if (!Array.isArray(n.secrets) || n.secrets.length === 0 || n.secrets.length > GHOST_NETWORK_MAX_SECRETS) {- return { ok: false, reason: `network.secrets 必须是 1–${GHOST_NETWORK_MAX_SECRETS} 条的数组` };+ if (+ !Array.isArray(n.secrets) ||+ n.secrets.length === 0 ||+ n.secrets.length > GHOST_NETWORK_MAX_SECRETS+ ) {+ return {+ ok: false,+ reason: `network.secrets 必须是 1–${GHOST_NETWORK_MAX_SECRETS} 条的数组`,+ };}secrets = [];const seenKeys = new Set<string>();for (const s of n.secrets) {if (!isPlainObject(s)) return { ok: false, reason: 'network.secrets 每项必须是对象' };if (typeof s.key === 'string' && isGhostManifestReservedRecordKey(s.key)) {- return { ok: false, reason: `network.secrets[].key 不允许使用对象保留键名 ${JSON.stringify(s.key)}` };+ return {+ ok: false,+ reason: `network.secrets[].key 不允许使用对象保留键名 ${JSON.stringify(s.key)}`,+ };}if (typeof s.key !== 'string' || !/^[a-z][a-z0-9_]{0,31}$/.test(s.key)) {- return { ok: false, reason: 'network.secrets[].key 必须是小写字母开头的 1–32 位小写/数字/下划线' };+ return {+ ok: false,+ reason: 'network.secrets[].key 必须是小写字母开头的 1–32 位小写/数字/下划线',+ };}if (seenKeys.has(s.key)) {return { ok: false, reason: `network.secrets 含重复 key ${JSON.stringify(s.key)}` };@@ -3622,7 +3833,8 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {if (s.input !== undefined && s.input !== 'ghost') {return {ok: false,- reason: 'network.secrets[].input 已退役:Setup 表单直接从 Secret 声明生成,详情页由 settingsHtml 管理(删掉 input 字段即可;唯一可接受的遗留值是 "ghost")',+ reason:+ 'network.secrets[].input 已退役:Setup 表单直接从 Secret 声明生成,详情页由 settingsHtml 管理(删掉 input 字段即可;唯一可接受的遗留值是 "ghost")',};}// login-email:值取自主机登录态派生,用户不填、没有输入面,@@ -3637,7 +3849,8 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {if (!hostDerived && raw.settingsHtml === undefined) {return {ok: false,- reason: 'network.secrets 声明了用户填写的凭证时必须同时声明 settingsHtml(调用前可由 Host Setup 卡收单,settingsHtml 仍是长期管理/替换/清除入口)',+ reason:+ 'network.secrets 声明了用户填写的凭证时必须同时声明 settingsHtml(调用前可由 Host Setup 卡收单,settingsHtml 仍是长期管理/替换/清除入口)',};}if (hostDerived && s.url !== undefined) {@@ -3671,18 +3884,30 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {return { ok: false, reason: 'network.secrets[].url 不是合法的绝对地址' };}if (parsed.protocol !== 'https:' || parsed.username || parsed.password) {- return { ok: false, reason: 'network.secrets[].url 仅支持 https 且不允许内嵌用户名/密码' };+ return {+ ok: false,+ reason: 'network.secrets[].url 仅支持 https 且不允许内嵌用户名/密码',+ };}}if (!isPlainObject(s.inject)) {- return { ok: false, reason: `network.secrets[${JSON.stringify(s.key)}].inject 必填(凭证要声明注入到哪个请求头)` };+ return {+ ok: false,+ reason: `network.secrets[${JSON.stringify(s.key)}].inject 必填(凭证要声明注入到哪个请求头)`,+ };}const inj = s.inject as Record<string, unknown>;if (typeof inj.header !== 'string' || !/^[A-Za-z0-9-]{1,64}$/.test(inj.header)) {- return { ok: false, reason: 'network.secrets[].inject.header 必须是 1–64 位字母/数字/连字符的头名' };+ return {+ ok: false,+ reason: 'network.secrets[].inject.header 必须是 1–64 位字母/数字/连字符的头名',+ };}if (GHOST_NETWORK_FORBIDDEN_INJECT_HEADERS.includes(inj.header.toLowerCase())) {- return { ok: false, reason: `network.secrets[].inject.header 不允许使用协议关键头 ${JSON.stringify(inj.header)}` };+ return {+ ok: false,+ reason: `network.secrets[].inject.header 不允许使用协议关键头 ${JSON.stringify(inj.header)}`,+ };}if (typeof inj.format !== 'string' ||@@ -3690,12 +3915,19 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {inj.format.length > 200 ||inj.format.split('{value}').length !== 2) {- return { ok: false, reason: 'network.secrets[].inject.format 必须是 ≤200 字符且恰含一个 {value} 占位的字符串(如 "Bearer {value}")' };+ return {+ ok: false,+ reason:+ 'network.secrets[].inject.format 必须是 ≤200 字符且恰含一个 {value} 占位的字符串(如 "Bearer {value}")',+ };}let injectHosts: string[] | undefined;if (inj.hosts !== undefined) {if (!Array.isArray(inj.hosts) || inj.hosts.length === 0) {- return { ok: false, reason: 'network.secrets[].inject.hosts 必须是非空数组(或省略 = 全部白名单域名)' };+ return {+ ok: false,+ reason: 'network.secrets[].inject.hosts 必须是非空数组(或省略 = 全部白名单域名)',+ };}injectHosts = [];for (const ih of inj.hosts) {@@ -3707,7 +3939,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {}const ihNorm = ih.trim().toLowerCase();if (injectHosts.includes(ihNorm)) {- return { ok: false, reason: `network.secrets[].inject.hosts 含重复条目 ${JSON.stringify(ih)}` };+ return {+ ok: false,+ reason: `network.secrets[].inject.hosts 含重复条目 ${JSON.stringify(ih)}`,+ };}injectHosts.push(ihNorm);}@@ -3716,19 +3951,22 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {if (inj.header !== 'Authorization' || inj.format !== 'Bearer {value}') {return {ok: false,- reason: 'network.secrets[].source 为 oidc-token 时 inject 必须是 Authorization: Bearer {value}',+ reason:+ 'network.secrets[].source 为 oidc-token 时 inject 必须是 Authorization: Bearer {value}',};}if (injectHosts === undefined) {return {ok: false,- reason: 'network.secrets[].source 为 oidc-token 时必须显式声明非空 inject.hosts,限制企业身份令牌的流向',+ reason:+ 'network.secrets[].source 为 oidc-token 时必须显式声明非空 inject.hosts,限制企业身份令牌的流向',};}if (injectHosts.some((host) => host.startsWith('*.'))) {return {ok: false,- reason: 'network.secrets[].source 为 oidc-token 时 inject.hosts 只允许精确域名,不允许通配',+ reason:+ 'network.secrets[].source 为 oidc-token 时 inject.hosts 只允许精确域名,不允许通配',};}}@@ -3750,11 +3988,18 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {}if (source === 'oauth' && s.exchange !== undefined) {// access token 已是最终注入物,再叠一段 key 换令牌没有语义。- return { ok: false, reason: 'network.secrets[].source 为 oauth 时不允许声明 exchange(access token 直接注入,无二段交换)' };+ return {+ ok: false,+ reason:+ 'network.secrets[].source 为 oauth 时不允许声明 exchange(access token 直接注入,无二段交换)',+ };}if (s.oauth !== undefined) {if (!isPlainObject(s.oauth)) {- return { ok: false, reason: `network.secrets[${JSON.stringify(s.key)}].oauth 必须是对象` };+ return {+ ok: false,+ reason: `network.secrets[${JSON.stringify(s.key)}].oauth 必须是对象`,+ };}const oa = s.oauth as Record<string, unknown>;const parseHostBoundUrl = (@@ -3762,7 +4007,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {field: string,): { ok: true; url: string } | { ok: false; reason: string } => {if (typeof raw2 !== 'string' || raw2.length === 0 || raw2.length > 2048) {- return { ok: false, reason: `network.secrets[].oauth.${field} 必须是 1–2048 字符的字符串` };+ return {+ ok: false,+ reason: `network.secrets[].oauth.${field} 必须是 1–2048 字符的字符串`,+ };}let parsed2: URL;try {@@ -3770,8 +4018,16 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {} catch {return { ok: false, reason: `network.secrets[].oauth.${field} 不是合法的绝对地址` };}- if (parsed2.protocol !== 'https:' || parsed2.port !== '' || parsed2.username || parsed2.password) {- return { ok: false, reason: `network.secrets[].oauth.${field} 仅支持 https 默认端口且不允许内嵌用户名/密码` };+ if (+ parsed2.protocol !== 'https:' ||+ parsed2.port !== '' ||+ parsed2.username ||+ parsed2.password+ ) {+ return {+ ok: false,+ reason: `network.secrets[].oauth.${field} 仅支持 https 默认端口且不允许内嵌用户名/密码`,+ };}if (!hosts.some((pattern) => ghostNetworkHostMatches(pattern, parsed2.hostname))) {return {@@ -3793,13 +4049,19 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {oa.clientId.length > 200 ||/\s/.test(oa.clientId)) {- return { ok: false, reason: 'network.secrets[].oauth.clientId 必须是 1–200 字符、不含空白的字符串' };+ return {+ ok: false,+ reason: 'network.secrets[].oauth.clientId 必须是 1–200 字符、不含空白的字符串',+ };}}let oaClientIdAlternatives: string[] | undefined;if (oa.clientIdAlternatives !== undefined) {if (oa.clientId === undefined) {- return { ok: false, reason: 'network.secrets[].oauth.clientIdAlternatives 必须与默认 clientId 一起声明' };+ return {+ ok: false,+ reason: 'network.secrets[].oauth.clientIdAlternatives 必须与默认 clientId 一起声明',+ };}if (!Array.isArray(oa.clientIdAlternatives) ||@@ -3821,7 +4083,8 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {) {return {ok: false,- reason: 'network.secrets[].oauth.clientIdAlternatives 含非法条目(须为 1–200 字符、不含空白的字符串)',+ reason:+ 'network.secrets[].oauth.clientIdAlternatives 含非法条目(须为 1–200 字符、不含空白的字符串)',};}if (clientId === oa.clientId || oaClientIdAlternatives.includes(clientId)) {@@ -3835,7 +4098,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {}if (oa.clientSecret !== undefined) {if (oa.clientId === undefined) {- return { ok: false, reason: 'network.secrets[].oauth.clientSecret 必须与 clientId 成对声明' };+ return {+ ok: false,+ reason: 'network.secrets[].oauth.clientSecret 必须与 clientId 成对声明',+ };}if (typeof oa.clientSecret !== 'string' ||@@ -3843,21 +4109,38 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {oa.clientSecret.length > 200 ||/\s/.test(oa.clientSecret)) {- return { ok: false, reason: 'network.secrets[].oauth.clientSecret 必须是 1–200 字符、不含空白的字符串' };+ return {+ ok: false,+ reason: 'network.secrets[].oauth.clientSecret 必须是 1–200 字符、不含空白的字符串',+ };}}let oaScopes: string[] | undefined;if (oa.scopes !== undefined) {if (!Array.isArray(oa.scopes) || oa.scopes.length > GHOST_OAUTH_SCOPES_MAX) {- return { ok: false, reason: `network.secrets[].oauth.scopes 必须是 ≤${GHOST_OAUTH_SCOPES_MAX} 条的数组` };+ return {+ ok: false,+ reason: `network.secrets[].oauth.scopes 必须是 ≤${GHOST_OAUTH_SCOPES_MAX} 条的数组`,+ };}oaScopes = [];for (const sc of oa.scopes) {- if (typeof sc !== 'string' || sc.trim().length === 0 || sc.length > 200 || /\s/.test(sc)) {- return { ok: false, reason: `network.secrets[].oauth.scopes 含非法条目 ${JSON.stringify(sc)}(1–200 字符、不含空白)` };+ if (+ typeof sc !== 'string' ||+ sc.trim().length === 0 ||+ sc.length > 200 ||+ /\s/.test(sc)+ ) {+ return {+ ok: false,+ reason: `network.secrets[].oauth.scopes 含非法条目 ${JSON.stringify(sc)}(1–200 字符、不含空白)`,+ };}if (oaScopes.includes(sc)) {- return { ok: false, reason: `network.secrets[].oauth.scopes 含重复条目 ${JSON.stringify(sc)}` };+ return {+ ok: false,+ reason: `network.secrets[].oauth.scopes 含重复条目 ${JSON.stringify(sc)}`,+ };}oaScopes.push(sc);}@@ -3866,27 +4149,45 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {return { ok: false, reason: 'network.secrets[].oauth.pkce 必须是布尔值(缺省 true)' };}if (oa.scopeDelimiter !== undefined && oa.scopeDelimiter !== ',') {- return { ok: false, reason: 'network.secrets[].oauth.scopeDelimiter 目前只支持 ","(缺省 = 空格拼接)' };+ return {+ ok: false,+ reason: 'network.secrets[].oauth.scopeDelimiter 目前只支持 ","(缺省 = 空格拼接)',+ };}let oaExtra: Record<string, string> | undefined;if (oa.extraAuthorizeParams !== undefined) {if (!isPlainObject(oa.extraAuthorizeParams)) {- return { ok: false, reason: 'network.secrets[].oauth.extraAuthorizeParams 必须是对象' };+ return {+ ok: false,+ reason: 'network.secrets[].oauth.extraAuthorizeParams 必须是对象',+ };}const entries = Object.entries(oa.extraAuthorizeParams as Record<string, unknown>);if (entries.length === 0 || entries.length > GHOST_OAUTH_EXTRA_PARAMS_MAX) {- return { ok: false, reason: `network.secrets[].oauth.extraAuthorizeParams 必须是 1–${GHOST_OAUTH_EXTRA_PARAMS_MAX} 条(或省略)` };+ return {+ ok: false,+ reason: `network.secrets[].oauth.extraAuthorizeParams 必须是 1–${GHOST_OAUTH_EXTRA_PARAMS_MAX} 条(或省略)`,+ };}oaExtra = {};for (const [pk, pv] of entries) {if (!/^[a-z][a-z0-9_]{0,31}$/.test(pk)) {- return { ok: false, reason: `network.secrets[].oauth.extraAuthorizeParams 键 ${JSON.stringify(pk)} 必须是小写字母开头的 1–32 位小写/数字/下划线` };+ return {+ ok: false,+ reason: `network.secrets[].oauth.extraAuthorizeParams 键 ${JSON.stringify(pk)} 必须是小写字母开头的 1–32 位小写/数字/下划线`,+ };}if (GHOST_OAUTH_RESERVED_AUTHORIZE_PARAMS.includes(pk)) {- return { ok: false, reason: `network.secrets[].oauth.extraAuthorizeParams 不允许声明协议保留参数 ${JSON.stringify(pk)}` };+ return {+ ok: false,+ reason: `network.secrets[].oauth.extraAuthorizeParams 不允许声明协议保留参数 ${JSON.stringify(pk)}`,+ };}if (typeof pv !== 'string' || pv.length === 0 || pv.length > 200) {- return { ok: false, reason: `network.secrets[].oauth.extraAuthorizeParams[${JSON.stringify(pk)}] 必须是 1–200 字符的字符串` };+ return {+ ok: false,+ reason: `network.secrets[].oauth.extraAuthorizeParams[${JSON.stringify(pk)}] 必须是 1–200 字符的字符串`,+ };}oaExtra[pk] = pv;}@@ -3899,17 +4200,31 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {oa.redirectPort < 1024 ||oa.redirectPort > 65535) {- return { ok: false, reason: 'network.secrets[].oauth.redirectPort 必须是 1024–65535 的整数' };+ return {+ ok: false,+ reason: 'network.secrets[].oauth.redirectPort 必须是 1024–65535 的整数',+ };}}// tokenBroker(可选):XDT server broker slug;secret 在服务端,与// clientSecret 互斥(同时声明说明作者没想清 secret 到底在哪)。if (oa.tokenBroker !== undefined) {- if (typeof oa.tokenBroker !== 'string' || !GHOST_OAUTH_TOKEN_BROKER_RE.test(oa.tokenBroker)) {- return { ok: false, reason: 'network.secrets[].oauth.tokenBroker 必须是小写字母开头的 1–32 位小写/数字/下划线/连字符' };+ if (+ typeof oa.tokenBroker !== 'string' ||+ !GHOST_OAUTH_TOKEN_BROKER_RE.test(oa.tokenBroker)+ ) {+ return {+ ok: false,+ reason:+ 'network.secrets[].oauth.tokenBroker 必须是小写字母开头的 1–32 位小写/数字/下划线/连字符',+ };}if (oa.clientSecret !== undefined) {- return { ok: false, reason: 'network.secrets[].oauth.tokenBroker 与 clientSecret 互斥(broker 模式下 secret 由服务端持有,不随包分发)' };+ return {+ ok: false,+ reason:+ 'network.secrets[].oauth.tokenBroker 与 clientSecret 互斥(broker 模式下 secret 由服务端持有,不随包分发)',+ };}}if (oaClientIdAlternatives !== undefined && oa.tokenBroker === undefined) {@@ -3923,7 +4238,11 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {let oaBounce: { path: string; callbackPath: string } | undefined;if (oa.brokerBounce !== undefined) {if (oa.tokenBroker === undefined || oa.redirectPort === undefined) {- return { ok: false, reason: 'network.secrets[].oauth.brokerBounce 必须与 tokenBroker、redirectPort 同时声明' };+ return {+ ok: false,+ reason:+ 'network.secrets[].oauth.brokerBounce 必须与 tokenBroker、redirectPort 同时声明',+ };}if (!isPlainObject(oa.brokerBounce)) {return { ok: false, reason: 'network.secrets[].oauth.brokerBounce 必须是对象' };@@ -3957,7 +4276,8 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {) {return {ok: false,- reason: 'network.secrets[].oauth.identity.labelPath 必须是 ≤128 字符的点分路径(段名限字母/数字/_/-,如 "email" / "user.name")',+ reason:+ 'network.secrets[].oauth.identity.labelPath 必须是 ≤128 字符的点分路径(段名限字母/数字/_/-,如 "email" / "user.name")',};}// displayTemplate(可选):展示名模板,占位符 `{点分路径}`(路径@@ -3975,11 +4295,14 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {reason: `network.secrets[].oauth.identity.displayTemplate 必须是 1–${GHOST_OAUTH_IDENTITY_TEMPLATE_MAX_CHARS} 字符的字符串`,};}- const placeholders = [...idn.displayTemplate.matchAll(GHOST_OAUTH_IDENTITY_TEMPLATE_PLACEHOLDER_RE)];+ const placeholders = [+ ...idn.displayTemplate.matchAll(GHOST_OAUTH_IDENTITY_TEMPLATE_PLACEHOLDER_RE),+ ];if (placeholders.length === 0) {return {ok: false,- reason: 'network.secrets[].oauth.identity.displayTemplate 必须含至少一个 {点分路径} 占位符(如 "{team} · {user}")',+ reason:+ 'network.secrets[].oauth.identity.displayTemplate 必须含至少一个 {点分路径} 占位符(如 "{team} · {user}")',};}for (const m of placeholders) {@@ -4003,7 +4326,8 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {) {return {ok: false,- reason: 'network.secrets[].oauth.identity.avatarPath 必须是 ≤128 字符的点分路径(段名限字母/数字/_/-,如 "data.avatar_thumb")',+ reason:+ 'network.secrets[].oauth.identity.avatarPath 必须是 ≤128 字符的点分路径(段名限字母/数字/_/-,如 "data.avatar_thumb")',};}idnAvatarPath = idn.avatarPath;@@ -4024,7 +4348,9 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {: {}),...(oa.clientSecret !== undefined ? { clientSecret: oa.clientSecret as string } : {}),...(oaScopes !== undefined ? { scopes: oaScopes } : {}),- ...(oa.scopeDelimiter !== undefined ? { scopeDelimiter: oa.scopeDelimiter as ',' } : {}),+ ...(oa.scopeDelimiter !== undefined+ ? { scopeDelimiter: oa.scopeDelimiter as ',' }+ : {}),...(oa.pkce !== undefined ? { pkce: oa.pkce as boolean } : {}),...(oaExtra !== undefined ? { extraAuthorizeParams: oaExtra } : {}),...(oaIdentity !== undefined ? { identity: oaIdentity } : {}),@@ -4038,11 +4364,17 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {let exchange: GhostSecretExchangeDecl | undefined;if (s.exchange !== undefined) {if (!isPlainObject(s.exchange)) {- return { ok: false, reason: `network.secrets[${JSON.stringify(s.key)}].exchange 必须是对象` };+ return {+ ok: false,+ reason: `network.secrets[${JSON.stringify(s.key)}].exchange 必须是对象`,+ };}const ex = s.exchange as Record<string, unknown>;if (typeof ex.url !== 'string' || ex.url.length === 0 || ex.url.length > 2048) {- return { ok: false, reason: 'network.secrets[].exchange.url 必须是 1–2048 字符的字符串' };+ return {+ ok: false,+ reason: 'network.secrets[].exchange.url 必须是 1–2048 字符的字符串',+ };}let exUrl: URL;try {@@ -4050,8 +4382,16 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {} catch {return { ok: false, reason: 'network.secrets[].exchange.url 不是合法的绝对地址' };}- if (exUrl.protocol !== 'https:' || exUrl.port !== '' || exUrl.username || exUrl.password) {- return { ok: false, reason: 'network.secrets[].exchange.url 仅支持 https 默认端口且不允许内嵌用户名/密码' };+ if (+ exUrl.protocol !== 'https:' ||+ exUrl.port !== '' ||+ exUrl.username ||+ exUrl.password+ ) {+ return {+ ok: false,+ reason: 'network.secrets[].exchange.url 仅支持 https 默认端口且不允许内嵌用户名/密码',+ };}if (!hosts.some((pattern) => ghostNetworkHostMatches(pattern, exUrl.hostname))) {return {@@ -4090,7 +4430,8 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {) {return {ok: false,- reason: 'network.secrets[].exchange.tokenPath 必须是 ≤128 字符的点分路径(段名限字母/数字/_/-,如 "session" / "data.token")',+ reason:+ 'network.secrets[].exchange.tokenPath 必须是 ≤128 字符的点分路径(段名限字母/数字/_/-,如 "session" / "data.token")',};}let exTtl: number | undefined;@@ -4143,14 +4484,18 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {n.connections.length === 0 ||n.connections.length > GHOST_NETWORK_MAX_CONNECTION_DECLS) {- return { ok: false, reason: `network.connections 必须是 1–${GHOST_NETWORK_MAX_CONNECTION_DECLS} 条的数组` };+ return {+ ok: false,+ reason: `network.connections 必须是 1–${GHOST_NETWORK_MAX_CONNECTION_DECLS} 条的数组`,+ };}// 没人收地址和 token:连接的地址与凭证一律由意识 settingsHtml 收单// (经 /connections 协议通道),没有界面就没有入口。if (raw.settingsHtml === undefined) {return {ok: false,- reason: '声明了 network.connections 必须同时声明 settingsHtml(连接地址与凭证由意识设置界面收单,没有界面就没人收单)',+ reason:+ '声明了 network.connections 必须同时声明 settingsHtml(连接地址与凭证由意识设置界面收单,没有界面就没人收单)',};}connections = [];@@ -4160,20 +4505,32 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {for (const c of n.connections) {if (!isPlainObject(c)) return { ok: false, reason: 'network.connections 每项必须是对象' };if (typeof c.key === 'string' && isGhostManifestReservedRecordKey(c.key)) {- return { ok: false, reason: `network.connections[].key 不允许使用对象保留键名 ${JSON.stringify(c.key)}` };+ return {+ ok: false,+ reason: `network.connections[].key 不允许使用对象保留键名 ${JSON.stringify(c.key)}`,+ };}if (typeof c.key !== 'string' || !/^[a-z][a-z0-9_]{0,31}$/.test(c.key)) {- return { ok: false, reason: 'network.connections[].key 必须是小写字母开头的 1–32 位小写/数字/下划线' };+ return {+ ok: false,+ reason: 'network.connections[].key 必须是小写字母开头的 1–32 位小写/数字/下划线',+ };}if (seenConnKeys.has(c.key)) {return { ok: false, reason: `network.connections 含重复 key ${JSON.stringify(c.key)}` };}// 与 secrets 共用键命名空间(保险库派生键同一前缀),撞名拒装。if (secretKeySet.has(c.key)) {- return { ok: false, reason: `network.connections[].key ${JSON.stringify(c.key)} 与 network.secrets 的 key 撞名(两者共用命名空间)` };+ return {+ ok: false,+ reason: `network.connections[].key ${JSON.stringify(c.key)} 与 network.secrets 的 key 撞名(两者共用命名空间)`,+ };}if (nodeSecretKeySet.has(c.key)) {- return { ok: false, reason: `network.connections[].key ${JSON.stringify(c.key)} 与 node.secretBindings 的 key 撞名(两者共用命名空间)` };+ return {+ ok: false,+ reason: `network.connections[].key ${JSON.stringify(c.key)} 与 node.secretBindings 的 key 撞名(两者共用命名空间)`,+ };}seenConnKeys.add(c.key);if (typeof c.label !== 'string' || c.label.trim().length === 0 || c.label.length > 64) {@@ -4186,14 +4543,23 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {return { ok: false, reason: 'network.connections[].hint 必须是 1–200 字符的非空字符串' };}if (!isPlainObject(c.inject)) {- return { ok: false, reason: `network.connections[${JSON.stringify(c.key)}].inject 必填(连接凭证要声明注入到哪个请求头)` };+ return {+ ok: false,+ reason: `network.connections[${JSON.stringify(c.key)}].inject 必填(连接凭证要声明注入到哪个请求头)`,+ };}const cinj = c.inject as Record<string, unknown>;if (typeof cinj.header !== 'string' || !/^[A-Za-z0-9-]{1,64}$/.test(cinj.header)) {- return { ok: false, reason: 'network.connections[].inject.header 必须是 1–64 位字母/数字/连字符的头名' };+ return {+ ok: false,+ reason: 'network.connections[].inject.header 必须是 1–64 位字母/数字/连字符的头名',+ };}if (GHOST_NETWORK_FORBIDDEN_INJECT_HEADERS.includes(cinj.header.toLowerCase())) {- return { ok: false, reason: `network.connections[].inject.header 不允许使用协议关键头 ${JSON.stringify(cinj.header)}` };+ return {+ ok: false,+ reason: `network.connections[].inject.header 不允许使用协议关键头 ${JSON.stringify(cinj.header)}`,+ };}if (typeof cinj.format !== 'string' ||@@ -4201,12 +4567,20 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {cinj.format.length > 200 ||cinj.format.split('{value}').length !== 2) {- return { ok: false, reason: 'network.connections[].inject.format 必须是 ≤200 字符且恰含一个 {value} 占位的字符串(如 "Bearer {value}")' };+ return {+ ok: false,+ reason:+ 'network.connections[].inject.format 必须是 ≤200 字符且恰含一个 {value} 占位的字符串(如 "Bearer {value}")',+ };}if (cinj.hosts !== undefined) {// 注入范围恒等于各连接自身地址(用户添加哪条注入哪条),作者无从// 收窄或扩张——声明即结构性误解,直接拒装。- return { ok: false, reason: 'network.connections[].inject.hosts 不允许声明(连接凭证只注入对应连接自身的地址)' };+ return {+ ok: false,+ reason:+ 'network.connections[].inject.hosts 不允许声明(连接凭证只注入对应连接自身的地址)',+ };}if (c.maxConnections !== undefined) {if (@@ -4215,7 +4589,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {c.maxConnections < 1 ||c.maxConnections > GHOST_NETWORK_MAX_CONNECTIONS_PER_DECL) {- return { ok: false, reason: `network.connections[].maxConnections 必须是 1–${GHOST_NETWORK_MAX_CONNECTIONS_PER_DECL} 的整数(缺省 ${GHOST_NETWORK_MAX_CONNECTIONS_PER_DECL})` };+ return {+ ok: false,+ reason: `network.connections[].maxConnections 必须是 1–${GHOST_NETWORK_MAX_CONNECTIONS_PER_DECL} 的整数(缺省 ${GHOST_NETWORK_MAX_CONNECTIONS_PER_DECL})`,+ };}}connections.push({@@ -4240,36 +4617,48 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {let setup: GhostSetupDecl | undefined;if (raw.setup !== undefined) {if (!isPlainObject(raw.setup)) {- return { ok: false, reason: 'setup 必须是对象(如 { "requires": [{ "anyOf": ["secret:api_key"] }] })' };+ return {+ ok: false,+ reason: 'setup 必须是对象(如 { "requires": [{ "anyOf": ["secret:api_key"] }] })',+ };}const su = raw.setup as Record<string, unknown>;// 空数组是合法的显式 opt-out:「本意识没有使用前置需求」——凭证全为// 可选项的意识用它关掉宿主启发式(不声明才走启发式)。if (!Array.isArray(su.requires) || su.requires.length > GHOST_SETUP_MAX_GROUPS) {- return { ok: false, reason: `setup.requires 必须是 0–${GHOST_SETUP_MAX_GROUPS} 组的数组(空数组 = 显式声明无使用前置需求)` };- }- const secretByKey = new Map<- string,- { hostDerivedSource: 'login-email' | 'oidc-token' | null }- >([- ...(network?.secrets ?? []).map(- (s) => [- s.key,- {- hostDerivedSource:- s.source === 'login-email' || s.source === 'oidc-token' ? s.source : null,- },- ] as const,- ),- ...(node?.secretBindings ?? []).map(- (s) => [s.key, { hostDerivedSource: null }] as const,- ),- ]);+ return {+ ok: false,+ reason: `setup.requires 必须是 0–${GHOST_SETUP_MAX_GROUPS} 组的数组(空数组 = 显式声明无使用前置需求)`,+ };+ }+ const secretByKey = new Map<string, { hostDerivedSource: 'login-email' | 'oidc-token' | null }>(+ [+ ...(network?.secrets ?? []).map(+ (s) =>+ [+ s.key,+ {+ hostDerivedSource:+ s.source === 'login-email' || s.source === 'oidc-token' ? s.source : null,+ },+ ] as const,+ ),+ ...(node?.secretBindings ?? []).map((s) => [s.key, { hostDerivedSource: null }] as const),+ ],+ );const connectionKeys = new Set((network?.connections ?? []).map((c) => c.key));const groups: GhostSetupGroup[] = [];for (const g of su.requires) {- if (!isPlainObject(g) || !Array.isArray(g.anyOf) || g.anyOf.length === 0 || g.anyOf.length > GHOST_SETUP_MAX_ITEMS_PER_GROUP) {- return { ok: false, reason: `setup.requires 每组必须是 { "anyOf": [...] } 且组内 1–${GHOST_SETUP_MAX_ITEMS_PER_GROUP} 条` };+ if (+ !isPlainObject(g) ||+ !Array.isArray(g.anyOf) ||+ g.anyOf.length === 0 ||+ g.anyOf.length > GHOST_SETUP_MAX_ITEMS_PER_GROUP+ ) {+ return {+ ok: false,+ reason: `setup.requires 每组必须是 { "anyOf": [...] } 且组内 1–${GHOST_SETUP_MAX_ITEMS_PER_GROUP} 条`,+ };}const items: GhostSetupRequirement[] = [];const seenRefs = new Set<string>();@@ -4278,40 +4667,72 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {if (typeof it === 'string') {const m = /^(secret|connection):(.+)$/.exec(it);if (!m) {- return { ok: false, reason: `setup 条目 ${JSON.stringify(it)} 形态不对(字符串条目须为 "secret:<key>" 或 "connection:<key>";kv 用对象 { "kv": "<key>", "label": "..." })` };+ return {+ ok: false,+ reason: `setup 条目 ${JSON.stringify(it)} 形态不对(字符串条目须为 "secret:<key>" 或 "connection:<key>";kv 用对象 { "kv": "<key>", "label": "..." })`,+ };}const [, refKind, refKey] = m;if (refKind === 'secret') {const decl = secretByKey.get(refKey);if (!decl) {- return { ok: false, reason: `setup 引用了未声明的凭证 ${JSON.stringify(refKey)}(必须逐字取自 network.secrets[].key 或 node.secretBindings[].key)` };+ return {+ ok: false,+ reason: `setup 引用了未声明的凭证 ${JSON.stringify(refKey)}(必须逐字取自 network.secrets[].key 或 node.secretBindings[].key)`,+ };}if (decl.hostDerivedSource) {- return { ok: false, reason: `setup 不允许引用 ${decl.hostDerivedSource} 源凭证 ${JSON.stringify(refKey)}(Host 派生身份没有用户配置动作可引导)` };+ return {+ ok: false,+ reason: `setup 不允许引用 ${decl.hostDerivedSource} 源凭证 ${JSON.stringify(refKey)}(Host 派生身份没有用户配置动作可引导)`,+ };}item = { kind: 'secret', key: refKey };} else {if (!connectionKeys.has(refKey)) {- return { ok: false, reason: `setup 引用了未声明的连接 ${JSON.stringify(refKey)}(必须逐字取自 network.connections[].key)` };+ return {+ ok: false,+ reason: `setup 引用了未声明的连接 ${JSON.stringify(refKey)}(必须逐字取自 network.connections[].key)`,+ };}item = { kind: 'connection', key: refKey };}} else if (isPlainObject(it)) {if (typeof it.kv === 'string' && isGhostManifestReservedRecordKey(it.kv)) {- return { ok: false, reason: `setup kv 条目的 kv 不允许使用对象保留键名 ${JSON.stringify(it.kv)}` };+ return {+ ok: false,+ reason: `setup kv 条目的 kv 不允许使用对象保留键名 ${JSON.stringify(it.kv)}`,+ };}if (typeof it.kv !== 'string' || !GHOST_SETUP_KV_KEY_RE.test(it.kv)) {- return { ok: false, reason: 'setup kv 条目的 kv 必须是 1–64 位字母/数字/下划线/点/连字符的键名' };+ return {+ ok: false,+ reason: 'setup kv 条目的 kv 必须是 1–64 位字母/数字/下划线/点/连字符的键名',+ };}- if (typeof it.label !== 'string' || it.label.trim().length === 0 || it.label.length > 64) {- return { ok: false, reason: 'setup kv 条目必须带 1–64 字符的 label(kv 键名宿主无先验,弹窗要有名字可展示)' };+ if (+ typeof it.label !== 'string' ||+ it.label.trim().length === 0 ||+ it.label.length > 64+ ) {+ return {+ ok: false,+ reason: 'setup kv 条目必须带 1–64 字符的 label(kv 键名宿主无先验,弹窗要有名字可展示)',+ };}if (raw.settingsHtml === undefined) {- return { ok: false, reason: 'setup 引用了 kv 参数但没有 settingsHtml——参数由意识设置界面收单,没有界面就没人填' };+ return {+ ok: false,+ reason:+ 'setup 引用了 kv 参数但没有 settingsHtml——参数由意识设置界面收单,没有界面就没人填',+ };}item = { kind: 'kv', key: it.kv, label: it.label };} else {- return { ok: false, reason: 'setup.requires[].anyOf 每条必须是字符串引用或 { "kv", "label" } 对象' };+ return {+ ok: false,+ reason: 'setup.requires[].anyOf 每条必须是字符串引用或 { "kv", "label" } 对象',+ };}const ref = `${item.kind}:${item.key}`;if (seenRefs.has(ref)) {@@ -4357,7 +4778,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {if (typeof k !== 'string') return { ok: false, reason: 'keywords 每项必须是字符串' };const word = k.trim();if (word.length < 2 || word.length > 24) {- return { ok: false, reason: `keywords 每项须为 2–24 字符(单字词命中面失控):${JSON.stringify(k)}` };+ return {+ ok: false,+ reason: `keywords 每项须为 2–24 字符(单字词命中面失控):${JSON.stringify(k)}`,+ };}const fold = word.toLowerCase();if (seen.has(fold)) continue; // 重复词静默去重,不拒装@@ -4867,6 +5291,83 @@ export type GhostPipeWorkspaceResult =message: string;};+/** 插件内置模拟器槽协议版本;能力按版本握手,不靠插件自报可用性。 */+export const GHOST_IOS_SIMULATOR_CAPABILITY_API_VERSION = 1 as const;++/**+ * 插件可见的最小模拟器状态。刻意不含 sessionId、UDID、source fingerprint、+ * lease、device grant、mutation state、路径或诊断;这些值既不是状态面板所需,+ * 也可能被滥用于跨任务控制或设备指纹识别。+ */+export interface GhostIOSSimulatorStatusSnapshot {+ environment: {+ platform: string;+ supported: boolean;+ ready: boolean;+ xcodeVersion: string | null;+ availableDeviceCount: number;+ };+ instances: Array<{+ instanceId: string;+ simulatorName: string;+ generation: number;+ lifecycleState: IOSSimulatorPublicInstance['lifecycleState'];+ healthState: IOSSimulatorPublicInstance['healthState'];+ }>;+ routeStatuses: Array<{+ instanceId: string;+ generation: number;+ stream: Pick<IOSSimulatorPublicRouteStatus['stream'], 'adapter' | 'encoding' | 'state'>;+ input: Pick<IOSSimulatorPublicRouteStatus['input'], 'adapter' | 'state'>;+ }>;+}++/** Host 内部的只读投影结果;供 capability slot 消费,不直接跨 preload。 */+export type GhostIOSSimulatorStatusProbeResult =+ | { ok: true; status: GhostIOSSimulatorStatusSnapshot }+ | { ok: false; errorCode: IOSSimulatorMcpErrorCode; message: string };++/** 插件只能请求能力摘要、当前台前任务状态,或打开 Host 面板。 */+export type GhostPipeIOSSimulatorRequest =+ | { type: 'ios-simulator-request'; kind: 'capabilities' }+ | { type: 'ios-simulator-request'; kind: 'status' }+ | { type: 'ios-simulator-request'; kind: 'open-panel'; instanceId?: string };++export type GhostPipeIOSSimulatorErrorCode =+ | IOSSimulatorMcpErrorCode+ | 'PERMISSION_DENIED'+ | 'INVALID_REQUEST'+ | 'INSTANCE_NOT_OWNED'+ | 'RATE_LIMITED'+ | 'HOST_NOT_READY'+ | 'IOS_SIMULATOR_HOST_ERROR';++export type GhostPipeIOSSimulatorResult =+ | {+ ok: true;+ apiVersion: typeof GHOST_IOS_SIMULATOR_CAPABILITY_API_VERSION;+ kind: 'capabilities';+ capabilities: {+ status: true;+ openHostPanel: true;+ pluginVideo: false;+ pluginInput: false;+ };+ }+ | {+ ok: true;+ apiVersion: typeof GHOST_IOS_SIMULATOR_CAPABILITY_API_VERSION;+ kind: 'status';+ status: GhostIOSSimulatorStatusSnapshot;+ }+ | {+ ok: true;+ apiVersion: typeof GHOST_IOS_SIMULATOR_CAPABILITY_API_VERSION;+ kind: 'open-panel';+ instanceId?: string;+ }+ | { ok: false; errorCode: GhostPipeIOSSimulatorErrorCode; message: string };+/*** 上行:preview 槽——请主机在右侧栏内置浏览器打开一个预览标签页。* url 必须命中身份卡 preview.hosts 白名单(ghostPreviewUrlAllowed);@@ -4935,11 +5436,7 @@ export type GhostPipeScheduleDraftResult =| {ok: false;errorCode:- | 'PERMISSION_DENIED'- | 'INVALID_REQUEST'- | 'RATE_LIMITED'- | 'HOST_NOT_READY'- | 'INTERNAL';+ 'PERMISSION_DENIED' | 'INVALID_REQUEST' | 'RATE_LIMITED' | 'HOST_NOT_READY' | 'INTERNAL';message: string;};@@ -5200,7 +5697,12 @@ export const GHOST_NOTIFY_MAX_CHARS = 200;* 校验后翻译渲染(i18n `chat.ghostNotify.<key>`);白名单外的键静默丢弃,* 防版本错配时把生肉 key 摆上界面。*/-export const GHOST_HOST_NOTICE_KEYS = ['secretSaved', 'oauthConnected', 'oauthConnectedNoLabel', 'connectionAdded'] as const;+export const GHOST_HOST_NOTICE_KEYS = [+ 'secretSaved',+ 'oauthConnected',+ 'oauthConnectedNoLabel',+ 'connectionAdded',+] as const;export type GhostHostNoticeKey = (typeof GHOST_HOST_NOTICE_KEYS)[number];/** 同一意识两条提示的最小间隔 ms(超发拒收,防 toast 刷屏骚扰)。 */@@ -5238,7 +5740,13 @@ export type GhostPipeConfirmResult =| { ok: true; confirmed: boolean }| {ok: false;- errorCode: 'PERMISSION_DENIED' | 'INVALID_REQUEST' | 'RATE_LIMITED' | 'BUSY' | 'UNAVAILABLE' | 'INTERNAL';+ errorCode:+ | 'PERMISSION_DENIED'+ | 'INVALID_REQUEST'+ | 'RATE_LIMITED'+ | 'BUSY'+ | 'UNAVAILABLE'+ | 'INTERNAL';message: string;};@@ -5995,16 +6503,11 @@ export interface GhostEventInteractionActivityData {requestId: string;}-export type GhostEventActivityData =- | GhostEventThinkingData- | GhostEventInteractionActivityData;+export type GhostEventActivityData = GhostEventThinkingData | GhostEventInteractionActivityData;/** 所有 did- 旁听事件共享的安全元数据载荷。 */export type GhostDidEventData =- | GhostEventTurnStartData- | GhostEventTurnEndData- | GhostEventSessionData- | GhostEventActivityData;+ GhostEventTurnStartData | GhostEventTurnEndData | GhostEventSessionData | GhostEventActivityData;/*** 下行:主机 → 意识的事件推送(经管子 onHostMessage 到达)。@@ -6280,8 +6783,20 @@ export interface GhostFsListEntry {/** 代写文件的返回(cindy.send 的 resolve 值;失败带人话原因,永不 reject)。 */export type GhostPipeFsResult =- | { ok: true; op: 'write'; /** 落盘后的相对路径(save 档为消毒去重后的文件名)。 */ path: string; bytes: number }- | { ok: true; op: 'read'; path: string; content: string; encoding: 'utf8' | 'base64'; bytes: number }+ | {+ ok: true;+ op: 'write';+ /** 落盘后的相对路径(save 档为消毒去重后的文件名)。 */ path: string;+ bytes: number;+ }+ | {+ ok: true;+ op: 'read';+ path: string;+ content: string;+ encoding: 'utf8' | 'base64';+ bytes: number;+ }| { ok: true; op: 'list'; entries: GhostFsListEntry[]; truncated?: boolean }| { ok: true; op: 'delete'; path: string; /** false = 本来就不存在(幂等)。 */ existed: boolean }| { ok: false; message: string };diff --git a/apps/desktop/src/shared/iosSimulatorIpc.ts b/apps/desktop/src/shared/iosSimulatorIpc.tsindex a252798779..3587c5bd0b 100644--- a/apps/desktop/src/shared/iosSimulatorIpc.ts+++ b/apps/desktop/src/shared/iosSimulatorIpc.ts@@ -12,7 +12,17 @@ import type {} from '@cindy/ios-simulator-runtime';import type { IOSSimulatorMcpErrorCode, IOSSimulatorMcpToolName } from '@cindy/mcps';-export type IOSSimulatorPublicDevice = Omit<IOSSimulatorDevice, 'availabilityError'>;+export type IOSSimulatorPublicDeviceOwnership = 'unowned' | 'current-task' | 'other-task';++export type IOSSimulatorPublicDeviceUnavailableReason =+ { code: 'missing-runtime'; runtimeName: string } | { code: 'device-unavailable' };++export type IOSSimulatorPublicDevice = Omit<IOSSimulatorDevice, 'availabilityError'> & {+ /** Optional so an older Host status remains consumable by a newer renderer. */+ ownership?: IOSSimulatorPublicDeviceOwnership;+ /** Renderer-safe diagnosis; raw CoreSimulator errors stay in Main. */+ unavailableReason?: IOSSimulatorPublicDeviceUnavailableReason | null;+};export type IOSSimulatorPublicRuntime = Omit<IOSSimulatorRuntimeInfo, 'availabilityError'>;@@ -32,15 +42,17 @@ export interface IOSSimulatorPublicViewport {orientation: IOSSimulatorOrientation;}+export interface IOSSimulatorPublicResourceStatus {+ runningCount: number;+ softLimit: number;+ hardLimit: number;+ maxInstancesPerTask: number;+}+export type IOSSimulatorPublicRouteAdapter = 'native-sidecar' | 'wda' | null;export type IOSSimulatorPublicRouteState =- | 'idle'- | 'detecting'- | 'active'- | 'fallback'- | 'reconnecting'- | 'unavailable';+ 'idle' | 'detecting' | 'active' | 'fallback' | 'reconnecting' | 'unavailable';/** Stable, renderer-safe reason codes for the selected simulator routes. */export type IOSSimulatorPublicRouteReasonCode =@@ -79,8 +91,7 @@ export interface IOSSimulatorPublicRouteStatus {}/** Shared channel name so main, preload and renderer cannot drift. */-export const IOS_SIMULATOR_ROUTE_STATUS_CHANNEL =- 'maker:ios-simulator:route-status' as const;+export const IOS_SIMULATOR_ROUTE_STATUS_CHANNEL = 'maker:ios-simulator:route-status' as const;export type IOSSimulatorSessionStatus =| {@@ -90,6 +101,8 @@ export type IOSSimulatorSessionStatus =instances: IOSSimulatorPublicInstance[];deviceGrants: IOSSimulatorDeviceGrant[];mutationStates: IOSSimulatorMutationState[];+ /** Optional for compatibility with older Host builds. */+ resource?: IOSSimulatorPublicResourceStatus;/** Optional for compatibility with older detached/sidebar renderers. */routeStatuses?: IOSSimulatorPublicRouteStatus[];}@@ -164,7 +177,10 @@ export interface IOSSimulatorLiveTouchRequest extends IOSSimulatorViewerRouteReqexport interface IOSSimulatorFocusRequest {sessionId: string;- instanceId: string;+ /** Omitted when a Host capability only needs to open the unbound simulator panel. */+ instanceId?: string;+ /** false for plugin/automation requests that must not steal focus as a direct user gesture. */+ userInitiated?: boolean;}export type IOSSimulatorH264FramePush = {diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.tsindex c9a73c7319..01e34741b2 100644--- a/apps/desktop/src/shared/ipc-errors.ts+++ b/apps/desktop/src/shared/ipc-errors.ts@@ -112,6 +112,7 @@ export type IpcErrorCode =| 'TERMINAL_ALREADY_DISPOSED' // 在已 dispose 的 session 上调 restart 等操作// 意识(.cindy 装入)| 'GHOST_FILE_INVALID' // 不是合法 zip / 缺 ghost.json / 清单不合格 / 超限+ | 'GHOST_HOST_UNSUPPORTED' // 插件包合法,但当前 Cindy 不认识其 schema / capability slot| 'GHOST_COMMAND_CONFLICT' // 显式指令与已装意识撞名(装入拒绝)| 'GHOST_ID_RESERVED' // id 属官方保留前缀(cindy-),用户通道拒装(防抢注蹭凭证别名)// 自定义插件市场源(Git / 本地文件夹)@@ -247,6 +248,7 @@ const IPC_ERROR_CODES: ReadonlySet<IpcErrorCode> = new Set<IpcErrorCode>(['TERMINAL_SHELL_NOT_FOUND','TERMINAL_ALREADY_DISPOSED','GHOST_FILE_INVALID',+ 'GHOST_HOST_UNSUPPORTED','GHOST_COMMAND_CONFLICT','GHOST_ID_RESERVED','MARKET_SOURCE_INVALID',diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.mdindex a55208acd4..9687355cf6 100644--- a/docs/dev-rules/plugin-security-and-authoring.md+++ b/docs/dev-rules/plugin-security-and-authoring.md@@ -24,17 +24,17 @@## 事实来源-| 内容 | 权威来源 |-|---|---|-| 编写手册(作者唯一教材,现拿现读) | `apps/desktop/src/main/cindy-brain/forge.ts` 的 `FORGE_GUIDE`,经 `ghost_forge_guide` 工具下发 |-| 身份卡字段与校验、管子协议类型 | `apps/desktop/src/shared/ghost.ts`(`validateGhostManifest`、`cindy.send` / `cindy.onHostMessage` 类型) |-| 打包限制 | `apps/desktop/src/main/cindy-brain/forge.ts` 的 `packGhostDir` |-| 运行时、沙箱进程与生命周期 | `apps/desktop/src/main/cindy-brain/runtime/GhostRuntime.ts`、`GhostManager.ts` |-| 能力 slot(网络/通知/确认/文件系统/技能/宿主等) | `apps/desktop/src/main/cindy-brain/networkSlot.ts`、`notifySlot.ts`、`badgeSlot.ts`(未读角标,落盘账本 `ghostUnreadStore.ts`)、`confirmSlot.ts`(往返桥 `ghostConfirmDialogBridge.ts`,renderer 落地 `cindy-brain/GhostConfirmDialogHost.tsx`)、`fsSlot.ts`、`cindySlot.ts`、`skillSlot.ts`、`agentSlot.ts`、`errandSlot.ts`(派活执行链在 `maker-ipc/ghostErrandRunner.ts`,每插件配置在 `errandPrefsStore.ts`) |-| 面板供片、注入主题 token 与协议 | `apps/desktop/src/renderer/cindy-brain/ghostPanelTheme.ts`、`cindy-ghost://` 分支 |-| 权限注入/更新确认 UI | `apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx` |-| 远程/手机版能力准入白名单 | `packages/device-link/src/allowlist.ts` |-| 行为与安全不变量 | `apps/desktop/src/main/cindy-brain/__tests__/`、`forge.test.ts` |+| 内容 | 权威来源 |+| ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| 编写手册(作者唯一教材,现拿现读) | `apps/desktop/src/main/cindy-brain/forge.ts` 的 `FORGE_GUIDE`,经 `ghost_forge_guide` 工具下发 |+| 身份卡字段与校验、管子协议类型 | `apps/desktop/src/shared/ghost.ts`(`validateGhostManifest`、`cindy.send` / `cindy.onHostMessage` 类型) |+| 打包限制 | `apps/desktop/src/main/cindy-brain/forge.ts` 的 `packGhostDir` |+| 运行时、沙箱进程与生命周期 | `apps/desktop/src/main/cindy-brain/runtime/GhostRuntime.ts`、`GhostManager.ts` |+| 能力 slot(网络/通知/确认/文件系统/技能/宿主等) | `apps/desktop/src/main/cindy-brain/networkSlot.ts`、`notifySlot.ts`、`badgeSlot.ts`(未读角标,落盘账本 `ghostUnreadStore.ts`)、`confirmSlot.ts`(往返桥 `ghostConfirmDialogBridge.ts`,renderer 落地 `cindy-brain/GhostConfirmDialogHost.tsx`)、`fsSlot.ts`、`cindySlot.ts`、`skillSlot.ts`、`agentSlot.ts`、`errandSlot.ts`(派活执行链在 `maker-ipc/ghostErrandRunner.ts`,每插件配置在 `errandPrefsStore.ts`)、`iosSimulatorSlot.ts`(当前台前任务的公开状态与 Host viewer 入口) |+| 面板供片、注入主题 token 与协议 | `apps/desktop/src/renderer/cindy-brain/ghostPanelTheme.ts`、`cindy-ghost://` 分支 |+| 权限注入/更新确认 UI | `apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx` |+| 远程/手机版能力准入白名单 | `packages/device-link/src/allowlist.ts` |+| 行为与安全不变量 | `apps/desktop/src/main/cindy-brain/__tests__/`、`forge.test.ts` |文档与实现冲突时以代码为准,但必须在同一改动内同步修正本文与手册。@@ -132,6 +132,13 @@再次核对根与目标真身;保存文件必须排他创建且不跟随最终 symlink,不能让短命票据留下消费期TOCTOU。附件继续使用裁决前已读入的字节,不得在批准后重新跟随原始路径。- 面板供片与注入的主题 token 只用 `ghostPanelTheme.ts` 白名单内的值,不扩大暴露面。+- `ios-simulator` 槽只允许读取 Host 当前台前任务的公开模拟器状态,并请求打开既有+ Host viewer。请求协议不得出现插件自报 `sessionId`,可选 `instanceId` 必须重新匹配+ 当前任务的公开实例。视频帧、viewer lease、触控、Sidecar/Helper、artifact 路径、进程+ 句柄和私有诊断都不得跨进插件沙箱;Agent 侧构建/安装/控制继续走 Host 注册的+ `cindy_ios_simulator` MCP。该能力是本机 Desktop 专属,不进入 device-link/mobile,+ SSH/远程任务 fail closed。状态查询必须走脱敏、短缓存、无副作用的只读投影,不得借+ panel 轮询执行 ownership reconcile、续租、启动 WDA/Sidecar 或创建 driver。## 5. 存量插件兼容:升级必须无感(红线)@@ -242,6 +249,10 @@(救不了「从引入版降到引入前」那一段,任何方案都救不了)。改动方向本身要过第 5 节红线评估:放宽校验等于让主机接受读不全的权限声明,不能顺手做。**触及 `validateGhostManifest()`的枚举白名单、或 `GhostManager.list()` 的跳过逻辑时必须一并考虑。**+ 新版 Host 的本地装入/更新/inspect 已先识别“未来 `schemaVersion`”与“形状合法但未知的+ 字符串 slot”,并以 `GHOST_HOST_UNSUPPORTED` 引导升级,不再把这两类新能力包误报为非法。+ 这只改善新版 Host 的错误分类,不改变严格校验,也无法追改已经发布的旧 Host;已装插件在+ 客户端降级后从列表消失的兼容缺口仍然存在。- `networkSlot.ts` 的 `as: 'media'` 不能只信任 Content-Type(GLB 常见`application/octet-stream`),需要安全的 magic-byte/扩展名嗅探。- SSH 远程场景必须让 `LiziMcpSessionContext` 携带 remote 标识;目录过户不得回退读取本机diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.mdindex c4109b3d9f..1082b4f2de 100644--- a/i18n/GLOSSARY.md+++ b/i18n/GLOSSARY.md@@ -187,6 +187,10 @@ OAuth 2.0 Device Authorization Grant 中由用户在另一设备验证页输入设备间数据在发送端加密、接收端解密,中转服务只搬运密文。当前先按四语言常用安全术语登记为待讨论,避免 E2EE、端对端加密、End-to-End 暗号化等多套可见说法并存。+### iOS Simulator++Apple Simulator 与 Cindy 内置查看器能力的用户可见名称。iOS 保留官方大小写;中文使用「模拟器」,日语使用「シミュレータ」,韩语使用「시뮬레이터」。先登记为 proposed,待插件与内置面板文案稳定后固化。+### LarkLark 国际版 IM 服务的官方品牌名,四语统一保留原品牌写法;先登记为 proposed,待产品术语评审后再决定是否固化。diff --git a/i18n/glossary.json b/i18n/glossary.jsonindex b4293c4293..bbb8c7cb18 100644--- a/i18n/glossary.json+++ b/i18n/glossary.json@@ -1,16 +1,9 @@{"$schema": "./glossary.schema.json","version": 1,- "locales": [- "en",- "zh-CN",- "ja",- "ko"- ],+ "locales": ["en", "zh-CN", "ja", "ko"],"sourceLocale": "en",- "punctuationExempt": [- "desktop:settings.help.qnaFeedbackBodyTemplate"- ],+ "punctuationExempt": ["desktop:settings.help.qnaFeedbackBodyTemplate"],"terms": [{"id": "active",@@ -286,9 +279,7 @@]},"note": "产品一级概念,四语统一保留英文原词。zh-CN 现状 44:5 已是主流;ja / ko 实测拉丁 Agent 同样是主流(59:38 / 58:39),故三语一致(2026-07 修正:此前误按抽样声明为片假名 エージェント / 한글 에이전트,那是少数派)。「代理」一词在中文 UI 里整体废弃——Agent 与 Proxy 都保留英文,不共用这个译名;「代理」按英文源分别登记在 agent / subagent / proxy 三条下(条件禁用),不再统一挂 proxy——统一登记会让自动替换无法确定目标:2026-07 一次批量重放就把 \"Agent\"→「代理」的 4 处和 \"Subagent models\" 的 4 处一并换成了 Proxy,产出「子 Proxy 模型」这种错译。引入术语表时全仓仅 9 处「代理」,已全部清理为 Agent / Subagent / Proxy。豁免 settings.remote 整段:那里的 agent 指 ssh-agent(英文原文即 \"SSH agent\" / \"probe agent\"),是与产品 Agent 同形的另一个概念。",- "exempt": [- "desktop:settings.remote."- ]+ "exempt": ["desktop:settings.remote."]},{"id": "author",@@ -332,12 +323,8 @@]},"forbidden": {- "ja": [- "オートメーション"- ],- "ko": [- "오토메이션"- ]+ "ja": ["オートメーション"],+ "ko": ["오토메이션"]},"note": "scheduler 的模块名、单条实例与能力名统一用「自动化」;不再把「自动任务」「自动化任务」登记为用户可见译法,避免与产品条目 Session(同样叫「任务」)在『删除自动化和任务』等文案里相撞。Computer Use 是另一个概念,用「自动操作电脑 / 浏览器」,改成「自动化电脑」反而不通。因此 zh-CN 只保留「自动操作」这一语境豁免。术语门禁只扫描 locale,不扫描源码注释;历史注释与测试 fixture 的旧称按 docs/product-rules/task-and-conversation-naming.md §6.0.5 逐条判断,不借术语改名机械扩大代码改动。(2026-07 修正:ja 原声明 オートメーション 仅 37/121,主流是 自動化;ko 的 자동화 75/121 本就正确。)豁免通讯录授权提示的两个 key:那里指的是 macOS 系统设置里的面板名,日文官方标签是「オートメーション」而非产品术语「自動化」——照产品术语改会让用户按提示在系统设置里找不到对应项,授权恢复路径直接断掉。zh-CN 的「自动化」与 ko 的「자동화」恰好就是各自的 macOS 官方标签,不受影响。","exempt": [@@ -376,9 +363,7 @@},"checkCase": false,"forbidden": {- "zh-CN": [- "聊天"- ]+ "zh-CN": ["聊天"]},"note": "Chat 专指任务内人与 AI 交流的过程与内容(对话区 / 对话正文 / 对话记录 / 继续对话),中文「对话」。指那个可打开可删除的条目时用 Session(中文「任务」)——此前 Chat 与 Session 混用同一个中文词的问题已随 2026-07-31 的改名解决:英文侧指容器的 Chat 已改为 Session。「聊天」一律禁用。ja / ko 保留各自既有译法。"},@@ -401,9 +386,7 @@]},"note": "Orca 多 Agent 功能名,中文用「协同」(现状 21:2)。可见 bug:设置导航项写「协作」,点进去页面标题写「协同」。条件禁用:settings.contacts 里的「协作经历」是 collaboration history,属另一个语义,英文源不含独立 Collaboration 一词时不判违规。",- "exempt": [- "desktop:settings.contacts."- ]+ "exempt": ["desktop:settings.contacts."]},{"id": "collapse",@@ -559,17 +542,8 @@"ko": "추론 강도"},"forbidden": {- "zh-CN": [- "思考强度",- "思考深度",- "推理深度",- "努力程度",- "推理力度"- ],- "ja": [- "推論レベル",- "推論の強度"- ]+ "zh-CN": ["思考强度", "思考深度", "推理深度", "努力程度", "推理力度"],+ "ja": ["推論レベル", "推論の強度"]},"note": "模型的推理投入档位(low/medium/high/…)。用「推理强度」有三重依据:①同类工具 i18n 里断层第一(GitHub 代码搜索共现量级 1452,第二名「思考强度」431);②OpenAI 简中帮助中心即用此词;③跨 provider 中立——Cindy 的 create_worker 用一个 effort 同时映射 Codex reasoning effort 与 Claude thinking 预算,而 Anthropic 官方简中叫「努力程度」、OpenAI 叫「推理强度」,需要不偏向任一方的词。禁用项各有硬理由:「思考深度」「推理深度」会与国内产品普遍的「深度思考」开关撞车,且语义错误(低 effort 是想得少,不是想得浅);「努力程度」在中文里强烈指向人的绩效评价;「推理等级/级别」未入禁用但不推荐——Cindy 已有 model tier 概念,「等级」易被读成模型档位。"},@@ -584,10 +558,7 @@},"checkCase": false,"forbidden": {- "zh-CN": [- "工单",- "议题"- ],+ "zh-CN": ["工单", "议题"],"ja": [{"text": "課題",@@ -658,10 +629,7 @@"ko": "플러그인"},"forbidden": {- "zh-CN": [- "Plugin",- "plugin"- ]+ "zh-CN": ["Plugin", "plugin"]},"note": "中文一律「插件」,不保留英文原词(现状 94:4)。历史上 Ghost / Plugin 两种叫法并存,对外统一为「插件」。","exempt": []@@ -687,9 +655,7 @@"ko": "프로젝트"},"forbidden": {- "zh-CN": [- "Project"- ]+ "zh-CN": ["Project"]},"note": "中文一律「项目」(现状 119:15)。同一个侧边栏里筛选叫「项目」、批量操作提示叫「Project」是既有 bug。小写 project 不入 forbidden——它常出现在路径与文件名里(project.json)。","exempt": []@@ -712,10 +678,7 @@]},"forbidden": {- "zh-CN": [- "提供方",- "提供商"- ],+ "zh-CN": ["提供方", "提供商"],"ja": [{"text": "提供元",@@ -726,10 +689,7 @@"whenEn": "Provider"}],- "ko": [- "공급자",- "제공업체"- ]+ "ko": ["공급자", "제공업체"]},"note": "中文用「供应商」(现状 36:18 领先简称)。全称「模型供应商」在需要消歧的位置仍可用。「提供商」「提供方」是同义漂移,禁用——设置页标题写「模型供应商」、它自己的表单写「提供商」是既有 bug。豁免 ssoVerificationSubtitle:那里的「身份提供方」是 SSO / SAML 领域 Identity Provider 的标准中文术语,与模型供应商是两个概念。该文案在 desktop locale 与 mobile 影子 catalog 各有一份副本,两处都要豁免。(2026-07 修正:ko 原声明 제공업체 仅 6 处,实测 제공자 32 处为主流,改随主流。)ja 的「提供元」是多义词——同时表示 \"source\"(来源),因此按 whenEn=Provider 条件禁用;无条件禁会把「共有元の提供元を信頼できるか」这类 source 语境一并换掉。豁免 creditParity 两条:那里的 third-party providers 指支付渠道/收单机构,不是模型供应商——ja 用「事業者」、zh-CN 用「第三方渠道」都对,套上「プロバイダー」反而会让用户以为是模型服务商在收钱。(2026-07 更新:billing 弃用「点数」概念改用金额/余额,creditParityCny/Usd 两条文案已删除,对应豁免一并移除。)","exempt": [@@ -767,9 +727,7 @@},"checkCase": false,"forbidden": {- "ja": [- "残量"- ],+ "ja": ["残量"],"zh-CN": [{"text": "额度",@@ -826,9 +784,7 @@},"checkCase": false,"forbidden": {- "zh-CN": [- "会话"- ]+ "zh-CN": ["会话"]},"note": "面向用户叫「任务」——它是左侧列表里可单独打开/删除/分享的条目,有自己的独立空间、可以同时跑多个;「对话」表达不出这个并行性(2026-07-31 裁决,替代此前的「对话」)。任务内人与 AI 交流的过程与内容仍叫「对话」,见 alsoAllowed 与 chat 条目。「会话」继续禁用于产品概念。但英文的 session 在本仓实际承载**五个**不同概念,其中最容易译错、也最影响用户行为的是 Agent 运行时会话——已单独立为 agent-session 条目,中文叫「Agent 会话」,务必先读它再改这类文案;余下三类(登录/绑定校验、SSH 远程与传输、操作系统桌面)与 mobile 语音连接会话都与产品无关,存量译法不在本条约束内,见本条 exempt。代码与内部标识仍用 Session,本条只约束 UI 文案。ja / ko 用音译 `セッション` / `세션`,本次一并收敛:改名前这两种语言就在混用(音译 271 / 277 处 vs `会話`・`대화` 16 / 11 处),改完英文后不一致放大到 133 处,2026-07-31 逐条判断后统一到音译(详见 docs/product-rules/task-and-conversation-naming.md §5.1)。日韩不存在中文那种一词多义问题,所以 `タスク` / `작업`(task)无需像中文那样改写成「自动化」。交流过程仍用 `会話` / `대화`,chat history 仍用 `チャット履歴` / `채팅 기록`。概念分层与判定规则见 docs/product-rules/task-and-conversation-naming.md。","exempt": [@@ -907,9 +863,7 @@}]},- "exempt": [- "desktop:chat.userMessage.forkErrors.unsupportedHistory"- ],+ "exempt": ["desktop:chat.userMessage.forkErrors.unsupportedHistory"],"note": "Agent / 引擎的**运行时**会话(SDK Query 的生命周期),不是 session 条目说的那个产品条目。中文必须叫「Agent 会话」而不是「任务」——两者的区别是用户会不会因此做一个多余的动作:记忆、MCP、内置工具、LSP、权限开关这类设置都在「下一个 Agent 会话」生效,而同一条任务里 /clear、rewind、重启都会开新的 Agent 会话,说「新建任务才生效」会让用户白开一条任务、还割裂上下文。forbidden 规则只覆盖英文源字面写了 agent session 的 key(精确、无误报);英文只写 session 的那批(`The Codex session state` / `Session is inactive` / `in-flight sessions`)**机器判不出来**——英语本身不区分这两个意思,同一句里两个所指并存也是合法的(`The historical agent session ... so a new session can't be started`:前半指运行时、后半指条目,已登记 exempt)。所以这批只能靠人读英文源判断,判据与全部踩坑记录见 docs/product-rules/task-and-conversation-naming.md §6.0.2。session 条目的 exempt 里另有三类同样叫 session 的东西:登录/绑定校验会话、SSH 远程与传输会话、操作系统桌面会话,以及 mobile 的语音连接会话——它们各自稳定、极少改动,故未单独立条目。"},{@@ -962,12 +916,8 @@]},"forbidden": {- "ja": [- "技能"- ],- "ko": [- "기술"- ]+ "ja": ["技能"],+ "ko": ["기술"]},"note": "中文用「技能」(现状 32:26 领先),偶尔保留英文 Skill 也允许,故 zh-CN 不设 forbidden——硬性禁用会逼出别扭的中文。ja / ko 则禁用 技能 / 기술:那是与 スキル / 스킬 并存的同义漂移,且只出现在 skillhub 内部(3 / 3 处)。ko 的 기술 是多义词(技术 / 记述 / 技能),两处非 Skill 义已按 key 豁免。SkillHub 作为产品名单独登记在 skillhub 条目。(2026-07 补充:alsoAllowed 允许保留英文,那就必须是规范形态 Skill——caseStandardFor 会把这类条目一并纳入大小写检查,skillhub 里原有 10 处小写 skill 已统一。)","exempt": [@@ -985,12 +935,8 @@"ko": "SkillHub"},"forbidden": {- "ja": [- "スキルハブ"- ],- "ko": [- "스킬 허브"- ]+ "ja": ["スキルハブ"],+ "ko": ["스킬 허브"]},"note": "产品名,四语一律保留英文原样(暂定保留,未来若做中文名再改)。注意与 skill 条目区分:侧边栏 tab 现在叫「技能」但实际指 SkillHub,创建面板的「技能」指 Skills——这是既有 bug,两者不是一个东西不该同名,清理存量时需一并处理。"},@@ -1036,9 +982,7 @@]},"forbidden": {- "zh-CN": [- "线程"- ]+ "zh-CN": ["线程"]},"note": "按语境分四类:①指产品内那个条目 → 跟随 session 叫「任务」(2026-07-31 随 session 改名一并更新);②Codex 外部概念 → 保留 thread;③GitHub PR review thread →「review 评论」;④比喻用法 \"persistent work thread\" → 改写为「持续推进的工作」。「线程」一律禁用。"},@@ -1052,17 +996,9 @@"ko": "사용량"},"forbidden": {- "zh-CN": [- "使用情况",- "使用表现"- ],- "ja": [- "使用状況",- "利用状況"- ],- "ko": [- "사용 현황"- ]+ "zh-CN": ["使用情况", "使用表现"],+ "ja": ["使用状況", "利用状況"],+ "ko": ["사용 현황"]},"note": "中文用「用量」(现状 37:6 压倒性)。「使用情况」「使用表现」是同义漂移,禁用。注意 usage 在英文里也有「用法」义(如 CLI usage),那属于另一个概念,不在本条约束范围。豁免遥测说明两处:那里的 usage 指「启动与留存情况」这类使用行为,不是计费口径的用量指标。硬套成「用量」会写出「启动与留存用量」这种不通的话——zh-CN 用的是「留存情况」+「使用环境」,ja/ko 的「継続利用状況」「지속 사용 현황」同理。","exempt": [@@ -1092,6 +1028,17 @@},"note": "设备间数据在发送端加密、接收端解密,中转服务只搬运密文。当前先按四语言常用安全术语登记为待讨论,避免 E2EE、端对端加密、End-to-End 暗号化等多套可见说法并存。"},+ {+ "id": "ios-simulator",+ "status": "proposed",+ "en": "iOS Simulator",+ "translations": {+ "zh-CN": "iOS 模拟器",+ "ja": "iOS シミュレータ",+ "ko": "iOS 시뮬레이터"+ },+ "note": "Apple Simulator 与 Cindy 内置查看器能力的用户可见名称。iOS 保留官方大小写;中文使用「模拟器」,日语使用「シミュレータ」,韩语使用「시뮬레이터」。先登记为 proposed,待插件与内置面板文案稳定后固化。"+ },{"id": "worker","status": "decided",@@ -1115,10 +1062,7 @@},"checkCase": false,"forbidden": {- "zh-CN": [- "任务空间",- "工作空间"- ]+ "zh-CN": ["任务空间", "工作空间"]},"note": "Agent 干活所在的那个目录,中文一律「工作目录」(现状 43:0,四语唯一译法)。**不绑项目的任务也有工作目录**:Cindy 在 userData/dialogues/<日期>/<sessionId>/ 下自动分配一个空目录,用来存 Agent 产出的文件;对话消息存在数据库里,与该目录无关。这个目录不要另起名字——「独立任务空间」「任务空间」「工作空间」一类新造说法一并禁用(2026-07-31 裁决),免得同一个东西攒出多套称呼。「工作区」不入 forbidden:它是 Workspace 的合法译法,见 worktree 条目 note(那里已裁定「工作区」只留给 Workspace、working directory 用「工作目录」,本条把该裁决提为独立条目并加上门禁)。"},@@ -1145,9 +1089,7 @@]},"note": "Git worktree 是外部工具的既定概念,四语一律保留英文小写原词(现状 21 处最多)。desktop:chat 一个模块里就有 worktree / 工作区 / 工作树 三种写法。特别要紧的是「工作区」——它同时被用于 worktree、Workspace、working tree 三个不同英文概念,必须让出来只表示 Workspace;working directory 用「工作目录」。条件禁用只在英文源含 Worktree 时生效,不影响 Workspace 的正常翻译。豁免导入提示那一句:英文原文同时出现 worktree 与 main workspace,条件禁用是按整句英文判定的,无法区分句内两个概念——那里的「主工作区」正是 Workspace,必须保留,否则会把「不影响主工作区」这条安全边界说成「不影响主 worktree」。",- "exempt": [- "desktop:sessionShare.import.useWorktreeHint"- ]+ "exempt": ["desktop:sessionShare.import.useWorktreeHint"]},{"id": "token-plan",diff --git a/packages/ios-simulator-runtime/native/ios-simulator-sidecar.swift b/packages/ios-simulator-runtime/native/ios-simulator-sidecar.swiftindex 23b1d50045..9075e4b51a 100644--- a/packages/ios-simulator-runtime/native/ios-simulator-sidecar.swift+++ b/packages/ios-simulator-runtime/native/ios-simulator-sidecar.swift@@ -78,6 +78,57 @@ func fail(_ message: String) -> Never {exit(2)}+typealias MTLSetShaderCachePathFunction = @convention(c) (NSString) -> Void++/**+ * Metal normally discovers its shader-cache root through+ * confstr(_CS_DARWIN_USER_CACHE_DIR), which requires the broad dirhelper+ * service. Route it into this Sidecar instance's Host-owned 0700 temp root+ * before SimulatorKit or VideoToolbox initializes instead of opening the+ * user's real cache directory to the sandbox.+ */+func configurePrivateMetalShaderCache() {+ let environment = ProcessInfo.processInfo.environment+ // Unsandboxed correctness harnesses do not provide a private cache root;+ // they retain Metal's normal system cache behavior.+ guard let configuredCacheDirectory = environment[+ "CINDY_IOS_SIDECAR_METAL_CACHE_DIR"+ ] else { return }+ guard let rawTemporaryDirectory = environment["TMPDIR"] else {+ fail("private Metal cache requires TMPDIR")+ }+ let temporaryDirectory = URL(+ fileURLWithPath: rawTemporaryDirectory,+ isDirectory: true+ ).standardizedFileURL+ guard temporaryDirectory.path.hasPrefix("/"),+ temporaryDirectory.path != "/" else {+ fail("private Metal cache requires an absolute private TMPDIR")+ }+ let expectedCacheDirectory = temporaryDirectory.appendingPathComponent(+ "metal-cache",+ isDirectory: true+ ).standardizedFileURL.path+ let cacheDirectory = URL(+ fileURLWithPath: configuredCacheDirectory,+ isDirectory: true+ ).standardizedFileURL.path+ guard cacheDirectory == expectedCacheDirectory else {+ fail("private Metal cache must be inside the Host-owned TMPDIR")+ }++ let metalPath = "/System/Library/Frameworks/Metal.framework/Metal"+ guard let metal = dlopen(metalPath, RTLD_LAZY | RTLD_LOCAL),+ let symbol = dlsym(metal, "MTLSetShaderCachePath") else {+ fail("private Metal cache routing is unavailable")+ }+ let setShaderCachePath = unsafeBitCast(+ symbol,+ to: MTLSetShaderCachePathFunction.self+ )+ setShaderCachePath(cacheDirectory as NSString)+}+func argument(_ name: String) -> String {guard let index = CommandLine.arguments.firstIndex(of: name),index + 1 < CommandLine.arguments.count else {@@ -98,6 +149,7 @@ guard !simulatorUdid.isEmpty else {guard let generation = Int(argument("--generation")), generation > 0 else {fail("generation must be a positive integer")}+configurePrivateMetalShaderCache()enum FramebufferCaptureError: Error {case nativeSymbolsUnavailablediff --git a/packages/ios-simulator-runtime/src/native-sidecar/channel.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/channel.test.tsindex 7241cfeefb..8ee1790919 100644--- a/packages/ios-simulator-runtime/src/native-sidecar/channel.test.ts+++ b/packages/ios-simulator-runtime/src/native-sidecar/channel.test.ts@@ -266,6 +266,43 @@ describe("IOSSimulatorNativeSidecarChannel", () => {await channel.stop();});+ it("retains structured process-exit evidence with a bounded stderr tail", async () => {+ const { channel, processes } = harness();+ await channel.start();+ processes[0]!.stderr.write(+ "VideoToolbox failed at /Users/example/private/SimulatorKit.framework\n",+ );+ processes[0]!.exit(23, null);++ expect(channel.lastTermination).toEqual({+ reasonCode: "process-exit",+ message: "Native sidecar exited (23).",+ exitCode: 23,+ signal: null,+ occurredAt: "2026-07-23T00:00:00.000Z",+ stderrTail:+ "VideoToolbox failed at /Users/example/private/SimulatorKit.framework\n",+ });+ });++ it("adds the final signal when stdout closes before the process exit event", async () => {+ const { channel, processes } = harness();+ await channel.start();+ const process = processes[0]!;+ process.emitExitOnKill = false;+ process.stderr.write("encoder stopped\n");+ process.stdout.end();+ await vi.waitFor(() => expect(channel.state).toBe("failed"));+ process.exit(null, "SIGABRT");++ expect(channel.lastTermination).toMatchObject({+ reasonCode: "stdout-closed",+ exitCode: null,+ signal: "SIGABRT",+ stderrTail: "encoder stopped\n",+ });+ });+it("does not let a retired process exit invalidate its replacement", async () => {const { channel, processes } = harness();await channel.start();diff --git a/packages/ios-simulator-runtime/src/native-sidecar/channel.ts b/packages/ios-simulator-runtime/src/native-sidecar/channel.tsindex 948a04ba96..e0dd66f5ee 100644--- a/packages/ios-simulator-runtime/src/native-sidecar/channel.ts+++ b/packages/ios-simulator-runtime/src/native-sidecar/channel.ts@@ -34,6 +34,25 @@ const MAX_CLOSED_STREAMS = 64;export type IOSSimulatorNativeSidecarChannelState ="idle" | "running" | "failed" | "parked" | "stopped";+export type IOSSimulatorNativeSidecarTerminationReasonCode =+ | "launch-failed"+ | "process-error"+ | "process-exit"+ | "stdout-closed"+ | "protocol-error"+ | "request-timeout"+ | "write-failed";++/** Raw channel-local evidence. Callers must sanitize text before exposing it. */+export interface IOSSimulatorNativeSidecarTermination {+ reasonCode: IOSSimulatorNativeSidecarTerminationReasonCode;+ message: string;+ exitCode: number | null;+ signal: NodeJS.Signals | null;+ occurredAt: string;+ stderrTail: string;+}+export interface IOSSimulatorNativeSidecarManagedProcess {readonly pid?: number;readonly stdin: Writable;@@ -290,6 +309,9 @@ export class IOSSimulatorNativeSidecarChannel implements IOSSimulatorNativeSidec#crashCount = 0;#consecutiveTimeouts = 0;#stderr = "";+ #lastTermination: IOSSimulatorNativeSidecarTermination | null = null;+ #lastTerminationProcess: IOSSimulatorNativeSidecarManagedProcess | null =+ null;#earlyStreamBytes = 0;#stopRequested = false;@@ -329,6 +351,10 @@ export class IOSSimulatorNativeSidecarChannel implements IOSSimulatorNativeSidecreturn this.#stderr;}+ get lastTermination(): IOSSimulatorNativeSidecarTermination | null {+ return this.#lastTermination ? { ...this.#lastTermination } : null;+ }+async start(): Promise<void> {if (this.#state === "running" && this.#process) return;if (this.#state === "parked") {@@ -339,6 +365,7 @@ export class IOSSimulatorNativeSidecarChannel implements IOSSimulatorNativeSidec}this.#stopRequested = false;let process: IOSSimulatorNativeSidecarManagedProcess;+ this.#stderr = "";try {process = this.#launcher.launch();} catch (error) {@@ -346,6 +373,8 @@ export class IOSSimulatorNativeSidecarChannel implements IOSSimulatorNativeSidec"PROCESS_EXITED",`Unable to launch native sidecar: ${error instanceof Error ? error.message : String(error)}`,);+ this.#recordTermination(wrapped, { reasonCode: "launch-failed" });+ this.#lastTerminationProcess = null;this.#recordCrash();throw wrapped;}@@ -369,6 +398,7 @@ export class IOSSimulatorNativeSidecarChannel implements IOSSimulatorNativeSidecerror instanceof Error ? error.message : String(error),),true,+ { reasonCode: "protocol-error" },);}});@@ -383,6 +413,7 @@ export class IOSSimulatorNativeSidecarChannel implements IOSSimulatorNativeSidecerror instanceof Error ? error.message : String(error),),true,+ { reasonCode: "protocol-error" },);return;}@@ -393,6 +424,7 @@ export class IOSSimulatorNativeSidecarChannel implements IOSSimulatorNativeSidec"Native sidecar stdout closed.",),true,+ { reasonCode: "stdout-closed" },);});process.stderr.on("data", (chunk: Buffer | Uint8Array | string) => {@@ -411,9 +443,17 @@ export class IOSSimulatorNativeSidecarChannel implements IOSSimulatorNativeSidec`Native sidecar process error: ${error.message}`,),true,+ { reasonCode: "process-error" },),);- process.once("exit", (code, signal) =>+ process.once("exit", (code, signal) => {+ if (+ this.#process !== process &&+ this.#lastTerminationProcess === process+ ) {+ this.#augmentTerminationExit(code, signal);+ return;+ }this.#terminateProcess(process,new IOSSimulatorNativeSidecarChannelError(@@ -421,8 +461,9 @@ export class IOSSimulatorNativeSidecarChannel implements IOSSimulatorNativeSidec`Native sidecar exited (${signal ?? code ?? "unknown"}).`,),false,- ),- );+ { reasonCode: "process-exit", exitCode: code, signal },+ );+ });}async restart(): Promise<void> {@@ -623,6 +664,7 @@ export class IOSSimulatorNativeSidecarChannel implements IOSSimulatorNativeSidec`Unable to write to native sidecar: ${error.message}`,),true,+ { reasonCode: "write-failed" },);});} catch (error) {@@ -967,18 +1009,59 @@ export class IOSSimulatorNativeSidecarChannel implements IOSSimulatorNativeSidecprocess: IOSSimulatorNativeSidecarManagedProcess | null,error: IOSSimulatorNativeSidecarChannelError,kill: boolean,+ termination: {+ reasonCode: IOSSimulatorNativeSidecarTerminationReasonCode;+ exitCode?: number | null;+ signal?: NodeJS.Signals | null;+ } = {+ reasonCode:+ error.code === "TIMEOUT" ? "request-timeout" : "process-error",+ },): void {if (!process || this.#process !== process) return;this.#process = null;if (this.#stopRequested) {this.#state = "stopped";} else {+ this.#recordTermination(error, termination);+ this.#lastTerminationProcess = process;this.#recordCrash();}this.#rejectAll(error);if (kill) process.kill("SIGTERM");}+ #recordTermination(+ error: IOSSimulatorNativeSidecarChannelError,+ termination: {+ reasonCode: IOSSimulatorNativeSidecarTerminationReasonCode;+ exitCode?: number | null;+ signal?: NodeJS.Signals | null;+ },+ ): void {+ this.#lastTermination = {+ reasonCode: termination.reasonCode,+ message: error.message,+ exitCode: termination.exitCode ?? null,+ signal: termination.signal ?? null,+ occurredAt: this.#timestamp(),+ stderrTail: this.#stderr,+ };+ }++ #augmentTerminationExit(+ exitCode: number | null,+ signal: NodeJS.Signals | null,+ ): void {+ if (!this.#lastTermination) return;+ this.#lastTermination = {+ ...this.#lastTermination,+ exitCode,+ signal,+ stderrTail: this.#stderr,+ };+ }+#rejectAll(error: unknown): void {for (const pending of this.#pending.values()) {clearTimeout(pending.timeout);diff --git a/packages/ios-simulator-runtime/src/native-sidecar/process-manager.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/process-manager.test.tsindex 7ad9650749..214847ed21 100644--- a/packages/ios-simulator-runtime/src/native-sidecar/process-manager.test.ts+++ b/packages/ios-simulator-runtime/src/native-sidecar/process-manager.test.ts@@ -10,7 +10,10 @@ import type {} from "../driver.js";import { createIOSSimulatorNativeDevelopmentAdmissionPolicy } from "../capability-admission.js";import type { IOSSimulatorNativeSidecarCommand } from "./adapter.js";-import type { IOSSimulatorNativeSidecarChannelState } from "./channel.js";+import type {+ IOSSimulatorNativeSidecarChannelState,+ IOSSimulatorNativeSidecarTermination,+} from "./channel.js";import {createIOSSimulatorNativeSidecarArguments,createIOSSimulatorNativeSidecarEnvironment,@@ -38,6 +41,7 @@ class FakeChannel implements IOSSimulatorNativeSidecarManagedChannel {state: IOSSimulatorNativeSidecarChannelState = "idle";crashCount = 0;stderrTail = "";+ lastTermination: IOSSimulatorNativeSidecarTermination | null = null;readonly requests: IOSSimulatorNativeSidecarCommand[] = [];readonly stop = vi.fn(async () => {this.state = "stopped";@@ -273,6 +277,13 @@ describe("IOSSimulatorNativeSidecarProcessManager", () => {expect((await stat(path.join(temporaryRoot, privateDirectory))).mode & 0o777,).toBe(0o700);+ expect(+ (+ await stat(+ path.join(temporaryRoot, privateDirectory, "metal-cache"),+ )+ ).mode & 0o777,+ ).toBe(0o700);await manager.stop(input().instanceId);expect(await readdir(temporaryRoot)).toEqual([]);@@ -356,10 +367,28 @@ describe("IOSSimulatorNativeSidecarProcessManager", () => {const first = await manager.start(input());channel.state = "failed";channel.crashCount = 1;+ channel.lastTermination = {+ reasonCode: "process-exit",+ message:+ "Native sidecar exited beside /Users/example/private/SimulatorKit.framework.",+ exitCode: 23,+ signal: null,+ occurredAt: "2026-07-23T00:00:01.000Z",+ stderrTail:+ "token=private-value VideoToolbox failed at /Users/example/private/CoreSimulator.framework",+ };expect(manager.diagnostics("instance-a")).toMatchObject({running: false,state: "failed",+ lastFailure: "Native sidecar exited beside <redacted-path>",+ lastTermination: {+ reasonCode: "process-exit",+ exitCode: 23,+ signal: null,+ occurredAt: "2026-07-23T00:00:01.000Z",+ stderrTail: "token=<redacted> VideoToolbox failed at <redacted-path>",+ },admission: {processState: "failed",launch: { active: false, reasonCode: "PROCESS_NOT_RUNNING" },@@ -385,8 +414,20 @@ describe("IOSSimulatorNativeSidecarProcessManager", () => {state: "running",crashCount: 1,lastFailure: null,+ lastTermination: {+ reasonCode: "process-exit",+ exitCode: 23,+ },});await manager.stop("instance-a");+ expect(manager.diagnostics("instance-a")).toMatchObject({+ running: false,+ state: "stopped",+ lastTermination: {+ reasonCode: "process-exit",+ exitCode: 23,+ },+ });});it("converges an in-flight start to stopped without leaving a late binding", async () => {@@ -530,8 +571,7 @@ describe("IOSSimulatorNativeSidecarProcessManager", () => {const start = {...input(),runtime: {- runtimeIdentifier:- "com.apple.CoreSimulator.SimRuntime.iOS-26-4",+ runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-4",runtimeBuildVersion: "23E244",xcodeBuild: "Xcode 26.4\nBuild version 17E192",architecture: "arm64" as const,diff --git a/packages/ios-simulator-runtime/src/native-sidecar/process-manager.ts b/packages/ios-simulator-runtime/src/native-sidecar/process-manager.tsindex c054245141..6c8650bde3 100644--- a/packages/ios-simulator-runtime/src/native-sidecar/process-manager.ts+++ b/packages/ios-simulator-runtime/src/native-sidecar/process-manager.ts@@ -1,5 +1,5 @@import { constants } from "node:fs";-import { access, chmod, mkdtemp, rm } from "node:fs/promises";+import { access, chmod, mkdir, mkdtemp, rm } from "node:fs/promises";import path from "node:path";import {@@ -22,6 +22,8 @@ import {createNodeIOSSimulatorNativeSidecarLauncher,IOSSimulatorNativeSidecarChannel,type IOSSimulatorNativeSidecarChannelState,+ type IOSSimulatorNativeSidecarTermination,+ type IOSSimulatorNativeSidecarTerminationReasonCode,} from "./channel.js";import { IOS_SIMULATOR_NATIVE_SIDECAR_PROTOCOL_VERSION } from "./protocol.js";import {@@ -42,6 +44,7 @@ export interface IOSSimulatorNativeSidecarManagedChannel extends IOSSimulatorNatreadonly state: IOSSimulatorNativeSidecarChannelState;readonly crashCount: number;readonly stderrTail: string;+ readonly lastTermination: IOSSimulatorNativeSidecarTermination | null;start(): Promise<void>;restart(): Promise<void>;rearm(): void;@@ -100,10 +103,21 @@ export interface IOSSimulatorNativeSidecarDiagnostics {crashCount: number;probe: IOSSimulatorNativeSidecarProbe | null;lastFailure: string | null;+ lastTermination: IOSSimulatorNativeSidecarTerminationDiagnostics | null;admission: IOSSimulatorNativeCapabilityAdmissionDecision | null;sandbox?: IOSSimulatorNativeSidecarSandboxDiagnostics;}+export interface IOSSimulatorNativeSidecarTerminationDiagnostics {+ reasonCode: IOSSimulatorNativeSidecarTerminationReasonCode;+ message: string;+ exitCode: number | null;+ signal: NodeJS.Signals | null;+ occurredAt: string;+ /** Bounded and redacted; raw channel stderr never crosses this boundary. */+ stderrTail: string | null;+}+export interface IOSSimulatorNativeSidecarRunningInstance {instanceId: string;simulatorUdid: string;@@ -204,6 +218,40 @@ function safeProcessManagerFailure();}+function safeNativeSidecarDiagnosticText(+ value: string,+ maxLength: number,+): string {+ return value+ .replace(/https?:\/\/[^\s)]+/gi, "<redacted-url>")+ .replace(+ /(?:\/Users\/|\/private\/|\/var\/folders\/|\/tmp\/|\/Applications\/|\/Library\/)[^\s"'(),;]+/g,+ "<redacted-path>",+ )+ .replace(+ /\b(authorization|cookie|password|secret|token)(\s*[:=]\s*)([^\s,;]+)/gi,+ "$1$2<redacted>",+ )+ .slice(-maxLength);+}++function safeNativeSidecarTermination(+ termination: IOSSimulatorNativeSidecarTermination,+): IOSSimulatorNativeSidecarTerminationDiagnostics {+ const stderrTail = safeNativeSidecarDiagnosticText(+ termination.stderrTail,+ 8_000,+ ).trim();+ return {+ reasonCode: termination.reasonCode,+ message: safeNativeSidecarDiagnosticText(termination.message, 2_000),+ exitCode: termination.exitCode,+ signal: termination.signal,+ occurredAt: termination.occurredAt,+ stderrTail: stderrTail || null,+ };+}+function isRecord(value: unknown): value is Record<string, unknown> {return Boolean(value) && typeof value === "object" && !Array.isArray(value);}@@ -517,6 +565,10 @@ export class IOSSimulatorNativeSidecarProcessManager {IOSSimulatorNativeSidecarProbe | null>();readonly #lastFailure = new Map<string, string>();+ readonly #lastTermination = new Map<+ string,+ IOSSimulatorNativeSidecarTerminationDiagnostics+ >();readonly #lastAdmission = new Map<string,IOSSimulatorNativeCapabilityAdmissionDecision@@ -570,13 +622,26 @@ export class IOSSimulatorNativeSidecarProcessManager {diagnostics(instanceId: string): IOSSimulatorNativeSidecarDiagnostics {const running = this.#running.get(instanceId);const admission = this.admission(instanceId);+ const channelTermination = running?.channel.lastTermination ?? null;+ if (channelTermination) {+ this.#lastTermination.set(+ instanceId,+ safeNativeSidecarTermination(channelTermination),+ );+ }+ const lastTermination = this.#lastTermination.get(instanceId) ?? null;return {running: running?.channel.state === "running",state: running?.channel.state ?? admission?.processState ?? "idle",crashCount: running?.channel.crashCount ?? 0,probe:running?.handshake.probe ?? this.#lastProbe.get(instanceId) ?? null,- lastFailure: this.#lastFailure.get(instanceId) ?? null,+ lastFailure:+ this.#lastFailure.get(instanceId) ??+ (running && running.channel.state !== "running"+ ? (lastTermination?.message ?? null)+ : null),+ lastTermination,admission,sandbox:running?.sandbox.diagnostics ??@@ -635,6 +700,7 @@ export class IOSSimulatorNativeSidecarProcessManager {operation: PendingSidecarOperation,): Promise<IOSSimulatorNativeSidecarRunningInstance> {this.#lastFailure.delete(input.instanceId);+ this.#lastTermination.delete(input.instanceId);const policy = this.#resolveAdmissionPolicy(input);operation.policy = policy;const preflight = evaluateIOSSimulatorNativeCapabilityAdmission({@@ -706,6 +772,13 @@ export class IOSSimulatorNativeSidecarProcessManager {this.#running.set(input.instanceId, running);return this.get(input.instanceId)!;} catch (error) {+ const channelTermination = channel.lastTermination;+ if (channelTermination) {+ this.#lastTermination.set(+ input.instanceId,+ safeNativeSidecarTermination(channelTermination),+ );+ }const failure = safeProcessManagerFailure(error,"Native sidecar process failed to start.",@@ -869,6 +942,13 @@ export class IOSSimulatorNativeSidecarProcessManager {this.#lastSandbox.set(input.instanceId, running.sandbox.diagnostics);return this.get(input.instanceId)!;} catch (error) {+ const channelTermination = running.channel.lastTermination;+ if (channelTermination) {+ this.#lastTermination.set(+ input.instanceId,+ safeNativeSidecarTermination(channelTermination),+ );+ }const failure = safeProcessManagerFailure(error,operation.stopRequested@@ -1000,12 +1080,26 @@ export class IOSSimulatorNativeSidecarProcessManager {async #stop(instanceId: string): Promise<void> {const pending = this.#starting.get(instanceId);+ const pendingTermination = pending?.channel?.lastTermination;+ if (pendingTermination) {+ this.#lastTermination.set(+ instanceId,+ safeNativeSidecarTermination(pendingTermination),+ );+ }if (pending) {pending.stopRequested = true;await pending.channel?.stop().catch(() => undefined);}let running = this.#running.get(instanceId);const stoppedRunning = running;+ const runningTermination = running?.channel.lastTermination;+ if (runningTermination) {+ this.#lastTermination.set(+ instanceId,+ safeNativeSidecarTermination(runningTermination),+ );+ }if (running) {this.#running.delete(instanceId);await running.adapter.detach().catch(() => undefined);@@ -1139,6 +1233,9 @@ export class IOSSimulatorNativeSidecarProcessManager {),);await chmod(temporaryDirectory, 0o700);+ const metalCacheDirectory = path.join(temporaryDirectory, "metal-cache");+ await mkdir(metalCacheDirectory, { mode: 0o700 });+ await chmod(metalCacheDirectory, 0o700);const diagnostics = createIOSSimulatorNativeSidecarSandboxLaunchPlan({policy,binaryPath: this.#options.binaryPath,diff --git a/packages/ios-simulator-runtime/src/native-sidecar/provider.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/provider.test.tsindex 9757b4acb5..dd11c60d6b 100644--- a/packages/ios-simulator-runtime/src/native-sidecar/provider.test.ts+++ b/packages/ios-simulator-runtime/src/native-sidecar/provider.test.ts@@ -152,6 +152,7 @@ class FakeRuntime implements IOSSimulatorSidecarRuntime {crashCount: 0,probe: null,lastFailure: null,+ lastTermination: null,admission: running.admission,};}diff --git a/packages/ios-simulator-runtime/src/native-sidecar/provider.ts b/packages/ios-simulator-runtime/src/native-sidecar/provider.tsindex 6ecb453803..4c96236093 100644--- a/packages/ios-simulator-runtime/src/native-sidecar/provider.ts+++ b/packages/ios-simulator-runtime/src/native-sidecar/provider.ts@@ -181,8 +181,7 @@ function sameIdentity(left.simulatorUdid === right.simulatorUdid &&left.generation === right.generation &&left.runtime?.runtimeIdentifier === right.runtime?.runtimeIdentifier &&- left.runtime?.runtimeBuildVersion ===- right.runtime?.runtimeBuildVersion &&+ left.runtime?.runtimeBuildVersion === right.runtime?.runtimeBuildVersion &&left.runtime?.xcodeBuild === right.runtime?.xcodeBuild &&left.runtime?.architecture === right.runtime?.architecture);@@ -572,6 +571,7 @@ export class HostIOSSimulatorSidecarSupervisor implements IOSSimulatorSidecarSupcrashCount: 0,probe: null,lastFailure: "Native capability provider admission was denied.",+ lastTermination: null,admission: decision,});throw new IOSSimulatorCapabilityProviderError(diff --git a/packages/ios-simulator-runtime/src/native-sidecar/sandbox.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/sandbox.test.tsindex 5b7db670b6..979ea1a344 100644--- a/packages/ios-simulator-runtime/src/native-sidecar/sandbox.test.ts+++ b/packages/ios-simulator-runtime/src/native-sidecar/sandbox.test.ts@@ -62,6 +62,7 @@ describe("IOSSimulator native sidecar sandbox", () => {`(subpath ${JSON.stringify(path.join("/Users/example", "Library", "Developer", "CoreSimulator"))})`,);expect(profile).not.toContain("(allow network");+ expect(profile).not.toContain("com.apple.bsd.dirhelper");expect(profile).not.toMatch(/\(allow mach-lookup\)\s*$/m);expect(profile).not.toMatch(/\(allow iokit-open\)\s*$/m);expect(profile).not.toContain("(allow signal");@@ -148,6 +149,7 @@ describe("IOSSimulator native sidecar sandbox", () => {HOME: "/Users/example",DEVELOPER_DIR: "/Applications/Xcode.app/Contents/Developer",TMPDIR: `${temp}${path.sep}`,+ CINDY_IOS_SIDECAR_METAL_CACHE_DIR: path.join(temp, "metal-cache"),});expect(plan.diagnostics).toMatchObject({required: true,diff --git a/packages/ios-simulator-runtime/src/native-sidecar/sandbox.ts b/packages/ios-simulator-runtime/src/native-sidecar/sandbox.tsindex a6f88c8562..7d7321670d 100644--- a/packages/ios-simulator-runtime/src/native-sidecar/sandbox.ts+++ b/packages/ios-simulator-runtime/src/native-sidecar/sandbox.ts@@ -361,6 +361,10 @@ export function createIOSSimulatorNativeSidecarSandboxLaunchPlan(HOME: input.policy.homeDirectory,DEVELOPER_DIR: input.policy.developerDirectory,TMPDIR: `${input.temporaryDirectory}${path.sep}`,+ CINDY_IOS_SIDECAR_METAL_CACHE_DIR: path.join(+ input.temporaryDirectory,+ "metal-cache",+ ),};if (input.environment.LC_ALL) {environment.LC_ALL = input.environment.LC_ALL;diff --git a/packages/ios-simulator-runtime/src/resource-scheduler.test.ts b/packages/ios-simulator-runtime/src/resource-scheduler.test.tsindex e5fb600a24..5157a00935 100644--- a/packages/ios-simulator-runtime/src/resource-scheduler.test.ts+++ b/packages/ios-simulator-runtime/src/resource-scheduler.test.ts@@ -129,4 +129,24 @@ describe("IOSSimulatorResourceScheduler", () => {code: "RESOURCE_LIMIT_REACHED",});});++ it("reports the configured limits and current running count", async () => {+ const scheduler = new IOSSimulatorResourceScheduler({+ softLimit: 2,+ hardLimit: 4,+ freeMemoryBytes: () => 100 * 1024 ** 3,+ });++ expect(scheduler.snapshot()).toEqual({+ runningCount: 0,+ softLimit: 2,+ hardLimit: 4,+ });+ await scheduler.runStart("a", async () => undefined);+ expect(scheduler.snapshot()).toEqual({+ runningCount: 1,+ softLimit: 2,+ hardLimit: 4,+ });+ });});diff --git a/packages/ios-simulator-runtime/src/resource-scheduler.ts b/packages/ios-simulator-runtime/src/resource-scheduler.tsindex 676395aa19..4f9ad9b6ba 100644--- a/packages/ios-simulator-runtime/src/resource-scheduler.ts+++ b/packages/ios-simulator-runtime/src/resource-scheduler.ts@@ -22,6 +22,12 @@ export interface IOSSimulatorResourceSchedulerOptions {freeMemoryBytes?: () => number;}+export interface IOSSimulatorResourceSchedulerSnapshot {+ runningCount: number;+ softLimit: number;+ hardLimit: number;+}+const GIB = 1024 ** 3;const MIB = 1024 ** 2;const CRITICAL_FREE_PERCENTAGE = 10;@@ -124,6 +130,14 @@ export class IOSSimulatorResourceScheduler {return this.#running.size;}+ snapshot(): IOSSimulatorResourceSchedulerSnapshot {+ return {+ runningCount: this.#running.size,+ softLimit: this.#softLimit,+ hardLimit: this.#hardLimit,+ };+ }+markStopped(instanceId: string): void {this.#running.delete(instanceId);}diff --git a/packages/ios-simulator-runtime/src/wda/process-manager.test.ts b/packages/ios-simulator-runtime/src/wda/process-manager.test.tsindex 557a8dbe49..2101b70303 100644--- a/packages/ios-simulator-runtime/src/wda/process-manager.test.ts+++ b/packages/ios-simulator-runtime/src/wda/process-manager.test.ts@@ -273,6 +273,7 @@ describe("WdaProcessManager", () => {crashCount: 0,probe: null,lastFailure: null,+ lastTermination: null,admission: nativeAdmission,})),admission: vi.fn(() => nativeAdmission),