Skip to content

armgit / cindy

Public Imported from GitHub
0

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

Merge upstream/main into feat/issue-397-ios-simulator-native-framebuffer

JiangJiahaofce7280cb1e3
diff --cc .gitignore
index a8c6605c04,0a3179aa00..7f812f37fe
--- a/.gitignore
+++ b/.gitignore
@@@ -154,12 -154,11 +154,17 @@@ config/endpoint.dev.jso
# 发布机本地地区 / 签名配置;仓库只保留对应的 .example 文件。
apps/mobile/scripts/self-host-regions.json
apps/desktop/scripts/release-regions.json
+# iOS Simulator WDA archives and native sidecars are generated locally.
+apps/desktop/resources/ios-simulator/*.tar.gz
+apps/desktop/resources/ios-simulator/*.tmp
+apps/desktop/resources/ios-simulator/native/arm64/
+apps/desktop/resources/ios-simulator/native/x86_64/
+apps/desktop/resources/ios-simulator/helper/
+ # 客户端日志上报目标(SLS project / logstore / 区域)。真值唯一事实源在
+ # cindy-build-scripts 仓根,打包机由 sync-desktop-release-kit.sh 拷回;
+ # 仓内只保留 config/log-upload.json.example。缺失时 cn/global 打包会硬失败,
+ # dev 缺失则该渠道的日志上报整体关闭。
+ config/log-upload.json
# 视觉基线截图是开发者本地对照数据(可能截到真实会话内容),不入仓;
# 本地跑 visual-baseline-check 时会自动生成。
apps/mobile/e2e/visual-baselines/
diff --cc apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
index 244aa8bd47,e20c53ecb0..ec369a81ea
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@@ -900,10 -895,6 +913,11 @@@ describe('FORGE_GUIDE', () =>
'创建工作区会话(workspace 槽)',
'cindy.workspace',
"kind: 'ensure-session'",
+ // 2026-08-06 iOS Simulator 插件能力:只读脱敏状态与 Host 面板入口。
+ '内置 iOS 模拟器(ios-simulator 槽)',
+ 'cindy.iosSimulator.request',
+ 'pluginVideo/pluginInput 都是 false',
++ '声明 `ios-simulator` 时必须同时声明 `minCindyVersion`',
// 2026-07-28 图标与官方仓门禁(#809):§1/§2 的 icon 字段说明、
// §8.1 官方插件仓的四语言 locale 与 assets/icon.png 惯例。
'"icon": "assets/icon.png"',
diff --cc apps/desktop/src/main/cindy-brain/forge.ts
index ccab365ad7,05d2bada7c..f136eeac1a
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@@ -3269,53 -3301,6 +3302,57 @@@ 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。
+
++声明 \`ios-simulator\` 时必须同时声明 \`minCindyVersion\`,取首次提供该 Host 能力的 Cindy
++正式版本。它用于让旧版 Host 把插件识别为“需要更新 Cindy”,而不是“插件非法”;不要填写
++当前开发环境版本,也不要用它替代下面的运行时 capability 检查。
++
+\`\`\`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 --cc apps/desktop/src/main/cindy-brain/index.ts
index 871f3a5683,a80395c110..e890859d4b
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@@ -2543,17 -2409,15 +2555,17 @@@ function getCatalogMediaConfig(kind: Ci
// 网关能力在场 —— 未登录本地模式(canUseCindyGateway=false)下 xd 的视频型号
// 不能进清单,否则用户在本地模式钉选/点名视频型号就是"可选但必失败"
// (2026-07 review:与图像的就绪语义对齐)。
- // 向量与视频同口径:通道只有 xd 一家、不经 registry,但要求网关能力在场
- // (本地模式没有网关 key,embedSync 必然 AUTH_FAILED —— 那种型号不该出现在
- // 清单里让用户钉选)。
+ // 向量与视频同口径:通道只有 xd 一家、不经 registry,但要求账号网关能力与
+ // model-access 随凭据成对下发的 endpoint 同时在场。登录同步完成前 / 存量
+ // 手填 key 没有配套 endpoint 时,那种型号不该出现在清单里让用户钉选。
kind === 'image'
? (providerId) => getImageChannelRegistry().isProviderReady(providerId)
- : (providerId) => providerId !== 'xd' || getAppCapabilities().canUseCindyGateway,
+ : isXdGatewayProviderReady,
// 编辑就绪过滤:仅支持生成的来源(supportsEdit: false)的模型不进编辑清单,
// 防用户把该型号钉到 image.edit 偏好后在 editImage 路径拿到确定性 400。
- kind === 'image' ? (providerId) => getImageChannelRegistry().isProviderEditReady(providerId) : undefined,
+ kind === 'image'
+ ? (providerId) => getImageChannelRegistry().isProviderEditReady(providerId)
+ : undefined,
);
} catch (err) {
// 目录读取异常 = 拿不到可用性证明,同「空清单」处理(不静默顶一份旧名单)。
@@@ -2994,9 -2863,32 +3027,33 @@@ export function getGhostCindySlot(): Gh
// 管子续命挂钩:同步视频代办(署名单)在途期间替 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),
+ claimPipeCall: (ghostId, callId, callerTool, binding, requestKey) =>
+ getGhostPipeDispatcher().claimPendingCall(
+ ghostId,
+ callId,
+ callerTool,
+ binding,
+ requestKey,
+ ),
+ settlePipeCallClaim: (
+ ghostId,
+ callId,
+ callerTool,
+ binding,
+ requestKey,
+ allowRetry,
+ ) =>
+ getGhostPipeDispatcher().settlePendingCallClaim(
+ ghostId,
+ callId,
+ callerTool,
+ binding,
+ requestKey,
+ allowRetry,
+ ),
// 视频型号预期耗时(registry 登记值;hold 预算与异步受理返回共用)。
// registry 缺席/型号查无 → null,cindySlot 用自己的缺省。
videoExpectedSeconds: (model) => {
@@@ -3725,29 -3619,19 +3787,16 @@@ async function installOrUpdateMarketGho
inspected.canonicalManifest.id !== expected.ghostId ||
inspected.canonicalManifest.version !== expected.version
) {
- throwIpcError(
- 'GHOST_FILE_INVALID',
- '下载包清单与市场 Release 不一致',
- );
+ throwIpcError('GHOST_FILE_INVALID', '下载包清单与市场 Release 不一致');
}
requireGhostAvailableForActiveSession(expected.ghostId);
- /**
- * 「审阅过的」与「真要装的」权限必须一致(2026-08-03,codex review P1)。
- *
- * 装入确认框渲染的是**来源方给的 manifest**(服务端市场 = release manifest,
- * 自定义市场 = 抓到的 ghost.json),而真正落地的是 `.cindy` 包里的 ghost.json。
- * 两者本该同一份,但来源方的投影层可能与客户端的清单契约漂移——`cindy-protocol`
- * 那份平行校验器就已经缺了 `confirm` 槽;新登记的槽(如 `badge`)在它眼里是
- * 未知槽名,投影时会被丢掉或整份拒绝。结果:确认框漏列该项权限,包却原样带着
- * 它装进来,用户**从没审过就多出一个常驻能力面**。
- *
- * 这里按权限项逐项比对。包里多出来的权限先暂停落位,由 Renderer 按真实包
- * 重新展示;用户批准后携带包 SHA 和已装权限基线重试。
- * 卡点落在 inspect 之后、任何落地动作之前,所以等待复核时磁盘上什么都没动。
- */
const installed = manager.list().find((ghost) => ghost.manifest.id === expected.ghostId);
if (expected.reviewedManifest) {
- const installedBaseline = installed ? ghostPermissionBaselineKey(installed.manifest) : null;
- // 真实包复核的批准必须始终绑定当时那份包与已装权限面,不能只在
- // 当前仍存在来源清单差异时才校验。否则两次请求间包字节发生变化、
- // 新包恰好不再多权限时,会绕过旧批准的 SHA/基线绑定直接落位。
+ const baselineManifest = expected.permissionBaselineManifest ?? null;
+ const installedBaseline = baselineManifest
+ ? ghostPermissionBaselineKey(baselineManifest)
+ : null;
+ // 批准始终绑定 Main 实际检查过的包 SHA 与本地已装权限基线。
if (
expected.approvedPackageSha256 !== undefined &&
(expected.approvedPackageSha256 !== inspected.packageSha256 ||
@@@ -4879,78 -4776,65 +4966,68 @@@ export function registerGhostIpc(): voi
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)}`);
+ }
+ // 白名单按能力键类目分流:image.*/video.*/embed.* 钉各媒体目录模型 id;
+ // text.*(快问快答)钉轻量档位键或目录钉(cat: 编码)——与消费方(cindySlot
+ // route)同一判据,否则存进去的值链路不认。刻意不查凭证态(与清单的凭证
+ // 过滤不同):凭证是瞬态(可以后补/会过期),钉档是持久意图;执行侧
+ // fail-closed 兜底,不在这层把「暂时没配 key」当成非法值。
+ if (
+ !isCindyOverrideModelAllowed(capability as string, model, {
+ image: getCatalogImageConfig().models,
+ video: getCatalogVideoConfig().models,
+ embed: getCatalogEmbedConfig().models,
+ textPinIds: buildTextOneshotPinOptions(getActiveCatalog(), readModelDisableOverrides()).map(
+ (o) => o.id,
+ ),
+ })
+ ) {
+ throwIpcError('INVALID_PARAMS', 'model must be null or an allowed 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,
diff --cc apps/desktop/src/main/maker-host/index.ts
index 30c206f078,4fe176a3e5..d061f6e830
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@@ -131,9 -128,11 +132,13 @@@ import
unregister as unregisterCodexProxyPrompt,
} from './codex-proxy-host.js';
import { createDesktopMcpProviders } from '../mcp-integrations/mcp-providers.js';
+import { getIOSSimulatorMcpDeps } from '../mcp-integrations/ios-simulator.js';
import { readContactsSettings } from './contacts-settings-store.js';
+import { createIOSSimulatorCodexDynamicToolProvider } from './ios-simulator-codex-dynamic-tools.js';
+ import {
+ captureKnownFileBefore,
+ noteOpaqueTurnChange,
+ } from '../turn-change-set/store.js';
/**
* 最近一次成功构建的 codex spawn 配置里, 通讯录开关的实际取值(null = 尚未
diff --cc apps/desktop/src/renderer/__tests__/chatInputGhostSnapshot.test.ts
index a3153eeef8,3db13aafe7..471821b967
--- a/apps/desktop/src/renderer/__tests__/chatInputGhostSnapshot.test.ts
+++ b/apps/desktop/src/renderer/__tests__/chatInputGhostSnapshot.test.ts
@@@ -31,11 -31,11 +31,19 @@@ describe('ChatInput Ghost snapshot cont
});
it('does not expose controller-local plugin rows in device-link sessions', () => {
++ expect(source).toContain('if (deviceLinkDeviceId) return [];');
expect(source).toContain(
-- 'if (deviceLinkDeviceId) return [];',
++ '[deviceLinkDeviceId, pluginsForMenu, pluginAvailableIds, remoteHostId, t]',
);
++ });
++
++ it('revalidates Host capability chips as enabled and local at send time', () => {
expect(source).toContain(
- '[deviceLinkDeviceId, pluginsForMenu, pluginAvailableIds]',
- '[deviceLinkDeviceId, pluginsForMenu, pluginAvailableIds, t]',
++ 'const canUseLocalHostCapability = !remoteHostId && !deviceLinkDeviceId;',
++ );
++ expect(source).toMatch(
++ /serializedHostCapability && canUseLocalHostCapability[\s\S]*?candidate\.enabled &&[\s\S]*?candidate\.manifest\.id === serializedHostCapability\.ghostId/,
);
++ expect(source).toContain("toast.warning(t('newChat.pluginSetup.error.TARGET_UNAVAILABLE'));");
});
});
diff --cc apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts
index 537e4f7d4c,4f0c115087..f817dfb1aa
--- a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts
+++ b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts
@@@ -93,31 -93,18 +93,42 @@@ describe('ChatInput session switch focu
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',
++ 'const insertAtResource = useCallback(',
++ 'const handleComposerSuggestionSelect = 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);
+ ).toHaveLength(1);
+ expect(
+ chatInputSource.match(
+ /placeGhostAtComposerStart\(editor, ghost, installedGhostsRef\.current\)/g,
+ ),
+ ).toHaveLength(1);
expect(chatInputSource).toContain('pendingGhostId: undefined');
+ expect(chatInputSource).toContain('pendingHostCapabilityGhostId: undefined');
+ expect(
+ chatInputSource.match(
+ /placeHostCapabilityAtComposerStart\(editor, ghost, installedGhosts\)/g,
+ ),
- ).toHaveLength(2);
++ ).toHaveLength(1);
++ expect(capabilitySelectionBlock).toContain("selectedItem.type === 'plugin-command'");
++ expect(capabilitySelectionBlock).toContain('if (ghost.manifest.command) {');
++ expect(capabilitySelectionBlock).toContain(
++ 'placeGhostAtComposerStart(editor, ghost, installedGhostsRef.current);',
++ );
+ expect(capabilitySelectionBlock).toContain(
- 'placeHostCapabilityAtComposerStart(editor, ghost, installedGhosts);',
++ 'placeHostCapabilityAtComposerStart(editor, ghost, installedGhostsRef.current);',
+ );
- expect(capabilitySelectionBlock).not.toContain('sessionId');
++ expect(capabilitySelectionBlock).toContain('!remoteHostId');
++ expect(capabilitySelectionBlock).toContain('!deviceLinkDeviceId');
+ expect(capabilitySelectionBlock).not.toContain('focusIOSSimulatorPanel');
expect(chatInputSource).toContain('focusComposerEndNextFrame(editor);');
});
diff --cc apps/desktop/src/renderer/__tests__/planModeComposerEntry.test.ts
index 34b4373e51,a3b4038941..ffb1757349
--- a/apps/desktop/src/renderer/__tests__/planModeComposerEntry.test.ts
+++ b/apps/desktop/src/renderer/__tests__/planModeComposerEntry.test.ts
@@@ -34,86 -36,13 +36,40 @@@ import { AtMentionPanel } from '@/compo
import { PlanActionCard } from '@/components/new-chat/PlanActionCard';
import { PlanModeIndicator } from '@/components/new-chat/PlanModeIndicator';
import { PlanViewerCard } from '@/components/new-chat/PlanViewerCard';
- import type { InstalledGhost } from '../../shared/ghost';
-
- const installedPlugin: InstalledGhost = {
- manifest: {
- schemaVersion: 2,
- id: 'cindy-art',
- name: 'Cindy Art',
- version: '1.0.0',
- kind: 'chip',
- entry: 'main.js',
- slots: ['tool'],
- tools: [{ name: 'draw', description: 'Draw.' }],
- command: 'art',
+ import {
+ buildComposerSuggestionEntries,
+ nextEnabledSuggestionIndex,
+ type ComposerSuggestionAction,
+ type ComposerSuggestionEntry,
++ type ComposerPluginSuggestion,
+ } from '@/lib/composerSuggestion';
+
++const iosSimulatorPluginSuggestion: ComposerPluginSuggestion = {
++ item: {
++ type: 'plugin-command',
++ name: 'iOS Simulator',
++ relPath: 'cindy://host-capability/ios-simulator',
++ pluginId: 'ios-simulator',
+ },
- dir: '/tmp/cindy-art',
- enabled: true,
+};
+
- const installedMermaidPlugin: InstalledGhost = {
- manifest: {
- schemaVersion: 2,
- id: 'cindy-mermaid',
- name: 'Mermaid',
- version: '1.0.0',
- kind: 'chip',
- entry: 'main.js',
- slots: ['tool'],
- tools: [{ name: 'render', description: 'Render a Mermaid diagram.' }],
- command: 'mermaid',
- },
- dir: '/tmp/cindy-mermaid',
- enabled: true,
++const disabledIOSSimulatorPluginSuggestion: ComposerPluginSuggestion = {
++ ...iosSimulatorPluginSuggestion,
++ disabled: true,
++ disabledReason: 'extraDirs.pluginDisabled',
+};
+
- 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',
++const skillOnlyPluginSuggestion: ComposerPluginSuggestion = {
++ item: {
++ type: 'plugin-command',
+ name: 'Skill only',
- version: '1.0.0',
- kind: 'chip',
- entry: 'main.js',
- slots: ['skill'],
- skill: {
- items: [
- {
- dir: 'skills/example',
- name: 'example',
- description: 'Example workflow.',
- },
- ],
- },
++ relPath: 'cindy://plugin/skill-only',
++ pluginId: 'skill-only',
+ },
- dir: '/tmp/skill-only',
- enabled: true,
++ disabled: true,
++ disabledReason: 'extraDirs.pluginAgentInvoked',
+};
+
afterEach(() => {
cleanup();
vi.clearAllMocks();
@@@ -238,146 -134,71 +161,148 @@@ describe('统一 composer 建议入口'
}),
);
- fireEvent.click(screen.getByLabelText('extraDirs.menuAria'));
expect(screen.getByText('goal.newGoalMenuItem')).toBeTruthy();
- expect(screen.getByText('planMode.menuItem')).toBeTruthy();
- const item = screen.getByRole('menuitemcheckbox', {
- name: 'newChat.collaboration.modeLabel',
- });
- expect(item.getAttribute('aria-checked')).toBe('true');
- expect(item.className).toContain('bg-[var(--model-item-hover)]');
- expect(screen.getByText('newChat.collaboration.modeLabel').className).toContain(
- 'text-[var(--warning-accent)]',
- );
- expect(item.querySelector('svg.lucide-check')).toBeTruthy();
- fireEvent.click(item);
- expect(onChange).toHaveBeenCalledWith({ enabled: false, worker: 'cc' });
+ expect(screen.getByText('Cindy Art')).toBeTruthy();
+ const plan = screen.getByRole('menuitemcheckbox', { name: 'planMode.menuItem' });
+ expect(plan.getAttribute('aria-checked')).toBe('true');
+ expect(plan.className).toContain('rounded-[8px]');
+ expect(plan.className).toContain('px-3');
+ expect(plan.className).toContain('py-2');
+ expect(plan.className).toContain('hover:bg-[var(--model-item-hover)]');
+ fireEvent.click(plan);
+ expect(onPlanToggle).toHaveBeenCalledWith(false);
+ expect(
- (screen.getByRole('menuitemcheckbox', {
- name: 'newChat.collaboration.modeLabel: policy unavailable',
- }) as HTMLButtonElement).disabled,
++ (
++ screen.getByRole('menuitemcheckbox', {
++ name: 'newChat.collaboration.modeLabel: policy unavailable',
++ }) as HTMLButtonElement
++ ).disabled,
+ ).toBe(true);
});
- it('策略暂不可用时保留可重试的协同菜单项', () => {
- const onDisabledActivate = vi.fn();
- render(
- createElement(ExtraDirsButton, {
- extraDirs: [],
- collaboration: {
- enabled: false,
- worker: 'pi',
- onChange: vi.fn(),
- disabled: true,
- disabledReason: 'policy unavailable',
- onDisabledActivate,
- },
- }),
- );
-
- fireEvent.click(screen.getByLabelText('extraDirs.menuAria'));
- const item = screen.getByRole('menuitemcheckbox', {
- name: 'newChat.collaboration.modeLabel: policy unavailable',
- });
- expect((item as HTMLButtonElement).disabled).toBe(false);
- fireEvent.click(item);
- expect(onDisabledActivate).toHaveBeenCalledTimes(1);
+ it('键盘导航跳过 disabled 条目', () => {
+ const entries: ComposerSuggestionEntry[] = [
+ {
+ kind: 'action',
+ action: { id: 'new-goal', label: 'goal', disabled: true, run: vi.fn() },
+ },
+ {
+ kind: 'action',
+ action: { id: 'plan-mode', label: 'plan', checked: false, run: vi.fn() },
+ },
+ ];
+ expect(nextEnabledSuggestionIndex(entries, 1, 1)).toBe(1);
+ expect(nextEnabledSuggestionIndex(entries, 0, 1)).toBe(1);
+ expect(nextEnabledSuggestionIndex(entries, 1, -1)).toBe(1);
});
- it('没有任何入口时保持不渲染', () => {
- const { container } = render(
- createElement(ExtraDirsButton, {
- extraDirs: [],
- }),
- );
- expect(container.firstChild).toBeNull();
- });
-
- it('Codex 接入 onChange 后显示引用目录、数量与增删入口', () => {
- const onChange = vi.fn();
+ it('引用目录管理复用统一面板的独立 section,移除按钮支持键盘访问', async () => {
+ const user = userEvent.setup();
+ const onRemove = vi.fn();
+ const entries = buildComposerSuggestionEntries({
+ query: '',
+ actions: [{ id: 'add-extra-dir', label: 'extraDirs.add', run: vi.fn() }],
+ resources: [],
+ plugins: [],
+ });
render(
- createElement(ExtraDirsButton, {
- extraDirs: ['/repo-shared'],
- workingDir: '/repo',
- onChange,
+ createElement(AtMentionPanel, {
+ query: '',
+ state: { kind: 'ready', items: [], truncated: false },
+ entries,
+ focusedIndex: 0,
+ onFocusedIndexChange: vi.fn(),
+ onSelect: vi.fn(),
+ onClose: vi.fn(),
+ onRetry: vi.fn(),
+ referenceDirs: { dirs: ['/repo-shared'], onRemove },
}),
);
-
- expect(screen.getByText('×1')).toBeTruthy();
- fireEvent.click(screen.getByLabelText('extraDirs.menuAria'));
expect(screen.getByText('extraDirs.sectionTitle')).toBeTruthy();
expect(screen.getByText('repo-shared')).toBeTruthy();
- fireEvent.click(screen.getByLabelText('extraDirs.remove'));
- expect(onChange).toHaveBeenCalledWith([]);
+ const removeButton = screen.getByLabelText('extraDirs.remove');
+ expect(removeButton.className).toContain('focus-visible:opacity-100');
+ expect(removeButton.className).toContain('focus-visible:ring-2');
+ removeButton.focus();
+ expect(document.activeElement).toBe(removeButton);
+ await user.keyboard('{Enter}');
+ expect(onRemove).toHaveBeenCalledWith('/repo-shared');
});
+
- it('展示所有已安装 Plugin,并把可用项交给 composer 放置', () => {
- const onPluginSelect = vi.fn();
- render(
- createElement(ExtraDirsButton, {
- extraDirs: [],
- plugins: [installedPlugin],
- onPluginSelect,
- }),
- );
-
- fireEvent.click(screen.getByLabelText('extraDirs.menuAria'));
- expect(screen.getByText('extraDirs.pluginsTitle')).toBeTruthy();
- const pluginRow = screen.getByRole('button', { name: 'Cindy Art' });
- expect(pluginRow.querySelector('span')?.className).toContain('size-5');
- fireEvent.click(pluginRow);
- expect(onPluginSelect).toHaveBeenCalledWith(installedPlugin);
- });
-
- it('复用 Plugin 页的功能兜底图标,避免无包内头像时入口不一致', () => {
- render(
- createElement(ExtraDirsButton, {
- extraDirs: [],
- plugins: [installedMermaidPlugin],
- onPluginSelect: vi.fn(),
- }),
- );
-
- fireEvent.click(screen.getByLabelText('extraDirs.menuAria'));
- const pluginRow = screen.getByRole('button', { name: 'Mermaid' });
- expect(pluginRow.querySelector('svg.lucide-workflow')).toBeTruthy();
- expect(pluginRow.querySelector('svg.lucide-package')).toBeNull();
- });
-
- it('Host capability 插件可从菜单交给 composer 处理,不伪造 command', () => {
- const onPluginCapabilitySelect = vi.fn();
++ it('Host capability 插件由统一建议面板交给 composer 处理,不伪造 command', () => {
++ const entries = buildComposerSuggestionEntries({
++ query: '',
++ actions: [],
++ resources: [],
++ plugins: [iosSimulatorPluginSuggestion],
++ });
++ const onSelect = vi.fn();
+ render(
- createElement(ExtraDirsButton, {
- extraDirs: [],
- plugins: [installedIOSSimulatorPlugin],
- pluginAvailableIds: new Set(['ios-simulator']),
- onPluginCapabilitySelect,
++ createElement(AtMentionPanel, {
++ query: '',
++ state: { kind: 'ready', items: [], truncated: false },
++ entries,
++ focusedIndex: 0,
++ onFocusedIndexChange: vi.fn(),
++ onSelect,
++ onClose: vi.fn(),
++ onRetry: vi.fn(),
++ embedded: true,
+ }),
+ );
+
- 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);
++ expect(onSelect).toHaveBeenCalledWith({
++ kind: 'resource',
++ item: iosSimulatorPluginSuggestion.item,
++ });
+ });
+
+ it('已停用优先显示停用状态;可用但无直接入口的 Skill 标为 Agent 自动调用', () => {
++ const disabledEntries = buildComposerSuggestionEntries({
++ query: '',
++ actions: [],
++ resources: [],
++ plugins: [disabledIOSSimulatorPluginSuggestion],
++ });
+ const { rerender } = render(
- createElement(ExtraDirsButton, {
- extraDirs: [],
- plugins: [installedIOSSimulatorPlugin],
- pluginAvailableIds: new Set<string>(),
- onPluginCapabilitySelect: vi.fn(),
++ createElement(AtMentionPanel, {
++ query: '',
++ state: { kind: 'ready', items: [], truncated: false },
++ entries: disabledEntries,
++ focusedIndex: 0,
++ onFocusedIndexChange: vi.fn(),
++ onSelect: vi.fn(),
++ onClose: vi.fn(),
++ onRetry: vi.fn(),
++ embedded: true,
+ }),
+ );
- fireEvent.click(screen.getByLabelText('extraDirs.menuAria'));
+ expect(screen.getByText('extraDirs.pluginDisabled')).toBeTruthy();
+
++ const skillOnlyEntries = buildComposerSuggestionEntries({
++ query: '',
++ actions: [],
++ resources: [],
++ plugins: [skillOnlyPluginSuggestion],
++ });
+ rerender(
- createElement(ExtraDirsButton, {
- extraDirs: [],
- plugins: [installedSkillOnlyPlugin],
- pluginAvailableIds: new Set(['skill-only']),
++ createElement(AtMentionPanel, {
++ query: '',
++ state: { kind: 'ready', items: [], truncated: false },
++ entries: skillOnlyEntries,
++ focusedIndex: 0,
++ onFocusedIndexChange: vi.fn(),
++ onSelect: vi.fn(),
++ onClose: vi.fn(),
++ onRetry: vi.fn(),
++ embedded: true,
+ }),
+ );
+ expect(screen.getByText('extraDirs.pluginAgentInvoked')).toBeTruthy();
+ });
});
describe('PlanModeIndicator 激活 chip', () => {
diff --cc apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index 4da407b6d2,f4f6f88c08..ecf162c1f2
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@@ -2394,27 -2467,48 +2478,51 @@@ export function ChatInput(
[installedGhosts, workingDir],
);
const pluginAvailableIds = useMemo(
-- () =>
- new Set(ghostsForCommand.filter((ghost) => ghost.enabled).map((ghost) => ghost.manifest.id)),
- 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[]>(() => {
+ // 统一建议面板的插件条目(旧 `+` 菜单口径的并集):可用项可选,无指令或
- // 未生效项保留展示但置灰(entry 级 disabled + 原因)。
- const pluginSuggestions = useMemo<ComposerPluginSuggestion[]>(
- () => {
- // device-link 远程会话的插件运行在被控端;控制端清单既不代表远端
- // 已安装状态,选择后也无法用本地 InstalledGhost 解析并插入命令。
- if (deviceLinkDeviceId) return [];
- return pluginsForMenu.map((ghost) => {
- const hasCommand = !!ghost.manifest.command;
- const selectable = pluginAvailableIds.has(ghost.manifest.id) && hasCommand;
- return {
- item: {
- type: 'plugin-command' as const,
- name: ghost.manifest.name,
- relPath: ghost.manifest.command ?? `cindy://plugin/${ghost.manifest.id}`,
- 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(),
- },
- ...(selectable
- ? {}
- : {
- disabled: true,
- disabledReason: t(
- hasCommand ? 'extraDirs.pluginDisabled' : 'extraDirs.pluginNoCommand',
- ),
- }),
- };
- });
- },
- [deviceLinkDeviceId, pluginsForMenu, pluginAvailableIds, t],
- );
++ // Host 入口或未生效项保留展示但置灰(entry 级 disabled + 原因)。
++ const pluginSuggestions = useMemo<ComposerPluginSuggestion[]>(() => {
+ // 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]);
++ return pluginsForMenu.map((ghost) => {
++ const hasCommand = !!ghost.manifest.command;
++ const hostCapability = remoteHostId ? null : hostCapabilityForGhost(ghost);
++ const hasComposerEntry = hasCommand || hostCapability !== null;
++ const selectable = pluginAvailableIds.has(ghost.manifest.id) && hasComposerEntry;
++ const entryKey = ghost.manifest.command ?? hostCapability ?? '';
++ return {
++ item: {
++ type: 'plugin-command' as const,
++ name: ghost.manifest.name,
++ relPath:
++ ghost.manifest.command ??
++ (hostCapability
++ ? `cindy://host-capability/${hostCapability}`
++ : `cindy://plugin/${ghost.manifest.id}`),
++ pluginId: ghost.manifest.id,
++ ...(ghost.iconDataUrl ? { iconDataUrl: ghost.iconDataUrl } : {}),
++ sourceLabel: entryKey,
++ _nameLower: `${ghost.manifest.name} ${entryKey}`.toLowerCase(),
++ _relPathLower: `${entryKey} ${ghost.manifest.id}`.toLowerCase(),
++ },
++ ...(selectable
++ ? {}
++ : {
++ disabled: true,
++ disabledReason: t(
++ !pluginAvailableIds.has(ghost.manifest.id)
++ ? 'extraDirs.pluginDisabled'
++ : ghost.manifest.slots.includes('skill')
++ ? 'extraDirs.pluginAgentInvoked'
++ : 'extraDirs.pluginNoCommand',
++ ),
++ }),
++ };
++ });
++ }, [deviceLinkDeviceId, pluginsForMenu, pluginAvailableIds, remoteHostId, t]);
useEffect(() => {
setGhostCommandRoster(editor, ghostsForCommand);
}, [editor, ghostsForCommand]);
@@@ -3761,10 -3965,10 +4006,17 @@@
if (selectedItem.type === 'file-picker') return;
if (selectedItem.type === 'plugin-command') {
if (!selectedItem.pluginId) return;
-- const ghost = installedGhostsRef.current.find(
-- (candidate) => candidate.manifest.id === selectedItem.pluginId,
-- );
-- if (!ghost?.enabled || !ghost.manifest.command) return;
++ const ghost = filterGhostsForWorkdir(
++ installedGhostsRef.current,
++ workingDirRef.current,
++ ).find((candidate) => candidate.manifest.id === selectedItem.pluginId);
++ if (!ghost?.enabled) return;
++ const useHostCapability =
++ !ghost.manifest.command &&
++ !remoteHostId &&
++ !deviceLinkDeviceId &&
++ hostCapabilityForGhost(ghost) !== null;
++ if (!ghost.manifest.command && !useHostCapability) return;
editor
.chain()
.focus()
@@@ -3773,13 -3977,11 +4025,15 @@@
return true;
})
.run();
-- placeGhostAtComposerStart(editor, ghost, installedGhostsRef.current);
- setSuppressedAtAt(from);
++ if (ghost.manifest.command) {
++ placeGhostAtComposerStart(editor, ghost, installedGhostsRef.current);
++ } else {
++ placeHostCapabilityAtComposerStart(editor, ghost, installedGhostsRef.current);
++ }
+ closeAtPanel();
return;
}
- const directoryQuery = selectedByNativePicker
- ? null
- : getAtDirectoryCompletionQuery(selectedItem);
+ const directoryQuery = getAtDirectoryCompletionQuery(selectedItem);
if (directoryQuery) {
editor
.chain()
@@@ -3825,8 -4034,64 +4086,66 @@@
return true;
})
.run();
+ closeAtPanel();
+ },
+ [
+ closeAtPanel,
++ deviceLinkDeviceId,
+ editor,
+ effectiveAt,
++ remoteHostId,
+ resolveEffectiveAtRange,
+ setSyntheticAtAnchor,
+ ],
+ );
+
+ const handleComposerSuggestionSelect = useCallback(
+ (entry: ComposerSuggestionEntry) => {
+ if (isComposerSuggestionEntryDisabled(entry)) return;
+ if (entry.kind === 'resource') {
+ void insertAtResource(entry.item);
+ return;
+ }
+ if (!editor) return;
+ const range = resolveEffectiveAtRange();
+ if (!range) return;
+ editor
+ .chain()
+ .focus()
+ .command(({ tr }) => {
+ tr.delete(range.from, range.to);
+ return true;
+ })
+ .run();
+ closeAtPanel();
+ entry.action.run();
},
- [editor, trigger, workingDir, storageKey],
+ [closeAtPanel, editor, insertAtResource, resolveEffectiveAtRange],
+ );
+
+ const handleComposerSuggestionOpenChange = useCallback((nextOpen: boolean) => {
+ if (!nextOpen) {
+ setSyntheticAtAnchor(null);
+ return;
+ }
+ if (!editor || editor.isDestroyed || composerMutationLocked) return;
+ if (trigger.kind === 'slash') {
+ setSuppressedSlashAt(trigger.from);
+ } else if (trigger.kind === 'at') {
+ setSuppressedAtAt(trigger.from);
+ }
+ setSyntheticAtAnchor(editor.state.selection.from);
+ setAtFocus(0);
+ editor.commands.focus();
+ }, [
+ composerMutationLocked,
+ editor,
+ setSyntheticAtAnchor,
+ trigger,
+ ]);
+ const composerSuggestionFocusTarget = useCallback(
+ () => editor?.view.dom ?? null,
+ [editor],
);
// ── Send / Stop wiring ─────────────────────────────────────────────
@@@ -3908,41 -4171,6 +4227,44 @@@
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;
++ const canUseLocalHostCapability = !remoteHostId && !deviceLinkDeviceId;
++ const hostCapabilityGhost =
++ serializedHostCapability && canUseLocalHostCapability
++ ? (eligibleGhosts.find(
++ (candidate) =>
++ candidate.enabled &&
++ 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"
@@@ -4443,6 -4662,6 +4765,7 @@@
restoreFiles,
storageKey,
deviceLinkDeviceId,
++ remoteHostId,
t,
currentModelAgentKind,
enforceConnectedSourceGate,
diff --cc apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx
index 26acecf3d0,560859a381..1662ebecf5
--- a/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx
@@@ -15,7 -15,7 +15,15 @@@
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
- import { FileDiff, FolderTree, Globe, ListTodo, Smartphone, Terminal } from 'lucide-react';
-import { Activity, FileDiff, FolderTree, Globe, ListTodo, Terminal } from 'lucide-react';
++import {
++ Activity,
++ FileDiff,
++ FolderTree,
++ Globe,
++ ListTodo,
++ Smartphone,
++ Terminal,
++} from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { TabKindId, TabKindMenuMeta } from './types';
diff --cc apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx
index fb1eaffe98,6330d107f9..528ecacb1f
--- a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx
@@@ -20,9 -20,9 +20,10 @@@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
+ Activity,
FolderTree,
Globe,
+ Smartphone,
Terminal,
GitPullRequestArrow,
UsersRound,
diff --cc apps/desktop/src/renderer/vite-env.d.ts
index ee175dd751,ac2ee90730..04626c0f02
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@@ -24,25 -26,7 +26,26 @@@ type VoiceInputConnectionTestResult
type DesktopLoginAction = import('../shared/authIpc').DesktopLoginAction;
type DesktopLoginActionResult = import('../shared/authIpc').DesktopLoginActionResult;
type UtilityTextFailure = import('../shared/utilityTextResult').UtilityTextFailure;
+type IOSSimulatorSessionStatus = import('../shared/iosSimulatorIpc').IOSSimulatorSessionStatus;
+type IOSSimulatorStatusRequest = import('../shared/iosSimulatorIpc').IOSSimulatorStatusRequest;
+type IOSSimulatorToolRequest = import('../shared/iosSimulatorIpc').IOSSimulatorToolRequest;
+type IOSSimulatorToolResponse = import('../shared/iosSimulatorIpc').IOSSimulatorToolResponse;
+type IOSSimulatorAgentControlRequest =
+ import('../shared/iosSimulatorIpc').IOSSimulatorAgentControlRequest;
+type IOSSimulatorFocusRequest = import('../shared/iosSimulatorIpc').IOSSimulatorFocusRequest;
+type IOSSimulatorH264FramePush = import('../shared/iosSimulatorIpc').IOSSimulatorH264FramePush;
+type IOSSimulatorRouteStatusPush = import('../shared/iosSimulatorIpc').IOSSimulatorRouteStatusPush;
+type IOSSimulatorLiveTouchRequest =
+ import('../shared/iosSimulatorIpc').IOSSimulatorLiveTouchRequest;
+type IOSSimulatorMutationControlRequest =
+ import('../shared/iosSimulatorIpc').IOSSimulatorMutationControlRequest;
+type IOSSimulatorViewerRouteRequest =
+ import('../shared/iosSimulatorIpc').IOSSimulatorViewerRouteRequest;
+type IOSSimulatorViewerVisibilityRequest =
+ import('../shared/iosSimulatorIpc').IOSSimulatorViewerVisibilityRequest;
+type IOSSimulatorStreamProfileRequest =
+ import('../shared/iosSimulatorIpc').IOSSimulatorStreamProfileRequest;
+ type ProviderRoutingPayload = import('@cindy/model-providers').Provider['routing'];
type MakerSessionTreeSnapshot = import('@cindy/maker-core').SessionTreeSnapshot;
type BrowserBackendHealth = import('../shared/browserBackend').BrowserBackendHealth;
type BrowserBackendRecoveryResult = import('../shared/browserBackend').BrowserBackendRecoveryResult;
diff --cc apps/desktop/src/shared/__tests__/ghost.test.ts
index 88c9082ebd,e247472870..1e624356e3
--- a/apps/desktop/src/shared/__tests__/ghost.test.ts
+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts
@@@ -3212,16 -2978,15 +3286,18 @@@ describe('ghost · 2026-07-23 通用能
expect(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'],
++ minCindyVersion: '1.2.3',
+ slots: ['panel', 'session-context', 'pick', 'preview', 'workspace', 'ios-simulator'],
preview: { hosts: ['example.com'] },
});
expect(r.ok).toBe(true);
if (!r.ok) return;
++ expect(r.manifest.minCindyVersion).toBe('1.2.3');
expect(ghostContentKeys(r.manifest)).toContain('slotWorkspace');
+ expect(ghostContentKeys(r.manifest)).toContain('slotIOSSimulator');
const items = ghostPermissionItems(r.manifest);
expect(items).toEqual(
expect.arrayContaining([
@@@ -3253,6 -3012,6 +3329,15 @@@
);
});
++ it('ios-simulator 槽必须声明最低 Cindy 版本', () => {
++ const r = validateGhostManifest({
++ ...goodChipManifest(),
++ slots: ['panel', 'ios-simulator'],
++ });
++ expect(r.ok).toBe(false);
++ if (!r.ok) expect(r.reason).toContain('minCindyVersion');
++ });
++
it('ghostPreviewUrlAllowed:https + 白名单命中放行;http 仅 loopback;凭证/越界/畸形拒', () => {
const r = validateGhostManifest({
...goodChipManifest(),
diff --cc apps/desktop/src/shared/ghost.ts
index b69ac277fe,5bfcdcf021..c2b81e1c58
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@@ -1,8 -1,6 +1,8 @@@
- import { GHOST_OAUTH_SCOPES_MAX } from '@cindy/plugin-protocol';
+ import { GHOST_OAUTH_SCOPES_MAX, isValidCindyVersion } 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 共用。
@@@ -2789,13 -2708,12 +2827,16 @@@ export function validateGhostManifest(r
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 字符的非空字符串' };
}
+ if (raw.minCindyVersion !== undefined && !isValidCindyVersion(raw.minCindyVersion)) {
+ return { ok: false, reason: 'minCindyVersion 必须是合法的 SemVer 字符串' };
+ }
// kind 可省略(2026-07-12 晚定案:单形态后字段纯冗余,缺省即 chip);
// 写了就必须是 chip——写错值仍拒,不静默纠正(规则 9)。
if (raw.kind !== undefined && raw.kind !== 'chip') {
@@@ -3046,6 -2934,6 +3087,14 @@@
}
slots.push(name as GhostSlot);
}
++ // Host-native capabilities cannot be safely ignored by an older Cindy.
++ // Require an explicit installation/enablement floor for deterministic UX.
++ if (slots.includes('ios-simulator') && raw.minCindyVersion === undefined) {
++ return {
++ ok: false,
++ reason: 'slots 声明了 "ios-simulator" 时必须同时声明 minCindyVersion',
++ };
++ }
// 声明了面板却没申请 panel 槽(或反之有槽无面板)都是清单自相矛盾。
if (panel !== undefined && !slots.includes('panel')) {
return { ok: false, reason: '声明了 panel 但 slots 未包含 "panel"' };
diff --cc packages/maker-core/src/agents/codex/index.ts
index b9c6f8d9ef,1e86b11c82..ebae2ca6e4
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@@ -5228,22 -5684,9 +5795,22 @@@ export class CodexAgent extends BaseAge
params: CommandExecutionRequestApprovalParams,
): Promise<CommandExecutionRequestApprovalResponse> => {
// buffered/墓碑 turn 的审批请求不得上 UI (codex R12 P1) — 孤儿直接拒。
- const turnGate = gateServerRequestTurn(params.turnId);
+ const turnGate = gateServerRequestTurn(params.turnId, params.threadId);
if (turnGate === false) return { decision: 'decline' };
if (turnGate instanceof Promise && !(await turnGate)) return { decision: 'decline' };
+ const hostPolicy = this.deps.getShellCommandPolicy?.({
+ agentKind: 'codex',
+ command: params.command ?? '',
+ cwd: params.cwd ?? undefined,
+ });
+ if (hostPolicy?.decision === 'deny') {
+ log.warn('command execution denied by host policy', {
+ command: params.command ?? '',
+ cwd: params.cwd ?? null,
+ reason: hostPolicy.reason,
+ });
+ return { decision: 'decline' };
+ }
// requestId: approvalId 优先 (zsh-exec-bridge 多 callback 场景); 否则用 itemId
const requestId = params.approvalId ?? params.itemId;
const decision = await awaitApprovalDecision(requestId, 'commandExecution', {
@@@ -7815,35 -8222,24 +8410,49 @@@
handleTurnCompleted(params);
},
itemStarted: (params) => {
+ // 血缘不能跟着 turn 对账队列一起迟到:AppServerHost 只为未知 child 缓冲 5s。
+ // 卡片/翻译仍在队列内,这里只保留 provisional claim;父 turn 被接受后
+ // 重放 item 才 commit root route,孤儿则 discard。
+ const reservedChildThreadIds = reserveSubagentSpawnLineage(params.item);
if (enqueueIfBufferedTurn(params.turnId, () => handlers.itemStarted?.(params), {
modelWork: itemRepresentsModelWork(params.item),
- })) return;
- if (shouldIgnoreStaleTurnEvent(params.turnId)) return;
- if (interceptProposedPlanItem(params.item)) return;
+ })) {
+ rememberPendingSpawnLineage(params.turnId, reservedChildThreadIds);
+ return;
+ }
+ if (shouldIgnoreStaleTurnEvent(params.turnId)) {
+ discardPendingSpawnLineageIds(reservedChildThreadIds);
+ return;
+ }
+ if (interceptProposedPlanItem(params.item)) {
+ discardPendingSpawnLineageIds(reservedChildThreadIds);
+ return;
+ }
+ const shellCommand = shellCommandFromCodexItem(params.item);
+ if (shellCommand) {
+ const hostPolicy = this.deps.getShellCommandPolicy?.({
+ agentKind: 'codex',
+ command: shellCommand.command,
+ cwd: shellCommand.cwd,
+ });
+ if (hostPolicy?.decision === 'deny') {
++ discardPendingSpawnLineageIds(reservedChildThreadIds);
+ log.warn('command execution interrupted by host policy', {
+ turnId: params.turnId,
+ command: shellCommand.command,
+ reason: hostPolicy.reason,
+ });
+ void host
+ .request(Method.TurnInterrupt, { threadId, turnId: params.turnId })
+ .catch(() => undefined);
+ eventQueue.push({
+ type: 'error',
+ data: { message: hostPolicy.reason, isTerminal: false },
+ source: 'codex',
+ });
+ return;
+ }
+ }
// 模型已开始产出 → 本 turn 不再适合被过载重投整体重放。SDK echo 类 item
// (userMessage 等)不算产出, 见 itemRepresentsModelWork。
if (itemRepresentsModelWork(params.item)) producedOutputTurnIds.add(params.turnId);