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。

feat(plugins): add host model picker and version-pinned source guidance

MagicLizi61d7c24d7fba
diff --git a/apps/desktop/resources/system-skills/cindy-plugin-creator/SKILL.md b/apps/desktop/resources/system-skills/cindy-plugin-creator/SKILL.md
index 457d0b85f7..d0de4ad0c3 100644
--- a/apps/desktop/resources/system-skills/cindy-plugin-creator/SKILL.md
+++ b/apps/desktop/resources/system-skills/cindy-plugin-creator/SKILL.md
@@ -7,15 +7,16 @@ metadata:
# Cindy Plugin Creator
-Build a Cindy plugin from the user's request, or update an existing plugin. This Skill and its references are the authoring documentation shipped with the current Cindy host. Use these contracts instead of guessing APIs from a different release. Keep the user's language for discussion.
+Build a Cindy plugin from the user's request, or update an existing plugin. This Skill and its references are the authoring documentation shipped with the current Cindy host. Start by identifying the plugin's execution host and pinning its source to a verified tag or commit; use the shipped contracts and matching source together. Keep the user's language for discussion.
## Workflow
-1. Read the [authoring overview](references/plugin-overview.md), [design alignment](references/plugin-design.md), [structure](references/plugin-structure.md), and [manifest and capabilities](references/plugin-manifest.md). For an existing plugin, inspect its ghost.json and source first. Ask only about decisions the request leaves open; use option cards when available. Summarize the intended behavior, UI, permissions and acceptance criteria before implementation, following the design reference.
-2. Before writing code, read the [sandbox boundaries](references/plugin-sandbox.md) and [packaging workflow](references/plugin-packaging.md). Read the capability references below as needed; do not load the whole manual at once.
-3. For a new plugin, prefer ghost_forge_scaffold with the appropriate plain, agent-action, node-json-rpc or node-mcp template, then edit the generated files. For an existing plugin, preserve its identity, data and compatible behavior. Use schemaVersion: 3 for new manifests and declare the first stable Cindy version actually required.
-4. Implement and validate the requested behavior, including Light and Dark modes for any UI. Separate current Agent tool-call operations from autonomous plugin capabilities, as described in the manifest and Agent-call references. Use [tool discovery](references/plugin-tool-discovery.md) and [manuals](references/plugin-manual.md) for authoring the plugin's own discovery and workflow documentation.
-5. Call ghost_forge_pack to validate and produce the .cindy artifact. Report what was tested and what remains unverified. Packaging does not install or publish: use ghost_forge_install only when installation is requested, and follow [public marketplace publication and attribution (§7.3–7.4)](references/plugin-packaging.md) for community publication, or [publishing signatures and review (§8)](references/plugin-publishing.md) as applicable. Read the releaseNotes contract in [manifest (§2)](references/plugin-manifest.md) before submitting a version.
+1. Read [host version and source verification](references/plugin-source-verification.md). Identify the Cindy computer that will execute the plugin, obtain its version through available read-only host information, and resolve that release's tag or the build's source commit in the official repository. Inspect the relevant public API and its host implementation at that exact commit before relying on a capability. Do not substitute latest main or an unrelated local checkout. If the version or source cannot be verified, follow the reference's fallback and state the limitation.
+2. Read the [authoring overview](references/plugin-overview.md), [design alignment](references/plugin-design.md), [structure](references/plugin-structure.md), and [manifest and capabilities](references/plugin-manifest.md). For an existing plugin, inspect its ghost.json and source first. Ask only about decisions the request leaves open; use option cards when available. Summarize the intended behavior, UI, permissions and acceptance criteria before implementation, following the design reference.
+3. Before writing code, read the [sandbox boundaries](references/plugin-sandbox.md) and [packaging workflow](references/plugin-packaging.md). Read the capability references below as needed; do not load the whole manual at once.
+4. For a new plugin, prefer ghost_forge_scaffold with the appropriate plain, agent-action, node-json-rpc or node-mcp template, then edit the generated files. For an existing plugin, preserve its identity, data and compatible behavior. Use schemaVersion: 3 for new manifests and declare the first stable Cindy version actually required.
+5. Implement and validate the requested behavior, including Light and Dark modes for any UI. Separate current Agent tool-call operations from autonomous plugin capabilities, as described in the manifest and Agent-call references. Use [tool discovery](references/plugin-tool-discovery.md) and [manuals](references/plugin-manual.md) for authoring the plugin's own discovery and workflow documentation.
+6. Call ghost_forge_pack to validate and produce the .cindy artifact. Report what was tested and what remains unverified. Packaging does not install or publish: use ghost_forge_install only when installation is requested, and follow [public marketplace publication and attribution (§7.3–7.4)](references/plugin-packaging.md) for community publication, or [publishing signatures and review (§8)](references/plugin-publishing.md) as applicable. Read the releaseNotes contract in [manifest (§2)](references/plugin-manifest.md) before submitting a version.
Cindy supplies the Forge tools. If they are unavailable in the current environment, explain the missing capability and continue any local source work that is possible; do not claim to have packaged, installed or published. The legacy ghost_forge_guide tool serves these same references by section number or title when needed. It is a compatibility entry point, not a second source of documentation.
@@ -27,6 +28,7 @@ These references describe Cindy plugin contracts and host APIs available to plug
Start here to define the plugin's behavior, package and Agent-facing tools.
+- [先按宿主版本定位开源源码:tag / commit(§0a)](references/plugin-source-verification.md)
- [插件创作总览](references/plugin-overview.md)
- [插件需求与交互设计(§0)](references/plugin-design.md)
- [插件源码与包目录结构(§1)](references/plugin-structure.md)
@@ -44,6 +46,7 @@ Use when implementing plugin code, calling host APIs or declaring access to reso
- [插件读取宿主公开上下文(§4.1)](references/plugin-host-context.md)
- [插件处理 Agent 在途调用:网络与工作目录(§4.2)](references/plugin-agent-call-context.md)
- [插件读取可用 Agent 模型列表(§4.0.3a)](references/plugin-agent-models.md)
+- [插件打开宿主统一模型选择器 pickModel(§4.0.3b)](references/plugin-agent-models.md)
- [插件接入媒体模型与生成结果(§4.0.4)](references/plugin-media.md)
- [插件联网与凭证代发 network(§4.7)](references/plugin-network.md)
- [插件文件操作与持久作品库 fs / library(§4.10)](references/plugin-files-and-library.md)
diff --git a/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-agent-models.md b/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-agent-models.md
index 3da505a5c8..517520752a 100644
--- a/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-agent-models.md
+++ b/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-agent-models.md
@@ -7,3 +7,53 @@ visible 跟随当前账号模型选择器;建议默认显示可见项,隐藏
只包含本机已连接且可用于新任务的模型,不代表远程 SSH 目录。读取不调用模型、
不触发凭证认领或上游发现,不返回凭证、账号 identity 或 endpoint;不需要新增 manifest 权限。
旧 Host 可能返回 404,插件应明确提示升级;503 时提供重试。运行前再次核验选定来源。
+
+## 4.0.3b 宿主统一模型选择器(新增接口,尚未发布)
+
+不想自行绘制选模界面时,电子脑调用 `cindy.pickModel(options?)`。
+Host 打开与 Cindy 共用的模型选择器,用户确认后返回完整配置;取消、关闭页面或超时不返回配置。
+不需要新增 manifest 权限,不改应用默认、插件默认或现有任务,不调用模型。
+
+```js
+if (typeof cindy.pickModel !== 'function') {
+ // 当前 Host 不支持,请提示用户升级;不要改为维护一份硬编码名单。
+ return;
+}
+const selected = await cindy.pickModel({
+ // initial: savedRoute, // 可选,必须是下面的完整 route
+ ...(msg.mobilePageId ? { mobilePageId: msg.mobilePageId } : {}),
+});
+if (selected.ok) {
+ // 自行保存 selected.route;创建普通任务时可原样作为 cindy.tasks.create 的 route。
+ // 任务创建和执行仍需 agent.tasks 的正常批准,选模本身不授予执行权限。
+}
+```
+
+成功:`{ok:true,route:{agentKind,providerId,model,effort,fastMode}}`。
+`agentKind` 为 `cc | codex | pi`,`effort` 为空串表示未指定,
+`fastMode` 为布尔值或 `"ultrafast"`。保留完整组合,不根据模型名重新猜来源或引擎。
+失败:`{ok:false,errorCode,message}`;`CANCELLED` 表示本次选择已取消,
+`BUSY` / `RATE_LIMITED` 表示已有选择器或请求过频,`UNAVAILABLE` 表示没有可用宿主页面,
+`PERMISSION_DENIED` 表示来源插件或账号已变化,`INVALID_REQUEST` 表示参数不合法。
+用户确认时 Host 重新校验真实来源、模型、档位和 Fast;不可用时保留选择器供用户改选。
+
+桌面插件的 settings、panel、mainView 还可直接发起同源请求:
+
+```js
+const response = await fetch('/model-picker', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ /* initial: savedRoute */ }),
+});
+const selected = await response.json();
+```
+
+该端点仅接受 `initial`,只支持 POST、无查询参数。旧 Host 404 时提示升级,
+503 时提示稍后重试;正常受理的取消与错误使用上述结构化结果。
+手机与远程桌面设置页通过业务频道交给电子脑调用 `pickModel`,必须原样转交 Host 附加的
+`mobilePageId`,选择器才会显示在发起操作的设备,并读取插件执行电脑的目录。
+不要把 `mobilePageId` 存成全局最近设备;不传时只在插件运行电脑打开。
+同一 Host 同时只有一个插件选模请求,等待上限 90 秒;不要后台循环弹窗或自动重试取消。
+窗口、页面、连接、账号或安装版本变化后,旧回执不能交给替代实例。
+此接口不选择执行电脑或 SSH 工作区,也不提供凭证、endpoint 或完整 ProviderView。
+依赖此接口的插件应在接口正式发布后填入实际的首个 `minCindyVersion`,并保留运行时能力检查。
diff --git a/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-compatibility.md b/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-compatibility.md
index 96e29d24f5..660a56d74d 100644
--- a/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-compatibility.md
+++ b/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-compatibility.md
@@ -1,5 +1,8 @@
## 9. 兼容性与常见拒装原因
+编写前先按 [§0a](plugin-source-verification.md) 用执行宿主的实际版本定位 tag / commit,
+核验所依赖接口;不能用最新 main、控制端版本或未核实的本地 HEAD 推断旧宿主支持范围。
+
插件开发不应受当前客户端能力注册进度限制。未知顶层能力、对象扩展字段、能力动作
与订阅事件保留为声明,不因此阻断发布或安装,也不因此获得执行权限。
插件必须检查所需接口是否存在并处理不支持响应:可选功能局部降级,必要能力缺失时
diff --git a/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-mobile-pages.md b/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-mobile-pages.md
index 7a1bdbb92d..f8bd67fc48 100644
--- a/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-mobile-pages.md
+++ b/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-mobile-pages.md
@@ -11,7 +11,7 @@
请求必须包含业务 requestId;保存、创建任务等写操作沿用同一个 requestId 查询/去重,
超时不等于未执行,Host 不替作者盲目重发。
- 电脑逻辑页收到手机业务消息时,Host 附上不透明 `mobilePageId`(覆盖页面自报的值)。
- 异步链显式保留它;confirm、notify、tasks、pick、workspace、preview、schedule 请求均原样附带。
+ 异步链显式保留它;confirm、notify、tasks、pick、pickModel、workspace、preview、schedule 请求均原样附带。
卡片动作消息也包含该字段。不要存为全局“最近手机”,也不能在后台复用过期来源。
- 示例:`const origin = msg.mobilePageId; const answer = await cindy.confirm({ body: "应用调整?", ...(origin ? { mobilePageId: origin } : {}) });`
只有 `answer.ok && answer.confirmed` 才能继续;页面关闭、覆盖、超时或撤权均不能当成同意。
diff --git a/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-overview.md b/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-overview.md
index 07df3e7298..17ec0e5c06 100644
--- a/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-overview.md
+++ b/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-overview.md
@@ -2,10 +2,14 @@
插件是 Cindy 的第三方能力包,文件形态是 `.cindy`(zip 包)。装入后可给
主机叠加:AI 可调用的工具、常驻界面面板、模型代办能力。本手册教你(agent)替用户
-写一个插件。**流程:先读本 Skill 的参考目录 → 按 §0 用提问卡片和用户对齐设计 → 按需
+写一个插件。**流程:先按 §0a 确认执行宿主并用 tag / commit 定位开源源码 → 读本 Skill 的参考目录 → 按 §0 用提问卡片和用户对齐设计 → 按需
读透相关章(动手前至少读完"沙箱红线"与"打包与测试"两章) → 在工作目录写源码文件 →
ghost_forge_pack 校验并生成 .cindy 产物;需要发布时改用 publish intent 取得一次性票据。**
+版本获取、tag / commit 解析、源码入口与无法核实时的处理见
+[按宿主版本定位开源源码(§0a)](plugin-source-verification.md)。先定位版本,再查所需接口;
+读取公开源码不扩张插件权限,仍须遵守当前宿主的真实运行结果。
+
**安装与更新契约**:用户导入本地 `.cindy`、点击市场安装、明确要求 Agent 安装,或插件命中
服务端 `defaultInstall`,都是明确的安装依据。Cindy 校验真实包后,首次安装会先列出插件声明的
全部权限请用户确认(Agent 发起的安装在任务里弹确认卡,不论任务权限档),确认后安装并启用;
diff --git a/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-source-verification.md b/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-source-verification.md
new file mode 100644
index 0000000000..27953505e7
--- /dev/null
+++ b/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-source-verification.md
@@ -0,0 +1,68 @@
+## 0a 先按宿主版本定位开源源码(tag / commit)
+
+编写、修改或回答插件宿主 API 问题时,先确定插件实际运行的 Cindy 版本,再核对该版本的
+公开接口和实现。随包手册用于发现能力与理解契约;源码用于核实具体行为和手册疑点。
+官方客户端仓库是 https://github.com/makecindy/cindy,包含 desktop、mobile 和共享 packages;
+服务端不在此仓库中,客户端代码不能证明服务端已经部署某项能力。
+
+### 先确定宿主和不可变的源码版本
+
+1. 确认插件会在哪台 Cindy 电脑运行。手机或远程设置页只是控制端时,应核对插件执行电脑,
+ 不能拿手机应用、控制端电脑或底层 Claude Code / Codex / Pi 的版本代替宿主版本。
+2. 从已发现的只读宿主能力取得版本。当前 Cindy 可先发现
+ `cindy_helper.list_tools({category: 'app_update'})`,再通过 `call_tool` 调用
+ `check_app_update`,读取 `currentVersion`。这一步不安装或重启应用;更新状态不受支持
+ 也可能仍有版本字段。该工具只查询其所在电脑,不要为它编造跨电脑参数。目标电脑的版本
+ 无法直接读取时,可请用户提供那台电脑侧栏左下角账号卡片显示的版本号。
+3. 若有该运行构建的 `sourceCommit`,优先核验并使用它;打包资源的 `cindy-source.json`
+ 可提供此字段,但旧版本可能没有。只在已确认的目标应用资源目录按需读取;不要假设安装版
+ 附带源码。`0.0.0`、开发版或个人构建需要核实实际构建来源;本地源码有未提交修改时,
+ commit 只代表已提交的基础源码。插件的 `/app-context` 当前不提供版本或 commit,
+ 不能捏造字段或 API。
+4. 对正式发布的构建,在官方仓库核实对应的实际 tag。通常是 `v<currentVersion>`,必须保留
+ `-beta` 等后缀并验证 tag 存在;不要只靠拼接名字就宣称匹配。将 tag 解析为完整 commit,
+ annotated tag 要继续解析其指向的 commit。若 tag 与可信构建 commit 不一致,以实际构建
+ 为依据并说明差异。tag、commit 均无法确认时,不选最近版本、latest 或 main 代替。
+
+### 按所锁定的 commit 只读查源码
+
+优先使用当前可用的 GitHub 插件、gh 或网页读取指定 ref;无需为一次查询克隆整个仓库。
+本地已有官方仓库时,可以用 `git show` 读取历史文件,无需切换或重置用户的工作分支。
+以下占位符需替换为已核实的值:
+
+```sh
+git ls-remote --tags https://github.com/makecindy/cindy.git 'refs/tags/<verified-tag>' 'refs/tags/<verified-tag>^{}'
+git -C <source-repo> rev-parse 'refs/tags/<verified-tag>^{commit}'
+git -C <source-repo> show '<full-commit>:apps/desktop/src/preload/ghostPreload.ts'
+```
+
+证据链接使用 `https://github.com/makecindy/cindy/blob/<full-commit>/<repo-relative-path>#L<line>`。
+对结论有影响的手册、类型、实现和测试使用同一个 commit;从 main 看到的能力只能作为
+未来版本线索。当前工作目录的 HEAD 也需要与宿主构建核对,不能因为目录叫 Cindy 就认定匹配。
+
+### 顺着公开入口核对实际行为
+
+下面的路径是查找入口;历史版本目录不同或文件缺失时,在该 commit 的树内继续检索。
+
+| 要核实的内容 | 源码入口 |
+| --- | --- |
+| 对应版本的手册 | `apps/desktop/resources/system-skills/cindy-plugin-creator/`;更早版本沿其实际手册位置查找 |
+| manifest 声明与校验 | `packages/plugin-protocol/src/manifest.ts`、`apps/desktop/src/shared/ghost.ts` |
+| 电子脑能调用的公开桥接方法 | `apps/desktop/src/preload/ghostPreload.ts` |
+| 管子请求的处理、资格与权限 | `apps/desktop/src/main/cindy-brain/index.ts` 及对应的 `*Slot.ts` / 服务实现 |
+| 设置页、panel、mainView 同源端点 | `apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts` |
+| 手机与远程页面 | `apps/desktop/src/main/cindy-brain/mobilePageService.ts`、`apps/mobile/src/plugins/PluginPage.tsx`、`packages/device-link/src/pluginPages.ts` |
+| 打包校验与产物 | `apps/desktop/src/main/cindy-brain/forge.ts` |
+
+对本次要依赖的 API,继续读宿主处理与相关测试,核对参数、返回值、能力声明、权限、
+平台及运行条件。Main 内部函数、类型声明或测试里的 mock 单独存在,都不能证明插件可调用。
+代码存在也不表示当前账号已授权、运行环境已就绪或服务端支持;执行时仍要检测接口并处理
+不支持、权限拒绝和真实错误。验证目标版本支持某接口,也不能据此推断它首次发布的
+`minCindyVersion`,兼容声明仍按实际确认的首个正式版本填写。
+
+### 版本、网络或源码不可核实时
+
+明确说明未核实的范围,继续依据当前宿主随包手册和可用的运行时结果做能完成的工作;
+不要将检索不到源码等同于没有该能力,也不要凭 main 给旧宿主增加接口。需要该证据才能
+完成的部分保留待核实项。源码与手册有差异时给出具体 API、commit 和文件证据,区分
+源码结论与实际调用结果,再选择当前宿主能工作的公开路径。
diff --git a/apps/desktop/scripts/fixtures/plugin-model-picker/fixture.tsx b/apps/desktop/scripts/fixtures/plugin-model-picker/fixture.tsx
new file mode 100644
index 0000000000..ce5aaf47c0
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/plugin-model-picker/fixture.tsx
@@ -0,0 +1,77 @@
+import type { ProviderView } from '@cindy/model-providers';
+import { mountPage, subscription, forbid } from '../../ui-page/harness';
+import { PluginModelPickerDialog } from '../../../src/renderer/cindy-brain/PluginModelPickerHost';
+import {
+ beginProvidersRefresh,
+ commitProvidersSnapshot,
+} from '../../../src/renderer/lib/providersSnapshotStore';
+import { getDataOwnerGeneration } from '../../../src/renderer/contexts/dataOwnerGeneration';
+
+const provider = {
+ id: 'example',
+ name: 'Example Provider',
+ source: 'user',
+ auth: { method: 'none' },
+ connected: true,
+ agents: ['codex'],
+ routing: { codex: {} },
+ models: {
+ codex: [
+ {
+ id: 'demo',
+ name: 'Demo Model',
+ mode: 'chat',
+ contextWindow: 128000,
+ efforts: ['low', 'medium', 'high'],
+ defaultEffort: 'medium',
+ supportsFastMode: true,
+ },
+ ],
+ },
+} as unknown as ProviderView;
+const owner = getDataOwnerGeneration();
+const snapshot = {
+ dataOwnerId: owner.dataOwnerId,
+ ownerGeneration: owner.generation,
+ providers: [provider],
+ providerOrder: [provider.id],
+};
+commitProvidersSnapshot(beginProvidersRefresh(), snapshot);
+
+void mountPage({
+ host: {
+ safeStorageRead: async () => null,
+ maker: {
+ listProviders: async () => snapshot,
+ listAvailableAgents: async () => ['codex'],
+ onProvidersChanged: subscription('providersChanged'),
+ getModelContextLimit: async () => ({ limit: 128000, isCustomized: false }),
+ getCapabilities: async () => ({
+ hasFastMode: true,
+ availableModels: [],
+ effortLevels: ['low', 'medium', 'high'].map((id) => ({ id, displayName: id })),
+ permissionModes: [],
+ }),
+ setModel: forbid('maker.setModel'),
+ createSession: forbid('maker.createSession'),
+ },
+ },
+ render: () => (
+ <PluginModelPickerDialog
+ request={{
+ requestId: 'fixture',
+ ghostId: 'example-plugin',
+ ghostName: 'Example Plugin',
+ expiresAt: Date.now() + 90_000,
+ initial: {
+ agentKind: 'codex',
+ providerId: 'example',
+ model: 'demo',
+ effort: 'medium',
+ fastMode: false,
+ },
+ }}
+ onAnswer={async () => ({ handled: true, accepted: false })}
+ />
+ ),
+});
diff --git a/apps/desktop/scripts/fixtures/plugin-model-picker/ui-page.mjs b/apps/desktop/scripts/fixtures/plugin-model-picker/ui-page.mjs
new file mode 100644
index 0000000000..6321f6a857
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/plugin-model-picker/ui-page.mjs
@@ -0,0 +1,24 @@
+export default {
+ name: 'plugin-model-picker',
+ entry: './fixture.tsx',
+ viewport: { width: 800, height: 760 },
+ real: 'PluginModelPickerDialog, ConfirmDialog, ModelSelectorContent and the unified model panel',
+ notCovered:
+ 'Plugin transport, real provider entitlement, account changes, mobile native controls and paid inference',
+ cases: {
+ default: { about: 'Plugin picker with a complete initial configuration' },
+ 'plugin-config': { about: 'Plugin picker with a complete initial configuration' },
+ 'plugin-narrow': {
+ about: 'Plugin picker in a narrow viewport',
+ viewport: { width: 360, height: 740 },
+ },
+ },
+ async check(page, ui) {
+ await page.getByRole('alertdialog').waitFor();
+ await page
+ .getByRole('listbox', { name: await ui.t('newChat.modelSelector.modelListAria') })
+ .waitFor();
+ await page.getByText('Demo Model').first().waitFor();
+ await ui.capture('picker');
+ },
+};
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostModelPicker.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostModelPicker.test.ts
new file mode 100644
index 0000000000..b0e489dd2c
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostModelPicker.test.ts
@@ -0,0 +1,188 @@
+/** Test value: new public request/resolve round trip, not covered by the read-only catalog tests.
+ * Protects plugin-security §3/§5 and Electron §5: minimal foreign-window answer, account switch
+ * during async validation, revoked source and closed page must never deliver a route. Tier: unit.
+ * No Electron, filesystem, network or real waits. Standalone wall time: 2.18s (2026-10-28).
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { ProviderView } from '@cindy/model-providers';
+import type { InstalledGhost } from '../../../shared/ghost.js';
+import type { PluginTaskRoute } from '../../../shared/pluginTasks.js';
+import type { PluginModelPickerRequest } from '../../../shared/pluginModelPicker.js';
+import { GhostModelPicker, isPluginModelPickerRouteAvailable } from '../ghostModelPicker.js';
+
+const route: PluginTaskRoute = {
+ agentKind: 'codex',
+ providerId: 'mine',
+ model: 'model',
+ effort: 'high',
+ fastMode: 'ultrafast',
+};
+function setup() {
+ let installation = 'owner-a:revision-1',
+ now = 1_000;
+ const ghost = { enabled: true, manifest: { name: 'Example' } } as InstalledGhost;
+ const sent: PluginModelPickerRequest[] = [];
+ const dismiss = vi.fn(),
+ available = vi.fn(async () => true);
+ let cancel!: () => void;
+ const target = vi.fn(() => ({
+ id: 7,
+ dismiss,
+ send: (request: PluginModelPickerRequest, close: () => void) => {
+ sent.push(request);
+ cancel = close;
+ return true;
+ },
+ }));
+ const picker = new GhostModelPicker({
+ getGhost: () => ghost,
+ installation: () => installation,
+ target,
+ available,
+ now: () => now,
+ });
+ return {
+ picker,
+ ghost,
+ sent,
+ dismiss,
+ available,
+ target,
+ changeOwner: () => {
+ installation = 'owner-b:revision-1';
+ },
+ advance: () => {
+ now += 3_000;
+ },
+ close: () => cancel(),
+ };
+}
+afterEach(() => vi.useRealTimers());
+
+describe('Host plugin model picker', () => {
+ it('returns a complete configuration only to the originating installation after its Host window answers', async () => {
+ const h = setup(),
+ result = h.picker.request('plugin', { initial: route });
+ const id = h.sent[0].requestId;
+ expect(await h.picker.resolve(99, id, route)).toEqual({ handled: false, accepted: false });
+ expect(await h.picker.resolve(7, 'other-request', route)).toEqual({
+ handled: false,
+ accepted: false,
+ });
+ expect(await h.picker.resolve(7, id, route)).toEqual({ handled: true, accepted: true });
+ expect(await result).toEqual({ ok: true, route });
+ expect(h.dismiss).toHaveBeenCalledWith(id);
+ expect(await h.picker.resolve(7, id, route)).toEqual({ handled: false, accepted: false });
+ });
+
+ it('keeps the picker open when a source disappears and accepts a later valid selection', async () => {
+ const h = setup(),
+ result = h.picker.request('plugin');
+ const id = h.sent[0].requestId;
+ expect(await h.picker.resolve(7, id, { ...route, apiKey: 'private' })).toEqual({
+ handled: true,
+ accepted: false,
+ });
+ h.available.mockResolvedValueOnce(false);
+ expect(await h.picker.resolve(7, id, route)).toEqual({ handled: true, accepted: false });
+ expect(h.dismiss).not.toHaveBeenCalled();
+ await h.picker.resolve(7, id, { ...route, providerId: 'replacement' });
+ expect(await result).toEqual({ ok: true, route: { ...route, providerId: 'replacement' } });
+ });
+
+ it.each(['installation', 'page'] as const)(
+ 'does not deliver a route when %s changes during validation',
+ async (boundary) => {
+ const h = setup(),
+ result = h.picker.request('plugin');
+ const target = h.target.mock.results[0].value as { isCurrent?: () => boolean };
+ h.available.mockImplementationOnce(async () => {
+ if (boundary === 'installation') h.changeOwner();
+ else target.isCurrent = () => false;
+ return true;
+ });
+ expect(await h.picker.resolve(7, h.sent[0].requestId, route)).toEqual({
+ handled: true,
+ accepted: false,
+ });
+ expect(await result).toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });
+ },
+ );
+
+ it.each(['cancel', 'page-abort', 'window-close', 'timeout'] as const)(
+ 'settles %s without returning a configuration',
+ async (reason) => {
+ vi.useFakeTimers();
+ const h = setup(),
+ controller = new AbortController();
+ const result = h.picker.request('plugin', {}, () => true, controller.signal);
+ if (reason === 'cancel') await h.picker.resolve(7, h.sent[0].requestId, null);
+ else if (reason === 'page-abort') controller.abort();
+ else if (reason === 'window-close') h.close();
+ else vi.advanceTimersByTime(90_000);
+ expect(await result).toMatchObject({ ok: false, errorCode: 'CANCELLED' });
+ expect(h.dismiss).toHaveBeenCalledWith(h.sent[0].requestId);
+ },
+ );
+
+ it('rejects malformed and disabled requests, concurrent dialogs and immediate reopening', async () => {
+ const h = setup();
+ expect(
+ await h.picker.request('plugin', { initial: { ...route, endpoint: 'private' } }),
+ ).toMatchObject({ errorCode: 'INVALID_REQUEST' });
+ h.ghost.enabled = false;
+ expect(await h.picker.request('plugin')).toMatchObject({ errorCode: 'PERMISSION_DENIED' });
+ h.ghost.enabled = true;
+ const pending = h.picker.request('plugin');
+ expect(await h.picker.request('other')).toMatchObject({ errorCode: 'BUSY' });
+ h.picker.cancel();
+ await pending;
+ expect(await h.picker.request('plugin')).toMatchObject({ errorCode: 'RATE_LIMITED' });
+ h.advance();
+ h.target.mockReturnValueOnce(null as never);
+ expect(await h.picker.request('plugin')).toMatchObject({ errorCode: 'UNAVAILABLE' });
+ });
+
+ it('forwards an explicit mobile origin without falling back to a local window', async () => {
+ const h = setup();
+ h.target.mockReturnValueOnce(null as never);
+ expect(await h.picker.request('plugin', { mobilePageId: 'expired-phone-page' })).toMatchObject({
+ errorCode: 'UNAVAILABLE',
+ });
+ expect(h.target).toHaveBeenCalledExactlyOnceWith('plugin', 'expired-phone-page');
+ });
+});
+
+it('validates effort and Fast against the exact connected model and available engine', () => {
+ const provider = {
+ id: 'mine',
+ source: 'user',
+ connected: true,
+ agents: ['codex'],
+ routing: { codex: { enabled: true } },
+ models: {
+ codex: [
+ {
+ id: 'model',
+ mode: 'chat',
+ efforts: ['high'],
+ supportsFastMode: true,
+ supportsUltrafastMode: true,
+ },
+ ],
+ },
+ } as unknown as ProviderView;
+ expect(isPluginModelPickerRouteAvailable(route, [provider], ['codex'])).toBe(true);
+ for (const candidate of [
+ { ...route, providerId: 'other' },
+ { ...route, effort: 'low' },
+ ])
+ expect(isPluginModelPickerRouteAvailable(candidate, [provider], ['codex'])).toBe(false);
+ expect(isPluginModelPickerRouteAvailable(route, [provider], [])).toBe(false);
+ provider.models.codex![0].supportsUltrafastMode = false;
+ expect(isPluginModelPickerRouteAvailable(route, [provider], ['codex'])).toBe(false);
+ provider.connected = false;
+ expect(
+ isPluginModelPickerRouteAvailable({ ...route, fastMode: false }, [provider], ['codex']),
+ ).toBe(false);
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/mobilePageService.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/mobilePageService.test.ts
index 930d20b9e1..8e20e19141 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/mobilePageService.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/mobilePageService.test.ts
@@ -7,7 +7,7 @@ import { parseRemoteResourceGetRequest, type PluginPageDocument } from '@cindy/d
function setup(
projection: Pick<
ConstructorParameters<typeof MobilePluginPages>[0],
- 'setupAssessment' | 'runtimeState' | 'listOrder'
+ 'setupAssessment' | 'runtimeState' | 'listOrder' | 'answerModelPicker'
> = {},
) {
let owner = 'a',
@@ -114,6 +114,29 @@ function setup(
};
}
describe('mobile plugin pages', () => {
+ // New Host picker round trip: page/controller ownership and suspend cancellation are
+ // not covered by the existing directory picker. Minimal input: one native request. Tier: unit.
+ it('delivers model selection only to its source controller and cancels it when the page suspends', async () => {
+ const answer = vi.fn(async () => ({ handled: true, accepted: true }));
+ const h = setup({ answerModelPicker: answer }), { pageId } = await h.open();
+ await h.invoke('poll', { pageId, after: 0 });
+ const target = h.service.modelPickerTarget(pageId, 'practice')!;
+ const cancel = vi.fn();
+ const request = { requestId: 'model-choice', ghostId: 'practice', ghostName: 'Practice', expiresAt: Date.now() + 90_000 };
+ expect(target.send(request, cancel)).toBe(true);
+ const poll = (await h.invoke('poll', { pageId, after: 0 })).result as { modelPickers: unknown[] };
+ expect(poll.modelPickers).toEqual([request]);
+ await expect(h.invoke('answer-model-picker', { pageId, requestId: request.requestId, route: null }, 'phone-b')).rejects.toThrow();
+ expect(answer).not.toHaveBeenCalled();
+ expect((await h.invoke('answer-model-picker', { pageId, requestId: request.requestId, route: null })).result)
+ .toEqual({ handled: true, accepted: true });
+ expect(answer).toHaveBeenCalledWith(pageId, request.requestId, null);
+ await h.invoke('suspend', { pageId });
+ expect(cancel).toHaveBeenCalledOnce();
+ expect(h.service.modelPickerTarget(pageId, 'practice')).toBeNull();
+ target.dismiss(request.requestId);
+ await h.invoke('close', { pageId });
+ });
it.each([undefined, true, false])('projects task card visibility without removing task settings access: %s', async (showTaskPreferences) => {
const h = setup();
h.ghost.manifest.agent = { tasks: true };
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.ts
index eda79c9687..d8b572555e 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.ts
@@ -3,6 +3,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import type { WebContents } from 'electron';
import { PLUGIN_OAUTH_CHANNEL, REMOTE_RESOURCE_INVOKE_CHANNEL } from '@cindy/device-link';
import { MobilePluginPages } from '../mobilePageService.js';
+import { GhostModelPicker } from '../ghostModelPicker.js';
import { AuthenticatedOauthHost, OauthHostIdentity } from '../../plugin-oauth/authentication.js';
import { getRemoteOauthContext, withRemoteOauthContext } from '../../plugin-oauth/context.js';
import { ghostInstallApprovalToken, type InstalledGhost } from '../../../shared/ghost.js';
@@ -56,6 +57,7 @@ import {
openRemotePluginSettings,
closeRemotePluginSettings,
answerRemotePluginSettingsDirectory,
+ answerRemotePluginSettingsModelPicker,
resolveRemoteSettingsAttach,
parseSettingsDocument,
} from '../remotePluginSettingsController.js';
@@ -68,7 +70,8 @@ afterEach(() => {
mock.peerCurrent = true;
vi.clearAllMocks();
});
-function fixture(namespace: string | null = null) {
+function fixture(namespace: string | null = null,
+ answerModelPicker?: ConstructorParameters<typeof MobilePluginPages>[0]['answerModelPicker']) {
let owner: string | null = 'owner',
revision = 'installed-1',
allowed = true,
@@ -127,6 +130,7 @@ function fixture(namespace: string | null = null) {
async () => '/target/resolved',
);
const service = new MobilePluginPages({
+ answerModelPicker,
now: () => Date.now() + nowOffset,
list: () => [ghost],
revision: () => revision,
@@ -474,6 +478,32 @@ describe('original remote plugin settings', () => {
expect((await writing).status).toBe(503);
expect(f.stored.size).toBe(0);
});
+ // New native request/result across the existing sealed settings channel. Unlike catalog GET,
+ // this must bind the answering host and withhold native requests from author HTML. Tier: unit.
+ it('returns model configuration from the originating remote settings view and strips native picker requests from author polling', async () => {
+ let picker!: GhostModelPicker;
+ const f = fixture(null, (page, id, route) => picker.resolve(page, id, route));
+ picker = new GhostModelPicker({ getGhost: () => f.ghost, installation: () => 'installed-1',
+ target: (id, page) => page ? f.service.modelPickerTarget(page, id) : null,
+ available: async () => true });
+ cleanup.push(() => picker.cancel());
+ const { view, fetch } = await f.open();
+ const pageId = [...(f.service as unknown as { pages: Map<string, unknown> }).pages.keys()][0];
+ const selected = picker.request(f.ghost.instanceKey!, { mobilePageId: pageId });
+ const html = await (await fetch('/settings.html')).text();
+ const internal = /src="([^"]+\.js)"/.exec(html)![1].slice(0, -3);
+ const poll = await fetch(internal, { method: 'POST', body: JSON.stringify({ kind: 'poll', after: 0 }) });
+ expect((await poll.json()).modelPickers).toBeUndefined();
+ const notice = vi.mocked(f.host.send).mock.calls.find(call => call[0] === 'ghosts:model-picker:request')![1];
+ expect(notice).toMatchObject({ deviceId: 'target-b', remoteViewId: view.id, ghostId: f.ghost.instanceKey });
+ const route = { agentKind: 'codex', providerId: 'target-provider', model: 'model', effort: 'high', fastMode: true };
+ const answer = { viewId: view.id, requestId: notice.requestId, route };
+ await expect(answerRemotePluginSettingsModelPicker({} as WebContents, answer)).rejects.toThrow();
+ expect(await answerRemotePluginSettingsModelPicker(f.host, answer)).toEqual({ handled: true, accepted: true });
+ expect(await selected).toEqual({ ok: true, route });
+ expect(f.host.send).toHaveBeenCalledWith('ghosts:model-picker:dismissed', { requestId: notice.requestId }, expect.anything());
+ });
+
it('returns a trusted directory selection to the target picker through the sealed page', async () => {
const f = fixture(),
{ view, fetch } = await f.open();
diff --git a/apps/desktop/src/main/cindy-brain/forgeGuide.ts b/apps/desktop/src/main/cindy-brain/forgeGuide.ts
index c5b55795be..edaa7f35b0 100644
--- a/apps/desktop/src/main/cindy-brain/forgeGuide.ts
+++ b/apps/desktop/src/main/cindy-brain/forgeGuide.ts
@@ -2,6 +2,7 @@
* Raw imports embed the same shipped Markdown in dev, tests and packaged builds.
*/
import overview from '../../../resources/system-skills/cindy-plugin-creator/references/plugin-overview.md?raw';
+import sourceVerification from '../../../resources/system-skills/cindy-plugin-creator/references/plugin-source-verification.md?raw';
import routineEvents from '../../../resources/system-skills/cindy-plugin-creator/references/plugin-routine-events.md?raw';
import design from '../../../resources/system-skills/cindy-plugin-creator/references/plugin-design.md?raw';
import structure from '../../../resources/system-skills/cindy-plugin-creator/references/plugin-structure.md?raw';
@@ -41,6 +42,7 @@ import compatibility from '../../../resources/system-skills/cindy-plugin-creator
export const FORGE_GUIDE = [
overview,
+ sourceVerification,
routineEvents,
design,
structure,
diff --git a/apps/desktop/src/main/cindy-brain/ghostModelPicker.ts b/apps/desktop/src/main/cindy-brain/ghostModelPicker.ts
new file mode 100644
index 0000000000..5d793f7697
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/ghostModelPicker.ts
@@ -0,0 +1,201 @@
+import { randomUUID } from 'node:crypto';
+import {
+ connectedProvidersForAgent,
+ isModelSelectableForNewRoute,
+ type ProviderView,
+} from '@cindy/model-providers';
+import { GHOST_PICK_MIN_INTERVAL_MS, type InstalledGhost } from '../../shared/ghost.js';
+import {
+ isPluginModelPickerRoute,
+ type PluginModelPickerRequest,
+ type PluginModelPickerResult,
+} from '../../shared/pluginModelPicker.js';
+import type { PluginTaskRoute } from '../../shared/pluginTasks.js';
+
+export interface PluginModelPickerTarget {
+ id: string | number;
+ isCurrent?(): boolean;
+ send(request: PluginModelPickerRequest, cancel: () => void): boolean;
+ dismiss(requestId: string): void;
+}
+
+/** Recheck the exact route without discovery, credential claims or inference. */
+export function isPluginModelPickerRouteAvailable(
+ route: PluginTaskRoute,
+ views: ProviderView[],
+ agents: readonly string[],
+): boolean {
+ const agent = route.agentKind === 'cc' ? 'claude-code' : route.agentKind;
+ if (!agents.includes(agent)) return false;
+ const provider = connectedProvidersForAgent(views, agent).find((p) => p.id === route.providerId);
+ const model = provider?.models[agent]?.find((m) => m.id === route.model);
+ return (
+ !!provider &&
+ !!model &&
+ isModelSelectableForNewRoute(model, { userProvider: provider.source === 'user' }) &&
+ (!route.effort || model.efforts.includes(route.effort as never)) &&
+ (!route.fastMode ||
+ (model.supportsFastMode === true &&
+ (route.fastMode !== 'ultrafast' ||
+ (agent === 'codex' && model.supportsUltrafastMode === true))))
+ );
+}
+
+interface Pending {
+ request: PluginModelPickerRequest;
+ target: PluginModelPickerTarget;
+ current(): boolean;
+ finish(result: PluginModelPickerResult): void;
+}
+
+/** One Host-owned picker, bound to its originating installation, page and answering window. */
+export class GhostModelPicker {
+ private pending?: Pending;
+ private readonly lastAttempt = new Map<string, number>();
+
+ constructor(
+ private readonly deps: {
+ getGhost(id: string): InstalledGhost | null;
+ installation(id: string): string | null;
+ target(ghostId: string, mobilePageId?: string): PluginModelPickerTarget | null;
+ available(route: PluginTaskRoute): Promise<boolean>;
+ timeoutMs?: number;
+ now?(): number;
+ },
+ ) {}
+
+ async request(
+ ghostId: string,
+ raw: unknown = {},
+ isCurrent = () => true,
+ signal?: AbortSignal,
+ ): Promise<PluginModelPickerResult> {
+ const fail = (
+ errorCode: Extract<PluginModelPickerResult, { ok: false }>['errorCode'],
+ message: string,
+ ): PluginModelPickerResult => ({ ok: false, errorCode, message });
+ const ghost = this.deps.getGhost(ghostId),
+ installation = this.deps.installation(ghostId);
+ const current = () =>
+ isCurrent() &&
+ !signal?.aborted &&
+ installation !== null &&
+ this.deps.installation(ghostId) === installation &&
+ this.deps.getGhost(ghostId)?.enabled === true;
+ if (!ghost?.enabled || !current())
+ return fail('PERMISSION_DENIED', 'Plugin is no longer available');
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
+ return fail('INVALID_REQUEST', 'Invalid model picker options');
+ const options = raw as Record<string, unknown>;
+ if (
+ Object.keys(options).some((k) => !['type', 'initial', 'mobilePageId'].includes(k)) ||
+ (options.initial !== undefined && !isPluginModelPickerRoute(options.initial)) ||
+ (options.mobilePageId !== undefined &&
+ (typeof options.mobilePageId !== 'string' ||
+ !options.mobilePageId ||
+ options.mobilePageId.length > 128))
+ )
+ return fail('INVALID_REQUEST', 'Invalid model picker options');
+ if (this.pending) return fail('BUSY', 'A model picker is already open');
+ const now = this.deps.now?.() ?? Date.now(),
+ last = this.lastAttempt.get(ghostId);
+ this.lastAttempt.set(ghostId, now);
+ if (last !== undefined && now - last < GHOST_PICK_MIN_INTERVAL_MS)
+ return fail('RATE_LIMITED', 'Please wait before opening the model picker again');
+ let target: PluginModelPickerTarget | null;
+ try {
+ target = this.deps.target(ghostId, options.mobilePageId as string | undefined);
+ } catch {
+ target = null;
+ }
+ if (!target) return fail('UNAVAILABLE', 'No active Host page is available');
+ const requestCurrent = () => current() && (target.isCurrent?.() ?? true);
+ const request: PluginModelPickerRequest = {
+ requestId: randomUUID(),
+ ghostId,
+ ghostName: ghost.manifest.name,
+ ...(options.initial ? { initial: { ...(options.initial as PluginTaskRoute) } } : {}),
+ expiresAt: now + (this.deps.timeoutMs ?? 90_000),
+ };
+ return new Promise((resolve) => {
+ const cancel = () => finish(fail('CANCELLED', 'Model selection was cancelled'));
+ const timer = setTimeout(cancel, this.deps.timeoutMs ?? 90_000);
+ const finish = (result: PluginModelPickerResult) => {
+ if (this.pending?.request.requestId !== request.requestId) return;
+ this.pending = undefined;
+ clearTimeout(timer);
+ signal?.removeEventListener('abort', cancel);
+ try {
+ target.dismiss(request.requestId);
+ } catch {
+ /* The page may already have closed. */
+ }
+ resolve(result);
+ };
+ this.pending = { request, target, current: requestCurrent, finish };
+ signal?.addEventListener('abort', cancel, { once: true });
+ try {
+ if (!target.send(request, cancel))
+ finish(fail('UNAVAILABLE', 'The model picker could not be opened'));
+ else if (!requestCurrent()) cancel();
+ } catch {
+ finish(fail('UNAVAILABLE', 'The model picker could not be opened'));
+ }
+ });
+ }
+
+ async resolve(
+ senderId: string | number,
+ requestId: string,
+ route: unknown,
+ ): Promise<{ handled: boolean; accepted: boolean }> {
+ const pending = this.pending;
+ if (!pending || pending.request.requestId !== requestId || pending.target.id !== senderId)
+ return { handled: false, accepted: false };
+ if (!pending.current()) {
+ pending.finish({
+ ok: false,
+ errorCode: 'PERMISSION_DENIED',
+ message: 'Plugin or account changed',
+ });
+ return { handled: true, accepted: false };
+ }
+ if (route === null) {
+ pending.finish({
+ ok: false,
+ errorCode: 'CANCELLED',
+ message: 'Model selection was cancelled',
+ });
+ return { handled: true, accepted: true };
+ }
+ if (!isPluginModelPickerRoute(route)) return { handled: true, accepted: false };
+ const selection = { ...route };
+ let available = false;
+ try {
+ available = await this.deps.available(selection);
+ } catch {
+ /* Keep the picker open for retry. */
+ }
+ if (this.pending !== pending) return { handled: false, accepted: false };
+ if (!pending.current()) {
+ pending.finish({
+ ok: false,
+ errorCode: 'PERMISSION_DENIED',
+ message: 'Plugin or account changed',
+ });
+ return { handled: true, accepted: false };
+ }
+ if (!available) return { handled: true, accepted: false };
+ pending.finish({ ok: true, route: selection });
+ return { handled: true, accepted: true };
+ }
+
+ cancel(ghostId?: string): void {
+ if (this.pending && (ghostId === undefined || this.pending.request.ghostId === ghostId))
+ this.pending.finish({
+ ok: false,
+ errorCode: 'CANCELLED',
+ message: 'Model selection was cancelled',
+ });
+ }
+}
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 7485b33d02..9362b0c561 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -76,6 +76,8 @@ async function resolveMobilePluginMedia(instanceId: string, url: string, current
}
import { getModelVisibilityOverride, waitForModelVisibilityMirror } from '../maker-host/model-visibility-mirror.js';
import { projectGhostAgentModels } from './ghostAgentModels.js';
+import { GhostModelPicker, isPluginModelPickerRouteAvailable } from './ghostModelPicker.js';
+import { getMakerIfReady } from '../maker-host/index.js';
import { getDesktopProviderService } from '../maker-host/createDesktopProviderService.js';
import { PluginDownloadSlot } from './downloadSlot.js';
import { createDownloader } from '../downloader/index.js';
@@ -285,6 +287,7 @@ import {
setGhostKvStore,
setGhostMediaModelsProvider,
setGhostAgentModelsProvider,
+ setGhostModelPickerProvider,
setGhostOauthHandler,
setGhostSandboxDevToolsDisabled,
setGhostSecretsHandler,
@@ -1252,6 +1255,7 @@ export async function interruptGhostCallsForAccountBoundary(): Promise<void> {
getGhostSetupInteractionBridge()?.cleanupAll('session_aborted');
getGhostGrantConfirmBridge()?.cleanupAll('session_aborted');
getGhostConfirmDialogBridge()?.cancelAll();
+ modelPickerSingleton?.cancel();
getForgeOidcInstallConfirmBridge()?.cancelAll();
installConsentWindowBridge.cancelAll();
abortAllGhostInstallConsentPrompts();
@@ -2085,6 +2089,7 @@ export function getGhostRuntime(): GhostRuntime {
// 崩溃/熄灯时把该意识名下的在途工具调用收掉(结构化失败给 agent)。
getGhostPipeDispatcher().onRuntimeState(storagePart, state);
if (state !== 'running') {
+ modelPickerSingleton?.cancel(storagePart);
pluginInvocations.invalidate(storagePart);
invocationRuntimeGenerations.set(storagePart, (invocationRuntimeGenerations.get(storagePart) ?? 0) + 1);
}
@@ -3749,6 +3754,50 @@ export function getGhostConfirmSlot(): GhostConfirmSlot {
return confirmSlotSingleton;
}
+let modelPickerSingleton: GhostModelPicker | null = null;
+export function getGhostModelPicker(): GhostModelPicker {
+ return modelPickerSingleton ??= new GhostModelPicker({
+ getGhost: findGhostForInstanceId,
+ installation: ghostInstallMutationTargetFor,
+ target: (ghostId, mobilePageId) => {
+ if (mobilePageId) return mobilePluginPages?.modelPickerTarget(mobilePageId, ghostId) ?? null;
+ const focused = BrowserWindow.getFocusedWindow();
+ const win = focused && isTrustedAppRendererWindow(focused) ? focused
+ : BrowserWindow.getAllWindows().find(w => !w.isDestroyed() && isTrustedAppRendererWindow(w));
+ if (!win || win.isDestroyed()) return null;
+ const contents = win.webContents, ownerStamp = getGhostOwnerPushStamp();
+ let cleanup = () => {};
+ return {
+ id: contents.id,
+ send: (request, cancel) => {
+ if (contents.isDestroyed()) return false;
+ const navigation = (_event: unknown, _url: string, sameDocument: boolean, mainFrame: boolean) => {
+ if (mainFrame && !sameDocument) cancel();
+ };
+ contents.once('destroyed', cancel);
+ contents.once('render-process-gone', cancel);
+ contents.on('did-start-navigation', navigation);
+ cleanup = () => {
+ contents.removeListener('destroyed', cancel);
+ contents.removeListener('render-process-gone', cancel);
+ contents.removeListener('did-start-navigation', navigation);
+ };
+ sendGhostContentsPush(contents, 'ghosts:model-picker:request', request, ownerStamp);
+ return true;
+ },
+ dismiss: (requestId) => {
+ cleanup();
+ if (!contents.isDestroyed()) sendGhostContentsPush(contents, 'ghosts:model-picker:dismissed', { requestId }, ownerStamp);
+ },
+ };
+ },
+ available: async route => {
+ const views = await getDesktopProviderService({ allowSideEffects: false }).listProviders({ allowSideEffects: false, snapshotOnly: true });
+ return isPluginModelPickerRouteAvailable(route, views, getMakerIfReady()?.listAvailableAgents() ?? []);
+ },
+ });
+}
+
let pickSlotSingleton: GhostPickSlot | null = null;
/**
@@ -7988,6 +8037,7 @@ async function setGhostEnabledForUser(id: string, enabled: boolean, expectedInst
const releaseSync = pluginDeviceSync.beginMutation(storagePart);
try {
if (!enabled) {
+ modelPickerSingleton?.cancel(storagePart);
runtime.stop(storagePart); // 沉睡立即熄灯
getGhostNodeRuntimeBroker().stop(storagePart); // 随包 Node 也立即关闭
getGhostSubscriptionGateway().dropGhost(storagePart); // 订阅态清零(缓冲/熔断/seq)
@@ -8195,6 +8245,7 @@ export function registerGhostIpc(): void {
installFile: installRemoteGhostFile,
});
mobilePluginPages = new MobilePluginPages({
+ answerModelPicker: (pageId, requestId, route) => getGhostModelPicker().resolve(pageId, requestId, route),
management: remotePluginManagement,
list: availableGhosts,
listOrder: () => {
@@ -8274,6 +8325,7 @@ export function registerGhostIpc(): void {
ipcMain.handle(LEGACY_GHOST_RECOVERY_RETRY_CHANNEL, legacyRecoveryIpc.retry);
setGhostSandboxDevToolsDisabled(app.isPackaged);
setGhostAppContextProvider(currentGhostAppContext);
+ setGhostModelPickerProvider((id, options, current, signal) => getGhostModelPicker().request(id, options, current, signal));
setGhostMediaModelsProvider(getGhostConfigurableMediaModels);
setGhostAgentModelsProvider(async (instanceId) => {
const owner = activeOwnerScopeKey();
@@ -8979,9 +9031,23 @@ export function registerGhostIpc(): void {
if (type === 'confirm-request') {
return getGhostConfirmSlot().handleRequest(id, payload);
}
+ if (type === 'model-picker-request') {
+ const target = ghostInstallMutationTargetFor(id);
+ return getGhostModelPicker().request(id, payload, () =>
+ !event.sender.isDestroyed() && ghostIdForLogicWebContents(event.sender.id) === id &&
+ target !== null && ghostInstallMutationTargetFor(id) === target);
+ }
throwIpcError('INVALID_PARAMS', '未知的管子消息类型');
});
+ ipcMain.handle('ghosts:model-picker:resolve', async (event, raw: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const p = raw as { requestId?: unknown; route?: unknown } | null;
+ if (!p || typeof p.requestId !== 'string' || !p.requestId || p.requestId.length > 128)
+ throwIpcError('INVALID_PARAMS', 'Invalid model picker response');
+ return getGhostModelPicker().resolve(event.sender.id, p.requestId, p.route);
+ });
+
// ── 确认弹窗回包(confirm 槽)────────────────────────────────────────
// renderer 上的确认框被用户点掉之后,把答案送回 main 结算那条挂起的管子请求。
// 不校验 sender 归属:requestId 是 main 自己铸的 randomUUID,只在本机 renderer
diff --git a/apps/desktop/src/main/cindy-brain/mobilePageService.ts b/apps/desktop/src/main/cindy-brain/mobilePageService.ts
index 9f1f1d97ef..89c336d755 100644
--- a/apps/desktop/src/main/cindy-brain/mobilePageService.ts
+++ b/apps/desktop/src/main/cindy-brain/mobilePageService.ts
@@ -25,6 +25,7 @@ import { t } from '../i18n.js';
import { mobilePluginUsage } from './mobilePluginUsage.js';
import { mobilePluginConfiguration } from './mobilePluginConfiguration.js';
import type { GhostConfirmShowParams } from './confirmSlot.js';
+import type { PluginModelPickerTarget } from './ghostModelPicker.js';
import {
RemoteResourceRegistryError,
type RemoteResourceProvider,
@@ -66,6 +67,7 @@ interface Page {
answering: boolean;
};
directoryAnswers?: Map<string, string>;
+ modelPicker?: { value: NonNullable<PluginPagePoll['modelPickers']>[number]; cancel(): void };
intents?: import('@cindy/device-link').PluginNativeIntent[];
previews?: Map<string, MobilePluginPreview>;
}
@@ -114,6 +116,7 @@ interface Dependencies {
): Promise<import('@cindy/device-link').PluginTaskPreferences>;
};
now?(): number;
+ answerModelPicker?(pageId: string, requestId: string, route: unknown): Promise<{ handled: boolean; accepted: boolean }>;
}
const fail = (message = 'Plugin page is no longer available'): never => {
throw new RemoteResourceRegistryError('NOT_FOUND', message);
@@ -172,6 +175,7 @@ export class MobilePluginPages {
for (const id of page.documentSources ?? []) this.documentSources.delete(id);
for (const id of page.authorizations?.keys() ?? []) notifyOauthCardClosed(id);
this.cancelDirectory(page);
+ page.modelPicker?.cancel();
page.previews?.clear();
for (const pending of page.confirms.values()) {
clearTimeout(pending.timer);
@@ -300,6 +304,7 @@ export class MobilePluginPages {
(page.documentSources ??= new Set()).add(page.documentId);
this.documentSources.set(page.documentId, page);
this.cancelDirectory(page);
+ page.modelPicker?.cancel();
for (const pending of page.confirms.values()) {
clearTimeout(pending.timer);
pending.answer(false);
@@ -341,6 +346,7 @@ export class MobilePluginPages {
confirms: sameDocument ? [...page.confirms.values()].map((p) => p.value) : [],
notifications: page.notices.splice(0),
directories: sameDocument && page.directory ? [page.directory.value] : [],
+ modelPickers: sameDocument && page.modelPicker ? [page.modelPicker.value] : [],
});
}
case 'confirm': {
@@ -351,6 +357,10 @@ export class MobilePluginPages {
pending.answer(command.accepted);
return {};
}
+ case 'answer-model-picker': {
+ if (!page.modelPicker || command.requestId !== page.modelPicker.value.requestId || !this.deps.answerModelPicker) return fail();
+ return done(await this.deps.answerModelPicker(page.id, command.requestId, command.route));
+ }
case 'answer-directory':
await this.answerDirectory(page, command);
return done({});
@@ -598,6 +608,29 @@ export class MobilePluginPages {
});
});
}
+ modelPickerTarget(pageId: string, pluginId: string): PluginModelPickerTarget | null {
+ const page = this.source(pageId);
+ if (!page || !page.active || page.sourceHidden || page.plugin !== pluginId) return null;
+ this.check(page);
+ return {
+ id: page.id,
+ isCurrent: () => {
+ try {
+ this.check(page);
+ return this.source(pageId) === page && page.active && !page.sourceHidden;
+ } catch { return false; }
+ },
+ send: (value, cancel) => {
+ this.check(page);
+ if (this.source(pageId) !== page || !page.active || page.sourceHidden || page.modelPicker) return false;
+ page.modelPicker = { value, cancel };
+ return true;
+ },
+ dismiss: requestId => {
+ if (page.modelPicker?.value.requestId === requestId) page.modelPicker = undefined;
+ },
+ };
+ }
private item(
ghost: InstalledGhost,
order?: RemoteCollectionItem['pluginOrder'],
@@ -1002,6 +1035,7 @@ export class MobilePluginPages {
// Suspension removes native intents; their cover must not survive resume.
page.sourceHidden = false;
this.cancelDirectory(page);
+ page.modelPicker?.cancel();
page.intents = [];
page.previews?.clear();
for (const pending of page.confirms.values()) {
@@ -1056,6 +1090,7 @@ export class MobilePluginPages {
notifications: page.notices.splice(0),
unreadAt: page.unreadAt,
directories: page.directory ? [page.directory.value] : [],
+ modelPickers: page.modelPicker ? [page.modelPicker.value] : [],
intents: page.intents ?? [],
};
return { effects: [], result };
@@ -1064,6 +1099,7 @@ export class MobilePluginPages {
if (typeof input.hidden !== 'boolean' || !page.active) return fail();
page.sourceHidden = input.hidden;
if (input.hidden) {
+ page.modelPicker?.cancel();
for (const pending of page.confirms.values()) {
clearTimeout(pending.timer);
pending.answer(false);
@@ -1113,6 +1149,13 @@ export class MobilePluginPages {
page.previews?.delete(input.intentId);
return { effects: [] };
}
+ case 'answer-model-picker': {
+ if (!page.active || page.sourceHidden || !page.modelPicker ||
+ input.requestId !== page.modelPicker.value.requestId || !this.deps.answerModelPicker) return fail();
+ const result = await this.deps.answerModelPicker(page.id, page.modelPicker.value.requestId, input.route);
+ this.check(page);
+ return { effects: [], result };
+ }
case 'answer-directory':
await this.answerDirectory(page, input);
return { effects: [] };
diff --git a/apps/desktop/src/main/cindy-brain/remotePluginSettingsController.ts b/apps/desktop/src/main/cindy-brain/remotePluginSettingsController.ts
index 1bde33a367..85368b0dd3 100644
--- a/apps/desktop/src/main/cindy-brain/remotePluginSettingsController.ts
+++ b/apps/desktop/src/main/cindy-brain/remotePluginSettingsController.ts
@@ -103,6 +103,7 @@ interface View {
attach(guest: WebContents): void;
close(): void;
answerDirectory(requestId: string, path: string | null): Promise<void>;
+ answerModelPicker(requestId: string, route: import('@cindy/device-link').PluginModelSelection | null): Promise<unknown>;
}
const views = new Map<string, View>();
@@ -144,6 +145,19 @@ export async function answerRemotePluginSettingsDirectory(
await view.answerDirectory(answer.requestId, answer.path);
}
+export async function answerRemotePluginSettingsModelPicker(host: WebContents, raw: unknown): Promise<unknown> {
+ const answer = raw as { viewId?: unknown; requestId?: unknown; route?: unknown } | null;
+ if (!answer || typeof answer.viewId !== 'string') throw unavailable();
+ const parsed = parsePluginSettingsRequest({ op: 'settings', id: 'local', command: {
+ kind: 'answer-model-picker', requestId: answer.requestId, route: answer.route,
+ } });
+ if (!parsed || parsed.command.kind !== 'answer-model-picker') throw unavailable();
+ const view = [...views.values()].find(v => v.id === answer.viewId && v.host === host);
+ if (!view) throw unavailable();
+ view.current();
+ return view.answerModelPicker(parsed.command.requestId, parsed.command.route);
+}
+
/** Main owns the encrypted exchange and the isolated page session. No values enter the app Renderer. */
export async function openRemotePluginSettings(
host: WebContents,
@@ -238,6 +252,11 @@ export async function openRemotePluginSettings(
const ses = session.fromPartition(partition);
let guest: WebContents | undefined;
const confirmations = new Set<string>();
+ const modelPickers = new Set<string>();
+ const dismissModelPicker = (requestId: string) => {
+ modelPickers.delete(requestId);
+ if (!host.isDestroyed()) host.send('ghosts:model-picker:dismissed', { requestId }, getSafeDataOwnerPushStamp());
+ };
const prompt = (options: MessageBoxOptions) => {
assertCurrent();
const parent = BrowserWindow.fromWebContents(host);
@@ -270,6 +289,15 @@ export async function openRemotePluginSettings(
const poll = async (after: number) => {
const result = (await send({ kind: 'poll', after })) as PluginPagePoll;
for (const item of result.confirms) void confirm(item);
+ for (const requestId of modelPickers) {
+ if (!result.modelPickers?.some(value => value.requestId === requestId)) dismissModelPicker(requestId);
+ }
+ for (const request of result.modelPickers ?? []) {
+ assertCurrent();
+ if (modelPickers.has(request.requestId)) continue;
+ modelPickers.add(request.requestId);
+ host.send('ghosts:model-picker:request', { ...request, deviceId: input.deviceId, remoteViewId: id }, getSafeDataOwnerPushStamp());
+ }
for (const request of result.directories ?? []) {
assertCurrent();
host.send(
@@ -286,7 +314,7 @@ export async function openRemotePluginSettings(
getSafeDataOwnerPushStamp(),
);
}
- return { ...result, directories: undefined };
+ return { ...result, directories: undefined, modelPickers: undefined };
};
const fetchSettings = async (
path: string,
@@ -431,10 +459,17 @@ export async function openRemotePluginSettings(
answerDirectory: async (requestId, path) => {
await send({ kind: 'answer-directory', requestId, path });
},
+ answerModelPicker: async (requestId, route) => {
+ if (!modelPickers.has(requestId)) throw unavailable();
+ const result = await send({ kind: 'answer-model-picker', requestId, route }) as { handled: boolean; accepted: boolean };
+ if (result.accepted || !result.handled) dismissModelPicker(requestId);
+ return result;
+ },
close: () => {
if (closed) return;
void send({ kind: 'close' }).catch(() => {});
closed = true;
+ for (const requestId of [...modelPickers]) dismissModelPicker(requestId);
clearInterval(keepAlive);
clearTimeout(attachDeadline);
views.delete(partition);
diff --git a/apps/desktop/src/main/cindy-brain/runtime/__tests__/electronSandboxAdapter.ownerPartition.test.ts b/apps/desktop/src/main/cindy-brain/runtime/__tests__/electronSandboxAdapter.ownerPartition.test.ts
index a4dd4456cd..7ebfc8c8a9 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/__tests__/electronSandboxAdapter.ownerPartition.test.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/__tests__/electronSandboxAdapter.ownerPartition.test.ts
@@ -127,6 +127,7 @@ import {
revokeLegacyGhostProtocolPartition,
setGhostAppContextProvider,
setGhostAgentModelsProvider,
+ setGhostModelPickerProvider,
setGhostKvStore,
setGhostConnectionsHandler,
setGhostOauthHandler,
@@ -797,6 +798,48 @@ describe('electronSandboxAdapter owner partition', () => {
});
});
+describe('Host model picker endpoint', () => {
+ beforeEach(() => {
+ kvEndpoint.readBoundedBodyText.mockImplementation((request: Request) => request.text());
+ });
+ // New interactive route: catalog tests cover GET only. Minimal POST must use the
+ // physical plugin identity; author-supplied remote origins must be rejected. Tier: unit.
+ it('opens only from a same-instance POST and returns a credential-free selection', async () => {
+ const route = { agentKind: 'codex', providerId: 'provider', model: 'model', effort: '', fastMode: false };
+ const provider = vi.fn().mockResolvedValue({ ok: true, route });
+ setGhostModelPickerProvider(provider);
+ ensureGhostProtocolRegistered(ghost('model-picker'));
+ const handler = harness.sessions.get(approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:model-picker'))!.protocolHandler!;
+ for (const [url, method, body, status] of [
+ ['model-picker/model-picker', 'GET', undefined, 405],
+ ['other/model-picker', 'POST', '{}', 403],
+ ['model-picker/model-picker?owner=b', 'POST', '{}', 400],
+ ['model-picker/model-picker', 'POST', '{"mobilePageId":"other"}', 400],
+ ['model-picker/model-picker', 'POST', '{', 400],
+ ] as const) {
+ const result = await handler(new Request('cindy-ghost://' + url, { method, body }));
+ expect(result.status).toBe(status);
+ }
+ expect(provider).not.toHaveBeenCalled();
+ const result = await handler(new Request('cindy-ghost://model-picker/model-picker', { method: 'POST', body: '{}' }));
+ expect(await result.json()).toEqual({ ok: true, route });
+ expect(result.headers.get('cache-control')).toBe('no-store');
+ expect(provider.mock.calls[0][0]).toBe('model-picker');
+ });
+
+ it('withholds an interactive result when the originating installation changes while the picker is open', async () => {
+ let finish!: (value: import('../../../../shared/pluginModelPicker').PluginModelPickerResult) => void;
+ setGhostModelPickerProvider(() => new Promise(resolve => { finish = resolve; }));
+ ensureGhostProtocolRegistered(ghost('model-picker-owner'));
+ const handler = harness.sessions.get(approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:model-picker-owner'))!.protocolHandler!;
+ const pending = handler(new Request('cindy-ghost://model-picker-owner/model-picker', { method: 'POST', body: '{}' }));
+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'));
+ harness.activeOwner = { mode: 'cloud', dataOwnerId: 'owner-b', generation: 2 };
+ finish({ ok: true, route: { agentKind: 'codex', providerId: 'provider', model: 'model', effort: '', fastMode: false } });
+ expect((await pending).status).toBe(403);
+ });
+});
+
describe('read-only agent model directory', () => {
it('identifies the organization instance when a root plugin has the same id', async () => {
const provider = vi.fn().mockResolvedValue({ ok: true, models: [] });
diff --git a/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts b/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts
index ce205f9441..4a4861d09a 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts
@@ -270,6 +270,10 @@ export function setGhostMediaModelsProvider(
}
let ghostAgentModelsProvider: ((ghostId: string) => Promise<GhostAgentModelsResult>) | null = null;
+let ghostModelPickerProvider: ((id: string, options: unknown, current: () => boolean, signal: AbortSignal) => Promise<import('../../../shared/pluginModelPicker.js').PluginModelPickerResult>) | null = null;
+export function setGhostModelPickerProvider(provider: NonNullable<typeof ghostModelPickerProvider>): void {
+ ghostModelPickerProvider = provider;
+}
export function setGhostAgentModelsProvider(
provider: (ghostId: string) => Promise<GhostAgentModelsResult>,
): void {
@@ -570,6 +574,24 @@ function registerGhostProtocol(
},
});
}
+ if (url.pathname === '/model-picker') {
+ const headers = { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' };
+ if (request.method !== 'POST') return new Response(null, { status: 405, headers });
+ if (url.search) return new Response(null, { status: 400, headers });
+ if (!ghostModelPickerProvider) return new Response(null, { status: 503, headers });
+ let options: unknown;
+ try {
+ const body = await readBoundedBodyText(request);
+ if (body.length > 4096) return new Response(null, { status: 400, headers });
+ options = JSON.parse(body || '{}');
+ } catch { return new Response(null, { status: 400, headers }); }
+ // Page authors cannot choose a different phone or impersonate a logic request.
+ if (!options || typeof options !== 'object' || Array.isArray(options) ||
+ Object.keys(options).some(key => key !== 'initial')) return new Response(null, { status: 400, headers });
+ const result = await ghostModelPickerProvider(storagePart, options, isRegistrationCurrent, request.signal);
+ if (!isRegistrationCurrent()) return new Response(null, { status: 403, headers });
+ return new Response(JSON.stringify(result), { status: 200, headers });
+ }
if (url.pathname === '/agent-models') {
const headers = { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' };
if (request.method !== 'GET') return new Response(null, { status: 405, headers });
diff --git a/apps/desktop/src/main/device-link/ipc.ts b/apps/desktop/src/main/device-link/ipc.ts
index e593496acc..74f50eca27 100644
--- a/apps/desktop/src/main/device-link/ipc.ts
+++ b/apps/desktop/src/main/device-link/ipc.ts
@@ -8,8 +8,8 @@
import { promises as pluginFileFs } from 'node:fs';
import { PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES } from '@cindy/plugin-protocol';
import { capturePluginOauthPeer } from '../plugin-oauth/runtime.js';
-import { openRemotePluginSettings, closeRemotePluginSettings, answerRemotePluginSettingsDirectory } from '../cindy-brain/remotePluginSettingsController.js';
-import { REMOTE_PLUGIN_SETTINGS_OPEN, REMOTE_PLUGIN_SETTINGS_CLOSE, REMOTE_PLUGIN_SETTINGS_DIRECTORY_ANSWER } from '../../shared/remotePluginSettings.js';
+import { openRemotePluginSettings, closeRemotePluginSettings, answerRemotePluginSettingsDirectory, answerRemotePluginSettingsModelPicker } from '../cindy-brain/remotePluginSettingsController.js';
+import { REMOTE_PLUGIN_SETTINGS_OPEN, REMOTE_PLUGIN_SETTINGS_CLOSE, REMOTE_PLUGIN_SETTINGS_DIRECTORY_ANSWER, REMOTE_PLUGIN_SETTINGS_MODEL_ANSWER } from '../../shared/remotePluginSettings.js';
import {
decodeModelSpeedPayload,
REMOTE_RESOURCE_MANIFEST_CHANNEL,
@@ -1600,6 +1600,11 @@ export function registerDeviceLinkIpc(deps: DeviceLinkIpcDeps = defaultDeps()):
try { await answerRemotePluginSettingsDirectory(event.sender, raw); }
catch { throwIpcError('PRECONDITION_FAILED', 'Remote plugin directory request unavailable'); }
});
+ ipcMain.handle(REMOTE_PLUGIN_SETTINGS_MODEL_ANSWER, async (event, raw: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ try { return await answerRemotePluginSettingsModelPicker(event.sender, raw); }
+ catch { throwIpcError('PRECONDITION_FAILED', 'Remote plugin model picker unavailable'); }
+ });
const authorizationHandler = (mode: 'oauth' | 'secret' | 'connection' | 'input') => async (event: import('electron').IpcMainInvokeEvent, raw: unknown) => {
assertTrustedAppRendererEvent(event);
requireDeviceLinkCapability();
diff --git a/apps/desktop/src/main/maker-host/built-in-skills.ts b/apps/desktop/src/main/maker-host/built-in-skills.ts
index 4846e265ad..e407ccfdd5 100644
--- a/apps/desktop/src/main/maker-host/built-in-skills.ts
+++ b/apps/desktop/src/main/maker-host/built-in-skills.ts
@@ -25,7 +25,7 @@ const VERSIONS_DIRECTORY = '.versions';
const ACTIVE_BUNDLE_LINK = '.active';
const BUILT_IN_SKILL_MUTATION_WAIT_MS = 5_000;
/** Increment whenever shipped built-in Skill bytes change between releases. */
-export const BUILT_IN_SKILLS_BUNDLE_VERSION = 22;
+export const BUILT_IN_SKILLS_BUNDLE_VERSION = 23;
const PLUGIN_CREATOR_FIRST_BUNDLE_VERSION = 13;
export interface BuiltInSkillDescriptor {
diff --git a/apps/desktop/src/preload/ghostPreload.ts b/apps/desktop/src/preload/ghostPreload.ts
index d9e4e9bfd8..847830b453 100644
--- a/apps/desktop/src/preload/ghostPreload.ts
+++ b/apps/desktop/src/preload/ghostPreload.ts
@@ -1,4 +1,5 @@
import { contextBridge, ipcRenderer } from 'electron';
+import type { PluginModelPickerOptions, PluginModelPickerResult } from '../shared/pluginModelPicker';
/**
* 意识电子脑的最小管子桥(脑机接口;docs/dev-rules/plugin-security-and-authoring.md)。
@@ -120,6 +121,8 @@ contextBridge.exposeInMainWorld('cindy', {
},
pick: (req: Record<string, unknown>): Promise<unknown> =>
ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'pick-request' }),
+ pickModel: (req: PluginModelPickerOptions = {}): Promise<PluginModelPickerResult> =>
+ ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'model-picker-request' }),
preview: (req: Record<string, unknown>): Promise<unknown> =>
ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'preview-request' }),
// 在任务右侧栏打开 / 聚焦本插件的任务页(taskView);缺省落台前任务,回执带回落点任务。
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 58b6d367b3..31412043b9 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -756,6 +756,8 @@ const fanOutGhostUnreadSnapshot = createIpcFanOut('ghosts:unread-snapshot');
// 意识确认弹窗(confirm 槽:renderer 用主机同款 ConfirmDialog 弹,答案回 main)。
// main 只投单个窗口(不广播),所以这里落地的窗口就是该弹框的唯一归属。
const fanOutGhostConfirmRequest = createIpcFanOut('ghosts:confirm-request');
+const fanOutGhostModelPickerRequest = createIpcFanOut('ghosts:model-picker:request');
+const fanOutGhostModelPickerDismissed = createIpcFanOut('ghosts:model-picker:dismissed');
const fanOutForgeOidcInstallConfirmRequest = createIpcFanOut('forge-oidc-install:confirm-request');
// 插件安装/更新确认(main 只投给发起安装的那个窗口;超时或取消时再发 dismissed 收起)。
const fanOutGhostInstallConsentRequest = createIpcFanOut('ghosts:install-consent:request');
@@ -1510,6 +1512,12 @@ contextBridge.exposeInMainWorld('electronAPI', {
onBadge: fanOutGhostBadge,
onUnreadSnapshot: fanOutGhostUnreadSnapshot,
onConfirmRequest: fanOutGhostConfirmRequest,
+ onModelPickerRequest: fanOutGhostModelPickerRequest,
+ onModelPickerDismissed: fanOutGhostModelPickerDismissed,
+ answerRemoteModelPicker: (viewId: string, requestId: string, route: import('../shared/pluginTasks').PluginTaskRoute | null) =>
+ ipcRenderer.invoke('device-link:plugin-settings:answer-model-picker', { viewId, requestId, route }),
+ resolveModelPicker: (requestId: string, route: import('../shared/pluginTasks').PluginTaskRoute | null) =>
+ ipcRenderer.invoke('ghosts:model-picker:resolve', { requestId, route }),
// 确认弹窗回包(confirm 槽):renderer 把用户的点击送回 main 结算那条挂起的
// 管子请求。requestId 是 main 铸的,陌生/重复 id 由桥忽略。
resolveConfirm: (requestId: string, confirmed: boolean): Promise<{ handled: boolean }> =>
diff --git a/apps/desktop/src/renderer/App.tsx b/apps/desktop/src/renderer/App.tsx
index 27260f0466..37251b2232 100644
--- a/apps/desktop/src/renderer/App.tsx
+++ b/apps/desktop/src/renderer/App.tsx
@@ -33,6 +33,7 @@ import { ConfirmDialogProvider } from '@/components/ui/confirm-dialog-provider';
import { FindInPageBar } from '@/components/find-in-page/FindInPageBar';
import { ProjectAutomationNotifyBridge } from '@/features/scheduler/components/ProjectAutomationNotifyBridge';
import { GhostConfirmDialogHost } from '@/cindy-brain/GhostConfirmDialogHost';
+import { PluginModelPickerHost } from '@/cindy-brain/PluginModelPickerHost';
import { LocalAgentConfirmationHost } from '@/components/LocalAgentConfirmationHost';
import { ForgeOidcInstallConfirmHost } from '@/cindy-brain/ForgeOidcInstallConfirmHost';
import { GhostInstallConsentHost } from '@/cindy-brain/GhostInstallConsentHost';
@@ -463,6 +464,7 @@ export function App() {
内(要 useConfirmDialog);main 只投单个窗口,所以每个窗口
都挂、谁收到谁弹,不按窗口类型 gate。 */}
<GhostConfirmDialogHost />
+ <PluginModelPickerHost />
<LocalAgentConfirmationHost />
<ForgeOidcInstallConfirmHost />
<GhostInstallConsentHost />
diff --git a/apps/desktop/src/renderer/cindy-brain/PluginModelPickerHost.tsx b/apps/desktop/src/renderer/cindy-brain/PluginModelPickerHost.tsx
new file mode 100644
index 0000000000..b266036634
--- /dev/null
+++ b/apps/desktop/src/renderer/cindy-brain/PluginModelPickerHost.tsx
@@ -0,0 +1,151 @@
+import { useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { ConfirmDialog } from '@/components/ui/confirm-dialog';
+import { ErrorNotice } from '@/components/ui/error-notice';
+import { ModelSelectorContent } from '@/components/new-chat/ModelSelector';
+import { useModelPickerAgents } from '@/hooks/useAvailableAgents';
+import type { Effort } from '@/lib/userPreferences.types';
+import type {
+ PluginModelPickerRequest,
+ PluginModelPickerPresentation,
+} from '../../shared/pluginModelPicker';
+import type { PluginTaskRoute } from '../../shared/pluginTasks';
+
+/** Host-owned presentation: selecting and editing only changes this dialog's draft. */
+export function PluginModelPickerDialog({
+ request,
+ deviceId,
+ onAnswer,
+}: {
+ request: PluginModelPickerRequest;
+ deviceId?: string;
+ onAnswer(route: PluginTaskRoute | null): Promise<{ handled: boolean; accepted: boolean }>;
+}) {
+ const { t } = useTranslation();
+ const [route, setRoute] = useState(request.initial);
+ const agents = useModelPickerAgents(
+ route?.agentKind === 'cc' ? 'claude-code' : (route?.agentKind ?? 'codex'),
+ deviceId,
+ );
+ const [busy, setBusy] = useState(false),
+ [error, setError] = useState(false);
+ const lock = useRef(false);
+ const answer = async (value: PluginTaskRoute | null) => {
+ if (lock.current) return;
+ lock.current = true;
+ setBusy(true);
+ setError(false);
+ try {
+ const result = await onAnswer(value);
+ if (!result.handled || !result.accepted) setError(true);
+ } catch {
+ setError(true);
+ } finally {
+ lock.current = false;
+ setBusy(false);
+ }
+ };
+ return (
+ <ConfirmDialog
+ open
+ title={t('settings.ghosts.modelPicker.title', { name: request.ghostName })}
+ maxWidth={460}
+ confirmDisabled={!route}
+ loading={busy}
+ onConfirm={() => {
+ void answer(route ?? null);
+ }}
+ onCancel={() => {
+ void answer(null);
+ }}
+ onOpenChange={(open) => {
+ if (!open && !lock.current) void answer(null);
+ }}
+ content={
+ <>
+ <ModelSelectorContent
+ deviceId={deviceId}
+ modelId={route?.model ?? ''}
+ currentProviderId={route?.providerId ?? null}
+ vendorKey={route?.agentKind}
+ effort={(route?.effort ?? '') as Effort}
+ fastMode={route?.fastMode ?? false}
+ unifiedAgents={agents}
+ overlayContentClassName="z-[10001]"
+ onModelChange={() => false}
+ onEffortChange={(effort) => {
+ setRoute((r) => (r ? { ...r, effort } : r));
+ }}
+ onFastModeChange={(fastMode) => {
+ setRoute((r) => (r ? { ...r, fastMode } : r));
+ }}
+ onUnifiedSelect={({ providerId, modelId, engine, effort, fast }) => {
+ setRoute({
+ providerId,
+ model: modelId,
+ agentKind: engine,
+ effort: effort ?? '',
+ fastMode: fast,
+ });
+ setError(false);
+ return true;
+ }}
+ />
+ {error && (
+ <ErrorNotice className="mt-3" message={t('settings.ghosts.modelPicker.unavailable')} />
+ )}
+ </>
+ }
+ />
+ );
+}
+
+export function PluginModelPickerHost() {
+ const [request, setRequest] = useState<PluginModelPickerPresentation>();
+ const active = useRef<PluginModelPickerPresentation | undefined>(undefined);
+ const dismissed = useRef(new Set<string>());
+ useEffect(() => {
+ const api = window.electronAPI.ghosts;
+ const off = api.onModelPickerRequest?.((next) => {
+ if (dismissed.current.has(next.requestId)) return;
+ if (active.current) {
+ if (active.current.requestId !== next.requestId) {
+ const answer = next.remoteViewId
+ ? api.answerRemoteModelPicker(next.remoteViewId, next.requestId, null)
+ : api.resolveModelPicker(next.requestId, null);
+ void answer.catch(() => {});
+ }
+ return;
+ }
+ active.current = next;
+ setRequest(next);
+ });
+ const dismiss = api.onModelPickerDismissed?.(({ requestId }) => {
+ dismissed.current.add(requestId);
+ if (dismissed.current.size > 64)
+ dismissed.current.delete(dismissed.current.values().next().value!);
+ if (active.current?.requestId === requestId) active.current = undefined;
+ setRequest((value) => (value?.requestId === requestId ? undefined : value));
+ });
+ return () => {
+ off?.();
+ dismiss?.();
+ };
+ }, []);
+ return request ? (
+ <PluginModelPickerDialog
+ key={request.requestId}
+ request={request}
+ deviceId={request.deviceId}
+ onAnswer={(route) =>
+ request.remoteViewId
+ ? window.electronAPI.ghosts.answerRemoteModelPicker(
+ request.remoteViewId,
+ request.requestId,
+ route,
+ )
+ : window.electronAPI.ghosts.resolveModelPicker(request.requestId, route)
+ }
+ />
+ ) : null;
+}
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/PluginModelPickerHost.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/PluginModelPickerHost.test.tsx
new file mode 100644
index 0000000000..f46d845eef
--- /dev/null
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/PluginModelPickerHost.test.tsx
@@ -0,0 +1,150 @@
+// @vitest-environment jsdom
+/** Test value: mounts the real Host and shared confirmation dialog. Existing picker tests do not
+ * cover the plugin IPC round trip. Minimal inputs: choose/confirm, cancel, rejected source,
+ * Host dismissal and a remote view. Protects plugin-security §3 and DESIGN §4; tier: unit.
+ * Standalone wall time: 2.18s (2026-10-28). */
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import type { ComponentProps } from 'react';
+import { PluginModelPickerHost } from '../PluginModelPickerHost';
+import type { PluginModelPickerPresentation } from '../../../shared/pluginModelPicker';
+import zh from '../../i18n/locales/zh-CN/common.json';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: { name?: string }) => {
+ const value = key
+ .split('.')
+ .reduce<unknown>((v, part) => (v as Record<string, unknown>)?.[part], zh);
+ return typeof value === 'string' ? value.replace('{{name}}', options?.name ?? '') : key;
+ },
+ }),
+}));
+vi.mock('@/hooks/useAvailableAgents', () => ({ useModelPickerAgents: () => ['codex'] }));
+vi.mock('@/components/new-chat/ModelSelector', () => ({
+ ModelSelectorContent: (
+ props: ComponentProps<
+ typeof import('@/components/new-chat/ModelSelector').ModelSelectorContent
+ >,
+ ) => (
+ <button
+ onClick={() =>
+ props.onUnifiedSelect?.({
+ providerId: 'chosen-provider',
+ modelId: 'chosen-model',
+ engine: 'codex',
+ effort: 'high',
+ fast: 'ultrafast',
+ favoriteUid: null,
+ })
+ }
+ >
+ Choose model
+ </button>
+ ),
+}));
+let push: (request: PluginModelPickerPresentation) => void;
+let dismiss: (request: { requestId: string }) => void;
+const resolve = vi.fn(),
+ remote = vi.fn();
+const request = {
+ requestId: 'request',
+ ghostId: 'example',
+ ghostName: '示例插件',
+ expiresAt: Date.now() + 90_000,
+};
+beforeEach(() => {
+ resolve.mockReset().mockResolvedValue({ handled: true, accepted: true });
+ remote.mockReset().mockResolvedValue({ handled: true, accepted: true });
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ ghosts: {
+ onModelPickerRequest: (cb: typeof push) => {
+ push = cb;
+ return () => {};
+ },
+ onModelPickerDismissed: (cb: typeof dismiss) => {
+ dismiss = cb;
+ return () => {};
+ },
+ resolveModelPicker: resolve,
+ answerRemoteModelPicker: remote,
+ },
+ },
+ });
+});
+afterEach(cleanup);
+
+it('keeps the full configuration as a draft until the user confirms, then returns it to Host', async () => {
+ render(<PluginModelPickerHost />);
+ act(() => push(request));
+ expect(screen.getByText('为插件「示例插件」选择模型')).toBeTruthy();
+ fireEvent.click(screen.getByText('Choose model'));
+ expect(resolve).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: zh.commonUi.confirmDialog.confirm }));
+ await waitFor(() =>
+ expect(resolve).toHaveBeenCalledExactlyOnceWith('request', {
+ providerId: 'chosen-provider',
+ model: 'chosen-model',
+ agentKind: 'codex',
+ effort: 'high',
+ fastMode: 'ultrafast',
+ }),
+ );
+});
+
+it('returns cancellation without a model and removes the dialog on Host dismissal', async () => {
+ render(<PluginModelPickerHost />);
+ act(() => push(request));
+ fireEvent.click(screen.getByRole('button', { name: zh.commonUi.confirmDialog.cancel }));
+ await waitFor(() => expect(resolve).toHaveBeenCalledExactlyOnceWith('request', null));
+ act(() => dismiss({ requestId: 'request' }));
+ await waitFor(() => expect(screen.queryByText('为插件「示例插件」选择模型')).toBeNull());
+ // A late remote poll must not reopen a picker the Host has already settled.
+ act(() => push(request));
+ expect(screen.queryByText('为插件「示例插件」选择模型')).toBeNull();
+});
+
+it('keeps the choice editable and reports an unavailable source after Host rejects it', async () => {
+ resolve.mockResolvedValue({ handled: true, accepted: false });
+ render(<PluginModelPickerHost />);
+ act(() => push(request));
+ fireEvent.click(screen.getByText('Choose model'));
+ fireEvent.click(screen.getByRole('button', { name: zh.commonUi.confirmDialog.confirm }));
+ await screen.findByText(zh.settings.ghosts.modelPicker.unavailable);
+ expect(screen.getByText('Choose model')).toBeTruthy();
+});
+
+it('returns remote selections through the original view without calling local plugin IPC', async () => {
+ render(<PluginModelPickerHost />);
+ act(() => push({ ...request, deviceId: 'other-computer', remoteViewId: 'remote-view' }));
+ fireEvent.click(screen.getByText('Choose model'));
+ fireEvent.click(screen.getByRole('button', { name: zh.commonUi.confirmDialog.confirm }));
+ await waitFor(() =>
+ expect(remote).toHaveBeenCalledWith(
+ 'remote-view',
+ 'request',
+ expect.objectContaining({ model: 'chosen-model' }),
+ ),
+ );
+ expect(resolve).not.toHaveBeenCalled();
+});
+
+it('keeps the active picker when another execution computer asks for a selection', async () => {
+ render(<PluginModelPickerHost />);
+ act(() => push(request));
+ act(() =>
+ push({
+ ...request,
+ requestId: 'second',
+ ghostName: 'Other plugin',
+ remoteViewId: 'remote-view',
+ }),
+ );
+ await waitFor(() =>
+ expect(remote).toHaveBeenCalledExactlyOnceWith('remote-view', 'second', null),
+ );
+ expect(screen.getByText('为插件「示例插件」选择模型')).toBeTruthy();
+ expect(screen.queryByText('Other plugin')).toBeNull();
+});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index bb33eed48e..0fd9eaf9ea 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -7371,6 +7371,10 @@
"confirm": {
"dialogTitle": "Plugin “{{name}}” needs your confirmation"
},
+ "modelPicker": {
+ "title": "Choose a model for plugin “{{name}}”",
+ "unavailable": "This model configuration is unavailable. Choose again and confirm."
+ },
"workspace": {
"dialogTitle": "Choose a project folder",
"dialogMessage": "Plugin “{{name}}” is asking you to choose a project folder to create a session in the sidebar"
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 3b905bdf74..fbeb997fa6 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -7340,6 +7340,10 @@
"confirm": {
"dialogTitle": "プラグイン「{{name}}」が確認を求めています"
},
+ "modelPicker": {
+ "title": "プラグイン「{{name}}」のモデルを選択",
+ "unavailable": "このモデル設定は現在利用できません。選択し直して確定してください。"
+ },
"workspace": {
"dialogTitle": "プロジェクトフォルダを選択",
"dialogMessage": "プラグイン「{{name}}」がサイドバーにセッションを作成するため、プロジェクトフォルダの選択を求めています"
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index e16b8a1f61..0b5788bbff 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -7340,6 +7340,10 @@
"confirm": {
"dialogTitle": "플러그인 \"{{name}}\"이(가) 확인을 요청합니다"
},
+ "modelPicker": {
+ "title": "플러그인 \"{{name}}\"에 사용할 모델 선택",
+ "unavailable": "현재 이 모델 설정을 사용할 수 없습니다. 다시 선택한 후 확인해 주세요."
+ },
"workspace": {
"dialogTitle": "프로젝트 폴더 선택",
"dialogMessage": "플러그인 \"{{name}}\"이(가) 사이드바에 세션을 만들기 위해 프로젝트 폴더 선택을 요청합니다"
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 393315dc2e..69583957ae 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -7340,6 +7340,10 @@
"confirm": {
"dialogTitle": "插件「{{name}}」请你确认"
},
+ "modelPicker": {
+ "title": "为插件「{{name}}」选择模型",
+ "unavailable": "这个模型配置暂时不可用,请重新选择后确认。"
+ },
"workspace": {
"dialogTitle": "选择项目文件夹",
"dialogMessage": "插件「{{name}}」请求你选择一个项目文件夹,用于在侧边栏创建任务"
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 61ac89f055..5f69ee0ff1 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -7340,6 +7340,10 @@
"confirm": {
"dialogTitle": "插件「{{name}}」請你確認"
},
+ "modelPicker": {
+ "title": "為插件「{{name}}」選擇模型",
+ "unavailable": "這個模型設定暫時無法使用,請重新選擇後確認。"
+ },
"workspace": {
"dialogTitle": "選擇專案資料夾",
"dialogMessage": "插件「{{name}}」請求你選擇一個專案資料夾,用於在側邊欄建立任務"
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 15660353c7..51ff58a86b 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1590,6 +1590,10 @@ interface ElectronAPI {
) => () => void;
/** confirm 槽回包:把用户的点击送回 main 结算挂起的管子请求。 */
resolveConfirm: (requestId: string, confirmed: boolean) => Promise<{ handled: boolean }>;
+ onModelPickerRequest: (callback: (request: import('../shared/pluginModelPicker').PluginModelPickerPresentation) => void) => () => void;
+ onModelPickerDismissed: (callback: (request: { requestId: string }) => void) => () => void;
+ resolveModelPicker: (requestId: string, route: import('../shared/pluginTasks').PluginTaskRoute | null) => Promise<{ handled: boolean; accepted: boolean }>;
+ answerRemoteModelPicker: (viewId: string, requestId: string, route: import('../shared/pluginTasks').PluginTaskRoute | null) => Promise<{ handled: boolean; accepted: boolean }>;
/** taskView 槽:插件请求在指定任务的右侧栏打开 / 聚焦它的任务页页签(main 已资格审)。 */
onTaskViewOpen: (
callback: (payload: { instanceId: string; sessionId: string; focus?: true }) => void,
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 9ce5ac8a0c..b1c9fabaa4 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -6417,6 +6417,8 @@ export function ghostManifestToAuthorFormat(manifest: GhostManifest): Record<str
* 当前 Agent tool-call 带严格在途 callId 时复用 Agent 授权;其它调用
* 须声明 network 域名详单。凭证只按声明注入,意识永不经手。
* - pick-request:pick 槽——请主机弹系统级选文件夹窗口(用户亲选即授权)。
+ * - model-picker-request:打开宿主统一模型选择器,返回 PluginTaskRoute;无需能力声明,
+ * 不修改任何默认或执行任务。协议见 shared/pluginModelPicker.ts 与 FORGE_GUIDE §4.0.3a。
* - preview-request:preview 槽——请主机在右侧栏内置浏览器开预览标签页
* (URL 必须命中身份卡 preview.hosts 白名单)。
* - schedule-request:agent 槽 schedule 加档——请主机**打开自动化创建面板并预填**
diff --git a/apps/desktop/src/shared/pluginModelPicker.ts b/apps/desktop/src/shared/pluginModelPicker.ts
new file mode 100644
index 0000000000..a519855deb
--- /dev/null
+++ b/apps/desktop/src/shared/pluginModelPicker.ts
@@ -0,0 +1,31 @@
+import type { PluginTaskRoute } from './pluginTasks.js';
+import type { PluginModelPickerRequest } from '@cindy/device-link';
+export {
+ isPluginModelSelection as isPluginModelPickerRoute,
+ type PluginModelPickerRequest,
+} from '@cindy/device-link';
+
+export interface PluginModelPickerOptions {
+ initial?: PluginTaskRoute;
+ /** Host-issued origin; never use the most recently active phone. */
+ mobilePageId?: string;
+}
+
+export interface PluginModelPickerPresentation extends PluginModelPickerRequest {
+ deviceId?: string;
+ remoteViewId?: string;
+}
+
+export type PluginModelPickerResult =
+ | { ok: true; route: PluginTaskRoute }
+ | {
+ ok: false;
+ errorCode:
+ | 'INVALID_REQUEST'
+ | 'PERMISSION_DENIED'
+ | 'BUSY'
+ | 'RATE_LIMITED'
+ | 'CANCELLED'
+ | 'UNAVAILABLE';
+ message: string;
+ };
diff --git a/apps/desktop/src/shared/remotePluginSettings.ts b/apps/desktop/src/shared/remotePluginSettings.ts
index 66af9a9655..4b4ce20874 100644
--- a/apps/desktop/src/shared/remotePluginSettings.ts
+++ b/apps/desktop/src/shared/remotePluginSettings.ts
@@ -4,6 +4,7 @@ export const REMOTE_PLUGIN_SETTINGS_CLOSE = 'device-link:plugin-settings:close';
export const REMOTE_PLUGIN_SETTINGS_DIRECTORY = 'device-link:plugin-settings:directory';
export const REMOTE_PLUGIN_SETTINGS_DIRECTORY_ANSWER =
'device-link:plugin-settings:answer-directory';
+export const REMOTE_PLUGIN_SETTINGS_MODEL_ANSWER = 'device-link:plugin-settings:answer-model-picker';
export interface RemotePluginSettingsTarget {
deviceId: string;
diff --git a/apps/mobile/src/__tests__/pluginNativeViews.test.tsx b/apps/mobile/src/__tests__/pluginNativeViews.test.tsx
index 6c1435759e..f96ff71f36 100644
--- a/apps/mobile/src/__tests__/pluginNativeViews.test.tsx
+++ b/apps/mobile/src/__tests__/pluginNativeViews.test.tsx
@@ -11,8 +11,10 @@ import { PluginTaskPickerView as AndroidTaskPickerView } from "@/plugins/PluginT
import { pluginDetailModel } from "@/plugins/pluginDetailModel";
import { palettes } from "@/theme/tokens";
import { PluginManagementConfirmation } from "@/plugins/PluginManagementConfirmation.ios";
+import { PluginModelPicker } from '@/plugins/PluginModelPicker';
const bridge = vi.hoisted(() => ({
+ maker: { getCapabilities: async () => ({ availableModels: [], effortLevels: [], permissionModes: [] }) },
props: new Map<string, any>(),
ownerCurrent: true,
keyboardVisible: false,
@@ -151,6 +153,8 @@ vi.mock("@expo/ui/swift-ui/modifiers", () => ({
),
}));
vi.mock("react-native", () => ({
+ Platform: { OS: 'ios' },
+ Alert: { alert: vi.fn() },
PlatformColor: (name: string) => name,
Keyboard: { addListener: () => ({ remove() {} }) },
useWindowDimensions: () => ({ width: 390, height: 844, fontScale: 1 }),
@@ -264,6 +268,12 @@ vi.mock("@/auth/authOwnerGeneration", () => ({
getMobileAuthOwner: () => "owner",
isMobileAuthOwnerCurrent: () => bridge.ownerCurrent,
}));
+vi.mock('@/device-link/useDeviceProviders', () => ({ useDeviceProviders: () => ({ providers: [], ready: true }) }));
+vi.mock('@/device-link/useMobileMakerTransport', () => ({ useMobileMakerTransport: () => bridge.maker }));
+vi.mock('@/session/ModelPickerSheet', () => ({ ModelPickerSheet: (props: unknown) => {
+ bridge.props.set('plugin-model-picker', props);
+ return null;
+} }));
vi.mock("@/session/CompanionNativeContent.ios", () => ({
CompanionNativeContent: (p: any) => p.children,
}));
@@ -292,6 +302,33 @@ function mount(component: any, props: any) {
act(() => root.render(createElement(component, props))),
};
}
+// New plugin picker wrapper: native sheets call onClose after a successful onSelect.
+// Minimal input is one model click; the observable result must be one complete route,
+// never a second cancellation. Existing native view tests do not cover this round trip. Tier: unit.
+it('returns the complete Host model choice once when the native sheet closes after selecting', async () => {
+ const onAnswer = vi.fn(async () => ({ handled: true, accepted: true }));
+ mount(PluginModelPicker, { deviceId: 'execution-computer', onAnswer,
+ request: { requestId: 'pick', ghostId: 'plugin', ghostName: 'Example', expiresAt: Date.now() + 90_000 } });
+ await act(async () => {
+ const props = bridge.props.get('plugin-model-picker');
+ await props.unified.onSelect({ agent: 'codex', providerId: 'provider', modelId: 'model', effort: 'high', fast: 'ultrafast' });
+ bridge.props.get('plugin-model-picker').onClose();
+ });
+ expect(onAnswer).toHaveBeenCalledExactlyOnceWith({ agentKind: 'codex', providerId: 'provider', model: 'model', effort: 'high', fastMode: 'ultrafast' });
+});
+
+it('returns cancellation from the native picker and ignores actions after owner revocation', async () => {
+ const onAnswer = vi.fn(async () => ({ handled: true, accepted: true }));
+ mount(PluginModelPicker, { deviceId: 'execution-computer', onAnswer,
+ request: { requestId: 'pick', ghostId: 'plugin', ghostName: 'Example', expiresAt: Date.now() + 90_000 } });
+ bridge.ownerCurrent = false;
+ await act(async () => { bridge.props.get('plugin-model-picker').onClose(); });
+ expect(onAnswer).not.toHaveBeenCalled();
+ bridge.ownerCurrent = true;
+ await act(async () => { bridge.props.get('plugin-model-picker').onClose(); });
+ expect(onAnswer).toHaveBeenCalledExactlyOnceWith(null);
+});
+
const row = {
key: "mac:demo",
host: { deviceId: "mac", deviceName: "Mac" },
diff --git a/apps/mobile/src/plugins/PluginModelPicker.tsx b/apps/mobile/src/plugins/PluginModelPicker.tsx
new file mode 100644
index 0000000000..920de96cff
--- /dev/null
+++ b/apps/mobile/src/plugins/PluginModelPicker.tsx
@@ -0,0 +1,128 @@
+import { useEffect, useRef, useState } from "react";
+import { Alert, Platform } from "react-native";
+import { useTranslation } from "react-i18next";
+import type {
+ PluginModelPickerRequest,
+ PluginModelSelection,
+} from "@cindy/device-link";
+import { useDeviceProviders } from "@/device-link/useDeviceProviders";
+import { useMobileMakerTransport } from "@/device-link/useMobileMakerTransport";
+import {
+ getMobileAuthOwner,
+ isMobileAuthOwnerCurrent,
+} from "@/auth/authOwnerGeneration";
+import { ModelPickerSheet } from "@/session/ModelPickerSheet";
+import {
+ normalizeMobileAgentCapabilities,
+ type MobileAgentCapabilities,
+} from "@/session/agentCapabilities";
+
+/** Native selector reads the execution computer's catalog; no local defaults are written. */
+export function PluginModelPicker({
+ request,
+ deviceId,
+ onAnswer,
+}: {
+ request: PluginModelPickerRequest;
+ deviceId: string;
+ onAnswer(
+ route: PluginModelSelection | null,
+ ): Promise<{ handled: boolean; accepted: boolean }>;
+}) {
+ const { t } = useTranslation();
+ const providers = useDeviceProviders(deviceId),
+ maker = useMobileMakerTransport(deviceId);
+ const [capabilities, setCapabilities] =
+ useState<MobileAgentCapabilities | null>(null);
+ const [busy, setBusy] = useState(false);
+ const owner = useRef(getMobileAuthOwner()).current,
+ alive = useRef(true),
+ lock = useRef(false),
+ finished = useRef(false);
+ const current = () => alive.current && isMobileAuthOwnerCurrent(owner);
+ const agent =
+ request.initial?.agentKind === "cc"
+ ? "claude-code"
+ : (request.initial?.agentKind ?? "codex");
+ useEffect(() => {
+ alive.current = true;
+ void maker
+ .getCapabilities(agent)
+ .then((raw) => {
+ if (current()) setCapabilities(normalizeMobileAgentCapabilities(raw));
+ })
+ .catch(() => {});
+ return () => {
+ alive.current = false;
+ };
+ }, [maker, agent]);
+ const answer = async (route: PluginModelSelection | null) => {
+ if (lock.current || finished.current || !current()) return false;
+ lock.current = true;
+ setBusy(true);
+ try {
+ const result = await onAnswer(route);
+ if (result.accepted) {
+ finished.current = true;
+ return true;
+ }
+ if (current()) Alert.alert(t("plugins.modelsUnavailable"));
+ } catch {
+ if (current()) Alert.alert(t("plugins.modelsUnavailable"));
+ } finally {
+ lock.current = false;
+ if (current()) setBusy(false);
+ }
+ return false;
+ };
+ return (
+ <ModelPickerSheet
+ visible
+ title={`${request.ghostName} · ${t("models.picker.title")}`}
+ onClose={() => {
+ void answer(null);
+ }}
+ agentKind={agent}
+ providers={providers.providers}
+ providersReady={providers.ready}
+ providersUnsupported={providers.unsupported}
+ modelVisibilityOverrides={providers.modelVisibilityOverrides}
+ flatOptions={[]}
+ capabilities={capabilities}
+ activeModelId={request.initial?.model ?? ""}
+ selectedProviderId={request.initial?.providerId ?? null}
+ selectedEffort={request.initial?.effort ?? ""}
+ selectedFastMode={request.initial?.fastMode ?? false}
+ loading={providers.loading}
+ disabled={busy}
+ hidePermissionTrigger
+ activePermissionMode=""
+ permissionOptions={[]}
+ onSelectPermissionMode={() => {}}
+ onSelectFlatModel={() => {}}
+ onSelectProviderRow={() => {}}
+ keyboardAvoidingBehavior={Platform.OS === "ios" ? "padding" : "height"}
+ emptyHint={t("plugins.modelsUnavailable")}
+ unified={{
+ scope: JSON.stringify([owner.accountKey, deviceId]),
+ agents: ["claude-code", "codex", "pi"],
+ loadCapabilities: async (kind) => {
+ const result = normalizeMobileAgentCapabilities(
+ await maker.getCapabilities(kind),
+ );
+ if (!result || !current())
+ throw new Error("CAPABILITIES_UNAVAILABLE");
+ return result;
+ },
+ onSelect: (value) =>
+ answer({
+ agentKind: value.agent === "claude-code" ? "cc" : value.agent,
+ providerId: value.providerId,
+ model: value.modelId,
+ effort: value.effort ?? "",
+ fastMode: value.fast,
+ }),
+ }}
+ />
+ );
+}
diff --git a/apps/mobile/src/plugins/PluginPage.tsx b/apps/mobile/src/plugins/PluginPage.tsx
index 0eb7f85a37..c2fce39878 100644
--- a/apps/mobile/src/plugins/PluginPage.tsx
+++ b/apps/mobile/src/plugins/PluginPage.tsx
@@ -22,6 +22,7 @@ import type {
PluginDirectoryRequest,
PluginNativeIntent as NativeIntent,
PluginPageFetchResult,
+ PluginModelPickerRequest,
} from "@cindy/device-link";
import { Text } from "@/components/AppText";
import { useDeviceLink } from "@/device-link/DeviceLinkContext";
@@ -42,6 +43,7 @@ import {
import { invokePlugin, loadPluginPageAssets } from "./pluginClient";
import { PluginNativeIntent } from "./PluginNativeIntent";
import { PluginDirectoryPicker } from "./PluginDirectoryPicker";
+import { PluginModelPicker } from './PluginModelPicker';
import { pluginPageHtml } from "./pluginPageHtml";
function pageColors(colors: ThemeColors) {
@@ -102,6 +104,8 @@ export function PluginPage({
const [directoryRequest, setDirectoryRequest] =
useState<PluginDirectoryRequest>();
const [confirm, setConfirm] = useState<PluginPageConfirm>();
+ const [modelPicker, setModelPicker] = useState<PluginModelPickerRequest>();
+ const completedModelPickers = useRef(new Set<string>());
const [answering, setAnswering] = useState(false);
const [notice, setNotice] = useState("");
const focusedRef = useRef(focused);
@@ -146,6 +150,7 @@ export function PluginPage({
"media:open",
"answer",
"answer-directory",
+ "answer-model-picker",
"intent:ack",
"preview:fetch",
"seen",
@@ -168,6 +173,8 @@ export function PluginPage({
setError(false);
setConfirm(undefined);
setDirectoryRequest(undefined);
+ setModelPicker(undefined);
+ completedModelPickers.current.clear();
setNativeIntent(undefined);
const poll = async () => {
if (!visible() || !page || !rendered.current || polling) return;
@@ -190,6 +197,7 @@ export function PluginPage({
});
setConfirm(result.confirms[0]);
setDirectoryRequest(result.directories?.[0]);
+ setModelPicker(result.modelPickers?.find(value => !completedModelPickers.current.has(value.requestId)));
setNativeIntent(result.intents?.[0]);
if (result.notifications?.length)
setNotice(result.notifications.at(-1)!.text);
@@ -239,6 +247,7 @@ export function PluginPage({
else {
setConfirm(undefined);
setDirectoryRequest(undefined);
+ setModelPicker(undefined);
setNativeIntent(undefined);
if (page) void call("suspend").catch(() => {});
}
@@ -662,10 +671,28 @@ export function PluginPage({
}}
/>
) : null}
+ {modelPicker && focused && !unavailable ? (
+ <PluginModelPicker key={modelPicker.requestId} request={modelPicker} deviceId={deviceId}
+ onAnswer={async route => {
+ const call = request.current;
+ if (!call || !focusedRef.current || AppState.currentState !== 'active')
+ return { handled: false, accepted: false };
+ const result = await call<{ handled: boolean; accepted: boolean }>('answer-model-picker', {
+ requestId: modelPicker.requestId, route,
+ });
+ if (request.current === call && (result.accepted || !result.handled)) {
+ completedModelPickers.current.add(modelPicker.requestId);
+ if (completedModelPickers.current.size > 64) completedModelPickers.current.delete(completedModelPickers.current.values().next().value!);
+ setModelPicker(undefined);
+ }
+ return result;
+ }} />
+ ) : null}
<Modal
visible={Boolean(
confirm &&
!directoryRequest &&
+ !modelPicker &&
!nativeIntent &&
focused &&
!unavailable,
diff --git a/apps/mobile/src/session/ModelPickerSheet.tsx b/apps/mobile/src/session/ModelPickerSheet.tsx
index 88f0a42ab2..32ac226be1 100644
--- a/apps/mobile/src/session/ModelPickerSheet.tsx
+++ b/apps/mobile/src/session/ModelPickerSheet.tsx
@@ -69,6 +69,8 @@ const SECONDARY_SLIDE_OUT_EASING = Easing.bezier(...motionEasing.in);
const EMPTY_FLAT_OPTIONS: readonly MobileModelOption[] = [];
export interface ModelPickerSheetProps {
+ /** Host-owned context, such as the plugin requesting this selection. */
+ title?: string;
unified?: UnifiedMobilePickerOptions;
visible: boolean;
onClose(): void;
@@ -132,6 +134,7 @@ export function ModelPickerSheet(props: ModelPickerSheetProps) {
}
function LegacyModelPickerSheet({
visible,
+ title,
onClose,
onClosed,
providers,
@@ -514,7 +517,7 @@ function LegacyModelPickerSheet({
if (Platform.OS === 'ios') {
return (
<ComposerSheet nativeContent visible={visible} onClose={onClose} onClosed={onClosed} backLabel={t('models.picker.backToModels')}
- title={view.kind === 'models' ? t('models.picker.title') : secondaryTitle}
+ title={view.kind === 'models' ? title ?? t('models.picker.title') : secondaryTitle}
onBack={view.kind === 'models' ? undefined : backToModels} testID={testID}>
{view.kind === 'models' ? <>
<ModelPickerNativeHeader query={query} onChangeQuery={setQuery}
@@ -547,7 +550,7 @@ function LegacyModelPickerSheet({
scrollRef={scrollRef}
snap={primarySnap}
testID={testID}
- title={t('models.picker.title')}
+ title={title ?? t('models.picker.title')}
>
{permissionRow}
{noResults ? (
diff --git a/apps/mobile/src/session/UnifiedModelPickerSheet.tsx b/apps/mobile/src/session/UnifiedModelPickerSheet.tsx
index 26aabacb07..c8a1137084 100644
--- a/apps/mobile/src/session/UnifiedModelPickerSheet.tsx
+++ b/apps/mobile/src/session/UnifiedModelPickerSheet.tsx
@@ -1070,7 +1070,7 @@ export function UnifiedModelPickerSheet(
title={
favoriteEdit
? t("models.unified.editFavorite")
- : (row?.entry.displayName ?? t("models.picker.title"))
+ : (row?.entry.displayName ?? p.title ?? t("models.picker.title"))
}
testID={p.testID ?? "modelSheet"}
query={query}
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index 692bf88910..05ea8d84fe 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -718,9 +718,14 @@ Host receipt 的 `simulatorPreviousRelId` 只允许这对 ID 和 root 路径,
## 6. 作者契约与编写手册同步
-内置 `cindy-plugin-creator` Skill 是 Agent 替用户编写插件的**唯一教材**,正本位于
+内置 `cindy-plugin-creator` Skill 是 Agent 替用户编写插件的**统一手册与流程入口**,正本位于
`apps/desktop/resources/system-skills/cindy-plugin-creator/`。`SKILL.md` 负责流程与按需阅读索引,
-`references/` 负责各章作者契约。插件页「让 Cindy 创建」从当前引擎的本机命令清单中选择
+`references/` 负责各章作者契约。创作流程以 §0a 的宿主版本与源码核验开头:先确认插件
+执行电脑,通过实际版本对应的已验证 tag 或构建 commit 定位官方仓库,再按需核对公开
+接口、宿主处理与测试。不能用 main 或未经核实的本地 HEAD 代替运行宿主;版本或源码
+不可核实时说明限制,继续完成随包手册和运行时结果可以支持的部分。源码核验的详细流程
+只维护在 `references/plugin-source-verification.md`,并由兼容手册入口读取同一份资料。
+插件页「让 Cindy 创建」从当前引擎的本机命令清单中选择
已验证的内置 Skill,预填其实际命令名(Claude 同名冲突时带 `cindy:`);始终优先内置版本,
不可用时提示并保留原草稿,不回退到同名用户 Skill。使用普通新任务的技能调用链路;
草稿保留内置身份,编辑正文、语音转写回填与切换 Agent 时不丢失;发送前按最终引擎和任务所在电脑的
@@ -928,6 +933,23 @@ visible 复用当前账号模型选择器的用户开关与目录默认值;隐
检查插件在装启用与 owner 归属,异步返回前复核。旧 Host 404 时插件应明确提示升级。
此端点不覆盖远程 SSH 模型,执行前仍需核验真实路由。
+### 宿主统一模型选择器(新增接口,尚未发布)
+
+电子脑 `cindy.pickModel({initial?,mobilePageId?})` 与桌面页面同源 `POST /model-picker`
+复用 Cindy 的统一模型选择器,返回完整 `PluginTaskRoute`(来源、模型、引擎、思考档位、Fast)。
+选模不需要新的 manifest 权限、不改变存量批准,不修改默认或现有任务、不执行模型调用。
+任务创建仍走原任务能力批准。仅返回显式配置字段,不返回凭证、endpoint 或 ProviderView。
+
+Main 按真实逻辑页或专属协议分区定位物理实例,绑定当前 owner 与安装批准版本;
+只接受目标宿主窗口或目标页面的回答,验证输入形状与实际可用路由,异步校验后再次复核绑定。
+同一 Host 仅一单,重复打开沿用目录选择的限速。取消、90 秒超时、窗口/页面关闭、账号边界、
+插件停止均撤销等待并收起界面;不可用的来源保持选择器可编辑,不能静默换模型。
+手机与远程桌面设置页保留显式 mobilePageId,展示端读取执行电脑目录,缺失/失效来源不回退另一设备。
+旧 Host 通过函数检查/404 明确升级;旧控制端忽略新增可选 modelPickers,超时取消,不产生执行。
+
+实现见 `ghostModelPicker.ts`、`PluginModelPickerHost.tsx`、`mobilePageService.ts`;
+作者契约见 `cindy-plugin-creator/references/plugin-agent-models.md`,回归见 `ghostModelPicker.test.ts`。
+
### 同账号插件资料同步
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 21b35b66a6..2b584d7fc0 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -22,6 +22,16 @@ Pi 只改写副本首行的 session ID 与 cwd,使其指向接收端工作目
确认卡(`hostOwnedConfirmation: native_history_fallback`)询问,支持同账号远控回答;取消、超时保留原电脑与原生记录。
旧客户端已支持 auto 和通用 permission 卡;共享来源仍沿用原来的 ask/记住偏好,不自动扩大授权。
+## 插件宿主模型选择器(新增接口,尚未发布)
+
+`PluginPagePoll` 新增可选 `modelPickers`,Host 绑定原插件安装与页面,手机及远程桌面
+设置页使用执行电脑的统一模型目录,只把用户确认的完整 route 通过原页面回传。
+远程设置的密封命令增量为 `answer-model-picker`;原有命令、权限、安装批准与账号凭证合同不变。
+未更新的控制端忽略可选字段,Host 在 90 秒后取消;新插件检查 `cindy.pickModel` 是否存在,
+不把目录读取或选模当成执行授权。两端都更新后才具备原生选模回执,不需要服务端变更。
+新增 Renderer IPC 仅本机宿主使用,不进入 device-link 通用 invoke/push 白名单;跨设备
+复用既有插件页面资源与密封设置链。正文详见 [插件规则](plugin-security-and-authoring.md#宿主统一模型选择器新增接口尚未发布)。
+
## 接受已保存的伙伴模型
既有 `local-db:bots:update` 可选接收 `acceptSavedModelSelectionVersion`(读取到的正整数
diff --git a/packages/device-link/src/__tests__/pluginSettings.test.ts b/packages/device-link/src/__tests__/pluginSettings.test.ts
index 4c2bb7d118..f0071312f7 100644
--- a/packages/device-link/src/__tests__/pluginSettings.test.ts
+++ b/packages/device-link/src/__tests__/pluginSettings.test.ts
@@ -25,6 +25,10 @@ describe("sealed original settings commands", () => {
{ kind: "post", channel: "one", data: { type: "status" } },
{ kind: "poll", after: 0 },
{ kind: "confirm", requestId: "confirm-1", accepted: true },
+ { kind: 'answer-model-picker', requestId: 'model-1', route: null },
+ { kind: 'answer-model-picker', requestId: 'model-1', route: {
+ agentKind: 'codex', providerId: 'provider', model: 'model', effort: 'high', fastMode: 'ultrafast',
+ } },
{
kind: "answer-directory",
requestId: "directory-1",
@@ -70,6 +74,10 @@ describe("sealed original settings commands", () => {
{ kind: "post", channel: "unsafe/channel", data: {} },
{ kind: "poll", after: Number.MAX_SAFE_INTEGER + 1 },
{ kind: "confirm", requestId: "confirm-1", accepted: "yes" },
+ { kind: 'answer-model-picker', requestId: 'model-1', route: { model: 'partial' } },
+ { kind: 'answer-model-picker', requestId: 'model-1', route: {
+ agentKind: 'codex', providerId: 'provider', model: 'model', effort: 'high', fastMode: false, apiKey: 'private',
+ } },
{ kind: "answer-directory", requestId: "directory-1", path: 42 },
{ kind: "authorization-result", requestId: "../elsewhere" },
{ kind: "close", path: "/kv" },
diff --git a/packages/device-link/src/pluginPages.ts b/packages/device-link/src/pluginPages.ts
index 62da12c594..7dd26d2198 100644
--- a/packages/device-link/src/pluginPages.ts
+++ b/packages/device-link/src/pluginPages.ts
@@ -268,6 +268,36 @@ export interface PluginPagePoll {
unreadAt?: number;
directories?: PluginDirectoryRequest[];
intents?: PluginNativeIntent[];
+ /** Optional; old controllers ignore requests and Host timeout cancels them. */
+ modelPickers?: PluginModelPickerRequest[];
+}
+
+export interface PluginModelSelection {
+ agentKind: 'cc' | 'codex' | 'pi';
+ providerId: string;
+ model: string;
+ effort: string;
+ fastMode: boolean | 'ultrafast';
+}
+
+export function isPluginModelSelection(value: unknown): value is PluginModelSelection {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
+ const v = value as Record<string, unknown>;
+ const text = (key: string, max: number) => typeof v[key] === 'string' &&
+ (v[key] as string).trim().length > 0 && (v[key] as string).length <= max;
+ return Object.keys(v).every(key => ['agentKind', 'providerId', 'model', 'effort', 'fastMode'].includes(key)) &&
+ ['cc', 'codex', 'pi'].includes(String(v.agentKind)) && text('providerId', 128) && text('model', 256) &&
+ typeof v.effort === 'string' && v.effort.length <= 32 &&
+ (typeof v.fastMode === 'boolean' || v.fastMode === 'ultrafast');
+}
+
+/** Native Host model selection; never forwarded into the plugin document. */
+export interface PluginModelPickerRequest {
+ requestId: string;
+ ghostId: string;
+ ghostName: string;
+ initial?: PluginModelSelection;
+ expiresAt: number;
}
export type PluginNativeIntent = {
id: string;
diff --git a/packages/device-link/src/pluginSettings.ts b/packages/device-link/src/pluginSettings.ts
index e74b8ebf3f..731f02fcb5 100644
--- a/packages/device-link/src/pluginSettings.ts
+++ b/packages/device-link/src/pluginSettings.ts
@@ -1,3 +1,4 @@
+import { isPluginModelSelection, type PluginModelSelection } from './pluginPages.js';
export const PLUGIN_SETTINGS_ACTION = "settings-page";
const oauthId = (value: unknown): value is string =>
typeof value === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(value);
@@ -11,6 +12,7 @@ export type PluginSettingsCommand =
| { kind: "poll"; after: number }
| { kind: "confirm"; requestId: string; accepted: boolean }
| { kind: "answer-directory"; requestId: string; path: string | null }
+ | { kind: "answer-model-picker"; requestId: string; route: PluginModelSelection | null }
| { kind: "authorize"; path: string; body?: string }
| { kind: "authorization-result"; requestId: string }
| { kind: "close" };
@@ -108,6 +110,10 @@ export function parsePluginSettingsRequest(
oauthId(c.requestId) &&
typeof c.accepted === "boolean";
break;
+ case "answer-model-picker":
+ valid = exact(['kind', 'requestId', 'route']) && oauthId(c.requestId) &&
+ (c.route === null || isPluginModelSelection(c.route));
+ break;
case "answer-directory":
valid =
exact(["kind", "requestId", "path"]) &&