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(mobile): 支持远程插件管理与原配置页

nana6551b7a4ecdb
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/fixtures/mobile-plugin-settings/README.md b/apps/desktop/src/main/cindy-brain/__tests__/fixtures/mobile-plugin-settings/README.md
new file mode 100644
index 0000000000..4be2677ef3
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/fixtures/mobile-plugin-settings/README.md
@@ -0,0 +1,61 @@
+# 原配置页 QA fixture
+
+仅供原 settingsHtml 桥的测试与隔离环境验收,不是产品设计稿,也不是可直接安装的插件包。
+没有 manifest、自动安装器、外网地址或凭证。此轮验收不含文件导入;目录选择只验证目标
+归属、取消与回传,不读取或导入所选目录内容。总控负责最终真机/模拟器闭环。
+
+## 给原页面桥提供内容
+
+- 将 `settings.html` 作为 `manifest.settingsHtml` 指向的原文件,原样供给 `settings.js`。
+- 测试 `bundle` 返回这两个文件的实际字节数、MIME;`asset` 按现有 49,152-byte 分片协议供给。
+- 使用现有物理实例、安装批准和设备身份;同 manifest id 的 root/org 两份分别运行。
+- 不根据 QA 插件 ID 修改生产代码,不把 `responses.json` 注册到生产路由。
+- `responses.json` 是固定的合成 Host 响应种子。页面不会读取它,Host 不可用时也不会偷换成
+ 这些数据。测试应在注入的原设置 executor/测试后端提供这些事实。
+- OAuth 测试后端提供两个账号;真实 OAuth 回跳仍需专用测试 provider/账号,本 fixture
+ 本身不声称已完成授权。
+
+## 原交互与后端合同
+
+| 页面动作 | 原接口 / 可观察结果 |
+| --- | --- |
+| 初始读取、重新读取 | `GET /kv`、`GET /secrets`、`GET /oauth`;失败显示失败,不伪造 ready |
+| 普通字段、底部长文本 | 读 `/kv` → 合并相关字段 → `PUT /kv` → 回读;保留无关键 |
+| 敏感输入 | `PUT /secrets/key`,body `{value}`;回读仅状态;成功或失败后清空输入 |
+| 增加测试账号 | `POST /oauth/login/connect`,body `{}`;随后回读账号 |
+| 切默认账号 | `POST /oauth/login/default`,body `{accountId}`;随后回读账号 |
+| 目录与频道 | 既有 `BroadcastChannel('qa-settings')`,见下表;不发明宿主 HTTP 端点 |
+
+测试端根据实际声明提供 `key`(user Secret)、`login`(OAuth)以及 `qa-settings` 频道。
+fixture 只操作这些声明;不含秘密初值,也不把 Secret 写到 `/kv`、页面状态、日志或本地存储。
+原页面里的短暂输入仍须由正在验收的加密设置桥承接;直接从浏览器访问不能证明秘密通道安全。
+
+| 频道请求 | 测试/插件执行端回复 |
+| --- | --- |
+| `{kind:'probe', requestId}` | `{kind:'probe-result', requestId, targetLabel:'QA target B'}` |
+| `{kind:'choose-directory', requestId}` | `{kind:'directory-result', requestId, name:'QA directory'}` 或 `{kind:'directory-result', requestId, cancelled:true}` |
+
+目录请求是这个 QA 插件自己的频道消息,不是 Cindy 公共 API。测试可以让执行端调用现有
+`MobilePluginPages.chooseDirectory` 来触发目标目录选择与回传;不要为了 fixture 新增
+`/__bridge__/pick-directory` 一类生产路由。真实插件使用既有目录选择能力时仍按其原声明和
+执行路径运行。迟到的旧 requestId 回复必须忽略。
+
+## 最小人工验收顺序
+
+1. 在总控集成预览分支的隔离 B 打开原页;确认标题与 QA 标记,两个账号来自 B。
+2. 修改 label、开关、语言,保存并重读;从另一控制端读取 B 核对;C 哨兵保持不同。
+3. 输入明显无效的 QA key,保存;输入被清空,页面只返回 saved 状态。
+4. 切换两账号默认值;取消/完成专用 OAuth 测试授权;回读事实。
+5. 发频道 probe;目录分别取消和选择;只显示匹配 requestId 的结果。
+6. 滚动至第 16 个输入和 Last field;输入后切主题、开关键盘,检查焦点、草稿和保存可达。
+7. 分别在 320px、常见手机、平板与 Light/Dark 检查;生产主题 token 由宿主提供。
+8. 等待/保存期间断线、切设备/账号/安装代次,回前台只对账,不能重放写入。
+
+本页 `/kv` 是原插件的整体覆盖接口,读后合并不提供原子并发控制;不以此 fixture 声称解决
+了插件的并发保存冲突。16 个 scrollProbe 字段仅是页内未保存草稿,只有 Last field 会持久化。
+
+## 验证边界
+
+合成响应和 DOM smoke 只证明原页交互可运行;Host 单元测试证明回执/时序合同;真实加密桥、
+钥匙串、OAuth 系统浏览器、键盘/滚动、安全区及网络恢复须由总控在隔离 Host 与原生客户端验收。
+不要用 Expo Go/mock-host 结果替代当前 native 包与真实 Host 的完整闭环。
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/fixtures/mobile-plugin-settings/responses.json b/apps/desktop/src/main/cindy-brain/__tests__/fixtures/mobile-plugin-settings/responses.json
new file mode 100644
index 0000000000..21f65180d4
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/fixtures/mobile-plugin-settings/responses.json
@@ -0,0 +1,19 @@
+{
+ "preferences": {
+ "displayLabel": "QA target B",
+ "notifications": true,
+ "language": "en",
+ "lastField": "QA long form initial value",
+ "unrelatedPreference": "must survive partial form saves"
+ },
+ "secrets": [{ "key": "key", "saved": false }],
+ "oauth": [{
+ "key": "login",
+ "clientConfigured": true,
+ "clientCustom": false,
+ "accounts": [
+ { "id": "qa-account-one", "label": "QA account one", "isDefault": true },
+ { "id": "qa-account-two", "label": "QA account two", "isDefault": false }
+ ]
+ }]
+}
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/fixtures/mobile-plugin-settings/settings.html b/apps/desktop/src/main/cindy-brain/__tests__/fixtures/mobile-plugin-settings/settings.html
new file mode 100644
index 0000000000..a359ceb4ce
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/fixtures/mobile-plugin-settings/settings.html
@@ -0,0 +1,64 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>QA original plugin settings</title>
+ <style>
+ * { box-sizing: border-box; }
+ body { margin: 0; padding: 16px; font: 16px/1.5 system-ui, sans-serif; color: var(--text-primary, CanvasText); background: var(--surface, Canvas); }
+ main { width: 100%; max-width: 40rem; margin: auto; }
+ h1, h2 { font-size: 18px; line-height: 1.4; }
+ fieldset { min-width: 0; margin: 16px 0; padding: 12px; border: 1px solid var(--border-default, GrayText); }
+ label { display: block; margin: 12px 0; }
+ input:not([type="checkbox"]), select, textarea { display: block; width: 100%; margin-top: 4px; padding: 8px; font: inherit; color: inherit; background: var(--surface-elevated, Field); border: 1px solid var(--border-default, GrayText); }
+ button { min-height: 44px; max-width: 100%; padding: 8px 12px; margin: 4px 0; font: inherit; white-space: normal; color: inherit; background: var(--surface-elevated, ButtonFace); border: 1px solid var(--border-default, GrayText); }
+ output, li { overflow-wrap: anywhere; }
+ :focus-visible { outline: 2px solid var(--focus-ring, Highlight); outline-offset: 2px; }
+ </style>
+ </head>
+ <body>
+ <main>
+ <h1>QA original plugin settings</h1>
+ <p>TEST DATA ONLY · original HTML fixture · no file import</p>
+ <output id="status" role="status" aria-live="polite">Reading target Host…</output>
+ <form id="preferences">
+ <fieldset>
+ <legend>Ordinary settings on the target Host</legend>
+ <label>Display label <input id="displayLabel" name="displayLabel" required maxlength="80"></label>
+ <label><input id="notifications" name="notifications" type="checkbox"> Notifications</label>
+ <label>Language <select id="language" name="language"><option value="en">English</option><option value="zh-CN">简体中文</option></select></label>
+ <button type="submit">Save ordinary settings</button>
+ <button id="reload" type="button">Read target again</button>
+ </fieldset>
+ </form>
+ <fieldset>
+ <legend>Write-only synthetic secret</legend>
+ <output id="secretState">Status unknown</output>
+ <label>Test key <input id="secret" type="password" autocomplete="off" placeholder="Use an invalid QA value only"></label>
+ <button id="saveSecret" type="button">Save test key to target</button>
+ </fieldset>
+ <fieldset>
+ <legend>OAuth accounts</legend>
+ <ul id="accounts"></ul>
+ <button id="connect" type="button">Connect a test account</button>
+ </fieldset>
+ <fieldset>
+ <legend>Directory and original channel interaction</legend>
+ <button id="pickDirectory" type="button">Choose a directory on the target</button>
+ <output id="directory">No directory selected</output>
+ <button id="echo" type="button">Send channel probe</button>
+ <output id="channelState">No reply received</output>
+ </fieldset>
+ <form id="longForm">
+ <fieldset>
+ <legend>Long form: keyboard and scroll</legend>
+ <div id="longFields"></div>
+ <label>Last field <textarea id="lastField" rows="4" placeholder="Keep this draft while opening the keyboard or changing theme"></textarea></label>
+ <button type="submit">Save bottom field</button>
+ </fieldset>
+ </form>
+ </main>
+ <script src="settings.js"></script>
+ </body>
+</html>
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/fixtures/mobile-plugin-settings/settings.js b/apps/desktop/src/main/cindy-brain/__tests__/fixtures/mobile-plugin-settings/settings.js
new file mode 100644
index 0000000000..97a634ebb1
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/fixtures/mobile-plugin-settings/settings.js
@@ -0,0 +1,143 @@
+// Test-only original plugin code: no local persistence, production ID branching, or external fetch.
+(() => {
+ const element = (id) => document.getElementById(id);
+ const status = (text) => { element('status').textContent = text; };
+ const channel = new BroadcastChannel('qa-settings');
+ let sequence = 0;
+ let pendingDirectory;
+ let pendingProbe;
+ const request = async (path, method = 'GET', body) => {
+ const response = await fetch(path, {
+ method,
+ ...(body === undefined ? {} : {
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ }),
+ });
+ if (!response.ok) throw new Error('Target request failed: ' + response.status);
+ return response.status === 204 ? undefined : response.json();
+ };
+ const action = (id, run) => {
+ element(id).addEventListener('click', async () => {
+ element(id).disabled = true;
+ try { await run(); } catch { status('Target request failed; read target again before retrying a write.'); }
+ finally { element(id).disabled = false; }
+ });
+ };
+ const refreshAccounts = async () => {
+ const declarations = await request('/oauth');
+ const accounts = declarations.find((entry) => entry.key === 'login')?.accounts ?? [];
+ element('accounts').replaceChildren();
+ for (const account of accounts) {
+ const row = document.createElement('li');
+ row.textContent = account.label + (account.isDefault ? ' (default)' : '');
+ const choose = document.createElement('button');
+ choose.type = 'button';
+ choose.textContent = 'Use ' + account.label;
+ choose.addEventListener('click', async () => {
+ choose.disabled = true;
+ try {
+ await request('/oauth/login/default', 'POST', { accountId: account.id });
+ await refreshAccounts();
+ status('Default test account read back from target.');
+ } catch { status('Account change not confirmed; read target again.'); }
+ finally { choose.disabled = false; }
+ });
+ row.append(document.createTextNode(' '), choose);
+ element('accounts').append(row);
+ }
+ };
+ const readTarget = async () => {
+ const preferences = await request('/kv');
+ element('displayLabel').value = preferences.displayLabel ?? '';
+ element('notifications').checked = preferences.notifications === true;
+ element('language').value = preferences.language ?? 'en';
+ element('lastField').value = preferences.lastField ?? '';
+ const secrets = await request('/secrets');
+ element('secretState').textContent = secrets.find((entry) => entry.key === 'key')?.saved
+ ? 'Test key saved on target (value is not returned)' : 'No test key saved';
+ await refreshAccounts();
+ status('Target Host state read.');
+ };
+ const savePreferences = async (patch) => {
+ // /kv replaces an object. Preserve unrelated keys; concurrent-edit semantics remain the plugin's.
+ const preferences = { ...await request('/kv'), ...patch };
+ await request('/kv', 'PUT', preferences);
+ const confirmed = await request('/kv');
+ status('Ordinary settings read back: ' + confirmed.displayLabel);
+ };
+ element('preferences').addEventListener('submit', async (event) => {
+ event.preventDefault();
+ const submit = element('preferences').querySelector('[type="submit"]');
+ if (submit.disabled) return;
+ submit.disabled = true;
+ try {
+ await savePreferences({
+ displayLabel: element('displayLabel').value,
+ notifications: element('notifications').checked,
+ language: element('language').value,
+ });
+ } catch { status('Save not confirmed; read target again.'); }
+ finally { submit.disabled = false; }
+ });
+ action('reload', readTarget);
+ action('saveSecret', async () => {
+ try {
+ await request('/secrets/key', 'PUT', { value: element('secret').value });
+ const secrets = await request('/secrets');
+ element('secretState').textContent = secrets.find((entry) => entry.key === 'key')?.saved
+ ? 'Test key saved on target (value is not returned)' : 'No test key saved';
+ status('Secret status read back from target.');
+ } finally { element('secret').value = ''; }
+ });
+ action('connect', async () => {
+ const result = await request('/oauth/login/connect', 'POST', {});
+ await refreshAccounts();
+ status(result?.ok ? 'Authorization completed on target.' : 'Authorization did not complete.');
+ });
+ action('pickDirectory', () => {
+ pendingDirectory = 'directory-' + ++sequence;
+ channel.postMessage({ kind: 'choose-directory', requestId: pendingDirectory });
+ element('directory').textContent = 'Waiting for target directory selection…';
+ });
+ action('echo', () => {
+ pendingProbe = 'probe-' + ++sequence;
+ channel.postMessage({ kind: 'probe', requestId: pendingProbe });
+ element('channelState').textContent = 'Waiting for channel reply…';
+ });
+ channel.onmessage = ({ data }) => {
+ if (data?.kind === 'directory-result' && data.requestId === pendingDirectory) {
+ pendingDirectory = undefined;
+ element('directory').textContent = data.cancelled ? 'Directory selection cancelled' : data.name;
+ }
+ if (data?.kind === 'probe-result' && data.requestId === pendingProbe) {
+ pendingProbe = undefined;
+ element('channelState').textContent = data.targetLabel;
+ }
+ };
+ for (let index = 1; index <= 16; index++) {
+ const label = document.createElement('label');
+ label.textContent = 'Unsaved scroll probe ' + index;
+ const input = document.createElement('input');
+ input.id = 'scrollProbe' + index;
+ input.placeholder = 'Local page draft only';
+ label.append(input);
+ element('longFields').append(label);
+ }
+ element('longForm').addEventListener('submit', async (event) => {
+ event.preventDefault();
+ const submit = element('longForm').querySelector('[type="submit"]');
+ if (submit.disabled) return;
+ submit.disabled = true;
+ try { await savePreferences({ lastField: element('lastField').value }); }
+ catch { status('Bottom field save not confirmed; read target again.'); }
+ finally { submit.disabled = false; }
+ });
+ window.addEventListener('pagehide', () => {
+ pendingDirectory = undefined;
+ pendingProbe = undefined;
+ element('secret').value = '';
+ channel.close();
+ }, { once: true });
+ readTarget().catch(() => status('Cannot read target Host. No fallback data was substituted.'));
+})();
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostCredentialProtocolCallbacks.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostCredentialProtocolCallbacks.test.ts
index 36abe1fa02..faee804955 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostCredentialProtocolCallbacks.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostCredentialProtocolCallbacks.test.ts
@@ -1,6 +1,7 @@
import { createGhostProductionCallbacks } from './ghostProductionCallbacksFixture.js';
import { describe, expect, it, vi } from 'vitest';
+import { withRemoteOauthContext, type RemoteOauthContext } from '../../plugin-oauth/context.js';
import type { InstalledGhost } from '../../../shared/ghost.js';
import { GhostConnectionManager } from '../ghostConnections.js';
import { GhostOauthAccountManager } from '../ghostOauthAccounts.js';
@@ -197,3 +198,51 @@ describe('Credential protocol wiring through actual index callbacks', () => {
expect(target.notice).not.toHaveBeenCalled();
});
});
+
+// The production callback and real account manager must keep a phone-owned exchange
+// on the remote path even when its controller rejects or cancels authorization.
+describe('Original settings OAuth remote routing', () => {
+ it.each(['denied', 'cancelled'] as const)('never opens the Host browser after remote %s', async (outcome) => {
+ const openExternal = vi.fn();
+ const fetchImpl = vi.fn();
+ const store = vi.fn(() => true);
+ const manager = new GhostOauthAccountManager({
+ vault: { read: () => null, store, remove: vi.fn() },
+ openExternal,
+ fetchImpl: fetchImpl as unknown as typeof fetch,
+ captureConnectTarget: () => ({ revision: 'approved-settings-target' }),
+ isConnectTargetCurrent: () => true,
+ });
+ const connect = vi.spyOn(manager, 'connectAccount');
+ const remote: RemoteOauthContext = {
+ scope: 'settings-request', peer: 'phone', assertCurrent: vi.fn(), finish: vi.fn(),
+ authorize: vi.fn(async (offer) => {
+ if (outcome === 'cancelled') throw new Error('CONTROLLER_CANCELLED');
+ return { state: offer.state, error: 'access_denied' };
+ }),
+ };
+ const decl = { authorizeUrl: 'https://accounts.example.com/authorize', tokenUrl: 'https://accounts.example.com/token', clientId: 'fake-public-client', scopes: ['read'] };
+ const handler = loadCallback('setGhostOauthHandler', {
+ findGhostForInstanceId: () => ({ manifest: { network: { hosts: ['api.example.com'], secrets: [{ key: 'account', source: 'oauth', oauth: decl }] } } }),
+ handleGhostOauthRequest,
+ getGhostOauthAccountManager: () => manager,
+ isGhostTokenBrokerAuthorized: () => false,
+ withActiveOwnerGhostOauthMutationLock: async (_id: string, task: () => unknown) => task(),
+ getGhostSetupChangeBus: () => ({ emit: vi.fn() }),
+ broadcastGhostsChanged: vi.fn(), getGhostManager: () => ({ list: () => [] }),
+ log: { warn: vi.fn() },
+ });
+ const result = await withRemoteOauthContext(remote, () => handler({
+ ghostId: 'settings-helper', method: 'POST', pathname: '/oauth/account/connect',
+ readBodyText: async () => '{"remote":{"scope":"forged"}}', isCurrent: () => true,
+ }));
+ expect(result.status).toBe(200);
+ expect(JSON.parse(result.body!)).toMatchObject({ ok: false, error: outcome === 'cancelled' ? 'CANCELLED' : 'CALLBACK_INVALID' });
+ expect(connect).toHaveBeenCalledExactlyOnceWith('settings-helper', 'account', decl, expect.objectContaining({ remote, assertCurrent: expect.any(Function) }));
+ expect(remote.authorize).toHaveBeenCalledTimes(1);
+ expect(remote.finish).toHaveBeenCalledWith(false);
+ expect(openExternal).not.toHaveBeenCalled();
+ expect(fetchImpl).not.toHaveBeenCalled();
+ expect(store).not.toHaveBeenCalled();
+ });
+});
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 2972ebe1ec..ad2d9592b7 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/mobilePageService.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/mobilePageService.test.ts
@@ -504,6 +504,8 @@ it('projects optional Host ordering facts without changing legacy lists on metad
});
+// The real get projection must retain semantic icon keys alongside localized copy;
+// checking both prevents controllers from having to infer permission kinds from text.
it('projects PC permission facts in the phone locale, excludes tools and keeps OAuth scopes', async () => {
const h = setup();
h.ghost.manifest.tools = [{name: 'calendar_events', description: 'Read events', parameters: {type: 'object'}}];
@@ -518,10 +520,14 @@ it('projects PC permission facts in the phone locale, excludes tools and keeps O
ref: {collectionId: 'plugins', kind: 'plugin', id: 'practice'},
client: {protocolVersion: 1, primitives: ['plugin-capabilities'], locale: 'zh-CN'},
});
- const facts = detail.blocks?.find(block => block.id === 'capabilities')?.data as {tools: unknown[]; permissions: Array<{title: string; description: string}>};
+ const facts = detail.blocks?.find(block => block.id === 'capabilities')?.data as {tools: unknown[]; permissions: Array<{kind?: string; labelKey?: string; title: string; description: string}>};
expect(facts.tools).toEqual([{name: 'calendar_events', description: 'Read events'}]);
- expect(facts.permissions.some(item => item.title.includes('calendar.example'))).toBe(true);
- expect(facts.permissions.some(item => item.description.includes('calendar.read'))).toBe(true);
+ expect(facts.permissions.find(item => item.title.includes('calendar.example'))).toMatchObject({
+ kind: 'network', labelKey: 'networkHost',
+ });
+ expect(facts.permissions.find(item => item.description.includes('calendar.read'))).toMatchObject({
+ kind: 'network', labelKey: 'networkSecretOauth',
+ });
expect(JSON.stringify(facts.permissions)).not.toContain('calendar_events');
expect(JSON.stringify(facts.permissions)).not.toContain('public-client-id');
expect(JSON.stringify(facts.permissions)).not.toContain('settings.ghosts.perm');
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/remotePluginManagement.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/remotePluginManagement.test.ts
index b01d6e3e6d..27269fbb70 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/remotePluginManagement.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/remotePluginManagement.test.ts
@@ -106,6 +106,117 @@ const flush = async () => {
await Promise.resolve();
await Promise.resolve();
};
+
+/*
+ * 测试价值(unit,内存依赖 + 假时钟;不启动 Host):
+ * - 生产入口/结果:RemotePluginManagement.invoke;回执到期/服务重建返回 NOT_FOUND,
+ * 真实已提交状态仍可读,取消不能把提交成功改成取消。
+ * - 依据:remotePluginManagement 的 15min 回执、进程内生命周期及提交后事实优先合同;
+ * engineering-conventions §3.2 的公开入口与时序结果要求。
+ * - 缺口:已有用例仅覆盖重连保留回执及提交前取消,未覆盖到期、服务重建、提交后取消。
+ * - 最小输入:一条等待确认/已成功操作跨过 TTL;同一持久状态重建服务;提交与完成之间取消。
+ * - 实测耗时:本机单文件 Vitest 0.65s(35 项测试执行 16ms);无真实等待/网络/用户数据。
+ */
+describe('remote plugin management receipt lifetime', () => {
+ it('expires a waiting confirmation at 15 minutes even when its receipt was just read', async () => {
+ const f = fixture();
+ const committed: string[] = [];
+ f.deps.market.install = vi.fn(async (id, _options, prompt, current) => {
+ const accepted = await prompt({
+ initiator: 'user',
+ origin: 'market',
+ facts: { kind: 'install', name: 'QA plugin', version: '1', permissions: [] },
+ });
+ if (!accepted) throw { code: 'MUTATION_CANCELLED' };
+ current();
+ committed.push(id);
+ });
+ await f.invoke('begin', {
+ operationId: 'expires-pending',
+ kind: 'install',
+ pluginId: 'qa-plugin',
+ expectedReleaseId: 'qa-release',
+ });
+ await vi.advanceTimersByTimeAsync(15 * 60_000 - 1);
+ const receipt = await f.invoke('operation', { operationId: 'expires-pending' });
+ expect(receipt.phase).toBe('confirmation');
+ const requestId = receipt.consent!.requestId;
+ await vi.advanceTimersByTimeAsync(1);
+ await expect(f.invoke('operation', { operationId: 'expires-pending' })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ await expect(
+ f.invoke('answer', {
+ operationId: 'expires-pending',
+ requestId,
+ confirmed: true,
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(committed).toEqual([]);
+ expect(f.deps.market.install).toHaveBeenCalledTimes(1);
+ });
+
+ it('forgets a completed receipt at 15 minutes without undoing or replaying its mutation', async () => {
+ const f = fixture();
+ await f.begin('disable', 'expires-completed');
+ await flush();
+ await vi.advanceTimersByTimeAsync(15 * 60_000 - 1);
+ expect((await f.invoke('operation', { operationId: 'expires-completed' })).phase).toBe('succeeded');
+ await vi.advanceTimersByTimeAsync(1);
+ await expect(f.invoke('operation', { operationId: 'expires-completed' })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ expect((await f.service.invoke('desktop-a', {
+ collectionId: 'plugins',
+ actionId: 'management:snapshot',
+ client: { protocolVersion: 1, primitives: ['action'] },
+ input: {},
+ })).result).toMatchObject({ ghosts: [{ enabled: false }, { enabled: true }] });
+ expect(f.deps.setEnabled).toHaveBeenCalledTimes(1);
+ });
+
+ it('exposes committed Host facts after service reconstruction without recovering an old receipt', async () => {
+ const f = fixture();
+ await f.begin('disable', 'before-restart');
+ await flush();
+ // Model a new Host service against the same installed state, not a real app restart.
+ const restarted = new RemotePluginManagement(f.deps);
+ const client = { protocolVersion: 1 as const, primitives: ['action'] };
+ await expect(restarted.invoke('desktop-a', {
+ collectionId: 'plugins',
+ actionId: 'management:operation',
+ client,
+ input: { operationId: 'before-restart' },
+ })).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect((await restarted.invoke('desktop-a', {
+ collectionId: 'plugins',
+ actionId: 'management:snapshot',
+ client,
+ input: {},
+ })).result).toMatchObject({ ghosts: [{ enabled: false }, { enabled: true }] });
+ expect(f.deps.setEnabled).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps a committed result successful when cancellation arrives before the executor returns', async () => {
+ const f = fixture();
+ let finish!: () => void;
+ f.deps.setEnabled = vi.fn(async (id, enabled, _approval, current) => {
+ current();
+ f.ghosts.find((ghost) => installedGhostStoragePart(ghost) === id)!.enabled = enabled;
+ await new Promise<void>((resolve) => { finish = resolve; });
+ });
+ await f.begin('disable', 'cancel-after-commit');
+ expect(f.ghosts.map((ghost) => ghost.enabled)).toEqual([false, true]);
+ await f.invoke('cancel', { operationId: 'cancel-after-commit' });
+ finish();
+ await flush();
+ expect((await f.invoke('operation', { operationId: 'cancel-after-commit' })).phase).toBe('succeeded');
+ expect((await f.invoke('cancel', { operationId: 'cancel-after-commit' })).phase).toBe('succeeded');
+ expect(f.ghosts.map((ghost) => ghost.enabled)).toEqual([false, true]);
+ expect(f.deps.setEnabled).toHaveBeenCalledTimes(1);
+ });
+});
+
describe('remote plugin management receipt boundaries', () => {
it('binds preference reads and writes to the physical instance, approval and live controller', async () => {
const f = fixture();
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 e3c18f84e8..f5a351d445 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.ts
@@ -71,7 +71,8 @@ afterEach(() => {
function fixture(namespace: string | null = null) {
let owner: string | null = 'owner',
revision = 'installed-1',
- allowed = true;
+ allowed = true,
+ now = Date.now();
const file = Buffer.from(
'<!doctype html><html><head></head><body><input id="original"><script src="settings.js"></script></body></html>',
);
@@ -125,6 +126,7 @@ function fixture(namespace: string | null = null) {
async () => '/target/resolved',
);
const service = new MobilePluginPages({
+ now: () => now,
list: () => [ghost],
revision: () => revision,
captureOwner: () => {
@@ -206,6 +208,8 @@ function fixture(namespace: string | null = null) {
return { view, fetch };
};
return {
+ advance: (ms: number) => { now += ms; },
+ now: () => now,
service,
ghost,
stored,
@@ -233,6 +237,14 @@ function fixture(namespace: string | null = null) {
}
describe('original remote plugin settings', () => {
+ it('advertises controller-routed settings authorization in the opened document', async () => {
+ const f = fixture();
+ const response = await f.service.provider().invoke!(
+ { controllerDeviceId: 'controller-a' },
+ { collectionId: 'plugins', actionId: 'settings:open', resourceRef: { collectionId: 'plugins', kind: 'plugin', id: f.ghost.instanceKey }, input: { expectedInstalledApproval: ghostInstallApprovalToken(f.ghost.approval) } } as never,
+ );
+ expect(response).toMatchObject({ result: { controllerAuthorization: true, pluginId: f.ghost.instanceKey } });
+ });
it.each([null, 'org'])(
'serves the original HTML in a unique, hardened session for namespace %s',
async (ns) => {
@@ -251,6 +263,15 @@ describe('original remote plugin settings', () => {
expect(ses.setPermissionCheckHandler).toHaveBeenCalled();
},
);
+ it('carries a credential check only inside the encrypted settings session', async () => {
+ const f = fixture(), { fetch } = await f.open();
+ f.settingsFetch.mockResolvedValueOnce({ status: 200, mime: 'application/json', base64: Buffer.from('{"valid":true}').toString('base64') });
+ const value = 'synthetic-check-candidate';
+ expect(await (await fetch('/secrets/key/check', { method: 'POST', body: JSON.stringify({ value }) })).json()).toEqual({ valid: true });
+ expect(f.settingsFetch).toHaveBeenCalledWith(expect.anything(), '/secrets/key/check', 'POST', JSON.stringify({ value }), expect.any(Function), expect.any(Function));
+ expect(JSON.stringify(f.wire)).not.toContain(value);
+ expect(f.controllerStored.size).toBe(0);
+ });
it('writes a new key only to B through the signed encrypted exchange, then reads B status', async () => {
const f = fixture(),
{ fetch } = await f.open();
@@ -503,6 +524,69 @@ describe('original remote plugin settings', () => {
expect(Buffer.from(result.base64, 'base64').toString()).toBe('{"ok":true}');
expect(f.service.settingsAuthorizationBinding(action)).toBeNull();
});
+ // Production settingsRequest/binding must survive a phone backgrounding during OAuth.
+ // Existing happy-path coverage never advances time; 121s idle is the minimal failure.
+ // Unit tier: in-memory endpoint/context, no provider tokens or external OAuth involved.
+ it.each([['page', true], ['sweep', false]] as const)('retains only an in-flight OAuth lease through %s after 120s idle (success=%s)', async (entry, success) => {
+ const f = fixture();
+ await f.open();
+ const pageId = [...(f.service as unknown as { pages: Map<string, unknown> }).pages.keys()][0];
+ const action = await f.service.settingsRequest('controller-a', {
+ op: 'settings', id: pageId, command: {kind: 'authorize', path: '/oauth/login/connect'},
+ }) as {requestId: string; actionId: string; expectedRevision: number};
+ let resolve!: (result: {status: number; mime: string; base64: string}) => void;
+ f.settingsFetch.mockImplementationOnce(() => new Promise(done => {resolve = done;}));
+ const finish = vi.fn();
+ const cancelled = new AbortController();
+ withRemoteOauthContext({scope: 'fixture', peer: 'controller-a', expiresAt: f.now() + 300_000,
+ cancelled: cancelled.signal, assertCurrent() {}, authorize: vi.fn(), finish},
+ () => expect(f.service.runSettingsAuthorization(action)).toBe(true));
+ f.advance(121_000);
+ if (entry === 'sweep') f.service.notify(pageId, 'example', 'fixture notification');
+ expect(f.service.settingsAuthorizationBinding(action)?.current()).toBe(true);
+ resolve({status: 200, mime: 'application/json', base64: Buffer.from(JSON.stringify({ok: success})).toString('base64')});
+ await Promise.resolve();
+ expect(finish).toHaveBeenCalledWith(success);
+ // A terminal authorization stays single-use until its result is consumed.
+ withRemoteOauthContext({scope: 'replay', peer: 'controller-a', expiresAt: f.now() + 300_000,
+ assertCurrent() {}, authorize: vi.fn(), finish},
+ () => expect(f.service.runSettingsAuthorization(action)).toBe(false));
+ expect(f.settingsFetch).toHaveBeenCalledTimes(1);
+ f.advance(121_000);
+ await expect(f.service.settingsRequest('controller-a', {op: 'settings', id: pageId,
+ command: {kind: 'poll', after: 0}})).rejects.toThrow();
+ });
+ it.each(['deadline', 'cancel', 'close', 'owner', 'controller', 'approval', 'no-deadline', 'not-started'] as const)(
+ 'does not retain an OAuth page after %s', async (reason) => {
+ const f = fixture();
+ await f.open();
+ const pageId = [...(f.service as unknown as {pages: Map<string, unknown>}).pages.keys()][0];
+ const action = await f.service.settingsRequest('controller-a', {op: 'settings', id: pageId,
+ command: {kind: 'authorize', path: '/oauth/login/connect'}}) as {requestId: string; actionId: string; expectedRevision: number};
+ let resolve!: (result: {status: number; mime: string; base64: string}) => void;
+ const cancelled = new AbortController();
+ const finish = vi.fn();
+ if (reason !== 'not-started') {
+ f.settingsFetch.mockImplementationOnce(() => new Promise(done => {resolve = done;}));
+ withRemoteOauthContext({scope: 'fixture', peer: 'controller-a',
+ expiresAt: reason === 'no-deadline' ? undefined : f.now() + 300_000,
+ cancelled: cancelled.signal, assertCurrent() {}, authorize: vi.fn(), finish},
+ () => expect(f.service.runSettingsAuthorization(action)).toBe(true));
+ }
+ f.advance(reason === 'deadline' ? 300_000 : 121_000);
+ if (reason === 'cancel') cancelled.abort();
+ if (reason === 'close') await f.service.settingsRequest('controller-a', {op: 'settings', id: pageId, command: {kind: 'close'}});
+ if (reason === 'owner') f.owner('replacement');
+ if (reason === 'controller') f.revoke();
+ if (reason === 'approval') f.revision();
+ f.service.notify(pageId, 'example', 'fixture notification');
+ expect(f.service.settingsAuthorizationBinding(action)?.current() ?? false).toBe(false);
+ await expect(f.service.settingsRequest('controller-a', {op: 'settings', id: pageId,
+ command: {kind: 'poll', after: 0}})).rejects.toThrow();
+ resolve?.({status: 200, mime: 'application/json', base64: Buffer.from('{"ok":true}').toString('base64')});
+ await Promise.resolve();
+ if (reason !== 'not-started') expect(finish).toHaveBeenCalledWith(false);
+ });
it('rejects foreign identities and unsafe package descriptors', () => {
expect(() =>
parseSettingsDocument({ pageId: 'p', pluginId: 'elsewhere' }, 'example'),
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index 82de4f26f8..73e62265c3 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -3181,6 +3181,20 @@ tail 也能画来写),DELETE 清除。红线:收单即交,不许把 key 落进 /
BroadcastChannel、日志或任何自存路径(review 必查)。凭证只会注入到它
\`inject.hosts\` 声明的域名请求,重定向出域也不会跟着走。用户没填时 cindy.fetch
返回结构化错误,把 message 原样告诉用户即可(里面带了去哪填的指引)。
+**可选的凭证校验**:普通 user secret 可声明 check:
+\`{ url, bodyFormat, validPath, validValue, expiresAtPath?, expiresAtFormat? }\`。
+url 必须是 HTTPS 默认端口且命中该凭证的 inject.hosts 与 network.hosts;bodyFormat
+为 JSON 对象模板,恰含一个字符串内的 {value}。validPath 为响应 JSON 点路径,
+validValue 为非空短字符串或布尔;有效期格式为 iso(默认)、unix-ms 或 unix-seconds。
+GET /secrets 仅对支持的声明返回 checkSupported:true。设置页可 POST
+\`/secrets/<key>/check\`,body 为 \`{value}\`,候选值只在 Host 此次请求内存中存在。
+Host 复用声明的 exchange 与 inject 完成两段请求,不保存候选、不共享换得的 token 缓存,
+不跟随重定向;只回 \`{valid:boolean,expiresAt?:ISO日期}\`,不回原响应或凭证。
+这是校验而非保存;PUT 的结果与 check 的结果必须分别呈现。旧 Host 缺 checkSupported
+时继续支持保存,明确说明未校验,不得退回 BC 发送凭证。服务端错误只回受控错误码。
+例:\`check:{url:"https://api.example.com/check",bodyFormat:'{"apiKey":"{value}"}',
+validPath:"status",validValue:"active",expiresAtPath:"expiresAtMs",expiresAtFormat:"unix-ms"}\`。
+
无论走 Setup 卡还是 settingsHtml,入库成功时主机会自动弹一条「凭证已保存」的系统提示(带你的身份头,
文案跟随用户语言;无需声明 notify)——设置页里画个就地的轻反馈即可,
不用自己想办法做全局提示。
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 483ee2019c..59881b3dfa 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -1,3 +1,4 @@
+import { checkGhostSecret } from './runtime/ghostSecretCheck.js';
import { RemotePluginPreferences } from './remotePluginPreferences.js';
import { readDeviceLinkSettings } from '../device-link/settings-store.js';
import { isSharedTaskPeer, isProviderSharePeer } from '@cindy/device-link';
@@ -8222,6 +8223,12 @@ export function registerGhostIpc(): void {
readBodyText,
isCurrent,
userSecretKeys,
+ checkSecretKeys: networkSecretDecls.filter((s) => s.check && (!s.source || s.source === 'user')).map((s) => s.key),
+ checkSecret: (key, value) => {
+ const secret = networkSecretDecls.find((s) => s.key === key)!;
+ return checkGhostSecret({ instanceKey: ghostId, secret, value, isCurrent,
+ fetch: (url, init) => outboundFetch(url, init) });
+ },
identitySecretKeys,
managedSecretStates,
hostCredentialStates: ghCliSecretDecls.map((s) => ({
diff --git a/apps/desktop/src/main/cindy-brain/mobilePageService.ts b/apps/desktop/src/main/cindy-brain/mobilePageService.ts
index 4e359bb964..cde9f81678 100644
--- a/apps/desktop/src/main/cindy-brain/mobilePageService.ts
+++ b/apps/desktop/src/main/cindy-brain/mobilePageService.ts
@@ -33,7 +33,7 @@ import {
interface Page {
desktopSettings?: true;
channels?: string[];
- authorizations?: Map<string, { path: string; body?: string; running: boolean; result?: import('@cindy/device-link').PluginPageFetchResult }>;
+ authorizations?: Map<string, { path: string; body?: string; running: boolean; keepAlive?: () => boolean; result?: import('@cindy/device-link').PluginPageFetchResult }>;
id: string;
controller: string;
plugin: string;
@@ -142,11 +142,15 @@ export class MobilePluginPages {
}
return ghost;
}
+ private idleExpired(page: Page): boolean {
+ return this.now() - page.touchedAt > 120_000 &&
+ ![...(page.authorizations?.values() ?? [])].some(a => a.running && a.keepAlive?.());
+ }
private page(id: unknown, controller: string): Page {
if (typeof id !== 'string') return fail();
const page = this.pages.get(id);
if (!page || page.controller !== controller) return fail();
- if (this.now() - page.touchedAt > 120_000) {
+ if (this.idleExpired(page)) {
this.close(page);
return fail();
}
@@ -219,8 +223,12 @@ export class MobilePluginPages {
const page = [...this.pages.values()].find((p) => p.authorizations?.has(action.requestId))!;
const authorization = page.authorizations!.get(action.requestId)!;
if (authorization.running) return false;
- authorization.running = true;
const ghost = this.check(page);
+ authorization.running = true;
+ // Only the already-bound transaction can retain this page while the phone is away.
+ // A missing deadline preserves the legacy idle policy. Identity checks still run.
+ authorization.keepAlive = () => remote.expiresAt !== undefined &&
+ this.now() < remote.expiresAt && !remote.cancelled?.aborted;
void (async () => {
try {
// The original endpoint owns OAuth validation, exchange and persistence.
@@ -248,6 +256,7 @@ export class MobilePluginPages {
};
remote.finish(false);
} finally {
+ authorization.keepAlive = undefined;
authorization.body = undefined;
}
})();
@@ -339,7 +348,7 @@ export class MobilePluginPages {
if (
url.origin !== 'https://plugin.invalid' ||
url.hash ||
- !/^\/(?:kv|app-context|agent-models|media-models|secrets(?:\/[^/]+)?|oauth(?:\/[^/]+\/(?:client|default|insufficient-scopes|accounts\/[^/]+))?|connections(?:\/[^/]+(?:\/[^/]+)?)?|wake)$/.test(
+ !/^\/(?:kv|app-context|agent-models|media-models|secrets(?:\/[^/]+(?:\/check)?)?|oauth(?:\/[^/]+\/(?:client|default|insufficient-scopes|accounts\/[^/]+))?|connections(?:\/[^/]+(?:\/[^/]+)?)?|wake)$/.test(
url.pathname,
)
)
@@ -520,12 +529,12 @@ export class MobilePluginPages {
}
private sweep() {
for (const page of this.pages.values()) {
- if (
- !page.currentOwner() ||
- !page.currentController() ||
- this.now() - page.touchedAt > 120_000
- )
- this.close(page);
+ try {
+ this.check(page);
+ if (this.idleExpired(page)) this.close(page);
+ } catch {
+ if (this.pages.has(page.id)) this.close(page);
+ }
}
}
/** Explicit page context supplied by a plugin handling that page's business request.
@@ -654,6 +663,8 @@ export class MobilePluginPages {
const permissions = ghostPermissionItems(ghost.manifest)
.filter((permission) => permission.kind !== 'tool')
.map((permission) => ({
+ kind: permission.kind,
+ labelKey: permission.labelKey,
title: permissionText(permission.labelKey, permission.labelArgs),
description: [
permission.detailKey
@@ -873,6 +884,7 @@ export class MobilePluginPages {
pluginId: id,
manifestId: ghost.manifest.id,
name: ghost.manifest.name,
+ controllerAuthorization: true,
entry: ghost.manifest.settingsHtml,
files: page.files,
},
diff --git a/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostOauthEndpoint.test.ts b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostOauthEndpoint.test.ts
index 760cd85e18..f2bbd0d806 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostOauthEndpoint.test.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostOauthEndpoint.test.ts
@@ -704,3 +704,11 @@ describe('tokenBroker 门控', () => {
expect(rejectedManager.connectAccount).not.toHaveBeenCalled();
});
});
+
+
+it('does not accept a remote context from a local guest request body', async () => {
+ const manager = fakeManager();
+ const result = await call({ method: 'POST', pathname: '/oauth/acct/connect', body: '{"remote":{"scope":"forged"}}', manager });
+ expect(result.status).toBe(200);
+ expect(manager.connectAccount).toHaveBeenCalledExactlyOnceWith(GHOST, 'acct', DECL, undefined);
+});
diff --git a/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostSecretCheck.test.ts b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostSecretCheck.test.ts
new file mode 100644
index 0000000000..299402a1cc
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostSecretCheck.test.ts
@@ -0,0 +1,110 @@
+import { describe, expect, it, vi } from 'vitest';
+import { checkGhostSecret } from '../ghostSecretCheck.js';
+import { handleGhostSecretsRequest } from '../ghostSecretsEndpoint.js';
+import type { GhostSecretDecl } from '../../../../shared/ghost.js';
+
+const value = 'fake-candidate-never-real';
+const secret: GhostSecretDecl = {
+ key: 'api_key', label: 'API Key', inject: { header: 'Authorization', format: 'Bearer {value}', hosts: ['api.example.com'] },
+ exchange: { url: 'https://api.example.com/token', bodyFormat: '{"key":"{value}"}', tokenPath: 'session' },
+ check: { url: 'https://api.example.com/check', bodyFormat: '{"apiKey":"{value}"}', validPath: 'status', validValue: 'active', expiresAtPath: 'expiresAtMs', expiresAtFormat: 'unix-ms' },
+};
+const ok = (data: unknown) => new Response(JSON.stringify(data), { status: 200 });
+const run = (fetch: typeof globalThis.fetch, isCurrent = () => true, candidate = value) => checkGhostSecret({ instanceKey: 'isolated', secret, value: candidate, isCurrent, fetch });
+
+describe('settings-only credential check', () => {
+ it('exchanges a transient candidate, injects the session, and returns only validity and expiry', async () => {
+ const fetch = vi.fn().mockResolvedValueOnce(ok({ session: 'fake-session-token' }))
+ .mockResolvedValueOnce(ok({ status: 'active', expiresAtMs: 2000000000000, apiKey: value, session: 'fake-session-token', debug: 'private' }));
+ expect(await run(fetch)).toEqual({ status: 200, body: '{"valid":true,"expiresAt":"2033-05-18T03:33:20.000Z"}' });
+ expect(JSON.parse(fetch.mock.calls[0][1].body)).toEqual({ key: value });
+ expect(fetch.mock.calls[1][1].headers.Authorization).toBe('Bearer fake-session-token');
+ expect(JSON.parse(fetch.mock.calls[1][1].body)).toEqual({ apiKey: value });
+ expect(fetch.mock.calls.every(([, init]) => init.redirect === 'manual')).toBe(true);
+ });
+ it('escapes quotes, slashes and replacement characters in both request bodies', async () => {
+ const candidate = 'fake-"\\-$&-key';
+ const fetch = vi.fn().mockResolvedValueOnce(ok({ session: 'fake-token' })).mockResolvedValueOnce(ok({ status: 'invalid' }));
+ expect(await run(fetch, undefined, candidate)).toMatchObject({ status: 200, body: '{"valid":false}' });
+ expect(JSON.parse(fetch.mock.calls[0][1].body).key).toBe(candidate);
+ expect(JSON.parse(fetch.mock.calls[1][1].body).apiKey).toBe(candidate);
+ });
+ it.each([302, 401, 500])('does not follow or expose an exchange failure (%s)', async (status) => {
+ const fetch = vi.fn().mockResolvedValue(new Response(value, { status, headers: { Location: 'https://evil.invalid' } }));
+ expect(await run(fetch)).toEqual({ status: 502, body: '{"error":"SECRET_CHECK_FAILED"}' });
+ expect(fetch).toHaveBeenCalledTimes(1);
+ });
+ it.each([null, { status: { token: value } }, { status: 'active', expiresAtMs: value }])('rejects malformed projections without returning upstream data', async (data) => {
+ const fetch = vi.fn().mockResolvedValueOnce(ok({ session: 'fake-token' })).mockResolvedValueOnce(ok(data));
+ expect((await run(fetch)).status).toBe(502);
+ });
+ it('bounds upstream response bytes', async () => {
+ const fetch = vi.fn().mockResolvedValue(new Response('x'.repeat(65537)));
+ expect((await run(fetch)).status).toBe(502);
+ });
+ it('does not issue the second request after identity changes', async () => {
+ let current = true;
+ const fetch = vi.fn(async () => { current = false; return ok({ session: 'fake-token' }); });
+ expect((await run(fetch, () => current)).status).toBe(403);
+ expect(fetch).toHaveBeenCalledTimes(1);
+ });
+ it('discards late result after identity changes', async () => {
+ let current = true;
+ const fetch = vi.fn().mockResolvedValueOnce(ok({ session: 'fake-token' })).mockImplementationOnce(async () => {
+ current = false; return ok({ status: 'active' });
+ });
+ expect((await run(fetch, () => current)).status).toBe(403);
+ });
+ it('limits concurrent checks and releases the slot after completion', async () => {
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => { release = resolve; });
+ const fetch = vi.fn(async () => { await gate; return ok({ session: 'fake-token', status: 'active' }); });
+ const first = run(fetch), second = run(fetch);
+ expect((await run(fetch)).status).toBe(429);
+ release();
+ expect((await first).status).toBe(200); expect((await second).status).toBe(200);
+ expect((await run(fetch)).status).toBe(200);
+ });
+ it('times out without exposing the fetch error', async () => {
+ vi.useFakeTimers();
+ try {
+ const fetch = vi.fn((_url, init) => new Promise<Response>((_resolve, reject) => {
+ init.signal.addEventListener('abort', () => reject(new Error(value)), { once: true });
+ }));
+ const result = run(fetch);
+ await vi.advanceTimersByTimeAsync(15_000);
+ expect(await result).toEqual({ status: 504, body: '{"error":"SECRET_CHECK_FAILED"}' });
+ } finally { vi.useRealTimers(); }
+ });
+ it('does not dispatch without a declared check', async () => {
+ const fetch = vi.fn();
+ expect(await checkGhostSecret({ instanceKey: 'test', secret: { ...secret, check: undefined }, value, isCurrent: () => true, fetch })).toEqual({ status: 404 });
+ expect(fetch).not.toHaveBeenCalled();
+ });
+});
+
+describe('credential check protocol', () => {
+ const vault = { saved: () => true, tail: () => 'fake', store: vi.fn(), remove: vi.fn() };
+ const checkSecret = vi.fn(async () => ({ status: 200, body: '{"valid":true}' }));
+ const args = { ghostId: 'test', userSecretKeys: ['api_key'], checkSecretKeys: ['api_key'], checkSecret, vault, readBodyText: async () => JSON.stringify({ value }) };
+ it('advertises only declared supported checks', async () => {
+ expect(JSON.parse((await handleGhostSecretsRequest({ ...args, method: 'GET', pathname: '/secrets' })).body!)[0].checkSupported).toBe(true);
+ expect(JSON.parse((await handleGhostSecretsRequest({ ...args, checkSecretKeys: [], method: 'GET', pathname: '/secrets' })).body!)[0]).not.toHaveProperty('checkSupported');
+ });
+ it('checks without storing or deleting the candidate', async () => {
+ expect((await handleGhostSecretsRequest({ ...args, method: 'POST', pathname: '/secrets/api_key/check' })).status).toBe(200);
+ expect(checkSecret).toHaveBeenCalledWith('api_key', value);
+ expect(vault.store).not.toHaveBeenCalled(); expect(vault.remove).not.toHaveBeenCalled();
+ });
+ it('keeps unsupported checks separate from the existing save endpoint', async () => {
+ expect((await handleGhostSecretsRequest({ ...args, checkSecretKeys: [], method: 'POST', pathname: '/secrets/api_key/check' })).status).toBe(404);
+ vault.store.mockReturnValueOnce(true);
+ expect((await handleGhostSecretsRequest({ ...args, checkSecretKeys: [], method: 'PUT', pathname: '/secrets/api_key' })).status).toBe(204);
+ });
+ it('rejects identity change while reading the candidate', async () => {
+ const check = vi.fn(); let current = true;
+ expect((await handleGhostSecretsRequest({ ...args, checkSecret: check, method: 'POST', pathname: '/secrets/api_key/check',
+ isCurrent: () => current, readBodyText: async () => { current = false; return JSON.stringify({ value }); } })).status).toBe(403);
+ expect(check).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostSecretCheckManifest.test.ts b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostSecretCheckManifest.test.ts
new file mode 100644
index 0000000000..9f1b7c4af5
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostSecretCheckManifest.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from 'vitest';
+import { validateGhostManifest as shared } from '@cindy/plugin-protocol';
+import { ghostNetworkAuthorizationWithinCap, validateGhostManifest as desktop } from '../../../../shared/ghost.js';
+const check = { url: 'https://api.example.com/check', bodyFormat: '{"apiKey":"{value}"}', validPath: 'status', validValue: 'active', expiresAtPath: 'expiresAt', expiresAtFormat: 'iso' };
+const manifest = (patch: Record<string, unknown> = {}) => ({ schemaVersion: 2, id: 'test-plugin', name: 'Test', version: '1.0.0', kind: 'chip', entry: 'main.js', slots: ['network'], settingsHtml: 'settings.html', network: { hosts: ['api.example.com', 'other.example.com'], secrets: [{ key: 'api_key', label: 'Key', inject: { header: 'Authorization', format: 'Bearer {value}', hosts: ['api.example.com'] }, ...patch }] } });
+for (const [name, validate] of [['protocol', shared], ['desktop', desktop]] as const) describe(name, () => {
+ it('preserves old manifests without adding a check field', () => {
+ const result = validate(manifest()); expect(result.ok).toBe(true);
+ if (result.ok) expect(result.manifest.network?.secrets?.[0]).not.toHaveProperty('check');
+ });
+ it('preserves the check through normalization', () => {
+ const result = validate(manifest({ check })); expect(result.ok).toBe(true);
+ if (result.ok) { expect(result.manifest.network?.secrets?.[0].check).toEqual(check); }
+ });
+ it.each([
+ { url: 'https://other.example.com/check' }, { url: 'http://api.example.com/check' },
+ { url: 'https://user:[email protected]/check' }, { url: 'https://api.example.com:8443/check' },
+ { bodyFormat: '{"key":{value}}' }, { bodyFormat: '{"key":"{value}","other":"{value}"}' },
+ { validPath: '__proto__.valid' }, { validValue: {} }, { expiresAtFormat: 'raw' },
+ ])('rejects invalid declarations %j', (patch) => expect(validate(manifest({ check: { ...check, ...patch } })).ok).toBe(false));
+ it('rejects managed credentials', () => expect(validate(manifest({ source: 'login-email', check })).ok).toBe(false));
+});
+
+it('enforces the reviewed credential check declaration without affecting old manifests', () => {
+ const old = desktop(manifest()), reviewed = desktop(manifest({ check }));
+ const changed = desktop(manifest({ check: { ...check, url: 'https://api.example.com/other' } }));
+ if (!old.ok || !reviewed.ok || !changed.ok) throw new Error('fixture invalid');
+ expect(ghostNetworkAuthorizationWithinCap(old.manifest, old.manifest)).toBe(true);
+ expect(ghostNetworkAuthorizationWithinCap(reviewed.manifest, reviewed.manifest)).toBe(true);
+ expect(ghostNetworkAuthorizationWithinCap(old.manifest, reviewed.manifest)).toBe(false);
+ expect(ghostNetworkAuthorizationWithinCap(reviewed.manifest, changed.manifest)).toBe(false);
+});
diff --git a/apps/desktop/src/main/cindy-brain/runtime/ghostOauthEndpoint.ts b/apps/desktop/src/main/cindy-brain/runtime/ghostOauthEndpoint.ts
index c1a26f0876..24b15a86c3 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/ghostOauthEndpoint.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/ghostOauthEndpoint.ts
@@ -28,6 +28,7 @@
* 产生的全部令牌只存在主机保险库与内存缓存,本端点没有任何读回动作。
*/
+import { getRemoteOauthContext, type RemoteOauthContext } from '../../plugin-oauth/context.js';
import { GhostKvError } from '../ghostKvStore.js';
import { assertGhostProtocolTargetCurrent, GhostProtocolTargetChangedError } from './ghostProtocolTargetGuard.js';
import { GHOST_SECRET_VALUE_MAX_CHARS } from './ghostSecretsEndpoint.js';
@@ -61,6 +62,8 @@ export interface GhostOauthEndpointManager {
secretKey: string,
decl: GhostOauthDecl,
opts?: {
+ /** Trusted Host transaction context; never supplied by the settings page. */
+ remote?: RemoteOauthContext;
scopes?: readonly string[];
clientId?: string;
deliveryHosts?: readonly string[];
@@ -101,6 +104,8 @@ export async function handleGhostOauthRequest(args: {
}): Promise<GhostOauthRequestOutcome> {
const { method, pathname, readBodyText, oauthSecrets, networkHosts, manager, ghostId: instanceKey, log } =
args;
+ // Capture the validated Host exchange before awaiting any untrusted page body.
+ const remote = getRemoteOauthContext();
if (args.isCurrent?.() === false) return { status: 403 };
const assertCurrent = (): void => assertGhostProtocolTargetCurrent(args.isCurrent);
const runMutation = async <T>(task: () => Promise<T> | T): Promise<T> => {
@@ -287,6 +292,7 @@ export async function handleGhostOauthRequest(args: {
try {
const opts = {
...connectTarget,
+ ...(remote ? { remote } : {}),
...(args.isCurrent ? { assertCurrent } : {}),
...(scopesOverride !== undefined ? { scopes: scopesOverride } : {}),
...(clientIdOverride !== undefined ? { clientId: clientIdOverride } : {}),
diff --git a/apps/desktop/src/main/cindy-brain/runtime/ghostSecretCheck.ts b/apps/desktop/src/main/cindy-brain/runtime/ghostSecretCheck.ts
new file mode 100644
index 0000000000..27248b29a0
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/runtime/ghostSecretCheck.ts
@@ -0,0 +1,103 @@
+import type { GhostSecretDecl } from '../../../shared/ghost.js';
+
+const activeChecks = new Map<string, number>();
+const LIMIT = 64 * 1024;
+function atPath(value: unknown, path: string): unknown {
+ for (const key of path.split('.')) {
+ if (!value || typeof value !== 'object' || Array.isArray(value) || !Object.hasOwn(value, key)) return undefined;
+ value = (value as Record<string, unknown>)[key];
+ }
+ return value;
+}
+async function jsonBody(response: Response): Promise<unknown> {
+ if (!response.body) throw new Error('empty');
+ const reader = response.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let size = 0;
+ try {
+ while (true) {
+ const part = await reader.read();
+ if (part.done) break;
+ size += part.value.byteLength;
+ if (size > LIMIT) throw new Error('large');
+ chunks.push(part.value);
+ }
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
+ } finally { await reader.cancel(); }
+}
+
+/** Candidate checks never write the vault or reuse the network slot's token cache. */
+export async function checkGhostSecret(args: {
+ instanceKey: string;
+ secret: GhostSecretDecl;
+ value: string;
+ isCurrent: () => boolean;
+ fetch: (url: string, init: RequestInit) => Promise<Response>;
+}): Promise<{ status: number; body?: string }> {
+ const { secret, value, isCurrent } = args;
+ if (!secret.check || (secret.source && secret.source !== 'user')) return { status: 404 };
+ if (!isCurrent()) return { status: 403 };
+ if ((activeChecks.get(args.instanceKey) ?? 0) >= 2) return { status: 429 };
+ activeChecks.set(args.instanceKey, (activeChecks.get(args.instanceKey) ?? 0) + 1);
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), 15_000);
+ timer.unref?.();
+ const assertCurrent = () => { if (!isCurrent()) throw new Error('stale'); };
+ const post = async (url: string, body: string, headers: Record<string, string>) => {
+ assertCurrent();
+ const response = await args.fetch(url, { method: 'POST', body, headers, redirect: 'manual', signal: controller.signal });
+ assertCurrent();
+ if (!response.ok) {
+ await response.body?.cancel();
+ throw new Error('upstream');
+ }
+ const result = await jsonBody(response);
+ assertCurrent();
+ return result;
+ };
+ try {
+ let token = value;
+ if (secret.exchange) {
+ const ex = secret.exchange;
+ const contentType = ex.contentType ?? 'application/json';
+ const escaped = contentType === 'application/json' ? JSON.stringify(value).slice(1, -1) : encodeURIComponent(value);
+ const data = await post(ex.url, ex.bodyFormat.replace('{value}', () => escaped), { 'Content-Type': contentType });
+ const exchanged = atPath(data, ex.tokenPath);
+ if (typeof exchanged !== 'string' || !exchanged || exchanged.length > LIMIT || /[\r\n]/.test(exchanged)) throw new Error('token');
+ token = exchanged;
+ }
+ const check = secret.check;
+ const data = await post(check.url, check.bodyFormat.replace('{value}', () => JSON.stringify(value).slice(1, -1)), {
+ 'Content-Type': 'application/json',
+ [secret.inject.header]: secret.inject.format.replace('{value}', () => token),
+ });
+ const valid = atPath(data, check.validPath);
+ if (typeof valid !== typeof check.validValue) throw new Error('shape');
+ const result: { valid: boolean; expiresAt?: string } = { valid: valid === check.validValue };
+ if (check.expiresAtPath) {
+ const expiry = atPath(data, check.expiresAtPath);
+ if (expiry !== undefined && expiry !== null) {
+ let ms: number;
+ if ((check.expiresAtFormat ?? 'iso') === 'iso') {
+ if (typeof expiry !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(expiry)) throw new Error('date');
+ ms = Date.parse(expiry);
+ } else {
+ if (typeof expiry !== 'number' || !Number.isFinite(expiry)) throw new Error('date');
+ ms = expiry * (check.expiresAtFormat === 'unix-seconds' ? 1000 : 1);
+ }
+ if (!Number.isFinite(ms) || ms < 0 || ms > 253402300799999) throw new Error('date');
+ result.expiresAt = new Date(ms).toISOString();
+ }
+ }
+ const body = JSON.stringify(result);
+ if (body.includes(value) || body.includes(token)) throw new Error('reflection');
+ return { status: 200, body };
+ } catch {
+ return { status: !isCurrent() ? 403 : controller.signal.aborted ? 504 : 502,
+ body: JSON.stringify({ error: 'SECRET_CHECK_FAILED' }) };
+ } finally {
+ clearTimeout(timer);
+ const count = (activeChecks.get(args.instanceKey) ?? 1) - 1;
+ if (count) activeChecks.set(args.instanceKey, count); else activeChecks.delete(args.instanceKey);
+ }
+}
diff --git a/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts b/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts
index 2d0cbc3fde..5d216c0433 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts
@@ -90,6 +90,8 @@ export async function handleGhostSecretsRequest(args: {
* 自己有反馈,不额外打扰;DELETE 不报(清除不是值得全局提示的事件)。
*/
onStored?: (secretKey: string) => void;
+ checkSecretKeys?: string[];
+ checkSecret?: (key: string, value: string) => Promise<GhostSecretsRequestOutcome>;
log?: { warn(message: string, meta?: Record<string, unknown>): void };
}): Promise<GhostSecretsRequestOutcome> {
const { method, pathname, readBodyText, userSecretKeys, vault, ghostId: instanceKey, log } = args;
@@ -109,6 +111,7 @@ export async function handleGhostSecretsRequest(args: {
// 指纹只在"确实存了"时给(没存过的键即便留有孤儿指纹也不回)。
const tail = saved ? vault.tail(instanceKey, key) : null;
const hostState = hostCredentialStates.get(key);
+ const checkFields = args.checkSecretKeys?.includes(key) && args.checkSecret ? { checkSupported: true } : {};
const hostFields = hostState
? {
hostSource: hostState.source,
@@ -116,7 +119,7 @@ export async function handleGhostSecretsRequest(args: {
...(hostState.managedSetup ? { hostManagedSetup: true } : {}),
}
: {};
- return tail ? { key, saved, tail, ...hostFields } : { key, saved, ...hostFields };
+ return tail ? { key, saved, tail, ...hostFields, ...checkFields } : { key, saved, ...hostFields, ...checkFields };
});
// 身份凭证:现读登录邮箱只读展示;identityKeys 为空时不碰登录态。
const email = identityKeys.length > 0 ? (args.getLoginEmail?.()?.trim() ?? '') : '';
@@ -135,6 +138,20 @@ export async function handleGhostSecretsRequest(args: {
}
}
+ const checkMatch = /^\/secrets\/([a-z][a-z0-9_]{0,31})\/check$/.exec(pathname);
+ if (checkMatch) {
+ const key = checkMatch[1];
+ if (!userSecretKeys.includes(key) || !args.checkSecretKeys?.includes(key) || !args.checkSecret) return { status: 404 };
+ if (method !== 'POST') return { status: 405 };
+ let input: unknown;
+ try { input = JSON.parse(await readBodyText()); } catch { return { status: 400 }; }
+ const value = input && typeof input === 'object' && !Array.isArray(input) ? (input as { value?: unknown }).value : undefined;
+ if (typeof value !== 'string' || !value.trim()) return { status: 400 };
+ if (value.length > GHOST_SECRET_VALUE_MAX_CHARS) return { status: 413 };
+ if (args.isCurrent?.() === false) return { status: 403 };
+ return args.checkSecret(key, value.trim());
+ }
+
// /secrets/<key>:key 段不再有子路径(带斜杠 = 非法形态,统一 404)。
const secretKey = pathname.slice('/secrets/'.length);
if (!secretKey || secretKey.includes('/')) return { status: 404 };
diff --git a/apps/desktop/src/main/plugin-oauth/context.ts b/apps/desktop/src/main/plugin-oauth/context.ts
index 593d654213..12af86e6e9 100644
--- a/apps/desktop/src/main/plugin-oauth/context.ts
+++ b/apps/desktop/src/main/plugin-oauth/context.ts
@@ -29,6 +29,8 @@ export interface RemoteOauthContext {
submitConnection?(offer: PluginConnectionOffer): Promise<PluginConnectionInput>;
/** 代输入 step values; one signed exchange per step. */
submitInput?(offer: InputHandoffOffer): Promise<InputHandoffSubmission>;
+ /** Original transaction deadline; may shorten when an offer expires sooner. */
+ readonly expiresAt?: number;
cancelled?: AbortSignal;
finish(ok: boolean): void;
}
diff --git a/apps/desktop/src/main/plugin-oauth/transactions.ts b/apps/desktop/src/main/plugin-oauth/transactions.ts
index f8c8df28c8..c520d6a2c5 100644
--- a/apps/desktop/src/main/plugin-oauth/transactions.ts
+++ b/apps/desktop/src/main/plugin-oauth/transactions.ts
@@ -173,6 +173,7 @@ export class OauthTransactions {
scope: t.id,
peer: t.peer,
cancelled: t.lifetime.signal,
+ get expiresAt() { return t.expiresAt; },
assertCurrent: () => this.assertCurrent(t),
authorize: (offer, signal) =>
this.waitForReply(t, {
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 8b222faa57..be008e75d0 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -1,3 +1,4 @@
+import { parseGhostSecretCheck, type GhostSecretCheckDecl } from '@cindy/plugin-protocol';
import { parseGhostRoutineEvents, type GhostRoutineEvents } from '@cindy/plugin-protocol';
import { parseMailReader } from '@cindy/maker-shared/mail-message';
import { parsePluginAuthorizationRequest, type PluginAuthorizationRequest, type PluginAuthorizationResult } from '@cindy/device-link';
@@ -950,6 +951,8 @@ export interface GhostSecretDecl {
inject: GhostSecretInjectDecl;
/** 可选:key 换令牌二段式声明(见 GhostSecretExchangeDecl;与 oauth 互斥)。 */
exchange?: GhostSecretExchangeDecl;
+ /** Optional settings-only credential check; never returns the credential. */
+ check?: GhostSecretCheckDecl;
/** source: 'oauth' 时必填的授权详单(见 GhostSecretOauthDecl);其它来源禁止声明。 */
oauth?: GhostSecretOauthDecl;
/**
@@ -2749,6 +2752,7 @@ export function ghostNetworkAuthorizationWithinCap(
) {
return false;
}
+ if (secret.check !== undefined && JSON.stringify(secret.check) !== JSON.stringify(cap.check)) return false;
if (secret.oauth !== undefined) {
if (!cap.oauth || !ghostOauthAuthorizationWithinCap(cap.oauth, secret.oauth)) return false;
}
@@ -5698,6 +5702,12 @@ function validateGhostManifestInput(value: unknown, preserveHistoricalTasks: boo
...(exTtl !== undefined ? { ttlSeconds: exTtl } : {}),
};
}
+ const check = s.check === undefined ? undefined : parseGhostSecretCheck(s.check,
+ (host) => hosts.some((pattern) => ghostNetworkHostMatches(pattern, host))
+ && (injectHosts ?? hosts).some((pattern) => ghostNetworkHostMatches(pattern, host)));
+ if (s.check !== undefined && (!check || (source !== undefined && source !== 'user'))) {
+ return { ok: false, reason: 'network.secrets[].check requires a user secret, a declared injection host, and a bounded response mapping' };
+ }
secrets.push({
key: s.key,
label: s.label,
@@ -5710,6 +5720,7 @@ function validateGhostManifestInput(value: unknown, preserveHistoricalTasks: boo
...(injectHosts !== undefined ? { hosts: injectHosts } : {}),
},
...(exchange !== undefined ? { exchange } : {}),
+ ...(check ? { check } : {}),
...(oauth !== undefined ? { oauth } : {}),
});
}
diff --git a/apps/mobile/app/(auth)/login.tsx b/apps/mobile/app/(auth)/login.tsx
index a690f8a76a..c8b8412371 100644
--- a/apps/mobile/app/(auth)/login.tsx
+++ b/apps/mobile/app/(auth)/login.tsx
@@ -1138,11 +1138,11 @@ export function LoginScreen({
y={LOGIN_LOADING_RING.yBrowser}
/>
<LoginPrimaryButton
- disabled={auth.isBusy}
label={loginText('cancel')}
onPress={reset}
testID="login.cancelBrowserButton"
/>
+ {errorNode}
</LoginPanel>
);
};
diff --git a/apps/mobile/app/plugin-management-preview.tsx b/apps/mobile/app/plugin-management-preview.tsx
new file mode 100644
index 0000000000..a750c6750d
--- /dev/null
+++ b/apps/mobile/app/plugin-management-preview.tsx
@@ -0,0 +1,253 @@
+import { goBackGuarded } from "@/utils/backGuard";
+import { useState } from "react";
+import { Alert, Platform } from "react-native";
+import { Redirect, useRouter, useLocalSearchParams } from "expo-router";
+import { SafeAreaView } from "react-native-safe-area-context";
+import { MOBILE_VISUAL_MOCK_ENABLED } from "@/config/env";
+import {
+ SimpleStackHeader,
+ simpleScreenSafeAreaEdges,
+} from "@/platform/chrome/SimpleStackHeader";
+import { PluginDetailView } from "@/plugins/PluginDetailView";
+import { PluginManagementMenu } from "@/plugins/PluginManagementMenu";
+import { PluginSettingsCard } from "@/plugins/PluginSettingsCard";
+import { useTheme } from "@/theme";
+import type { HostedRemoteCollectionItem } from "@/device-link/remoteResources";
+import type { PluginDetailModel } from "@/plugins/pluginDetailModel";
+import type { PluginSettingsClientOptions } from "@/plugins/pluginSettingsClient";
+import { PluginNoticePreview } from "@/debug/PluginNoticePreview";
+import assets from "@/debug/pluginSettingsPreviewAssets.json";
+
+// Isolated native visual fixture. No real Host, plugin installation, credentials or authorization.
+export default function PluginManagementPreview() {
+ const { scenario } = useLocalSearchParams<{ scenario?: string }>();
+ const [options] = useState(createSettingsFixture);
+ const demosEnabled = typeof __DEV__ !== "undefined" && __DEV__ && process.env.EXPO_PUBLIC_CINDY_PLUGIN_DEMOS === "1";
+ if (!MOBILE_VISUAL_MOCK_ENABLED && !demosEnabled) return <Redirect href="/" />;
+ if (scenario && !demosEnabled) return <Redirect href="/" />;
+ return scenario ? <PluginNoticePreview scenario={scenario} settingsOptions={options} /> : <Preview />;
+}
+function Preview() {
+ const { colors } = useTheme(),
+ router = useRouter();
+ const [enabled, setEnabled] = useState(true);
+ const [notice, setNotice] = useState(
+ "QA preview · Synthetic Host · No real account",
+ );
+ const [options] = useState(createSettingsFixture);
+ const row: HostedRemoteCollectionItem = {
+ key: "qa-settings",
+ host: { deviceId: "qa-host", deviceName: "QA Mac" },
+ item: {
+ ref: { collectionId: "plugins", kind: "plugin", id: "qa-settings" },
+ revision: "1",
+ display: {
+ title: "Settings Playground",
+ subtitle: "Original plugin settings on your computer",
+ },
+ actions: [],
+ links: [],
+ },
+ };
+ const model: PluginDetailModel = {
+ version: "1.0.0",
+ details: [{ key: "author", title: "Author", value: "QA plugin author" }],
+ description: "Edit your plugin’s original settings, then use it in a task.",
+ taskUsable: true,
+ canUseTasks: enabled,
+ canToggle: true,
+ hasSettings: true,
+ taskPreferences: false,
+ mobileSettings: false,
+ builtin: false,
+ missing: [],
+ expired: [],
+ setupGroups: [],
+ permissions: [
+ {
+ kind: "network",
+ labelKey: "networkHost",
+ title: "Network access",
+ description: "Connect to the service you configure.",
+ },
+ {
+ kind: "network",
+ labelKey: "networkSecret",
+ title: "Account credentials",
+ description: "Stored on the selected computer.",
+ },
+ ],
+ tools: [
+ {
+ name: "Search documents",
+ description: "Search the configured workspace.",
+ },
+ ],
+ };
+ return (
+ <SafeAreaView
+ edges={simpleScreenSafeAreaEdges()}
+ style={{ flex: 1, backgroundColor: colors.surface }}
+ >
+ <SimpleStackHeader
+ title="Settings Playground"
+ onBack={() => goBackGuarded(router)}
+ rightToolbar={
+ Platform.OS === "ios" ? (
+ <PluginManagementMenu
+ nativeToolbar
+ actions={[
+ { id: "update", title: "Update · 2.0.0" },
+ { id: "uninstall", title: "Uninstall", destructive: true },
+ ]}
+ onAction={(action) =>
+ Alert.alert(
+ "QA only",
+ action === "update"
+ ? "Update selected"
+ : "Uninstall selected",
+ )
+ }
+ />
+ ) : undefined
+ }
+ right={
+ Platform.OS === "ios" ? undefined : (
+ <PluginManagementMenu
+ actions={[
+ { id: "update", title: "Update · 2.0.0" },
+ { id: "uninstall", title: "Uninstall", destructive: true },
+ ]}
+ onAction={(action) =>
+ Alert.alert(
+ "QA only",
+ action === "update"
+ ? "Update selected"
+ : "Uninstall selected",
+ )
+ }
+ />
+ )
+ }
+ />
+ <PluginDetailView
+ row={row}
+ enabled={enabled}
+ busy={false}
+ online
+ model={model}
+ settingsOpen={false}
+ onEnabledChange={setEnabled}
+ onOpen={() => {}}
+ onResolveStatus={() => {}}
+ onNewTask={() => Alert.alert("QA only", "New task selected")}
+ onChooseTask={() => Alert.alert("QA only", "Existing task selected")}
+ previewLabel={notice}
+ settingsContent={
+ <PluginSettingsCard
+ {...options}
+ active
+ generation="qa"
+ onNotice={setNotice}
+ onLoading={(loading) =>
+ setNotice(
+ loading ? "QA settings loading" : "QA settings resources ready",
+ )
+ }
+ onError={(error) => setNotice("QA: " + error.message)}
+ onConfirm={async () => false}
+ onDirectory={async () => null}
+ />
+ }
+ />
+ </SafeAreaView>
+ );
+}
+function createSettingsFixture(): PluginSettingsClientOptions {
+ let preferences = {
+ displayLabel: "QA Mac",
+ notifications: true,
+ language: "en",
+ lastField: "Long form field",
+ };
+ let saved = false;
+ let accounts = [
+ { id: "one", label: "Test account one", isDefault: true },
+ { id: "two", label: "Test account two", isDefault: false },
+ ];
+ const files = Object.entries(assets).map(([path, text]) => ({
+ path,
+ size: new TextEncoder().encode(text).length,
+ mime: path.endsWith("html") ? "text/html" : "application/javascript",
+ }));
+ const document = {
+ pageId: "qa-page",
+ pluginId: "qa-settings",
+ manifestId: "qa-settings",
+ name: "QA settings",
+ entry: "settings.html",
+ files,
+ };
+ return {
+ identity: {
+ deviceId: "qa-host",
+ instanceId: "qa-settings",
+ expectedInstalledApproval: "legacy-unapproved",
+ },
+ assertCurrent() {},
+ invokeTarget: async () => ({ result: document }),
+ openSession: async () => ({
+ dispose() {},
+ request: async (raw) => {
+ if (raw.op !== "settings") throw new Error("QA_ONLY");
+ const c = raw.command;
+ if (c.kind === "asset") {
+ const text = assets[c.path as keyof typeof assets];
+ const bytes = new TextEncoder()
+ .encode(text)
+ .slice(c.offset, c.offset + 48 * 1024);
+ return {
+ base64: btoa(
+ Array.from(bytes, (byte) => String.fromCharCode(byte)).join(""),
+ ),
+ mime: files.find((file) => file.path === c.path)!.mime,
+ };
+ }
+ if (c.kind === "poll")
+ return {
+ events: [],
+ confirms: [],
+ notifications: [],
+ directories: [],
+ };
+ if (c.kind !== "fetch") return {};
+ let body: unknown;
+ if (c.path === "/kv") {
+ if (c.method === "PUT") preferences = JSON.parse(c.body ?? "{}");
+ body = preferences;
+ } else if (c.path === "/secrets/key" && c.method === "PUT") {
+ saved = true;
+ return { status: 204, mime: "application/json", base64: "" };
+ } else if (c.path === "/secrets") body = [{ key: "key", saved }];
+ else if (c.path === "/oauth/login/default") {
+ const id = JSON.parse(c.body ?? "{}").accountId;
+ accounts = accounts.map((account) => ({
+ ...account,
+ isDefault: account.id === id,
+ }));
+ body = { ok: true };
+ } else if (c.path === "/oauth") body = [{ key: "login", accounts }];
+ else return { status: 400, mime: "application/json", base64: "e30=" };
+ return {
+ status: 200,
+ mime: "application/json",
+ base64: btoa(
+ String.fromCharCode(
+ ...new TextEncoder().encode(JSON.stringify(body)),
+ ),
+ ),
+ };
+ },
+ }),
+ };
+}
diff --git a/apps/mobile/modules/cindy-plugin-oauth/android/build.gradle b/apps/mobile/modules/cindy-plugin-oauth/android/build.gradle
new file mode 100644
index 0000000000..30cdf34bab
--- /dev/null
+++ b/apps/mobile/modules/cindy-plugin-oauth/android/build.gradle
@@ -0,0 +1,10 @@
+plugins {
+ id 'com.android.library'
+ id 'expo-module-gradle-plugin'
+}
+group = 'expo.modules.cindypluginoauth'
+version = '1.0.0'
+android {
+ namespace 'expo.modules.cindypluginoauth'
+ defaultConfig { versionCode 1; versionName '1.0.0' }
+}
diff --git a/apps/mobile/modules/cindy-plugin-oauth/android/src/main/AndroidManifest.xml b/apps/mobile/modules/cindy-plugin-oauth/android/src/main/AndroidManifest.xml
new file mode 100644
index 0000000000..f14571084e
--- /dev/null
+++ b/apps/mobile/modules/cindy-plugin-oauth/android/src/main/AndroidManifest.xml
@@ -0,0 +1 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"><uses-permission android:name="android.permission.INTERNET" /></manifest>
diff --git a/apps/mobile/modules/cindy-plugin-oauth/android/src/main/java/expo/modules/cindypluginoauth/CindyPluginOauthModule.kt b/apps/mobile/modules/cindy-plugin-oauth/android/src/main/java/expo/modules/cindypluginoauth/CindyPluginOauthModule.kt
new file mode 100644
index 0000000000..1941e166dc
--- /dev/null
+++ b/apps/mobile/modules/cindy-plugin-oauth/android/src/main/java/expo/modules/cindypluginoauth/CindyPluginOauthModule.kt
@@ -0,0 +1,151 @@
+package expo.modules.cindypluginoauth
+
+import expo.modules.kotlin.modules.Module
+import expo.modules.kotlin.modules.ModuleDefinition
+import expo.modules.kotlin.Promise
+import java.net.InetAddress
+import java.net.InetSocketAddress
+import java.net.ServerSocket
+import java.net.Socket
+import java.net.URI
+import java.net.URLDecoder
+import java.util.concurrent.Executors
+import java.util.concurrent.TimeUnit
+
+class CindyPluginOauthModule : Module() {
+ private val listeners = mutableMapOf<String, CallbackListener>()
+ override fun definition() = ModuleDefinition {
+ Name("CindyPluginOauth")
+ AsyncFunction("start") { options: Map<String, Any> -> synchronized(listeners) {
+ require(listeners.isEmpty()) { "PLUGIN_OAUTH_LISTEN_FAILED" }
+ val id = options["id"] as? String ?: error("PLUGIN_OAUTH_LISTEN_FAILED")
+ val receiver = CallbackListener(options)
+ listeners[id] = receiver
+ receiver.start()
+ } }
+ AsyncFunction("wait") { id: String, promise: Promise -> synchronized(listeners) {
+ val listener = listeners[id]
+ if (listener == null) promise.reject("PLUGIN_OAUTH_CLOSED", "Authorization listener is closed", null)
+ else listener.waitForCallback(promise)
+ } }
+ AsyncFunction("status") { id: String -> synchronized(listeners) { listeners[id]?.status() ?: "closed" } }
+ AsyncFunction("close") { id: String -> synchronized(listeners) { listeners.remove(id)?.close(); Unit } }
+ OnDestroy { synchronized(listeners) { listeners.values.forEach { it.close() }; listeners.clear() } }
+ }
+}
+
+private class CallbackListener(options: Map<String, Any>) {
+ private val state = options["state"] as? String ?: ""
+ private val expiresAt = (options["expiresAt"] as? Number)?.toLong() ?: 0
+ private val callback = URI(options["callbackUrl"] as? String ?: "")
+ private val host = "127.0.0.1:${callback.port}"
+ private val socket = ServerSocket()
+ // Expiry must run even while the socket worker is reading a partial request.
+ private val worker = Executors.newScheduledThreadPool(2)
+ private var activeClient: Socket? = null
+ private var pending: Promise? = null
+ private var result: Map<String, String>? = null
+ private var closed = false
+ private var consumed = false
+ init {
+ val id = options["id"] as? String ?: ""
+ val now = System.currentTimeMillis()
+ require(id.matches(Regex("^[A-Za-z0-9_-]{16,128}$")) && state.matches(Regex("^[A-Za-z0-9._~-]{16,512}$")))
+ require(expiresAt > now && expiresAt <= now + 600000)
+ require(callback.scheme == "http" && callback.host == "127.0.0.1" && callback.port in 1024..65535)
+ require(callback.rawUserInfo == null && callback.rawQuery == null && callback.rawFragment == null)
+ require(callback.rawPath.length <= 256 && callback.rawPath.matches(Regex("^/[A-Za-z0-9._~/-]*$")))
+ require(callback.toString() == "http://$host${callback.rawPath}")
+ try {
+ socket.reuseAddress = false
+ socket.bind(InetSocketAddress(InetAddress.getByName("127.0.0.1"), callback.port), 8)
+ socket.soTimeout = 1000
+ } catch (error: Exception) { socket.close(); worker.shutdownNow(); throw error }
+ }
+ fun start() {
+ worker.schedule({ close() }, (expiresAt - System.currentTimeMillis()).coerceAtLeast(1), TimeUnit.MILLISECONDS)
+ worker.execute {
+ while (status() == "waiting") {
+ if (System.currentTimeMillis() >= expiresAt) { close(); break }
+ try {
+ socket.accept().use { client ->
+ synchronized(this) {
+ if (closed) return@use
+ activeClient = client
+ }
+ try {
+ val readDeadline = minOf(expiresAt, System.currentTimeMillis() + 5000)
+ val input = client.getInputStream()
+ val bytes = java.io.ByteArrayOutputStream()
+ var complete = false
+ while (bytes.size() < 16384) {
+ val remaining = readDeadline - System.currentTimeMillis()
+ if (remaining <= 0) break
+ client.soTimeout = remaining.coerceAtMost(5000).toInt()
+ val b = input.read(); if (b < 0) break
+ bytes.write(b)
+ val data = bytes.toByteArray()
+ if (data.size >= 4 && data.takeLast(4) == listOf<Byte>(13, 10, 13, 10)) { complete = true; break }
+ }
+ val value = if (complete) parse(bytes.toString("UTF-8")) else null
+ val accepted = synchronized(this) {
+ if (value != null && !closed && result == null && System.currentTimeMillis() < expiresAt) {
+ result = value; socket.close(); true
+ } else false
+ }
+ val body = if (accepted) "Authorization received. Return to Cindy." else "Invalid callback."
+ val response = "HTTP/1.1 ${if (accepted) "200 OK" else "400 Bad Request"}\r\nContent-Type: text/plain; charset=utf-8\r\nCache-Control: no-store\r\nContent-Security-Policy: default-src 'none'\r\nConnection: close\r\nContent-Length: ${body.toByteArray().size}\r\n\r\n$body"
+ // Deliver the HTTP response before JS can close the accepted connection.
+ try { client.getOutputStream().write(response.toByteArray()) }
+ finally {
+ synchronized(this) {
+ if (accepted && !closed) { pending?.let { consumed = true; it.resolve(result) }; pending = null }
+ }
+ }
+ } finally {
+ synchronized(this) { if (activeClient === client) activeClient = null }
+ }
+ }
+ } catch (_: Exception) { /* Invalid/closed sockets never disclose request bytes. */ }
+ }
+ worker.shutdown()
+ }
+ }
+ @Synchronized fun status() = if (result != null) "received" else if (closed) "closed" else "waiting"
+ @Synchronized fun waitForCallback(promise: Promise) {
+ if (consumed || pending != null || (closed && result == null)) promise.reject("PLUGIN_OAUTH_CLOSED", "Authorization listener is closed", null)
+ else if (result != null) { consumed = true; promise.resolve(result) }
+ else pending = promise
+ }
+ @Synchronized fun close() {
+ closed = true; socket.close(); activeClient?.close(); activeClient = null; worker.shutdownNow()
+ pending?.reject("PLUGIN_OAUTH_CLOSED", "Authorization listener is closed", null); pending = null; result = null
+ }
+ private fun parse(text: String): Map<String, String>? = try {
+ val lines = text.split("\r\n")
+ val request = lines[0].split(' ')
+ require(request.size == 3 && request[0] == "GET" && request[2] in listOf("HTTP/1.0", "HTTP/1.1"))
+ require(request[1].length <= 8192 && request[1].startsWith(callback.rawPath + "?"))
+ val url = URI("http://$host${request[1]}")
+ require(url.rawPath == callback.rawPath && url.rawFragment == null)
+ val headers = mutableMapOf<String, String>()
+ lines.drop(1).filter { it.isNotEmpty() }.forEach {
+ val colon = it.indexOf(':'); require(colon > 0)
+ val key = it.substring(0, colon).lowercase(); require(!headers.containsKey(key))
+ headers[key] = it.substring(colon + 1).trim()
+ }
+ require(headers["host"] == host && !headers.containsKey("origin") && !headers.containsKey("transfer-encoding"))
+ require(headers["content-length"] == null || headers["content-length"] == "0")
+ val params = mutableMapOf<String, String>()
+ (url.rawQuery ?: "").split('&').forEach {
+ val pieces = it.split('=', limit = 2); require(pieces.size == 2)
+ val key = URLDecoder.decode(pieces[0], "UTF-8"); val value = URLDecoder.decode(pieces[1], "UTF-8")
+ require(!params.containsKey(key) && value.toByteArray().size <= 4096); params[key] = value
+ }
+ require(params["state"] == state && (params.containsKey("code") != params.containsKey("error")))
+ val key = if (params.containsKey("code")) "code" else "error"
+ val value = requireNotNull(params[key]); require(value.isNotEmpty() && value.none { it.code < 32 })
+ require(key != "error" || value.matches(Regex("^[A-Za-z0-9_.-]{1,128}$")))
+ mapOf("state" to state, key to value)
+ } catch (_: Exception) { null }
+}
diff --git a/apps/mobile/modules/cindy-plugin-oauth/expo-module.config.json b/apps/mobile/modules/cindy-plugin-oauth/expo-module.config.json
new file mode 100644
index 0000000000..ebf118817c
--- /dev/null
+++ b/apps/mobile/modules/cindy-plugin-oauth/expo-module.config.json
@@ -0,0 +1 @@
+{"platforms":["apple","android"],"apple":{"modules":["CindyPluginOauthModule"]},"android":{"modules":["expo.modules.cindypluginoauth.CindyPluginOauthModule"]}}
diff --git a/apps/mobile/modules/cindy-plugin-oauth/ios/CindyPluginOauth.podspec b/apps/mobile/modules/cindy-plugin-oauth/ios/CindyPluginOauth.podspec
new file mode 100644
index 0000000000..d52ccc42cf
--- /dev/null
+++ b/apps/mobile/modules/cindy-plugin-oauth/ios/CindyPluginOauth.podspec
@@ -0,0 +1,17 @@
+Pod::Spec.new do |s|
+ s.name = 'CindyPluginOauth'
+ s.version = '1.0.0'
+ s.summary = 'In-memory plugin OAuth loopback receiver'
+ s.description = 'Receives one phone-controlled OAuth callback without token exchange or persistence.'
+ s.author = 'Cindy'
+ s.license = { :type => 'Apache-2.0', :file => '../../../../../LICENSE' }
+ s.homepage = 'https://github.com/makecindy/cindy'
+ s.platforms = { :ios => '16.4' }
+ s.source = { git: 'https://github.com/makecindy/cindy.git' }
+ s.swift_version = '5.9'
+ s.frameworks = 'Network'
+ s.static_framework = true
+ s.dependency 'ExpoModulesCore'
+ s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
+ s.source_files = '**/*.{h,m,mm,swift,hpp,cpp}'
+end
diff --git a/apps/mobile/modules/cindy-plugin-oauth/ios/CindyPluginOauthModule.swift b/apps/mobile/modules/cindy-plugin-oauth/ios/CindyPluginOauthModule.swift
new file mode 100644
index 0000000000..bf22c627d3
--- /dev/null
+++ b/apps/mobile/modules/cindy-plugin-oauth/ios/CindyPluginOauthModule.swift
@@ -0,0 +1,161 @@
+import ExpoModulesCore
+import Network
+
+struct PluginOauthListenerOptions: Record {
+ @Field var id: String = ""
+ @Field var callbackUrl: String = ""
+ @Field var state: String = ""
+ @Field var expiresAt: Double = 0
+}
+
+public class CindyPluginOauthModule: Module {
+ private let queue = DispatchQueue(label: "cindy.plugin-oauth")
+ private var listeners: [String: PluginOauthListener] = [:]
+ public func definition() -> ModuleDefinition {
+ Name("CindyPluginOauth")
+ AsyncFunction("start") { (options: PluginOauthListenerOptions, promise: Promise) in
+ do {
+ guard self.listeners.isEmpty else { throw PluginOauthListener.Failure.invalid }
+ let listener = try PluginOauthListener(options, queue: self.queue)
+ self.listeners[options.id] = listener
+ listener.start { ok in
+ if ok { promise.resolve(nil) }
+ else {
+ self.listeners.removeValue(forKey: options.id)?.close()
+ promise.reject("PLUGIN_OAUTH_LISTEN_FAILED", "Unable to bind callback listener")
+ }
+ }
+ } catch { promise.reject("PLUGIN_OAUTH_LISTEN_FAILED", "Unable to bind callback listener") }
+ }.runOnQueue(queue)
+ AsyncFunction("wait") { (id: String, promise: Promise) in
+ guard let listener = self.listeners[id] else {
+ promise.reject("PLUGIN_OAUTH_CLOSED", "Authorization listener is closed"); return
+ }
+ listener.wait(promise)
+ }.runOnQueue(queue)
+ AsyncFunction("status") { (id: String) -> String in self.listeners[id]?.status() ?? "closed" }.runOnQueue(queue)
+ AsyncFunction("close") { (id: String) in self.listeners.removeValue(forKey: id)?.close() }.runOnQueue(queue)
+ OnDestroy { self.queue.async { self.closeAll() } }
+ }
+ private func closeAll() {
+ let active = listeners.values
+ listeners.removeAll()
+ active.forEach { $0.close() }
+ }
+}
+
+private final class PluginOauthListener {
+ enum Failure: Error { case invalid }
+ private let listener: NWListener
+ private let queue: DispatchQueue
+ private let options: PluginOauthListenerOptions
+ private let path: String
+ private let host: String
+ private var clients: [UUID: NWConnection] = [:]
+ private var pending: Promise?
+ private var result: [String: String]?
+ private var closed = false
+ private var consumed = false
+ private var deadline: DispatchWorkItem?
+ init(_ options: PluginOauthListenerOptions, queue: DispatchQueue) throws {
+ let now = Date().timeIntervalSince1970 * 1000
+ guard options.id.range(of: "^[A-Za-z0-9_-]{16,128}$", options: .regularExpression) != nil,
+ options.state.range(of: "^[A-Za-z0-9._~-]{16,512}$", options: .regularExpression) != nil,
+ options.expiresAt > now, options.expiresAt <= now + 600_000,
+ let url = URLComponents(string: options.callbackUrl), url.scheme == "http", url.host == "127.0.0.1",
+ let port = url.port, (1024...65535).contains(port), url.user == nil, url.password == nil,
+ url.query == nil, url.fragment == nil, url.path.utf8.count <= 256,
+ url.path.range(of: "^/[A-Za-z0-9._~/-]*$", options: .regularExpression) != nil,
+ options.callbackUrl == "http://127.0.0.1:\(port)\(url.path)"
+ else { throw Failure.invalid }
+ self.options = options; self.queue = queue; path = url.path; host = "127.0.0.1:\(port)"
+ let parameters = NWParameters.tcp
+ parameters.allowLocalEndpointReuse = false
+ parameters.requiredLocalEndpoint = .hostPort(host: .ipv4(.loopback), port: NWEndpoint.Port(rawValue: UInt16(port))!)
+ listener = try NWListener(using: parameters)
+ }
+ func start(_ ready: @escaping (Bool) -> Void) {
+ var settled = false
+ listener.stateUpdateHandler = { state in
+ if !settled {
+ if case .ready = state { settled = true; ready(true) }
+ else if case .failed = state { settled = true; ready(false) }
+ else if case .cancelled = state { settled = true; ready(false) }
+ }
+ }
+ listener.newConnectionHandler = { [weak self] connection in
+ guard let self, !self.closed, self.result == nil, self.clients.count < 8 else { connection.cancel(); return }
+ let id = UUID(); self.clients[id] = connection
+ connection.start(queue: self.queue)
+ self.queue.asyncAfter(deadline: .now() + 5) { [weak self] in self?.clients.removeValue(forKey: id)?.cancel() }
+ self.receive(id, Data())
+ }
+ let timeout = DispatchWorkItem { [weak self] in self?.close() }
+ deadline = timeout
+ queue.asyncAfter(deadline: .now() + max(0, (options.expiresAt - Date().timeIntervalSince1970 * 1000) / 1000), execute: timeout)
+ listener.start(queue: queue)
+ }
+ func status() -> String { result != nil ? "received" : closed ? "closed" : "waiting" }
+ func wait(_ promise: Promise) {
+ guard !consumed, pending == nil else { promise.reject("PLUGIN_OAUTH_CLOSED", "Authorization listener is closed"); return }
+ if let result { consumed = true; promise.resolve(result) }
+ else if closed { promise.reject("PLUGIN_OAUTH_CLOSED", "Authorization listener is closed") }
+ else { pending = promise }
+ }
+ func close() {
+ closed = true; deadline?.cancel(); listener.cancel()
+ clients.values.forEach { $0.cancel() }; clients.removeAll()
+ pending?.reject("PLUGIN_OAUTH_CLOSED", "Authorization listener is closed"); pending = nil
+ result = nil
+ }
+ private func receive(_ id: UUID, _ previous: Data) {
+ clients[id]?.receive(minimumIncompleteLength: 1, maximumLength: 4096) { [weak self] data, _, ended, error in
+ guard let self, !self.closed, self.result == nil else { return }
+ var bytes = previous; if let data { bytes.append(data) }
+ if bytes.count > 16384 { self.respond(id, status: 400); return }
+ if let boundary = bytes.range(of: Data("\r\n\r\n".utf8)) {
+ guard boundary.upperBound == bytes.endIndex, let text = String(data: bytes, encoding: .utf8),
+ let value = self.parse(text) else { self.respond(id, status: 400); return }
+ self.result = value
+ self.listener.cancel()
+ self.respond(id, status: 200)
+ for other in Array(self.clients.keys) where other != id { self.clients.removeValue(forKey: other)?.cancel() }
+ if let pending = self.pending { self.consumed = true; self.pending = nil; pending.resolve(value) }
+ } else if ended || error != nil { self.clients.removeValue(forKey: id)?.cancel() }
+ else { self.receive(id, bytes) }
+ }
+ }
+ private func parse(_ text: String) -> [String: String]? {
+ guard Date().timeIntervalSince1970 * 1000 < options.expiresAt else { return nil }
+ let lines = text.components(separatedBy: "\r\n")
+ let request = (lines.first ?? "").split(separator: " ", omittingEmptySubsequences: false)
+ guard request.count == 3, request[0] == "GET", ["HTTP/1.1", "HTTP/1.0"].contains(String(request[2])),
+ request[1].utf8.count <= 8192, request[1].hasPrefix(path + "?"),
+ let url = URLComponents(string: "http://" + host + String(request[1])), url.path == path, url.fragment == nil
+ else { return nil }
+ var headers: [String: String] = [:]
+ for line in lines.dropFirst() where !line.isEmpty {
+ guard let colon = line.firstIndex(of: ":") else { return nil }
+ let name = line[..<colon].lowercased()
+ guard headers[name] == nil else { return nil }
+ headers[name] = line[line.index(after: colon)...].trimmingCharacters(in: .whitespaces)
+ }
+ guard headers["host"] == host, headers["origin"] == nil, headers["transfer-encoding"] == nil,
+ headers["content-length"] == nil || headers["content-length"] == "0" else { return nil }
+ var params: [String: String] = [:]
+ for item in url.queryItems ?? [] {
+ guard params[item.name] == nil, let value = item.value, value.utf8.count <= 4096 else { return nil }
+ params[item.name] = value
+ }
+ guard params["state"] == options.state, (params["code"] != nil) != (params["error"] != nil) else { return nil }
+ let key = params["code"] != nil ? "code" : "error"
+ guard let value = params[key], !value.isEmpty, !value.unicodeScalars.contains(where: { $0.value < 32 }) else { return nil }
+ if key == "error", value.range(of: "^[A-Za-z0-9_.-]{1,128}$", options: .regularExpression) == nil { return nil }
+ return ["state": options.state, key: value]
+ }
+ private func respond(_ id: UUID, status: Int) {
+ let body = status == 200 ? "Authorization received. Return to Cindy." : "Invalid callback."
+ let response = "HTTP/1.1 \(status) \(status == 200 ? "OK" : "Bad Request")\r\nContent-Type: text/plain; charset=utf-8\r\nCache-Control: no-store\r\nContent-Security-Policy: default-src 'none'\r\nConnection: close\r\nContent-Length: \(body.utf8.count)\r\n\r\n\(body)"
+ clients[id]?.send(content: Data(response.utf8), completion: .contentProcessed { [weak self] _ in self?.clients.removeValue(forKey: id)?.cancel() })
+ }
+}
diff --git a/apps/mobile/src/__tests__/pluginAuthorizationLoopback.test.ts b/apps/mobile/src/__tests__/pluginAuthorizationLoopback.test.ts
new file mode 100644
index 0000000000..ab754f4b70
--- /dev/null
+++ b/apps/mobile/src/__tests__/pluginAuthorizationLoopback.test.ts
@@ -0,0 +1,57 @@
+import { afterEach, expect, it, vi } from "vitest";
+import { runMobilePluginAuthorization } from "../plugins/pluginAuthorizationController";
+const h = vi.hoisted(() => ({ offer: {} as any, sealed: [] as any[] }));
+vi.mock("../plugins/pluginOauthCrypto", () => ({ MobileOauthBox: class {
+ publicKey = "a".repeat(59);
+ async open() { return h.offer; }
+ async seal(_peer: string, _id: string, _purpose: string, value: unknown) { h.sealed.push(value); return "a".repeat(60); }
+ dispose() {}
+} }));
+const bridgeState = "b".repeat(43), providerState = "provider-state-123456789";
+const url = (state: string) => "https://accounts.example.com/authorize?" + new URLSearchParams({ state, redirect_uri: "http://127.0.0.1:57123/callback", response_type: "code", client_id: "synthetic-client", code_challenge: "c".repeat(43), code_challenge_method: "S256" });
+function harness(typed: boolean) {
+ const state = typed ? providerState : bridgeState;
+ h.offer = typed ? { kind: "authorization", state: bridgeState, request: { kind: "loopback", url: url(state), callbackUrl: "http://127.0.0.1:57123/callback", state } } : { authorizeUrl: url(state), callbackUrl: "http://127.0.0.1:57123/callback", state, corsHosts: [], corsOrigins: [] };
+ let delivered = false, foreground = true;
+ const invoke = vi.fn(async (request: any): Promise<any> => {
+ if (request.op === "capabilities") return { version: 1, encrypted: true, callback: "desktop-loopback", authorizationV1: true };
+ if (request.op === "start") return { id: "transaction123456", publicKey: "a".repeat(59) };
+ if (request.op === "status") { expect(foreground).toBe(true); return delivered ? { phase: "succeeded" } : { phase: "authorizing", offer: "sealed" }; }
+ if (request.op === "callback") { expect(foreground).toBe(true); delivered = true; return { accepted: true }; }
+ return {};
+ });
+ const receiveLoopback = vi.fn(async (_request: any, _expiresAt: number, _signal: AbortSignal) => ({ state, code: "synthetic-code" }));
+ const deps = { action: {} as any, crypto: {} as any, kind: "oauth" as const, invoke, assertCurrent: vi.fn(), clearInput: vi.fn(), pause: async () => {}, isForeground: () => foreground, showAuthorization: vi.fn(), receiveLoopback };
+ return { deps, invoke, receiveLoopback, foreground(value: boolean) { foreground = value; } };
+}
+afterEach(() => { h.sealed = []; vi.useRealTimers(); });
+it.each([true, false])("seals the correct bridge callback and waits for Host success (typed=%s)", async (typed) => {
+ const test = harness(typed);
+ await runMobilePluginAuthorization(test.deps);
+ expect(h.sealed).toEqual([{ state: bridgeState, code: "synthetic-code" }]);
+ expect(test.receiveLoopback.mock.calls[0][0]).toMatchObject({ state: typed ? providerState : bridgeState });
+ expect(test.invoke.mock.calls.some(([request]) => request.op === "cancel")).toBe(false);
+});
+it("does not poll or submit while Android CustomTabs is background, then submits on foreground", async () => {
+ vi.useFakeTimers();
+ const test = harness(false);
+ test.receiveLoopback.mockImplementation(async () => {
+ test.foreground(false);
+ setTimeout(() => test.foreground(true), 750);
+ return { state: bridgeState, code: "synthetic-code" };
+ });
+ const authorization = runMobilePluginAuthorization(test.deps);
+ await vi.advanceTimersByTimeAsync(500);
+ expect(h.sealed).toEqual([]);
+ expect(test.invoke.mock.calls.some(([request]) => request.op === "callback")).toBe(false);
+ await vi.advanceTimersByTimeAsync(500);
+ await authorization;
+ expect(h.sealed).toEqual([{ state: bridgeState, code: "synthetic-code" }]);
+});
+it("never claims success when the Host rejects the sealed callback", async () => {
+ const test = harness(false);
+ const invoke = test.deps.invoke;
+ test.deps.invoke = vi.fn(async (request: any) => request.op === "callback" ? { accepted: false } : invoke(request));
+ await expect(runMobilePluginAuthorization(test.deps)).rejects.toThrow("OAUTH_BRIDGE_UNAVAILABLE");
+ expect(test.invoke.mock.calls.some(([request]) => request.op === "cancel")).toBe(true);
+});
diff --git a/apps/mobile/src/__tests__/pluginDetailModel.test.ts b/apps/mobile/src/__tests__/pluginDetailModel.test.ts
index 371d42d1fe..48c7d39244 100644
--- a/apps/mobile/src/__tests__/pluginDetailModel.test.ts
+++ b/apps/mobile/src/__tests__/pluginDetailModel.test.ts
@@ -156,12 +156,12 @@ describe("minimal plugin detail state", () => {
status: "setupRequired",
statusAction: "settings",
hasSettings: true,
- canUseTasks: false,
+ canUseTasks: true,
missing: ["API key"],
expired: ["Account"],
});
});
- it("never treats an unknown assessment as ready", () => {
+ it("keeps task entry available without treating an unknown assessment as ready", () => {
expect(
pluginDetailModel(
row(),
@@ -175,7 +175,7 @@ describe("minimal plugin detail state", () => {
).toMatchObject({
status: "setupUnknown",
statusAction: "retry",
- canUseTasks: false,
+ canUseTasks: true,
});
});
it("does not advertise tasks for page-only plugins or confuse a crash with disabled", () => {
diff --git a/apps/mobile/src/__tests__/pluginManagement.test.ts b/apps/mobile/src/__tests__/pluginManagement.test.ts
new file mode 100644
index 0000000000..1dfad604a3
--- /dev/null
+++ b/apps/mobile/src/__tests__/pluginManagement.test.ts
@@ -0,0 +1,276 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { getMobileAuthOwner, setMobileAuthOwner } from '@/auth/authOwnerGeneration';
+import { createPluginManagementClient, type PluginManagementInvoke } from '@/plugins/pluginManagementClient';
+import { createPluginManagementController } from '@/plugins/pluginManagementController';
+import { isBoundedPluginResponse, parsePluginManagementDetail, parsePluginManagementReceipt,
+ parsePluginManagementSnapshot, marketItemMatchesPlugin, type ManagedPlugin,
+ type ManagedMarketDetail, type PluginManagementReceipt, type PluginManagementSnapshot } from '@/plugins/pluginManagementTypes';
+
+vi.mock('expo-crypto', () => ({ randomUUID: () => 'operation-1' }));
+
+/* 测试价值
+ * 生产入口:mobile management client/controller;观察 Host 请求、确认、未知结果与当前设备事实。
+ * 依据:plugin-security-and-authoring §1.1 安装身份,remote-and-mobile-adaptation 故障半径/不重放。
+ * 缺口:已有 pluginClient/page 测试没有管理事务;Desktop 测试不经过手机版 owner/队列 fence。
+ * 最小失败输入:begin 丢回执、同物理键更换批准、排队后切设备/账号/离线;tier: unit(内存 Host、假时钟)。
+ * 实测耗时:定向两文件 Vitest 0.989s(本文件测试 496ms);无真实网络/插件/凭证。
+ */
+const manifest = { schemaVersion: 3 as const, id: 'demo', name: 'Demo', version: '2', kind: 'chip' };
+const plugin: ManagedPlugin = { instanceKey: '_root__demo', namespace: null, manifest: { ...manifest, version: '1' },
+ enabled: true, approval: { state: 'approved', revision: '12345678-1234-4123-8123-123456789abc' } };
+const detail: ManagedMarketDetail = { pluginId: 'market/demo', ghostId: 'demo', namespace: null, name: 'Demo',
+ description: null, author: null, scope: 'public', organizationId: null, defaultInstall: false,
+ releaseId: 'release-2', version: '2', publishedAt: '', icon: null, installState: 'update-available',
+ enabled: true, sourceType: 'server', sourceMarketName: null, manifest };
+const snapshot = (ghosts: ManagedPlugin[] = [plugin]): PluginManagementSnapshot => ({ version: 1, ghosts,
+ market: { items: [detail], unavailableReason: null, customSourceNames: [], unavailableCustomSourceNames: [] } });
+const receipt = (phase: PluginManagementReceipt['phase'] = 'running'): PluginManagementReceipt => ({ operationId: 'operation-1', phase });
+const confirmation = (): PluginManagementReceipt => ({ ...receipt('confirmation'), consent: { requestId: 'consent-1',
+ initiator: 'user', origin: 'market', facts: { kind: 'install', ghostId: 'demo', name: 'Demo', version: '2', permissions: [] } } });
+const capability = { protocolVersion: 1, collections: [{ id: 'plugins', actions: [{ id: 'management:snapshot', label: 'Manage' }] }] };
+function deferred<T>() { let resolve!: (value: T) => void, reject!: (reason: unknown) => void;
+ const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no; }); return { promise, resolve, reject }; }
+type Envelope = { actionId: string; input: Record<string, unknown>; resourceRef?: { id: string } };
+function host(handler?: (request: Envelope) => unknown | Promise<unknown>) {
+ const requests: Envelope[] = [];
+ let facts = snapshot();
+ const invoke = vi.fn(async (_id: string, channel: string, args?: unknown[], options?: { preSend?: () => void }) => {
+ options?.preSend?.();
+ if (channel.endsWith(':manifest')) return capability;
+ const request = args?.[0] as Envelope;
+ requests.push(request);
+ let result;
+ if (request.actionId === 'management:snapshot') result = facts;
+ else if (request.actionId === 'management:market-detail') result = detail;
+ else result = handler ? await handler(request) : receipt();
+ return { effects: [], result };
+ }) as unknown as PluginManagementInvoke;
+ const client = createPluginManagementClient({ deviceId: 'host-1', invoke });
+ return { invoke, requests, client, setFacts: (next: PluginManagementSnapshot) => { facts = next; } };
+}
+const controllers: Array<ReturnType<typeof createPluginManagementController>> = [];
+function controller(client: ReturnType<typeof createPluginManagementClient>) {
+ const value = createPluginManagementController(client, { createOperationId: () => 'operation-1' });
+ controllers.push(value); return value;
+}
+beforeEach(() => { setMobileAuthOwner('owner'); });
+afterEach(() => { controllers.forEach((value) => value.dispose()); controllers.length = 0; vi.useRealTimers(); });
+
+describe('mobile management contract', () => {
+ it.each([JSON.parse('{"__proto__":{}}'), { constructor: {} }, { value: Infinity }, new Date(),
+ { value: 'x'.repeat(8_000_001) }, Array(50_001).fill(null)])('rejects non-JSON or oversized Host declarations', (value) => {
+ expect(isBoundedPluginResponse(value)).toBe(false);
+ });
+ it('bounds recursion and validates receipt identity and permission facts', () => {
+ let deep: unknown = null; for (let i = 0; i < 25; i++) deep = { child: deep };
+ expect(isBoundedPluginResponse(deep)).toBe(false);
+ expect(() => parsePluginManagementReceipt(receipt(), 'different-operation')).toThrow('INVALID_RESPONSE');
+ expect(() => parsePluginManagementReceipt({ ...confirmation(), consent: { ...confirmation().consent,
+ facts: { kind: 'install', ghostId: 'demo', name: 'Demo', version: '2', permissions: [{ key: 'fs' }] } } }, 'operation-1')).toThrow('INVALID_RESPONSE');
+ });
+ it('keeps namespace missing distinct from root, and removes Host-local icon lookup keys', () => {
+ const legacy = { ...plugin }; delete legacy.namespace;
+ const parsed = parsePluginManagementSnapshot({ ...snapshot([legacy]), market: { ...snapshot().market,
+ items: [{ ...detail, customIconKey: 'target-only' }] } });
+ expect(Object.hasOwn(parsed.ghosts[0], 'namespace')).toBe(false);
+ expect(parsed.market.items[0]).not.toHaveProperty('customIconKey');
+ expect(marketItemMatchesPlugin(detail, legacy)).toBe(false);
+ expect(marketItemMatchesPlugin(detail, { ...plugin, namespace: 'enterprise' })).toBe(false);
+ expect(() => parsePluginManagementSnapshot(snapshot([{ ...plugin, approval: { state: 'approved', revision: 'bad' } }]))).toThrow('INVALID_RESPONSE');
+ expect(() => parsePluginManagementDetail({ ...detail, manifest: { ...manifest, id: 'other' } })).toThrow('INVALID_RESPONSE');
+ });
+ it('uses only the exact physical key for legacy namespace matches, never a same-named organization instance', () => {
+ const legacyItem = { ...detail }; delete legacyItem.namespace;
+ expect(marketItemMatchesPlugin(legacyItem, { ...plugin, instanceKey: 'demo' })).toBe(true);
+ for (const instanceKey of ['enterprise__demo', '_root__demo', 'demo-enterprise']) {
+ expect(marketItemMatchesPlugin(legacyItem, { ...plugin, instanceKey, namespace: 'enterprise' })).toBe(false);
+ }
+ const legacyPlugin = { ...plugin }; delete legacyPlugin.namespace;
+ expect(marketItemMatchesPlugin(detail, legacyPlugin)).toBe(false);
+ });
+ it('detects an old Host without hiding transient or malformed discovery errors', async () => {
+ const invoke = vi.fn().mockResolvedValueOnce({ collections: [{ id: 'plugins' }] })
+ .mockRejectedValueOnce(Object.assign(new Error('blocked'), { code: 'CHANNEL_NOT_ALLOWED' }))
+ .mockRejectedValueOnce(new Error('offline')).mockResolvedValueOnce({ collections: 'invalid' });
+ const client = createPluginManagementClient({ invoke, deviceId: 'host-1' });
+ await expect(client.capability()).resolves.toBe('unsupported');
+ await expect(client.capability()).resolves.toBe('unsupported');
+ await expect(client.capability()).rejects.toThrow('offline');
+ await expect(client.capability()).rejects.toThrow('INVALID_RESPONSE');
+ });
+ it('binds upgrades to release, physical instance, and approval; custom install also retains the full manifest', async () => {
+ const h = host();
+ await h.client.begin({ operationId: 'operation-1', kind: 'install', detail, installed: plugin });
+ expect(h.requests[0]).toMatchObject({ resourceRef: { id: plugin.instanceKey }, input: {
+ expectedReleaseId: 'release-2', expectedInstalledApproval: `approved:${(plugin.approval as { revision: string }).revision}` } });
+ expect(h.requests[0].input).not.toHaveProperty('expectedManifest');
+ const custom = { ...detail, sourceType: 'git-market' as const, sourceMarketName: 'Custom', manifest: { ...manifest, extension: { keep: true } } };
+ await h.client.begin({ operationId: 'operation-1', kind: 'install', detail: custom, installed: plugin });
+ expect(h.requests[1].input.expectedManifest).toEqual(custom.manifest);
+ expect(h.requests[1].input).not.toHaveProperty('allowSourceReplacement');
+ });
+ it('rejects source conflicts and byte-oversized custom install before sending', async () => {
+ const h = host();
+ expect(() => h.client.begin({ operationId: 'operation-1', kind: 'install', detail: { ...detail, installState: 'conflict' }, installed: plugin })).toThrow('PLUGIN_INSTALL_CHANGED');
+ await expect(h.client.begin({ operationId: 'operation-1', kind: 'install', installed: plugin, detail: {
+ ...detail, sourceType: 'local-market', manifest: { ...manifest, large: '汉'.repeat(25_000) } } })).rejects.toThrow('INPUT_TOO_LARGE');
+ expect(h.requests).toHaveLength(0);
+ });
+ it.each(['target', 'account'] as const)('fences queued writes and late reads after changing %s', async (change) => {
+ let active = true;
+ const pending = deferred<unknown>();
+ let preSend!: () => void;
+ const invoke = vi.fn(async (_d, _c, _a, opts) => { preSend = opts!.preSend!; return pending.promise; }) as PluginManagementInvoke;
+ const client = createPluginManagementClient({ invoke, deviceId: 'host-1', isCurrent: () => active });
+ const request = client.begin({ operationId: 'operation-1', kind: 'uninstall', installed: plugin });
+ if (change === 'target') active = false; else setMobileAuthOwner('replacement');
+ expect(() => preSend()).toThrow('PLUGIN_MANAGEMENT_STALE');
+ pending.resolve({ effects: [], result: receipt('succeeded') });
+ await expect(request).rejects.toMatchObject({ message: 'PLUGIN_MANAGEMENT_STALE', outcomeUnknown: true });
+ });
+});
+
+describe('mobile management transactions', () => {
+ it('submits only the active consent request and preserves Host failure receipts', async () => {
+ const h = host((r) => r.actionId === 'management:begin' ? confirmation() : { ...receipt('failed'), errorCode: 'PACKAGE_CHANGED' });
+ const c = controller(h.client); await c.refresh(); await c.install(detail, plugin); await c.answer(true);
+ expect(c.getState()).toMatchObject({ outcome: 'failed', errorCode: 'PACKAGE_CHANGED', busy: false });
+ expect(h.requests.find((r) => r.actionId === 'management:answer')?.input).toEqual({
+ operationId: 'operation-1', requestId: 'consent-1', confirmed: true,
+ });
+ });
+ it('keeps a second target independent when the first target has an unknown write result', async () => {
+ const first = host(() => { throw new Error('timeout'); });
+ const second = host(() => receipt('succeeded'));
+ const one = controller(first.client);
+ const two = controller(createPluginManagementClient({ deviceId: 'host-2', invoke: second.invoke }));
+ await Promise.all([one.refresh(), two.refresh()]);
+ await one.uninstall(plugin); await two.setEnabled(plugin, false);
+ expect(one.getState().outcome).toBe('unknown');
+ expect(two.getState().outcome).toBe('succeeded');
+ });
+ it('queries the original operation after a lost begin response and never replays it, even when Host forgot the receipt', async () => {
+ let missing = false;
+ const h = host((request) => {
+ if (request.actionId === 'management:begin') throw new Error('timeout');
+ if (missing) throw Object.assign(new Error('forgotten'), { code: 'NOT_FOUND' });
+ return receipt('succeeded');
+ });
+ const c = controller(h.client); await c.refresh(); await c.uninstall(plugin);
+ expect(c.getState()).toMatchObject({ outcome: 'unknown', operationId: 'operation-1', busy: false });
+ missing = true; await c.reconcile();
+ expect(c.getState()).toMatchObject({ outcome: 'unknown', errorCode: 'NOT_FOUND' });
+ await c.uninstall(plugin);
+ missing = false; await c.reconcile();
+ expect(c.getState().outcome).toBe('succeeded');
+ expect(h.requests.filter((r) => r.actionId === 'management:begin')).toHaveLength(1);
+ });
+ it('refreshes before mutation and rejects a replaced install or changed release', async () => {
+ const h = host(); const c = controller(h.client); await c.refresh();
+ h.setFacts(snapshot([{ ...plugin, approval: { state: 'approved', revision: 'aaaaaaaa-1234-4123-8123-123456789abc' } }]));
+ await c.uninstall(plugin);
+ expect(c.getState()).toMatchObject({ outcome: 'failed', errorCode: 'PLUGIN_INSTALL_CHANGED' });
+ await c.install({ ...detail, releaseId: 'old-release' }, plugin);
+ expect(c.getState().errorCode).toBe('PLUGIN_RELEASE_CHANGED');
+ expect(h.requests.some((r) => r.actionId === 'management:begin')).toBe(false);
+ });
+ it('requires the original installed generation again before accepting permission consent', async () => {
+ const h = host(() => confirmation()); const c = controller(h.client); await c.refresh(); await c.install(detail, plugin);
+ expect(c.getState().outcome).toBe('confirmation');
+ h.setFacts(snapshot([{ ...plugin, approval: { state: 'invalid' } }]));
+ await c.answer(true);
+ expect(c.getState()).toMatchObject({ outcome: 'unknown', errorCode: 'PLUGIN_INSTALL_CHANGED' });
+ expect(h.requests.some((r) => r.actionId === 'management:answer')).toBe(false);
+ });
+ it('preserves committed success when cancellation races the original begin response', async () => {
+ const begin = deferred<PluginManagementReceipt>();
+ const h = host((r) => r.actionId === 'management:begin' ? begin.promise : receipt('succeeded'));
+ const c = controller(h.client); await c.refresh();
+ const start = c.uninstall(plugin);
+ await vi.waitFor(() => expect(c.getState().operationId).toBe('operation-1'));
+ await c.cancel(); begin.resolve(receipt('running')); await start;
+ expect(c.getState().outcome).toBe('succeeded');
+ });
+ it('blocks an enqueued begin after cancellation before transport sends it', async () => {
+ const queued = deferred<unknown>(); let preSend!: () => void;
+ const h = host();
+ const invoke = (async (d, channel, args, opts) => {
+ if ((args?.[0] as Envelope)?.actionId === 'management:begin') { preSend = opts!.preSend!; return queued.promise; }
+ return h.invoke(d, channel, args, opts);
+ }) as PluginManagementInvoke;
+ const c = controller(createPluginManagementClient({ invoke, deviceId: 'host-1' })); await c.refresh();
+ const start = c.uninstall(plugin);
+ await vi.waitFor(() => expect(preSend).toBeTypeOf('function'));
+ await c.cancel();
+ expect(() => preSend()).toThrow('PLUGIN_MANAGEMENT_STALE');
+ queued.reject(new Error('cancelled before send')); await start;
+ expect(c.getState().outcome).toBe('running');
+ });
+ it.each(['begin', 'answer', 'cancel'] as const)('permanently fences queued %s across offline and online epochs', async (action) => {
+ const queued = deferred<unknown>(); let preSend!: () => void;
+ const h = host((r) => action === 'answer' || r.actionId === 'management:begin' && action !== 'cancel' ? confirmation() : receipt());
+ const invoke = (async (d, channel, args, opts) => {
+ if ((args?.[0] as Envelope)?.actionId === `management:${action}`) { preSend = opts!.preSend!; return queued.promise; }
+ return h.invoke(d, channel, args, opts);
+ }) as PluginManagementInvoke;
+ const c = controller(createPluginManagementClient({ invoke, deviceId: 'host-1' })); await c.refresh();
+ let pending: Promise<void>;
+ if (action === 'begin') pending = c.install(detail, plugin);
+ else { await c.install(detail, plugin); pending = action === 'answer' ? c.answer(true) : c.cancel(); }
+ await vi.waitFor(() => expect(preSend).toBeTypeOf('function'));
+ c.setOnline(false); c.setOnline(true);
+ await vi.waitFor(() => expect(c.getState().busy).toBe(false));
+ expect(c.getState().online).toBe(true);
+ expect(() => preSend()).toThrow('PLUGIN_MANAGEMENT_STALE');
+ const recoveredOutcome = c.getState().outcome;
+ queued.resolve({ effects: [], result: receipt('succeeded') }); await pending;
+ expect(c.getState().outcome).toBe(recoveredOutcome);
+ });
+ it('still cancels the original operation when the view becomes stale before disposal', async () => {
+ let alive = true;
+ const h = host();
+ const c = controller(createPluginManagementClient({ invoke: h.invoke, deviceId: 'original-host', isCurrent: () => alive }));
+ await c.refresh(); await c.uninstall(plugin); alive = false; c.dispose();
+ await vi.waitFor(() => expect(h.requests.some((r) => r.actionId === 'management:cancel')).toBe(true));
+ expect(h.requests.find((r) => r.actionId === 'management:cancel')?.input).toEqual({ operationId: 'operation-1' });
+ expect(h.invoke).toHaveBeenLastCalledWith('original-host', expect.any(String), expect.any(Array), expect.any(Object));
+ });
+ it('blocks queued disposal cancellation after the account owner changes', async () => {
+ let preSend!: () => void;
+ const queued = deferred<unknown>(), h = host();
+ const invoke = (async (d, channel, args, opts) => {
+ if ((args?.[0] as Envelope)?.actionId === 'management:cancel') { preSend = opts!.preSend!; return queued.promise; }
+ return h.invoke(d, channel, args, opts);
+ }) as PluginManagementInvoke;
+ const c = controller(createPluginManagementClient({ invoke, deviceId: 'original-host' }));
+ await c.refresh(); await c.uninstall(plugin); c.dispose();
+ expect(preSend).toBeTypeOf('function'); setMobileAuthOwner('replacement');
+ expect(() => preSend()).toThrow('PLUGIN_MANAGEMENT_STALE');
+ queued.reject(new Error('account switched'));
+ });
+ it('ignores late offline results and reconnects by operation lookup, with no write replay', async () => {
+ const begin = deferred<PluginManagementReceipt>();
+ const h = host((r) => r.actionId === 'management:begin' ? begin.promise : receipt('cancelled'));
+ const c = controller(h.client); await c.refresh(); const start = c.uninstall(plugin);
+ await vi.waitFor(() => expect(c.getState().operationId).toBe('operation-1'));
+ c.setOnline(false); begin.resolve(receipt('succeeded')); await start;
+ expect(c.getState()).toMatchObject({ online: false, outcome: 'unknown' });
+ c.setOnline(true);
+ await vi.waitFor(() => expect(c.getState().outcome).toBe('cancelled'));
+ expect(h.requests.filter((r) => r.actionId === 'management:begin')).toHaveLength(1);
+ });
+ it('polls only running receipts, stops at confirmation, and clears account data on owner switch', async () => {
+ vi.useFakeTimers();
+ const h = host((r) => r.actionId === 'management:operation' ? confirmation() : receipt());
+ const c = controller(h.client); await c.refresh(); await c.setEnabled(plugin, false);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(c.getState().outcome).toBe('confirmation');
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(h.requests.filter((r) => r.actionId === 'management:operation')).toHaveLength(1);
+ const oldOwner = getMobileAuthOwner(); setMobileAuthOwner('new-owner');
+ expect(getMobileAuthOwner().generation).not.toBe(oldOwner.generation);
+ expect(c.getState()).toMatchObject({ snapshot: null, operationId: null, receipt: null });
+ await c.answer(true);
+ expect(h.requests.some((r) => r.actionId === 'management:answer')).toBe(false);
+ });
+});
diff --git a/apps/mobile/src/__tests__/pluginNativeViews.test.tsx b/apps/mobile/src/__tests__/pluginNativeViews.test.tsx
index ed73b7bcb5..68ca4cd1b8 100644
--- a/apps/mobile/src/__tests__/pluginNativeViews.test.tsx
+++ b/apps/mobile/src/__tests__/pluginNativeViews.test.tsx
@@ -1,19 +1,25 @@
// @vitest-environment jsdom
+import { PluginNativeNotice, PluginNotice as PluginNoticeHost } from "@/plugins/PluginNotice.ios";
import { act, createElement } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, expect, it, vi } from "vitest";
import { PluginDirectoryView } from "@/plugins/PluginDirectoryView.ios";
import { PluginDetailView } from "@/plugins/PluginDetailView.ios";
+import { PluginDetailView as AndroidDetailView } from "@/plugins/PluginDetailView";
import { PluginTaskPickerView } from "@/plugins/PluginTaskPickerView.ios";
import { PluginTaskPickerView as AndroidTaskPickerView } from "@/plugins/PluginTaskPickerView";
import { pluginDetailModel } from "@/plugins/pluginDetailModel";
import { palettes } from "@/theme/tokens";
+import { PluginManagementConfirmation } from "@/plugins/PluginManagementConfirmation.ios";
const bridge = vi.hoisted(() => ({
props: new Map<string, any>(),
ownerCurrent: true,
+ keyboardVisible: false,
mode: "light" as "light" | "dark",
}));
+vi.mock("@/hooks/useReduceMotion", () => ({ useReduceMotionEnabled: () => false }));
+vi.mock("@/session/useMobileKeyboardState", () => ({ useMobileKeyboardState: () => ({ visible: bridge.keyboardVisible }) }));
vi.mock("@expo/ui/swift-ui", async () => {
const React = await import("react");
const TextField = Object.assign(
@@ -27,8 +33,19 @@ vi.mock("@expo/ui/swift-ui", async () => {
},
{ Placeholder: (p: any) => p.children },
);
+ const DisclosureLabel = (p: any) => p.children;
+ const DisclosureGroup = Object.assign((p: any) => {
+ if (p.testID) bridge.props.set(p.testID, p);
+ const children = React.Children.toArray(p.children);
+ return React.createElement("div", {
+ "data-native": "DisclosureGroup", "data-testid": p.testID,
+ }, p.label, children.filter((child: any) =>
+ child.type === DisclosureLabel || p.isExpanded !== false));
+ }, { Label: DisclosureLabel });
return {
TextField,
+ DisclosureGroup,
+ Background: Object.assign((p: any) => createElement("div", null, p.children), { Content: (p: any) => p.children }),
useNativeState: (initial: string) =>
React.useRef({
value: initial,
@@ -49,8 +66,11 @@ vi.mock("@expo/ui/swift-ui", async () => {
...Object.fromEntries(
[
"Button",
+ "Label",
+ "ContentUnavailableView",
"Circle",
- "DisclosureGroup",
+ "Rectangle",
+ "ZStack",
"Divider",
"HStack",
"Image",
@@ -74,9 +94,7 @@ vi.mock("@expo/ui/swift-ui", async () => {
p.title,
p.label,
p.header ? React.createElement("header", null, p.header) : null,
- name === "DisclosureGroup" && p.isExpanded === false
- ? null
- : p.children,
+ p.modifiers?.some((modifier: any) => modifier.accessibilityHidden === true) ? null : p.children,
);
},
]),
@@ -84,6 +102,8 @@ vi.mock("@expo/ui/swift-ui", async () => {
};
});
vi.mock("@expo/ui/swift-ui/modifiers", () => ({
+ Animation: { easeInOut: vi.fn(() => ({})) },
+ animation: vi.fn(() => ({})),
shapes: {
capsule: () => "capsule",
rectangle: () => "rectangle",
@@ -92,6 +112,11 @@ vi.mock("@expo/ui/swift-ui/modifiers", () => ({
...Object.fromEntries(
[
"accessibilityLabel",
+ "accessibilityHidden",
+ "clipped",
+ "clipShape",
+ "onGeometryChange",
+ "rotationEffect",
"autocorrectionDisabled",
"textInputAutocapitalization",
"textFieldStyle",
@@ -100,6 +125,7 @@ vi.mock("@expo/ui/swift-ui/modifiers", () => ({
"background",
"buttonStyle",
"contentShape",
+ "controlSize",
"disabled",
"font",
"fixedSize",
@@ -126,6 +152,7 @@ vi.mock("@expo/ui/swift-ui/modifiers", () => ({
}));
vi.mock("react-native", () => ({
PlatformColor: (name: string) => name,
+ Keyboard: { addListener: () => ({ remove() {} }) },
useWindowDimensions: () => ({ width: 390, height: 844, fontScale: 1 }),
Image: () => null,
View: (p: any) => {
@@ -138,22 +165,64 @@ vi.mock("react-native", () => ({
},
Text: (p: any) => p.children,
TextInput: () => null,
- Pressable: (p: any) => p.children,
+ ScrollView: (p: any) => createElement("div", { "data-testid": p.testID }, p.children),
+ Pressable: (p: any) => { if (p.testID) bridge.props.set(p.testID, p); return createElement("div", { "data-testid": p.testID }, p.children); },
ActivityIndicator: () => null,
- AccessibilityInfo: { isReduceMotionEnabled: async () => false, addEventListener: () => ({ remove() {} }) },
+ AccessibilityInfo: {
+ isReduceMotionEnabled: async () => false,
+ addEventListener: () => ({ remove() {} }),
+ },
StyleSheet: { create: (s: any) => s },
}));
-vi.mock("lucide-react-native", () => ({
- CircleAlert: () => null,
- Puzzle: () => null,
- Wrench: () => null,
-}));
-vi.mock('@/components/AppText', async () => {
- const native = await import('react-native');
- return { Text: native.Text, TextInput: native.TextInput, MAX_FONT_SIZE_MULTIPLIER: 1.2 };
+vi.mock("lucide-react-native", () =>
+ Object.fromEntries(
+ [
+ "CircleAlert",
+ "Info",
+ "WifiOff",
+ "Puzzle",
+ "AppWindow",
+ "Bot",
+ "Cpu",
+ "FileCode2",
+ "FilePen",
+ "FolderOpen",
+ "FolderPlus",
+ "Globe",
+ "GraduationCap",
+ "KeyRound",
+ "LayoutTemplate",
+ "Library",
+ "MapPin",
+ "Megaphone",
+ "MessageCircleQuestion",
+ "PanelLeft",
+ "PanelRight",
+ "Radio",
+ "ShieldCheck",
+ "Shield",
+ "Sparkles",
+ "Terminal",
+ "Wrench",
+ ].map((name) => [name, () => createElement("i", { "data-permission-icon": name })]),
+ ),
+);
+vi.mock("@/platform/chrome/NativeSwitch", () => ({ NativeSwitch: () => null }));
+vi.mock("@/components/AppText", async () => {
+ const native = await import("react-native");
+ return {
+ Text: native.Text,
+ TextInput: native.TextInput,
+ MAX_FONT_SIZE_MULTIPLIER: 1.2,
+ };
});
-vi.mock('@/components/MobilePrimitives', () => ({
- MainWindowActionButton: ({ action }: any) => createElement('button', { onClick: action.onPress, disabled: action.disabled || action.busy }, action.label),
+vi.mock("@/components/MobilePrimitives", () => ({
+ MainWindowActionButton: ({ action }: any) =>
+ createElement(
+ "button",
+ { onClick: action.onPress, disabled: action.disabled || action.busy },
+ action.label,
+ ),
}));
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key, i18n: { language: "en" } }),
@@ -178,12 +247,13 @@ vi.mock("@/session/ComposerNativeRow", () => ({
}));
vi.mock("@/session/ComposerSheet", () => ({
ComposerSheet: (p: any) => {
- bridge.props.set("plugins.taskPicker", p);
+ bridge.props.set(p.testID ?? "plugins.taskPicker", p);
return createElement(
"div",
{ "data-native": "sheet", "data-testid": p.testID },
p.nativeHeader,
p.children,
+ p.footer,
);
},
}));
@@ -209,6 +279,7 @@ afterEach(() => {
bridge.props.clear();
bridge.mode = "light";
bridge.ownerCurrent = true;
+ bridge.keyboardVisible = false;
});
function mount(component: any, props: any) {
const container = document.createElement("div");
@@ -321,7 +392,7 @@ it.each(["light", "dark"] as const)(
false,
),
settingsOpen: false,
- onSettings: vi.fn(),
+
onResolveStatus: vi.fn(),
onEnabledChange: change,
@@ -344,7 +415,7 @@ it.each(["light", "dark"] as const)(
});
},
);
-it("groups use buttons under a heading, puts the switch beside the title and guides configuration to PC", () => {
+it("keeps task actions outside the scrolling detail, preserves the switch and old Host configuration guidance", () => {
const p = {
row,
enabled: true,
@@ -366,7 +437,7 @@ it("groups use buttons under a heading, puts the switch beside the title and gui
onOpen: vi.fn(),
onNewTask: vi.fn(),
onChooseTask: vi.fn(),
- onSettings: vi.fn(),
+
onResolveStatus: vi.fn(),
};
const { container, rerender } = mount(PluginDetailView, p);
@@ -378,7 +449,7 @@ it("groups use buttons under a heading, puts the switch beside the title and gui
).toBe("Button");
for (const id of ["plugins.newTask", "plugins.chooseTask"]) {
expect(bridge.props.get(id).modifiers).toContainEqual({
- nativeButton: "secondary",
+ nativeButton: id === "plugins.newTask" ? "primary" : "secondary",
});
}
expect(container.querySelector('[data-testid="plugins.tools"]')).toBeNull();
@@ -388,19 +459,33 @@ it("groups use buttons under a heading, puts the switch beside the title and gui
),
).not.toBeNull();
expect(
- container.querySelector('[data-testid="plugins.useHeading"]')?.textContent,
- ).toBe("plugins.detail.useItIn");
+ container.querySelector(
+ '[data-testid="plugins.detail"] [data-testid="plugins.newTask"]',
+ ),
+ ).toBeNull();
expect(
- container.querySelector('[data-testid="plugins.computerSettings"]'),
+ container.querySelector(
+ '[data-testid="plugins.use"] [data-testid="plugins.newTask"]',
+ ),
).not.toBeNull();
+ expect(
+ container.querySelector('[data-testid="plugins.computerSettings"]'),
+ ).toBeNull();
expect(
container.querySelector('[data-testid="plugins.permissions"]'),
).toBeNull();
expect(
container.querySelector('[data-testid="plugins.metadata"]'),
- ).not.toBeNull();
+ ).toBeNull();
act(() => bridge.props.get("plugins.chooseTask").onPress());
expect(p.onChooseTask).toHaveBeenCalledOnce();
+ bridge.keyboardVisible = true;
+ rerender(p);
+ expect(container.querySelector('[data-testid="plugins.newTask"]')).toBeNull();
+ bridge.keyboardVisible = false;
+ rerender({ ...p, settingsContent: createElement("div", null, "Original settings form") });
+ expect(container.querySelector('[data-testid="plugins.settingsCard"]')?.textContent).toContain("Original settings form");
+ expect(container.querySelector('[data-testid="plugins.computerSettings"]')).toBeNull();
rerender({ ...p, settingsOpen: true });
expect(container.textContent).not.toContain("Task preferences content");
expect(container.querySelector('[data-testid="plugins.newTask"]')).toBeNull();
@@ -422,7 +507,7 @@ it("uses the title switch to recover a disabled plugin without a duplicate enabl
onOpen: vi.fn(),
onNewTask: vi.fn(),
onChooseTask: vi.fn(),
- onSettings: vi.fn(),
+
onResolveStatus: vi.fn(),
};
const { container } = mount(PluginDetailView, p);
@@ -509,6 +594,28 @@ it("keeps the offline indicator ahead of long preview text so it stays visible",
);
});
+it("keeps the avatar's measured native root when its remote image arrives", () => {
+ const p = {
+ row, enabled: true, online: true, busy: false, settingsOpen: false,
+ model: pluginDetailModel(row as any, undefined, true, false, false),
+ onEnabledChange: vi.fn(), onOpen: vi.fn(), onNewTask: vi.fn(),
+ onChooseTask: vi.fn(), onResolveStatus: vi.fn(),
+ };
+ const { container, rerender } = mount(PluginDetailView, p);
+ const measuredRoot = () => container.querySelector(
+ '[data-testid="plugins.identity"] [data-native="RNHostView"]',
+ )?.firstElementChild;
+ const originalRoot = measuredRoot();
+ expect(originalRoot).toBeTruthy();
+ rerender({ ...p, row: { ...row, item: { ...row.item, display: {
+ ...row.item.display, avatar: { value: "data:image/png;base64,aGVsbG8=" },
+ } } }, settingsContent: createElement("div", null, "Loaded original settings") });
+ // RNHostView's native size observer stays attached to its first UIView.
+ expect(measuredRoot()).toBe(originalRoot);
+ rerender(p);
+ expect(measuredRoot()).toBe(originalRoot);
+});
+
it("renders real Host facts and hides unavailable information", () => {
const p = {
row,
@@ -539,7 +646,7 @@ it("renders real Host facts and hides unavailable information", () => {
onOpen: vi.fn(),
onNewTask: vi.fn(),
onChooseTask: vi.fn(),
- onSettings: vi.fn(),
+
onResolveStatus: vi.fn(),
};
const { container, rerender } = mount(PluginDetailView, p);
@@ -562,10 +669,8 @@ it("renders real Host facts and hides unavailable information", () => {
),
).toBeNull();
expect(
- container.querySelectorAll(
- '[data-testid="plugins.metadata"] [data-native="Divider"]',
- ),
- ).toHaveLength(1);
+ container.querySelector('[data-testid="plugins.fact.version"]')?.textContent,
+ ).toContain("2.3.0");
expect(bridge.props.get("plugins.identity").modifiers).toContainEqual({
listRowInsets: { leading: 20, trailing: 20, top: 8, bottom: 16 },
});
@@ -578,9 +683,7 @@ it("renders real Host facts and hides unavailable information", () => {
expect(
container.querySelector('[data-testid="plugins.identity"]')?.textContent,
).toContain("Full plugin introduction");
- expect(
- container.querySelector('[data-testid="plugins.metadata"]')?.textContent,
- ).toContain("2.3.0");
+ expect(container.textContent).not.toContain("plugins.detail.identifier");
expect(
container.querySelector('[data-testid="plugins.permissions"]'),
).toBeNull();
@@ -648,12 +751,14 @@ it("renders real Host facts and hides unavailable information", () => {
container.querySelector('[data-testid="plugins.toolsDisclosure"]'),
).toBeNull();
for (const empty of [undefined, []]) {
- rerender({ ...p, model: { ...p.model, tools: empty, permissions: empty } });
+ rerender({ ...p, model: { ...p.model, version: undefined, tools: empty, permissions: empty } });
expect(container.querySelector('[data-testid="plugins.tools"]')).toBeNull();
expect(
container.querySelector('[data-testid="plugins.permissions"]'),
).toBeNull();
- expect(container.textContent).toContain("v2.3.0");
+ expect(
+ container.querySelector('[data-testid="plugins.metadata"]'),
+ ).toBeNull();
}
rerender({
...p,
@@ -663,21 +768,19 @@ it("renders real Host facts and hides unavailable information", () => {
{ key: "author", title: "Author", value: " " },
{ key: "version", title: "Version", value: "v2.3.0" },
],
- permissions: [{ title: "Network", description: "" }],
+ permissions: [{ title: "Network", description: "Permission detail belongs only in the full PC view" }],
},
});
expect(
container.querySelector('[data-testid="plugins.fact.author"]'),
).toBeNull();
- expect(
- container.querySelector('[data-testid="plugins.fact.version"]')
- ?.textContent,
- ).toContain("v2.3.0");
+ expect(container.querySelector('[data-testid="plugins.fact.version"]')?.textContent).toContain("v2.3.0");
expect(
container.querySelector('[data-testid="plugins.permissions"]')?.textContent,
).toContain("Network");
+ expect(container.textContent).not.toContain("Permission detail belongs only in the full PC view");
expect(container.textContent).not.toContain("plugins.detail.noDescription");
- rerender({ ...p, model: { ...p.model, details: [], hasSettings: false } });
+ rerender({ ...p, model: { ...p.model, version: undefined, details: [], hasSettings: false } });
expect(
container.querySelector('[data-testid="plugins.metadata"]'),
).toBeNull();
@@ -766,6 +869,7 @@ it("drops a pending task selection if the owner or plugin changes during dismiss
act(() => bridge.props.get("plugins.taskPicker").onClosed());
expect(p.onSelect).not.toHaveBeenCalled();
bridge.ownerCurrent = true;
+ bridge.keyboardVisible = false;
act(() => bridge.props.get("plugins.task.calendar-task").onPress());
rerender({ ...p, deviceId: "other-computer" });
act(() => bridge.props.get("plugins.taskPicker").onClosed());
@@ -786,3 +890,242 @@ it("shows Android task search empty results and restores the matching tasks", ()
rerender({ ...p, rows: [] });
expect(container.textContent).toContain("plugins.noTasks");
});
+
+
+it("expands full Host information on demand and resets when switching plugins", () => {
+ const fullPath = "/Users/example/Library/Application Support/Cindy/owners/owner/plugins/taptap-maker";
+ const contents = "Custom settings UI · Executable code · Local Node program · Tools";
+ const p = {
+ row, enabled: true, online: true, busy: false, settingsOpen: false,
+ model: { ...pluginDetailModel(row as any, undefined, true, false, false),
+ details: [
+ { key: "version", title: "Version", value: "v2.1.22" },
+ { key: "contents", title: "Contains", value: contents },
+ { key: "location", title: "Install location", value: fullPath },
+ ],
+ },
+ onEnabledChange: vi.fn(), onOpen: vi.fn(), onNewTask: vi.fn(),
+ onChooseTask: vi.fn(), onResolveStatus: vi.fn(),
+ };
+ const { container, rerender } = mount(PluginDetailView, p);
+ const fact = (key: string) => container.querySelector(`[data-testid="plugins.fact.${key}"]`)!;
+ expect(fact("location").textContent).toContain("Install location");
+ expect(fact("location").textContent).toContain("taptap-maker");
+ expect(fact("location").textContent).not.toContain(fullPath);
+ expect(fact("contents").textContent).toContain("Custom settings UI…");
+ expect(fact("contents").textContent).not.toContain(contents);
+ for (const key of ["contents", "location"]) {
+ act(() => bridge.props.get(`plugins.fact.${key}.toggle`).onPress());
+ const geometry = bridge.props.get(`plugins.fact.${key}.value`).modifiers.find((modifier: any) => modifier.onGeometryChange);
+ act(() => geometry.onGeometryChange({ width: 350, height: 84 }));
+ expect(bridge.props.get(`plugins.fact.${key}.content`).modifiers).toContainEqual({ frame: { height: 84, alignment: "topLeading" } });
+ if (key === "contents") expect(fact("location").textContent).not.toContain(fullPath);
+ }
+ expect(fact("contents").textContent).toContain(contents);
+ expect(fact("location").textContent).toContain(fullPath);
+ act(() => bridge.props.get("plugins.fact.location.toggle").onPress());
+ expect(bridge.props.get("plugins.fact.location.content").modifiers).toContainEqual({ frame: { height: 0, alignment: "topLeading" } });
+ expect(fact("contents").textContent).toContain(contents);
+ expect(fact("location").textContent).not.toContain(fullPath);
+ rerender({ ...p, row: { ...row, key: "another-host:another-plugin" } });
+ expect(fact("contents").textContent).not.toContain(contents);
+ expect(fact("location").textContent).not.toContain(fullPath);
+});
+
+// 用户要求提示按阻断范围并存;生产原生详情入口验证,避免离线缓存被描述为当前配置事实。
+it.each(["offline", "loadFailed", "loading"] as const)("does not show stale setup or runtime facts while %s", (status) => {
+ const p = {
+ row, enabled: true, online: status !== "offline", busy: false, settingsOpen: false,
+ model: { ...pluginDetailModel(row as any, undefined, true, false, false), status,
+ missing: ["token"], expired: ["account"], runtimeIssue: "fused" as const },
+ onEnabledChange: vi.fn(), onOpen: vi.fn(), onNewTask: vi.fn(), onChooseTask: vi.fn(), onResolveStatus: vi.fn(),
+ };
+ const { container } = mount(PluginDetailView, p);
+ expect(container.querySelector('[data-testid="plugins.configurationStatus"]')).toBeNull();
+ expect(container.textContent).not.toContain("plugins.detail.runtimeFused");
+ expect(Boolean(container.querySelector('[data-testid="plugins.loading"]'))).toBe(status === "loading");
+ expect(container.textContent).not.toContain("plugins.detail.status.loading");
+});
+it("leaves unknown configuration to the original form without a second status or action", () => {
+ const p = {
+ row, enabled: false, online: true, busy: false, settingsOpen: false,
+ model: { ...pluginDetailModel(row as any, undefined, true, false, false), status: "disabled" as const, statusAction: "enable" as const,
+ configuration: { items: [{ id: "account", kind: "oauth" as const, label: "Account", state: "unknown" as const }], alternatives: [] } },
+ settingsContent: createElement("span", null, "Original configuration"),
+ onEnabledChange: vi.fn(), onOpen: vi.fn(), onNewTask: vi.fn(), onChooseTask: vi.fn(), onResolveStatus: vi.fn(),
+ };
+ const { container } = mount(PluginDetailView, p);
+ expect(container.querySelector('[data-testid="plugins.status"]')).toBeNull();
+ expect(container.querySelector('[data-testid="plugins.configurationStatus"]')).toBeNull();
+ expect(container.textContent).toContain("Original configuration");
+ expect(p.onResolveStatus).not.toHaveBeenCalled();
+ expect(p.onEnabledChange).not.toHaveBeenCalled();
+});
+it("shows full consent facts in a separate sheet and rejects stale owner or request callbacks", () => {
+ const state = { outcome: "confirmation", operationId: "operation", online: true, busy: false, receipt: { consent: {
+ requestId: "request", origin: "custom-market", originLabel: "Verified source", initiator: "user",
+ facts: { kind: "update", ghostId: "plugin-id", name: "Plugin", version: "2", previousVersion: "1", unchangedCount: 2, builtinOauthClientChanged: true,
+ added: [{ key: "node", kind: "node", labelKey: "nodeRuntime", detailKey: "nodeRuntimeDetail", detail: "Full local access risk" }],
+ removed: [{ key: "network", kind: "network", labelKey: "networkHost", detail: "Removed host access" }] },
+ } } } as any;
+ const controller = { getState: () => state, answer: vi.fn() } as any;
+ const props = { state, controller, active: true, deviceName: "Mac" };
+ const { container, rerender } = mount(PluginManagementConfirmation, props);
+ expect(bridge.props.get("plugins.managementConfirmation").visible).toBe(true);
+ for (const fact of ["Plugin · 2", "plugin-id", "Verified source", "Full local access risk", "Removed host access", "plugins.management.permissions.nodeRuntimeDetail", "plugins.management.oauthChanged"]) expect(container.textContent).toContain(fact);
+ const allow = bridge.props.get("plugins.management.allow").onPress;
+ state.online = false;
+ rerender({ ...props, active: false });
+ expect(bridge.props.get("plugins.managementConfirmation").visible).toBe(false);
+ act(() => allow());
+ expect(controller.answer).not.toHaveBeenCalled();
+ state.online = true;
+ rerender(props);
+ expect(bridge.props.get("plugins.managementConfirmation").visible).toBe(true);
+ expect(controller.answer).not.toHaveBeenCalled();
+ bridge.ownerCurrent = false;
+ act(() => allow());
+ expect(controller.answer).not.toHaveBeenCalled();
+ bridge.ownerCurrent = true;
+ state.receipt.consent.requestId = "new-request";
+ act(() => allow());
+ expect(controller.answer).not.toHaveBeenCalled();
+ state.receipt.consent.requestId = "request";
+ act(() => bridge.props.get("plugins.management.reject").onPress());
+ expect(controller.answer).toHaveBeenCalledWith(false);
+ act(() => roots.pop()!.unmount());
+ act(() => allow());
+ expect(controller.answer).toHaveBeenCalledTimes(1);
+});
+
+it("constrains RN notice Hosts to the measured width and measures only their height", () => {
+ const { container } = mount(PluginNoticeHost, { testID: "noticeSizing", title: "Read failed", detail: "A long settings read failure that must wrap", actions: [{ label: "Reload", onPress() {} }] });
+ act(() => bridge.props.get("noticeSizing.layout").onLayout({ nativeEvent: { layout: { width: 350 } } }));
+ expect(bridge.props.get("host").matchContents).toEqual({ vertical: true });
+ expect(bridge.props.get("host").style.width).toBe(350);
+ expect(container.textContent).toContain("Reload");
+});
+
+
+it.each([PluginDetailView, AndroidDetailView])("keeps task actions for pending setup without a redundant prompt beside the original form (%#)", (DetailView) => {
+ const resource = { ...row.item, blocks: [{ id: "capabilities", primitive: "plugin-capabilities", fallbackMarkdown: "", data: { usage: {
+ taskUsable: true, hasSettings: true, builtin: false, retired: false, approvalRequired: false,
+ setup: { state: "required", missing: ["Account"], expired: [] },
+ } } }] };
+ const model = pluginDetailModel(row as any, resource as any, true, false, false);
+ const p = { row, model, enabled: true, online: true, busy: false, settingsOpen: false,
+ settingsContent: createElement("span", null, "Original account form"),
+ onEnabledChange: vi.fn(), onOpen: vi.fn(), onNewTask: vi.fn(), onChooseTask: vi.fn(), onResolveStatus: vi.fn() };
+ const { container, rerender } = mount(DetailView, p);
+ expect(model.status).toBe("setupRequired");
+ expect(model.missing).toEqual(["Account"]);
+ expect(container.querySelector('[data-testid="plugins.configurationStatus"]')).toBeNull();
+ expect(container.textContent).toContain("Original account form");
+ for (const action of ["newTask", "chooseTask"]) expect(container.querySelector(`[data-testid="plugins.${action}"]`)).not.toBeNull();
+ act(() => bridge.props.get("plugins.newTask").onPress());
+ act(() => bridge.props.get("plugins.chooseTask").onPress());
+ expect(p.onNewTask).toHaveBeenCalledOnce(); expect(p.onChooseTask).toHaveBeenCalledOnce();
+ bridge.keyboardVisible = true; rerender(p);
+ expect(container.querySelector('[data-testid="plugins.newTask"]')).toBeNull();
+ bridge.keyboardVisible = false;
+ rerender({ ...p, model: { ...model, missing: [], expired: ["Account"] } });
+ expect(container.querySelector('[data-testid="plugins.configurationStatus"]')).toBeNull();
+});
+
+it.each([PluginDetailView, AndroidDetailView])("separates read/navigation recovery from pending write and task gates (%#)", (DetailView) => {
+ const p = { row, enabled: true, online: false, busy: true, statusRecoveryBusy: false, settingsOpen: false,
+ model: pluginDetailModel(row as any, undefined, false, false, false),
+ onEnabledChange: vi.fn(), onOpen: vi.fn(), onNewTask: vi.fn(), onChooseTask: vi.fn(), onResolveStatus: vi.fn() };
+ const { rerender } = mount(DetailView, p);
+ const disabled = (id: string) => {
+ const value = bridge.props.get(id);
+ return value.disabled ?? value.modifiers?.find((m: any) => 'disabled' in m)?.disabled;
+ };
+ for (const online of [false, true]) {
+ const model = pluginDetailModel(row as any, undefined, online, false, online);
+ rerender({ ...p, online, model });
+ expect(disabled("plugins.resolveStatus")).toBe(false);
+ act(() => bridge.props.get("plugins.resolveStatus").onPress());
+ rerender({ ...p, online, model, statusRecoveryBusy: true });
+ expect(disabled("plugins.resolveStatus")).toBe(true);
+ }
+ expect(p.onResolveStatus).toHaveBeenCalledTimes(2);
+ rerender({ ...p, online: true, model: { ...p.model, status: undefined, canUseTasks: true } });
+ for (const id of ["plugins.newTask", "plugins.chooseTask"]) expect(disabled(id)).toBe(true);
+});
+
+
+it.each(["light", "dark"] as const)("pairs confirmation Allow background and custom label contrast in %s", (mode) => {
+ bridge.mode = mode;
+ const state = { outcome: "confirmation", online: true, busy: false, receipt: { consent: {
+ requestId: "request", origin: "local-file", initiator: "user", facts: { kind: "install", ghostId: "qa", name: "QA", version: "1", permissions: [] },
+ } } } as any;
+ mount(PluginManagementConfirmation, { state, controller: { getState: () => state, answer: vi.fn() } as any, active: true, deviceName: "QA Mac" });
+ const allow = bridge.props.get("plugins.management.allow");
+ expect(allow.modifiers).toContainEqual({ tint: palettes[mode].cta });
+ expect(allow.modifiers).toContainEqual({ foregroundStyle: palettes[mode].ctaText });
+ expect(allow.children.props.modifiers).toContainEqual({ foregroundStyle: palettes[mode].ctaText });
+ expect(palettes[mode].cta).not.toBe(palettes[mode].ctaText);
+});
+
+
+it("uses an identifiable native bordered recovery action without a second card", () => {
+ const { container } = mount(PluginNativeNotice, { compact: true, testID: "compact", title: "Long recovery message", actions: [{ label: "Reload", testID: "reload", onPress: vi.fn() }] });
+ expect(bridge.props.get("reload").modifiers).toContainEqual({ buttonStyle: "bordered" });
+ expect(bridge.props.get("reload").modifiers).toContainEqual({ controlSize: "small" });
+ const title = Array.from(container.querySelectorAll('[data-native="Text"]')).find((node) => node.textContent === "Long recovery message")!;
+ expect(title).toBeTruthy();
+});
+
+
+it("keeps settings load failure compact with its semantic icon and standard reload action", () => {
+ const onPress = vi.fn();
+ const { container } = mount(PluginNativeNotice, { unavailable: true, testID: "loadFailure", title: "Could not load settings", detail: "Should not repeat", actions: [{ label: "Reload settings", testID: "reload", onPress }] });
+ expect(container.querySelector('[data-native="ContentUnavailableView"]')).toBeNull();
+ expect(container.textContent).toContain("Could not load settings");
+ expect(bridge.props.get("loadFailure").modifiers).not.toContainEqual({ frame: { height: 180, maxWidth: Infinity } });
+ expect(container.textContent).not.toContain("Should not repeat");
+ expect(bridge.props.get("reload").label).toBe("Reload settings");
+ expect(bridge.props.get("reload").children).toBeUndefined();
+ act(() => bridge.props.get("reload").onPress());
+ expect(onPress).toHaveBeenCalledOnce();
+});
+
+
+it.each(["light", "dark"] as const)("renders the actual top notice as a low-contrast status strip in %s and moves narrow actions below", (mode) => {
+ bridge.mode = mode;
+ const { container } = mount(PluginNativeNotice, { testID: "strip", title: "Computer offline", icon: "offline", actions: [{ label: "Connect computer", testID: "connect", onPress: vi.fn() }] });
+ const modifiers = bridge.props.get("strip").modifiers;
+ expect(modifiers).toContainEqual({ background: palettes[mode].surfaceChip });
+ expect(modifiers).toContainEqual({ frame: { minHeight: 48, maxWidth: Infinity, alignment: "leading" } });
+ const root = container.querySelector('[data-testid="strip"]')!;
+ expect(root.querySelector('[data-testid="connect"]')?.parentElement?.getAttribute("data-native")).toBe("HStack");
+ act(() => modifiers.find((modifier: any) => modifier.onGeometryChange).onGeometryChange({ width: 280, height: 52 }));
+ expect(root.querySelector('[data-testid="connect"]')?.parentElement?.getAttribute("data-native")).toBe("VStack");
+});
+
+
+it.each([PluginDetailView, AndroidDetailView])("limits permission summaries to four, keeps icons, and resets expansion only for another target (%#)", (DetailView) => {
+ const permissions = Array.from({ length: 5 }, (_, index) => ({ title: `Full permission title ${index + 1}`, kind: "network", labelKey: "networkHost", description: "Not part of summary" }));
+ const p = { row, enabled: true, online: true, busy: false, settingsOpen: false,
+ model: { ...pluginDetailModel(row as any, undefined, true, false, false), permissions: permissions.slice(0, 4) },
+ onEnabledChange: vi.fn(), onOpen: vi.fn(), onNewTask: vi.fn(), onChooseTask: vi.fn(), onResolveStatus: vi.fn() };
+ const { container, rerender } = mount(DetailView, p);
+ const card = () => container.querySelector('[data-testid="plugins.permissions"]')!;
+ expect(container.querySelector('[data-testid="plugins.permissionsDisclosure"]')).toBeNull();
+ expect(card().querySelectorAll('[data-permission-icon="Globe"]')).toHaveLength(4);
+ rerender({ ...p, model: { ...p.model, permissions } });
+ expect(card().textContent).not.toContain("Full permission title 5");
+ act(() => bridge.props.get("plugins.permissionsDisclosure").onPress());
+ expect(card().textContent).toContain("Full permission title 5");
+ expect(card().querySelectorAll('[data-permission-icon="Globe"]')).toHaveLength(5);
+ expect(card().querySelector('[data-permission-icon="Shield"]')).toBeNull();
+ expect(card().textContent).not.toContain("Not part of summary");
+ rerender({ ...p, model: { ...p.model, permissions: permissions.map(item => ({ ...item })) } });
+ expect(card().textContent).toContain("Full permission title 5");
+ act(() => bridge.props.get("plugins.permissionsDisclosure").onPress());
+ expect(card().textContent).not.toContain("Full permission title 5");
+ act(() => bridge.props.get("plugins.permissionsDisclosure").onPress());
+ rerender({ ...p, row: { ...row, key: "other-device:other-plugin" }, model: { ...p.model, permissions } });
+ expect(card().textContent).not.toContain("Full permission title 5");
+});
diff --git a/apps/mobile/src/__tests__/pluginOauthLoopback.test.ts b/apps/mobile/src/__tests__/pluginOauthLoopback.test.ts
new file mode 100644
index 0000000000..a87343f6ed
--- /dev/null
+++ b/apps/mobile/src/__tests__/pluginOauthLoopback.test.ts
@@ -0,0 +1,57 @@
+import { afterEach, expect, it, vi } from "vitest";
+import { receivePluginOauthLoopback } from "../plugins/pluginOauthLoopback";
+const state = "provider_state_123456789";
+function deferred<T>() { let resolve!: (value: T) => void; const promise = new Promise<T>((r) => { resolve = r; }); return { promise, resolve }; }
+function harness(platform = "ios") {
+ const received = deferred<unknown>(), browser = deferred<{ type: string }>();
+ let appState!: (state: string) => void;
+ const native = { start: vi.fn(async () => {}), wait: vi.fn(() => received.promise), status: vi.fn(async () => "waiting"), close: vi.fn(async () => {}) };
+ const input = { native, id: "test-listener-identifier", platform, request: { url: "https://accounts.example.com/authorize", callbackUrl: "http://127.0.0.1:57123/callback", state }, expiresAt: Date.now() + 60000,
+ assertCurrent: vi.fn(), openBrowser: vi.fn(() => browser.promise), dismissBrowser: vi.fn(async () => {}), onAppState: (fn: typeof appState) => { appState = fn; return vi.fn(); } };
+ return { input, native, received, browser, appState: (value: string) => appState(value) };
+}
+afterEach(() => vi.useRealTimers());
+it("binds before browser presentation and receives without waiting for iOS Done; provider state need not be bridge state", async () => {
+ const h = harness(); const result = receivePluginOauthLoopback(h.input);
+ await vi.waitFor(() => expect(h.input.openBrowser).toHaveBeenCalled());
+ expect(h.native.start.mock.invocationCallOrder[0]).toBeLessThan(h.input.openBrowser.mock.invocationCallOrder[0]);
+ h.appState("background"); h.appState("active");
+ h.received.resolve({ state, code: "fake-code" });
+ await expect(result).resolves.toEqual({ state, code: "fake-code" });
+ expect(h.native.close).toHaveBeenCalled(); expect(h.input.dismissBrowser).toHaveBeenCalledOnce();
+});
+it("does not mistake Android opened or a foreground callback race for completion/cancellation", async () => {
+ const h = harness("android"); const result = receivePluginOauthLoopback(h.input);
+ await vi.waitFor(() => expect(h.input.openBrowser).toHaveBeenCalled());
+ h.browser.resolve({ type: "opened" }); h.appState("background"); h.appState("active");
+ h.native.status.mockResolvedValue("received");
+ h.received.resolve({ state, error: "access_denied" });
+ await expect(result).resolves.toEqual({ state, error: "access_denied" });
+});
+it("keeps an already received iOS callback when Done resolves concurrently", async () => {
+ const h = harness(); const result = receivePluginOauthLoopback(h.input);
+ await vi.waitFor(() => expect(h.input.openBrowser).toHaveBeenCalled());
+ h.native.status.mockResolvedValue("received"); h.browser.resolve({ type: "cancel" });
+ h.received.resolve({ state, code: "fake-code" });
+ await expect(result).resolves.toMatchObject({ code: "fake-code" });
+});
+it("closes a late bind after owner cancellation and never opens the browser", async () => {
+ const h = harness(); const ready = deferred<void>(); h.native.start.mockReturnValue(ready.promise);
+ const abort = new AbortController(); const result = receivePluginOauthLoopback({ ...h.input, signal: abort.signal });
+ const rejected = expect(result).rejects.toThrow("PLUGIN_OAUTH_CLOSED"); abort.abort(); await rejected;
+ ready.resolve(); await Promise.resolve();
+ expect(h.native.close.mock.calls.length).toBeGreaterThanOrEqual(2); expect(h.input.openBrowser).not.toHaveBeenCalled();
+});
+it("cleans up on owner changes while awaiting the callback", async () => {
+ const h = harness(); const result = receivePluginOauthLoopback(h.input);
+ await vi.waitFor(() => expect(h.input.openBrowser).toHaveBeenCalled());
+ const rejected = expect(result).rejects.toThrow("PLUGIN_OAUTH_CLOSED");
+ h.input.assertCurrent.mockImplementation(() => { throw new Error("owner changed"); });
+ await rejected; expect(h.native.close).toHaveBeenCalled();
+});
+it("requires the updated module and refuses unsupported callbacks before opening a browser", async () => {
+ const h = harness();
+ await expect(receivePluginOauthLoopback({ ...h.input, native: null })).rejects.toThrow("PLUGIN_OAUTH_UPDATE_REQUIRED");
+ await expect(receivePluginOauthLoopback({ ...h.input, request: { ...h.input.request, callbackUrl: "http://localhost:57123/callback" } })).rejects.toThrow("PLUGIN_OAUTH_CALLBACK_UNSUPPORTED");
+ expect(h.input.openBrowser).not.toHaveBeenCalled();
+});
diff --git a/apps/mobile/src/__tests__/pluginOriginalSettings.test.tsx b/apps/mobile/src/__tests__/pluginOriginalSettings.test.tsx
new file mode 100644
index 0000000000..0e66637428
--- /dev/null
+++ b/apps/mobile/src/__tests__/pluginOriginalSettings.test.tsx
@@ -0,0 +1,148 @@
+// @vitest-environment jsdom
+import { act, createElement } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, expect, it, vi } from "vitest";
+import { Alert } from "react-native";
+import * as WebBrowser from "expo-web-browser";
+import { PluginOriginalSettings } from "../plugins/PluginOriginalSettings";
+
+// Card callbacks exercise the original settings boundary without a native WebView or credentials.
+const state = vi.hoisted(() => ({ card: {} as any, notice: undefined as any, owner: true, authorize: vi.fn() }));
+vi.mock("react-native", async () => {
+ const React = await import("react");
+ return {
+ View: (p: any) => React.createElement("div", { style: p.style, "data-testid": p.testID, "aria-hidden": p.accessibilityElementsHidden }, p.children),
+ ActivityIndicator: (p: any) => React.createElement("div", { "data-testid": p.testID, role: "progressbar" }),
+ Alert: { alert: vi.fn() }, AppState: { currentState: "active" },
+ };
+});
+vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock("@/theme", () => ({ spacing: { md: 12 }, useTheme: () => ({ colors: {} }) }));
+vi.mock("@/auth/AuthContext", () => ({ useAuth: () => ({ deviceId: "phone", accountGeneration: 1 }) }));
+vi.mock("@/auth/authOwnerGeneration", () => ({ getMobileAuthOwner: () => "owner", isMobileAuthOwnerCurrent: () => state.owner }));
+vi.mock("@/device-link/DeviceLinkContext", () => ({ useDeviceLink: () => ({ connectionEpoch: 1, invoke: vi.fn() }) }));
+vi.mock("expo-web-browser", () => ({ openBrowserAsync: vi.fn() }));
+vi.mock("../plugins/PluginDirectoryPicker", () => ({ PluginDirectoryPicker: () => null }));
+vi.mock("../plugins/PluginSettingsCard", () => ({ PluginSettingsCard: (p: any) => { state.card = p; return null; } }));
+vi.mock("../plugins/PluginNotice", () => ({ PluginNotice: (p: any) => { state.notice = p; return p.title; } }));
+vi.mock("../plugins/pluginOauthSession", () => ({ openMobilePluginOauthSession: async () => ({ request: vi.fn(), dispose: vi.fn() }) }));
+vi.mock("../plugins/pluginAuthorizationController", () => ({ runMobilePluginAuthorization: (...args: any[]) => state.authorize(...args) }));
+vi.mock("../plugins/pluginOauthLoopbackNative", () => ({ receiveMobilePluginOauthLoopback: vi.fn() }));
+vi.mock("../plugins/pluginOauthPlatformCrypto", () => ({ pluginOauthPlatformCrypto: {} }));
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+let root: ReturnType<typeof createRoot>;
+afterEach(() => { act(() => root?.unmount()); state.notice = undefined; state.owner = true; vi.clearAllMocks(); });
+const identity = { deviceId: "mac", instanceId: "plugin", expectedInstalledApproval: "approval" } as any;
+function mount() {
+ const element = document.createElement("div");
+ root = createRoot(element);
+ const onNotice = vi.fn();
+ const render = (active: boolean, target = identity) => act(() => root.render(createElement(PluginOriginalSettings, { identity: target, active, onNotice })));
+ render(true);
+ return { onNotice, render, element };
+}
+it("shows a specific bridge-only authorization failure once, then accepts a new error", async () => {
+ const { onNotice } = mount();
+ const error = new Error("PLUGIN_AUTHORIZATION_COMPUTER_CALLBACK");
+ state.authorize.mockRejectedValueOnce(error);
+ await act(async () => { await expect(state.card.onAuthorize({})).rejects.toBe(error); });
+ expect(state.notice).toBeUndefined();
+ act(() => state.card.onError(new Error(error.message), "operation"));
+ expect(state.notice.detail).toBe("plugins.computerAuthorizationHint");
+ expect(state.notice.title).toBe("plugins.notice.title.authorization");
+ act(() => state.card.onError(new Error(error.message), "operation"));
+ expect(state.notice.title).toBe("plugins.notice.title.writeFailed");
+ expect(onNotice).not.toHaveBeenCalled();
+});
+it("keeps read and unknown results local and rejects stale inactive or replacement-target callbacks", () => {
+ const { render, onNotice } = mount();
+ act(() => state.card.onError(new Error("read"), "read"));
+ expect(state.notice.title).toBe("plugins.notice.title.readFailed");
+ act(() => state.card.onError(new Error("unknown"), "unknown"));
+ expect(state.notice.title).toBe("plugins.notice.title.resultUnknown");
+ const stale = state.card;
+ render(false);
+ act(() => { stale.onNotice("late"); stale.onError(new Error("late"), "operation"); });
+ expect(state.notice.title).toBe("plugins.notice.title.resultUnknown");
+ render(true, { ...identity, instanceId: "other" });
+ act(() => stale.onNotice("wrong target"));
+ expect(onNotice).not.toHaveBeenCalled();
+});
+
+
+it("lets the original form handle replied command failures without a duplicate native error", () => {
+ mount();
+ for (const context of ["read", "operation", "unknown"]) act(() => state.card.onError(new Error("PLUGIN_SETTINGS_UNAVAILABLE"), context, true));
+ expect(state.notice).toBeUndefined();
+ act(() => state.card.onError(new Error("PLUGIN_SETTINGS_DOWNLOAD_BLOCKED"), "operation"));
+ expect(state.notice.title).toBe("plugins.notice.title.writeFailed");
+ expect(state.notice.compact).toBe(true);
+});
+
+
+it.each(["OAUTH_BRIDGE_UNAVAILABLE", "PLUGIN_SETTINGS_AUTHORIZATION_CANCELLED", "PLUGIN_OAUTH_UPDATE_REQUIRED"])("delegates replied authorization failure %s to the page except required native upgrade", async (code) => {
+ mount();
+ state.authorize.mockRejectedValueOnce(new Error(code));
+ await act(async () => { await expect(state.card.onAuthorize({})).rejects.toThrow(code); });
+ expect(state.notice).toBeUndefined();
+ act(() => state.card.onError(new Error(code), "operation", true));
+ if (code === "PLUGIN_OAUTH_UPDATE_REQUIRED") expect(state.notice.detail).toBe("plugins.oauthUpdateRequired");
+ else expect(state.notice).toBeUndefined();
+});
+
+it("does not retain a native error for a cancelled authorization even without a page reply", async () => {
+ mount();
+ const code = "PLUGIN_SETTINGS_AUTHORIZATION_CANCELLED";
+ state.authorize.mockRejectedValueOnce(new Error(code));
+ await act(async () => { await expect(state.card.onAuthorize({})).rejects.toThrow(code); });
+ act(() => state.card.onError(new Error(code), "operation", false));
+ expect(state.notice).toBeUndefined();
+});
+
+it.each(["accept", "cancel", "stale"])("opens external links on this phone only after current-page confirmation (%s)", async (decision) => {
+ const { render } = mount();
+ const check = vi.fn();
+ let work!: Promise<void>;
+ await act(async () => { work = state.card.onOpenLink("https://example.com/console#keys", check); });
+ expect(WebBrowser.openBrowserAsync).not.toHaveBeenCalled();
+ const buttons = vi.mocked(Alert.alert).mock.calls.at(-1)![2]!;
+ if (decision === "stale") render(false);
+ await act(async () => {
+ buttons[decision === "cancel" ? 0 : 1].onPress!();
+ if (decision === "stale") await expect(work).rejects.toThrow("CLOSED");
+ else await work;
+ });
+ if (decision === "accept") expect(WebBrowser.openBrowserAsync).toHaveBeenCalledExactlyOnceWith("https://example.com/console#keys", { showTitle: true });
+ else expect(WebBrowser.openBrowserAsync).not.toHaveBeenCalled();
+});
+it.each(["javascript:alert(1)", "file:///tmp/x", "https://user:[email protected]", "https://example.com/\npath"])("refuses unsupported external navigation %s", async (url) => {
+ mount();
+ await expect(state.card.onOpenLink(url, () => {})).rejects.toThrow();
+ expect(Alert.alert).not.toHaveBeenCalled();
+ expect(WebBrowser.openBrowserAsync).not.toHaveBeenCalled();
+});
+it("explains target-local links without opening a phone-local service", async () => {
+ const { onNotice } = mount();
+ await state.card.onOpenLink("http://127.0.0.1:3923/console", () => {});
+ expect(onNotice).toHaveBeenCalledWith("plugins.settingsComputerLink");
+ expect(WebBrowser.openBrowserAsync).not.toHaveBeenCalled();
+});
+it("identifies the computer that needs the settings authorization update even after a page reply", () => {
+ mount();
+ act(() => state.card.onError(new Error("PLUGIN_SETTINGS_HOST_UPDATE_REQUIRED"), "operation", true));
+ expect(state.notice.detail).toBe("plugins.settingsHostUpdateRequired");
+});
+
+// User-reported blank interval: the real wrapper must keep a visible progress
+// indicator and disable the unpainted form until the card reports document readiness.
+// Existing callback tests did not inspect this presentation. Tier: unit, fake WebView only.
+it("shows progress in the configuration area until the page is ready, and on reload", () => {
+ const { element } = mount();
+ expect(element.querySelector('[role="progressbar"]')).not.toBeNull();
+ expect(element.querySelector('[aria-hidden="true"]')?.getAttribute("style")).toContain("opacity: 0");
+ act(() => state.card.onLoading(false));
+ expect(element.querySelector('[role="progressbar"]')).toBeNull();
+ expect(element.querySelector('[aria-hidden="true"]')).toBeNull();
+ act(() => state.card.onLoading(true));
+ expect(element.querySelectorAll('[role="progressbar"]')).toHaveLength(1);
+});
diff --git a/apps/mobile/src/__tests__/pluginSettingsBootstrap.test.ts b/apps/mobile/src/__tests__/pluginSettingsBootstrap.test.ts
new file mode 100644
index 0000000000..b5787a5184
--- /dev/null
+++ b/apps/mobile/src/__tests__/pluginSettingsBootstrap.test.ts
@@ -0,0 +1,304 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { createRequire } from "node:module";
+const { JSDOM } = createRequire(import.meta.url)("jsdom");
+import {
+ prepareSettingsHtml,
+ settingsBridgeAsset,
+} from "../plugins/pluginSettingsHtml";
+
+/* 测试价值
+ * 生产入口与可观察结果:settingsBridgeAsset 的实际预编译脚本;原页fetch/XHR、动态频道、主题和离页取消。
+ * Bug/规则依据:plugin-mobile-implementation「入口与页面」;protocol-compatibility「同账号远程插件管理」。
+ * 现有覆盖缺口:pluginPage只支持声明频道/Blob资源,不承载存量settingsHtml的独立同源桥。
+ * 最小失败输入:嵌套页面相对XHR、运行时频道、换主题时保留输入、超时后迟到回执。
+ * tier:unit;只有DOM执行需要JSDOM,不创建socket或原生WebView。
+ * 实测耗时:单文件墙钟 2.42s。
+ */
+const document = {
+ pageId: "settings",
+ pluginId: "_ns__example__test",
+ manifestId: "test",
+ name: "Original",
+ entry: "ui/settings.html",
+ files: [
+ { path: "ui/settings.html", mime: "text/html", size: 0 },
+ { path: "ui/data.json", mime: "application/json", size: 2 },
+ ],
+};
+const theme = {
+ dark: false,
+ colors: { "panel-bg": "ivory", "text-primary": "black" },
+};
+const cleanup: Array<() => void> = [];
+afterEach(() => {
+ for (const close of cleanup.splice(0)) close();
+ vi.useRealTimers();
+});
+function fixture(body = '<input id="field">') {
+ const messages: any[] = [];
+ const localFetch = vi.fn(
+ async () =>
+ new Response("{}", { headers: { "content-type": "application/json" } }),
+ );
+ const dom = new JSDOM(
+ "<!doctype html><html><head></head><body>" + body + "</body></html>",
+ {
+ url: "http://127.0.0.1:42300/ui/settings.html",
+ runScripts: "dangerously",
+ beforeParse(window: Window & typeof globalThis) {
+ Object.assign(window, {
+ Request,
+ Response,
+ Blob,
+ TextEncoder,
+ TextDecoder,
+ fetch: localFetch,
+ ReactNativeWebView: {
+ postMessage: (raw: string) => messages.push(JSON.parse(raw)),
+ },
+ });
+ },
+ },
+ );
+ cleanup.push(() => {
+ dom.window.dispatchEvent(new dom.window.Event("pagehide"));
+ dom.window.close();
+ });
+ const bridge = settingsBridgeAsset(document, theme);
+ dom.window.eval(bridge.text);
+ const reply = (id: number, value: unknown, ok = true) =>
+ dom.window.__cindySettingsReceive({ kind: "reply", id, ok, value });
+ return { dom, window: dom.window, messages, reply, localFetch };
+}
+describe("original settings generated bridge", () => {
+ // 用户实测:13px原页输入框聚焦触发iOS自动zoom并裁切卡片;现有主题测试不覆盖字号。
+ // unit最小输入:继承13px的文本控件、大字号/非文本控件,以及DOM-ready后新增子树。
+ it("raises only small editable control fonts while preserving drafts and disconnecting on close", async () => {
+ const f = fixture(`<style>body{font-size:13px}.input{font:inherit}</style>
+ <input id="small" class="input" value="unsaved draft">
+ <textarea id="area" style="font-size:12px">draft</textarea>
+ <select id="select" style="font-size:14px"><option>Choice</option></select>
+ <input id="large" style="font-size:22px">
+ <input id="check" type="checkbox" style="font-size:12px">`);
+ await new Promise<void>((resolve) =>
+ f.window.document.addEventListener("DOMContentLoaded", () => resolve(), {
+ once: true,
+ }),
+ );
+ const get = (id: string) => f.window.document.getElementById(id);
+ for (const id of ["small", "area", "select"])
+ expect(get(id).style.fontSize).toBe("16px");
+ expect(get("large").style.fontSize).toBe("22px");
+ expect(get("check").style.fontSize).toBe("12px");
+ expect(get("small").value).toBe("unsaved draft");
+ expect(get("area").value).toBe("draft");
+ const subtree = f.window.document.createElement("div");
+ subtree.innerHTML =
+ '<input id="dynamic" style="font-size:13px"><textarea id="dynamicLarge" style="font-size:20px"></textarea>';
+ f.window.document.body.append(subtree);
+ await Promise.resolve();
+ expect(get("dynamic").style.fontSize).toBe("16px");
+ expect(get("dynamicLarge").style.fontSize).toBe("20px");
+ f.window.dispatchEvent(new f.window.Event("pagehide"));
+ const later = f.window.document.createElement("input");
+ later.style.fontSize = "13px";
+ f.window.document.body.append(later);
+ await Promise.resolve();
+ expect(later.style.fontSize).toBe("13px");
+ });
+ it("keeps the original OAuth request pending through browser interaction without replaying it", async () => {
+ vi.useFakeTimers();
+ const f = fixture();
+ const work = f.window.fetch("/oauth/provider/connect", {
+ method: "POST",
+ body: "{}",
+ });
+ let settled = false;
+ void work.then(
+ () => {
+ settled = true;
+ },
+ () => {
+ settled = true;
+ },
+ );
+ await vi.advanceTimersByTimeAsync(31_000);
+ expect(settled).toBe(false);
+ const requests = f.messages.filter(
+ (message) => message.command?.kind === "fetch",
+ );
+ expect(requests).toHaveLength(1);
+ f.reply(requests[0].id, {
+ status: 200,
+ mime: "application/json",
+ base64: Buffer.from('{"accounts":["test"]}').toString("base64"),
+ });
+ expect(await (await work).json()).toEqual({ accounts: ["test"] });
+ });
+ it("routes fetch and asynchronous XHR through one settings request and preserves original HTTP results", async () => {
+ const f = fixture();
+ const fetchWork = f.window.fetch("cindy-ghost://test/kv", {
+ method: "PUT",
+ body: '{"mode":"manual"}',
+ });
+ expect(f.messages.at(-1).command).toEqual({
+ kind: "fetch",
+ path: "/kv",
+ method: "PUT",
+ body: '{"mode":"manual"}',
+ });
+ f.reply(f.messages.at(-1).id, {
+ status: 204,
+ base64: "",
+ mime: "application/json",
+ });
+ expect((await fetchWork).status).toBe(204);
+ const xhr = new f.window.XMLHttpRequest();
+ xhr.open("GET", "../kv");
+ xhr.responseType = "json";
+ const loaded = new Promise<void>((resolve) => {
+ xhr.onload = resolve;
+ });
+ xhr.send();
+ f.reply(f.messages.at(-1).id, {
+ status: 200,
+ base64: Buffer.from('{"fields":["中文","b"]}').toString("base64"),
+ mime: "application/json",
+ });
+ await loaded;
+ expect(xhr.response).toEqual({ fields: ["中文", "b"] });
+ expect(xhr.readyState).toBe(4);
+ expect(f.localFetch).not.toHaveBeenCalled();
+ });
+ it("keeps package fetches relative and denies network escape without issuing a native command", async () => {
+ const f = fixture();
+ await f.window.fetch("./data.json");
+ expect(f.localFetch).toHaveBeenCalledWith(
+ "http://127.0.0.1:42300/ui/data.json",
+ undefined,
+ );
+ await expect(f.window.fetch("https://example.invalid/kv")).rejects.toThrow(
+ "NETWORK_BLOCKED",
+ );
+ await expect(f.window.fetch("/not-in-package.js")).rejects.toThrow(
+ "NETWORK_BLOCKED",
+ );
+ expect(f.messages.filter((message) => message.command)).toEqual([]);
+ });
+ it("subscribes dynamically, posts only after registration and delivers the original result event", async () => {
+ const f = fixture(),
+ channel = new f.window.BroadcastChannel("original-runtime-channel");
+ await vi.waitFor(() =>
+ expect(
+ f.messages.find((message) => message.command?.kind === "subscribe"),
+ ).toBeDefined(),
+ );
+ channel.postMessage({ kind: "connect", fields: { region: "test" } });
+ expect(
+ f.messages.filter((message) => message.command?.kind === "post"),
+ ).toHaveLength(0);
+ f.reply(
+ f.messages.find((message) => message.command?.kind === "subscribe").id,
+ {},
+ );
+ await vi.waitFor(() =>
+ expect(
+ f.messages.find((message) => message.command?.kind === "post"),
+ ).toBeDefined(),
+ );
+ const received = vi.fn();
+ channel.onmessage = received;
+ f.window.__cindySettingsReceive({
+ kind: "events",
+ events: [
+ {
+ sequence: 1,
+ channel: channel.name,
+ data: { accounts: ["Test account"] },
+ },
+ ],
+ });
+ expect(received.mock.calls[0][0].data).toEqual({
+ accounts: ["Test account"],
+ });
+ f.reply(
+ f.messages.find((message) => message.command?.kind === "post").id,
+ {},
+ );
+ channel.close();
+ await vi.waitFor(() =>
+ expect(
+ f.messages.find((message) => message.command?.kind === "unsubscribe"),
+ ).toBeDefined(),
+ );
+ f.reply(
+ f.messages.find((message) => message.command?.kind === "unsubscribe").id,
+ {},
+ );
+ });
+ it("updates theme without replacing the original fields and rejects outstanding work on page hide", async () => {
+ const f = fixture(),
+ field = f.window.document.getElementById("field");
+ field.value = "unsaved non-secret";
+ f.window.__cindySettingsTheme({
+ dark: true,
+ colors: { "panel-bg": "charcoal" },
+ });
+ expect(f.window.document.documentElement.classList.contains("dark")).toBe(
+ true,
+ );
+ expect(
+ f.window.document.documentElement.style.getPropertyValue("--panel-bg"),
+ ).toBe("charcoal");
+ expect(field.value).toBe("unsaved non-secret");
+ const work = f.window.fetch("/kv");
+ f.window.dispatchEvent(new f.window.Event("pagehide"));
+ await expect(work).rejects.toThrow("CLOSED");
+ expect(field.value).toBe("");
+ f.reply(f.messages.at(-1).id, { status: 200, base64: "e30=" });
+ await expect(f.window.fetch("/kv")).rejects.toThrow("CLOSED");
+ });
+ it("injects a separate first script while preserving the original HTML and author viewport", () => {
+ const html =
+ '<html><head><meta name="viewport" content="width=700"><script type="module" src="./settings.js"></script></head><body class="author">Original</body></html>';
+ const prepared = prepareSettingsHtml(html, "__bridge.js");
+ expect(prepared).toContain(
+ '<head><script src="/__bridge.js"></script><style>',
+ );
+ expect(prepared).toContain(
+ '<script type="module" src="./settings.js"></script>',
+ );
+ expect(prepared).toContain('<body class="author">Original</body>');
+ expect(prepared.match(/name="viewport"/g)).toHaveLength(1);
+ });
+ it("keeps fresh credential submission off BC/storage and clears the input on leaving", async () => {
+ const f = fixture(),
+ field = f.window.document.getElementById("field");
+ field.type = "password";
+ field.value = "invalid-fixture-secret";
+ expect(() => f.window.localStorage.setItem("new-key", field.value)).toThrow(
+ "storage disabled",
+ );
+ expect(f.window.indexedDB).toBeUndefined();
+ expect(f.window.Worker).toBeUndefined();
+ const channel = new f.window.BroadcastChannel("original-settings");
+ expect(() => channel.postMessage({ credential: field.value })).toThrow(
+ "cannot use BroadcastChannel",
+ );
+ const work = f.window.fetch("/secrets/key", {
+ method: "PUT",
+ body: JSON.stringify({ value: field.value }),
+ });
+ const request = f.messages.find(
+ (message) => message.command?.kind === "fetch",
+ );
+ expect(request.command.path).toBe("/secrets/key");
+ f.reply(request.id, { status: 204, base64: "", mime: "application/json" });
+ await work;
+ expect(
+ f.messages.filter((message) => message.command?.kind === "post"),
+ ).toHaveLength(0);
+ f.window.dispatchEvent(new f.window.Event("pagehide"));
+ expect(field.value).toBe("");
+ });
+});
diff --git a/apps/mobile/src/__tests__/pluginSettingsCard.test.tsx b/apps/mobile/src/__tests__/pluginSettingsCard.test.tsx
new file mode 100644
index 0000000000..1f060f26c8
--- /dev/null
+++ b/apps/mobile/src/__tests__/pluginSettingsCard.test.tsx
@@ -0,0 +1,527 @@
+// @vitest-environment jsdom
+import { act, createElement } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, expect, it, vi } from "vitest";
+import { PluginSettingsCard } from "../plugins/PluginSettingsCard";
+import { openPluginSettingsClient } from "../plugins/pluginSettingsClient";
+
+/* 测试价值
+ * 生产入口与结果:PluginSettingsCard,浏览器授权覆盖/后台期间保留lease,返回后重建原资源且不重放保存。
+ * 规则依据:plugin-mobile-implementation 配置与授权;原生预览资源后台停止的既有生命周期。
+ * 覆盖缺口:client/资源测试不执行React effect,无法发现AppState造成授权中途销毁或回前台重复提交。
+ * 最小输入:一个挂起的授权请求、background→active、一次真实结果;资源/Host均为内存假对象。
+ * tier:unit;不启动原生应用、不读用户数据、不验证真实OAuth。
+ * 实测耗时:单文件墙钟 1.71s。
+ */
+const state = vi.hoisted(() => ({
+ windowHeight: 800,
+ cardStyle: undefined as any,
+ appState: "active",
+ listener: undefined as undefined | ((value: string) => void),
+ web: undefined as any,
+ options: [] as any[],
+ clients: [] as any[],
+ resources: [] as any[],
+ inject: vi.fn(),
+ colors: {} as Record<string, string>,
+}));
+vi.mock("react-native", async () => {
+ const React = await import("react");
+ return {
+ useWindowDimensions: () => ({
+ width: 390,
+ height: state.windowHeight,
+ scale: 1,
+ fontScale: 1,
+ }),
+ AppState: {
+ get currentState() {
+ return state.appState;
+ },
+ addEventListener: (_: string, fn: any) => {
+ state.listener = fn;
+ return {
+ remove() {
+ state.listener = undefined;
+ },
+ };
+ },
+ },
+ StyleSheet: { create: (value: unknown) => value, hairlineWidth: 1 },
+ View: (p: any) => {
+ state.cardStyle = Object.assign({}, ...p.style);
+ return React.createElement("div", null, p.children);
+ },
+ };
+});
+vi.mock("react-native-webview", async () => {
+ const React = await import("react");
+ return {
+ default: React.forwardRef((p: any, ref) => {
+ state.web = p;
+ React.useImperativeHandle(ref, () => ({
+ injectJavaScript: state.inject,
+ }));
+ return React.createElement("div");
+ }),
+ };
+});
+vi.mock("@/theme", () => ({
+ motionDuration: { fast: 100, spinnerCycle: 1000 },
+ motionEasing: { out: [0, 0, 1, 1] },
+ radius: { container: 12 },
+ spacing: { lg: 16 },
+ useTheme: () => ({ colors: state.colors, mode: "light" }),
+}));
+vi.mock("../plugins/pluginSettingsResources", () => ({
+ preparePluginSettingsResources: vi.fn(async () => {
+ const resource = {
+ url: "http://127.0.0.1:1/__cindy/fixture-token",
+ close: vi.fn(async () => {}),
+ };
+ state.resources.push(resource);
+ return resource;
+ }),
+}));
+vi.mock("../plugins/pluginSettingsClient", () => ({
+ openPluginSettingsClient: vi.fn(async (options: any) => {
+ state.options.push(options);
+ const client = {
+ document: {
+ pageId: "page",
+ files: [{ path: "settings.html", mime: "text/html" }],
+ },
+ assertCurrent: options.assertCurrent,
+ close: vi.fn(async () => {
+ options.assertCleanupCurrent();
+ }),
+ send: vi.fn(async () => ({
+ events: [],
+ notifications: [],
+ confirms: [],
+ })),
+ fetch: vi.fn(async () => {
+ await options.onAuthorize({
+ requestId: "auth",
+ actionId: "connect",
+ expectedRevision: 0,
+ });
+ return {
+ status: 200,
+ base64: Buffer.from('{"connected":true}').toString("base64"),
+ mime: "application/json",
+ };
+ }),
+ };
+ state.clients.push(client);
+ return client;
+ }),
+}));
+let cleanup: (() => Promise<void>) | undefined;
+afterEach(async () => {
+ await cleanup?.();
+ cleanup = undefined;
+ state.options = [];
+ state.clients = [];
+ state.resources = [];
+ state.windowHeight = 800;
+ state.cardStyle = undefined;
+ state.appState = "active";
+ state.web = undefined;
+ vi.useRealTimers();
+ vi.clearAllMocks();
+});
+it.each([false, true])(
+ "retains the authorizing lease and delivers notices only to the current identity (replaced=%s)",
+ async (replaced) => {
+ (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+ vi.useFakeTimers();
+ let finish!: () => void;
+ const authorization = new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+ const ownerGuard = vi.fn();
+ const onNotice = vi.fn();
+ const props = {
+ identity: {
+ deviceId: "host",
+ instanceId: "plugin",
+ expectedInstalledApproval: "approval",
+ },
+ active: true,
+ generation: 1,
+ assertCurrent: ownerGuard,
+ assertCleanupCurrent: ownerGuard,
+ invokeTarget: vi.fn(),
+ openSession: vi.fn(),
+ onAuthorize: () => authorization,
+ onNotice,
+ };
+ const element = document.createElement("div");
+ document.body.append(element);
+ const root = createRoot(element);
+ cleanup = async () => {
+ await act(async () => root.unmount());
+ element.remove();
+ };
+ await act(async () =>
+ root.render(createElement(PluginSettingsCard, props)),
+ );
+ expect(state.clients).toHaveLength(1);
+ // A poll can finish after the browser covers the page; Host notices are consumed on read.
+ let finishPoll!: (value: unknown) => void;
+ state.clients[0].send.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finishPoll = resolve;
+ }),
+ );
+ await act(async () => state.web.onLoad());
+ await act(async () =>
+ state.web.onMessage({
+ nativeEvent: {
+ data: JSON.stringify({
+ settings: "page",
+ id: 1,
+ command: {
+ kind: "fetch",
+ path: "/oauth/main/connect",
+ method: "POST",
+ },
+ }),
+ },
+ }),
+ );
+ await act(async () => {
+ state.appState = "background";
+ state.listener?.("background");
+ });
+ await act(async () =>
+ finishPoll({
+ events: [],
+ confirms: [],
+ notifications: [{ text: "Account connected" }],
+ }),
+ );
+ await act(async () => vi.advanceTimersByTimeAsync(1600));
+ expect(onNotice).not.toHaveBeenCalled();
+ expect(state.clients[0].send).toHaveBeenCalledTimes(1);
+ expect(state.clients[0].close).not.toHaveBeenCalled();
+ expect(state.resources[0].close).not.toHaveBeenCalled();
+ await act(async () => {
+ state.appState = "active";
+ state.listener?.("active");
+ if (replaced)
+ root.render(
+ createElement(PluginSettingsCard, { ...props, generation: 2 }),
+ );
+ finish();
+ });
+ if (replaced) expect(onNotice).not.toHaveBeenCalled();
+ else expect(onNotice).toHaveBeenCalledExactlyOnceWith("Account connected");
+ expect(state.clients).toHaveLength(2);
+ expect(state.clients[0].fetch).toHaveBeenCalledTimes(1);
+ expect(state.clients[1].fetch).not.toHaveBeenCalled();
+ expect(state.clients[0].close).toHaveBeenCalledTimes(1);
+ expect(state.resources[0].close).toHaveBeenCalledTimes(1);
+ expect(state.options[0].assertCleanupCurrent).toBe(ownerGuard);
+ expect(
+ state.inject.mock.calls.some(([script]) =>
+ script.includes(Buffer.from('{"connected":true}').toString("base64")),
+ ),
+ ).toBe(!replaced);
+ },
+);
+
+// A failed opening and an unacknowledged write previously became the same notice.
+it.each(["load", "read", "unknown", "readBridge"] as const)(
+ "reports %s in the actual card callback without replaying a request",
+ async (context) => {
+ (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+ const onError = vi.fn();
+ if (context === "load")
+ vi.mocked(openPluginSettingsClient).mockRejectedValueOnce(
+ new Error("PLUGIN_SETTINGS_UNAVAILABLE"),
+ );
+ const root = createRoot(document.createElement("div"));
+ cleanup = async () => {
+ await act(async () => root.unmount());
+ };
+ await act(async () =>
+ root.render(
+ createElement(PluginSettingsCard, {
+ identity: {
+ deviceId: "host",
+ instanceId: "plugin",
+ expectedInstalledApproval: "approval",
+ },
+ active: true,
+ generation: 1,
+ assertCurrent() {},
+ invokeTarget: vi.fn(),
+ openSession: vi.fn(),
+ onError,
+ }),
+ ),
+ );
+ if (context !== "load") {
+ const client = state.clients[0];
+ client.fetch.mockRejectedValueOnce(
+ Object.assign(
+ new Error("RESPONSE_LOST"),
+ context === "unknown" ? { settingsOutcome: "unknown" } : {},
+ ),
+ );
+ if (context === "readBridge")
+ state.inject.mockImplementationOnce(() => {
+ throw new Error("native injection unavailable");
+ });
+ await act(async () =>
+ state.web.onMessage({
+ nativeEvent: {
+ data: JSON.stringify({
+ settings: "page",
+ id: 1,
+ command: {
+ kind: "fetch",
+ path: "/kv",
+ method: context === "unknown" ? "PUT" : "GET",
+ ...(context === "unknown" ? { body: "{}" } : {}),
+ },
+ }),
+ },
+ }),
+ );
+ expect(client.fetch).toHaveBeenCalledOnce();
+ }
+ if (context === "load")
+ expect(onError).toHaveBeenCalledWith(expect.any(Error), context);
+ else
+ expect(onError).toHaveBeenCalledWith(
+ expect.any(Error),
+ context === "readBridge" ? "read" : context,
+ context !== "readBridge",
+ );
+ },
+);
+
+// 用户要求配置卡片有内边距和高度上限;现有授权用例未覆盖页面高度消息。
+// unit:同一生产组件依次接收短/长页面高度,再改变窗口尺寸,检查滚动及原会话保留。
+it("bounds original settings content and resizes without replacing its document or lease", async () => {
+ (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+ const props = {
+ identity: {
+ deviceId: "host",
+ instanceId: "plugin",
+ expectedInstalledApproval: "approval",
+ },
+ active: true,
+ generation: 1,
+ assertCurrent() {},
+ invokeTarget: vi.fn(),
+ openSession: vi.fn(),
+ };
+ const root = createRoot(document.createElement("div"));
+ cleanup = async () => {
+ await act(async () => root.unmount());
+ };
+ const render = () => root.render(createElement(PluginSettingsCard, props));
+ await act(async () => render());
+ const source = state.web.source.uri;
+ const reportHeight = async (height: number) =>
+ act(async () =>
+ state.web.onMessage({
+ nativeEvent: { data: JSON.stringify({ settings: "page", height }) },
+ }),
+ );
+ await reportHeight(100);
+ expect(state.cardStyle.height).toBe(132);
+ expect(state.cardStyle.padding).toBe(16);
+ expect(state.web.style.height).toBe(100);
+ expect(state.web.scrollEnabled).toBe(false);
+ await reportHeight(2000);
+ expect(state.cardStyle.height).toBe(400);
+ expect(state.web.style.height).toBe(368);
+ expect(state.web.scrollEnabled).toBe(true);
+ expect(state.web.nestedScrollEnabled).toBe(true);
+ state.windowHeight = 600;
+ await act(async () => render());
+ expect(state.cardStyle.height).toBe(300);
+ expect(state.web.style.height).toBe(268);
+ state.windowHeight = 1000;
+ await act(async () => render());
+ expect(state.cardStyle.height).toBe(420);
+ expect(state.web.source.uri).toBe(source);
+ expect(state.clients).toHaveLength(1);
+ expect(state.resources).toHaveLength(1);
+ expect(state.clients[0].close).not.toHaveBeenCalled();
+});
+
+it("routes external anchors and new windows once, keeps package navigation local, and rejects stale links", async () => {
+ (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+ let finish!: () => void;
+ const onOpenLink = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const props = {
+ identity: {
+ deviceId: "host",
+ instanceId: "plugin",
+ expectedInstalledApproval: "approval",
+ },
+ active: true,
+ generation: 1,
+ assertCurrent: vi.fn(),
+ invokeTarget: vi.fn(),
+ openSession: vi.fn(),
+ onOpenLink,
+ };
+ const element = document.createElement("div"),
+ root = createRoot(element);
+ cleanup = async () => {
+ await act(async () => root.unmount());
+ };
+ await act(async () => root.render(createElement(PluginSettingsCard, props)));
+ const web = state.web;
+ expect(
+ web.onShouldStartLoadWithRequest({ url: web.source.uri + "#section" }),
+ ).toBe(true);
+ const url = "https://example.com/console#keys";
+ await act(async () => {
+ expect(web.onShouldStartLoadWithRequest({ url })).toBe(false);
+ web.onOpenWindow({ nativeEvent: { targetUrl: url } });
+ });
+ expect(onOpenLink).toHaveBeenCalledExactlyOnceWith(url, expect.any(Function));
+ await act(async () => {
+ finish();
+ });
+ await act(async () =>
+ root.render(
+ createElement(PluginSettingsCard, {
+ ...props,
+ identity: { ...props.identity, instanceId: "other" },
+ }),
+ ),
+ );
+ await act(async () => web.onOpenWindow({ nativeEvent: { targetUrl: url } }));
+ expect(onOpenLink).toHaveBeenCalledTimes(1);
+});
+
+// Regression: downloading the package is not a rendered WebView. Unit callback sequence
+// covers the reported spinner-free blank interval, navigation, failure and stale pages.
+it("keeps loading through resource preparation until WebView loads, including reload and failure", async () => {
+ (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+ const onLoading = vi.fn(),
+ onError = vi.fn();
+ const props = {
+ identity: {
+ deviceId: "host",
+ instanceId: "plugin",
+ expectedInstalledApproval: "approval",
+ },
+ active: true,
+ generation: 1,
+ assertCurrent: vi.fn(),
+ invokeTarget: vi.fn(),
+ openSession: vi.fn(),
+ onLoading,
+ onError,
+ };
+ const root = createRoot(document.createElement("div"));
+ cleanup = async () => {
+ await act(async () => root.unmount());
+ };
+ await act(async () => root.render(createElement(PluginSettingsCard, props)));
+ expect(state.web.source.uri).toBeTruthy();
+ expect(onLoading).toHaveBeenLastCalledWith(true);
+ const first = state.web;
+ await act(async () => first.onLoad());
+ expect(onLoading).toHaveBeenLastCalledWith(false);
+ await act(async () => first.onLoadStart());
+ expect(onLoading).toHaveBeenLastCalledWith(true);
+ await act(async () => first.onError());
+ expect(onLoading).toHaveBeenLastCalledWith(false);
+ expect(onError).toHaveBeenLastCalledWith(expect.any(Error), "load");
+ await act(async () =>
+ root.render(createElement(PluginSettingsCard, { ...props, generation: 2 })),
+ );
+ expect(onLoading).toHaveBeenLastCalledWith(true);
+ await act(async () => first.onLoad());
+ expect(onLoading).toHaveBeenLastCalledWith(true);
+});
+
+// Each HTML document restarts its bridge request IDs. A late response must not
+// resolve the new document's request with the same ID, or report its old error.
+it.each([false, true])(
+ "discards pending replies after in-package navigation (failed=%s)",
+ async (failed) => {
+ (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+ const onError = vi.fn();
+ const root = createRoot(document.createElement("div"));
+ cleanup = async () => {
+ await act(async () => root.unmount());
+ };
+ await act(async () =>
+ root.render(
+ createElement(PluginSettingsCard, {
+ identity: {
+ deviceId: "host",
+ instanceId: "plugin",
+ expectedInstalledApproval: "approval",
+ },
+ active: true,
+ generation: 1,
+ assertCurrent() {},
+ invokeTarget: vi.fn(),
+ openSession: vi.fn(),
+ onError,
+ }),
+ ),
+ );
+ let finish!: () => void;
+ state.clients[0].fetch.mockImplementationOnce(
+ () =>
+ new Promise((resolve, reject) => {
+ finish = () =>
+ failed
+ ? reject(new Error("OLD_DOCUMENT_FAILED"))
+ : resolve({ oldDocument: true });
+ }),
+ );
+ await act(async () =>
+ state.web.onMessage({
+ nativeEvent: {
+ data: JSON.stringify({
+ settings: "page",
+ id: 1,
+ command: { kind: "fetch", path: "/kv", method: "GET" },
+ }),
+ },
+ }),
+ );
+ await act(async () => state.web.onLoadStart());
+ state.inject.mockClear();
+ await act(async () => finish());
+ expect(state.inject).not.toHaveBeenCalled();
+ expect(onError).not.toHaveBeenCalled();
+ state.clients[0].fetch.mockResolvedValueOnce({ newDocument: true });
+ await act(async () =>
+ state.web.onMessage({
+ nativeEvent: {
+ data: JSON.stringify({
+ settings: "page",
+ id: 1,
+ command: { kind: "fetch", path: "/kv", method: "GET" },
+ }),
+ },
+ }),
+ );
+ expect(state.inject).toHaveBeenCalledWith(
+ expect.stringContaining('"newDocument":true'),
+ );
+ expect(state.clients[0].fetch).toHaveBeenCalledTimes(2);
+ },
+);
diff --git a/apps/mobile/src/__tests__/pluginSettingsClient.test.ts b/apps/mobile/src/__tests__/pluginSettingsClient.test.ts
new file mode 100644
index 0000000000..6fe7bce6da
--- /dev/null
+++ b/apps/mobile/src/__tests__/pluginSettingsClient.test.ts
@@ -0,0 +1,344 @@
+import { describe, expect, it, vi } from "vitest";
+import type { PluginOauthRequest } from "@cindy/device-link";
+import {
+ openPluginSettingsClient,
+ isPluginSettingsFetch,
+ parsePluginSettingsDocument,
+} from "../plugins/pluginSettingsClient";
+import { readPluginSettingsAsset } from "../plugins/pluginSettingsAssets";
+
+/* 测试价值
+ * 生产入口与可观察结果:openPluginSettingsClient/readPluginSettingsAsset,目标绑定、原页KV回显和未知保存不重放。
+ * Bug/规则依据:plugin-mobile-implementation「配置与授权」;protocol-compatibility「同账号远程插件管理」。
+ * 现有覆盖缺口:remotePluginSettings 测Desktop Main;pluginPage 测普通页面,不经过手机专用settings client。
+ * 最小失败输入:跨实例文档、轮换中的并发请求、已提交但丢失回执、资源截短、读取中换账号。
+ * tier:unit;内存transport/clock,不使用网络、原生应用或真实密钥。
+ * 实测耗时:单文件墙钟 2.32s。
+ */
+const document = {
+ pageId: "page",
+ pluginId: "_ns__example__test",
+ manifestId: "test",
+ name: "Original",
+ entry: "ui/settings.html",
+ controllerAuthorization: true,
+ files: [{ path: "ui/settings.html", size: 1, mime: "text/html" }],
+};
+function fixture() {
+ let time = 0,
+ valid = true;
+ const request = vi.fn(
+ async (_request: PluginOauthRequest): Promise<unknown> => ({
+ status: 200,
+ base64: Buffer.from('{"enabled":true}').toString("base64"),
+ mime: "application/json",
+ }),
+ );
+ const dispose = vi.fn();
+ const openSession = vi.fn(async () => ({ request, dispose }));
+ const invokeTarget = vi.fn(async () => ({ result: document }));
+ return {
+ request,
+ openSession,
+ dispose,
+ invokeTarget,
+ advance: () => {
+ time += 240_000;
+ },
+ invalidate: () => {
+ valid = false;
+ },
+ options: {
+ identity: {
+ deviceId: "computer",
+ instanceId: document.pluginId,
+ expectedInstalledApproval: "approval",
+ },
+ invokeTarget,
+ openSession,
+ assertCurrent: () => {
+ if (!valid) throw new Error("STALE_OWNER");
+ },
+ now: () => time,
+ },
+ };
+}
+describe("dedicated mobile original settings client", () => {
+ // Real Host ghostFileMime includes charset; the bare-MIME fixture missed this contract.
+ it("accepts the Host UTF-8 document and preserves MIME for exact asset verification", () => {
+ const hostDocument = {
+ ...document,
+ files: [{ ...document.files[0], mime: "text/html; charset=utf-8" }],
+ };
+ expect(
+ parsePluginSettingsDocument(hostDocument, document.pluginId).files[0]
+ .mime,
+ ).toBe("text/html; charset=utf-8");
+ for (const mime of [
+ "text/html\r\nX-Test: value",
+ "text/html-invalid",
+ "text/html; charset=utf-8\r\n",
+ ]) {
+ expect(() =>
+ parsePluginSettingsDocument(
+ { ...hostDocument, files: [{ ...hostDocument.files[0], mime }] },
+ document.pluginId,
+ ),
+ ).toThrow();
+ }
+ });
+ it("releases a hidden page with the captured cleanup guard while refusing further page writes", async () => {
+ const f = fixture();
+ let visible = true;
+ const client = await openPluginSettingsClient({
+ ...f.options,
+ assertCurrent: () => {
+ f.options.assertCurrent();
+ if (!visible) throw new Error("PAGE_HIDDEN");
+ },
+ assertCleanupCurrent: f.options.assertCurrent,
+ });
+ visible = false;
+ await expect(client.fetch("/kv", "PUT", "{}")).rejects.toThrow(
+ "PAGE_HIDDEN",
+ );
+ await client.close();
+ expect(f.request).toHaveBeenLastCalledWith({
+ op: "settings",
+ id: "page",
+ command: { kind: "close" },
+ });
+ expect(f.openSession).toHaveBeenCalledTimes(1);
+ });
+ it("binds the physical instance/approval and uses only the signed settings session for configuration", async () => {
+ const f = fixture(),
+ client = await openPluginSettingsClient(f.options);
+ expect(f.invokeTarget.mock.calls[0]).toMatchObject([
+ expect.any(String),
+ [
+ {
+ resourceRef: { id: document.pluginId },
+ input: { expectedInstalledApproval: "approval" },
+ },
+ ],
+ ]);
+ expect(f.openSession).toHaveBeenCalledWith({
+ actionId: "settings-page",
+ requestId: "page",
+ expectedRevision: 0,
+ });
+ expect(await client.fetch("/kv", "PUT", '{"enabled":true}')).toMatchObject({
+ status: 200,
+ });
+ expect(f.request).toHaveBeenCalledWith({
+ op: "settings",
+ id: "page",
+ command: {
+ kind: "fetch",
+ path: "/kv",
+ method: "PUT",
+ body: '{"enabled":true}',
+ },
+ });
+ expect(f.invokeTarget).toHaveBeenCalledTimes(1);
+ await expect(client.fetch("/secrets/key", "GET")).rejects.toThrow(
+ "ENDPOINT_BLOCKED",
+ );
+ await expect(client.fetch("https://example.invalid/kv")).rejects.toThrow(
+ "ENDPOINT_BLOCKED",
+ );
+ await client.close();
+ expect(f.dispose).toHaveBeenCalledOnce();
+ });
+ it("submits new credentials only in the dedicated exchange and reuses the original OAuth HTTP result", async () => {
+ const f = fixture();
+ const authorize = vi.fn(async () => {});
+ const client = await openPluginSettingsClient({
+ ...f.options,
+ onAuthorize: authorize,
+ });
+ await client.fetch(
+ "/secrets/key",
+ "PUT",
+ '{"value":"invalid-fixture-key"}',
+ );
+ expect(f.request).toHaveBeenLastCalledWith({
+ op: "settings",
+ id: "page",
+ command: {
+ kind: "fetch",
+ path: "/secrets/key",
+ method: "PUT",
+ body: '{"value":"invalid-fixture-key"}',
+ },
+ });
+ f.request.mockImplementation(async (request) =>
+ request.op === "settings" && request.command.kind === "authorize"
+ ? {
+ requestId: "oauth-ticket",
+ actionId: "settings-oauth",
+ expectedRevision: 0,
+ }
+ : {
+ status: 200,
+ mime: "application/json",
+ base64: Buffer.from(
+ '{"accounts":[{"id":"test-account"}]}',
+ ).toString("base64"),
+ },
+ );
+ expect(
+ await client.fetch("/oauth/provider/connect", "POST", "{}"),
+ ).toMatchObject({
+ base64: Buffer.from('{"accounts":[{"id":"test-account"}]}').toString(
+ "base64",
+ ),
+ });
+ expect(authorize).toHaveBeenCalledWith({
+ requestId: "oauth-ticket",
+ actionId: "settings-oauth",
+ expectedRevision: 0,
+ });
+ expect(f.request).toHaveBeenLastCalledWith({
+ op: "settings",
+ id: "page",
+ command: { kind: "authorization-result", requestId: "oauth-ticket" },
+ });
+ expect(f.invokeTarget).toHaveBeenCalledTimes(1);
+ await client.close();
+ });
+ it.each([undefined, false, "true"])("refuses OAuth on a Host without settings routing (%s) before creating an action", async (controllerAuthorization) => {
+ const f = fixture();
+ f.invokeTarget.mockResolvedValue({ result: { ...document, controllerAuthorization } } as any);
+ const onAuthorize = vi.fn();
+ const client = await openPluginSettingsClient({ ...f.options, onAuthorize });
+ await expect(client.fetch("/oauth/provider/connect", "POST", "{}")).rejects.toThrow("PLUGIN_SETTINGS_HOST_UPDATE_REQUIRED");
+ expect(f.request).not.toHaveBeenCalled();
+ expect(onAuthorize).not.toHaveBeenCalled();
+ // Existing configuration reads and writes remain available on older computers.
+ await expect(client.fetch("/kv")).resolves.toMatchObject({ status: 200 });
+ await client.close();
+ });
+ it("reports an unavailable loopback result without pretending browser dismissal completed authorization", async () => {
+ const f = fixture();
+ const client = await openPluginSettingsClient({
+ ...f.options,
+ onAuthorize: async () => {
+ throw new Error("PLUGIN_AUTHORIZATION_COMPUTER_CALLBACK");
+ },
+ });
+ f.request.mockImplementation(async (request) => {
+ if (request.op === "settings" && request.command.kind === "authorize")
+ return {
+ requestId: "oauth-ticket",
+ actionId: "settings-oauth",
+ expectedRevision: 0,
+ };
+ throw new Error("NO_RESULT");
+ });
+ await expect(
+ client.fetch("/oauth/provider/connect", "POST"),
+ ).rejects.toThrow("PLUGIN_AUTHORIZATION_COMPUTER_CALLBACK");
+ await client.close();
+ });
+ it("renews once for concurrent reads and never replays a write whose response was lost", async () => {
+ const f = fixture(),
+ client = await openPluginSettingsClient(f.options);
+ f.advance();
+ await Promise.all([client.fetch("/kv"), client.fetch("/agent-models")]);
+ expect(f.openSession).toHaveBeenCalledTimes(2);
+ f.request.mockRejectedValueOnce(new Error("RESPONSE_LOST"));
+ await expect(client.fetch("/kv", "PUT", "{}")).rejects.toMatchObject({
+ message: "RESPONSE_LOST",
+ settingsOutcome: "unknown",
+ });
+ f.request.mockRejectedValueOnce(new Error("READ_LOST"));
+ await expect(client.fetch("/kv")).rejects.not.toHaveProperty(
+ "settingsOutcome",
+ );
+ await expect(
+ client.fetch("https://invalid.example/kv", "PUT", "{}"),
+ ).rejects.not.toHaveProperty("settingsOutcome");
+ expect(
+ f.request.mock.calls.filter(
+ ([value]) =>
+ value.op === "settings" &&
+ value.command.kind === "fetch" &&
+ value.command.method === "PUT",
+ ),
+ ).toHaveLength(1);
+ await client.close();
+ });
+ it("rejects late responses after an owner change and does not open a new cleanup session", async () => {
+ const f = fixture(),
+ client = await openPluginSettingsClient(f.options);
+ let answer!: (value: unknown) => void;
+ f.request.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ answer = resolve;
+ }),
+ );
+ const work = client.fetch("/kv");
+ f.invalidate();
+ answer({ status: 200 });
+ await expect(work).rejects.toThrow("STALE_OWNER");
+ await client.close();
+ expect(f.openSession).toHaveBeenCalledTimes(1);
+ await expect(client.fetch("/kv")).rejects.toThrow("UNAVAILABLE");
+ });
+ it("rejects a different instance or unsafe/duplicate package declaration", () => {
+ for (const changed of [
+ { pageId: undefined },
+ { manifestId: undefined },
+ { pluginId: "other" },
+ { entry: "../settings.html" },
+ { files: [...document.files, ...document.files] },
+ ])
+ expect(() =>
+ parsePluginSettingsDocument(
+ { ...document, ...changed },
+ document.pluginId,
+ ),
+ ).toThrow("UNAVAILABLE");
+ });
+ it("assembles the final unaligned chunk and refuses truncated bytes or a stale source", async () => {
+ const bytes = Buffer.alloc(48 * 1024 + 13, 194);
+ const file = {
+ path: "ui/settings.js",
+ mime: "application/javascript",
+ size: bytes.length,
+ };
+ const read = vi.fn(async (_path: string, offset: number) => ({
+ mime: file.mime,
+ base64: bytes.subarray(offset, offset + 48 * 1024).toString("base64"),
+ }));
+ expect(await readPluginSettingsAsset(file, read, () => {})).toEqual(
+ new Uint8Array(bytes),
+ );
+ await expect(
+ readPluginSettingsAsset(
+ { ...file, size: 3 },
+ async () => ({ mime: file.mime, base64: "YQ==" }),
+ () => {},
+ ),
+ ).rejects.toThrow("ASSET_INVALID");
+ const stale = vi.fn(() => {
+ throw new Error("STALE_OWNER");
+ });
+ await expect(readPluginSettingsAsset(file, read, stale)).rejects.toThrow(
+ "STALE_OWNER",
+ );
+ });
+});
+
+it('routes only the fixed credential check through encrypted settings and never replays it', async () => {
+ expect(isPluginSettingsFetch('/secrets/key/check', 'POST')).toBe(true);
+ for (const method of ['GET', 'PUT', 'DELETE']) expect(isPluginSettingsFetch('/secrets/key/check', method)).toBe(false);
+ expect(isPluginSettingsFetch('/secrets/key/other', 'POST')).toBe(false);
+ const f = fixture();
+ const client = await openPluginSettingsClient(f.options);
+ await client.fetch('/secrets/key/check', 'POST', '{"value":"fake-check-key"}');
+ expect(f.request).toHaveBeenCalledTimes(1);
+ await client.close();
+});
diff --git a/apps/mobile/src/__tests__/pluginSettingsResources.test.ts b/apps/mobile/src/__tests__/pluginSettingsResources.test.ts
new file mode 100644
index 0000000000..64c6d360b7
--- /dev/null
+++ b/apps/mobile/src/__tests__/pluginSettingsResources.test.ts
@@ -0,0 +1,221 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+const state = vi.hoisted(() => ({
+ files: new Map<string, string | Uint8Array>(),
+ removed: [] as string[],
+}));
+const native = vi.hoisted(() => ({
+ start: vi.fn(
+ async (
+ _root: string,
+ _entry: string,
+ _token: string,
+ _csp: string,
+ _files: string[][],
+ ) => "http://127.0.0.1:42300/__cindy/test",
+ ),
+ stop: vi.fn(async (_token: string) => {}),
+}));
+vi.mock("../../modules/cindy-html-preview/src/CindyHtmlPreviewModule", () => ({
+ default: native,
+}));
+vi.mock("expo-crypto", () => ({
+ getRandomBytes: (length: number) => new Uint8Array(length).fill(2),
+}));
+vi.mock("expo-file-system", () => ({
+ Paths: { cache: "file:///cache" },
+ Directory: class {
+ uri: string;
+ exists = false;
+ constructor(...parts: string[]) {
+ this.uri = parts.join("/");
+ }
+ create() {
+ this.exists = true;
+ }
+ delete() {
+ this.exists = false;
+ state.removed.push(this.uri);
+ }
+ },
+ File: class {
+ name: string;
+ constructor(_dir: unknown, name: string) {
+ this.name = name;
+ }
+ create() {}
+ write(value: string | Uint8Array) {
+ state.files.set(this.name, value);
+ }
+ },
+}));
+import { preparePluginSettingsResources } from "../plugins/pluginSettingsResources";
+import type { PluginSettingsClient } from "../plugins/pluginSettingsClient";
+
+/* 测试价值
+ * 生产入口与可观察结果:preparePluginSettingsResources发布完整原包到既有服务器,失败/取消清掉自己的缓存。
+ * Bug/规则依据:credentials-and-local-storage「临时文件」;plugin-mobile-implementation「页面租约」。
+ * 现有覆盖缺口:pluginLocalPreview测按需远程URL,未覆盖settings包清单、桥先执行及start期间取消。
+ * 最小失败输入:UI子目录+相对模块/CSS、读取失败、服务器创建尚未完成时离页、重复close。
+ * tier:unit;原生边界和文件系统用内存fake,不运行真实App或读取用户数据。
+ * 实测耗时:单文件墙钟 1.06s。
+ */
+beforeEach(() => {
+ vi.clearAllMocks();
+ state.files.clear();
+ state.removed.length = 0;
+});
+function fixture() {
+ const content = new Map([
+ [
+ "ui/settings.html",
+ '<html><head><link rel="stylesheet" href="./style.css"><script type="module" src="./main.js"></script></head><body>Original</body></html>',
+ ],
+ ["ui/main.js", 'import "./child.js"; fetch("cindy-ghost://test/kv");'],
+ ["ui/child.js", 'export const label = "original";'],
+ ["ui/style.css", 'body { background-image: url("./icon.svg"); }'],
+ ["ui/icon.svg", '<svg xmlns="http://www.w3.org/2000/svg"></svg>'],
+ ]);
+ const document = {
+ pageId: "settings",
+ pluginId: "test",
+ manifestId: "test",
+ name: "Original",
+ entry: "ui/settings.html",
+ files: [...content].map(([path, text]) => ({
+ path,
+ size: Buffer.byteLength(text),
+ mime: path.endsWith("html")
+ ? "text/html; charset=utf-8"
+ : path.endsWith("css")
+ ? "text/css; charset=utf-8"
+ : path.endsWith("svg")
+ ? "image/svg+xml"
+ : "text/javascript; charset=utf-8",
+ })),
+ };
+ const send = vi.fn(async (command: any) => ({
+ base64: Buffer.from(content.get(command.path)!).toString("base64"),
+ mime: document.files.find((file) => file.path === command.path)!.mime,
+ }));
+ return {
+ client: {
+ document,
+ send,
+ assertCurrent: () => {},
+ } as unknown as PluginSettingsClient,
+ send,
+ };
+}
+const theme = { dark: false, colors: { "panel-bg": "ivory" } };
+describe("dedicated settings resource origin", () => {
+ it("publishes relative modules/CSS intact and only writes package bytes plus a public bridge", async () => {
+ const f = fixture(),
+ resource = await preparePluginSettingsResources(
+ f.client,
+ theme,
+ new AbortController().signal,
+ );
+ const [, entry, token, csp, files] = native.start.mock.calls[0];
+ expect(entry).toBe("ui/settings.html");
+ expect(csp).toContain("form-action 'none'");
+ expect(files.map((file) => file[0])).toContain("ui/child.js");
+ // The installed native server accepts a bare media type, while chunks retain Host MIME.
+ expect(files.find((file) => file[0] === "ui/settings.html")?.[2]).toBe(
+ "text/html",
+ );
+ expect(files.find((file) => file[0] === "ui/main.js")?.[2]).toBe(
+ "text/javascript",
+ );
+ expect(state.files.get("0")).toContain(
+ '<head><script src="/__cindy_settings_bridge.js"></script>',
+ );
+ expect(state.files.get("0")).toContain('href="./style.css"');
+ expect(state.files.get("1")).toContain('import "./child.js"; fetch("/kv")');
+ expect(state.files.get("3")).toBe(
+ 'body { background-image: url("./icon.svg"); }',
+ );
+ expect(
+ f.send.mock.calls.every(([command]) => command.kind === "asset"),
+ ).toBe(true);
+ await resource.close();
+ await resource.close();
+ expect(native.stop).toHaveBeenCalledOnce();
+ expect(native.stop).toHaveBeenCalledWith(token);
+ expect(state.removed).toEqual([`file:///cache/html-previews/${token}`]);
+ });
+ it("does not start a partial page and deletes its cache when package reading fails", async () => {
+ const f = fixture();
+ f.send.mockRejectedValueOnce(new Error("SOURCE_CHANGED"));
+ await expect(
+ preparePluginSettingsResources(
+ f.client,
+ theme,
+ new AbortController().signal,
+ ),
+ ).rejects.toThrow("SOURCE_CHANGED");
+ expect(native.start).not.toHaveBeenCalled();
+ expect(state.removed).toHaveLength(1);
+ });
+ it("stops a server created after cancellation, then removes its directory", async () => {
+ const f = fixture(),
+ abort = new AbortController();
+ let finish!: (url: string) => void;
+ native.start.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const work = preparePluginSettingsResources(f.client, theme, abort.signal);
+ await vi.waitFor(() => expect(native.start).toHaveBeenCalledOnce());
+ abort.abort();
+ expect(native.stop).not.toHaveBeenCalled();
+ finish("http://127.0.0.1:42300/__cindy/test");
+ await expect(work).rejects.toThrow("CLOSED");
+ expect(native.stop).toHaveBeenCalledOnce();
+ expect(state.removed).toHaveLength(1);
+ });
+ it("does not materialize anything for an already cancelled lease", async () => {
+ const f = fixture(),
+ abort = new AbortController();
+ abort.abort();
+ await expect(
+ preparePluginSettingsResources(f.client, theme, abort.signal),
+ ).rejects.toThrow("CLOSED");
+ expect(f.send).not.toHaveBeenCalled();
+ expect(native.start).not.toHaveBeenCalled();
+ expect(state.files.size).toBe(0);
+ });
+});
+
+// Regression: each package file used to wait a full remote round trip. A deferred
+// transport verifies bounded overlapping reads and rejects late bytes after cancellation.
+it.each([false, true])("overlaps independent assets without publishing partial or cancelled files (abort=%s)", async (cancel) => {
+ const f = fixture(), abort = new AbortController();
+ const original = f.send.getMockImplementation()!;
+ const finishes: Array<() => void> = [];
+ f.send.mockImplementation((command) => new Promise((resolve) => {
+ finishes.push(() => { void original(command).then(resolve); });
+ }));
+ const work = preparePluginSettingsResources(f.client, theme, abort.signal);
+ const outcome = work.then((resource) => resource, (error: Error) => error);
+ await Promise.resolve();
+ const initialRequests = finishes.length;
+ if (cancel) abort.abort();
+ // Settle every outstanding request even if an assertion below fails.
+ while (finishes.length) {
+ finishes.splice(0).reverse().forEach((finish) => finish());
+ for (let i = 0; i < 10; i++) await Promise.resolve();
+ }
+ const result = await outcome;
+ expect(initialRequests).toBe(4);
+ if (cancel) {
+ expect(result).toBeInstanceOf(Error);
+ expect(native.start).not.toHaveBeenCalled();
+ expect(state.files.size).toBe(0);
+ } else {
+ expect(result).not.toBeInstanceOf(Error);
+ expect(native.start.mock.calls[0][4].slice(0, 5).map((file) => file[1])).toEqual(["0", "1", "2", "3", "4"]);
+ await (result as { close(): Promise<void> }).close();
+ }
+});
diff --git a/apps/mobile/src/__tests__/pluginsScreen.test.tsx b/apps/mobile/src/__tests__/pluginsScreen.test.tsx
index 1f46d5feef..915162ad58 100644
--- a/apps/mobile/src/__tests__/pluginsScreen.test.tsx
+++ b/apps/mobile/src/__tests__/pluginsScreen.test.tsx
@@ -3,9 +3,15 @@ import { act, createElement } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import PluginsScreen from "@/plugins/PluginsScreen";
+import { usePluginManagement } from "@/plugins/usePluginManagement";
const fixture = vi.hoisted(() => ({
props: new Map<string, any>(),
+ realManagement: false,
+ accountGeneration: 0,
+ wire: vi.fn(),
+ management: { state: null, controller: null } as any,
+ marketRead: vi.fn(),
enabled: true,
online: true,
focused: true,
@@ -20,20 +26,45 @@ const fixture = vi.hoisted(() => ({
devicesFailed: false,
devicesAbsent: false,
platform: "ios",
+ width: 390,
storage: new Map<string, string>(),
getStored: vi.fn(),
setStored: vi.fn(),
}));
+vi.mock("@/plugins/usePluginManagement", async (importOriginal) => {
+ const actual = await importOriginal<any>();
+ return ({
+ usePluginManagement: (...args: any[]) => {
+ fixture.props.set("managementScope", args);
+ return fixture.realManagement ? actual.usePluginManagement(...args) : fixture.management;
+ },
+});
+});
+vi.mock("expo-crypto", () => ({ randomUUID: () => "screen-operation" }));
+vi.mock("@/plugins/PluginOriginalSettings", () => ({
+ PluginOriginalSettings: (p: any) => { fixture.props.set("originalSettings", p); return null; },
+}));
+vi.mock("@/plugins/pluginManagementClient", async (importOriginal) => {
+ const actual = await importOriginal<any>();
+ return { ...actual, createPluginManagementClient: (...args: any[]) => fixture.realManagement
+ ? actual.createPluginManagementClient(...args) : ({ detail: fixture.marketRead }) };
+});
+vi.mock("@/plugins/PluginManagementMenu", () => ({
+ PluginManagementMenu: () => null,
+}));
+vi.mock("@/plugins/PluginManagementConfirmation", () => ({ PluginManagementConfirmation: () => null }));
+vi.mock("@/plugins/PluginNotice", () => ({ PluginNotice: (p: any) => { fixture.props.set(p.testID ?? "notice", p); return createElement("span", null, p.title); } }));
vi.mock("react-native", async () => {
const React = await import("react");
const view = ({ children }: any) =>
React.createElement("div", null, children);
return {
+ AppState: { currentState: "active", addEventListener: () => ({ remove() {} }) },
ActivityIndicator: view,
Alert: { alert: fixture.alert },
BackHandler: { addEventListener: () => ({ remove() {} }) },
Image: view,
- Pressable: view,
+ Pressable: (p: any) => { if (p.accessibilityLabel) fixture.props.set("pressable." + p.accessibilityLabel, p); return view(p); },
RefreshControl: view,
ScrollView: view,
View: view,
@@ -43,7 +74,7 @@ vi.mock("react-native", async () => {
},
},
StyleSheet: { create: (s: any) => s, hairlineWidth: 1 },
- useWindowDimensions: () => ({ width: 390 }),
+ useWindowDimensions: () => ({ width: fixture.width }),
};
});
vi.mock("react-native-safe-area-context", async () => ({
@@ -66,9 +97,15 @@ vi.mock("react-i18next", () => ({
}));
vi.mock("lucide-react-native", () =>
Object.fromEntries(
- ["ChevronDown", "ChevronRight", "Info", "Monitor", "Puzzle", "Search"].map(
- (key) => [key, () => null],
- ),
+ [
+ "ChevronDown",
+ "ChevronRight",
+ "Info",
+ "Monitor",
+ "Puzzle",
+ "Search",
+ "Plus",
+ ].map((key) => [key, () => null]),
),
);
vi.mock("@/components/AppText", () => ({
@@ -76,14 +113,15 @@ vi.mock("@/components/AppText", () => ({
TextInput: () => null,
}));
vi.mock("@/auth/AuthContext", () => ({
- useAuth: () => ({ accountGeneration: 0, apiFetch: vi.fn() }),
+ useAuth: () => ({ accountGeneration: fixture.accountGeneration, apiFetch: vi.fn() }),
}));
vi.mock("@/auth/authOwnerGeneration", () => ({
+ subscribeMobileAuthOwner: () => () => {},
getMobileAuthOwner: () => ({ accountKey: "demo" }),
isMobileAuthOwnerCurrent: () => fixture.owner,
}));
vi.mock("@/device-link/DeviceLinkContext", () => ({
- useDeviceLink: () => ({ invoke: vi.fn() }),
+ useDeviceLink: () => ({ invoke: fixture.wire }),
}));
vi.mock("@/device-link/useDeviceManagement", () => ({
useDeviceManagement: () => ({
@@ -115,6 +153,7 @@ const row = () => ({
});
vi.mock("@/device-link/remoteResources", () => ({
getRemoteResource: (...args: any[]) => fixture.read(...args),
+ isRemoteResourcesUnsupported: () => false,
}));
vi.mock("@/session/useRemoteResourceList", () => ({
useRemoteResourceList: () => ({
@@ -164,7 +203,7 @@ vi.mock("@/plugins/PluginDirectoryView", () => ({
vi.mock("@/plugins/PluginDetailView", () => ({
PluginDetailView: (p: any) => {
fixture.props.set("detail", p);
- return null;
+ return createElement("div", null, p.settingsContent);
},
}));
vi.mock("@/plugins/PluginTaskPicker", () => ({
@@ -181,6 +220,11 @@ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
let root: ReturnType<typeof createRoot>;
beforeEach(() => {
fixture.props.clear();
+ fixture.realManagement = false;
+ fixture.accountGeneration = 0;
+ fixture.wire.mockReset();
+ fixture.management = { state: null, controller: null };
+ fixture.marketRead.mockReset();
fixture.storage.clear();
fixture.getStored
.mockReset()
@@ -202,6 +246,7 @@ beforeEach(() => {
fixture.focused = true;
fixture.owner = true;
fixture.platform = "ios";
+ fixture.width = 390;
fixture.invoke
.mockReset()
.mockImplementation(async (_invoke, _device, _plugin, action) => {
@@ -663,6 +708,7 @@ it("guides setup to PC without opening configuration or creating a task", async
await openDetail();
const detail = fixture.props.get("detail");
expect(detail.model.status).toBe("setupRequired");
+ expect(detail.model.canUseTasks).toBe(true);
expect(detail.children).toBeUndefined();
await act(async () => detail.onResolveStatus());
expect(fixture.alert).toHaveBeenCalledWith("plugins.detail.computerSettings");
@@ -690,3 +736,318 @@ it("records recent use when choosing an existing task", async () => {
JSON.stringify(["mac:plugin"]),
);
});
+
+// Management UI integration: the real screen must bind actions to the selected Host/instance,
+// discard late native confirmations and expose only negotiated original-settings support.
+// Existing controller tests cover wire validation; these unit cases cover the missing UI wiring.
+function managedScreen() {
+ const plugin = {
+ instanceKey: "demo",
+ namespace: null,
+ enabled: true,
+ manifest: { id: "demo", name: "Demo", version: "1" },
+ approval: {
+ state: "approved",
+ revision: "12345678-1234-4123-8123-123456789abc",
+ },
+ };
+ const market = {
+ pluginId: "market/demo",
+ ghostId: "demo",
+ namespace: null,
+ name: "Demo",
+ releaseId: "r2",
+ version: "2",
+ sourceType: "server",
+ installState: "update-available",
+ manifest: { ...plugin.manifest, version: "2" },
+ };
+ const snapshot = {
+ version: 1,
+ settingsPage: true,
+ ghosts: [plugin],
+ market: { items: [market], unavailableCustomSourceNames: [] },
+ };
+ const controller = {
+ uninstall: vi.fn(),
+ install: vi.fn(),
+ refresh: vi.fn().mockResolvedValue(undefined),
+ getState: () => fixture.management.state,
+ };
+ fixture.management = {
+ state: {
+ capability: "supported",
+ snapshot,
+ online: true,
+ busy: false,
+ outcome: "idle",
+ },
+ controller,
+ };
+ fixture.marketRead.mockResolvedValue(market);
+ return { plugin, market, snapshot, controller };
+}
+it("binds update and uninstall to the selected physical installation", async () => {
+ const { plugin, market, controller } = managedScreen();
+ await openDetail();
+ const menu = fixture.props.get("header").rightToolbar.props;
+ expect(menu.nativeToolbar).toBe(true);
+ expect(fixture.props.get("header").right).toBeUndefined();
+ expect(menu.actions.map((a: any) => a.id)).toEqual(["update", "uninstall"]);
+ await act(async () => menu.onAction("update"));
+ expect(controller.install).toHaveBeenCalledWith(market, plugin);
+ await act(async () => menu.onAction("uninstall"));
+ const buttons = fixture.alert.mock.calls.at(-1)![2];
+ expect(controller.uninstall).not.toHaveBeenCalled();
+ await act(async () => buttons[1].onPress());
+ expect(controller.uninstall).toHaveBeenCalledWith(plugin);
+ expect(fixture.props.get("managementScope")[0]).toBe("mac");
+});
+// Preflight can fail before an operation ID exists; the removed status strip must not swallow that failure.
+it.each(["update", "uninstall"])("reports %s preflight failure without an operation ID", async (action) => {
+ const { controller } = managedScreen();
+ controller[action === "update" ? "install" : "uninstall"].mockImplementation(async () => {
+ fixture.management.state = { ...fixture.management.state, outcome: "failed", operationId: null, errorCode: "PLUGIN_INSTALL_CHANGED" };
+ });
+ await openDetail();
+ await act(async () => fixture.props.get("header").rightToolbar.props.onAction(action));
+ if (action === "uninstall") await act(async () => fixture.alert.mock.calls.at(-1)![2][1].onPress());
+ expect(fixture.alert).toHaveBeenCalledWith("plugins.notice.title.managementFailed");
+});
+it("discards an uninstall confirmation after navigating to another plugin", async () => {
+ const { controller } = managedScreen();
+ await openDetail();
+ act(() => fixture.props.get("header").rightToolbar.props.onAction("uninstall"));
+ const confirm = fixture.alert.mock.calls.at(-1)![2][1].onPress;
+ await act(async () =>
+ fixture.props
+ .get("directory")
+ .onDetail({
+ ...row(),
+ key: "mac:other",
+ item: { ...row().item, ref: { ...row().item.ref, id: "other" } },
+ }),
+ );
+ await act(async () => confirm());
+ expect(controller.uninstall).not.toHaveBeenCalled();
+});
+it("requires an explicit review when the release changed before installing", async () => {
+ const { market, controller } = managedScreen();
+ fixture.marketRead.mockResolvedValue({ ...market, releaseId: "r3" });
+ await openDetail();
+ await act(async () =>
+ fixture.props.get("header").rightToolbar.props.onAction("update"),
+ );
+ expect(controller.install).not.toHaveBeenCalled();
+ expect(controller.refresh).toHaveBeenCalled();
+ expect(fixture.alert).toHaveBeenCalledWith(
+ "plugins.management.releaseChanged",
+ );
+});
+it("mounts original settings with Host approval and retains the old-Host fallback", async () => {
+ const { snapshot } = managedScreen();
+ fixture.blocks = [
+ {
+ id: "capabilities",
+ primitive: "plugin-capabilities",
+ data: {
+ usage: {
+ taskUsable: true,
+ hasSettings: true,
+ approvalRequired: false,
+ builtin: false,
+ retired: false,
+ setup: { state: "ready", missing: [], expired: [] },
+ configuration: { items: [], alternatives: [] },
+ },
+ },
+ },
+ ];
+ await openDetail();
+ expect(fixture.props.get("detail").settingsContent.props.identity).toEqual({
+ deviceId: "mac",
+ instanceId: "demo",
+ expectedInstalledApproval: "approved:12345678-1234-4123-8123-123456789abc",
+ });
+ snapshot.settingsPage = false;
+ await act(async () => root.render(createElement(PluginsScreen)));
+ expect(fixture.props.get("detail").settingsContent).toBeUndefined();
+});
+// Production screen → hook → controller → client. Transport and visual leaves remain isolated.
+function realManagementHost() {
+ const { plugin, market, snapshot } = managedScreen();
+ Object.assign(plugin.manifest, { schemaVersion: 3 });
+ Object.assign(market, { description: null, author: null, scope: "public", organizationId: null,
+ defaultInstall: false, publishedAt: "", icon: null, enabled: true, sourceMarketName: null });
+ Object.assign(market.manifest, { schemaVersion: 3 });
+ Object.assign(snapshot.market, { unavailableReason: null, customSourceNames: [] });
+ fixture.realManagement = true;
+ fixture.wire.mockImplementation(async (_host, channel, args, options) => {
+ options?.preSend?.();
+ if (channel.endsWith(":manifest")) return { collections: [{ id: "plugins", actions: [{ id: "management:snapshot" }] }] };
+ const request = args[0];
+ if (request.actionId === "management:snapshot") return { result: snapshot };
+ if (request.actionId === "management:market-detail") return { result: market };
+ throw new Error("Unexpected action " + request.actionId);
+ });
+ return { plugin, market, snapshot };
+}
+it("rejects a delayed native menu after changing selection through the real hook", async () => {
+ realManagementHost();
+ await openDetail();
+ const menu = fixture.props.get("header").rightToolbar.props;
+ await act(async () => fixture.props.get("directory").onDetail({ ...row(), key: "mac:other",
+ item: { ...row().item, ref: { ...row().item.ref, id: "other" } } }));
+ await act(async () => menu.onAction("uninstall"));
+ expect(fixture.alert).not.toHaveBeenCalled();
+ expect(fixture.wire.mock.calls.some((call) => call[2]?.[0]?.actionId === "management:begin")).toBe(false);
+});
+it("keeps a successful write unconfirmed when production snapshot readback fails", async () => {
+ realManagementHost();
+ const readHost = fixture.wire.getMockImplementation()!;
+ let completed = false;
+ fixture.wire.mockImplementation(async (...args) => {
+ const request = args[2]?.[0];
+ if (request?.actionId === "management:begin") {
+ args[3]?.preSend?.();
+ completed = true;
+ return { result: { operationId: request.input.operationId, phase: "succeeded" } };
+ }
+ if (completed && request?.actionId === "management:snapshot") throw new Error("READ_FAILED");
+ return readHost(...args);
+ });
+ await openDetail();
+ await act(async () => fixture.props.get("header").rightToolbar.props.onAction("uninstall"));
+ await act(async () => fixture.alert.mock.calls.at(-1)![2][1].onPress());
+ expect(completed).toBe(true);
+ expect(fixture.read).toHaveBeenCalledTimes(1);
+ expect(fixture.props.get("detail").row.item.ref.id).toBe("demo");
+ expect(fixture.props.get("header").rightToolbar.props.actions.every((action: any) => action.disabled)).toBe(true);
+});
+
+it("isolates Host and selection changes during render before effects publish new facts", async () => {
+ const { plugin } = realManagementHost();
+ const renders: any[] = [];
+ function Probe({ host, selection }: { host: string; selection: string }) {
+ const binding = usePluginManagement(host, true, true, selection);
+ renders.push({ host, selection, ...binding });
+ return null;
+ }
+ await act(async () => root.render(createElement(Probe, { host: "mac", selection: "same-instance" })));
+ const oldController = renders.at(-1).controller;
+ const start = renders.length;
+ await act(async () => root.render(createElement(Probe, { host: "other-mac", selection: "same-instance" })));
+ expect(renders[start]).toMatchObject({ state: null, controller: null });
+ await act(async () => oldController.uninstall(plugin));
+ expect(fixture.wire.mock.calls.some((call) => call[2]?.[0]?.actionId === "management:begin")).toBe(false);
+ const next = renders.length;
+ await act(async () => root.render(createElement(Probe, { host: "other-mac", selection: "other-instance" })));
+ expect(renders[next]).toMatchObject({ state: null, controller: null });
+ const account = renders.length;
+ fixture.accountGeneration += 1;
+ await act(async () => root.render(createElement(Probe, { host: "other-mac", selection: "other-instance" })));
+ expect(renders[account]).toMatchObject({ state: null, controller: null });
+});
+
+
+it.each(["required", "unknown"] as const)("allows %s configuration plugins to start and choose tasks without claiming configuration is ready", async (assessment) => {
+ fixture.blocks = [{ id: "capabilities", data: { usage: {
+ taskUsable: true, hasSettings: true, approvalRequired: false, builtin: false, retired: false,
+ setup: { state: assessment, missing: ["Account"], expired: [] },
+ } } }];
+ await openDetail();
+ const detail = fixture.props.get("detail");
+ expect(detail.model.status).toBe(assessment === "unknown" ? "setupUnknown" : "setupRequired");
+ expect(detail.model.missing).toEqual(["Account"]);
+ await act(async () => detail.onNewTask());
+ expect(fixture.push).toHaveBeenCalledWith(expect.objectContaining({ pathname: "/sessions/new" }));
+ await act(async () => detail.onChooseTask());
+ await act(async () => fixture.props.get("taskPicker").onSelect("pending-setup-task"));
+ expect(fixture.push).toHaveBeenCalledWith(expect.objectContaining({ pathname: "/sessions/[sessionId]", params: expect.objectContaining({ sessionId: "pending-setup-task" }) }));
+});
+
+it("keeps recovery navigation and reads available during pending management while retaining local locks", async () => {
+ fixture.management = { state: { outcome: "unknown", busy: false, capability: "supported", online: false, snapshot: null }, controller: null };
+ fixture.online = false;
+ await openDetail();
+ expect(fixture.props.get("detail")).toMatchObject({ busy: true, statusRecoveryBusy: false });
+ act(() => fixture.props.get("detail").onResolveStatus());
+ expect(fixture.push).toHaveBeenCalledWith("/devices/manage");
+ fixture.management.state.outcome = "running";
+ fixture.online = true;
+ fixture.read.mockRejectedValueOnce(new Error("READ_FAILED"));
+ await act(async () => root.render(createElement(PluginsScreen)));
+ expect(fixture.props.get("detail")).toMatchObject({ busy: true, statusRecoveryBusy: false, model: { status: "loadFailed" } });
+ let finish!: (resource: any) => void;
+ fixture.read.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
+ act(() => fixture.props.get("detail").onResolveStatus());
+ expect(fixture.props.get("detail")).toMatchObject({ busy: true, statusRecoveryBusy: true });
+ await act(async () => finish({ ...row().item, blocks: [] }));
+ expect(fixture.props.get("detail")).toMatchObject({ busy: true, statusRecoveryBusy: false });
+ expect(fixture.invoke).not.toHaveBeenCalled();
+ fixture.management = { state: null, controller: null };
+ await act(async () => root.render(createElement(PluginsScreen)));
+ let reject!: (error: Error) => void;
+ fixture.invoke.mockImplementationOnce(() => new Promise((_resolve, fail) => { reject = fail; }));
+ act(() => fixture.props.get("detail").onEnabledChange(false));
+ expect(fixture.props.get("detail")).toMatchObject({ busy: true, statusRecoveryBusy: true });
+ await act(async () => reject(new Error("WRITE_FAILED")));
+});
+
+
+it("silently reads uncertain configuration once without clearing the detail or replacing its form identity", async () => {
+ fixture.blocks = [{ id: "capabilities", primitive: "plugin-capabilities", data: { usage: { taskUsable: true, hasSettings: true, builtin: false, retired: false, approvalRequired: false, setup: { state: "unknown", missing: [], expired: [] } } } }];
+ await openDetail();
+ expect(fixture.read).toHaveBeenCalledTimes(2);
+ expect(fixture.props.get("detail")).toMatchObject({ model: { status: "setupUnknown" }, busy: false });
+ await act(async () => root.render(createElement(PluginsScreen)));
+ expect(fixture.read).toHaveBeenCalledTimes(2);
+ expect(fixture.alert).not.toHaveBeenCalled();
+ expect(fixture.invoke).not.toHaveBeenCalled();
+});
+
+
+it("reports a failed management operation once without a permanent refresh card", async () => {
+ fixture.management = { state: { outcome: "failed", operationId: "failed-once", busy: false, capability: "supported", online: true, snapshot: null }, controller: null };
+ await openDetail();
+ expect(fixture.alert).toHaveBeenCalledWith("plugins.notice.title.managementFailed");
+ await act(async () => root.render(createElement(PluginsScreen)));
+ expect(fixture.alert).toHaveBeenCalledTimes(1);
+ expect(fixture.invoke).not.toHaveBeenCalled();
+});
+
+
+it.each(["ios", "android"])("removes only the %s plugin-list plus while retaining device selection and detail management", async (platform) => {
+ fixture.platform = platform;
+ managedScreen();
+ await act(async () => root.render(createElement(PluginsScreen)));
+ expect(fixture.props.get("header").right).toBeUndefined();
+ expect(fixture.props.get("header").rightToolbar).toBeUndefined();
+ if (platform === "ios") {
+ expect(fixture.props.get("directory").targets).toBeDefined();
+ await act(async () => fixture.props.get("directory").onDetail(row()));
+ } else await act(async () => fixture.props.get("pressable.plugins.detailsFor").onPress());
+ const header = fixture.props.get("header");
+ const menu = platform === "ios" ? header.rightToolbar : header.right;
+ expect(menu.props.actions.some((action: any) => action.id === "uninstall")).toBe(true);
+});
+
+it("refreshes an unknown management result using its original operation without replaying the write", async () => {
+ realManagementHost();
+ fixture.width = 900;
+ const readHost = fixture.wire.getMockImplementation()!;
+ fixture.wire.mockImplementation(async (...args) => {
+ const request = args[2]?.[0];
+ if (request?.actionId === "management:begin") throw new Error("CONNECTION_LOST");
+ if (request?.actionId === "management:operation") return { result: { operationId: request.input.operationId, phase: "running" } };
+ return readHost(...args);
+ });
+ await openDetail();
+ await act(async () => fixture.props.get("header").rightToolbar.props.onAction("uninstall"));
+ await act(async () => fixture.alert.mock.calls.at(-1)![2][1].onPress());
+ expect(fixture.props.get("detail").busy).toBe(true);
+ await act(async () => fixture.props.get("directory").onRefresh());
+ const requests = fixture.wire.mock.calls.map((call) => call[2]?.[0]);
+ expect(requests.filter((request) => request?.actionId === "management:begin")).toHaveLength(1);
+ expect(requests.filter((request) => request?.actionId === "management:operation").map((request) => request.input.operationId)).toEqual(["screen-operation"]);
+});
diff --git a/apps/mobile/src/__tests__/remoteResources.test.ts b/apps/mobile/src/__tests__/remoteResources.test.ts
index c75b921255..34d6bce7b7 100644
--- a/apps/mobile/src/__tests__/remoteResources.test.ts
+++ b/apps/mobile/src/__tests__/remoteResources.test.ts
@@ -23,6 +23,15 @@ const targets = [
];
describe('remote resource discovery', () => {
+ // plugin-security-and-authoring §1.1: preserve Host capability declarations so mobile never guesses support.
+ // Existing discovery tests omitted collection actions. Minimal regression: one plugins management action (unit).
+ it('retains bounded collection capability actions from the Host manifest', async () => {
+ const invoke = vi.fn(async () => ({ protocolVersion: 1, collections: [{
+ id: 'plugins', resourceKind: 'plugin', title: 'Plugins', actions: [{ id: 'management:snapshot', label: 'Manage' }],
+ }] })) as RemoteInvoke;
+ const manifest = await loadRemoteResourceManifest(invoke, targets[0]);
+ expect(manifest?.collections[0].actions).toEqual([{ id: 'management:snapshot', label: 'Manage' }]);
+ });
it('omits desktop routines from live discovery and offline fallback while keeping other collections', async () => {
const collections = [
{ id: 'routines', title: '例行任务', resourceKind: 'routine', placement: 'home-scope', targets },
diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsx
index bda65e0b1e..27fcf48970 100644
--- a/apps/mobile/src/auth/AuthContext.tsx
+++ b/apps/mobile/src/auth/AuthContext.tsx
@@ -2069,11 +2069,21 @@ export function AuthProvider({ children }: { children: ReactNode }) {
codeChallenge,
state,
});
- const result = await WebBrowser.openAuthSessionAsync(
- authUrl,
- MOBILE_REDIRECT_URL,
- );
- assertLoginFlowCurrent(expectedLoginFlowEpoch);
+ let result: Awaited<ReturnType<typeof WebBrowser.openAuthSessionAsync>>;
+ try {
+ result = await WebBrowser.openAuthSessionAsync(
+ authUrl,
+ MOBILE_REDIRECT_URL,
+ );
+ } catch (error) {
+ // The browser promise outlives the dispatch body. Report launch
+ // failures here, while preserving a newer attempt's ownership.
+ if (loginFlowEpochRef.current !== expectedLoginFlowEpoch
+ || loginActionInFlightRef.current !== run) return false;
+ setAuthError(authErrorCode(error));
+ return false;
+ }
+ if (loginFlowEpochRef.current !== expectedLoginFlowEpoch) return false;
// Linking may already have handed ownership to a continuation.
// A late native result must not cancel or mutate that newer work.
if (loginActionInFlightRef.current !== run) return true;
diff --git a/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx b/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx
index 0e42f95c18..b39a3974aa 100644
--- a/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx
+++ b/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx
@@ -731,6 +731,43 @@ describe('browser auth session lifecycle (real AuthProvider, mocked native/netwo
expect(auth.authError).toBeNull();
});
+
+ // A native browser promise may outlive the screen's explicit reset. Exercise
+ // the real provider epoch fence with success, rejection and dismissal replies.
+ it.each(['success', 'reject', 'cancel'] as const)('can reset a hung browser and fences its late %s result from the next attempt', async result => {
+ let settle!: (value: any) => void;
+ let fail!: (error: Error) => void;
+ native.open.mockImplementationOnce(() => new Promise((resolve, reject) => { settle = resolve; fail = reject; }));
+ let old!: Promise<boolean>;
+ await act(async () => { old = auth.dispatchLoginAction({ type: 'start-social-browser', provider: 'wechat', label: 'WeChat' }); });
+ expect(auth.loginState?.step).toBe('browser-redirect');
+ expect(native.open).toHaveBeenCalledOnce();
+ const oldCallback = callbackUrl();
+ await act(async () => { expect(await auth.dispatchLoginAction({ type: 'reset' })).toBe(true); });
+ expect(auth.isBusy).toBe(false);
+ await start('social');
+ const pending = native.storage.get(pendingKey);
+ const state = auth.loginState;
+ await act(async () => {
+ if (result === 'reject') fail(new Error('old browser failed'));
+ else settle(result === 'success' ? { type: 'success', url: oldCallback } : { type: 'cancel' });
+ expect(await old).toBe(false);
+ });
+ expect(auth.loginState).toBe(state);
+ expect(auth.authError).toBeNull();
+ expect(native.storage.get(pendingKey)).toBe(pending);
+ expect(native.exchange).not.toHaveBeenCalled();
+ await emitLink(callbackUrl());
+ expect(native.exchange).toHaveBeenCalledOnce();
+ });
+ it('reports native browser launch failures without consuming the pending callback identity', async () => {
+ native.open.mockRejectedValueOnce(new Error('BROWSER_UNAVAILABLE'));
+ await start('social');
+ expect(auth.authError).toBe('BROWSER_UNAVAILABLE');
+ expect(auth.isBusy).toBe(false);
+ expect(native.storage.has(pendingKey)).toBe(true);
+ });
+
it('an earlier attempt cannot consume the new attempt after cancel and retry', async () => {
await start();
const oldCallback = callbackUrl();
diff --git a/apps/mobile/src/auth/__tests__/loginSkinStates.test.ts b/apps/mobile/src/auth/__tests__/loginSkinStates.test.ts
index 9ef0235606..7f40de44d0 100644
--- a/apps/mobile/src/auth/__tests__/loginSkinStates.test.ts
+++ b/apps/mobile/src/auth/__tests__/loginSkinStates.test.ts
@@ -90,6 +90,21 @@ function control(tree: any, id: string): any {
}
describe('production login state renderers', () => {
+ // Browser launch can fail or remain pending without a native surface. The real
+ // wait renderer must expose the failure and let its owner abandon that epoch.
+ it.each(['failure', 'pending'])('keeps the browser %s recoverable through the production wait renderer', (kind) => {
+ const reset = vi.fn();
+ const errorNode = React.createElement('LoginErrorText', { testID: 'login.error' }, 'Browser unavailable');
+ const rendered = productionRender('renderBrowserRedirect', { step: 'browser-redirect', label: 'SSO' }, {
+ auth: { loginState: { step: 'browser-redirect', label: 'SSO' }, isBusy: true }, reset, errorNode,
+ });
+ if (kind === 'failure') expect(control(rendered.tree, 'login.error')).toBeDefined();
+ const cancel = control(rendered.tree, 'login.cancelBrowserButton');
+ expect(cancel.disabled).not.toBe(true);
+ cancel.onPress();
+ expect(reset).toHaveBeenCalledOnce();
+ });
+
it.each(['phone', 'email', 'apple', 'google', 'sso'])('routes the actual %s entry through its consent authority', (entry) => {
const requireConsent = vi.fn();
const state = { step: 'identifier', providers: { social: ['apple', 'google'], phone: true, email: true } };
diff --git a/apps/mobile/src/debug/PluginNoticePreview.tsx b/apps/mobile/src/debug/PluginNoticePreview.tsx
new file mode 100644
index 0000000000..13661a1ae1
--- /dev/null
+++ b/apps/mobile/src/debug/PluginNoticePreview.tsx
@@ -0,0 +1,96 @@
+import { goBackGuarded } from "@/utils/backGuard";
+import { useEffect, useRef, useState } from "react";
+import { Alert, Pressable, View } from "react-native";
+import { useRouter } from "expo-router";
+import { SafeAreaView } from "react-native-safe-area-context";
+import { useTranslation } from "react-i18next";
+import type { PluginUsageSummary, RemoteResource } from "@cindy/device-link";
+import { Text } from "@/components/AppText";
+import { SimpleStackHeader, simpleScreenSafeAreaEdges } from "@/platform/chrome/SimpleStackHeader";
+import { PluginDetailView } from "@/plugins/PluginDetailView";
+import { pluginDetailModel } from "@/plugins/pluginDetailModel";
+import { PluginManagementConfirmation } from "@/plugins/PluginManagementConfirmation";
+import { PluginNotice } from "@/plugins/PluginNotice";
+import { PluginSettingsCard } from "@/plugins/PluginSettingsCard";
+import type { PluginSettingsClientOptions } from "@/plugins/pluginSettingsClient";
+import type { PluginManagementController, PluginManagementState } from "@/plugins/pluginManagementController";
+import type { HostedRemoteCollectionItem } from "@/device-link/remoteResources";
+import { spacing, useTheme } from "@/theme";
+
+/** Stable order for QA Next; all data/receipts are synthetic and never sent to a Host. */
+export const PLUGIN_NOTICE_SCENARIOS = [
+ "ready", "disabled", "loading", "setupRequired", "setupRequiredFallback", "setupExpired", "setupUnknown", "crashed",
+ "offline", "loadFailed", "retired", "approvalRequired", "builtinRecovery", "fused",
+ "managementRunning", "managementUnknown", "managementFailed", "managementUnsupported", "managementReadFailed",
+ "offline-managementUnknown", "loadFailed-managementRunning", "fused-managementFailed", "managementUnknownUnsupported",
+ "settingsLoadFailed", "settingsReadFailed", "settingsOperationFailed", "settingsResultUnknown", "settingsAuthorization", "settingsComputerCallback", "settingsUpdateRequired",
+ "pluginNotice", "managementCancelled", "managementSucceeded", "managementSucceededReadFailed", "confirmation",
+] as const;
+
+export function PluginNoticePreview({ scenario, settingsOptions }: { scenario: string; settingsOptions: PluginSettingsClientOptions }) {
+ const { colors } = useTheme(), router = useRouter();
+ const initial = Math.max(0, PLUGIN_NOTICE_SCENARIOS.indexOf(scenario as typeof PLUGIN_NOTICE_SCENARIOS[number]));
+ const [index, setIndex] = useState(initial), [reset, setReset] = useState(0);
+ useEffect(() => { setIndex(initial); setReset((value) => value + 1); }, [initial]);
+ return <SafeAreaView edges={simpleScreenSafeAreaEdges()} style={{ flex: 1, backgroundColor: colors.surface }}>
+ <SimpleStackHeader title={`QA ${index + 1}/${PLUGIN_NOTICE_SCENARIOS.length}`} onBack={() => goBackGuarded(router)} right={
+ <View style={{ flexDirection: "row", gap: spacing.sm }}>
+ <Pressable testID="qa.plugin.reset" accessibilityRole="button" accessibilityLabel="QA Reset" onPress={() => setReset((value) => value + 1)} style={{ minHeight: 44, justifyContent: "center", paddingHorizontal: spacing.xs }}><Text style={{ color: colors.textPrimary }}>Reset</Text></Pressable>
+ <Pressable testID="qa.plugin.next" accessibilityRole="button" accessibilityLabel="QA Next" onPress={() => { setIndex((value) => (value + 1) % PLUGIN_NOTICE_SCENARIOS.length); setReset(0); }} style={{ minHeight: 44, justifyContent: "center", paddingHorizontal: spacing.xs }}><Text style={{ color: colors.textPrimary }}>Next</Text></Pressable>
+ </View>
+ } />
+ <NoticeScene key={`${index}:${reset}`} scenario={PLUGIN_NOTICE_SCENARIOS[index]} settingsOptions={settingsOptions} />
+ </SafeAreaView>;
+}
+
+function NoticeScene({ scenario, settingsOptions }: { scenario: string; settingsOptions: PluginSettingsClientOptions }) {
+ const { t } = useTranslation();
+ const [resolved, setResolved] = useState(false), [enabled, setEnabled] = useState(scenario !== "disabled"), [feedback, setFeedback] = useState("");
+ const [toast, setToast] = useState(scenario === "pluginNotice" ? "QA · Plugin notification" : "");
+ useEffect(() => { if (!toast) return; const timer = setTimeout(() => setToast(""), 4000); return () => clearTimeout(timer); }, [toast]);
+ const current = resolved ? "ready" : scenario;
+ const online = !current.startsWith("offline"), loading = current === "loading", failed = current.startsWith("loadFailed");
+ const required = current === "setupRequired" || current === "setupRequiredFallback", expired = current === "setupExpired", unknown = current === "setupUnknown";
+ const usage: PluginUsageSummary = {
+ taskUsable: true, hasSettings: required || expired || unknown || current.startsWith("settings"), builtin: current === "builtinRecovery",
+ retired: current === "retired", approvalRequired: current === "approvalRequired" || current === "builtinRecovery",
+ setup: { state: required || expired ? "required" : unknown ? "unknown" : "ready", missing: required ? ["QA account"] : [], expired: expired ? ["QA account"] : [] },
+ ...(current.startsWith("fused") ? { runtimeIssue: "fused" as const } : current === "crashed" ? { runtimeIssue: "crashed" as const } : {}),
+ };
+ const row: HostedRemoteCollectionItem = { key: `qa-notice:${scenario}`, host: { deviceId: "qa-only", deviceName: "QA Mac" }, item: {
+ ref: { collectionId: "plugins", kind: "plugin", id: "qa-notice" }, revision: "qa", display: { title: "QA Plugin · Synthetic" }, links: [],
+ actions: [{ id: enabled ? "disable" : "enable", label: "QA toggle" }],
+ } };
+ const resource: RemoteResource = { ...row.item, blocks: [{ id: "capabilities", primitive: "plugin-capabilities", fallbackMarkdown: "", data: { usage, details: [{ key: "author", title: "Author", value: "QA fixture" }] } }] };
+ const model = pluginDetailModel(row, resource, online, loading, failed);
+ const outcome: PluginManagementState["outcome"] = current.includes("managementRunning") ? "running" : current.includes("managementUnknown") ? "unknown" : current.includes("managementFailed") ? "failed" : current === "confirmation" ? "confirmation" : current === "managementCancelled" ? "cancelled" : current.startsWith("managementSucceeded") ? "succeeded" : "idle";
+ const state: PluginManagementState = { outcome, capability: current === "managementUnsupported" || current === "managementUnknownUnsupported" ? "unsupported" : "supported", online, busy: false,
+ operationId: "qa-operation", snapshot: null, receipt: current === "confirmation" ? { operationId: "qa-operation", phase: "confirmation", consent: {
+ requestId: "qa-consent", origin: "local-file", originLabel: "QA only", initiator: "user", facts: { kind: "install", ghostId: "qa-notice", name: "QA Plugin", version: "1.0.0", permissions: [{ key: "qa-network", kind: "network", labelKey: "networkHost", labelArgs: { host: "api.example.com" }, detail: "QA fixture · api.example.com" }] },
+ } } as PluginManagementState["receipt"] : null,
+ errorCode: current === "managementReadFailed" || current === "managementSucceededReadFailed" ? "QA_READ_FAILED" : null,
+ };
+ const stateRef = useRef(state); stateRef.current = state;
+ const recover = (action: string) => { setFeedback(`QA · ${action} · local only`); setResolved(true); };
+ const controller = { getState: () => stateRef.current, refresh: async () => recover("refresh"), reconcile: async () => recover("check result"), cancel: async () => { recover("cancel"); }, answer: async (accepted: boolean) => recover(accepted ? "allow" : "reject") } as unknown as PluginManagementController;
+ useEffect(() => { if (outcome === "failed") Alert.alert("QA · " + t("plugins.notice.title.managementFailed")); }, [outcome, t]);
+ const errorKind = current === "settingsLoadFailed" || current === "settingsReadFailed" ? "readFailed" : current === "settingsOperationFailed" ? "writeFailed" : current === "settingsResultUnknown" ? "resultUnknown" : current.startsWith("settings") ? "authorization" : undefined;
+ const errorDetail = current === "settingsResultUnknown" ? "plugins.management.settingsResultUnknown" : current === "settingsOperationFailed" ? "plugins.management.settingsOperationFailed" : current === "settingsReadFailed" || current === "settingsLoadFailed" ? "plugins.management.settingsUnavailable" : current === "settingsComputerCallback" ? "plugins.computerAuthorizationHint" : current === "settingsUpdateRequired" ? "plugins.oauthUpdateRequired" : "plugins.authorizationCheckHint";
+ const hasForm = current === "setupRequired" || expired || unknown || (!!errorKind && current !== "settingsLoadFailed");
+ const settingsContent = hasForm || errorKind ? <View style={{ gap: spacing.md }}>
+ {errorKind ? <PluginNotice compact unavailable={current === "settingsLoadFailed"} testID="plugins.settingsError" title={t("plugins.notice.title." + errorKind)} detail={errorKind === "readFailed" ? undefined : t(errorDetail)} icon="warning" actions={errorKind === "authorization" ? undefined : [{ label: t("plugins.management.settingsReload"), testID: "plugins.settingsReload", onPress: () => recover("reload settings, no write replay") }]} /> : null}
+ {hasForm ? <PluginSettingsCard {...settingsOptions} active generation="qa-notice" onConfirm={async () => false} onDirectory={async () => null} onNotice={setToast} /> : null}
+ </View> : undefined;
+ return <View style={{ flex: 1 }}>
+ <PluginDetailView row={row} enabled={enabled} online={online} busy={loading || state.busy || ["running", "confirmation", "unknown"].includes(outcome)} statusRecoveryBusy={loading || state.busy} model={model} settingsOpen={false}
+ previewLabel={`QA fixture · ${scenario}${errorKind ? " · bridge-only failure; no page reply" : ""}${feedback ? " · " + feedback : ""}`} settingsContent={settingsContent}
+ onEnabledChange={(value) => { setEnabled(value); setFeedback("QA · local switch"); }}
+ onOpen={() => Alert.alert("QA only", "No Host was opened")}
+ onResolveStatus={() => recover(online ? "retry" : "connect")}
+ onNewTask={() => Alert.alert("QA only", "New task selected; no task created")}
+ onChooseTask={() => Alert.alert("QA only", "Choose task selected; no navigation")}
+ />
+ {toast ? <View pointerEvents="none" style={{ position: "absolute", top: spacing.md, left: spacing.lg + spacing.xs, right: spacing.lg + spacing.xs }}><PluginNotice testID="plugins.transientNotice" title={toast} /></View> : null}
+ {current === "confirmation" ? <PluginManagementConfirmation state={state} controller={controller} deviceName="QA Mac" active /> : null}
+ </View>;
+}
diff --git a/apps/mobile/src/debug/pluginSettingsPreviewAssets.json b/apps/mobile/src/debug/pluginSettingsPreviewAssets.json
new file mode 100644
index 0000000000..4000eb9464
--- /dev/null
+++ b/apps/mobile/src/debug/pluginSettingsPreviewAssets.json
@@ -0,0 +1,4 @@
+{
+ "settings.html": "<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <title>QA original plugin settings</title>\n <style>\n * { box-sizing: border-box; }\n body { margin: 0; padding: 16px; font: 16px/1.5 system-ui, sans-serif; color: var(--text-primary, CanvasText); background: var(--surface, Canvas); }\n main { width: 100%; max-width: 40rem; margin: auto; }\n h1, h2 { font-size: 18px; line-height: 1.4; }\n fieldset { min-width: 0; margin: 16px 0; padding: 12px; border: 1px solid var(--border-default, GrayText); }\n label { display: block; margin: 12px 0; }\n input:not([type=\"checkbox\"]), select, textarea { display: block; width: 100%; margin-top: 4px; padding: 8px; font: inherit; color: inherit; background: var(--surface-elevated, Field); border: 1px solid var(--border-default, GrayText); }\n button { min-height: 44px; max-width: 100%; padding: 8px 12px; margin: 4px 0; font: inherit; white-space: normal; color: inherit; background: var(--surface-elevated, ButtonFace); border: 1px solid var(--border-default, GrayText); }\n output, li { overflow-wrap: anywhere; }\n :focus-visible { outline: 2px solid var(--focus-ring, Highlight); outline-offset: 2px; }\n </style>\n </head>\n <body>\n <main>\n <h1>QA original plugin settings</h1>\n <p>TEST DATA ONLY · original HTML fixture · no file import</p>\n <output id=\"status\" role=\"status\" aria-live=\"polite\">Reading target Host…</output>\n <form id=\"preferences\">\n <fieldset>\n <legend>Ordinary settings on the target Host</legend>\n <label>Display label <input id=\"displayLabel\" name=\"displayLabel\" required maxlength=\"80\"></label>\n <label><input id=\"notifications\" name=\"notifications\" type=\"checkbox\"> Notifications</label>\n <label>Language <select id=\"language\" name=\"language\"><option value=\"en\">English</option><option value=\"zh-CN\">简体中文</option></select></label>\n <button type=\"submit\">Save ordinary settings</button>\n <button id=\"reload\" type=\"button\">Read target again</button>\n </fieldset>\n </form>\n <fieldset>\n <legend>Write-only synthetic secret</legend>\n <output id=\"secretState\">Status unknown</output>\n <label>Test key <input id=\"secret\" type=\"password\" autocomplete=\"off\" placeholder=\"Use an invalid QA value only\"></label>\n <button id=\"saveSecret\" type=\"button\">Save test key to target</button>\n </fieldset>\n <fieldset>\n <legend>OAuth accounts</legend>\n <ul id=\"accounts\"></ul>\n <button id=\"connect\" type=\"button\">Connect a test account</button>\n </fieldset>\n <fieldset>\n <legend>Directory and original channel interaction</legend>\n <button id=\"pickDirectory\" type=\"button\">Choose a directory on the target</button>\n <output id=\"directory\">No directory selected</output>\n <button id=\"echo\" type=\"button\">Send channel probe</button>\n <output id=\"channelState\">No reply received</output>\n </fieldset>\n <form id=\"longForm\">\n <fieldset>\n <legend>Long form: keyboard and scroll</legend>\n <div id=\"longFields\"></div>\n <label>Last field <textarea id=\"lastField\" rows=\"4\" placeholder=\"Keep this draft while opening the keyboard or changing theme\"></textarea></label>\n <button type=\"submit\">Save bottom field</button>\n </fieldset>\n </form>\n </main>\n <script src=\"settings.js\"></script>\n </body>\n</html>\n",
+ "settings.js": "// Test-only original plugin code: no local persistence, production ID branching, or external fetch.\n(() => {\n const element = (id) => document.getElementById(id);\n const status = (text) => { element('status').textContent = text; };\n const channel = new BroadcastChannel('qa-settings');\n let sequence = 0;\n let pendingDirectory;\n let pendingProbe;\n const request = async (path, method = 'GET', body) => {\n const response = await fetch(path, {\n method,\n ...(body === undefined ? {} : {\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n }),\n });\n if (!response.ok) throw new Error('Target request failed: ' + response.status);\n return response.status === 204 ? undefined : response.json();\n };\n const action = (id, run) => {\n element(id).addEventListener('click', async () => {\n element(id).disabled = true;\n try { await run(); } catch { status('Target request failed; read target again before retrying a write.'); }\n finally { element(id).disabled = false; }\n });\n };\n const refreshAccounts = async () => {\n const declarations = await request('/oauth');\n const accounts = declarations.find((entry) => entry.key === 'login')?.accounts ?? [];\n element('accounts').replaceChildren();\n for (const account of accounts) {\n const row = document.createElement('li');\n row.textContent = account.label + (account.isDefault ? ' (default)' : '');\n const choose = document.createElement('button');\n choose.type = 'button';\n choose.textContent = 'Use ' + account.label;\n choose.addEventListener('click', async () => {\n choose.disabled = true;\n try {\n await request('/oauth/login/default', 'POST', { accountId: account.id });\n await refreshAccounts();\n status('Default test account read back from target.');\n } catch { status('Account change not confirmed; read target again.'); }\n finally { choose.disabled = false; }\n });\n row.append(document.createTextNode(' '), choose);\n element('accounts').append(row);\n }\n };\n const readTarget = async () => {\n const preferences = await request('/kv');\n element('displayLabel').value = preferences.displayLabel ?? '';\n element('notifications').checked = preferences.notifications === true;\n element('language').value = preferences.language ?? 'en';\n element('lastField').value = preferences.lastField ?? '';\n const secrets = await request('/secrets');\n element('secretState').textContent = secrets.find((entry) => entry.key === 'key')?.saved\n ? 'Test key saved on target (value is not returned)' : 'No test key saved';\n await refreshAccounts();\n status('Target Host state read.');\n };\n const savePreferences = async (patch) => {\n // /kv replaces an object. Preserve unrelated keys; concurrent-edit semantics remain the plugin's.\n const preferences = { ...await request('/kv'), ...patch };\n await request('/kv', 'PUT', preferences);\n const confirmed = await request('/kv');\n status('Ordinary settings read back: ' + confirmed.displayLabel);\n };\n element('preferences').addEventListener('submit', async (event) => {\n event.preventDefault();\n const submit = element('preferences').querySelector('[type=\"submit\"]');\n if (submit.disabled) return;\n submit.disabled = true;\n try {\n await savePreferences({\n displayLabel: element('displayLabel').value,\n notifications: element('notifications').checked,\n language: element('language').value,\n });\n } catch { status('Save not confirmed; read target again.'); }\n finally { submit.disabled = false; }\n });\n action('reload', readTarget);\n action('saveSecret', async () => {\n try {\n await request('/secrets/key', 'PUT', { value: element('secret').value });\n const secrets = await request('/secrets');\n element('secretState').textContent = secrets.find((entry) => entry.key === 'key')?.saved\n ? 'Test key saved on target (value is not returned)' : 'No test key saved';\n status('Secret status read back from target.');\n } finally { element('secret').value = ''; }\n });\n action('connect', async () => {\n const result = await request('/oauth/login/connect', 'POST', {});\n await refreshAccounts();\n status(result?.ok ? 'Authorization completed on target.' : 'Authorization did not complete.');\n });\n action('pickDirectory', () => {\n pendingDirectory = 'directory-' + ++sequence;\n channel.postMessage({ kind: 'choose-directory', requestId: pendingDirectory });\n element('directory').textContent = 'Waiting for target directory selection…';\n });\n action('echo', () => {\n pendingProbe = 'probe-' + ++sequence;\n channel.postMessage({ kind: 'probe', requestId: pendingProbe });\n element('channelState').textContent = 'Waiting for channel reply…';\n });\n channel.onmessage = ({ data }) => {\n if (data?.kind === 'directory-result' && data.requestId === pendingDirectory) {\n pendingDirectory = undefined;\n element('directory').textContent = data.cancelled ? 'Directory selection cancelled' : data.name;\n }\n if (data?.kind === 'probe-result' && data.requestId === pendingProbe) {\n pendingProbe = undefined;\n element('channelState').textContent = data.targetLabel;\n }\n };\n for (let index = 1; index <= 16; index++) {\n const label = document.createElement('label');\n label.textContent = 'Unsaved scroll probe ' + index;\n const input = document.createElement('input');\n input.id = 'scrollProbe' + index;\n input.placeholder = 'Local page draft only';\n label.append(input);\n element('longFields').append(label);\n }\n element('longForm').addEventListener('submit', async (event) => {\n event.preventDefault();\n const submit = element('longForm').querySelector('[type=\"submit\"]');\n if (submit.disabled) return;\n submit.disabled = true;\n try { await savePreferences({ lastField: element('lastField').value }); }\n catch { status('Bottom field save not confirmed; read target again.'); }\n finally { submit.disabled = false; }\n });\n window.addEventListener('pagehide', () => {\n pendingDirectory = undefined;\n pendingProbe = undefined;\n element('secret').value = '';\n channel.close();\n }, { once: true });\n readTarget().catch(() => status('Cannot read target Host. No fallback data was substituted.'));\n})();\n"
+}
diff --git a/apps/mobile/src/device-link/remoteResources.ts b/apps/mobile/src/device-link/remoteResources.ts
index c437a0449f..f943c4918b 100644
--- a/apps/mobile/src/device-link/remoteResources.ts
+++ b/apps/mobile/src/device-link/remoteResources.ts
@@ -231,6 +231,7 @@ function validDescriptor(value: unknown): RemoteCollectionDescriptor | null {
id,
resourceKind,
title,
+ ...(record.actions !== undefined ? { actions: normalizeRemoteActions(record.actions) } : {}),
...(placement ? { placement } : {}),
...(iconName && iconFallbackText !== null
? { icon: { name: iconName, fallbackText: iconFallbackText } }
diff --git a/apps/mobile/src/i18n/locales/en/plugins.json b/apps/mobile/src/i18n/locales/en/plugins.json
index 9f517570c6..615b2aa07f 100644
--- a/apps/mobile/src/i18n/locales/en/plugins.json
+++ b/apps/mobile/src/i18n/locales/en/plugins.json
@@ -1,5 +1,19 @@
{
- "mailReader": {"markReadFailed":"Could not sync read status. Check mailbox authorization and reopen this email.","title":"Mail","openMailbox":"Open in mailbox","loading":"Loading email…","failed":"Could not load this email. Check the connected mailbox account, retry, or open it in your mailbox.","retry":"Retry","to":"To","cc":"Cc","bcc":"Bcc","subject":"Subject"},
+ "settingsHostUpdateRequired": "Update Cindy on the selected computer to authorize on this phone.",
+ "settingsComputerLink": "This link opens a service on the computer. Open it there.",
+ "settingsLinkUnavailable": "Could not open this link.",
+ "mailReader": {
+ "markReadFailed": "Could not sync read status. Check mailbox authorization and reopen this email.",
+ "title": "Mail",
+ "openMailbox": "Open in mailbox",
+ "loading": "Loading email…",
+ "failed": "Could not load this email. Check the connected mailbox account, retry, or open it in your mailbox.",
+ "retry": "Retry",
+ "to": "To",
+ "cc": "Cc",
+ "bcc": "Bcc",
+ "subject": "Subject"
+ },
"title": "Plugins",
"all": "All",
"unread": "Unread",
@@ -30,8 +44,8 @@
"mainView": "Open page",
"settings": "Plugin settings",
"useInTask": "Use in a task",
- "newTask": "New task",
- "chooseTask": "Existing task",
+ "newTask": "Use in a new task",
+ "chooseTask": "Use in an existing task",
"taskHint": "Describe what you need in a task. Cindy will use the appropriate plugin. Existing tasks keep their model and permissions.",
"noMobilePage": "This plugin has no mobile page yet. Its tools can be used in a task.",
"expandFields": "Expand",
@@ -59,6 +73,7 @@
"identityChangedHint": "Configuration stopped because this computer’s authorization identity changed. Verify the computer and register its device identity again before connecting. This card cannot replace a registered identity.",
"connectAccount": "Connect account",
"computerAuthorization": "Computer callback required",
+ "oauthUpdateRequired": "Update Cindy on this phone to complete browser authorization.",
"computerAuthorizationHint": "This sign-in method uses a callback on the computer. Complete it using this card’s computer entry, then return to check its status.",
"authorizationCheckHint": "Check this setup step’s status. Unconfirmed actions are not automatically replayed.",
"connectionHost": "Connection host (HTTPS domain)",
@@ -112,8 +127,8 @@
"setupUnknown": "Configuration status could not be confirmed. Refresh to check again."
},
"action": {
- "connect": "Connect computer",
- "retry": "Try again",
+ "connect": "Connect",
+ "retry": "Retry",
"enable": "Enable plugin",
"settings": "Complete setup",
"reconnect": "Reconnect account"
@@ -138,5 +153,158 @@
"mailAttaching": "Adding attachment…",
"mailAttachFailed": "Could not add the attachment. Check your connection and try again.",
"mailAttachTooLarge": "Each email attachment must be 16 MB or smaller.",
- "mailRemoveAttachment": "Remove {{name}}"
+ "mailRemoveAttachment": "Remove {{name}}",
+ "management": {
+ "manage": "Manage plugin",
+ "update": "Update",
+ "uninstall": "Uninstall",
+ "uninstallTitle": "Uninstall {{name}}?",
+ "uninstallBody": "This removes the plugin, its credentials and private settings from {{device}}. Library items and existing task content are kept.",
+ "reject": "Cancel",
+ "allow": "Allow and continue",
+ "versionChange": "{{previous}} → {{next}}",
+ "oauthChanged": "The account sign-in configuration has changed.",
+ "state": {
+ "readFailed": "Could not read plugin management information. Refresh to check again."
+ },
+ "permissions": {
+ "mail": "Use mail drafts and send cards",
+ "mailDetail": "Edit and sync drafts in a card, with confirmation and an undo countdown before sending.",
+ "mailReader": "View mail in the app",
+ "mailReaderHost": "Open mail links from {{host}} in the app",
+ "mailMarkRead": "Mark messages as read when opened",
+ "grantsTitle": "After installing it will have:",
+ "toolsGroup": "Registered Tools",
+ "toolsDiffGroup": "Registered Tool Changes",
+ "itemCount": "{{count}} total",
+ "cindyImageGenerate": "Image generation (delegated to Cindy)",
+ "cindyImageEdit": "Image editing (delegated to Cindy, its own images only)",
+ "cindyVideoGenerate": "Video generation (delegated to Cindy)",
+ "cindyVideoEdit": "Image-to-video (delegated to Cindy, reference images from its own media only)",
+ "cindyMediaDeposit": "Can save images, video or audio it holds into your media library",
+ "cindyMediaDepositDetail": "This lets AI work on material you paste or drop into the plugin. Saved items are recorded under this plugin, use at most {{quota}}, and are cleaned up when you uninstall it.",
+ "cindyTextOneshot": "Can ask Cindy's fast lane a question and receive a text answer",
+ "cindyTextOneshotDetail": "Uses the system's lightweight utility model chain (the same lane as auto titles). No Agent involved and no file access. Model charges may apply.",
+ "cindyEmbedText": "Can send text to be turned into vectors (for semantic search)",
+ "cindyEmbedTextDetail": "Text is sent to the system embedding model and turned into numbers, up to {{max}} items per call. Model charges may apply. The vectors go only to the plugin — nothing is written to your own library.",
+ "cindySearchWeb": "Can search the public web with Cindy AI",
+ "cindySearchWebDetail": "Search requests access the public web and may consume Cindy AI quota.",
+ "cindyTextOneshotModelDetail": "Uses the system's lightweight utility model chain (the same lane as auto titles). No Agent involved and no file access. Model charges may apply. The plugin declares a preferred model: {{model}} (effective when available in the current catalog; your pin takes precedence).",
+ "agentUserAction": "Can start a new Agent turn after you click a plugin card",
+ "agentUserActionDetail": "Each click permits one turn only, and only in the session that owns the card.",
+ "agentBackground": "Can automatically start new Agent turns in the background",
+ "agentBackgroundDetail": "Does not require a click each time, but can only use sessions you previously connected to this plugin. Model charges may apply.",
+ "agentTasksRequest": "Review task permission",
+ "agentTasks": "Can create and manage its own Cindy tasks",
+ "agentTasksDetail": "Can send messages, read results and stop its own executions. Tasks remain visible to you. Uses this plugin’s AI settings and may incur model charges; does not grant access to other tasks.",
+ "agentHiddenTasks": "Can create background tasks hidden from the task list",
+ "agentHiddenTasksDetail": "Tasks this plugin creates can stay out of the task list, search and notifications. You can always view, open or show them in the task list from Background Tasks on this plugin’s page; uninstalling the plugin shows them again.",
+ "agentErrand": "Create tasks, perform work, and read results",
+ "agentErrandDetail": "Created tasks appear in Cindy’s task list, where you can view progress and continue the conversation.",
+ "agentSchedule": "Can ask you to create an automation",
+ "agentScheduleDetail": "It can only open the new-automation panel with the fields filled in; whether it is created is up to you — pick a model and save it yourself. Once created, Cindy runs it on the schedule you set. Model charges may apply.",
+ "nodeRuntime": "Can run a bundled Node program on this computer",
+ "nodeMcp": "Can run a bundled stdio MCP on this computer",
+ "nodeRuntimeDetail": "High risk: it has the same local access as your user account, including files, network, and starting other programs. Cindy cannot contain it in the browser sandbox.",
+ "nodeSecret": "Can provide the stored credential “{{name}}” to the local Node program",
+ "nodeSecretDetail": "Cindy stores it encrypted and injects it only while the declared Worker methods below run. The Node program receives the plaintext and can return, log, save, or otherwise expose it to browser-side plugin code or Agent parameters. Only install plugins you trust.",
+ "nodeResident": "The Node program can stay running in the background",
+ "nodeResidentDetail": "Runs while the plugin is enabled and stops when disabled, updated, uninstalled, or when Cindy exits.",
+ "tool": "Tool \"{{name}}\"",
+ "command": "Chat command ${{command}}",
+ "panelLeft": "Panel \"{{title}}\" · docked left of the chat",
+ "panelTab": "Panel \"{{title}}\" · opens inside the Plugins page",
+ "mainView": "Can add a “{{title}}” entry to Cindy's sidebar",
+ "mainViewDetail": "Opening it displays the main view in the plugin sandbox and does not grant file, network, or credential access.",
+ "code": "Executable code",
+ "codeDetail": "Runs in an isolated sandbox with no access to your files or network.",
+ "resident": "Always-on (starts when enabled, keeps a background process even when idle)",
+ "residentDetail": "Uses a small amount of memory while idle; the process stops immediately when it is disabled or uninstalled.",
+ "subscribeTopics": "Observes your session activity (turn and session events, no message content)",
+ "subscribeActivity": "Observes when the AI is thinking and when it is waiting on you",
+ "subscribeActivityDetail": "Sees only the timing: when thinking starts and ends, and when the AI is waiting for your approval or your answer. It never sees the reasoning text, the action awaiting approval, the command or file involved, the plan, the question, or your answer — and it cannot approve anything on your behalf.",
+ "subscribeHooks": "Can read, block, or rewrite the messages you send",
+ "subscribeHooksDetail": "Reviews each message before sending: it may block it or rewrite the text before it goes out; blocked messages can be edited and resent.",
+ "subscribeAssistantReply": "Can read and rewrite the AI's replies",
+ "subscribeAssistantReplyDetail": "Processes each AI reply after it completes: it may polish or rewrite the text (replacing it directly, without keeping the original), or replace the reply bubble with its own rendered card (in that case the original text is kept and can be viewed with one tap).",
+ "card": "Renders message cards",
+ "cardExternalLink": "Cards may declare external links that open your browser after confirmation",
+ "cardExternalLinkDetail": "Clicking a card link shows a confirmation dialog; the URL opens in your system browser only after you approve. Only http/https addresses are allowed.",
+ "notify": "Can show system tips (light banner at the top of the screen)",
+ "notifyDetail": "Tip text is provided by this plugin and labeled with its name; tips fade automatically and never block your work.",
+ "badge": "Can light an unread mark on the Plugins entry",
+ "badgeDetail": "When it has something new, it can show a green dot on the sidebar Plugins entry and on its own card, with a one-line summary. Opening its panel clears the dot. The dot makes no sound, does not vibrate, never reaches your system notification center, and is a permission separate from system tips.",
+ "confirm": "Can ask for your confirmation in a dialog",
+ "confirmDetail": "Before acting it can open a dialog that looks like Cindy's own to ask you. The question comes from the plugin and the dialog is labeled with its name; only you can click confirm or cancel — the plugin cannot. At most one dialog at a time, and asking too often is blocked.",
+ "fsWrite": "Can write files (create / modify)",
+ "fsWriteDetail": "Its own private data folder is always writable. Writes into the current session's working directory follow the session's permission mode (auto-approve modes write directly; per-action modes ask you first). Any other folder always requires your confirmation. Files are always written by the host — the plugin itself never touches your file system.",
+ "libraryPersist": "Can use a durable library (large files and databases)",
+ "libraryPersistDetail": "It gets a Cindy-managed storage area for your work (canvases, images, databases) with no normal plugin data quota. All file and database operations are executed by the host; the plugin only uses relative paths inside its own library and cannot touch your other files. It can also ask Cindy to show a library file in Finder or Explorer, or open the system Save As dialog so you choose where a copy goes; cancelling Save As copies nothing. It can also write a PNG bitmap to the system clipboard with no confirmation dialog; this overwrites the current clipboard. Uninstalling the plugin does not delete this data; deletion requires separate confirmation in Cindy settings.",
+ "networkHost": "Accesses the network domain {{host}}",
+ "networkSecret": "Needs a credential from you: \"{{name}}\"",
+ "networkSecretGhostInputDetail": "Collected by this plugin's own settings UI — the plugin page sees the value at entry time. It is then handed to the host in one step for encrypted storage; once stored, the plugin can never read it back, and the host injects it only for the domains it declares.",
+ "networkSecretIdentity": "Will use your login email as the credential \"{{name}}\"",
+ "networkSecretIdentityDetail": "The value comes from your signed-in account's email, derived and injected by the host at request time; nothing to fill in. The plugin can read this email to show the current identity in its settings UI.",
+ "networkSecretGhCli": "Will prefer your local GitHub CLI login for the credential \"{{name}}\"",
+ "networkSecretGhCliDetail": "The host reads the local gh login token only when needed and injects it only into GitHub API requests; plugin code cannot read or store the token. If gh is unavailable, you can configure a fallback Personal Access Token in the plugin settings.",
+ "networkSecretOrganizationIdentity": "Will use your Cindy organization identity as the credential \"{{name}}\"",
+ "networkSecretOrganizationIdentityDetail": "Cindy issues a short-lived identity assertion when needed, and the host sends it only to the explicitly listed service hosts. The plugin code cannot read or store the token.",
+ "networkSecretOauth": "Will guide you through OAuth authorization at {{host}} ({{name}})",
+ "networkSecretOauthDetail": "The authorization flow and all tokens are managed by the host and can never be read by the plugin code; you provide the client credentials on the plugin detail page. The requested permission scopes are listed verbatim below — review them before approving.",
+ "networkConnections": "Can connect to {{label}} addresses you add",
+ "networkConnectionsDetail": "Addresses are added in this plugin's settings UI; every new address requires your confirmation, and the credential you provide is injected only for its own address.",
+ "codeDetailNetwork": "Runs in an isolated sandbox with no access to your files; network access is limited to the domains listed above, relayed by the host.",
+ "codeDetailWithNode": "The panel UI runs in an isolated sandbox; local processing is provided by the Node runtime declared above.",
+ "added": "New",
+ "removed": "Removed",
+ "updated": "Updated",
+ "unchanged": "{{count}} other permissions unchanged",
+ "noChange": "No permission changes.",
+ "pick": "Can ask you to pick a folder for it",
+ "pickDetail": "When it asks, Cindy shows the system folder picker; you decide what to share, and cancelling gives it nothing.",
+ "workspace": "Can ask to create a session entry for a project folder in the sidebar",
+ "workspaceDetail": "When it asks, you either pick the folder yourself or see the full path on a confirmation card before deciding; while it is handling a call you started, subfolders inside the current session's working directory are used directly without an extra prompt. Folders that already have a session are reused, and what gets created is an empty session — nothing starts running on its own.",
+ "sessionContext": "Can learn which project folder the current session is working in",
+ "sessionContextDetail": "Shares only location facts (session ID and project folder path) while it works for the current session — no file contents, and no file access is granted.",
+ "preview": "Can open preview pages from the sites below in the sidebar browser",
+ "previewDetail": "Only the sites listed below can be opened; every page it opens is attributed to this plugin.",
+ "nodeChildSpawn": "Its Node program can ask the host to start declared sub-processes from its package",
+ "nodeChildSpawnDetail": "Only JS files declared inside its own package can be started (same local permissions as the main program); arbitrary commands cannot be executed. Sub-processes are closed together when the plugin is disabled or exits.",
+ "skill": "Adds the skill \"{{name}}\" to your AI assistants",
+ "skillDetail": "A skill is an instruction file the AI loads and follows as its own, with your full permissions, in Claude Code and Codex, across every project — it is not confined to this plugin's sandbox. It stays available while the plugin is enabled and is removed when the plugin is disabled or uninstalled; turning the plugin off for a single folder does not hide it. The full skill text cannot be previewed here — only install plugins you trust.",
+ "routineEvents": "Routine Events"
+ },
+ "releaseChanged": "The available version changed. Review the refreshed version before installing.",
+ "settingsUnavailable": "Could not load the plugin settings. Reload settings to try again.",
+ "settingsResultUnknown": "The operation result could not be confirmed. Reload the computer’s settings before submitting again.",
+ "settingsOperationFailed": "The settings operation could not be completed. Check the connection and try again.",
+ "settingsReload": "Retry"
+ },
+ "notice": {
+ "title": {
+ "offline": "Computer offline",
+ "loadFailed": "Could not load plugin",
+ "retired": "Feature retired",
+ "approvalRequired": "Installation needs attention",
+ "builtinRecovery": "Built-in plugin needs attention",
+ "fused": "Plugin paused",
+ "authorization": "Authorization needs attention",
+ "resultUnknown": "Result unconfirmed",
+ "writeFailed": "Settings operation failed",
+ "readFailed": "Could not load settings",
+ "managementFailed": "Operation failed",
+ "confirmation": "Review plugin permissions"
+ },
+ "consentOrigin": {
+ "market": "Official market",
+ "custom-market": "Custom market",
+ "local-file": "Local file",
+ "forge": "Built locally"
+ },
+ "initiator": {
+ "user": "Requested by you",
+ "agent": "Requested by Agent"
+ },
+ "taskCapability": "For this task"
+ }
}
diff --git a/apps/mobile/src/i18n/locales/ja/plugins.json b/apps/mobile/src/i18n/locales/ja/plugins.json
index 9337b70fe9..d4af7d12a7 100644
--- a/apps/mobile/src/i18n/locales/ja/plugins.json
+++ b/apps/mobile/src/i18n/locales/ja/plugins.json
@@ -1,5 +1,19 @@
{
- "mailReader": {"markReadFailed":"既読状態を同期できませんでした。メールボックスの認証を確認して開き直してください。","title":"メール","openMailbox":"メールボックスで開く","loading":"メールを読み込み中…","failed":"メールを読み込めませんでした。接続したアカウントを確認して再試行するか、メールボックスで開いてください。","retry":"再試行","to":"宛先","cc":"Cc","bcc":"Bcc","subject":"件名"},
+ "settingsHostUpdateRequired": "このスマートフォンで認証するには、選択したコンピュータの Cindy を更新してください。",
+ "settingsComputerLink": "このリンクはコンピュータ上のローカルサービスを開きます。そのコンピュータで開いてください。",
+ "settingsLinkUnavailable": "このリンクを開けませんでした。",
+ "mailReader": {
+ "markReadFailed": "既読状態を同期できませんでした。メールボックスの認証を確認して開き直してください。",
+ "title": "メール",
+ "openMailbox": "メールボックスで開く",
+ "loading": "メールを読み込み中…",
+ "failed": "メールを読み込めませんでした。接続したアカウントを確認して再試行するか、メールボックスで開いてください。",
+ "retry": "再試行",
+ "to": "宛先",
+ "cc": "Cc",
+ "bcc": "Bcc",
+ "subject": "件名"
+ },
"title": "プラグイン",
"all": "すべて",
"unread": "未読",
@@ -30,8 +44,8 @@
"mainView": "ページを開く",
"settings": "プラグイン設定",
"useInTask": "タスクで使用",
- "newTask": "新規タスク",
- "chooseTask": "既存のタスク",
+ "newTask": "新しいタスクで使う",
+ "chooseTask": "既存のタスクで使う",
"taskHint": "タスクで要望を伝えると、Cindy が適切なプラグインを使用します。既存のタスクのモデルと権限は保持されます。",
"noMobilePage": "モバイルページはまだありません。ツールはタスクで使用できます。",
"expandFields": "展開",
@@ -59,6 +73,7 @@
"identityChangedHint": "このパソコンの認証識別情報が変更されたため、設定を停止しました。パソコンを確認し、デバイスの識別情報を再登録してから接続してください。このカードで登録済みの識別情報を置き換えることはできません。",
"connectAccount": "アカウントを接続",
"computerAuthorization": "パソコンのコールバックが必要です",
+ "oauthUpdateRequired": "ブラウザで認証を完了するには、この端末の Cindy を更新してください。",
"computerAuthorizationHint": "この接続方式はパソコン上のコールバックを使用します。このカードのパソコン入口で接続し、戻って状態を確認してください。",
"authorizationCheckHint": "設定手順の状態を確認してください。未確認の操作は自動で再送しません。",
"connectionHost": "接続先(HTTPSドメイン)",
@@ -112,8 +127,8 @@
"setupUnknown": "設定状態を確認できませんでした。再読み込みしてください。"
},
"action": {
- "connect": "コンピューターに接続",
- "retry": "再読み込み",
+ "connect": "接続",
+ "retry": "再試行",
"enable": "有効にする",
"settings": "設定を完了",
"reconnect": "アカウントを再接続"
@@ -138,5 +153,158 @@
"mailAttaching": "添付ファイルを追加中…",
"mailAttachFailed": "添付ファイルを追加できませんでした。接続を確認して再試行してください。",
"mailAttachTooLarge": "添付ファイルは1件につき16 MB以下にしてください。",
- "mailRemoveAttachment": "{{name}} を削除"
+ "mailRemoveAttachment": "{{name}} を削除",
+ "management": {
+ "manage": "プラグインを管理",
+ "update": "更新",
+ "uninstall": "アンインストール",
+ "uninstallTitle": "{{name}} をアンインストールしますか?",
+ "uninstallBody": "{{device}} からプラグイン、認証情報、専用設定を削除します。ライブラリと既存のセッション内容は保持されます。",
+ "reject": "キャンセル",
+ "allow": "許可して続行",
+ "versionChange": "{{previous}} → {{next}}",
+ "oauthChanged": "アカウントのログイン設定が変更されています。",
+ "state": {
+ "readFailed": "プラグイン管理情報を読み込めませんでした。再読み込みしてください。"
+ },
+ "permissions": {
+ "mail": "メールの下書き・送信カードを使用",
+ "mailDetail": "カードで下書きを編集・同期し、送信前に確認と取り消しカウントダウンを表示します。",
+ "mailReader": "アプリ内でメールを表示",
+ "mailReaderHost": "{{host}} のメールリンクをアプリ内で開く",
+ "mailMarkRead": "開いたメールを既読にする",
+ "grantsTitle": "インストール後に持つ権限:",
+ "toolsGroup": "登録ツール",
+ "toolsDiffGroup": "登録ツールの変更",
+ "itemCount": "{{count}} 件",
+ "cindyImageGenerate": "画像生成(Cindy に代行依頼)",
+ "cindyImageEdit": "画像編集(Cindy に代行依頼、自身が生成した画像のみ)",
+ "cindyVideoGenerate": "動画生成(Cindy に代行依頼)",
+ "cindyVideoEdit": "画像から動画(Cindy に代行依頼、参照画像は自身名義のもののみ)",
+ "cindyMediaDeposit": "保有している画像・動画・音声をあなたのメディアライブラリに保存できます",
+ "cindyMediaDepositDetail": "プラグイン内で貼り付け・ドロップした素材も AI で加工できるようにするための権限です。保存内容はこのプラグイン名義で記録され、最大 {{quota}} まで使用し、アンインストール時に併せて削除されます。",
+ "cindyTextOneshot": "Cindy のクイックチャンネルに質問してテキスト回答を受け取れます",
+ "cindyTextOneshotDetail": "システムの軽量タスクモデルチェーン(自動タイトルと同じ経路)を使用します。Agent は使わず、ファイルにもアクセスしません。モデル料金が発生する場合があります。",
+ "cindyEmbedText": "テキストをベクトルに変換できます(意味検索用)",
+ "cindyEmbedTextDetail": "テキストはシステムのベクトルモデルに送られて数値列に変換されます。1 回あたり最大 {{max}} 件で、モデル料金が発生する場合があります。生成されたベクトルはプラグインだけが保持し、あなたのライブラリには書き込まれません。",
+ "cindySearchWeb": "Cindy AI で公開ウェブを検索できます",
+ "cindySearchWebDetail": "検索では公開ウェブにアクセスし、Cindy AI の利用枠を消費する場合があります。",
+ "cindyTextOneshotModelDetail": "システムの軽量タスクモデルチェーン(自動タイトルと同じ経路)を使用します。Agent は使わず、ファイルにもアクセスしません。モデル料金が発生する場合があります。プラグインが希望モデルを宣言しています: {{model}}(現在のカタログで利用可能な場合に有効。ピン留めが優先されます)。",
+ "agentUserAction": "プラグインカードをクリックした後、Agent の新しいターンを開始できます",
+ "agentUserActionDetail": "1 回のクリックにつき 1 回だけ開始でき、そのカードが属するセッションでのみ使用できます。",
+ "agentBackground": "バックグラウンドで Agent の新しいターンを自動的に開始できます",
+ "agentBackgroundDetail": "毎回のクリックは不要ですが、以前このプラグインに関連付けたセッションでのみ使用できます。モデル料金が発生する場合があります。",
+ "agentTasksRequest": "セッション権限を確認",
+ "agentTasks": "このプラグインの Cindy セッションを作成・管理できます",
+ "agentTasksDetail": "メッセージの送信、結果の読み取り、自身の実行の停止ができます。セッションはユーザーに表示されます。プラグインの AI 設定を使用し、モデル料金が発生する場合があります。他のセッションへのアクセスは許可されません。",
+ "agentHiddenTasks": "セッションリストに表示されないバックグラウンドセッションを作成できます",
+ "agentHiddenTasksDetail": "このプラグインが作成したセッションを、セッションリスト・検索・通知に表示しないようにできます。プラグイン詳細の「バックグラウンドセッション」からいつでも確認したり開いたり、セッションリストに表示したりできます。プラグインをアンインストールすると再び表示されます。",
+ "agentErrand": "タスクを作成し、作業を実行して結果を取得できます",
+ "agentErrandDetail": "作成したタスクは Cindy のタスク一覧に表示され、進行状況を確認して会話を続けられます。",
+ "agentSchedule": "自動化の新規作成をあなたに依頼できます",
+ "agentScheduleDetail": "できるのは内容が入力済みの新規自動化パネルを開くことだけで、作成するかどうかはあなたがモデルを選んで自分で保存して決めます。作成後は Cindy があなたの設定した時間に実行します。モデル料金が発生する場合があります。",
+ "nodeRuntime": "同梱された Node プログラムをこのコンピューターで実行できます",
+ "nodeMcp": "同梱された stdio MCP をこのコンピューターで実行できます",
+ "nodeRuntimeDetail": "高リスク:あなたのユーザーアカウントと同じ権限で、ローカルファイルの読み書き、ネットワークアクセス、他のプログラムの起動ができます。Cindy のブラウザーサンドボックスでは隔離できません。",
+ "nodeSecret": "保存済みの認証情報「{{name}}」をローカル Node プログラムに渡せます",
+ "nodeSecretDetail": "Cindy は暗号化して保管し、以下で宣言された Worker メソッドの実行時だけ一時的に注入します。Node プログラムは平文を受け取り、ブラウザー側のプラグインコードや Agent パラメーターへ返したり、ログやファイルに保存したりできるため、信頼できるプラグインだけをインストールしてください。",
+ "nodeResident": "Node プログラムをバックグラウンドで常駐実行できます",
+ "nodeResidentDetail": "プラグインが有効な間は実行を続け、無効化、更新、アンインストール、または Cindy 終了時に停止します。",
+ "tool": "ツール「{{name}}」",
+ "command": "チャット指令 ${{command}}",
+ "panelLeft": "パネル「{{title}}」· チャットの左側にドッキング",
+ "panelTab": "パネル「{{title}}」· プラグインページ内で開く",
+ "mainView": "Cindy のサイドバーに「{{title}}」への入口を追加できます",
+ "mainViewDetail": "クリックするとプラグインのサンドボックス内でメインビューが開き、ファイル、ネットワーク、認証情報へのアクセスが追加で付与されることはありません。",
+ "code": "実行コード",
+ "codeDetail": "独立したサンドボックスで実行され、ファイルやネットワークにはアクセスできません。",
+ "resident": "常駐実行(有効化すると起動し、呼び出されなくてもバックグラウンドプロセスを維持)",
+ "residentDetail": "待機中も少量のメモリを使用します。無効化またはアンインストールすると、プロセスは直ちに終了します。",
+ "subscribeTopics": "セッションの動きを傍受(ターン・セッションイベント、メッセージ内容は含まない)",
+ "subscribeActivity": "AI が思考中のタイミングと、あなたの操作を待っているタイミングを傍受",
+ "subscribeActivityDetail": "分かるのはタイミングのみです。思考の開始と終了、そして AI があなたの承認や回答を待っている時点だけを把握します。思考の内容、承認待ちの操作、関係するコマンドやファイル、計画の本文、質問、あなたの回答は一切見えず、あなたの代わりに承認することもできません。",
+ "subscribeHooks": "送信するメッセージの読み取り・ブロック・書き換えが可能",
+ "subscribeHooksDetail": "送信前に各メッセージを審査します。ブロックしたり、本文を書き換えてから送信することがあります。ブロックされたメッセージは編集して再送信できます。",
+ "subscribeAssistantReply": "AI の返信を読み取り・書き換え可能",
+ "subscribeAssistantReplyDetail": "AI の返信が完了するたびに処理します。本文を推敲・書き換えたり(直接置き換えられ、原文は残りません)、返信の吹き出しを独自に描画したカードに差し替えることがあります(カード差し替えの場合は原文が保持され、ワンタップで確認できます)。",
+ "card": "メッセージカードを描画",
+ "cardExternalLink": "カード内で外部リンクを宣言でき、確認後にブラウザで開きます",
+ "cardExternalLinkDetail": "カード内のリンクをクリックすると確認ダイアログが表示され、承認後にシステムブラウザで開きます。http/https アドレスのみ許可されます。",
+ "notify": "システム通知を表示可能(画面上部のライトな通知)",
+ "notifyDetail": "通知の内容はこのプラグインが提供し、通知にはその名前が表示されます。自動的に消え、操作を妨げることはありません。",
+ "badge": "プラグイン入口に未読マークを点灯できます",
+ "badgeDetail": "新しい内容があるとき、サイドバーのプラグイン入口と自身のカードに緑の点を点灯し、一行の要約を添えられます。パネルを開くと消えます。音は鳴らず、振動もせず、システムの通知センターにも入らず、システム通知とは別個の権限です。",
+ "confirm": "確認ダイアログで同意を求められます",
+ "confirmDetail": "実行前に Cindy 自身と同じ確認ダイアログを開いて尋ねることができます。文面はプラグインが提供し、ダイアログにはその名前が表示されます。確認するかキャンセルするかはあなたがクリックして決め、プラグイン自身はクリックできません。同時に開けるのは 1 つまでで、頻繁な要求はブロックされます。",
+ "fsWrite": "ファイルを書き込めます(作成/変更)",
+ "fsWriteDetail": "専用データフォルダにはいつでも書き込めます。現在のセッションの作業ディレクトリへの書き込みはセッションの権限モードに従います(自動承認モードでは直接書き込み、逐次確認モードでは事前に承認を求めます)。それ以外のフォルダへの書き込みは毎回確認が必要です。ファイルは常にホストが代理で書き込み、プラグイン自体があなたのファイルシステムに直接アクセスすることはありません。",
+ "libraryPersist": "永続ライブラリを使用可能(大量のファイルとデータベース)",
+ "libraryPersistDetail": "Cindy が管理する独立した保存領域を取得し、作品データ(キャンバス、画像、データベースなど)を保存します。通常のプラグインデータ割り当ての制限を受けません。ファイルとデータベースの操作はすべてホストが代行実行し、プラグインはライブラリ内の相対パスのみを使用して、他のファイルに触れることはできません。ライブラリ内のファイルをシステムのフォルダで表示したり、システムの名前を付けて保存ダイアログを開いてコピー先を選ばせることもできます。キャンセルすれば何もコピーされません。確認ダイアログなしで PNG ビットマップをシステムクリップボードに書き込むこともでき、その場合は現在のクリップボード内容が上書きされます。プラグインをアンインストールしてもこのデータは削除されず、削除には Cindy 設定での個別確認が必要です。",
+ "networkHost": "ネットワークドメイン {{host}} にアクセス",
+ "networkSecret": "認証情報「{{name}}」の入力が必要",
+ "networkSecretGhostInputDetail": "この資格情報はプラグイン自身の設定画面で入力を受け付けるため、入力時にはプラグインのページを経由します。その後ホストへ一度だけ渡されて暗号化保存され、保存後はプラグインから読み出せません。注入は宣言されたドメインへのリクエスト時のみホストが行います。",
+ "networkSecretIdentity": "ログインメールアドレスを認証情報「{{name}}」として使用します",
+ "networkSecretIdentityDetail": "値はログイン中のアカウントのメールアドレスから取得され、リクエスト時にホストが自動的に導出・注入します。入力は不要です。プラグインは設定画面に現在の身元を表示する目的で、このメールアドレスを読み取れます。",
+ "networkSecretGhCli": "認証情報「{{name}}」にはローカルの GitHub CLI ログインを優先して使用します",
+ "networkSecretGhCliDetail": "ホストは必要なときだけローカルの gh ログイントークンを読み取り、GitHub API リクエストにだけ注入します。プラグインのコードはトークンを読み取ったり保存したりできません。gh を利用できない場合は、プラグイン設定で予備の Personal Access Token を設定できます。",
+ "networkSecretOrganizationIdentity": "Cindy の組織ユーザー ID を認証情報「{{name}}」として使用します",
+ "networkSecretOrganizationIdentityDetail": "Cindy は必要なときに短時間有効な ID アサーションを発行し、ホストだけが明示されたサービスホストへ送信します。プラグインのコードはトークンを読み取ったり保存したりできません。",
+ "networkSecretOauth": "{{host}} で OAuth 認可を行うよう案内します({{name}})",
+ "networkSecretOauthDetail": "認可フローとすべてのトークンはホストが管理し、プラグインのコードからは読み取れません。クライアント資格情報はこのプラグインの詳細ページで入力します。以下は要求される権限スコープの原文です。確認のうえ許可してください。",
+ "networkConnections": "あなたが追加した{{label}}に接続可能",
+ "networkConnectionsDetail": "アドレスはこのプラグインの設定画面で追加します。新しいアドレスの追加には毎回あなたの確認が必要で、入力した資格情報は対応するアドレスにのみ注入されます。",
+ "codeDetailNetwork": "独立したサンドボックスで実行され、ファイルにはアクセスできません。ネットワークは上記のドメインに限られ、ホストが代理送信します。",
+ "codeDetailWithNode": "パネル UI は独立したサンドボックスで実行されます。ローカル処理は上記で宣言された Node ランタイムが提供します。",
+ "added": "追加",
+ "removed": "削除",
+ "updated": "更新",
+ "unchanged": "他 {{count}} 件の権限は変更なし",
+ "noChange": "権限に変更はありません。",
+ "pick": "フォルダの選択をあなたに依頼できます",
+ "pickDetail": "依頼があると、Cindy がシステムのフォルダ選択ウィンドウを表示します。どのフォルダを渡すかはあなたが直接決め、キャンセルすれば何も渡りません。",
+ "workspace": "プロジェクトフォルダのセッション入口をサイドバーに作成するよう依頼できます",
+ "workspaceDetail": "依頼があると、あなたが直接フォルダを選ぶか、確認カードでフルパスを見てから許可を決めます。あなたが開始した呼び出しの処理中は、現在のセッションの作業ディレクトリ内のサブフォルダは追加確認なしで使用されます。既にセッションがあるフォルダは再利用され、重複作成はされません。作成されるのは空のセッションだけで、勝手にタスクが始まることはありません。",
+ "sessionContext": "現在のセッションが使用中のプロジェクトフォルダの場所を知ることができます",
+ "sessionContextDetail": "現在のセッションのために動作するときだけ、場所の情報(セッション ID とプロジェクトフォルダのパス)を伝えます。ファイルの内容は含まれず、ファイルへのアクセス権も与えられません。",
+ "preview": "以下のサイトのプレビューページをサイドバーのブラウザで開けます",
+ "previewDetail": "開けるのは下に列挙されたサイトだけです。ページを開くたびに、どのプラグインが開いたかが表示されます。",
+ "nodeChildSpawn": "Node プログラムは、パッケージ内で申告済みのサブプロセスの起動をホストに依頼できます",
+ "nodeChildSpawnDetail": "起動できるのは自身のパッケージ内で申告済みの JS ファイルだけです(メインプログラムと同じローカル権限)。任意のコマンドは実行できません。プラグインの無効化や終了時にはサブプロセスも一緒に閉じられます。",
+ "skill": "AI アシスタントにスキル「{{name}}」を追加します",
+ "skillDetail": "スキルは AI が自分の指示として読み込んで実行する指示ファイルです。あなたの全権限で、Claude Code と Codex のすべてのプロジェクトに適用され、このプラグインのサンドボックスには制限されません。プラグインが有効な間は利用可能で、無効化またはアンインストールすると削除されます。特定のフォルダーだけでプラグインをオフにしても非表示にはなりません。ここではスキルの全文をプレビューできません——信頼できるプラグインのみをインストールしてください。",
+ "routineEvents": "ルーティンイベント"
+ },
+ "releaseChanged": "利用可能なバージョンが変更されました。更新後のバージョンを確認してからインストールしてください。",
+ "settingsUnavailable": "プラグイン設定を読み込めませんでした。設定を再読み込みしてお試しください。",
+ "settingsResultUnknown": "操作結果を確認できません。再送信する前にコンピューターの設定を再読み込みしてください。",
+ "settingsOperationFailed": "設定の操作を完了できませんでした。接続を確認して再試行してください。",
+ "settingsReload": "再試行"
+ },
+ "notice": {
+ "title": {
+ "offline": "コンピュータがオフライン",
+ "loadFailed": "プラグインを読み込めません",
+ "retired": "提供終了の機能",
+ "approvalRequired": "インストールの復元が必要",
+ "builtinRecovery": "内蔵プラグインの復元が必要",
+ "fused": "プラグインを一時停止中",
+ "authorization": "認証の確認が必要",
+ "resultUnknown": "結果を確認できません",
+ "writeFailed": "設定操作を完了できません",
+ "readFailed": "設定を読み込めません",
+ "managementFailed": "操作に失敗しました",
+ "confirmation": "プラグインの権限を確認"
+ },
+ "consentOrigin": {
+ "market": "公式マーケット",
+ "custom-market": "カスタムマーケット",
+ "local-file": "ローカルファイル",
+ "forge": "ローカルビルド"
+ },
+ "initiator": {
+ "user": "あなたのリクエスト",
+ "agent": "Agent のリクエスト"
+ },
+ "taskCapability": "現在のタスク用"
+ }
}
diff --git a/apps/mobile/src/i18n/locales/ko/plugins.json b/apps/mobile/src/i18n/locales/ko/plugins.json
index 60c0265c69..79e8af0187 100644
--- a/apps/mobile/src/i18n/locales/ko/plugins.json
+++ b/apps/mobile/src/i18n/locales/ko/plugins.json
@@ -1,5 +1,19 @@
{
- "mailReader": {"markReadFailed":"읽음 상태를 동기화하지 못했습니다. 메일함 인증을 확인하고 다시 여세요.","title":"메일","openMailbox":"메일함에서 열기","loading":"메일 읽는 중…","failed":"메일을 읽지 못했습니다. 연결된 계정을 확인하고 다시 시도하거나 메일함에서 여세요.","retry":"다시 시도","to":"받는 사람","cc":"참조","bcc":"숨은 참조","subject":"제목"},
+ "settingsHostUpdateRequired": "이 휴대폰에서 인증하려면 선택한 컴퓨터의 Cindy를 업데이트하세요.",
+ "settingsComputerLink": "이 링크는 컴퓨터의 로컬 서비스를 엽니다. 해당 컴퓨터에서 여세요.",
+ "settingsLinkUnavailable": "이 링크를 열 수 없습니다.",
+ "mailReader": {
+ "markReadFailed": "읽음 상태를 동기화하지 못했습니다. 메일함 인증을 확인하고 다시 여세요.",
+ "title": "메일",
+ "openMailbox": "메일함에서 열기",
+ "loading": "메일 읽는 중…",
+ "failed": "메일을 읽지 못했습니다. 연결된 계정을 확인하고 다시 시도하거나 메일함에서 여세요.",
+ "retry": "다시 시도",
+ "to": "받는 사람",
+ "cc": "참조",
+ "bcc": "숨은 참조",
+ "subject": "제목"
+ },
"title": "플러그인",
"all": "전체",
"unread": "읽지 않음",
@@ -30,8 +44,8 @@
"mainView": "페이지 열기",
"settings": "플러그인 설정",
"useInTask": "작업에서 사용",
- "newTask": "새 작업",
- "chooseTask": "기존 작업",
+ "newTask": "새 작업에서 사용",
+ "chooseTask": "기존 작업에서 사용",
"taskHint": "작업에서 요청을 설명하면 Cindy가 적절한 플러그인을 사용합니다. 기존 작업의 모델과 권한은 유지됩니다.",
"noMobilePage": "아직 모바일 페이지가 없습니다. 도구는 작업에서 사용할 수 있습니다.",
"expandFields": "펼치기",
@@ -59,6 +73,7 @@
"identityChangedHint": "컴퓨터의 인증 식별 정보가 변경되어 설정을 중단했습니다. 컴퓨터를 확인하고 장치 식별 정보를 다시 등록한 후 연결하세요. 이 카드에서는 등록된 식별 정보를 교체할 수 없습니다.",
"connectAccount": "계정 연결",
"computerAuthorization": "컴퓨터 콜백 필요",
+ "oauthUpdateRequired": "브라우저 인증을 완료하려면 이 휴대폰의 Cindy를 업데이트하세요.",
"computerAuthorizationHint": "이 연결 방식은 컴퓨터의 로컬 콜백을 사용합니다. 카드의 컴퓨터 진입점에서 연결을 완료하고 돌아와 상태를 확인하세요.",
"authorizationCheckHint": "설정 단계의 상태를 확인하세요. 확인되지 않은 작업은 자동으로 재전송하지 않습니다.",
"connectionHost": "연결 주소 (HTTPS 도메인)",
@@ -112,8 +127,8 @@
"setupUnknown": "설정 상태를 확인하지 못했습니다. 다시 불러오세요."
},
"action": {
- "connect": "컴퓨터 연결",
- "retry": "다시 불러오기",
+ "connect": "연결",
+ "retry": "재시도",
"enable": "플러그인 활성화",
"settings": "설정 완료",
"reconnect": "계정 다시 연결"
@@ -138,5 +153,158 @@
"mailAttaching": "첨부 파일 추가 중…",
"mailAttachFailed": "첨부 파일을 추가하지 못했습니다. 연결을 확인한 후 다시 시도해 주세요.",
"mailAttachTooLarge": "메일 첨부 파일 하나의 크기는 16 MB 이하여야 합니다.",
- "mailRemoveAttachment": "{{name}} 삭제"
+ "mailRemoveAttachment": "{{name}} 삭제",
+ "management": {
+ "manage": "플러그인 관리",
+ "update": "업데이트",
+ "uninstall": "제거",
+ "uninstallTitle": "{{name}}을(를) 제거할까요?",
+ "uninstallBody": "{{device}}에서 플러그인, 인증 정보 및 전용 설정을 제거합니다. 라이브러리와 기존 작업 내용은 유지됩니다.",
+ "reject": "취소",
+ "allow": "허용하고 계속",
+ "versionChange": "{{previous}} → {{next}}",
+ "oauthChanged": "계정 로그인 설정이 변경되었습니다.",
+ "state": {
+ "readFailed": "플러그인 관리 정보를 불러오지 못했습니다. 새로 고침하세요."
+ },
+ "permissions": {
+ "mail": "메일 초안 및 전송 카드 사용",
+ "mailDetail": "카드에서 초안을 편집하고 동기화하며, 전송 전에 확인 및 실행 취소 카운트다운을 표시합니다.",
+ "mailReader": "앱에서 메일 보기",
+ "mailReaderHost": "{{host}}의 메일 링크를 앱에서 열기",
+ "mailMarkRead": "메일을 열면 읽음으로 표시",
+ "grantsTitle": "설치 후 갖게 되는 권한:",
+ "toolsGroup": "등록 도구",
+ "toolsDiffGroup": "등록 도구 변경",
+ "itemCount": "{{count}}개",
+ "cindyImageGenerate": "이미지 생성(Cindy에게 대행 요청)",
+ "cindyImageEdit": "이미지 편집(Cindy에게 대행 요청, 자신이 생성한 이미지만)",
+ "cindyVideoGenerate": "영상 생성(Cindy에게 대행 요청)",
+ "cindyVideoEdit": "이미지로 영상 만들기(Cindy에게 대행 요청, 참조 이미지는 자신 소유만)",
+ "cindyMediaDeposit": "보유한 이미지·영상·오디오를 내 미디어 라이브러리에 저장할 수 있음",
+ "cindyMediaDepositDetail": "플러그인에 붙여넣거나 끌어다 놓은 소재도 AI가 편집할 수 있게 하는 권한입니다. 저장된 항목은 이 플러그인 이름으로 기록되며 최대 {{quota}}까지 사용하고, 플러그인을 삭제하면 함께 정리됩니다.",
+ "cindyTextOneshot": "Cindy의 빠른 채널에 질문하고 텍스트 답변을 받을 수 있음",
+ "cindyTextOneshotDetail": "시스템의 경량 작업 모델 체인(자동 제목과 같은 경로)을 사용합니다. Agent를 사용하지 않고 파일에도 접근하지 않습니다. 모델 비용이 발생할 수 있습니다.",
+ "cindyEmbedText": "텍스트를 벡터로 변환할 수 있습니다(의미 검색용)",
+ "cindyEmbedTextDetail": "텍스트가 시스템 벡터 모델로 전송되어 숫자 배열로 변환됩니다. 한 번에 최대 {{max}}개이며 모델 요금이 발생할 수 있습니다. 생성된 벡터는 플러그인만 보관하며 사용자 라이브러리에는 기록되지 않습니다.",
+ "cindySearchWeb": "Cindy AI로 공개 웹을 검색할 수 있음",
+ "cindySearchWebDetail": "검색 요청은 공개 웹에 접근하며 Cindy AI 사용량을 소모할 수 있습니다.",
+ "cindyTextOneshotModelDetail": "시스템의 경량 작업 모델 체인(자동 제목과 같은 경로)을 사용합니다. Agent를 사용하지 않고 파일에도 접근하지 않습니다. 모델 비용이 발생할 수 있습니다. 플러그인이 선호 모델을 선언했습니다: {{model}}(현재 카탈로그에서 사용 가능한 경우에 적용되며, 핀 설정이 우선 적용됩니다).",
+ "agentUserAction": "플러그인 카드를 클릭한 뒤 Agent의 새 작업을 시작할 수 있음",
+ "agentUserActionDetail": "클릭 한 번마다 한 번만 시작할 수 있으며, 해당 카드가 속한 세션에서만 사용할 수 있습니다.",
+ "agentBackground": "백그라운드에서 Agent의 새 작업을 자동으로 시작할 수 있음",
+ "agentBackgroundDetail": "매번 클릭할 필요는 없지만, 이전에 이 플러그인과 연결한 세션에서만 사용할 수 있습니다. 모델 비용이 발생할 수 있습니다.",
+ "agentTasksRequest": "세션 권한 확인",
+ "agentTasks": "이 플러그인의 Cindy 세션을 만들고 관리할 수 있음",
+ "agentTasksDetail": "메시지를 보내고 결과를 읽으며 자신의 실행을 중지할 수 있습니다. 세션은 사용자에게 표시됩니다. 플러그인의 AI 설정을 사용하며 모델 비용이 발생할 수 있습니다. 다른 세션에 대한 접근 권한은 부여하지 않습니다.",
+ "agentHiddenTasks": "세션 목록에 표시되지 않는 백그라운드 세션을 만들 수 있음",
+ "agentHiddenTasksDetail": "이 플러그인이 만든 세션을 세션 목록, 검색, 알림에 표시하지 않을 수 있습니다. 플러그인 상세의 「백그라운드 세션」에서 언제든지 확인하고 열거나 세션 목록에 표시할 수 있으며, 플러그인을 제거하면 다시 표시됩니다.",
+ "agentErrand": "작업을 만들고 실행하며 결과를 읽을 수 있습니다",
+ "agentErrandDetail": "생성된 작업은 Cindy 작업 목록에 표시되며 진행 상황을 확인하고 대화를 이어갈 수 있습니다.",
+ "agentSchedule": "자동화 새로 만들기를 요청할 수 있음",
+ "agentScheduleDetail": "내용이 미리 채워진 자동화 만들기 패널을 여는 것만 할 수 있으며, 실제로 만들지는 사용자가 모델을 고르고 직접 저장해 결정합니다. 만든 뒤에는 Cindy가 설정한 시간에 실행합니다. 모델 비용이 발생할 수 있습니다.",
+ "nodeRuntime": "함께 제공된 Node 프로그램을 이 컴퓨터에서 실행할 수 있음",
+ "nodeMcp": "함께 제공된 stdio MCP를 이 컴퓨터에서 실행할 수 있음",
+ "nodeRuntimeDetail": "고위험:사용자 계정과 같은 권한으로 로컬 파일을 읽거나 수정하고, 네트워크에 접근하며, 다른 프로그램을 시작할 수 있습니다. Cindy의 브라우저 샌드박스로 격리할 수 없습니다.",
+ "nodeSecret": "저장된 자격 증명 ‘{{name}}’을(를) 로컬 Node 프로그램에 제공할 수 있음",
+ "nodeSecretDetail": "Cindy가 암호화해 보관하고 아래에 선언된 Worker 메서드가 실행될 때만 임시로 주입합니다. Node 프로그램은 평문을 받으며 브라우저 측 플러그인 코드나 Agent 매개변수로 반환하거나 로그 또는 파일에 저장할 수 있으므로 신뢰할 수 있는 플러그인만 설치하세요.",
+ "nodeResident": "Node 프로그램을 백그라운드에서 계속 실행할 수 있음",
+ "nodeResidentDetail": "플러그인이 활성화된 동안 실행되며 비활성화, 업데이트, 제거 또는 Cindy 종료 시 중지됩니다.",
+ "tool": "도구 \"{{name}}\"",
+ "command": "채팅 명령 ${{command}}",
+ "panelLeft": "패널 \"{{title}}\" · 채팅 왼쪽에 도킹",
+ "panelTab": "패널 \"{{title}}\" · 플러그인 페이지에서 열기",
+ "mainView": "Cindy 사이드바에 “{{title}}” 항목을 추가할 수 있음",
+ "mainViewDetail": "클릭하면 플러그인 샌드박스에서 메인 보기가 열리며 파일, 네트워크 또는 자격 증명 접근 권한이 추가로 부여되지 않습니다.",
+ "code": "실행 코드",
+ "codeDetail": "격리된 샌드박스에서 실행되며 파일과 네트워크에 접근할 수 없습니다.",
+ "resident": "상주 실행(활성화하면 시작되며 호출이 없어도 백그라운드 프로세스 유지)",
+ "residentDetail": "대기 중에도 소량의 메모리를 사용합니다. 비활성화하거나 제거하면 프로세스가 즉시 종료됩니다.",
+ "subscribeTopics": "세션 활동을 수신(턴 및 세션 이벤트, 메시지 내용 제외)",
+ "subscribeActivity": "AI가 언제 생각하고 언제 사용자를 기다리는지 수신",
+ "subscribeActivityDetail": "시점만 알 수 있습니다. 생각이 언제 시작되고 끝나는지, 그리고 AI가 언제 사용자의 승인이나 답변을 기다리는지만 파악합니다. 생각의 내용, 승인 대기 중인 작업, 관련된 명령과 파일, 계획 본문, 질문, 사용자의 답변은 전혀 볼 수 없으며 사용자를 대신해 승인할 수도 없습니다.",
+ "subscribeHooks": "보내는 메시지를 읽고 차단하거나 고쳐 쓸 수 있음",
+ "subscribeHooksDetail": "전송 전에 각 메시지를 검토합니다. 차단하거나 본문을 고쳐 쓴 뒤 전송할 수 있으며, 차단된 메시지는 수정 후 다시 보낼 수 있습니다.",
+ "subscribeAssistantReply": "AI의 답변을 읽고 다시 쓸 수 있음",
+ "subscribeAssistantReplyDetail": "AI 답변이 완료될 때마다 처리합니다. 본문을 다듬거나 고쳐 쓸 수 있고(직접 교체되어 원문은 남지 않음), 답변 말풍선을 직접 렌더링한 카드로 교체할 수도 있습니다(카드로 교체된 경우 원문이 보존되며 한 번의 탭으로 확인할 수 있습니다).",
+ "card": "메시지 카드 렌더링",
+ "cardExternalLink": "카드에서 외부 링크를 선언할 수 있으며, 확인 후 브라우저에서 열립니다",
+ "cardExternalLinkDetail": "카드의 링크를 클릭하면 확인 대화 상자가 표시되며, 승인 후에만 시스템 브라우저에서 열립니다. http/https 주소만 허용됩니다.",
+ "notify": "시스템 알림 표시 가능(화면 상단의 가벼운 알림)",
+ "notifyDetail": "알림 내용은 이 플러그인이 제공하며 알림에는 이름이 표시됩니다. 자동으로 사라지며 작업을 방해하지 않습니다.",
+ "badge": "플러그인 입구에 읽지 않음 표시를 켤 수 있음",
+ "badgeDetail": "새 내용이 있으면 사이드바 플러그인 입구와 자체 카드에 초록 점을 켜고 한 줄 요약을 함께 표시할 수 있습니다. 패널을 열면 사라집니다. 소리를 내지 않고 진동하지도 않으며 시스템 알림 센터에도 들어가지 않고, 시스템 알림과는 별개의 권한입니다.",
+ "confirm": "확인 대화상자로 동의를 요청할 수 있음",
+ "confirmDetail": "작업 전에 Cindy 자체와 동일한 확인 대화상자를 열어 물어볼 수 있습니다. 질문 내용은 플러그인이 제공하며 대화상자에는 그 이름이 표시됩니다. 확인이든 취소든 직접 클릭해야 하고 플러그인은 스스로 누를 수 없습니다. 동시에 하나만 열 수 있으며 너무 자주 요청하면 차단됩니다.",
+ "fsWrite": "파일을 쓸 수 있음(생성/수정)",
+ "fsWriteDetail": "전용 데이터 폴더에는 언제든지 쓸 수 있습니다. 현재 세션의 작업 디렉터리 쓰기는 세션의 권한 모드를 따릅니다(자동 승인 모드에서는 바로 쓰고, 개별 확인 모드에서는 먼저 승인을 요청합니다). 그 외 폴더에 쓰려면 매번 확인이 필요합니다. 파일은 항상 호스트가 대신 기록하며 플러그인 자체는 파일 시스템에 직접 접근할 수 없습니다.",
+ "libraryPersist": "영구 라이브러리 사용 가능(대용량 파일 및 데이터베이스)",
+ "libraryPersistDetail": "Cindy가 관리하는 독립 저장 공간을 받아 작업 데이터(캔버스, 이미지, 데이터베이스 등)를 저장하며, 일반 플러그인 데이터 할당량 제한을 받지 않습니다. 파일과 데이터베이스 작업은 모두 호스트가 대신 실행하고 플러그인은 라이브러리 내 상대 경로만 사용하여 다른 파일에는 접근할 수 없습니다. 라이브러리 파일을 시스템 폴더에서 보여 주거나 시스템 다른 이름으로 저장 대화상자를 열어 복사 위치를 고르게 할 수도 있으며, 취소하면 아무 파일도 복사되지 않습니다. 확인 대화상자 없이 PNG 비트맵을 시스템 클립보드에 쓸 수도 있으며, 이때 현재 클립보드 내용이 덮어쓰입니다. 플러그인을 제거해도 이 데이터는 삭제되지 않으며, 삭제는 Cindy 설정에서 별도 확인이 필요합니다.",
+ "networkHost": "네트워크 도메인 {{host}}에 접근",
+ "networkSecret": "자격 증명 \"{{name}}\" 입력 필요",
+ "networkSecretGhostInputDetail": "이 자격 증명은 플러그인 자체 설정 화면에서 입력받으므로 입력 시점에 플러그인 페이지를 거칩니다. 이후 호스트에 한 번만 전달되어 암호화 저장되며, 저장 후에는 플러그인이 다시 읽을 수 없습니다. 주입은 선언된 도메인 요청 시에만 호스트가 수행합니다.",
+ "networkSecretIdentity": "로그인 이메일을 자격 증명 \"{{name}}\"(으)로 사용합니다",
+ "networkSecretIdentityDetail": "값은 로그인된 계정의 이메일에서 가져오며, 요청 시 호스트가 자동으로 파생하여 주입합니다. 입력할 필요가 없으며, 플러그인은 설정 화면에 현재 신원을 표시하기 위해 이 이메일을 읽을 수 있습니다.",
+ "networkSecretGhCli": "자격 증명 \"{{name}}\"에는 로컬 GitHub CLI 로그인을 우선 사용합니다",
+ "networkSecretGhCliDetail": "호스트는 필요할 때만 로컬 gh 로그인 토큰을 읽어 GitHub API 요청에만 주입합니다. 플러그인 코드는 토큰을 읽거나 저장할 수 없습니다. gh를 사용할 수 없으면 플러그인 설정에서 예비 Personal Access Token을 구성할 수 있습니다.",
+ "networkSecretOrganizationIdentity": "Cindy 조직 사용자 신원을 자격 증명 \"{{name}}\"(으)로 사용합니다",
+ "networkSecretOrganizationIdentityDetail": "Cindy가 필요할 때 단기 신원 어설션을 발급하며, 호스트만 명시된 서비스 호스트로 전송합니다. 플러그인 코드는 토큰을 읽거나 저장할 수 없습니다.",
+ "networkSecretOauth": "{{host}}에서 OAuth 인증을 진행하도록 안내합니다({{name}})",
+ "networkSecretOauthDetail": "인증 흐름과 모든 토큰은 호스트가 관리하며 플러그인 코드는 읽을 수 없습니다. 클라이언트 자격 증명은 이 플러그인의 상세 페이지에서 직접 입력합니다. 아래는 요청되는 권한 범위(scopes) 원문이니 확인 후 허용하세요.",
+ "networkConnections": "내가 추가한 {{label}}에 연결 가능",
+ "networkConnectionsDetail": "주소는 이 플러그인의 설정 화면에서 추가합니다. 새 주소를 추가할 때마다 확인이 필요하며, 입력한 자격 증명은 해당 주소에만 주입됩니다.",
+ "codeDetailNetwork": "독립된 샌드박스에서 실행되며 파일에는 접근할 수 없습니다. 네트워크는 위에 표시된 도메인으로 제한되며 호스트가 대신 전송합니다.",
+ "codeDetailWithNode": "패널 UI는 독립된 샌드박스에서 실행됩니다. 로컬 처리는 위에서 선언된 Node 런타임이 제공합니다.",
+ "added": "추가",
+ "removed": "제거",
+ "updated": "업데이트됨",
+ "unchanged": "그 외 {{count}}개 권한은 변경 없음",
+ "noChange": "권한 변경이 없습니다.",
+ "pick": "폴더 선택을 요청할 수 있습니다",
+ "pickDetail": "요청 시 Cindy가 시스템 폴더 선택 창을 띄웁니다. 어떤 폴더를 넘길지는 직접 결정하며, 취소하면 아무것도 전달되지 않습니다.",
+ "workspace": "프로젝트 폴더의 세션 항목을 사이드바에 만들도록 요청할 수 있습니다",
+ "workspaceDetail": "요청 시 직접 폴더를 선택하거나 확인 카드에서 전체 경로를 본 뒤 허용 여부를 결정합니다. 사용자가 시작한 호출을 처리하는 동안에는 현재 세션 작업 디렉터리 안의 하위 폴더는 추가 확인 없이 사용됩니다. 이미 세션이 있는 폴더는 재사용되어 중복 생성되지 않습니다. 만들어지는 것은 빈 세션뿐이며 스스로 작업을 시작하지 않습니다.",
+ "sessionContext": "현재 세션이 사용 중인 프로젝트 폴더 위치를 알 수 있습니다",
+ "sessionContextDetail": "현재 세션을 위해 작동할 때만 위치 정보(세션 ID와 프로젝트 폴더 경로)를 전달합니다. 파일 내용은 포함되지 않으며 파일 접근 권한도 부여되지 않습니다.",
+ "preview": "아래 사이트의 미리보기 페이지를 사이드바 브라우저에서 열 수 있습니다",
+ "previewDetail": "아래에 나열된 사이트만 열 수 있으며, 페이지를 열 때마다 어떤 플러그인이 열었는지 표시됩니다.",
+ "nodeChildSpawn": "Node 프로그램이 패키지에 신고된 하위 프로세스 시작을 호스트에 요청할 수 있습니다",
+ "nodeChildSpawnDetail": "자신의 패키지 안에 신고된 JS 파일만 시작할 수 있으며(메인 프로그램과 동일한 로컬 권한), 임의의 명령은 실행할 수 없습니다. 플러그인이 비활성화되거나 종료되면 하위 프로세스도 함께 종료됩니다.",
+ "skill": "AI 어시스턴트에 스킬 \"{{name}}\"을(를) 추가합니다",
+ "skillDetail": "스킬은 AI가 자신의 지시로 읽어들여 실행하는 지시 파일입니다. 사용자의 전체 권한으로 Claude Code와 Codex의 모든 프로젝트에 적용되며, 이 플러그인의 샌드박스에 제한되지 않습니다. 플러그인이 활성화된 동안 계속 사용 가능하며, 비활성화하거나 제거하면 삭제됩니다. 특정 폴더에서만 플러그인을 끄더라도 숨겨지지 않습니다. 여기서는 스킬 전문을 미리 볼 수 없습니다 — 신뢰할 수 있는 플러그인만 설치하세요.",
+ "routineEvents": "루틴 이벤트"
+ },
+ "releaseChanged": "사용 가능한 버전이 변경되었습니다. 새 버전을 확인한 뒤 설치하세요.",
+ "settingsUnavailable": "플러그인 설정을 불러오지 못했습니다. 설정을 다시 불러와 주세요.",
+ "settingsResultUnknown": "작업 결과를 확인하지 못했습니다. 다시 제출하기 전에 컴퓨터의 설정을 다시 불러와 확인하세요.",
+ "settingsOperationFailed": "설정 작업을 완료하지 못했습니다. 연결을 확인하고 다시 시도해 주세요.",
+ "settingsReload": "재시도"
+ },
+ "notice": {
+ "title": {
+ "offline": "컴퓨터 오프라인",
+ "loadFailed": "플러그인을 불러올 수 없음",
+ "retired": "종료된 기능",
+ "approvalRequired": "설치 복구 필요",
+ "builtinRecovery": "기본 플러그인 복구 필요",
+ "fused": "플러그인 일시 중지",
+ "authorization": "인증 확인 필요",
+ "resultUnknown": "결과 확인 필요",
+ "writeFailed": "설정 작업을 완료하지 못했습니다",
+ "readFailed": "설정 읽기 실패",
+ "managementFailed": "작업 실패",
+ "confirmation": "플러그인 권한 확인"
+ },
+ "consentOrigin": {
+ "market": "공식 마켓",
+ "custom-market": "사용자 지정 마켓",
+ "local-file": "로컬 파일",
+ "forge": "로컬 빌드"
+ },
+ "initiator": {
+ "user": "사용자가 요청함",
+ "agent": "Agent가 요청함"
+ },
+ "taskCapability": "현재 작업용"
+ }
}
diff --git a/apps/mobile/src/i18n/locales/zh-CN/plugins.json b/apps/mobile/src/i18n/locales/zh-CN/plugins.json
index e179d405d6..7efe04f05d 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/plugins.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/plugins.json
@@ -1,5 +1,19 @@
{
- "mailReader": {"markReadFailed":"未能同步已读状态,请检查邮箱授权后重新打开。","title":"邮件","openMailbox":"在邮箱中打开","loading":"正在读取邮件…","failed":"未能读取这封邮件。请检查连接的邮箱账号后重试,或在邮箱中打开。","retry":"重试","to":"收件人","cc":"抄送","bcc":"密送","subject":"主题"},
+ "settingsHostUpdateRequired": "请更新所选电脑上的 Cindy,以便在手机上完成授权。",
+ "settingsComputerLink": "此链接指向电脑上的本地服务,请在该电脑打开。",
+ "settingsLinkUnavailable": "无法打开此链接。",
+ "mailReader": {
+ "markReadFailed": "未能同步已读状态,请检查邮箱授权后重新打开。",
+ "title": "邮件",
+ "openMailbox": "在邮箱中打开",
+ "loading": "正在读取邮件…",
+ "failed": "未能读取这封邮件。请检查连接的邮箱账号后重试,或在邮箱中打开。",
+ "retry": "重试",
+ "to": "收件人",
+ "cc": "抄送",
+ "bcc": "密送",
+ "subject": "主题"
+ },
"title": "插件",
"all": "全部",
"unread": "未读",
@@ -30,8 +44,8 @@
"mainView": "打开页面",
"settings": "插件设置",
"useInTask": "在任务中使用",
- "newTask": "新建任务",
- "chooseTask": "已有任务",
+ "newTask": "新建任务并使用",
+ "chooseTask": "在已有任务中使用",
"taskHint": "在任务中说明你的需求,Cindy 会调用适合的插件。已有任务继续使用原来的模型和权限。",
"noMobilePage": "此插件尚未提供手机页面,可在任务中使用其工具。",
"expandFields": "展开",
@@ -59,6 +73,7 @@
"identityChangedHint": "这台电脑的授权身份与上次不同,已停止配置。请先核实电脑并重新登记设备身份,再连接;这里不能确认或替换已登记的身份。",
"connectAccount": "连接账号",
"computerAuthorization": "需要电脑上的回调",
+ "oauthUpdateRequired": "请更新此手机上的 Cindy,以完成浏览器授权。",
"computerAuthorizationHint": "此账号连接方式使用电脑本地回调。请使用此卡片的电脑入口完成连接,然后回到这里查看状态。",
"authorizationCheckHint": "请查看此配置步骤的状态;未确认的操作不会自动重发。",
"connectionHost": "连接地址(HTTPS 域名)",
@@ -112,8 +127,8 @@
"setupUnknown": "配置状态尚未确认,请重新读取。"
},
"action": {
- "connect": "连接电脑",
- "retry": "重新读取",
+ "connect": "连接",
+ "retry": "重试",
"enable": "启用插件",
"settings": "完成配置",
"reconnect": "重新连接账号"
@@ -138,5 +153,158 @@
"mailAttaching": "正在添加附件…",
"mailAttachFailed": "附件未能添加,请检查连接后重试。",
"mailAttachTooLarge": "单个邮件附件不能超过 16 MB。",
- "mailRemoveAttachment": "移除 {{name}}"
+ "mailRemoveAttachment": "移除 {{name}}",
+ "management": {
+ "manage": "管理插件",
+ "update": "升级",
+ "uninstall": "卸载",
+ "uninstallTitle": "卸载 {{name}}?",
+ "uninstallBody": "将从 {{device}} 移除此插件、凭证和私有配置。作品库及已有任务内容会保留。",
+ "reject": "取消",
+ "allow": "允许并继续",
+ "versionChange": "{{previous}} → {{next}}",
+ "oauthChanged": "账号登录配置发生了变化。",
+ "state": {
+ "readFailed": "未能读取插件管理信息,请刷新查看。"
+ },
+ "permissions": {
+ "mail": "使用邮件草稿与发送卡片",
+ "mailDetail": "可在卡片中编辑和同步草稿,并在发送前提供确认和撤销倒计时。",
+ "mailReader": "在应用内查看邮件",
+ "mailReaderHost": "在应用内打开 {{host}} 的邮件链接",
+ "mailMarkRead": "打开邮件时可将其标记为已读",
+ "grantsTitle": "安装后它将拥有:",
+ "toolsGroup": "注册工具",
+ "toolsDiffGroup": "注册工具变化",
+ "itemCount": "{{count}} 项",
+ "cindyImageGenerate": "图像生成(请 Cindy 代办)",
+ "cindyImageEdit": "图像编辑(请 Cindy 代办,仅限它自己生成的图)",
+ "cindyVideoGenerate": "视频生成(请 Cindy 代办)",
+ "cindyVideoEdit": "图生视频(请 Cindy 代办,参考图仅限它名下的图)",
+ "cindyMediaDeposit": "可将它手中的图片、视频或音频存入你的媒体库",
+ "cindyMediaDepositDetail": "用于让你在插件里粘贴或拖入的素材也能被 AI 加工。存入的内容记在这个插件名下,最多占用 {{quota}},卸载插件时一并清理。",
+ "cindyTextOneshot": "可向 Cindy 的快速通道提问并获得文字回答",
+ "cindyTextOneshotDetail": "走系统的轻量任务模型链(与自动起标题同一条通道),不动用 Agent、碰不到你的文件,可能产生模型费用。",
+ "cindyEmbedText": "可把文字送去算成向量(用于语义检索)",
+ "cindyEmbedTextDetail": "文字会送到系统的向量模型算成一串数字,单次最多 {{max}} 条,可能产生模型费用。算出的向量只交给插件自己保管,不写入你的资料库。",
+ "cindySearchWeb": "可使用 Cindy AI 搜索公网",
+ "cindySearchWebDetail": "查询会访问公网,并可能消耗 Cindy AI 配额。",
+ "cindyTextOneshotModelDetail": "走系统的轻量任务模型链(与自动起标题同一条通道),不动用 Agent、碰不到你的文件,可能产生模型费用。插件声明了偏好模型:{{model}}(当前目录可用时生效;你的钉档优先)。",
+ "agentUserAction": "用户点击插件卡片后,可让 Agent 开始新一轮工作",
+ "agentUserActionDetail": "每次点击只允许启动一次,并且只能使用这张卡所属的任务。",
+ "agentBackground": "可在后台自动让 Agent 开始新一轮工作",
+ "agentBackgroundDetail": "不需要当次点击,但只能使用你曾为这个插件建立过关联的任务,可能产生模型费用。",
+ "agentTasksRequest": "确认任务权限",
+ "agentTasks": "可创建和管理本插件的 Cindy 任务",
+ "agentTasksDetail": "可发送消息、读取结果和停止本插件的执行,任务对你可见。沿用插件的 AI 配置,可能产生模型费用;不授予其他任务的访问权。",
+ "agentHiddenTasks": "可创建不显示在任务列表里的后台任务",
+ "agentHiddenTasksDetail": "本插件创建的任务可以不出现在任务列表、搜索和通知里。你可以随时在插件详情的「后台任务」中查看、打开,或显示到任务列表;卸载插件时这些任务会恢复显示。",
+ "agentErrand": "可以新建任务、执行工作并读取结果",
+ "agentErrandDetail": "创建的任务会出现在 Cindy 的任务列表中,可以查看过程并继续交流。",
+ "agentSchedule": "可以请你新建自动化",
+ "agentScheduleDetail": "它只能为你打开新建自动化的面板并把内容填好,是否创建由你在面板上选好模型后亲手保存决定。创建后由 Cindy 按你设定的时间运行,可能产生模型费用。",
+ "nodeRuntime": "可在本机运行随插件附带的 Node 程序",
+ "nodeMcp": "可在本机运行随插件附带的 stdio MCP",
+ "nodeRuntimeDetail": "高风险:它和你本人一样,可以读取或修改你账号能访问的本机文件、访问网络并启动其它程序。Cindy 不能用浏览器沙箱限制它。",
+ "nodeSecret": "可将已保存凭证「{{name}}」提供给本机 Node 程序",
+ "nodeSecretDetail": "Cindy 加密保管,仅在下列已声明 Worker 方法执行时临时注入。Node 程序会收到明文,也可以将其回传、记录、保存或暴露给浏览器侧插件代码及 Agent 参数;请只安装可信插件。",
+ "nodeResident": "Node 程序可常驻后台",
+ "nodeResidentDetail": "插件启用期间会一直运行;停用、更新、卸载或退出 Cindy 时关闭。",
+ "tool": "工具「{{name}}」",
+ "command": "对话指令 ${{command}}",
+ "panelLeft": "面板「{{title}}」· 停靠主对话区左侧",
+ "panelTab": "面板「{{title}}」· 插件页内打开",
+ "mainView": "可在 Cindy 侧边栏添加“{{title}}”入口",
+ "mainViewDetail": "点击后将在插件沙箱中打开主视图,不会因此获得文件、网络或凭证访问权限。",
+ "code": "可执行代码",
+ "codeDetail": "在独立沙箱中运行,无法访问你的文件与网络。",
+ "resident": "常驻运行(生效后即启动,不调用也保持后台进程)",
+ "residentDetail": "空闲时也占用少量内存;停用或卸载后进程立即关闭。",
+ "subscribeTopics": "旁听你的任务动态(每轮往来与任务事件,不含消息内容)",
+ "subscribeActivity": "旁听 AI 何时在思考、何时在等你",
+ "subscribeActivityDetail": "只知道时机:思考何时开始与结束,以及 AI 何时在等你批准或等你回答。看不到思考内容、待批准的操作、涉及的命令与文件、计划正文、问题与你的答案,也无法代你批准。",
+ "subscribeHooks": "可读取、拦截或改写你发出的消息",
+ "subscribeHooksDetail": "发送前先经它审阅:可拦下消息,也可能改写正文后再发出;被拦的消息可编辑后重发。",
+ "subscribeAssistantReply": "可读取并重写 AI 的回复",
+ "subscribeAssistantReplyDetail": "AI 每轮回复完成后先经它处理:可润色改写正文(直接替换,不留原文),或用自绘卡片替换回复气泡(卡片替换时原文保留,可一键查看)。",
+ "card": "渲染消息卡片",
+ "cardExternalLink": "卡片内可声明外链,经你确认后打开浏览器",
+ "cardExternalLinkDetail": "卡片中的链接点击后会弹出确认框,你同意后才会在系统浏览器中打开;仅限 http/https 地址。",
+ "notify": "可弹出系统提示(屏幕顶部的轻提示)",
+ "notifyDetail": "提示内容由这个插件提供,提示上会标注它的名字;自动消失,不会打断你的操作。",
+ "badge": "可在插件入口点亮未读提醒",
+ "badgeDetail": "有新内容时,它可以在侧栏插件入口和自己的卡片上点亮一个绿点,并附一句话摘要;你打开它的面板即清零。绿点不出声、不震动,也不会进入系统通知中心,和上面的系统提示是两项独立权限。",
+ "confirm": "可弹出确认框征求你同意",
+ "confirmDetail": "它动手前可以弹一个和 Cindy 同款的确认框来问你,问句由它提供、框上会标注它的名字;同意还是取消都由你亲手点,它自己点不了。同时最多一个确认框,弹得太频会被拦下。",
+ "fsWrite": "可写入文件(创建/修改)",
+ "fsWriteDetail": "它自己的专属数据目录随时可写;当前任务的工作目录跟随任务的权限模式(免批模式直接写,逐条确认模式先征求你同意);其它目录每次都需要你确认。文件始终由主机代写,插件本身无法直接访问你的文件系统。",
+ "libraryPersist": "可使用持久作品库(大量文件与数据库)",
+ "libraryPersistDetail": "它会获得一个由 Cindy 管理的独立存储区,用来保存你的作品数据(如画布、图片、数据库),不受普通插件数据配额限制。文件与数据库操作全部由主机代执行,插件只能使用库内相对路径,无法触碰你的其它文件。它还可以让 Cindy 在系统文件夹中显示库内文件,或弹出系统另存为窗口由你选择拷贝位置;取消则不会拷出任何文件。它还可以把 PNG 位图写入系统剪贴板;没有确认框,会覆盖当前剪贴板内容。卸载插件不会删除这些数据;删除必须在 Cindy 设置中单独确认。",
+ "networkHost": "访问网络域名 {{host}}",
+ "networkSecret": "需要你提供凭证「{{name}}」",
+ "networkSecretGhostInputDetail": "凭证由这个插件自己的设置界面收集,录入时会经过插件页面;随后一次性交给主机加密保管,存入后插件无法读回,主机只在请求它声明的域名时注入。",
+ "networkSecretIdentity": "将使用你的登录邮箱作为凭证「{{name}}」",
+ "networkSecretIdentityDetail": "值取自当前登录账号的邮箱,请求时由主机自动派生注入;无需填写。插件可读取该邮箱,用于在它的设置界面里展示当前身份。",
+ "networkSecretGhCli": "将优先使用本机 GitHub CLI 登录作为凭证「{{name}}」",
+ "networkSecretGhCliDetail": "主机按需读取本机 gh 登录令牌,并且只注入 GitHub API 请求;插件代码无法读取或保存令牌。若 gh 不可用,可在插件设置中配置备用 Personal Access Token。",
+ "networkSecretOrganizationIdentity": "将使用你的 Cindy 企业身份作为凭证「{{name}}」",
+ "networkSecretOrganizationIdentityDetail": "Cindy 会按需签发短时身份断言,仅由主机发送给明确列出的服务域名;插件代码无法读取或保存令牌。",
+ "networkSecretOauth": "将引导你在 {{host}} 完成 OAuth 授权({{name}})",
+ "networkSecretOauthDetail": "授权流程与全部令牌由主机代管,插件代码无法读取;客户端凭证由你在本插件详情页自填。下方为其申请的权限范围(scopes)原文,请确认后再放行。",
+ "networkConnections": "可连接你添加的 {{label}}",
+ "networkConnectionsDetail": "地址在这个插件的设置界面里添加;每次新增地址都需要你确认,你提供的凭证只注入对应地址。",
+ "codeDetailNetwork": "在独立沙箱中运行,无法访问你的文件;网络仅限上方声明的域名,由主机代发。",
+ "codeDetailWithNode": "面板 UI 在独立沙箱中运行;本地处理能力由上方声明的 Node 运行时提供。",
+ "added": "新增",
+ "removed": "移除",
+ "updated": "更新",
+ "unchanged": "其余 {{count}} 项权限不变",
+ "noChange": "权限无变化。",
+ "pick": "可请求你选择一个文件夹交给它",
+ "pickDetail": "它发起请求时,Cindy 会弹出系统的选择文件夹窗口;选哪个、给不给,都由你亲手决定,取消则它什么都拿不到。",
+ "workspace": "可请求为项目文件夹在侧边栏创建任务入口",
+ "workspaceDetail": "它发起请求时,由你亲手选择文件夹,或在确认卡上看到完整路径后再决定;它正在处理你发起的调用时,当前任务工作目录内的子文件夹可直接使用,不再单独确认。文件夹已有任务时直接复用,不重复创建。创建的只是空任务,不会自动开始运行。",
+ "sessionContext": "可获知当前任务正在使用的项目文件夹位置",
+ "sessionContextDetail": "只在它为当前任务干活时告知位置信息(任务编号与项目文件夹路径),不包含文件内容,也不因此获得文件访问权。",
+ "preview": "可在右侧栏浏览器中打开以下网站的预览页面",
+ "previewDetail": "只能打开下方列出的网站;每次打开都会提示是哪个插件打开的。",
+ "nodeChildSpawn": "Node 程序可请宿主再启动包内申报过的子进程",
+ "nodeChildSpawnDetail": "只能启动它自己包里申报过的 JS 文件(与主程序同样的本机权限),不能执行任意命令;插件停用或退出时子进程一并关闭。",
+ "skill": "为 AI 助手添加技能「{{name}}」",
+ "skillDetail": "技能是一份指令文件,AI 会把它当作自己的指令加载执行,拥有你的全部权限,对 Claude Code 与 Codex、所有项目都生效——不受本插件沙箱约束。插件启用期间持续可用,停用或卸载即移除;仅对某个文件夹关闭本插件不会隐藏它。此处无法预览技能全文——请只安装你信任的插件。",
+ "routineEvents": "例行任务事件"
+ },
+ "releaseChanged": "可用版本已变化,请查看刷新后的版本,再选择安装。",
+ "settingsUnavailable": "插件设置加载失败,请重新加载设置后重试。",
+ "settingsResultUnknown": "尚未确认操作结果。请先重新读取电脑上的设置,再决定是否提交。",
+ "settingsOperationFailed": "设置操作未能完成,请检查连接后重试。",
+ "settingsReload": "重试"
+ },
+ "notice": {
+ "title": {
+ "offline": "电脑已离线",
+ "loadFailed": "插件加载失败",
+ "retired": "功能已停用",
+ "approvalRequired": "安装需要恢复",
+ "builtinRecovery": "内置插件需要恢复",
+ "fused": "插件已暂停",
+ "authorization": "授权需要处理",
+ "resultUnknown": "结果待确认",
+ "writeFailed": "配置操作未完成",
+ "readFailed": "配置读取失败",
+ "managementFailed": "操作失败",
+ "confirmation": "确认插件权限"
+ },
+ "consentOrigin": {
+ "market": "官方市场",
+ "custom-market": "自定义市场",
+ "local-file": "本地文件",
+ "forge": "本地构建"
+ },
+ "initiator": {
+ "user": "由你发起",
+ "agent": "由 Agent 发起"
+ },
+ "taskCapability": "用于当前任务"
+ }
}
diff --git a/apps/mobile/src/i18n/locales/zh-TW/plugins.json b/apps/mobile/src/i18n/locales/zh-TW/plugins.json
index f235bd43d0..86f5b9cb05 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/plugins.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/plugins.json
@@ -1,5 +1,19 @@
{
- "mailReader": {"markReadFailed":"未能同步已讀狀態,請檢查信箱授權後重新開啟。","title":"郵件","openMailbox":"在信箱中開啟","loading":"正在讀取郵件…","failed":"未能讀取這封郵件。請檢查連接的信箱帳號後重試,或在信箱中開啟。","retry":"重試","to":"收件人","cc":"副本","bcc":"密件副本","subject":"主旨"},
+ "settingsHostUpdateRequired": "請更新所選電腦上的 Cindy,以便在手機上完成授權。",
+ "settingsComputerLink": "此連結指向電腦上的本機服務,請在該電腦開啟。",
+ "settingsLinkUnavailable": "無法開啟此連結。",
+ "mailReader": {
+ "markReadFailed": "未能同步已讀狀態,請檢查信箱授權後重新開啟。",
+ "title": "郵件",
+ "openMailbox": "在信箱中開啟",
+ "loading": "正在讀取郵件…",
+ "failed": "未能讀取這封郵件。請檢查連接的信箱帳號後重試,或在信箱中開啟。",
+ "retry": "重試",
+ "to": "收件人",
+ "cc": "副本",
+ "bcc": "密件副本",
+ "subject": "主旨"
+ },
"title": "插件",
"all": "全部",
"unread": "未讀",
@@ -30,8 +44,8 @@
"mainView": "開啟頁面",
"settings": "插件設定",
"useInTask": "在任務中使用",
- "newTask": "新增任務",
- "chooseTask": "已有任務",
+ "newTask": "建立任務並使用",
+ "chooseTask": "在既有任務中使用",
"taskHint": "在任務中說明需求,Cindy 會使用適合的插件。現有任務保留原有模型與權限。",
"noMobilePage": "此插件尚未提供手機頁面,可在任務中使用其工具。",
"expandFields": "展開",
@@ -59,6 +73,7 @@
"identityChangedHint": "這台電腦的授權身分與上次不同,已停止設定。請先核實電腦並重新登記裝置身分,再連線;此處不能確認或取代已登記的身分。",
"connectAccount": "連接帳號",
"computerAuthorization": "需要電腦上的回呼",
+ "oauthUpdateRequired": "請更新此手機上的 Cindy,以完成瀏覽器授權。",
"computerAuthorizationHint": "此帳號連接方式使用電腦本機回呼。請使用此卡片的電腦入口完成連接,再回到這裡查看狀態。",
"authorizationCheckHint": "請查看此設定步驟的狀態;未確認的操作不會自動重送。",
"connectionHost": "連接地址(HTTPS 網域)",
@@ -112,8 +127,8 @@
"setupUnknown": "設定狀態尚未確認,請重新讀取。"
},
"action": {
- "connect": "連線電腦",
- "retry": "重新讀取",
+ "connect": "連線",
+ "retry": "重試",
"enable": "啟用插件",
"settings": "完成設定",
"reconnect": "重新連線帳號"
@@ -138,5 +153,158 @@
"mailAttaching": "正在新增附件…",
"mailAttachFailed": "無法新增附件,請檢查連線後重試。",
"mailAttachTooLarge": "單個郵件附件不能超過 16 MB。",
- "mailRemoveAttachment": "移除 {{name}}"
+ "mailRemoveAttachment": "移除 {{name}}",
+ "management": {
+ "manage": "管理插件",
+ "update": "升級",
+ "uninstall": "解除安裝",
+ "uninstallTitle": "解除安裝 {{name}}?",
+ "uninstallBody": "將從 {{device}} 移除此插件、憑證和私有設定。作品庫及既有任務內容會保留。",
+ "reject": "取消",
+ "allow": "允許並繼續",
+ "versionChange": "{{previous}} → {{next}}",
+ "oauthChanged": "帳號登入設定已變更。",
+ "state": {
+ "readFailed": "無法讀取插件管理資訊,請重新整理。"
+ },
+ "permissions": {
+ "mail": "使用郵件草稿與傳送卡片",
+ "mailDetail": "可在卡片中編輯和同步草稿,並在傳送前提供確認與撤銷倒數。",
+ "mailReader": "在應用程式內查看郵件",
+ "mailReaderHost": "在應用程式內開啟 {{host}} 的郵件連結",
+ "mailMarkRead": "開啟郵件時可將其標記為已讀",
+ "grantsTitle": "安裝後它將擁有:",
+ "toolsGroup": "註冊工具",
+ "toolsDiffGroup": "註冊工具變化",
+ "itemCount": "{{count}} 項",
+ "cindyImageGenerate": "影像生成(請 Cindy 代辦)",
+ "cindyImageEdit": "影像編輯(請 Cindy 代辦,僅限它自己生成的圖)",
+ "cindyVideoGenerate": "影片生成(請 Cindy 代辦)",
+ "cindyVideoEdit": "圖生影片(請 Cindy 代辦,參考圖僅限它名下的圖)",
+ "cindyMediaDeposit": "可將它手中的圖片、影片或音訊存入你的媒體庫",
+ "cindyMediaDepositDetail": "用於讓你在插件裡貼上或拖入的素材也能被 AI 加工。存入的內容記在這個插件名下,最多佔用 {{quota}},解除安裝插件時一併清理。",
+ "cindyTextOneshot": "可向 Cindy 的快速通道提問並獲得文字回答",
+ "cindyTextOneshotDetail": "走系統的輕量任務模型鏈(與自動起標題同一條通道),不動用 Agent、碰不到你的檔案,可能產生模型費用。",
+ "cindyEmbedText": "可把文字送去算成向量(用於語義檢索)",
+ "cindyEmbedTextDetail": "文字會送到系統的向量模型算成一串數字,單次最多 {{max}} 條,可能產生模型費用。算出的向量只交給插件自己保管,不寫入你的資料庫。",
+ "cindySearchWeb": "可使用 Cindy AI 搜尋公網",
+ "cindySearchWebDetail": "查詢會訪問公網,並可能消耗 Cindy AI 配額。",
+ "cindyTextOneshotModelDetail": "走系統的輕量任務模型鏈(與自動起標題同一條通道),不動用 Agent、碰不到你的檔案,可能產生模型費用。插件聲明瞭偏好模型:{{model}}(當前目錄可用時生效;你的釘檔優先)。",
+ "agentUserAction": "使用者點選插件卡片後,可讓 Agent 開始新一輪工作",
+ "agentUserActionDetail": "每次點選只允許啟動一次,並且只能使用這張卡所屬的任務。",
+ "agentBackground": "可在後臺自動讓 Agent 開始新一輪工作",
+ "agentBackgroundDetail": "不需要當次點選,但只能使用你曾為這個插件建立過關聯的任務,可能產生模型費用。",
+ "agentTasksRequest": "確認任務權限",
+ "agentTasks": "可建立和管理本插件的 Cindy 任務",
+ "agentTasksDetail": "可傳送訊息、讀取結果和停止本插件的執行,任務對你可見。沿用插件的 AI 配置,可能產生模型費用;不授予其他任務的存取權。",
+ "agentHiddenTasks": "可建立不顯示在任務列表裡的後臺任務",
+ "agentHiddenTasksDetail": "本插件建立的任務可以不出現在任務列表、搜尋和通知裡。你可以隨時在插件詳情的「後臺任務」中查看、開啟,或顯示到任務列表;解除安裝插件時這些任務會恢復顯示。",
+ "agentErrand": "可建立任務、執行工作並讀取結果",
+ "agentErrandDetail": "建立的任務會顯示在 Cindy 任務列表中,可查看過程並繼續交流。",
+ "agentSchedule": "可以請你新建自動化",
+ "agentScheduleDetail": "它只能為你開啟新建自動化的面板並把內容填好,是否建立由你在面板上選好模型後親手儲存決定。建立後由 Cindy 按你設定的時間執行,可能產生模型費用。",
+ "nodeRuntime": "可在本機執行隨插件附帶的 Node 程式",
+ "nodeMcp": "可在本機執行隨插件附帶的 stdio MCP",
+ "nodeRuntimeDetail": "高風險:它和你本人一樣,可以讀取或修改你帳號能訪問的本機檔案、訪問網路並啟動其它程式。Cindy 不能用瀏覽器沙箱限制它。",
+ "nodeSecret": "可將已儲存憑證「{{name}}」提供給本機 Node 程式",
+ "nodeSecretDetail": "Cindy 加密保管,僅在下列已宣告 Worker 方法執行時臨時注入。Node 程式會收到明文,也可以將其回傳、記錄、儲存或暴露給瀏覽器側插件程式碼及 Agent 引數;請只安裝可信插件。",
+ "nodeResident": "Node 程式可常駐後臺",
+ "nodeResidentDetail": "插件啟用期間會一直執行;停用、更新、解除安裝或退出 Cindy 時關閉。",
+ "tool": "工具「{{name}}」",
+ "command": "對話指令 ${{command}}",
+ "panelLeft": "面板「{{title}}」· 停靠主對話區左側",
+ "panelTab": "面板「{{title}}」· 插件頁內開啟",
+ "mainView": "可在 Cindy 側邊欄新增「{{title}}」入口",
+ "mainViewDetail": "點擊後將在插件沙箱中開啟主視圖,不會因此取得檔案、網路或憑證存取權限。",
+ "code": "可執行程式碼",
+ "codeDetail": "在獨立沙箱中執行,無法訪問你的檔案與網路。",
+ "resident": "常駐執行(生效後即啟動,不呼叫也保持後臺處理程序)",
+ "residentDetail": "空閒時也佔用少量記憶體;停用或解除安裝後進程立即關閉。",
+ "subscribeTopics": "旁聽你的任務動態(每輪往來與任務事件,不含訊息內容)",
+ "subscribeActivity": "旁聽 AI 何時在思考、何時在等你",
+ "subscribeActivityDetail": "只知道時機:思考何時開始與結束,以及 AI 何時在等你批准或等你回答。看不到思考內容、待批准的操作、涉及的命令與檔案、計劃正文、問題與你的答案,也無法代你批准。",
+ "subscribeHooks": "可讀取、攔截或改寫你發出的訊息",
+ "subscribeHooksDetail": "傳送前先經它審閱:可攔下訊息,也可能改寫正文後再發出;被攔的訊息可編輯後重發。",
+ "subscribeAssistantReply": "可讀取並重寫 AI 的回覆",
+ "subscribeAssistantReplyDetail": "AI 每輪迴復完成後先經它處理:可潤色改寫正文(直接替換,不留原文),或用自繪卡片替換回復氣泡(卡片替換時原文保留,可一鍵檢視)。",
+ "card": "渲染訊息卡片",
+ "cardExternalLink": "卡片內可宣告外鏈,經你確認後開啟瀏覽器",
+ "cardExternalLinkDetail": "卡片中的連結點選後會彈出確認框,你同意後才會在系統瀏覽器中開啟;僅限 http/https 地址。",
+ "notify": "可彈出系統提示(螢幕頂部的輕提示)",
+ "notifyDetail": "提示內容由這個插件提供,提示上會標註它的名字;自動消失,不會打斷你的操作。",
+ "badge": "可在插件入口點亮未讀提醒",
+ "badgeDetail": "有新內容時,它可以在側欄插件入口和自己的卡片上點亮一個綠點,並附一句話摘要;你開啟它的面板即清零。綠點不出聲、不震動,也不會進入系統通知中心,和上面的系統提示是兩項獨立權限。",
+ "confirm": "可彈出確認框徵求你同意",
+ "confirmDetail": "它動手前可以彈一個和 Cindy 同款的確認框來問你,問句由它提供、框上會標註它的名字;同意還是取消都由你親手點,它自己點不了。同時最多一個確認框,彈得太頻會被攔下。",
+ "fsWrite": "可寫入檔案(建立/修改)",
+ "fsWriteDetail": "它自己的專屬資料目錄隨時可寫;當前任務的工作目錄跟隨任務的權限模式(免批模式直接寫,逐條確認模式先徵求你同意);其它目錄每次都需要你確認。檔案始終由主機代寫,插件本身無法直接訪問你的檔案系統。",
+ "libraryPersist": "可使用持久作品庫(大量檔案與資料庫)",
+ "libraryPersistDetail": "它會取得一個由 Cindy 管理的獨立儲存區,用來保存你的作品資料(如畫布、圖片、資料庫),不受一般插件資料配額限制。檔案與資料庫操作全部由主機代執行,插件只能使用庫內相對路徑,無法觸碰你的其它檔案。它還可以讓 Cindy 在系統資料夾中顯示庫內檔案,或彈出系統另存為視窗由你選擇拷貝位置;取消則不會拷出任何檔案。它還可以把 PNG 點陣圖寫入系統剪貼簿;沒有確認框,會覆蓋目前剪貼簿內容。解除安裝插件不會刪除這些資料;刪除必須在 Cindy 設定中單獨確認。",
+ "networkHost": "訪問網路域名 {{host}}",
+ "networkSecret": "需要你提供憑證「{{name}}」",
+ "networkSecretGhostInputDetail": "憑證由這個插件自己的設定介面收集,錄入時會經過插件頁面;隨後一次性交給主機加密保管,存入後插件無法讀回,主機只在請求它宣告的域名時注入。",
+ "networkSecretIdentity": "將使用你的登入電子郵件作為憑證「{{name}}」",
+ "networkSecretIdentityDetail": "值取自當前登入帳號的電子郵件,請求時由主機自動派生注入;無需填寫。插件可讀取該電子郵件,用於在它的設定介面裡展示當前身份。",
+ "networkSecretGhCli": "將優先使用本機 GitHub CLI 登入作為憑證「{{name}}」",
+ "networkSecretGhCliDetail": "主機按需讀取本機 gh 登入令牌,並且只注入 GitHub API 請求;插件程式碼無法讀取或儲存令牌。若 gh 不可用,可在插件設定中配置備用 Personal Access Token。",
+ "networkSecretOrganizationIdentity": "將使用你的 Cindy 企業身份作為憑證「{{name}}」",
+ "networkSecretOrganizationIdentityDetail": "Cindy 會按需簽發短時身份斷言,僅由主機傳送給明確列出的服務域名;插件程式碼無法讀取或儲存令牌。",
+ "networkSecretOauth": "將引導你在 {{host}} 完成 OAuth 授權({{name}})",
+ "networkSecretOauthDetail": "授權流程與全部令牌由主機代管,插件程式碼無法讀取;客戶端憑證由你在本插件詳情頁自填。下方為其申請的權限範圍(scopes)原文,請確認後再放行。",
+ "networkConnections": "可連線你新增的 {{label}}",
+ "networkConnectionsDetail": "地址在這個插件的設定介面裡新增;每次新增地址都需要你確認,你提供的憑證只注入對應地址。",
+ "codeDetailNetwork": "在獨立沙箱中執行,無法訪問你的檔案;網路僅限上方宣告的域名,由主機代發。",
+ "codeDetailWithNode": "面板 UI 在獨立沙箱中執行;本地處理能力由上方宣告的 Node 執行時提供。",
+ "added": "新增",
+ "removed": "移除",
+ "updated": "更新",
+ "unchanged": "其餘 {{count}} 項權限不變",
+ "noChange": "權限無變化。",
+ "pick": "可請求你選擇一個資料夾交給它",
+ "pickDetail": "它發起請求時,Cindy 會彈出系統的選擇資料夾視窗;選哪個、給不給,都由你親手決定,取消則它什麼都拿不到。",
+ "workspace": "可請求為專案資料夾在側邊欄建立任務入口",
+ "workspaceDetail": "它發起請求時,由你親手選擇資料夾,或在確認卡上看到完整路徑後再決定;它正在處理你發起的呼叫時,當前任務工作目錄內的子資料夾可直接使用,不再單獨確認。資料夾已有任務時直接複用,不重複建立。建立的只是空任務,不會自動開始執行。",
+ "sessionContext": "可獲知當前任務正在使用的專案資料夾位置",
+ "sessionContextDetail": "只在它為當前任務幹活時告知位置資訊(任務編號與專案資料夾路徑),不包含檔案內容,也不因此獲得檔案訪問權。",
+ "preview": "可在右側欄瀏覽器中開啟以下網站的預覽頁面",
+ "previewDetail": "只能開啟下方列出的網站;每次開啟都會提示是哪個插件開啟的。",
+ "nodeChildSpawn": "Node 程式可請宿主再啟動包內申報過的子處理程序",
+ "nodeChildSpawnDetail": "只能啟動它自己包裡申報過的 JS 檔案(與主程式同樣的本機權限),不能執行任意命令;插件停用或退出時子處理程序一併關閉。",
+ "skill": "為 AI 助手新增技能「{{name}}」",
+ "skillDetail": "技能是一份指令檔案,AI 會把它當作自己的指令載入執行,擁有你的全部權限,對 Claude Code 與 Codex、所有專案都生效——不受本插件沙箱約束。插件啟用期間持續可用,停用或解除安裝即移除;僅對某個資料夾關閉本插件不會隱藏它。此處無法預覽技能全文——請只安裝你信任的插件。",
+ "routineEvents": "例行任務事件"
+ },
+ "releaseChanged": "可用版本已變更,請查看更新後的版本,再選擇安裝。",
+ "settingsUnavailable": "插件設定載入失敗,請重新載入設定後再試。",
+ "settingsResultUnknown": "尚未確認操作結果。請先重新讀取電腦上的設定,再決定是否提交。",
+ "settingsOperationFailed": "設定操作未能完成,請檢查連線後再試。",
+ "settingsReload": "重試"
+ },
+ "notice": {
+ "title": {
+ "offline": "電腦已離線",
+ "loadFailed": "插件載入失敗",
+ "retired": "功能已停用",
+ "approvalRequired": "安裝需要復原",
+ "builtinRecovery": "內建插件需要復原",
+ "fused": "插件已暫停",
+ "authorization": "授權需要處理",
+ "resultUnknown": "結果待確認",
+ "writeFailed": "設定操作未完成",
+ "readFailed": "設定讀取失敗",
+ "managementFailed": "操作失敗",
+ "confirmation": "確認插件權限"
+ },
+ "consentOrigin": {
+ "market": "官方市集",
+ "custom-market": "自訂市集",
+ "local-file": "本機檔案",
+ "forge": "本機建置"
+ },
+ "initiator": {
+ "user": "由你發起",
+ "agent": "由 Agent 發起"
+ },
+ "taskCapability": "用於目前任務"
+ }
}
diff --git a/apps/mobile/src/platform/chrome/SimpleStackHeader.tsx b/apps/mobile/src/platform/chrome/SimpleStackHeader.tsx
index d60e619865..fb8abdeab4 100644
--- a/apps/mobile/src/platform/chrome/SimpleStackHeader.tsx
+++ b/apps/mobile/src/platform/chrome/SimpleStackHeader.tsx
@@ -49,6 +49,7 @@ export const simpleScrollInsetProps = Platform.OS === "ios"
export function SimpleStackHeader({
action,
right,
+ rightToolbar,
backTestID,
onBack,
title,
@@ -58,6 +59,8 @@ export function SimpleStackHeader({
}: {
action?: MainWindowAction;
right?: ReactNode;
+ /** Native toolbar elements, rendered beside Stack.Screen rather than inside headerRight. */
+ rightToolbar?: ReactNode;
backTestID?: string;
/**
* @deprecated 两端都不渲染(iOS 系统顶栏无此槽,Android 跟随 iOS)。
@@ -117,6 +120,7 @@ export function SimpleStackHeader({
: undefined,
}}
/>
+ {rightToolbar}
{onBack ? <Stack.Toolbar placement="left">
<Stack.Toolbar.Button icon="chevron.backward" onPress={onBack} accessibilityLabel={t('shared.back')} />
</Stack.Toolbar> : null}
diff --git a/apps/mobile/src/plugins/PluginDetailView.ios.tsx b/apps/mobile/src/plugins/PluginDetailView.ios.tsx
index 0725663896..7428efe2fe 100644
--- a/apps/mobile/src/plugins/PluginDetailView.ios.tsx
+++ b/apps/mobile/src/plugins/PluginDetailView.ios.tsx
@@ -1,5 +1,9 @@
import {
Host,
+ Background,
+ Divider,
+ Rectangle,
+ ZStack,
List,
HStack,
Image as NativeImage,
@@ -10,10 +14,15 @@ import {
VStack,
Button,
ProgressView,
- DisclosureGroup,
- Divider,
} from "@expo/ui/swift-ui";
import {
+ Animation,
+ animation,
+ accessibilityHidden,
+ clipped,
+ fixedSize,
+ onGeometryChange,
+ rotationEffect,
background,
buttonStyle,
disabled,
@@ -42,43 +51,50 @@ import { useTranslation } from "react-i18next";
import { resolveRemoteText } from "@cindy/device-link";
import { ComposerNativeRow } from "@/session/ComposerNativeRow";
import { useNativeGlassButtonStyle } from "@/platform/chrome/nativeGlassButtonStyle.ios";
-import { iconSize, radius, spacing, useTheme } from "@/theme";
+import { iconSize, motionDuration, radius, spacing, useTheme } from "@/theme";
+import { useReduceMotionEnabled } from "@/hooks/useReduceMotion";
import type { PluginDetailViewProps } from "./PluginDetailView";
+import { useMobileKeyboardState } from "@/session/useMobileKeyboardState";
import { PluginToolChips } from "./PluginToolChips";
+import { PluginPermissionCard } from "./PluginPermissionCard";
+import { PluginNativeNotice } from "./PluginNotice.ios";
+import { pluginDetailNotices } from "./pluginDetailNotices";
export function PluginDetailView(p: PluginDetailViewProps) {
const { t, i18n } = useTranslation();
const { mode, colors } = useTheme();
+ const reduceMotion = useReduceMotionEnabled();
const { width, fontScale } = useWindowDimensions();
const primaryStyle = useNativeGlassButtonStyle({ prominent: true });
const secondaryStyle = useNativeGlassButtonStyle();
const text = (value: Parameters<typeof resolveRemoteText>[0]) =>
resolveRemoteText(value, i18n.language);
const { model } = p;
+ const facts = (model.details ?? []).filter((fact) => fact.value.trim());
+ if (model.version?.trim() && !facts.some((fact) => fact.key === "version")) {
+ facts.push({
+ key: "version",
+ title: t("plugins.detail.version"),
+ value: model.version,
+ });
+ }
+ const [factHeights, setFactHeights] = useState<Record<string, number>>({});
+ useEffect(() => setFactHeights({}), [p.row.key]);
+ const [expandedFacts, setExpandedFacts] = useState<Record<string, boolean>>(
+ {},
+ );
+ useEffect(() => setExpandedFacts({}), [p.row.key]);
+ const factsAnimation = Animation.easeInOut({
+ duration: reduceMotion === false ? motionDuration.base / 1000 : 0,
+ });
const [toolsExpanded, setToolsExpanded] = useState(false);
+ const [permissionsExpanded, setPermissionsExpanded] = useState(false);
const [toolsOverflow, setToolsOverflow] = useState(false);
const [hostWidth, setHostWidth] = useState(width);
- useEffect(() => setToolsExpanded(false), [p.row.key]);
- const detailFacts = (
- model.details ?? [
- ...(model.version
- ? [
- {
- key: "version",
- title: t("plugins.detail.version"),
- value: "v" + model.version,
- },
- ]
- : []),
- {
- key: "identifier",
- title: t("plugins.detail.identifier"),
- value: p.row.item.ref.id,
- },
- ]
- ).filter((fact) => fact.title.trim() && fact.value.trim());
+ useEffect(() => { setToolsExpanded(false); setPermissionsExpanded(false); }, [p.row.key]);
+ const { visible: keyboardVisible } = useMobileKeyboardState();
const uri = p.row.item.display.avatar?.value;
- const Actions = fontScale > 1.2 || width < 380 ? VStack : HStack;
+ const showActions = !p.settingsOpen && model.canUseTasks && !keyboardVisible;
const note = (value: string, id?: string) => (
<Text
testID={id}
@@ -110,7 +126,7 @@ export function PluginDetailView(p: PluginDetailViewProps) {
modifiers={[
font({ textStyle: "body", weight: "semibold" }),
foregroundStyle(prominent ? colors.ctaText : colors.textPrimary),
- frame({ maxWidth: Infinity, minHeight: 28 }),
+ frame({ maxWidth: Infinity, minHeight: 36 }),
padding({ horizontal: spacing.xs }),
]}
>
@@ -118,6 +134,17 @@ export function PluginDetailView(p: PluginDetailViewProps) {
</Text>
</Button>
);
+ const sectionTitle = (title: string) => (
+ <Text
+ modifiers={[
+ font({ textStyle: "title3", weight: "semibold" }),
+ foregroundStyle(colors.textPrimary),
+ frame({ maxWidth: Infinity, alignment: "leading" }),
+ ]}
+ >
+ {title}
+ </Text>
+ );
const chevron = (
<NativeImage
systemName="chevron.right"
@@ -125,44 +152,33 @@ export function PluginDetailView(p: PluginDetailViewProps) {
modifiers={[foregroundStyle(colors.textTertiary)]}
/>
);
- const statusKey =
- model.status === "approvalRequired" && model.builtin
- ? "builtinRecovery"
- : model.status === "setupRequired" &&
- !model.missing.length &&
- model.expired.length
- ? "setupExpired"
- : model.status;
- const status = model.status ? (
- <VStack
- alignment="leading"
- spacing={spacing.md}
- modifiers={[
- listRowSeparator("hidden"),
- padding({ vertical: spacing.sm }),
- ]}
- testID="plugins.status"
- >
- {model.status === "loading" ? <ProgressView /> : null}
- {note(t("plugins.detail.status." + statusKey))}
- {!p.settingsOpen && model.statusAction && model.statusAction !== "enable"
- ? button(
- t("plugins.detail.action." + model.statusAction),
- p.onResolveStatus,
- true,
- "plugins.resolveStatus",
- )
- : null}
+ const notices = pluginDetailNotices(model);
+ const status = notices.top ? (
+ <VStack modifiers={[listRowSeparator("hidden")]}>
+ <PluginNativeNotice
+ testID="plugins.status"
+ icon={notices.top === "offline" ? "offline" : "warning"}
+ title={t("plugins.notice.title." + notices.top)}
+ detail={["offline", "loadFailed"].includes(notices.top) ? undefined : t(
+ notices.top === "fused"
+ ? "plugins.detail.runtimeFused"
+ : "plugins.detail.status." + notices.top,
+ )}
+ actions={
+ model.statusAction &&
+ ["connect", "retry"].includes(model.statusAction)
+ ? [
+ {
+ label: t("plugins.detail.action." + model.statusAction),
+ onPress: p.onResolveStatus,
+ disabled: p.statusRecoveryBusy ?? p.busy,
+ testID: "plugins.resolveStatus",
+ },
+ ]
+ : undefined
+ }
+ />
</VStack>
- ) : model.runtimeIssue ? (
- note(
- t(
- model.runtimeIssue === "fused"
- ? "plugins.detail.runtimeFused"
- : "plugins.detail.runtimeIssue",
- ),
- "plugins.runtimeIssue",
- )
) : null;
return (
<Host
@@ -172,353 +188,504 @@ export function PluginDetailView(p: PluginDetailViewProps) {
style={styles.root}
ignoreSafeArea="container"
>
- <List
- key={p.settingsOpen ? "settings" : "detail"}
- modifiers={[
- listStyle("plain"),
- scrollContentBackground("hidden"),
- background(colors.surface),
- listRowSeparatorTint(colors.border),
- ]}
- testID={p.settingsOpen ? "plugins.settingsPage" : "plugins.detail"}
+ <ZStack
+ alignment="bottom"
+ modifiers={[frame({ maxWidth: Infinity, maxHeight: Infinity })]}
>
- <Section
+ <List
+ key={p.settingsOpen ? "settings" : "detail"}
modifiers={[
- listRowBackground(colors.surface),
- listRowInsets({
- leading: spacing.lg + spacing.xs,
- trailing: spacing.lg + spacing.xs,
- top: spacing.md,
- bottom: spacing.md,
- }),
+ listStyle("plain"),
+ scrollContentBackground("hidden"),
+ background(colors.surface),
+ listRowSeparatorTint(colors.border),
]}
+ testID={p.settingsOpen ? "plugins.settingsPage" : "plugins.detail"}
>
- {p.previewLabel ? (
- <VStack
- alignment="leading"
- modifiers={[listRowSeparator("hidden")]}
- >
- {note(p.previewLabel)}
- </VStack>
- ) : null}
- {!p.settingsOpen ? (
- <VStack
- alignment="leading"
- spacing={spacing.lg}
- modifiers={[
- listRowSeparator("hidden"),
- listRowInsets({
- leading: spacing.lg + spacing.xs,
- trailing: spacing.lg + spacing.xs,
- top: spacing.sm,
- bottom: spacing.lg,
- }),
- ]}
- testID="plugins.identity"
- >
- <HStack spacing={spacing.lg}>
- <RNHostView matchContents>
- {uri &&
- /^data:image\/(?:png|jpeg|webp|svg\+xml);base64,/.test(
- uri,
- ) ? (
- <Image source={{ uri }} style={styles.icon} />
- ) : (
- <View
- style={[
- styles.icon,
- styles.fallback,
- { backgroundColor: colors.surfaceChip },
- ]}
- >
- <Puzzle
- size={iconSize.xxl}
- color={colors.textSecondary}
- />
- </View>
- )}
- </RNHostView>
- <VStack
- alignment="leading"
- spacing={spacing.xs}
- modifiers={[
- frame({ maxWidth: Infinity, alignment: "leading" }),
- ]}
- >
- <HStack
- spacing={spacing.sm}
- modifiers={[frame({ maxWidth: Infinity })]}
- >
- <Text
- modifiers={[
- font({ textStyle: "title2", weight: "semibold" }),
- frame({ maxWidth: Infinity, alignment: "leading" }),
- ]}
- >
- {text(p.row.item.display.title)}
- </Text>
- <Toggle
- label={t("plugins.enabled")}
- isOn={p.enabled}
- onIsOnChange={p.onEnabledChange}
- modifiers={[
- labelsHidden(),
- frame({ width: 61, height: 28 }),
- scaleEffect({ x: 48 / 61, y: 24 / 28 }),
- frame({ width: 56, height: 44 }),
- contentShape(shapes.rectangle()),
- accessibilityLabel(t("plugins.enabled")),
- disabled(p.busy || !p.online || !model.canToggle),
- tint(colors.inputCaret),
- ]}
- testID="plugins.enabled"
- />
- </HStack>
- {note(p.row.host.deviceName)}
- </VStack>
- </HStack>
- {model.description || p.row.item.display.subtitle ? (
- <Text
- modifiers={[
- font({ textStyle: "subheadline" }),
- foregroundStyle(colors.textSecondary),
- lineLimit(3),
- ]}
- >
- {model.description || text(p.row.item.display.subtitle!)}
- </Text>
- ) : null}
- </VStack>
- ) : null}
- {p.settingsOpen && model.status === "setupRequired" ? null : status}
- {!p.settingsOpen && model.canUseTasks ? (
- <VStack
- alignment="leading"
- spacing={spacing.md}
- modifiers={[
- listRowSeparator("hidden"),
- // List cells clip the native glass shadow; reserve its tail inside this row.
- padding({ bottom: spacing.xl }),
- ]}
- testID="plugins.use"
- >
- <Text
- modifiers={[font({ textStyle: "title3", weight: "semibold" })]}
- testID="plugins.useHeading"
+ <Section
+ modifiers={[
+ listRowBackground(colors.surface),
+ listRowInsets({
+ leading: spacing.lg + spacing.xs,
+ trailing: spacing.lg + spacing.xs,
+ top: spacing.md,
+ bottom: spacing.md,
+ }),
+ ]}
+ >
+ {p.previewLabel ? (
+ <VStack
+ alignment="leading"
+ modifiers={[listRowSeparator("hidden")]}
>
- {t("plugins.detail.useItIn")}
- </Text>
- <Actions
- spacing={spacing.md}
- modifiers={[frame({ maxWidth: Infinity })]}
+ {note(p.previewLabel)}
+ </VStack>
+ ) : null}
+ {status}
+ {notices.loading ? (
+ <VStack
+ testID="plugins.loading"
+ modifiers={[
+ listRowSeparator("hidden"),
+ frame({ maxWidth: Infinity, alignment: "center" }),
+ ]}
>
- {button(
- t("plugins.newTask"),
- p.onNewTask,
- false,
- "plugins.newTask",
- )}
- {button(
- t("plugins.chooseTask"),
- p.onChooseTask,
- false,
- "plugins.chooseTask",
- )}
- </Actions>
- </VStack>
- ) : null}
- {!p.settingsOpen && model.mainSurface ? (
- <ComposerNativeRow
- title={t("plugins.detail.openPlugin")}
- accessory={chevron}
- disabled={p.busy || !p.online || !p.enabled || !model.canToggle}
- onPress={() => p.onOpen(model.mainSurface!)}
- testID="plugins.openPlugin"
- />
- ) : null}
- {model.tools?.length ? (
- <VStack
- alignment="leading"
- spacing={spacing.md}
- modifiers={[
- listRowSeparator("hidden"),
- ...(model.canUseTasks && !p.settingsOpen && !model.mainSurface
- ? [
- listRowInsets({
- leading: spacing.lg + spacing.xs,
- trailing: spacing.lg + spacing.xs,
- top: 0,
- bottom: spacing.md,
- }),
- ]
- : []),
- ]}
- testID="plugins.tools"
- >
- <HStack spacing={spacing.md}>
- <Text
- modifiers={[
- font({ textStyle: "title3", weight: "semibold" }),
- frame({ maxWidth: Infinity, alignment: "leading" }),
- ]}
- >
- {t("plugins.detail.tools") + " · " + model.tools.length}
- </Text>
- {toolsOverflow ? (
- <Button
- testID="plugins.toolsDisclosure"
- onPress={() => setToolsExpanded(!toolsExpanded)}
+ <ProgressView />
+ </VStack>
+ ) : null}
+ {!p.settingsOpen ? (
+ <VStack
+ alignment="leading"
+ spacing={spacing.lg}
+ modifiers={[
+ listRowSeparator("hidden"),
+ listRowInsets({
+ leading: spacing.lg + spacing.xs,
+ trailing: spacing.lg + spacing.xs,
+ top: spacing.sm,
+ bottom: spacing.lg,
+ }),
+ ]}
+ testID="plugins.identity"
+ >
+ <HStack spacing={spacing.lg}>
+ <VStack modifiers={[frame({ width: 72, height: 72 })]}>
+ <RNHostView matchContents>
+ <View collapsable={false} style={styles.icon}>
+ {uri &&
+ /^data:image\/(?:png|jpeg|webp|svg\+xml);base64,/.test(
+ uri,
+ ) ? (
+ <Image source={{ uri }} style={styles.icon} />
+ ) : (
+ <View
+ style={[
+ styles.icon,
+ styles.fallback,
+ { backgroundColor: colors.surfaceChip },
+ ]}
+ >
+ <Puzzle
+ size={iconSize.xxl}
+ color={colors.textSecondary}
+ />
+ </View>
+ )}
+ </View>
+ </RNHostView>
+ </VStack>
+ <VStack
+ alignment="leading"
+ spacing={spacing.xs}
modifiers={[
- buttonStyle("plain"),
- frame({ minWidth: 44, minHeight: 44 }),
- contentShape(shapes.rectangle()),
- accessibilityLabel(
- t(
- toolsExpanded
- ? "plugins.detail.showLess"
- : "plugins.detail.showAll",
- ),
- ),
+ frame({ maxWidth: Infinity, alignment: "leading" }),
]}
>
- <Text
- modifiers={[
- font({ textStyle: "body" }),
- foregroundStyle(colors.inputCaret),
- ]}
+ <HStack
+ spacing={spacing.sm}
+ modifiers={[frame({ maxWidth: Infinity })]}
>
- {t(
- toolsExpanded
- ? "plugins.detail.showLess"
- : "plugins.detail.showAll",
- )}
- </Text>
- </Button>
+ <Text
+ modifiers={[
+ font({ textStyle: "title2", weight: "semibold" }),
+ frame({ maxWidth: Infinity, alignment: "leading" }),
+ ]}
+ >
+ {text(p.row.item.display.title)}
+ </Text>
+ <Toggle
+ label={t("plugins.enabled")}
+ isOn={p.enabled}
+ onIsOnChange={p.onEnabledChange}
+ modifiers={[
+ labelsHidden(),
+ frame({ width: 61, height: 28 }),
+ scaleEffect({ x: 48 / 61, y: 24 / 28 }),
+ frame({ width: 56, height: 44 }),
+ contentShape(shapes.rectangle()),
+ accessibilityLabel(t("plugins.enabled")),
+ disabled(p.busy || !p.online || !model.canToggle),
+ tint(colors.inputCaret),
+ ]}
+ testID="plugins.enabled"
+ />
+ </HStack>
+ {note(p.row.host.deviceName)}
+ </VStack>
+ </HStack>
+ {model.description || p.row.item.display.subtitle ? (
+ <Text
+ modifiers={[
+ font({ textStyle: "subheadline" }),
+ foregroundStyle(colors.textSecondary),
+ lineLimit(3),
+ ]}
+ >
+ {model.description || text(p.row.item.display.subtitle!)}
+ </Text>
) : null}
- </HStack>
+ </VStack>
+ ) : null}
+ {p.settingsContent ? (
<VStack
alignment="leading"
- spacing={0}
- modifiers={[frame({ maxWidth: Infinity })]}
+ spacing={spacing.md}
+ modifiers={[listRowSeparator("hidden")]}
>
+ {sectionTitle(t("plugins.settings"))}
<RNHostView matchContents>
- <PluginToolChips
- key={
- p.row.key + model.tools.map((tool) => tool.name).join("|")
- }
- tools={model.tools}
- expanded={toolsExpanded}
- width={Math.max(
- 0,
- hostWidth - (spacing.lg + spacing.xs) * 2,
- )}
- onOverflowChange={setToolsOverflow}
- />
+ <View
+ collapsable={false}
+ style={[
+ styles.settings,
+ {
+ width: Math.max(
+ 0,
+ hostWidth - (spacing.lg + spacing.xs) * 2,
+ ),
+ },
+ ]}
+ testID="plugins.settingsCard"
+ >
+ {p.settingsContent}
+ </View>
</RNHostView>
</VStack>
- </VStack>
- ) : null}
- {model.permissions?.length ? (
- <VStack
- alignment="leading"
- spacing={spacing.md}
- modifiers={[listRowSeparator("hidden")]}
- testID="plugins.permissions"
- >
- <Text
- modifiers={[font({ textStyle: "title3", weight: "semibold" })]}
+ ) : null}
+ {!p.settingsOpen && model.mainSurface ? (
+ <ComposerNativeRow
+ title={t("plugins.detail.openPlugin")}
+ accessory={chevron}
+ disabled={p.busy || !p.online || !p.enabled || !model.canToggle}
+ onPress={() => p.onOpen(model.mainSurface!)}
+ testID="plugins.openPlugin"
+ />
+ ) : null}
+ {model.tools?.length ? (
+ <VStack
+ alignment="leading"
+ spacing={spacing.md}
+ modifiers={[listRowSeparator("hidden")]}
+ testID="plugins.tools"
>
- {t("plugins.detail.permissions")}
- </Text>
- {model.permissions?.map((permission, index) =>
- permission.description ? (
- <DisclosureGroup
- key={index}
- label={permission.title}
- modifiers={[tint(colors.textSecondary)]}
+ <HStack spacing={spacing.md}>
+ <Text
+ modifiers={[
+ font({ textStyle: "title3", weight: "semibold" }),
+ frame({ maxWidth: Infinity, alignment: "leading" }),
+ ]}
>
- {note(permission.description)}
- </DisclosureGroup>
- ) : (
- <Text key={index}>{permission.title}</Text>
- ),
- )}
- </VStack>
- ) : null}
- {detailFacts.length || model.hasSettings ? (
- <VStack
- alignment="leading"
- spacing={spacing.md}
- modifiers={[listRowSeparator("hidden")]}
- testID="plugins.metadata"
- >
- <Text
- modifiers={[font({ textStyle: "title3", weight: "semibold" })]}
- >
- {t("plugins.detail.details")}
- </Text>
- {detailFacts.map((fact, index) => (
- <VStack
- key={fact.key}
- alignment="leading"
- spacing={spacing.md}
- modifiers={[
- frame({ maxWidth: Infinity, alignment: "leading" }),
- ]}
- >
- {fact.key === "contents" || fact.key === "location" ? (
- <VStack
- key={fact.key}
- alignment="leading"
- spacing={spacing.xs}
- testID={"plugins.fact." + fact.key}
+ {t("plugins.detail.tools") + " · " + model.tools.length}
+ </Text>
+ {toolsOverflow ? (
+ <Button
+ testID="plugins.toolsDisclosure"
+ onPress={() => setToolsExpanded(!toolsExpanded)}
+ modifiers={[
+ buttonStyle("plain"),
+ frame({ minWidth: 44, minHeight: 44 }),
+ contentShape(shapes.rectangle()),
+ accessibilityLabel(
+ t(
+ toolsExpanded
+ ? "plugins.detail.showLess"
+ : "plugins.detail.showAll",
+ ),
+ ),
+ ]}
>
- {note(fact.title)}
<Text
modifiers={[
- font({
- textStyle:
- fact.key === "location" ? "footnote" : "body",
- }),
+ font({ textStyle: "body" }),
+ foregroundStyle(colors.inputCaret),
]}
>
- {fact.value}
+ {t(
+ toolsExpanded
+ ? "plugins.detail.showLess"
+ : "plugins.detail.showAll",
+ )}
</Text>
- </VStack>
- ) : (
- <HStack
- key={fact.key}
- spacing={spacing.md}
- testID={"plugins.fact." + fact.key}
- >
- {note(fact.title)}
- <Text
+ </Button>
+ ) : null}
+ </HStack>
+ <VStack
+ alignment="leading"
+ spacing={0}
+ modifiers={[frame({ maxWidth: Infinity })]}
+ >
+ <RNHostView matchContents>
+ <PluginToolChips
+ key={
+ p.row.key +
+ model.tools.map((tool) => tool.name).join("|")
+ }
+ tools={model.tools}
+ expanded={toolsExpanded}
+ width={Math.max(
+ 0,
+ hostWidth - (spacing.lg + spacing.xs) * 2,
+ )}
+ onOverflowChange={setToolsOverflow}
+ />
+ </RNHostView>
+ </VStack>
+ </VStack>
+ ) : null}
+ {model.permissions?.length ? (
+ <VStack alignment="leading" spacing={spacing.md}
+ modifiers={[listRowSeparator("hidden"), animation(factsAnimation, permissionsExpanded)]}>
+ <HStack alignment="center" spacing={spacing.sm}>
+ {sectionTitle(t("plugins.detail.permissions"))}
+ {model.permissions.length > 4 ? <Button
+ testID="plugins.permissionsDisclosure"
+ label={t(permissionsExpanded ? "plugins.collapseFields" : "plugins.expandFields")}
+ onPress={() => setPermissionsExpanded(!permissionsExpanded)}
+ modifiers={[buttonStyle("plain"), font({ textStyle: "subheadline" }), foregroundStyle(colors.inputCaret), frame({ minWidth: 44, minHeight: 44 }), contentShape(shapes.rectangle())]}
+ /> : null}
+ </HStack>
+ <RNHostView matchContents>
+ <PluginPermissionCard
+ permissions={permissionsExpanded ? model.permissions : model.permissions.slice(0, 4)}
+ showHeading={false}
+ width={Math.max(0, hostWidth - (spacing.lg + spacing.xs) * 2)}
+ />
+ </RNHostView>
+ </VStack>
+ ) : null}
+ {facts.length ? (
+ <VStack
+ alignment="leading"
+ spacing={spacing.md}
+ testID="plugins.metadata"
+ modifiers={[
+ listRowSeparator("hidden"),
+ fixedSize({ horizontal: false, vertical: true }),
+ frame({ maxWidth: Infinity, alignment: "topLeading" }),
+ animation(
+ factsAnimation,
+ (expandedFacts.contents ? 1 : 0) |
+ (expandedFacts.location ? 2 : 0),
+ ),
+ ]}
+ >
+ {sectionTitle(t("plugins.detail.details"))}
+ <VStack alignment="leading" spacing={0}>
+ {facts.map((fact, index) => {
+ const expandable =
+ fact.key === "contents" || fact.key === "location";
+ const summary =
+ fact.key === "location"
+ ? fact.value
+ .replace(/[\\/]+$/, "")
+ .split(/[\\/]/)
+ .pop() || fact.value
+ : fact.key === "contents" && fact.value.includes(" · ")
+ ? fact.value.split(" · ")[0] + "…"
+ : fact.value;
+ const label = (
+ <HStack
+ spacing={spacing.lg}
modifiers={[
- font({ textStyle: "body" }),
- frame({ maxWidth: Infinity, alignment: "trailing" }),
+ frame({ maxWidth: Infinity, minHeight: 50 }),
]}
>
- {fact.value}
- </Text>
- </HStack>
- )}
- {index < detailFacts.length - 1 ? <Divider /> : null}
- </VStack>
- ))}
- {model.hasSettings ? (
- <VStack alignment="leading" testID="plugins.computerSettings">
- {note(t("plugins.detail.computerSettings"))}
+ <Text
+ modifiers={[
+ font({ textStyle: "subheadline" }),
+ foregroundStyle(colors.textSecondary),
+ lineLimit(1),
+ ]}
+ >
+ {fact.title}
+ </Text>
+ <Text
+ modifiers={[
+ font({ textStyle: "subheadline" }),
+ foregroundStyle(colors.textPrimary),
+ lineLimit(1),
+ frame({
+ maxWidth: Infinity,
+ alignment: "trailing",
+ }),
+ ]}
+ >
+ {summary}
+ </Text>
+ </HStack>
+ );
+ return (
+ <VStack
+ key={p.row.key + ":" + fact.key}
+ alignment="leading"
+ spacing={0}
+ >
+ {expandable ? (
+ <VStack
+ testID={"plugins.fact." + fact.key}
+ alignment="leading"
+ spacing={0}
+ >
+ <Button
+ testID={"plugins.fact." + fact.key + ".toggle"}
+ onPress={() =>
+ setExpandedFacts((current) => ({
+ ...current,
+ [fact.key]: !current[fact.key],
+ }))
+ }
+ modifiers={[
+ buttonStyle("plain"),
+ contentShape(shapes.rectangle()),
+ ]}
+ >
+ <HStack
+ spacing={spacing.sm}
+ modifiers={[
+ fixedSize({
+ horizontal: false,
+ vertical: true,
+ }),
+ ]}
+ >
+ {label}
+ <NativeImage
+ systemName="chevron.down"
+ size={iconSize.xs}
+ modifiers={[
+ foregroundStyle(colors.textSecondary),
+ rotationEffect(
+ expandedFacts[fact.key] ? 180 : 0,
+ ),
+ ]}
+ />
+ </HStack>
+ </Button>
+ <VStack
+ testID={"plugins.fact." + fact.key + ".content"}
+ alignment="leading"
+ spacing={0}
+ modifiers={[
+ fixedSize({
+ horizontal: false,
+ vertical: true,
+ }),
+ frame({
+ height: expandedFacts[fact.key]
+ ? (factHeights[fact.key] ?? 0)
+ : 0,
+ alignment: "topLeading",
+ }),
+ clipped(),
+ accessibilityHidden(!expandedFacts[fact.key]),
+ ]}
+ >
+ <Text
+ testID={"plugins.fact." + fact.key + ".value"}
+ modifiers={[
+ font({ textStyle: "subheadline" }),
+ foregroundStyle(colors.textPrimary),
+ frame({
+ maxWidth: Infinity,
+ alignment: "leading",
+ }),
+ fixedSize({
+ horizontal: false,
+ vertical: true,
+ }),
+ padding({ bottom: spacing.md }),
+ onGeometryChange(({ height }) => {
+ if (height > 0)
+ setFactHeights((current) =>
+ current[fact.key] === height
+ ? current
+ : { ...current, [fact.key]: height },
+ );
+ }),
+ ]}
+ >
+ {fact.value}
+ </Text>
+ </VStack>
+ </VStack>
+ ) : (
+ <VStack testID={"plugins.fact." + fact.key}>
+ {label}
+ </VStack>
+ )}
+ {index < facts.length - 1 ? <Divider /> : null}
+ </VStack>
+ );
+ })}
</VStack>
- ) : null}
+ </VStack>
+ ) : null}
+ {showActions ? (
+ <Rectangle
+ modifiers={[
+ foregroundStyle("clear"),
+ frame({ height: 180 * Math.max(1, fontScale) }),
+ listRowSeparator("hidden"),
+ ]}
+ />
+ ) : null}
+ </Section>
+ </List>
+ {showActions ? (
+ <Background>
+ <VStack
+ alignment="leading"
+ spacing={spacing.md}
+ modifiers={[
+ padding({
+ horizontal: spacing.lg + spacing.xs,
+ top: spacing.xl,
+ bottom: spacing.md,
+ }),
+ ]}
+ testID="plugins.use"
+ >
+ {button(
+ t("plugins.newTask"),
+ p.onNewTask,
+ true,
+ "plugins.newTask",
+ )}
+ {button(
+ t("plugins.chooseTask"),
+ p.onChooseTask,
+ false,
+ "plugins.chooseTask",
+ )}
</VStack>
- ) : null}
- </Section>
- </List>
+ <Background.Content>
+ <Rectangle
+ modifiers={[
+ foregroundStyle({
+ type: "linearGradient",
+ colors: [
+ "transparent",
+ colors.surface,
+ colors.surface,
+ colors.surface,
+ ],
+ startPoint: { x: 0.5, y: 0 },
+ endPoint: { x: 0.5, y: 1 },
+ }),
+ ]}
+ />
+ </Background.Content>
+ </Background>
+ ) : null}
+ </ZStack>
</Host>
);
}
const styles = StyleSheet.create({
root: { flex: 1 },
+ settings: {
+ minHeight: 44,
+ },
icon: { width: 72, height: 72, borderRadius: radius.container },
fallback: { alignItems: "center", justifyContent: "center" },
});
diff --git a/apps/mobile/src/plugins/PluginDetailView.tsx b/apps/mobile/src/plugins/PluginDetailView.tsx
index 5edb5a904b..6ee65ec225 100644
--- a/apps/mobile/src/plugins/PluginDetailView.tsx
+++ b/apps/mobile/src/plugins/PluginDetailView.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from "react";
+import { useEffect, useState, type ReactNode } from "react";
import {
Image,
Pressable,
@@ -6,7 +6,6 @@ import {
StyleSheet,
View,
ActivityIndicator,
- useWindowDimensions,
} from "react-native";
import { useTranslation } from "react-i18next";
import { resolveRemoteText } from "@cindy/device-link";
@@ -27,77 +26,49 @@ import {
import type { PluginPageSurface } from "@cindy/device-link";
import type { HostedRemoteCollectionItem } from "@/device-link/remoteResources";
import type { PluginDetailModel } from "./pluginDetailModel";
+import { useMobileKeyboardState } from "@/session/useMobileKeyboardState";
+import { PluginPermissionCard } from "./PluginPermissionCard";
import { PluginToolChips } from "./PluginToolChips";
+import { PluginNotice } from "./PluginNotice";
+import { pluginDetailNotices } from "./pluginDetailNotices";
export interface PluginDetailViewProps {
row: HostedRemoteCollectionItem;
enabled: boolean;
busy: boolean;
+ /** Navigation/read recovery may remain available during a pending management transaction. */
+ statusRecoveryBusy?: boolean;
online: boolean;
model: PluginDetailModel;
settingsOpen: boolean;
previewLabel?: string;
+ settingsContent?: ReactNode;
onEnabledChange(enabled: boolean): void;
onOpen(surface: PluginPageSurface): void;
onNewTask(): void;
onChooseTask(): void;
- onSettings(): void;
onResolveStatus(): void;
}
-function InformationRow({
- title,
- description,
-}: {
- title: string;
- description: string;
-}) {
- const [expanded, setExpanded] = useState(false);
- const styles = useThemedStyles(makeStyles);
- return (
- <View>
- <Pressable
- accessibilityRole="button"
- accessibilityState={{ expanded }}
- onPress={() => setExpanded(!expanded)}
- style={styles.informationRow}
- >
- <Text style={styles.rowText}>{title}</Text>
- <Text style={styles.note}>{expanded ? "−" : "+"}</Text>
- </Pressable>
- {expanded ? <Text style={styles.note}>{description}</Text> : null}
- </View>
- );
-}
-
/** Android shares the page hierarchy and Host facts, with its platform Switch. */
export function PluginDetailView(p: PluginDetailViewProps) {
const { t, i18n } = useTranslation(),
{ colors } = useTheme();
const styles = useThemedStyles(makeStyles);
- const { width, fontScale } = useWindowDimensions();
const { model } = p;
+ const facts = (model.details ?? []).filter((fact) => fact.value.trim());
+ if (model.version?.trim() && !facts.some((fact) => fact.key === "version")) {
+ facts.push({
+ key: "version",
+ title: t("plugins.detail.version"),
+ value: model.version,
+ });
+ }
const [toolsExpanded, setToolsExpanded] = useState(false);
+ const [permissionsExpanded, setPermissionsExpanded] = useState(false);
const [toolsOverflow, setToolsOverflow] = useState(false);
- useEffect(() => setToolsExpanded(false), [p.row.key]);
- const detailFacts = (
- model.details ?? [
- ...(model.version
- ? [
- {
- key: "version",
- title: t("plugins.detail.version"),
- value: "v" + model.version,
- },
- ]
- : []),
- {
- key: "identifier",
- title: t("plugins.detail.identifier"),
- value: p.row.item.ref.id,
- },
- ]
- ).filter((fact) => fact.title.trim() && fact.value.trim());
+ useEffect(() => { setToolsExpanded(false); setPermissionsExpanded(false); }, [p.row.key]);
+ const { visible: keyboardVisible } = useMobileKeyboardState();
const text = (value: Parameters<typeof resolveRemoteText>[0]) =>
resolveRemoteText(value, i18n.language);
const uri = p.row.item.display.avatar?.value;
@@ -141,97 +112,171 @@ export function PluginDetailView(p: PluginDetailViewProps) {
<ChevronRight size={iconSize.md} color={colors.textTertiary} />
</Pressable>
);
- const statusKey =
- model.status === "approvalRequired" && model.builtin
- ? "builtinRecovery"
- : model.status === "setupRequired" &&
- !model.missing.length &&
- model.expired.length
- ? "setupExpired"
- : model.status;
+ const notices = pluginDetailNotices(model);
return (
- <ScrollView
- testID={p.settingsOpen ? "plugins.settingsPage" : "plugins.detail"}
- contentContainerStyle={styles.content}
- >
- {p.previewLabel ? note(p.previewLabel) : null}
- {!p.settingsOpen ? (
- <View style={styles.identity}>
- <View style={styles.hero}>
- {uri &&
- /^data:image\/(?:png|jpeg|webp|svg\+xml);base64,/.test(uri) ? (
- <Image source={{ uri }} style={styles.icon} />
- ) : (
- <View style={[styles.icon, styles.fallback]}>
- <Puzzle size={iconSize.xxl} color={colors.textSecondary} />
- </View>
+ <View style={styles.root}>
+ <ScrollView
+ keyboardShouldPersistTaps="handled"
+ testID={p.settingsOpen ? "plugins.settingsPage" : "plugins.detail"}
+ contentContainerStyle={styles.content}
+ >
+ {p.previewLabel ? note(p.previewLabel) : null}
+ {notices.top ? (
+ <PluginNotice
+ testID="plugins.status"
+ icon={notices.top === "offline" ? "offline" : "warning"}
+ title={t("plugins.notice.title." + notices.top)}
+ detail={["offline", "loadFailed"].includes(notices.top) ? undefined : t(
+ notices.top === "fused"
+ ? "plugins.detail.runtimeFused"
+ : "plugins.detail.status." + notices.top,
)}
- <View style={styles.identityText}>
- <View style={styles.titleRow}>
- <Text style={[styles.title, styles.titleText]}>
- {text(p.row.item.display.title)}
- </Text>
- <NativeSwitch
- testID="plugins.enabled"
- accessibilityLabel={t("plugins.enabled")}
- value={p.enabled}
- disabled={p.busy || !p.online || !model.canToggle}
- onValueChange={p.onEnabledChange}
- />
+ actions={
+ model.statusAction &&
+ ["connect", "retry"].includes(model.statusAction)
+ ? [
+ {
+ label: t("plugins.detail.action." + model.statusAction),
+ onPress: p.onResolveStatus,
+ disabled: p.statusRecoveryBusy ?? p.busy,
+ testID: "plugins.resolveStatus",
+ },
+ ]
+ : undefined
+ }
+ />
+ ) : null}
+ {notices.loading ? (
+ <ActivityIndicator
+ testID="plugins.loading"
+ color={colors.textSecondary}
+ />
+ ) : null}
+ {!p.settingsOpen ? (
+ <View style={styles.identity}>
+ <View style={styles.hero}>
+ {uri &&
+ /^data:image\/(?:png|jpeg|webp|svg\+xml);base64,/.test(uri) ? (
+ <Image source={{ uri }} style={styles.icon} />
+ ) : (
+ <View style={[styles.icon, styles.fallback]}>
+ <Puzzle size={iconSize.xxl} color={colors.textSecondary} />
+ </View>
+ )}
+ <View style={styles.identityText}>
+ <View style={styles.titleRow}>
+ <Text style={[styles.title, styles.titleText]}>
+ {text(p.row.item.display.title)}
+ </Text>
+ <NativeSwitch
+ testID="plugins.enabled"
+ accessibilityLabel={t("plugins.enabled")}
+ value={p.enabled}
+ disabled={p.busy || !p.online || !model.canToggle}
+ onValueChange={p.onEnabledChange}
+ />
+ </View>
+ {note(p.row.host.deviceName)}
</View>
- {note(p.row.host.deviceName)}
</View>
+ {model.description || p.row.item.display.subtitle ? (
+ <Text numberOfLines={3} style={styles.note}>
+ {model.description || text(p.row.item.display.subtitle!)}
+ </Text>
+ ) : null}
</View>
- {model.description || p.row.item.display.subtitle ? (
- <Text numberOfLines={3} style={styles.note}>
- {model.description || text(p.row.item.display.subtitle!)}
+ ) : null}
+ {p.settingsContent ? (
+ <View style={styles.information}>
+ <Text style={styles.sectionHeading}>{t("plugins.settings")}</Text>
+ <View testID="plugins.settingsCard">
+ {p.settingsContent}
+ </View>
+ </View>
+ ) : null}
+ {!p.settingsOpen && model.mainSurface
+ ? row(
+ t("plugins.detail.openPlugin"),
+ () => p.onOpen(model.mainSurface!),
+ p.busy || !p.online || !p.enabled || !model.canToggle,
+ "plugins.openPlugin",
+ )
+ : null}
+ {model.tools?.length ? (
+ <View style={styles.information} testID="plugins.tools">
+ <View style={styles.titleRow}>
+ <Text style={[styles.sectionHeading, styles.titleText]}>
+ {t("plugins.detail.tools") + " · " + model.tools.length}
+ </Text>
+ {toolsOverflow ? (
+ <Pressable
+ testID="plugins.toolsDisclosure"
+ accessibilityRole="button"
+ accessibilityState={{ expanded: toolsExpanded }}
+ onPress={() => setToolsExpanded(!toolsExpanded)}
+ style={styles.toolsToggle}
+ >
+ <Text style={styles.toolsToggleText}>
+ {t(
+ toolsExpanded
+ ? "plugins.detail.showLess"
+ : "plugins.detail.showAll",
+ )}
+ </Text>
+ </Pressable>
+ ) : null}
+ </View>
+ <PluginToolChips
+ key={p.row.key + model.tools.map((tool) => tool.name).join("|")}
+ tools={model.tools}
+ expanded={toolsExpanded}
+ onOverflowChange={setToolsOverflow}
+ />
+ </View>
+ ) : null}
+ {model.permissions?.length ? (
+ <View style={styles.information}>
+ <View style={styles.titleRow}>
+ <Text style={[styles.sectionHeading, styles.titleText]}>{t("plugins.detail.permissions")}</Text>
+ {model.permissions.length > 4 ? <Pressable
+ testID="plugins.permissionsDisclosure" accessibilityRole="button"
+ accessibilityState={{ expanded: permissionsExpanded }}
+ onPress={() => setPermissionsExpanded(!permissionsExpanded)} style={styles.toolsToggle}>
+ <Text style={styles.toolsToggleText}>{t(permissionsExpanded ? "plugins.collapseFields" : "plugins.expandFields")}</Text>
+ </Pressable> : null}
+ </View>
+ <PluginPermissionCard
+ permissions={permissionsExpanded ? model.permissions : model.permissions.slice(0, 4)}
+ showHeading={false}
+ />
+ </View>
+ ) : null}
+ {facts.length ? (
+ <View style={styles.information} testID="plugins.metadata">
+ <Text style={styles.sectionHeading}>
+ {t("plugins.detail.details")}
</Text>
- ) : null}
- </View>
- ) : null}
- {model.status && !(p.settingsOpen && model.status === "setupRequired") ? (
- <View testID="plugins.status" style={styles.status}>
- {model.status === "loading" ? (
- <ActivityIndicator color={colors.textSecondary} />
- ) : null}
- {note(t("plugins.detail.status." + statusKey))}
- {!p.settingsOpen &&
- model.statusAction &&
- model.statusAction !== "enable"
- ? button(
- t("plugins.detail.action." + model.statusAction),
- p.onResolveStatus,
- true,
- "plugins.resolveStatus",
- )
- : null}
- </View>
- ) : model.runtimeIssue ? (
- note(
- t(
- model.runtimeIssue === "fused"
- ? "plugins.detail.runtimeFused"
- : "plugins.detail.runtimeIssue",
- ),
- )
- ) : null}
- {!p.settingsOpen && model.canUseTasks ? (
- <View style={styles.use}>
- <Text style={styles.sectionHeading} testID="plugins.useHeading">
- {t("plugins.detail.useItIn")}
- </Text>
- <View
- style={[
- styles.actions,
- (fontScale > 1.2 || width < 380) && styles.verticalActions,
- ]}
- >
- {button(
- t("plugins.newTask"),
- p.onNewTask,
- false,
- "plugins.newTask",
- )}
+ {facts.map((fact) => (
+ <View
+ key={fact.key}
+ style={styles.metadataRow}
+ testID={"plugins.fact." + fact.key}
+ >
+ {note(fact.title)}
+ <Text
+ style={[styles.note, styles.titleText, styles.metadataValue]}
+ >
+ {fact.value}
+ </Text>
+ </View>
+ ))}
+ </View>
+ ) : null}
+ </ScrollView>
+ {!p.settingsOpen && model.canUseTasks && !keyboardVisible ? (
+ <View style={styles.use} testID="plugins.use">
+ <View style={[styles.actions, styles.verticalActions]}>
+ {button(t("plugins.newTask"), p.onNewTask, true, "plugins.newTask")}
{button(
t("plugins.chooseTask"),
p.onChooseTask,
@@ -241,112 +286,12 @@ export function PluginDetailView(p: PluginDetailViewProps) {
</View>
</View>
) : null}
- {!p.settingsOpen && model.mainSurface
- ? row(
- t("plugins.detail.openPlugin"),
- () => p.onOpen(model.mainSurface!),
- p.busy || !p.online || !p.enabled || !model.canToggle,
- "plugins.openPlugin",
- )
- : null}
- {model.tools?.length ? (
- <View style={styles.information} testID="plugins.tools">
- <View style={styles.titleRow}>
- <Text style={[styles.sectionHeading, styles.titleText]}>
- {t("plugins.detail.tools") + " · " + model.tools.length}
- </Text>
- {toolsOverflow ? (
- <Pressable
- testID="plugins.toolsDisclosure"
- accessibilityRole="button"
- accessibilityState={{ expanded: toolsExpanded }}
- onPress={() => setToolsExpanded(!toolsExpanded)}
- style={styles.toolsToggle}
- >
- <Text style={styles.toolsToggleText}>
- {t(
- toolsExpanded
- ? "plugins.detail.showLess"
- : "plugins.detail.showAll",
- )}
- </Text>
- </Pressable>
- ) : null}
- </View>
- <PluginToolChips
- key={p.row.key + model.tools.map((tool) => tool.name).join("|")}
- tools={model.tools}
- expanded={toolsExpanded}
- onOverflowChange={setToolsOverflow}
- />
- </View>
- ) : null}
- {model.permissions?.length ? (
- <View style={styles.information} testID="plugins.permissions">
- <Text style={styles.sectionHeading}>
- {t("plugins.detail.permissions")}
- </Text>
- {model.permissions?.map((permission, index) =>
- permission.description ? (
- <InformationRow
- key={index}
- title={permission.title}
- description={permission.description}
- />
- ) : (
- <Text key={index} style={styles.rowText}>
- {permission.title}
- </Text>
- ),
- )}
- </View>
- ) : null}
- {detailFacts.length || model.hasSettings ? (
- <View style={styles.information} testID="plugins.metadata">
- <Text style={styles.sectionHeading}>
- {t("plugins.detail.details")}
- </Text>
- {detailFacts.map((fact, index) => (
- <View
- key={fact.key}
- testID={"plugins.fact." + fact.key}
- style={
- fact.key === "contents" || fact.key === "location"
- ? [
- styles.toolDescription,
- index < detailFacts.length - 1 && styles.factSeparator,
- ]
- : [
- styles.metadataRow,
- index < detailFacts.length - 1 && styles.factSeparator,
- ]
- }
- >
- {note(fact.title)}
- <Text
- style={[
- styles.rowText,
- fact.key !== "contents" &&
- fact.key !== "location" &&
- styles.metadataValue,
- ]}
- >
- {fact.value}
- </Text>
- </View>
- ))}
- {model.hasSettings ? (
- <View testID="plugins.computerSettings">
- {note(t("plugins.detail.computerSettings"))}
- </View>
- ) : null}
- </View>
- ) : null}
- </ScrollView>
+ </View>
);
}
const makeStyles = (c: ThemeColors) =>
StyleSheet.create({
+ root: { flex: 1 },
content: {
paddingHorizontal: spacing.lg + spacing.xs,
paddingVertical: spacing.lg,
@@ -376,19 +321,19 @@ const makeStyles = (c: ThemeColors) =>
lineHeight: lineHeight.bodySmall,
color: c.textSecondary,
},
- status: { gap: spacing.md, paddingVertical: spacing.lg },
- use: { gap: spacing.md, paddingBottom: spacing.lg },
+ use: {
+ paddingHorizontal: spacing.lg + spacing.xs,
+ paddingVertical: spacing.md,
+ backgroundColor: c.surface,
+ borderTopWidth: StyleSheet.hairlineWidth,
+ borderTopColor: c.border,
+ },
titleRow: { flexDirection: "row", alignItems: "center", gap: spacing.sm },
titleText: { flex: 1 },
information: {
gap: spacing.md,
paddingVertical: spacing.lg,
},
- factSeparator: {
- borderBottomWidth: StyleSheet.hairlineWidth,
- borderBottomColor: c.border,
- paddingBottom: spacing.md,
- },
toolsToggle: {
minWidth: 44,
minHeight: 44,
@@ -400,13 +345,6 @@ const makeStyles = (c: ThemeColors) =>
lineHeight: lineHeight.body,
color: c.inputCaret,
},
- informationRow: {
- flexDirection: "row",
- alignItems: "center",
- minHeight: 44,
- gap: spacing.sm,
- },
- toolDescription: { gap: spacing.xs },
metadataValue: { textAlign: "right" },
metadataRow: {
flexDirection: "row",
diff --git a/apps/mobile/src/plugins/PluginManagementConfirmation.ios.tsx b/apps/mobile/src/plugins/PluginManagementConfirmation.ios.tsx
new file mode 100644
index 0000000000..dfbeeb538a
--- /dev/null
+++ b/apps/mobile/src/plugins/PluginManagementConfirmation.ios.tsx
@@ -0,0 +1,111 @@
+import { Button, Text, VStack, HStack } from "@expo/ui/swift-ui";
+import {
+ buttonStyle,
+ disabled,
+ fixedSize,
+ font,
+ foregroundStyle,
+ frame,
+ padding,
+ tint,
+} from "@expo/ui/swift-ui/modifiers";
+import { useTranslation } from "react-i18next";
+import { ComposerSheet } from "@/session/ComposerSheet";
+import { spacing, useTheme } from "@/theme";
+import {
+ usePluginConsent,
+ type PluginManagementConfirmationProps,
+} from "./usePluginConsent";
+import { pluginConsentPresentation } from "./pluginConsentPresentation";
+export function PluginManagementConfirmation(
+ props: PluginManagementConfirmationProps,
+) {
+ const { t } = useTranslation(),
+ { colors } = useTheme();
+ const { consent, visible, answer } = usePluginConsent(props);
+ const info = consent ? pluginConsentPresentation(consent, t) : undefined;
+ const body = (text?: string) =>
+ text ? (
+ <Text
+ modifiers={[
+ font({ textStyle: "footnote" }),
+ foregroundStyle(colors.textSecondary),
+ fixedSize({ horizontal: false, vertical: true }),
+ ]}
+ >
+ {text}
+ </Text>
+ ) : null;
+ return (
+ <ComposerSheet
+ visible={visible}
+ onClose={() => answer(false)}
+ title={t("plugins.notice.title.confirmation")}
+ nativeContent
+ testID="plugins.managementConfirmation"
+ footer={
+ <HStack spacing={spacing.md}>
+ {[false, true].map((accept) => (
+ <Button
+ key={String(accept)}
+ testID={"plugins.management." + (accept ? "allow" : "reject")}
+ onPress={() => answer(accept)}
+ modifiers={[
+ buttonStyle(accept ? "borderedProminent" : "bordered"),
+ ...(accept ? [tint(colors.cta), foregroundStyle(colors.ctaText)] : []),
+ disabled(
+ !props.active || props.state.busy || !props.state.online,
+ ),
+ frame({ maxWidth: Infinity, minHeight: 44 }),
+ ]}
+ >
+ <Text
+ modifiers={[
+ font({ textStyle: "subheadline", weight: "medium" }),
+ ...(accept ? [foregroundStyle(colors.ctaText)] : []),
+ ]}
+ >
+ {t("plugins.management." + (accept ? "allow" : "reject"))}
+ </Text>
+ </Button>
+ ))}
+ </HStack>
+ }
+ >
+ <VStack
+ alignment="leading"
+ spacing={spacing.md}
+ modifiers={[padding({ vertical: spacing.sm })]}
+ >
+ <Text
+ modifiers={[
+ font({ textStyle: "headline" }),
+ foregroundStyle(colors.textPrimary),
+ ]}
+ >
+ {info?.title ?? ""}
+ </Text>
+ {body(props.deviceName)}
+ {body(info?.identity)}
+ {body(info?.origin)}
+ {body(info?.version)}
+ {info?.permissions.map((permission, index) => (
+ <VStack key={index} alignment="leading" spacing={spacing.xs}>
+ <Text
+ modifiers={[
+ font({ textStyle: "subheadline", weight: "medium" }),
+ foregroundStyle(colors.textPrimary),
+ fixedSize({ horizontal: false, vertical: true }),
+ ]}
+ >
+ {permission.title}
+ </Text>
+ {body(permission.detail)}
+ </VStack>
+ ))}
+ {body(info?.unchanged)}
+ {body(info?.oauth)}
+ </VStack>
+ </ComposerSheet>
+ );
+}
diff --git a/apps/mobile/src/plugins/PluginManagementConfirmation.tsx b/apps/mobile/src/plugins/PluginManagementConfirmation.tsx
new file mode 100644
index 0000000000..e70aa5a652
--- /dev/null
+++ b/apps/mobile/src/plugins/PluginManagementConfirmation.tsx
@@ -0,0 +1,121 @@
+import { Pressable, ScrollView, StyleSheet, View } from "react-native";
+import { useTranslation } from "react-i18next";
+import { SheetModal } from "@/session/SheetModal";
+import { Text } from "@/components/AppText";
+import {
+ fontWeight,
+ lineHeight,
+ radius,
+ spacing,
+ typeScale,
+ useThemedStyles,
+ type ThemeColors,
+} from "@/theme";
+import {
+ usePluginConsent,
+ type PluginManagementConfirmationProps,
+} from "./usePluginConsent";
+import { pluginConsentPresentation } from "./pluginConsentPresentation";
+export function PluginManagementConfirmation(
+ props: PluginManagementConfirmationProps,
+) {
+ const { t } = useTranslation(),
+ styles = useThemedStyles(makeStyles);
+ const { consent, visible, answer } = usePluginConsent(props);
+ const info = consent ? pluginConsentPresentation(consent, t) : undefined;
+ return (
+ <SheetModal
+ nativePresentation
+ visible={visible}
+ onRequestClose={() => answer(false)}
+ onBackdropPress={() => answer(false)}
+ >
+ <View style={styles.sheet} testID="plugins.managementConfirmation">
+ <ScrollView contentContainerStyle={styles.content}>
+ <Text style={styles.title}>
+ {t("plugins.notice.title.confirmation")}
+ </Text>
+ <Text style={styles.title}>{info?.title}</Text>
+ {[props.deviceName, info?.identity, info?.origin, info?.version]
+ .filter(Boolean)
+ .map((text, index) => (
+ <Text key={index} style={styles.body}>
+ {text}
+ </Text>
+ ))}
+ {info?.permissions.map((permission, index) => (
+ <View key={index} style={styles.permission}>
+ <Text style={styles.label}>{permission.title}</Text>
+ {permission.detail ? (
+ <Text style={styles.body}>{permission.detail}</Text>
+ ) : null}
+ </View>
+ ))}
+ {[info?.unchanged, info?.oauth].filter(Boolean).map((text, index) => (
+ <Text key={index} style={styles.body}>
+ {text}
+ </Text>
+ ))}
+ </ScrollView>
+ <View style={styles.actions}>
+ {[false, true].map((accept) => (
+ <Pressable
+ key={String(accept)}
+ testID={"plugins.management." + (accept ? "allow" : "reject")}
+ accessibilityRole="button"
+ disabled={
+ !props.active || props.state.busy || !props.state.online
+ }
+ onPress={() => answer(accept)}
+ style={[styles.button, accept && styles.primary]}
+ >
+ <Text style={[styles.label, accept && styles.primaryText]}>
+ {t("plugins.management." + (accept ? "allow" : "reject"))}
+ </Text>
+ </Pressable>
+ ))}
+ </View>
+ </View>
+ </SheetModal>
+ );
+}
+const makeStyles = (c: ThemeColors) =>
+ StyleSheet.create({
+ sheet: {
+ maxHeight: "85%",
+ backgroundColor: c.surfaceElevated,
+ borderTopLeftRadius: radius.container,
+ borderTopRightRadius: radius.container,
+ padding: spacing.lg + spacing.xs,
+ },
+ content: { gap: spacing.md, paddingBottom: spacing.md },
+ permission: { gap: spacing.xs },
+ title: {
+ fontSize: typeScale.body,
+ lineHeight: lineHeight.body,
+ fontWeight: fontWeight.semibold,
+ color: c.textPrimary,
+ },
+ label: {
+ fontSize: typeScale.bodySmall,
+ lineHeight: lineHeight.bodySmall,
+ fontWeight: fontWeight.medium,
+ color: c.textPrimary,
+ },
+ body: {
+ fontSize: typeScale.footnote,
+ lineHeight: lineHeight.caption,
+ color: c.textSecondary,
+ },
+ actions: { flexDirection: "row", gap: spacing.sm },
+ button: {
+ flex: 1,
+ minHeight: 44,
+ alignItems: "center",
+ justifyContent: "center",
+ borderRadius: radius.pill,
+ backgroundColor: c.surfaceChip,
+ },
+ primary: { backgroundColor: c.cta },
+ primaryText: { color: c.ctaText },
+ });
diff --git a/apps/mobile/src/plugins/PluginManagementMenu.tsx b/apps/mobile/src/plugins/PluginManagementMenu.tsx
new file mode 100644
index 0000000000..550b1a7010
--- /dev/null
+++ b/apps/mobile/src/plugins/PluginManagementMenu.tsx
@@ -0,0 +1,78 @@
+import { Stack } from "expo-router";
+import { nativeToolbarMenuItems } from "@/platform/chrome/nativeToolbarMenuItems";
+import { Alert, Pressable, StyleSheet } from "react-native";
+import { Settings } from "lucide-react-native";
+import { useTranslation } from "react-i18next";
+import {
+ NativePullDownMenu,
+ usesNativePullDownMenu,
+ type NativePullDownAction,
+} from "@/platform/chrome/NativePullDownMenu";
+import { iconSize, useTheme } from "@/theme";
+
+export function PluginManagementMenu({
+ actions,
+ onAction,
+ nativeToolbar = false,
+}: {
+ actions: NativePullDownAction[];
+ nativeToolbar?: boolean;
+ onAction(id: string): void;
+}) {
+ const { t } = useTranslation();
+ const { colors } = useTheme();
+ const disabled = !actions.some((action) => !action.disabled);
+ if (nativeToolbar) return (
+ <Stack.Toolbar placement="right">
+ <Stack.Toolbar.Menu icon="gearshape" disabled={disabled}
+ accessibilityLabel={t("plugins.management.manage")}>
+ {nativeToolbarMenuItems(actions, onAction)}
+ </Stack.Toolbar.Menu>
+ </Stack.Toolbar>
+ );
+ return (
+ <NativePullDownMenu
+ actions={actions}
+ onAction={onAction}
+ testID="plugins.managementMenu"
+ >
+ <Pressable
+ testID="plugins.manage"
+ accessibilityRole="button"
+ accessibilityLabel={t("plugins.management.manage")}
+ disabled={disabled}
+ style={styles.trigger}
+ onPress={
+ usesNativePullDownMenu()
+ ? undefined
+ : () =>
+ Alert.alert(t("plugins.management.manage"), undefined, [
+ ...actions
+ .filter((action) => !action.disabled)
+ .map((action) => ({
+ text: action.title,
+ style: action.destructive
+ ? ("destructive" as const)
+ : ("default" as const),
+ onPress: () => onAction(action.id),
+ })),
+ { text: t("plugins.cancel"), style: "cancel" },
+ ])
+ }
+ >
+ <Settings
+ size={iconSize.md}
+ color={disabled ? colors.textTertiary : colors.textPrimary}
+ />
+ </Pressable>
+ </NativePullDownMenu>
+ );
+}
+const styles = StyleSheet.create({
+ trigger: {
+ width: 44,
+ height: 44,
+ alignItems: "center",
+ justifyContent: "center",
+ },
+});
diff --git a/apps/mobile/src/plugins/PluginNotice.ios.tsx b/apps/mobile/src/plugins/PluginNotice.ios.tsx
new file mode 100644
index 0000000000..a1d7e69b3c
--- /dev/null
+++ b/apps/mobile/src/plugins/PluginNotice.ios.tsx
@@ -0,0 +1,60 @@
+import { useState } from "react";
+import { View, useWindowDimensions } from "react-native";
+import { Host, HStack, Image, Text, VStack, Button } from "@expo/ui/swift-ui";
+import { background, buttonStyle, clipShape, controlSize, disabled, fixedSize, font, foregroundStyle, frame, onGeometryChange, padding } from "@expo/ui/swift-ui/modifiers";
+import { iconSize, radius, spacing, useTheme } from "@/theme";
+import type { PluginNoticeProps } from "./PluginNotice";
+
+/** A compact status strip; SwiftUI owns label and button layout. */
+export function PluginNativeNotice({ title, detail, icon = "info", testID, actions, unavailable, compact = false }: PluginNoticeProps) {
+ const { colors } = useTheme();
+ const { width, fontScale } = useWindowDimensions();
+ const [measuredWidth, setMeasuredWidth] = useState(0);
+ const availableWidth = measuredWidth || width - (spacing.lg + spacing.xs) * 2;
+ // Keep native button labels intact on narrow screens and with larger accessibility text.
+ const stackedActions = (actions?.length ?? 0) > 1 || (!unavailable && !!detail) || availableWidth < 340 || fontScale > 1.2;
+ const systemImage = icon === "offline" ? "desktopcomputer.trianglebadge.exclamationmark" : icon === "warning" ? "exclamationmark.circle" : "info.circle";
+ const buttons = actions?.map((action) => <Button
+ key={action.label} label={action.label} testID={action.testID} onPress={action.onPress}
+ modifiers={[buttonStyle("bordered"), controlSize("small"), fixedSize({ horizontal: true, vertical: false }), frame({ minHeight: 44 }), disabled(Boolean(action.disabled))]}
+ />);
+ return <VStack testID={testID} alignment="leading" spacing={spacing.sm}
+ modifiers={[
+ padding({ horizontal: compact ? 0 : spacing.md, vertical: spacing.xs }),
+ frame({ minHeight: 48, maxWidth: Infinity, alignment: "leading" }),
+ ...(compact ? [] : [background(colors.surfaceChip), clipShape("roundedRectangle", radius.container)]),
+ onGeometryChange(({ width: nextWidth }) => setMeasuredWidth((previous) => previous === nextWidth ? previous : nextWidth)),
+ ]}>
+ <HStack alignment={stackedActions ? "top" : "center"} spacing={spacing.sm}>
+ <VStack modifiers={[frame({ width: iconSize.md, alignment: "top" })]}>
+ <Image systemName={systemImage} size={iconSize.md} modifiers={[foregroundStyle(colors.textSecondary)]} />
+ </VStack>
+ <VStack alignment="leading" spacing={spacing.sm} modifiers={[frame({ maxWidth: Infinity, alignment: "leading" })]}>
+ <Text modifiers={[font({ textStyle: "subheadline" }), foregroundStyle(colors.textPrimary), fixedSize({ horizontal: false, vertical: true })]}>{title}</Text>
+ {!unavailable && detail ? <Text modifiers={[font({ textStyle: "footnote" }), foregroundStyle(colors.textSecondary), fixedSize({ horizontal: false, vertical: true })]}>{detail}</Text> : null}
+ {stackedActions ? buttons : null}
+ </VStack>
+ {!stackedActions ? buttons : null}
+ </HStack>
+ </VStack>;
+}
+export function PluginNotice(props: PluginNoticeProps) {
+ const { mode } = useTheme();
+ const [width, setWidth] = useState(0);
+ return (
+ <View
+ testID={props.testID ? props.testID + ".layout" : undefined}
+ collapsable={false}
+ style={{ width: "100%", minHeight: 44 }}
+ onLayout={({ nativeEvent }) => setWidth(nativeEvent.layout.width)}
+ >
+ {width > 0 ? (
+ <Host colorScheme={mode} matchContents={{ vertical: true }} style={{ width }}>
+ <VStack modifiers={[frame({ width, alignment: "leading" })]}>
+ <PluginNativeNotice {...props} />
+ </VStack>
+ </Host>
+ ) : null}
+ </View>
+ );
+}
diff --git a/apps/mobile/src/plugins/PluginNotice.tsx b/apps/mobile/src/plugins/PluginNotice.tsx
new file mode 100644
index 0000000000..6ba87ac5d7
--- /dev/null
+++ b/apps/mobile/src/plugins/PluginNotice.tsx
@@ -0,0 +1,116 @@
+import { Pressable, StyleSheet, View } from "react-native";
+import { CircleAlert, Info, WifiOff } from "lucide-react-native";
+import { Text } from "@/components/AppText";
+import {
+ fontWeight,
+ iconSize,
+ lineHeight,
+ radius,
+ spacing,
+ typeScale,
+ useTheme,
+ useThemedStyles,
+ type ThemeColors,
+} from "@/theme";
+export interface PluginNoticeProps {
+ title: string;
+ compact?: boolean;
+ unavailable?: boolean;
+ detail?: string;
+ icon?: "info" | "warning" | "offline";
+ testID?: string;
+ actions?: Array<{
+ label: string;
+ onPress(): void;
+ disabled?: boolean;
+ testID?: string;
+ }>;
+}
+export function PluginNotice({
+ title,
+ compact,
+ detail,
+ icon = "info",
+ testID,
+ actions,
+}: PluginNoticeProps) {
+ const { colors } = useTheme(),
+ styles = useThemedStyles(makeStyles);
+ const Icon =
+ icon === "offline" ? WifiOff : icon === "warning" ? CircleAlert : Info;
+ const renderActions = () => (
+ <>
+ {actions?.length ? (
+ <View style={styles.actions}>
+ {actions.map((action) => (
+ <Pressable
+ key={action.label}
+ testID={action.testID}
+ accessibilityRole="button"
+ disabled={action.disabled}
+ onPress={action.onPress}
+ style={[styles.button, compact && { borderWidth: StyleSheet.hairlineWidth, borderColor: colors.border, borderRadius: radius.control }]}
+ >
+ <Text
+ style={[
+ styles.action,
+ action.disabled && { color: colors.textTertiary },
+ ]}
+ >
+ {action.label}
+ </Text>
+ </Pressable>
+ ))}
+ </View>
+ ) : null}
+ </>
+ );
+ return (
+ <View testID={testID} style={[styles.card, compact && { backgroundColor: "transparent", paddingHorizontal: 0, paddingVertical: spacing.xs }]} accessibilityLiveRegion="polite">
+ <View style={[styles.row, compact && { alignItems: "baseline", flexWrap: "wrap" }]}>
+ <Icon size={iconSize.sm} color={colors.textSecondary} />
+ <View style={styles.content}>
+ <Text style={styles.title}>{title}</Text>
+ {detail ? <Text style={styles.body}>{detail}</Text> : null}
+ </View>
+ {actions?.length === 1 ? renderActions() : null}
+ </View>
+ {actions && actions.length > 1 ? renderActions() : null}
+ </View>
+ );
+}
+const makeStyles = (c: ThemeColors) =>
+ StyleSheet.create({
+ card: {
+ padding: spacing.md,
+ gap: spacing.sm,
+ backgroundColor: c.surfaceChip,
+ borderRadius: radius.container,
+ },
+ row: { flexDirection: "row", alignItems: "center", gap: spacing.sm },
+ content: { flex: 1, minWidth: 0, gap: spacing.xs },
+ title: {
+ fontSize: typeScale.bodySmall,
+ lineHeight: lineHeight.bodySmall,
+ fontWeight: fontWeight.medium,
+ color: c.textPrimary,
+ },
+ body: {
+ fontSize: typeScale.footnote,
+ lineHeight: lineHeight.caption,
+ color: c.textSecondary,
+ },
+ actions: { flexDirection: "row", flexWrap: "wrap", gap: spacing.sm },
+ button: {
+ minHeight: 44,
+ justifyContent: "center",
+ paddingHorizontal: spacing.sm,
+ maxWidth: "48%",
+ },
+ action: {
+ fontSize: typeScale.bodySmall,
+ lineHeight: lineHeight.bodySmall,
+ fontWeight: fontWeight.medium,
+ color: c.textPrimary,
+ },
+ });
diff --git a/apps/mobile/src/plugins/PluginOriginalSettings.tsx b/apps/mobile/src/plugins/PluginOriginalSettings.tsx
new file mode 100644
index 0000000000..cac34d0333
--- /dev/null
+++ b/apps/mobile/src/plugins/PluginOriginalSettings.tsx
@@ -0,0 +1,464 @@
+import { useEffect, useRef, useState } from "react";
+import { ActivityIndicator, Alert, AppState, View } from "react-native";
+import * as WebBrowser from "expo-web-browser";
+import { useTranslation } from "react-i18next";
+import {
+ PLUGIN_OAUTH_CHANNEL,
+ type PluginDirectoryRequest,
+ type PluginOauthAction,
+} from "@cindy/device-link";
+import { useAuth } from "@/auth/AuthContext";
+import {
+ getMobileAuthOwner,
+ isMobileAuthOwnerCurrent,
+} from "@/auth/authOwnerGeneration";
+import { useDeviceLink } from "@/device-link/DeviceLinkContext";
+import { spacing, useTheme } from "@/theme";
+import { PluginNotice } from "./PluginNotice";
+import { PluginSettingsCard } from "./PluginSettingsCard";
+import { PluginDirectoryPicker } from "./PluginDirectoryPicker";
+import { openMobilePluginOauthSession } from "./pluginOauthSession";
+import { runMobilePluginAuthorization } from "./pluginAuthorizationController";
+import { receiveMobilePluginOauthLoopback } from "./pluginOauthLoopbackNative";
+import { pluginOauthPlatformCrypto } from "./pluginOauthPlatformCrypto";
+import type { PluginSettingsIdentity } from "./pluginSettingsClient";
+
+/** Native prompts and the original author page share one captured target and owner. */
+export function PluginOriginalSettings({
+ identity,
+ active,
+ onNotice,
+}: {
+ identity: PluginSettingsIdentity;
+ active: boolean;
+ onNotice(text: string): void;
+}) {
+ const auth = useAuth(),
+ link = useDeviceLink(),
+ { t } = useTranslation(),
+ { colors } = useTheme();
+ const owner = useRef(getMobileAuthOwner()).current;
+ const captured = useRef({ ...identity, epoch: link.connectionEpoch }).current;
+ const live = useRef({ identity, active, epoch: link.connectionEpoch });
+ live.current = { identity, active, epoch: link.connectionEpoch };
+ const alive = useRef(true);
+ const pending = useRef(new Set<() => void>());
+ const authorizationFailure = useRef<string | undefined>(undefined);
+ const [loading, setLoading] = useState(true);
+ const [failed, setFailed] = useState(false);
+ const [cardUnavailable, setCardUnavailable] = useState(false);
+ const [localError, setLocalError] = useState<{
+ title: string;
+ detail: string;
+ }>();
+ const [attempt, setAttempt] = useState(0);
+ const [directory, setDirectory] = useState<{
+ request: PluginDirectoryRequest;
+ resolve(path: string | null): void;
+ }>();
+ useEffect(() => {
+ alive.current = true;
+ return () => {
+ alive.current = false;
+ for (const cancel of pending.current) cancel();
+ pending.current.clear();
+ };
+ }, []);
+ useEffect(() => {
+ if (!active) for (const cancel of Array.from(pending.current)) cancel();
+ }, [active]);
+ const assertIdentityCurrent = () => {
+ const current = live.current;
+ if (
+ !isMobileAuthOwnerCurrent(owner) ||
+ current.epoch !== captured.epoch ||
+ current.identity.deviceId !== captured.deviceId ||
+ current.identity.instanceId !== captured.instanceId ||
+ current.identity.expectedInstalledApproval !==
+ captured.expectedInstalledApproval
+ )
+ throw new Error("PLUGIN_SETTINGS_CLOSED");
+ };
+ const assertCurrent = () => {
+ assertIdentityCurrent();
+ if (!alive.current || !live.current.active)
+ throw new Error("PLUGIN_SETTINGS_CLOSED");
+ };
+ const confirm = (
+ title: string,
+ body: string,
+ yes: string,
+ no: string,
+ danger = false,
+ expiresAt?: number,
+ ) =>
+ new Promise<boolean>((resolve) => {
+ let settled = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const finish = (accepted: boolean) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ pending.current.delete(cancel);
+ try {
+ assertCurrent();
+ resolve(accepted && (!expiresAt || Date.now() < expiresAt));
+ } catch {
+ resolve(false);
+ }
+ };
+ const cancel = () => finish(false);
+ pending.current.add(cancel);
+ if (expiresAt)
+ timer = setTimeout(cancel, Math.max(0, expiresAt - Date.now()));
+ Alert.alert(
+ title,
+ body,
+ [
+ { text: no, style: "cancel", onPress: cancel },
+ {
+ text: yes,
+ style: danger ? "destructive" : "default",
+ onPress: () => finish(true),
+ },
+ ],
+ { cancelable: true, onDismiss: cancel },
+ );
+ });
+ const openSession = async (action: PluginOauthAction) => {
+ assertCurrent();
+ if (!auth.deviceId) throw new Error("PLUGIN_SETTINGS_CLOSED");
+ return openMobilePluginOauthSession({
+ deviceId: captured.deviceId,
+ peer: auth.deviceId,
+ owner,
+ ghostId: captured.instanceId,
+ action,
+ assertCurrent: assertIdentityCurrent,
+ invoke: (raw) =>
+ link.invoke(captured.deviceId, PLUGIN_OAUTH_CHANNEL, [raw], {
+ preSend: assertIdentityCurrent,
+ }),
+ });
+ };
+ const authorize = async (action: PluginOauthAction) => {
+ assertCurrent();
+ authorizationFailure.current = undefined;
+ setLocalError(undefined);
+ setFailed(false);
+ const session = await openSession(action);
+ try {
+ await runMobilePluginAuthorization({
+ crypto: pluginOauthPlatformCrypto,
+ kind: "oauth",
+ action,
+ invoke: session.request,
+ assertCurrent,
+ clearInput() {},
+ receiveLoopback: async (request, expiresAt, signal) => {
+ assertCurrent();
+ const accepted = await confirm(
+ t("plugins.connectAccount"),
+ new URL(request.url).hostname,
+ t("plugins.open"),
+ t("plugins.cancel"),
+ false,
+ expiresAt,
+ );
+ assertCurrent();
+ if (!accepted)
+ throw new Error("PLUGIN_SETTINGS_AUTHORIZATION_CANCELLED");
+ return receiveMobilePluginOauthLoopback(
+ request,
+ expiresAt,
+ assertCurrent,
+ signal,
+ );
+ },
+ isForeground: () => AppState.currentState === "active",
+ pause: async () => {
+ do {
+ await new Promise((resolve) => setTimeout(resolve, 600));
+ assertCurrent();
+ } while (AppState.currentState !== "active");
+ },
+ showAuthorization: async (url, code, expiresAt) => {
+ assertCurrent();
+ const accepted = await confirm(
+ t("plugins.connectAccount"),
+ new URL(url).hostname + (code ? "\n" + code : ""),
+ t("plugins.open"),
+ t("plugins.cancel"),
+ false,
+ expiresAt,
+ );
+ assertCurrent();
+ if (!accepted)
+ throw new Error("PLUGIN_SETTINGS_AUTHORIZATION_CANCELLED");
+ await WebBrowser.openBrowserAsync(url, { showTitle: true });
+ assertCurrent();
+ },
+ });
+ } catch (error) {
+ assertCurrent();
+ // Card forwards only a sanitized code in a new Error instance.
+ authorizationFailure.current =
+ error instanceof Error && /^[A-Z_]{1,80}$/.test(error.message)
+ ? error.message
+ : "PLUGIN_SETTINGS_UNAVAILABLE";
+ throw error;
+ } finally {
+ session.dispose();
+ }
+ };
+ return (
+ <View testID="plugins.originalSettings" style={{ gap: spacing.md }}>
+ {localError ? (
+ <PluginNotice
+ compact
+ unavailable={cardUnavailable}
+ testID="plugins.settingsError"
+ title={localError.title}
+ detail={
+ localError.title === t("plugins.notice.title.readFailed")
+ ? undefined
+ : localError.detail
+ }
+ icon="warning"
+ actions={
+ failed
+ ? [
+ {
+ label: t("plugins.management.settingsReload"),
+ testID: "plugins.settingsReload",
+ disabled: !active,
+ onPress: () => {
+ setFailed(false);
+ setLocalError(undefined);
+ setAttempt((value) => value + 1);
+ },
+ },
+ ]
+ : undefined
+ }
+ />
+ ) : null}
+ <View
+ style={
+ cardUnavailable
+ ? { height: 0, overflow: "hidden" }
+ : { minHeight: loading ? 80 : undefined }
+ }
+ >
+ <View
+ pointerEvents={loading ? "none" : "auto"}
+ accessibilityElementsHidden={loading}
+ importantForAccessibility={loading ? "no-hide-descendants" : "auto"}
+ style={{ opacity: loading ? 0 : 1 }}
+ >
+ <PluginSettingsCard
+ key={attempt}
+ identity={identity}
+ active={active}
+ generation={
+ String(auth.accountGeneration) + ":" + link.connectionEpoch
+ }
+ assertCurrent={assertCurrent}
+ assertCleanupCurrent={assertIdentityCurrent}
+ openSession={openSession}
+ invokeTarget={(channel, args) =>
+ link.invoke(captured.deviceId, channel, args, {
+ preSend: assertCurrent,
+ })
+ }
+ onAuthorize={authorize}
+ onOpenLink={async (raw, checkPage) => {
+ checkPage();
+ assertCurrent();
+ if (raw.length > 8192 || /[\x00-\x20\\]/.test(raw))
+ throw new Error("PLUGIN_SETTINGS_LINK_UNAVAILABLE");
+ const url = new URL(raw);
+ if (
+ !["https:", "http:"].includes(url.protocol) ||
+ url.username ||
+ url.password
+ )
+ throw new Error("PLUGIN_SETTINGS_LINK_UNAVAILABLE");
+ // A target computer's loopback URL is not a service on this phone.
+ const host = url.hostname.toLowerCase().replace(/\.$/, "");
+ if (
+ host === "localhost" ||
+ host.endsWith(".localhost") ||
+ /^127\./.test(host) ||
+ host === "[::1]" ||
+ host === "0.0.0.0"
+ ) {
+ onNotice(t("plugins.settingsComputerLink"));
+ return;
+ }
+ const accepted = await confirm(
+ t("plugins.externalTitle"),
+ url.hostname,
+ t("plugins.open"),
+ t("plugins.cancel"),
+ );
+ checkPage();
+ assertCurrent();
+ if (accepted)
+ await WebBrowser.openBrowserAsync(url.toString(), {
+ showTitle: true,
+ });
+ }}
+ onLoading={(value) => {
+ setLoading(value);
+ if (value) {
+ setCardUnavailable(false);
+ authorizationFailure.current = undefined;
+ setFailed(false);
+ setLocalError(undefined);
+ }
+ }}
+ onNotice={(notice) => {
+ try {
+ assertCurrent();
+ } catch {
+ return;
+ }
+ onNotice(notice);
+ }}
+ onError={(error, context = "load", reportedToPage = false) => {
+ try {
+ assertCurrent();
+ } catch {
+ return;
+ }
+ if (error.message === "PLUGIN_SETTINGS_LINK_UNAVAILABLE") {
+ onNotice(t("plugins.settingsLinkUnavailable"));
+ return;
+ }
+ if (error.message === "PLUGIN_SETTINGS_HOST_UPDATE_REQUIRED") {
+ setFailed(false);
+ setLocalError({
+ title: t("plugins.notice.title.authorization"),
+ detail: t("plugins.settingsHostUpdateRequired"),
+ });
+ return;
+ }
+ if (
+ context === "operation" &&
+ error instanceof Error &&
+ authorizationFailure.current === error.message
+ ) {
+ authorizationFailure.current = undefined;
+ if (error.message === "PLUGIN_SETTINGS_AUTHORIZATION_CANCELLED")
+ return;
+ if (
+ reportedToPage &&
+ error.message !== "PLUGIN_OAUTH_UPDATE_REQUIRED"
+ )
+ return;
+ setFailed(false);
+ setLocalError({
+ title: t("plugins.notice.title.authorization"),
+ detail: t(
+ error.message === "PLUGIN_OAUTH_UPDATE_REQUIRED"
+ ? "plugins.oauthUpdateRequired"
+ : [
+ "PLUGIN_AUTHORIZATION_COMPUTER_CALLBACK",
+ "PLUGIN_OAUTH_CALLBACK_UNSUPPORTED",
+ ].includes(error.message)
+ ? "plugins.computerAuthorizationHint"
+ : "plugins.authorizationCheckHint",
+ ),
+ });
+ return;
+ }
+ authorizationFailure.current = undefined;
+ // The original form receives command failures; only bridge-only failures need native recovery UI.
+ if (reportedToPage) return;
+ setFailed(true);
+ if (context === "load") setCardUnavailable(true);
+ setLocalError({
+ title: t(
+ "plugins.notice.title." +
+ (context === "unknown"
+ ? "resultUnknown"
+ : context === "operation"
+ ? "writeFailed"
+ : "readFailed"),
+ ),
+ detail: t(
+ context === "unknown"
+ ? "plugins.management.settingsResultUnknown"
+ : context === "operation"
+ ? "plugins.management.settingsOperationFailed"
+ : "plugins.management.settingsUnavailable",
+ ),
+ });
+ }}
+ onConfirm={(request) => {
+ assertCurrent();
+ return confirm(
+ request.title,
+ request.body,
+ request.confirmText ?? t("plugins.management.allow"),
+ request.cancelText ?? t("plugins.cancel"),
+ request.danger,
+ request.expiresAt,
+ );
+ }}
+ onDirectory={(request) =>
+ new Promise((resolve) => {
+ assertCurrent();
+ let settled = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const finish = (path: string | null) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ pending.current.delete(cancel);
+ if (alive.current) setDirectory(undefined);
+ try {
+ assertCurrent();
+ resolve(Date.now() < request.expiresAt ? path : null);
+ } catch {
+ resolve(null);
+ }
+ };
+ const cancel = () => finish(null);
+ pending.current.add(cancel);
+ timer = setTimeout(
+ cancel,
+ Math.max(0, request.expiresAt - Date.now()),
+ );
+ setDirectory({ request, resolve: finish });
+ })
+ }
+ />
+ </View>
+ {loading ? (
+ <ActivityIndicator
+ testID="plugins.settingsLoading"
+ color={colors.textSecondary}
+ pointerEvents="none"
+ style={{
+ position: "absolute",
+ top: 0,
+ right: 0,
+ bottom: 0,
+ left: 0,
+ }}
+ />
+ ) : null}
+ </View>
+ {directory ? (
+ <PluginDirectoryPicker
+ key={directory.request.id}
+ request={directory.request}
+ deviceId={captured.deviceId}
+ onAnswer={async (path) => directory.resolve(path)}
+ />
+ ) : null}
+ </View>
+ );
+}
diff --git a/apps/mobile/src/plugins/PluginPermissionCard.tsx b/apps/mobile/src/plugins/PluginPermissionCard.tsx
new file mode 100644
index 0000000000..ef4361623d
--- /dev/null
+++ b/apps/mobile/src/plugins/PluginPermissionCard.tsx
@@ -0,0 +1,143 @@
+import { View, StyleSheet } from "react-native";
+import { useTranslation } from "react-i18next";
+import {
+ AppWindow,
+ Bot,
+ Cpu,
+ FileCode2,
+ FilePen,
+ FolderOpen,
+ FolderPlus,
+ Globe,
+ GraduationCap,
+ KeyRound,
+ LayoutTemplate,
+ Library,
+ MapPin,
+ Megaphone,
+ MessageCircleQuestion,
+ PanelLeft,
+ PanelRight,
+ Radio,
+ Shield,
+ Sparkles,
+ Terminal,
+ Wrench,
+} from "lucide-react-native";
+import { Text } from "@/components/AppText";
+import {
+ iconSize,
+ iconStroke,
+ spacing,
+ radius,
+ typeScale,
+ lineHeight,
+ fontWeight,
+ useTheme,
+ useThemedStyles,
+ type ThemeColors,
+} from "@/theme";
+import type { PluginDetailModel } from "./pluginDetailModel";
+
+const icons = {
+ cindy: Sparkles,
+ agent: Bot,
+ node: Cpu,
+ tool: Wrench,
+ command: Terminal,
+ panel: PanelRight,
+ "main-view": AppWindow,
+ code: FileCode2,
+ subscribe: Radio,
+ card: LayoutTemplate,
+ network: Globe,
+ notify: Megaphone,
+ confirm: MessageCircleQuestion,
+ fs: FilePen,
+ library: Library,
+ "session-context": MapPin,
+ pick: FolderOpen,
+ preview: AppWindow,
+ skill: GraduationCap,
+ workspace: FolderPlus,
+};
+
+/** Host owns the copy and permission meaning. Older Hosts retain a neutral icon. */
+export function PluginPermissionCard({
+ permissions,
+ showHeading = true,
+ width,
+}: {
+ permissions: NonNullable<PluginDetailModel["permissions"]>;
+ showHeading?: boolean;
+ width?: number;
+}) {
+ const { t } = useTranslation();
+ const { colors } = useTheme();
+ const styles = useThemedStyles(makeStyles);
+ return (
+ <View
+ testID="plugins.permissions"
+ style={[styles.card, width !== undefined && { width }]}
+ >
+ {showHeading ? (
+ <Text style={styles.heading}>{t("plugins.detail.permissions")}</Text>
+ ) : null}
+ {permissions.map((permission, index) => {
+ const Icon =
+ permission.labelKey === "panelLeft"
+ ? PanelLeft
+ : [
+ "networkSecret",
+ "networkSecretOauth",
+ "networkSecretGhCli",
+ "networkSecretIdentity",
+ ].includes(permission.labelKey ?? "")
+ ? KeyRound
+ : Object.prototype.hasOwnProperty.call(
+ icons,
+ permission.kind ?? "",
+ )
+ ? icons[permission.kind as keyof typeof icons]
+ : Shield;
+ return (
+ <View key={index} style={styles.row}>
+ <Icon
+ size={iconSize.action}
+ strokeWidth={iconStroke.thin}
+ color={colors.textSecondary}
+ />
+ <View style={styles.copy}>
+ <Text style={styles.title}>{permission.title}</Text>
+ </View>
+ </View>
+ );
+ })}
+ </View>
+ );
+}
+const makeStyles = (c: ThemeColors) =>
+ StyleSheet.create({
+ card: {
+ padding: spacing.lg,
+ gap: spacing.lg,
+ backgroundColor: c.surfaceElevated,
+ borderRadius: radius.container,
+ borderWidth: StyleSheet.hairlineWidth,
+ borderColor: c.border,
+ },
+ heading: {
+ fontSize: typeScale.subtitle,
+ lineHeight: lineHeight.subtitle,
+ fontWeight: fontWeight.medium,
+ color: c.textPrimary,
+ },
+ row: { flexDirection: "row", gap: spacing.md, alignItems: "flex-start" },
+ copy: { flex: 1, gap: spacing.xs },
+ title: {
+ fontSize: typeScale.body,
+ lineHeight: lineHeight.body,
+ fontWeight: fontWeight.medium,
+ color: c.textPrimary,
+ },
+ });
diff --git a/apps/mobile/src/plugins/PluginSettingsCard.tsx b/apps/mobile/src/plugins/PluginSettingsCard.tsx
new file mode 100644
index 0000000000..f18801979a
--- /dev/null
+++ b/apps/mobile/src/plugins/PluginSettingsCard.tsx
@@ -0,0 +1,636 @@
+import { useEffect, useRef, useState } from "react";
+import { AppState, StyleSheet, View, useWindowDimensions } from "react-native";
+import WebView from "react-native-webview";
+import {
+ parsePluginSettingsRequest,
+ type PluginPageConfirm,
+ type PluginPagePoll,
+ type PluginDirectoryRequest,
+} from "@cindy/device-link";
+import {
+ motionDuration,
+ motionEasing,
+ radius,
+ spacing,
+ useTheme,
+} from "@/theme";
+import {
+ openPluginSettingsClient,
+ type PluginSettingsClient,
+ type PluginSettingsClientOptions,
+} from "./pluginSettingsClient";
+import { preparePluginSettingsResources } from "./pluginSettingsResources";
+import { settingsInjection } from "./pluginSettingsHtml";
+import { pluginSettingsMediaType } from "./pluginSettingsAssets";
+
+export interface PluginSettingsCardProps extends PluginSettingsClientOptions {
+ active: boolean;
+ /** Captured owner + connection epoch. Changing it tears down the entire document/lease. */
+ generation: string | number;
+ onError?(
+ error: Error,
+ context?: "load" | "read" | "operation" | "unknown",
+ reportedToPage?: boolean,
+ ): void;
+ onOpenLink?(url: string, assertCurrent: () => void): Promise<void>;
+ onNotice?(text: string): void;
+ onLoading?(loading: boolean): void;
+ onConfirm?(request: PluginPageConfirm): Promise<boolean>;
+ onDirectory?(request: PluginDirectoryRequest): Promise<string | null>;
+}
+
+/** The parent owns the header/banner/native prompts; this card only contains the original settings. */
+export function PluginSettingsCard(props: PluginSettingsCardProps) {
+ const { colors, mode } = useTheme();
+ const { height: windowHeight } = useWindowDimensions();
+ const theme = {
+ dark: mode === "dark",
+ colors: {
+ "panel-bg": colors.surfaceElevated,
+ surface: colors.surfaceElevated,
+ "surface-elevated": colors.surfaceElevated,
+ "surface-chip": colors.surfaceChip,
+ "border-default": colors.border,
+ "text-primary": colors.textPrimary,
+ "text-secondary": colors.textSecondary,
+ "text-tertiary": colors.textTertiary,
+ "text-placeholder": colors.textPlaceholder,
+ "accent-soft": colors.surfaceChip,
+ "accent-cta-bg": colors.cta,
+ "accent-pure-cta-fg": colors.ctaText,
+ "error-bg": colors.surfaceElevated,
+ "error-border": colors.errorBorder,
+ "error-fg": colors.statusError,
+ "focus-ring": colors.inputCaret,
+ "msg-scrollbar": colors.border,
+ "msg-scrollbar-hover": colors.borderStrong,
+ "motion-fast": motionDuration.fast + "ms",
+ "motion-spinner-cycle": motionDuration.spinnerCycle + "ms",
+ "motion-ease-out": "cubic-bezier(" + motionEasing.out.join(",") + ")",
+ "slider-track": colors.surfaceChip,
+ "slider-fill": colors.cta,
+ "slider-thumb": colors.surfaceElevated,
+ "slider-thumb-shadow": "none",
+ "msg-tool-card-bg": colors.surfaceElevated,
+ "msg-tool-card-border": colors.border,
+ "msg-tool-card-text": colors.textPrimary,
+ "msg-tool-card-chevron": colors.textSecondary,
+ "text-secondary-mid": colors.textSecondary,
+ "settings-theme-card-bg": colors.surfaceElevated,
+ },
+ };
+ const latest = useRef(props);
+ latest.current = props;
+ const themeRef = useRef(theme);
+ themeRef.current = theme;
+ const webview = useRef<WebView>(null);
+ const clientRef = useRef<PluginSettingsClient | undefined>(undefined);
+ const documentEpoch = useRef(0);
+ const pollRef = useRef<(() => void) | undefined>(undefined);
+ const covered = useRef(0);
+ const openingLink = useRef<object | null>(null);
+ const authorizationActive = useRef<object | null>(null);
+ const browserBackground = useRef(false);
+ const [resourceEpoch, setResourceEpoch] = useState(0);
+ const [authorizing, setAuthorizing] = useState(false);
+ const [source, setSource] = useState<{ uri: string }>();
+ const [height, setHeight] = useState(160);
+ const [foreground, setForeground] = useState(
+ AppState.currentState === "active",
+ );
+ const foregroundRef = useRef(foreground);
+ foregroundRef.current = foreground;
+ useEffect(() => {
+ const listener = AppState.addEventListener("change", (state) => {
+ if (state !== "active" && authorizationActive.current)
+ browserBackground.current = true;
+ foregroundRef.current = state === "active";
+ setForeground(state === "active");
+ });
+ return () => listener.remove();
+ }, []);
+ const { deviceId, instanceId, expectedInstalledApproval } = props.identity;
+ const notificationScope = JSON.stringify([
+ deviceId,
+ instanceId,
+ expectedInstalledApproval,
+ props.generation,
+ ]);
+ const deferredNotices = useRef<
+ | {
+ scope: string;
+ notices: PluginPagePoll["notifications"];
+ }
+ | undefined
+ >(undefined);
+ useEffect(() => {
+ const pending = deferredNotices.current;
+ if (!pending) return;
+ if (!props.active || pending.scope !== notificationScope) {
+ deferredNotices.current = undefined;
+ return;
+ }
+ if (!foreground || authorizing) return;
+ deferredNotices.current = undefined;
+ try {
+ props.assertCurrent();
+ for (const notice of pending.notices)
+ latest.current.onNotice?.(notice.text);
+ } catch {
+ /* A replaced owner or connection cannot receive old notices. */
+ }
+ }, [foreground, authorizing, props.active, notificationScope]);
+ const leaseActive = props.active && (foreground || authorizing);
+ useEffect(() => {
+ if (!leaseActive) {
+ setSource(undefined);
+ return;
+ }
+ let disposed = false;
+ let client: PluginSettingsClient | undefined;
+ let resource:
+ Awaited<ReturnType<typeof preparePluginSettingsResources>> | undefined;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let after = 0;
+ const abort = new AbortController();
+ const prompts = new Set<string>();
+ let promptQueue = Promise.resolve();
+ const check = () => {
+ if (
+ disposed ||
+ !latest.current.active ||
+ latest.current.generation !== props.generation ||
+ latest.current.identity.deviceId !== deviceId ||
+ latest.current.identity.instanceId !== instanceId ||
+ latest.current.identity.expectedInstalledApproval !==
+ expectedInstalledApproval
+ )
+ throw new Error("PLUGIN_SETTINGS_CLOSED");
+ props.assertCurrent();
+ };
+ const report = (error: unknown, context: "load" | "read" = "read") => {
+ if (!disposed)
+ latest.current.onError?.(
+ new Error(
+ error instanceof Error && /^[A-Z_]{1,80}$/.test(error.message)
+ ? error.message
+ : "PLUGIN_SETTINGS_UNAVAILABLE",
+ ),
+ context,
+ );
+ };
+ const inject = (value: unknown) => {
+ check();
+ webview.current?.injectJavaScript(
+ settingsInjection("__cindySettingsReceive", value),
+ );
+ };
+ const prompt = async (
+ request: PluginPageConfirm | PluginDirectoryRequest,
+ directory: boolean,
+ ) => {
+ let presented = false;
+ try {
+ check();
+ covered.current++;
+ presented = true;
+ const answer =
+ Date.now() >= request.expiresAt
+ ? null
+ : directory
+ ? ((await latest.current.onDirectory?.(
+ request as PluginDirectoryRequest,
+ )) ?? null)
+ : ((await latest.current.onConfirm?.(
+ request as PluginPageConfirm,
+ )) ?? false);
+ check();
+ if (Date.now() >= request.expiresAt) return;
+ await client!.send(
+ directory
+ ? {
+ kind: "answer-directory",
+ requestId: request.id,
+ path: typeof answer === "string" ? answer : null,
+ }
+ : {
+ kind: "confirm",
+ requestId: request.id,
+ accepted: answer === true,
+ },
+ );
+ } catch (error) {
+ report(error);
+ } finally {
+ if (presented && !disposed)
+ covered.current = Math.max(0, covered.current - 1);
+ }
+ };
+ const enqueue = (
+ request: PluginPageConfirm | PluginDirectoryRequest,
+ directory: boolean,
+ ) => {
+ if (prompts.has(request.id)) return;
+ prompts.add(request.id);
+ promptQueue = promptQueue.then(() => prompt(request, directory));
+ };
+ const poll = async () => {
+ try {
+ check();
+ // Host retains the authorization lease; do not consume notices while the browser owns the UI.
+ if (!foregroundRef.current || authorizationActive.current) {
+ timer = setTimeout(() => void poll(), 800);
+ return;
+ }
+ const result = (await client!.send({
+ kind: "poll",
+ after,
+ })) as PluginPagePoll;
+ check();
+ if (
+ !result ||
+ !Array.isArray(result.events) ||
+ !Array.isArray(result.confirms) ||
+ !Array.isArray(result.notifications)
+ )
+ throw new Error("PLUGIN_SETTINGS_INVALID_POLL");
+ if (!foregroundRef.current || authorizationActive.current) {
+ // An in-flight poll has already consumed these notices on Host. Keep them across resource reload.
+ deferredNotices.current = {
+ scope: notificationScope,
+ notices: result.notifications,
+ };
+ timer = setTimeout(() => void poll(), 800);
+ return;
+ }
+ inject({ kind: "events", events: result.events });
+ for (const event of result.events)
+ after = Math.max(after, event.sequence);
+ for (const notice of result.notifications)
+ latest.current.onNotice?.(notice.text);
+ for (const confirmation of result.confirms)
+ enqueue(confirmation, false);
+ for (const directory of result.directories ?? [])
+ enqueue(directory, true);
+ if (!disposed) timer = setTimeout(() => void poll(), 800);
+ } catch (error) {
+ report(error);
+ if (!disposed) {
+ void client?.close().catch(() => {});
+ abort.abort();
+ setSource(undefined);
+ }
+ }
+ };
+ latest.current.onLoading?.(true);
+ void (async () => {
+ try {
+ client = await openPluginSettingsClient({
+ ...props,
+ assertCurrent: check,
+ assertCleanupCurrent:
+ props.assertCleanupCurrent ?? props.assertCurrent,
+ onAuthorize: async (action) => {
+ check();
+ if (!latest.current.onAuthorize || authorizationActive.current)
+ throw new Error("PLUGIN_SETTINGS_AUTHORIZATION_UNAVAILABLE");
+ const token = {};
+ authorizationActive.current = token;
+ setAuthorizing(true);
+ try {
+ await latest.current.onAuthorize(action);
+ check();
+ } finally {
+ if (authorizationActive.current === token) {
+ authorizationActive.current = null;
+ if (!disposed) setAuthorizing(false);
+ }
+ }
+ },
+ });
+ check();
+ clientRef.current = client;
+ resource = await preparePluginSettingsResources(
+ client,
+ themeRef.current,
+ abort.signal,
+ );
+ check();
+ setSource({ uri: resource.url });
+ pollRef.current = () => {
+ pollRef.current = undefined;
+ void poll();
+ };
+ } catch (error) {
+ report(error, "load");
+ void client?.close().catch(() => {});
+ if (!disposed) latest.current.onLoading?.(false);
+ }
+ // Resource readiness only mounts the WebView; keep loading until its document loads.
+ })();
+ return () => {
+ disposed = true;
+ clearTimeout(timer);
+ abort.abort();
+ covered.current = 0;
+ openingLink.current = null;
+ authorizationActive.current = null;
+ browserBackground.current = false;
+ setAuthorizing(false);
+ pollRef.current = undefined;
+ if (clientRef.current === client) clientRef.current = undefined;
+ void resource?.close().catch(() => {});
+ void client?.close().catch(() => {});
+ setSource(undefined);
+ };
+ // Functions are captured by this lease; the owner/connection guard must reject a stale source.
+ }, [
+ deviceId,
+ instanceId,
+ expectedInstalledApproval,
+ props.generation,
+ leaseActive,
+ resourceEpoch,
+ ]);
+ useEffect(() => {
+ if (source)
+ webview.current?.injectJavaScript(
+ settingsInjection("__cindySettingsTheme", theme),
+ );
+ }, [mode, colors, source]);
+ const cardHeight = Math.min(height + spacing.lg * 2, 420, windowHeight * 0.5);
+ const viewportHeight = Math.max(0, cardHeight - spacing.lg * 2);
+ const scrollable = height > viewportHeight;
+ if (!source) return null;
+ const navigationClient = clientRef.current;
+ const pageCurrent = () => {
+ try {
+ navigationClient?.assertCurrent();
+ return !!navigationClient && navigationClient === clientRef.current;
+ } catch {
+ return false;
+ }
+ };
+ const openLink = (url: string) => {
+ const check = () => {
+ navigationClient?.assertCurrent();
+ if (
+ !navigationClient ||
+ navigationClient !== clientRef.current ||
+ !latest.current.active ||
+ !foregroundRef.current
+ )
+ throw new Error("PLUGIN_SETTINGS_CLOSED");
+ };
+ try {
+ check();
+ } catch {
+ return;
+ }
+ if (covered.current || authorizationActive.current || openingLink.current)
+ return;
+ const token = {};
+ openingLink.current = token;
+ covered.current++;
+ void (async () => {
+ try {
+ if (!latest.current.onOpenLink)
+ throw new Error("PLUGIN_SETTINGS_LINK_UNAVAILABLE");
+ await latest.current.onOpenLink(url, check);
+ } catch {
+ try {
+ check();
+ latest.current.onError?.(
+ new Error("PLUGIN_SETTINGS_LINK_UNAVAILABLE"),
+ "operation",
+ );
+ } catch {
+ /* The initiating page has gone away. */
+ }
+ } finally {
+ if (openingLink.current === token) {
+ openingLink.current = null;
+ covered.current = Math.max(0, covered.current - 1);
+ }
+ }
+ })();
+ };
+ const navigate = (raw: string) => {
+ try {
+ navigationClient?.assertCurrent();
+ if (!navigationClient || navigationClient !== clientRef.current)
+ return false;
+ const url = new URL(raw);
+ const bootstrap = new URL(source.uri);
+ bootstrap.hash = "";
+ const withoutHash = new URL(raw);
+ withoutHash.hash = "";
+ if (withoutHash.href === bootstrap.href) return true;
+ if (url.origin === new URL(source.uri).origin) {
+ return navigationClient.document.files.some(
+ (file) =>
+ pluginSettingsMediaType(file.mime) === "text/html" &&
+ file.path === decodeURIComponent(url.pathname.slice(1)),
+ );
+ }
+ openLink(raw);
+ } catch {
+ /* Untrusted or obsolete navigation stays inside the settings boundary. */
+ }
+ return false;
+ };
+ return (
+ <View
+ style={[
+ styles.card,
+ {
+ height: cardHeight,
+ backgroundColor: colors.surfaceElevated,
+ borderColor: colors.border,
+ },
+ ]}
+ >
+ <WebView
+ ref={webview}
+ source={{ uri: source.uri }}
+ style={{
+ height: viewportHeight,
+ backgroundColor: colors.surfaceElevated,
+ }}
+ incognito
+ cacheEnabled={false}
+ sharedCookiesEnabled={false}
+ thirdPartyCookiesEnabled={false}
+ allowFileAccess={false}
+ allowFileAccessFromFileURLs={false}
+ allowUniversalAccessFromFileURLs={false}
+ javaScriptCanOpenWindowsAutomatically={false}
+ setSupportMultipleWindows={true}
+ mediaPlaybackRequiresUserAction
+ allowsInlineMediaPlayback={false}
+ scrollEnabled={scrollable}
+ indicatorStyle={mode === "dark" ? "white" : "black"}
+ nestedScrollEnabled={scrollable}
+ // RNW sends whitelist failures to the OS before our navigation callback. Always consume them here.
+ originWhitelist={["*"]}
+ onShouldStartLoadWithRequest={(request) => navigate(request.url)}
+ onOpenWindow={(event) => {
+ const url = event.nativeEvent.targetUrl;
+ if (navigate(url)) setSource({ uri: url });
+ }}
+ mediaCapturePermissionGrantType="deny"
+ onFileDownload={() =>
+ latest.current.onError?.(
+ new Error("PLUGIN_SETTINGS_DOWNLOAD_BLOCKED"),
+ "operation",
+ )
+ }
+ onLoadStart={() => {
+ if (!pageCurrent()) return;
+ documentEpoch.current++;
+ latest.current.onLoading?.(true);
+ }}
+ onLoad={() => {
+ if (!pageCurrent()) return;
+ latest.current.onLoading?.(false);
+ webview.current?.injectJavaScript(
+ settingsInjection("__cindySettingsTheme", themeRef.current),
+ );
+ pollRef.current?.();
+ }}
+ onError={() => {
+ if (!pageCurrent()) return;
+ latest.current.onLoading?.(false);
+ latest.current.onError?.(
+ new Error("PLUGIN_SETTINGS_UNAVAILABLE"),
+ "load",
+ );
+ }}
+ onMessage={(event) => {
+ const client = navigationClient;
+ if (
+ !pageCurrent() ||
+ !client ||
+ event.nativeEvent.data.length > 150_000
+ )
+ return;
+ const requestDocument = documentEpoch.current;
+ try {
+ client.assertCurrent();
+ const message = JSON.parse(event.nativeEvent.data);
+ if (message.settings !== client.document.pageId) return;
+ if (Number.isFinite(message.height) && message.id === undefined) {
+ setHeight(Math.max(64, Math.min(12_000, message.height)));
+ return;
+ }
+ if (
+ !Number.isSafeInteger(message.id) ||
+ message.id < 1 ||
+ !parsePluginSettingsRequest({
+ op: "settings",
+ id: message.settings,
+ command: message.command,
+ })
+ )
+ return;
+ const command = message.command;
+ const requestId = message.id;
+ const authorization =
+ command.kind === "fetch" &&
+ command.method === "POST" &&
+ /^\/oauth\/[^/]+\/connect$/.test(command.path);
+ const work =
+ covered.current ||
+ !foregroundRef.current ||
+ authorizationActive.current
+ ? Promise.reject(new Error("PLUGIN_SETTINGS_COVERED"))
+ : command.kind === "fetch"
+ ? client.fetch(command.path, command.method, command.body)
+ : ["subscribe", "unsubscribe", "post"].includes(command.kind)
+ ? client.send(command)
+ : Promise.reject(
+ new Error("PLUGIN_SETTINGS_COMMAND_BLOCKED"),
+ );
+ if (command.kind === "fetch") command.body = undefined;
+ void work
+ .then((value) => {
+ client.assertCurrent();
+ // Package navigation keeps the lease but restarts bridge request IDs.
+ if (requestDocument !== documentEpoch.current) return;
+ webview.current?.injectJavaScript(
+ settingsInjection("__cindySettingsReceive", {
+ kind: "reply",
+ id: requestId,
+ ok: true,
+ value,
+ }),
+ );
+ })
+ .catch((error) => {
+ try {
+ client.assertCurrent();
+ if (requestDocument !== documentEpoch.current) return;
+ let reportedToPage = false;
+ const page = webview.current;
+ if (page) {
+ try {
+ page.injectJavaScript(
+ settingsInjection("__cindySettingsReceive", {
+ kind: "reply",
+ id: requestId,
+ ok: false,
+ }),
+ );
+ reportedToPage = true;
+ } catch {
+ /* A live native recovery surface remains available if injection fails. */
+ }
+ }
+ latest.current.onError?.(
+ new Error(
+ error instanceof Error &&
+ /^[A-Z_]{1,80}$/.test(error.message)
+ ? error.message
+ : "PLUGIN_SETTINGS_UNAVAILABLE",
+ ),
+ error &&
+ typeof error === "object" &&
+ error.settingsOutcome === "unknown"
+ ? "unknown"
+ : command.kind === "fetch" && command.method === "GET"
+ ? "read"
+ : "operation",
+ reportedToPage,
+ );
+ } catch {
+ /* Stale page cannot receive results. */
+ }
+ })
+ .finally(() => {
+ if (!authorization || !browserBackground.current) return;
+ try {
+ client.assertCurrent();
+ // Native preview servers stop on background. Reopen from Host facts
+ // after authorization settles, without copying drafts or replaying writes.
+ browserBackground.current = false;
+ setResourceEpoch((value) => value + 1);
+ } catch {
+ /* A replaced lease cannot reopen its old page. */
+ }
+ });
+ } catch {
+ /* Untrusted page messages never reach a general-purpose invoke. */
+ }
+ }}
+ />
+ </View>
+ );
+}
+const styles = StyleSheet.create({
+ card: {
+ padding: spacing.lg,
+ overflow: "hidden",
+ borderRadius: radius.container,
+ borderWidth: StyleSheet.hairlineWidth,
+ },
+});
diff --git a/apps/mobile/src/plugins/PluginSetupNativeForm.tsx b/apps/mobile/src/plugins/PluginSetupNativeForm.tsx
index 5b641de2d7..b3e6eec73a 100644
--- a/apps/mobile/src/plugins/PluginSetupNativeForm.tsx
+++ b/apps/mobile/src/plugins/PluginSetupNativeForm.tsx
@@ -1,3 +1,4 @@
+import { receiveMobilePluginOauthLoopback } from "./pluginOauthLoopbackNative";
import { useEffect, useRef, useState } from "react";
import {
ActivityIndicator,
@@ -163,6 +164,18 @@ export default function PluginSetupNativeForm({
? { inputConnection: { host, token: secret } }
: {}),
clearInput: clear,
+ receiveLoopback: async (request, expiresAt, signal) => {
+ assertCurrent();
+ const accepted = await new Promise<boolean>((resolve) => Alert.alert(
+ t("plugins.connectAccount"), new URL(request.url).hostname,
+ [{ text: t("plugins.cancel"), style: "cancel", onPress: () => resolve(false) }, { text: t("plugins.open"), onPress: () => resolve(true) }],
+ { cancelable: false },
+ ));
+ assertCurrent();
+ if (!accepted || Date.now() >= expiresAt) throw new Error("PLUGIN_OAUTH_CLOSED");
+ return receiveMobilePluginOauthLoopback(request, expiresAt, assertCurrent, signal);
+ },
+ isForeground: () => AppState.currentState === "active",
pause: async () => {
await new Promise((resolve) => setTimeout(resolve, 600));
while (AppState.currentState !== "active") {
@@ -213,7 +226,8 @@ export default function PluginSetupNativeForm({
e.message === "PLUGIN_AUTHORIZATION_IDENTITY_CHANGED";
const computerCallback =
e instanceof Error &&
- e.message === "PLUGIN_AUTHORIZATION_COMPUTER_CALLBACK";
+ ["PLUGIN_AUTHORIZATION_COMPUTER_CALLBACK", "PLUGIN_OAUTH_CALLBACK_UNSUPPORTED"].includes(e.message);
+ const updateRequired = e instanceof Error && e.message === "PLUGIN_OAUTH_UPDATE_REQUIRED";
Alert.alert(
identityChanged
? t("plugins.identityChanged")
@@ -224,7 +238,7 @@ export default function PluginSetupNativeForm({
? t("plugins.identityChangedHint")
: computerCallback
? t("plugins.computerAuthorizationHint")
- : t("plugins.authorizationCheckHint"),
+ : updateRequired ? t("plugins.oauthUpdateRequired") : t("plugins.authorizationCheckHint"),
);
}
} finally {
diff --git a/apps/mobile/src/plugins/PluginsScreen.tsx b/apps/mobile/src/plugins/PluginsScreen.tsx
index afe018b88a..50c0511b8c 100644
--- a/apps/mobile/src/plugins/PluginsScreen.tsx
+++ b/apps/mobile/src/plugins/PluginsScreen.tsx
@@ -67,6 +67,16 @@ import {
getMobileAuthOwner,
isMobileAuthOwnerCurrent,
} from "@/auth/authOwnerGeneration";
+import { PluginOriginalSettings } from "./PluginOriginalSettings";
+import { usePluginManagement } from "./usePluginManagement";
+import { PluginManagementMenu } from "./PluginManagementMenu";
+import { PluginManagementConfirmation } from "./PluginManagementConfirmation";
+import { PluginNotice } from "./PluginNotice";
+import { createPluginManagementClient } from "./pluginManagementClient";
+import {
+ marketItemMatchesPlugin,
+ pluginApprovalToken,
+} from "./pluginManagementTypes";
import { pluginDetailModel } from "./pluginDetailModel";
import { PluginDirectoryView } from "./PluginDirectoryView";
import { PluginDetailView } from "./PluginDetailView";
@@ -86,7 +96,7 @@ function PluginDirectory() {
const { t, i18n } = useTranslation();
const { preview } = useLocalSearchParams<{ preview?: string }>();
const previewSelection = useRef<string | undefined>(undefined);
- const { invoke } = useDeviceLink();
+ const { invoke, connectionEpoch } = useDeviceLink();
const { colors } = useTheme(),
styles = useThemedStyles(makeStyles);
const { width } = useWindowDimensions();
@@ -111,10 +121,23 @@ function PluginDirectory() {
const directoryLoading = Boolean(devices.loading || list.loading);
const [deviceId, setDeviceId] = useState("");
const [query, setQuery] = useState("");
+ const [settingsNotice, setSettingsNotice] = useState("");
+ const transientScope = useRef("");
const [selected, setSelected] = useState<{
row: HostedRemoteCollectionItem;
surface?: PluginPageSurface;
}>();
+ const noticeScope = JSON.stringify([
+ selected?.row.key,
+ selected?.surface,
+ auth.accountGeneration,
+ connectionEpoch,
+ focused,
+ ]);
+ const showSettingsNotice = (notice: string) => {
+ transientScope.current = noticeScope;
+ setSettingsNotice(notice);
+ };
const [detailOpen, setDetailOpen] = useState(false);
const [detail, setDetail] = useState<RemoteResource>();
const [detailLoading, setDetailLoading] = useState(false);
@@ -125,6 +148,53 @@ function PluginDirectory() {
const enableLock = useRef(false);
const [taskPicker, setTaskPicker] = useState(false);
const [pageTitle, setPageTitle] = useState("");
+ const liveSelection = useRef({
+ epoch: connectionEpoch,
+ key: selected?.row.key,
+ focused,
+ online: selected ? list.isOnline(selected.row.host) : false,
+ });
+ liveSelection.current = {
+ epoch: connectionEpoch,
+ key: selected?.row.key,
+ focused,
+ online: selected
+ ? targets.some((host) => host.deviceId === selected.row.host.deviceId) &&
+ list.isOnline(selected.row.host)
+ : false,
+ };
+ const managementHost = selected?.row.host;
+ const management = usePluginManagement(
+ managementHost?.deviceId,
+ !!managementHost &&
+ targets.some((host) => host.deviceId === managementHost.deviceId) &&
+ list.isOnline(managementHost),
+ focused,
+ selected?.row.key,
+ );
+ const liveManagement = useRef(management.controller);
+ liveManagement.current = management.controller;
+ const managed = management.state?.snapshot?.ghosts.find(
+ (plugin) => plugin.instanceKey === selected?.row.item.ref.id,
+ );
+ const marketItem = managed
+ ? management.state?.snapshot?.market.items.find((item) =>
+ marketItemMatchesPlugin(item, managed),
+ )
+ : undefined;
+ const managementPending =
+ !!management.state &&
+ (management.state.busy ||
+ ["running", "confirmation", "unknown"].includes(
+ management.state.outcome,
+ ));
+ const managementAvailable =
+ management.state?.capability === "supported" &&
+ !management.state.errorCode &&
+ !!management.state.snapshot &&
+ management.state.online &&
+ !managementPending;
+
const searchVisible = Platform.OS === "ios" && (!selected || wide);
const latestQuery = useRef(query);
latestQuery.current = query;
@@ -166,7 +236,19 @@ function PluginDirectory() {
);
useEffect(() => {
setPageTitle("");
- }, [selected?.row.key, selected?.surface]);
+ setSettingsNotice("");
+ }, [
+ selected?.row.key,
+ selected?.surface,
+ auth.accountGeneration,
+ connectionEpoch,
+ focused,
+ ]);
+ useEffect(() => {
+ if (!settingsNotice) return;
+ const timer = setTimeout(() => setSettingsNotice(""), 4000);
+ return () => clearTimeout(timer);
+ }, [settingsNotice]);
const pageBack = useRef<(() => void) | null>(null);
const registerBack = useCallback((handler: (() => void) | null) => {
pageBack.current = handler;
@@ -246,6 +328,11 @@ function PluginDirectory() {
),
recent,
);
+ const refreshDirectory = async () => {
+ devices.refresh();
+ await management.controller?.reconcile();
+ await list.refresh();
+ };
const showDetail = async (row: HostedRemoteCollectionItem) => {
const generation = ++detailGeneration.current,
owner = getMobileAuthOwner();
@@ -372,15 +459,39 @@ function PluginDirectory() {
},
[router, selected],
);
- const selectDevice = () =>
+ const selectDirectoryDevice = (id: string) => {
+ if (
+ selected &&
+ id !== deviceId &&
+ id && id !== selected.row.host.deviceId
+ ) {
+ detailGeneration.current += 1;
+ setSelected(undefined);
+ setDetail(undefined);
+ setSettingsOpen(false);
+ }
+ setDeviceId(id);
+ };
+ const selectDevice = () => {
+ const generation = detailGeneration.current;
+ const select = (id: string) => {
+ if (
+ generation !== detailGeneration.current ||
+ !liveSelection.current.focused ||
+ !isMobileAuthOwnerCurrent(recentOwner)
+ )
+ return;
+ selectDirectoryDevice(id);
+ };
Alert.alert(t("plugins.computer"), undefined, [
- { text: t("plugins.allComputers"), onPress: () => setDeviceId("") },
+ { text: t("plugins.allComputers"), onPress: () => select("") },
...targets.map((host) => ({
text: host.deviceName,
- onPress: () => setDeviceId(host.deviceId),
+ onPress: () => select(host.deviceId),
})),
{ text: t("plugins.cancel"), style: "cancel" },
]);
+ };
const icon = (row: HostedRemoteCollectionItem) => {
const uri = row.item.display.avatar?.value;
return uri &&
@@ -455,17 +566,14 @@ function PluginDirectory() {
<PluginDirectoryView
targets={targets}
deviceId={deviceId}
- onDeviceChange={setDeviceId}
+ onDeviceChange={selectDirectoryDevice}
query={query}
items={items}
selectedKey={wide ? selected?.row.key : undefined}
loading={directoryLoading}
error={listFailed}
isOnline={(row) => list.isOnline(row.host)}
- onRefresh={async () => {
- devices.refresh();
- await list.refresh();
- }}
+ onRefresh={refreshDirectory}
onOpen={open}
onDetail={(row) => {
void showDetail(row);
@@ -483,8 +591,7 @@ function PluginDirectory() {
<RefreshControl
refreshing={list.refreshing}
onRefresh={() => {
- devices.refresh();
- void list.refresh();
+ void refreshDirectory();
}}
tintColor={colors.textSecondary}
/>
@@ -631,6 +738,169 @@ function PluginDirectory() {
detailFailed || demoScenario?.state === "loadFailed",
)
: undefined;
+ // One bounded read per target/connection resolves uncertain facts without replacing the author page.
+ const uncertainFactsRead = useRef<string | undefined>(undefined);
+ const uncertainConfiguration = model?.status === "setupUnknown" || model?.configuration?.items.some((item) => item.state === "unknown");
+ useEffect(() => {
+ if (!uncertainConfiguration || !selected || !focused || !online || detailLoading || detailFailed) return;
+ const row = selected.row, generation = detailGeneration.current, owner = getMobileAuthOwner(), epoch = connectionEpoch;
+ const key = JSON.stringify([row.key, auth.accountGeneration, connectionEpoch]);
+ if (uncertainFactsRead.current === key) return;
+ uncertainFactsRead.current = key;
+ void getRemoteResource(invoke, row.host, row.item.ref, i18n.language, ["plugin-capabilities"]).then((resource) => {
+ if (generation === detailGeneration.current && liveSelection.current.epoch === epoch && isMobileAuthOwnerCurrent(owner) && liveSelection.current.key === row.key && liveSelection.current.focused && liveSelection.current.online) setDetail(resource);
+ }).catch(() => { /* Existing author page stays usable; an uncertain background read needs no second notice. */ });
+ }, [uncertainConfiguration, selected?.row.key, focused, online, detailLoading, detailFailed, connectionEpoch, auth.accountGeneration]);
+ const renderedGeneration = detailGeneration.current;
+ const manageAction = async (action: string) => {
+ if (
+ !managementAvailable ||
+ !selected ||
+ !management.controller ||
+ liveManagement.current !== management.controller ||
+ renderedGeneration !== detailGeneration.current ||
+ liveSelection.current.key !== selected.row.key ||
+ !liveSelection.current.focused ||
+ !liveSelection.current.online
+ )
+ return;
+ const controller = management.controller,
+ row = selected.row,
+ expectedGeneration = detailGeneration.current,
+ owner = getMobileAuthOwner();
+ const current = () =>
+ expectedGeneration === detailGeneration.current &&
+ liveManagement.current === controller &&
+ isMobileAuthOwnerCurrent(owner) &&
+ liveSelection.current.key === row.key &&
+ liveSelection.current.focused &&
+ liveSelection.current.online;
+ const reportPreflightFailure = () => {
+ const state = controller.getState();
+ if (current() && state.outcome === "failed" && !state.operationId)
+ Alert.alert(t("plugins.notice.title.managementFailed"));
+ };
+ if (action === "uninstall" && managed) {
+ const plugin = managed;
+ Alert.alert(
+ t("plugins.management.uninstallTitle", { name: plugin.manifest.name }),
+ t("plugins.management.uninstallBody", { device: row.host.deviceName }),
+ [
+ { text: t("plugins.cancel"), style: "cancel" },
+ {
+ text: t("plugins.management.uninstall"),
+ style: "destructive",
+ onPress: async () => {
+ if (!current()) return;
+ await controller.uninstall(plugin);
+ reportPreflightFailure();
+ },
+ },
+ ],
+ );
+ } else if (action === "update" && marketItem && managed) {
+ const displayed = marketItem;
+ try {
+ const client = createPluginManagementClient({
+ invoke,
+ deviceId: row.host.deviceId,
+ isCurrent: current,
+ });
+ const next = await client.detail(displayed.pluginId);
+ if (!current()) return;
+ if (next.releaseId !== displayed.releaseId) {
+ await controller.refresh();
+ if (current()) Alert.alert(t("plugins.management.releaseChanged"));
+ return;
+ }
+ await controller.install(next, managed);
+ reportPreflightFailure();
+ } catch {
+ if (current()) Alert.alert(t("plugins.management.state.readFailed"));
+ }
+ }
+ };
+ const managementActions = [
+ ...(marketItem?.installState === "update-available" && managed
+ ? [
+ {
+ id: "update",
+ title: t("plugins.management.update") + " · " + marketItem.version,
+ disabled: !managementAvailable,
+ },
+ ]
+ : []),
+ ...(managed && !managed.builtin
+ ? [
+ {
+ id: "uninstall",
+ title: t("plugins.management.uninstall"),
+ destructive: true,
+ disabled: !managementAvailable,
+ },
+ ]
+ : []),
+ ];
+ const completedOperation = useRef<string | undefined>(undefined);
+ useEffect(() => {
+ const state = management.state;
+ if (
+ !state ||
+ state.outcome !== "succeeded" ||
+ !state.operationId ||
+ completedOperation.current === state.operationId
+ )
+ return;
+ completedOperation.current = state.operationId;
+ const row = selected?.row,
+ generation = detailGeneration.current,
+ owner = getMobileAuthOwner();
+ void list.refresh();
+ const controller = management.controller;
+ void controller?.refresh().then(() => {
+ if (
+ !row ||
+ liveManagement.current !== controller ||
+ generation !== detailGeneration.current ||
+ !isMobileAuthOwnerCurrent(owner)
+ )
+ return;
+ const refreshed = controller.getState();
+ if (!refreshed || refreshed.errorCode || !refreshed.online) return;
+ const snapshot = refreshed.snapshot;
+ const plugin = snapshot?.ghosts.find(
+ (item) => item.instanceKey === row.item.ref.id,
+ );
+ if (plugin)
+ void showDetail({
+ ...row,
+ key: JSON.stringify([
+ row.host.deviceId,
+ "plugins",
+ "plugin",
+ plugin.instanceKey,
+ ]),
+ item: {
+ ...row.item,
+ ref: { ...row.item.ref, id: plugin.instanceKey },
+ },
+ });
+ else if (snapshot) {
+ detailGeneration.current += 1;
+ setSelected(undefined);
+ setDetail(undefined);
+ }
+ });
+ }, [management.state?.outcome, management.state?.operationId]);
+ const failedOperationNotice = useRef<string | undefined>(undefined);
+ useEffect(() => {
+ const state = management.state;
+ if (!focused || !selected || state?.outcome !== "failed" || !state.operationId) return;
+ const key = JSON.stringify([selected.row.key, auth.accountGeneration, connectionEpoch, state.operationId]);
+ if (failedOperationNotice.current === key) return;
+ failedOperationNotice.current = key;
+ Alert.alert(t("plugins.notice.title.managementFailed"));
+ }, [management.state?.outcome, management.state?.operationId, selected?.row.key, focused, auth.accountGeneration, connectionEpoch]);
const newTask = () => {
if (!selected || !model || busy || !online || !detail || !enabled) return;
if (!model.canUseTasks) return;
@@ -646,6 +916,10 @@ function PluginDirectory() {
},
});
};
+ const originalSettings =
+ !!managed &&
+ !!model?.hasSettings &&
+ management.state?.snapshot?.settingsPage === true;
const resolveStatus = () => {
if (!selected || !model || busy) return;
switch (model.statusAction) {
@@ -653,6 +927,7 @@ function PluginDirectory() {
router.push("/devices/manage");
break;
case "retry":
+ void management.controller?.reconcile();
void showDetail(selected.row);
break;
case "enable":
@@ -660,16 +935,19 @@ function PluginDirectory() {
break;
case "reconnect":
case "settings":
- Alert.alert(t("plugins.detail.computerSettings"));
+ if (originalSettings) setSettingsOpen(true);
+ else Alert.alert(t("plugins.detail.computerSettings"));
break;
}
};
+ const noticeOwner = getMobileAuthOwner();
const detailView =
selected && model ? (
<PluginDetailView
row={selected.row}
enabled={enabled}
- busy={busy || detailLoading}
+ busy={busy || detailLoading || managementPending}
+ statusRecoveryBusy={busy || detailLoading}
online={online}
model={model}
previewLabel={
@@ -677,6 +955,33 @@ function PluginDirectory() {
? t("plugins.demo.hint") + " · " + demoScenario.label
: undefined
}
+ settingsContent={
+ originalSettings && managed ? (
+ <PluginOriginalSettings
+ key={JSON.stringify([
+ selected.row.host.deviceId,
+ managed.instanceKey,
+ pluginApprovalToken(managed),
+ connectionEpoch,
+ ])}
+ identity={{
+ deviceId: selected.row.host.deviceId,
+ instanceId: managed.instanceKey,
+ expectedInstalledApproval: pluginApprovalToken(managed),
+ }}
+ active={focused && online && detailOpen && !managementPending}
+ onNotice={(notice) => {
+ if (
+ renderedGeneration === detailGeneration.current &&
+ liveSelection.current.key === selected.row.key &&
+ liveSelection.current.focused &&
+ isMobileAuthOwnerCurrent(noticeOwner)
+ )
+ showSettingsNotice(notice);
+ }}
+ />
+ ) : undefined
+ }
settingsOpen={settingsOpen}
onEnabledChange={(value) => {
if (model.canToggle) void enable(value);
@@ -686,7 +991,6 @@ function PluginDirectory() {
onChooseTask={() => {
if (model.canUseTasks && !busy) setTaskPicker(true);
}}
- onSettings={() => setSettingsOpen(true)}
onResolveStatus={resolveStatus}
/>
) : (
@@ -706,6 +1010,17 @@ function PluginDirectory() {
: t("plugins.title")
}
onBack={goBack}
+ rightToolbar={
+ Platform.OS === "ios" &&
+ selected &&
+ !(selected.surface && !detailOpen) ? (
+ <PluginManagementMenu
+ nativeToolbar
+ actions={managementActions}
+ onAction={(action) => void manageAction(action)}
+ />
+ ) : undefined
+ }
right={
selected?.surface && !detailOpen ? (
<Pressable
@@ -717,6 +1032,13 @@ function PluginDirectory() {
>
<Info size={iconSize.md} color={colors.textPrimary} />
</Pressable>
+ ) : selected ? (
+ Platform.OS === "ios" ? undefined : (
+ <PluginManagementMenu
+ actions={managementActions}
+ onAction={(action) => void manageAction(action)}
+ />
+ )
) : undefined
}
/>
@@ -745,6 +1067,19 @@ function PluginDirectory() {
}}
/>
) : null}
+ {selected && management.state && management.controller ? (
+ <PluginManagementConfirmation
+ key={JSON.stringify([
+ selected.row.key,
+ auth.accountGeneration,
+ connectionEpoch,
+ ])}
+ state={management.state}
+ controller={management.controller}
+ deviceName={selected.row.host.deviceName}
+ active={focused && online && detailOpen}
+ />
+ ) : null}
<View style={styles.layout}>
{wide || !selected ? directory : null}
{wide || selected ? (
@@ -765,6 +1100,14 @@ function PluginDirectory() {
</View>
) : null}
{!selected?.surface || detailOpen ? detailView : null}
+ {settingsNotice && transientScope.current === noticeScope ? (
+ <View pointerEvents="none" style={styles.toast}>
+ <PluginNotice
+ testID="plugins.transientNotice"
+ title={settingsNotice}
+ />
+ </View>
+ ) : null}
</View>
) : null}
</View>
@@ -773,6 +1116,12 @@ function PluginDirectory() {
}
const makeStyles = (c: ThemeColors) =>
StyleSheet.create({
+ toast: {
+ position: "absolute",
+ top: spacing.md,
+ left: spacing.lg + spacing.xs,
+ right: spacing.lg + spacing.xs,
+ },
hidden: { display: "none" },
root: { flex: 1, backgroundColor: c.surface },
layout: { flex: 1, flexDirection: "row" },
diff --git a/apps/mobile/src/plugins/pluginAuthorizationController.ts b/apps/mobile/src/plugins/pluginAuthorizationController.ts
index cd4d2a51ea..628dd72e26 100644
--- a/apps/mobile/src/plugins/pluginAuthorizationController.ts
+++ b/apps/mobile/src/plugins/pluginAuthorizationController.ts
@@ -8,6 +8,8 @@ import {
parsePluginConnectionOffer,
parsePluginConnectionInput,
parsePluginAuthorizationOffer,
+ parsePluginAuthorizationRequest,
+ type PluginOauthCallback,
parsePluginDeviceOffer,
parseInputHandoffOffer,
parseInputHandoffPresentation,
@@ -46,9 +48,11 @@ export async function runMobilePluginAuthorization(deps: {
code: string | undefined,
expiresAt: number,
): Promise<void>;
+ receiveLoopback?(request: { url: string; callbackUrl: string; state: string }, expiresAt: number, signal: AbortSignal): Promise<PluginOauthCallback>;
clearInput(): void;
assertCurrent(): void;
pause(): Promise<void>;
+ isForeground?(): boolean;
now?(): number;
}): Promise<void> {
const now = deps.now ?? Date.now,
@@ -105,6 +109,35 @@ export async function runMobilePluginAuthorization(deps: {
);
if (result.accepted !== true) throw new Error("OAUTH_BRIDGE_UNAVAILABLE");
};
+ const receiveLoopback = async (request: { url: string; callbackUrl: string; state: string }) => {
+ if (!deps.receiveLoopback) throw new Error("PLUGIN_OAUTH_UPDATE_REQUIRED");
+ const abort = new AbortController();
+ let checking = false;
+ const monitor = setInterval(() => {
+ if (checking || deps.isForeground?.() === false) return;
+ checking = true;
+ void (async () => {
+ try {
+ deps.assertCurrent();
+ const status = object(await deps.invoke({ op: "status", id: id! }));
+ deps.assertCurrent();
+ if (!["authorizing", "starting"].includes(String(status.phase))) abort.abort();
+ } catch { if (deps.isForeground?.() !== false) abort.abort(); }
+ finally { checking = false; }
+ })();
+ }, 600);
+ try {
+ const value = await deps.receiveLoopback(request, deadline, abort.signal);
+ while (deps.isForeground?.() === false) {
+ deps.assertCurrent();
+ if (now() >= deadline) throw new Error("PLUGIN_OAUTH_CLOSED");
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ }
+ deps.assertCurrent();
+ if (now() >= deadline) throw new Error("PLUGIN_OAUTH_CLOSED");
+ return value;
+ } finally { clearInterval(monitor); abort.abort(); }
+ };
while (now() < deadline) {
await deps.pause();
deps.assertCurrent();
@@ -179,9 +212,12 @@ export async function runMobilePluginAuthorization(deps: {
if (caps.authorizationV1 !== true)
throw new Error("OAUTH_BRIDGE_UNAVAILABLE");
const offer = parsePluginAuthorizationOffer(raw);
- // A computer loopback callback cannot be reinterpreted as the phone's localhost.
- if (offer.request.kind === "loopback")
- throw new Error("PLUGIN_AUTHORIZATION_COMPUTER_CALLBACK");
+ if (offer.request.kind === "loopback") {
+ const value = await receiveLoopback(offer.request);
+ await deliver({ ...value, state: offer.state });
+ opened = true;
+ continue;
+ }
await deps.showAuthorization(
offer.request.url,
offer.request.kind === "device" ? offer.request.userCode : undefined,
@@ -199,7 +235,6 @@ export async function runMobilePluginAuthorization(deps: {
);
await deliver({ kind: "device-opened", state: offer.state });
} else {
- // Legacy PKCE loopback offers need the computer's callback listener.
oauthExact(raw, [
"authorizeUrl",
"callbackUrl",
@@ -207,7 +242,9 @@ export async function runMobilePluginAuthorization(deps: {
"corsOrigins",
"state",
]);
- throw new Error("PLUGIN_AUTHORIZATION_COMPUTER_CALLBACK");
+ const request = parsePluginAuthorizationRequest({ kind: "loopback", url: raw.authorizeUrl, callbackUrl: raw.callbackUrl, state: raw.state });
+ if (request.kind !== "loopback") throw new Error("OAUTH_BRIDGE_UNAVAILABLE");
+ await deliver(await receiveLoopback(request));
}
opened = true;
}
diff --git a/apps/mobile/src/plugins/pluginConsentPresentation.ts b/apps/mobile/src/plugins/pluginConsentPresentation.ts
new file mode 100644
index 0000000000..ac28e657ca
--- /dev/null
+++ b/apps/mobile/src/plugins/pluginConsentPresentation.ts
@@ -0,0 +1,66 @@
+import type {
+ PluginManagementReceipt,
+ PluginPermissionItem,
+} from "./pluginManagementTypes";
+export function pluginConsentPresentation(
+ consent: NonNullable<PluginManagementReceipt["consent"]>,
+ t: (key: string, args?: Record<string, unknown>) => string,
+) {
+ const facts = consent.facts;
+ const permissions = (items: PluginPermissionItem[], prefix = "") =>
+ items.map((item) => ({
+ title:
+ (prefix ? t("plugins.management.permissions." + prefix) + " · " : "") +
+ t("plugins.management.permissions." + item.labelKey, {
+ ...item.labelArgs,
+ defaultValue: item.kind,
+ }),
+ detail: [
+ item.detailKey
+ ? t("plugins.management.permissions." + item.detailKey, {
+ ...item.detailArgs,
+ defaultValue: "",
+ })
+ : "",
+ item.detail,
+ ]
+ .filter(Boolean)
+ .join("\n\n"),
+ }));
+ return {
+ title: facts.name + " · " + facts.version,
+ identity: facts.ghostId,
+ origin: [
+ t("plugins.notice.consentOrigin." + consent.origin),
+ consent.originLabel,
+ t("plugins.notice.initiator." + consent.initiator),
+ consent.purpose ? t("plugins.notice.taskCapability") : "",
+ ]
+ .filter(Boolean)
+ .join(" · "),
+ version:
+ facts.kind === "update"
+ ? t("plugins.management.versionChange", {
+ previous: facts.previousVersion,
+ next: facts.version,
+ })
+ : undefined,
+ permissions:
+ facts.kind === "install"
+ ? permissions(facts.permissions)
+ : [
+ ...permissions(facts.added, "added"),
+ ...permissions(facts.removed, "removed"),
+ ],
+ unchanged:
+ facts.kind === "update"
+ ? t("plugins.management.permissions.unchanged", {
+ count: facts.unchangedCount,
+ })
+ : undefined,
+ oauth:
+ facts.kind === "update" && facts.builtinOauthClientChanged
+ ? t("plugins.management.oauthChanged")
+ : undefined,
+ };
+}
diff --git a/apps/mobile/src/plugins/pluginDetailModel.ts b/apps/mobile/src/plugins/pluginDetailModel.ts
index 6f7f56fa9f..fe98397bd5 100644
--- a/apps/mobile/src/plugins/pluginDetailModel.ts
+++ b/apps/mobile/src/plugins/pluginDetailModel.ts
@@ -18,7 +18,12 @@ export type PluginDetailStatus =
export interface PluginDetailModel {
details?: Array<{ key: string; title: string; value: string }>;
tools?: Array<{ name: string; description: string }>;
- permissions?: Array<{ title: string; description: string }>;
+ permissions?: Array<{
+ title: string;
+ description: string;
+ kind?: string;
+ labelKey?: string;
+ }>;
description?: string;
version?: string;
status?: PluginDetailStatus;
@@ -126,6 +131,12 @@ export function pluginDetailModel(
? capabilities.permissions.map((permission) => ({
title: permission.title,
description: permission.description,
+ kind:
+ typeof permission.kind === "string" ? permission.kind : undefined,
+ labelKey:
+ typeof permission.labelKey === "string"
+ ? permission.labelKey
+ : undefined,
}))
: undefined;
const details =
@@ -154,7 +165,8 @@ export function pluginDetailModel(
status,
statusAction,
taskUsable,
- canUseTasks: taskUsable && !status && usage?.runtimeIssue !== "fused",
+ // Setup facts guide configuration; they do not remove task entry for an enabled plugin.
+ canUseTasks: taskUsable && (!status || status === "setupRequired" || (status === "setupUnknown" && !!usage)) && usage?.runtimeIssue !== "fused",
canToggle:
online &&
!loading &&
diff --git a/apps/mobile/src/plugins/pluginDetailNotices.ts b/apps/mobile/src/plugins/pluginDetailNotices.ts
new file mode 100644
index 0000000000..85b6f2b1d5
--- /dev/null
+++ b/apps/mobile/src/plugins/pluginDetailNotices.ts
@@ -0,0 +1,17 @@
+import type { PluginDetailModel } from "./pluginDetailModel";
+/** Status belongs to the smallest surface it blocks; independent scopes can coexist. */
+export function pluginDetailNotices(model: PluginDetailModel) {
+ const fresh = !["offline", "loadFailed", "loading"].includes(
+ model.status ?? "",
+ );
+ const top = ["offline", "loadFailed", "retired", "approvalRequired"].includes(
+ model.status ?? "",
+ )
+ ? model.status === "approvalRequired" && model.builtin
+ ? "builtinRecovery"
+ : model.status
+ : fresh && model.runtimeIssue === "fused"
+ ? "fused"
+ : undefined;
+ return { top, loading: model.status === "loading" };
+}
diff --git a/apps/mobile/src/plugins/pluginManagementClient.ts b/apps/mobile/src/plugins/pluginManagementClient.ts
new file mode 100644
index 0000000000..8d2db7fa1f
--- /dev/null
+++ b/apps/mobile/src/plugins/pluginManagementClient.ts
@@ -0,0 +1,124 @@
+import { REMOTE_RESOURCE_INVOKE_CHANNEL, REMOTE_RESOURCE_MANIFEST_CHANNEL } from '@cindy/device-link';
+import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
+import { isRemoteResourcesUnsupported } from '@/device-link/remoteResources';
+import {
+ isBoundedPluginResponse, marketItemMatchesPlugin, parsePluginManagementDetail,
+ parsePluginManagementReceipt, parsePluginManagementSnapshot, pluginApprovalToken,
+ type ManagedMarketDetail, type ManagedPlugin,
+} from './pluginManagementTypes';
+
+/** Use DeviceLinkContext.invoke directly; preserve its final, synchronous queue fence. */
+export type PluginManagementInvoke = <T = unknown>(deviceId: string, channel: string, args?: unknown[],
+ options?: { preSend?: () => void; background?: boolean }) => Promise<T>;
+export interface PluginManagementClientOptions {
+ invoke: PluginManagementInvoke;
+ deviceId: string;
+ /** Target/view/connection fence, in addition to the built-in account-owner fence. */
+ isCurrent?: () => boolean;
+}
+export type PluginManagementBegin = { operationId: string } & (
+ | { kind: 'install'; detail: ManagedMarketDetail; installed?: ManagedPlugin }
+ | { kind: 'uninstall' | 'enable' | 'disable'; installed: ManagedPlugin }
+);
+export class PluginManagementRequestError extends Error {
+ constructor(message: string, readonly outcomeUnknown = false) { super(message); }
+}
+export function pluginManagementErrorCode(error: unknown): string {
+ if (error && typeof error === 'object' && 'code' in error && typeof error.code === 'string') return error.code;
+ return error instanceof Error ? error.message : 'REQUEST_FAILED';
+}
+const descriptor = { protocolVersion: 1, primitives: ['status', 'markdown', 'action', 'form', 'list'] };
+const validId = (id: string, max = 128) => typeof id === 'string' && id.length > 0 && id.length <= max && !id.includes('\0');
+const localError = (code: string): never => { throw new PluginManagementRequestError(code); };
+/** Input budget is UTF-8 bytes, matching the existing Host resource invoke contract. */
+function utf8Bytes(value: string): number {
+ let bytes = 0;
+ for (const char of value) { const code = char.codePointAt(0)!; bytes += code <= 0x7f ? 1 : code <= 0x7ff ? 2 : code <= 0xffff ? 3 : 4; }
+ return bytes;
+}
+export function createPluginManagementClient(options: PluginManagementClientOptions) {
+ const owner = getMobileAuthOwner();
+ const isOwnerCurrent = () => !owner.switching && isMobileAuthOwnerCurrent(owner);
+ const isCurrent = () => isOwnerCurrent() && (options.isCurrent?.() ?? true);
+ async function call<T>(channel: string, payload: unknown, parse: (value: unknown) => T, mutation = false, guard?: () => boolean, cleanup = false): Promise<T> {
+ const requestCurrent = () => (cleanup ? isOwnerCurrent() : isCurrent()) && (!guard || guard());
+ const assertRequestCurrent = () => { if (!requestCurrent()) localError('PLUGIN_MANAGEMENT_STALE'); };
+ assertRequestCurrent();
+ try {
+ const response = await options.invoke(options.deviceId, channel, [payload], { preSend: assertRequestCurrent });
+ if (!requestCurrent()) throw new PluginManagementRequestError('PLUGIN_MANAGEMENT_STALE', mutation);
+ if (!isBoundedPluginResponse(response)) throw new Error('INVALID_RESPONSE');
+ return parse(response);
+ } catch (error) {
+ if (error instanceof PluginManagementRequestError) throw error;
+ throw new PluginManagementRequestError(pluginManagementErrorCode(error), mutation);
+ }
+ }
+ async function action<T>(name: string, input: Record<string, unknown>, parse: (value: unknown) => T, instance?: string, mutation = false, guard?: () => boolean, cleanup = false) {
+ if (!isBoundedPluginResponse(input)) return localError('INVALID_INPUT');
+ if (utf8Bytes(JSON.stringify(input)) > 64 * 1024) return localError('INPUT_TOO_LARGE');
+ return call(REMOTE_RESOURCE_INVOKE_CHANNEL, {
+ client: descriptor, collectionId: 'plugins', actionId: `management:${name}`, input,
+ ...(instance ? { resourceRef: { collectionId: 'plugins', kind: 'plugin', id: instance } } : {}),
+ }, (response) => {
+ if (!response || typeof response !== 'object' || !('result' in response)) throw new Error('INVALID_RESPONSE');
+ return parse(response.result);
+ }, mutation, guard, cleanup);
+ }
+ const receiptAction = (name: string, operationId: string, input: Record<string, unknown> = {}, mutation = false, guard?: () => boolean, cleanup = false) => {
+ if (!validId(operationId)) return localError('INVALID_INPUT');
+ return action(name, { operationId, ...input }, (v) => parsePluginManagementReceipt(v, operationId), undefined, mutation, guard, cleanup);
+ };
+ return {
+ deviceId: options.deviceId,
+ isCurrent,
+ async capability(): Promise<'supported' | 'unsupported'> {
+ try {
+ return await call(REMOTE_RESOURCE_MANIFEST_CHANNEL, { client: descriptor }, (value) => {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('INVALID_RESPONSE');
+ const data = value as { collections?: Array<{ id?: string; actions?: Array<{ id?: string; disabled?: boolean }> }> };
+ if (!Array.isArray(data.collections) || !data.collections.every((c) => c && typeof c.id === 'string'
+ && (c.actions === undefined || (Array.isArray(c.actions) && c.actions.every((a) => a && typeof a.id === 'string'))))) throw new Error('INVALID_RESPONSE');
+ return data.collections.some((c) => c.id === 'plugins' && c.actions?.some((a) => a.id === 'management:snapshot' && !a.disabled)) ? 'supported' : 'unsupported';
+ });
+ } catch (error) {
+ if (isRemoteResourcesUnsupported(error)) return 'unsupported';
+ throw error;
+ }
+ },
+ snapshot: () => action('snapshot', {}, parsePluginManagementSnapshot),
+ async detail(pluginId: string) {
+ if (!validId(pluginId, 1024)) return localError('INVALID_INPUT');
+ return action('market-detail', { pluginId }, (v) => {
+ const detail = parsePluginManagementDetail(v);
+ if (detail.pluginId !== pluginId) throw new Error('INVALID_RESPONSE');
+ return detail;
+ });
+ },
+ begin(request: PluginManagementBegin, guard?: () => boolean) {
+ if (!validId(request.operationId)) return localError('INVALID_INPUT');
+ const installed = request.installed;
+ if (installed && !validId(installed.instanceKey, 1024)) return localError('INVALID_INPUT');
+ const input: Record<string, unknown> = { operationId: request.operationId, kind: request.kind,
+ ...(installed ? { expectedInstalledApproval: pluginApprovalToken(installed) } : {}) };
+ if (request.kind === 'install') {
+ const detail = parsePluginManagementDetail(request.detail);
+ if (detail.installState === 'conflict' || (installed && !marketItemMatchesPlugin(detail, installed))
+ || (!installed && detail.installState !== 'not-installed')) return localError('PLUGIN_INSTALL_CHANGED');
+ input.pluginId = detail.pluginId;
+ input.expectedReleaseId = detail.releaseId;
+ if (detail.sourceType !== 'server') input.expectedManifest = detail.manifest;
+ }
+ return action('begin', input, (v) => parsePluginManagementReceipt(v, request.operationId), installed?.instanceKey, true, guard);
+ },
+ operation: (id: string) => receiptAction('operation', id),
+ answer(id: string, requestId: string, confirmed: boolean, guard?: () => boolean) {
+ if (!validId(requestId) || typeof confirmed !== 'boolean') return localError('INVALID_INPUT');
+ return receiptAction('answer', id, { requestId, confirmed }, true, guard);
+ },
+ cancel: (id: string, guard?: () => boolean) => receiptAction('cancel', id, {}, true, guard),
+ /** Controller teardown only: cancel the original Host operation after its view is gone. Owner fencing remains mandatory. */
+ async cancelForCleanup(id: string) { return receiptAction('cancel', id, {}, true, undefined, true); },
+ };
+}
+export type PluginManagementClient = ReturnType<typeof createPluginManagementClient>;
diff --git a/apps/mobile/src/plugins/pluginManagementController.ts b/apps/mobile/src/plugins/pluginManagementController.ts
new file mode 100644
index 0000000000..8ccacaceed
--- /dev/null
+++ b/apps/mobile/src/plugins/pluginManagementController.ts
@@ -0,0 +1,194 @@
+import { randomUUID } from 'expo-crypto';
+import { subscribeMobileAuthOwner } from '@/auth/authOwnerGeneration';
+import { PluginManagementRequestError, pluginManagementErrorCode,
+ type PluginManagementBegin, type PluginManagementClient } from './pluginManagementClient';
+import { marketItemMatchesPlugin, pluginApprovalToken, type ManagedMarketDetail, type ManagedPlugin,
+ type PluginManagementReceipt, type PluginManagementSnapshot } from './pluginManagementTypes';
+
+export interface PluginManagementState {
+ capability: 'unknown' | 'supported' | 'unsupported';
+ snapshot: PluginManagementSnapshot | null;
+ receipt: PluginManagementReceipt | null;
+ operationId: string | null;
+ busy: boolean;
+ online: boolean;
+ outcome: 'idle' | 'running' | 'confirmation' | 'succeeded' | 'cancelled' | 'failed' | 'unknown';
+ errorCode: string | null;
+}
+export interface PluginManagementControllerOptions {
+ online?: boolean;
+ onChange?: (state: PluginManagementState) => void;
+ /** Testable identity source; production uses the existing Expo UUID implementation. */
+ createOperationId?: () => string;
+ pollIntervalMs?: number;
+}
+type BeginIntent = PluginManagementBegin extends infer T ? T extends PluginManagementBegin ? Omit<T, 'operationId'> : never : never;
+const terminal = (receipt: PluginManagementReceipt) => ['succeeded', 'cancelled', 'failed'].includes(receipt.phase);
+
+/** One controller per selected Host/owner. Dispose when changing targets. No persisted writes or replay queue. */
+export function createPluginManagementController(client: PluginManagementClient, options: PluginManagementControllerOptions = {}) {
+ let state: PluginManagementState = { capability: 'unknown', snapshot: null, receipt: null,
+ operationId: null, busy: false, online: options.online ?? true, outcome: 'idle', errorCode: null };
+ let disposed = false, epoch = 0, refreshSequence = 0, snapshotSequence = 0;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let receiver: ManagedPlugin | undefined;
+ let installDetail: ManagedMarketDetail | undefined;
+ const listeners = new Set<() => void>();
+ const current = (token: number) => !disposed && epoch === token && client.isCurrent();
+ const publish = (patch: Partial<PluginManagementState>) => {
+ if (disposed) return;
+ state = { ...state, ...patch };
+ options.onChange?.(state);
+ listeners.forEach((listener) => listener());
+ };
+ const stopPolling = () => { if (timer !== undefined) clearTimeout(timer); timer = undefined; };
+ function schedulePoll() {
+ stopPolling();
+ if (state.online && state.operationId && state.outcome === 'running' && !state.busy && !disposed)
+ timer = setTimeout(() => { timer = undefined; void reconcile(); }, Math.max(250, options.pollIntervalMs ?? 1000));
+ }
+ function receiverCurrent(snapshot: PluginManagementSnapshot): boolean {
+ if (receiver) {
+ const live = snapshot.ghosts.find((g) => g.instanceKey === receiver!.instanceKey);
+ return !!live && live.manifest.id === receiver.manifest.id && live.namespace === receiver.namespace
+ && pluginApprovalToken(live) === pluginApprovalToken(receiver);
+ }
+ return !installDetail || !snapshot.ghosts.some((g) => marketItemMatchesPlugin(installDetail!, g));
+ }
+ async function readSnapshot(token: number) {
+ const sequence = ++snapshotSequence;
+ const snapshot = await client.snapshot();
+ if (current(token) && sequence === snapshotSequence) publish({ snapshot });
+ return snapshot;
+ }
+ async function acceptReceipt(receipt: PluginManagementReceipt, token: number) {
+ if (!current(token) || receipt.operationId !== state.operationId) return;
+ publish({ receipt, outcome: receipt.phase, busy: false, errorCode: receipt.errorCode ?? null });
+ if (terminal(receipt)) {
+ // A cancel racing commit must still show succeeded. Refresh facts, without changing the receipt on read failure.
+ stopPolling();
+ try { await readSnapshot(token); } catch (error) { if (current(token)) publish({ errorCode: pluginManagementErrorCode(error) }); }
+ } else schedulePoll();
+ }
+ async function refresh() {
+ if (disposed || !state.online || !client.isCurrent()) return;
+ const token = epoch, sequence = ++refreshSequence;
+ try {
+ const capability = await client.capability();
+ if (!current(token) || sequence !== refreshSequence) return;
+ publish({ capability, errorCode: null, ...(capability === 'unsupported' ? { snapshot: null } : {}) });
+ if (capability === 'supported') {
+ const snapshotToken = ++snapshotSequence;
+ const snapshot = await client.snapshot();
+ if (current(token) && sequence === refreshSequence && snapshotToken === snapshotSequence) publish({ snapshot });
+ }
+ } catch (error) {
+ if (current(token) && sequence === refreshSequence) publish({ errorCode: pluginManagementErrorCode(error) });
+ }
+ }
+ async function start(intent: BeginIntent) {
+ if (disposed || !client.isCurrent()) return;
+ if (!state.online) { publish({ errorCode: 'DEVICE_OFFLINE' }); return; }
+ if (state.busy || (state.operationId && !['succeeded', 'cancelled', 'failed'].includes(state.outcome))) return;
+ if (state.capability !== 'supported') { publish({ errorCode: state.capability === 'unsupported' ? 'PLUGIN_MANAGEMENT_UNSUPPORTED' : 'PLUGIN_MANAGEMENT_NOT_READY' }); return; }
+ const token = ++epoch;
+ let began = false;
+ publish({ busy: true, errorCode: null, operationId: null, receipt: null, outcome: 'idle' });
+ receiver = intent.installed;
+ installDetail = intent.kind === 'install' ? intent.detail : undefined;
+ try {
+ let request: BeginIntent = intent;
+ if (intent.kind === 'install') {
+ const detail = await client.detail(intent.detail.pluginId);
+ if (!current(token)) return;
+ if (detail.releaseId !== intent.detail.releaseId || detail.namespace !== intent.detail.namespace
+ || detail.sourceType !== intent.detail.sourceType || (detail.sourceType !== 'server'
+ && JSON.stringify(detail.manifest) !== JSON.stringify(intent.detail.manifest))) throw new Error('PLUGIN_RELEASE_CHANGED');
+ request = { ...intent, detail };
+ }
+ const snapshot = await readSnapshot(token);
+ if (!current(token)) return;
+ if (!receiverCurrent(snapshot)) throw new Error('PLUGIN_INSTALL_CHANGED');
+ const operationId = (options.createOperationId ?? randomUUID)();
+ publish({ operationId, outcome: 'running' });
+ began = true;
+ await acceptReceipt(await client.begin({ ...request, operationId }, () => current(token)
+ && state.online && !!state.snapshot && receiverCurrent(state.snapshot)), token);
+ } catch (error) {
+ if (!current(token)) return;
+ const unknown = began && (!(error instanceof PluginManagementRequestError) || error.outcomeUnknown);
+ publish({ busy: false, outcome: unknown ? 'unknown' : 'failed', errorCode: pluginManagementErrorCode(error) });
+ }
+ }
+ async function reconcile() {
+ if (disposed || !state.online || state.busy || !client.isCurrent()) return;
+ const id = state.operationId;
+ if (!id || ['succeeded', 'cancelled', 'failed'].includes(state.outcome)) { await refresh(); return; }
+ const token = epoch;
+ stopPolling();
+ publish({ busy: true });
+ try { await acceptReceipt(await client.operation(id), token); }
+ catch (error) {
+ if (!current(token)) return;
+ // NOT_FOUND can mean Host restart or its 15-minute memory expiry. Never infer rollback or send begin again.
+ publish({ busy: false, outcome: 'unknown', errorCode: pluginManagementErrorCode(error) });
+ try { await readSnapshot(token); } catch { /* Keep the original unknown-result reason. */ }
+ }
+ }
+ async function answer(confirmed: boolean) {
+ const receipt = state.receipt;
+ if (!receipt?.consent || state.outcome !== 'confirmation' || !state.online || state.busy || disposed || !client.isCurrent()) return;
+ const token = epoch;
+ publish({ busy: true, errorCode: null });
+ try {
+ if (confirmed) {
+ const snapshot = await readSnapshot(token);
+ if (!current(token)) return;
+ if (!receiverCurrent(snapshot)) throw new PluginManagementRequestError('PLUGIN_INSTALL_CHANGED');
+ }
+ if (current(token)) await acceptReceipt(await client.answer(receipt.operationId, receipt.consent.requestId, confirmed,
+ () => current(token) && state.online && (!confirmed || (!!state.snapshot && receiverCurrent(state.snapshot)))), token);
+ } catch (error) {
+ if (current(token)) publish({ busy: false, outcome: 'unknown', errorCode: pluginManagementErrorCode(error) });
+ }
+ }
+ async function cancel() {
+ const id = state.operationId;
+ if (!id || !state.online || disposed || !client.isCurrent() || ['succeeded', 'cancelled', 'failed'].includes(state.outcome)) return;
+ // Cancellation may race a queued/read request. Its newer result invalidates that request's late response.
+ const token = ++epoch;
+ stopPolling();
+ publish({ busy: true, errorCode: null });
+ try { await acceptReceipt(await client.cancel(id, () => current(token) && state.online), token); }
+ catch (error) { if (current(token)) publish({ busy: false, outcome: 'unknown', errorCode: pluginManagementErrorCode(error) }); }
+ }
+ const unsubscribeOwner = subscribeMobileAuthOwner(() => {
+ if (client.isCurrent()) return;
+ ++epoch; stopPolling();
+ publish({ capability: 'unknown', snapshot: null, receipt: null, operationId: null, busy: false, outcome: 'idle', errorCode: null });
+ });
+ return {
+ getState: () => state,
+ subscribe(listener: () => void) { listeners.add(listener); return () => { listeners.delete(listener); }; },
+ refresh,
+ install: (detail: ManagedMarketDetail, installed?: ManagedPlugin) => start({ kind: 'install', detail, installed }),
+ uninstall: (installed: ManagedPlugin) => start({ kind: 'uninstall', installed }),
+ setEnabled: (installed: ManagedPlugin, enabled: boolean) => start({ kind: enabled ? 'enable' : 'disable', installed }),
+ answer, cancel, reconcile,
+ setOnline(online: boolean) {
+ if (disposed || state.online === online) return;
+ ++epoch; stopPolling();
+ const active = state.operationId && !['succeeded', 'cancelled', 'failed'].includes(state.outcome);
+ publish({ online, busy: false, ...(active ? { outcome: 'unknown' as const } : {}) });
+ if (online) void reconcile();
+ },
+ dispose() {
+ if (disposed) return;
+ const id = state.operationId;
+ const active = id && !['succeeded', 'cancelled', 'failed'].includes(state.outcome);
+ disposed = true; ++epoch; stopPolling(); unsubscribeOwner(); listeners.clear();
+ if (active && state.online) void client.cancelForCleanup(id).catch(() => {});
+ },
+ };
+}
+export type PluginManagementController = ReturnType<typeof createPluginManagementController>;
diff --git a/apps/mobile/src/plugins/pluginManagementTypes.ts b/apps/mobile/src/plugins/pluginManagementTypes.ts
new file mode 100644
index 0000000000..3638d47b71
--- /dev/null
+++ b/apps/mobile/src/plugins/pluginManagementTypes.ts
@@ -0,0 +1,191 @@
+/** Mobile projection of the existing Host management contract. Never contains saved settings. */
+export interface ManagedPluginManifest {
+ [key: string]: unknown;
+ schemaVersion: 2 | 3;
+ id: string;
+ name: string;
+ version: string;
+ description?: string;
+ author?: string;
+}
+export type PluginApproval =
+ | { state: 'approved'; revision: string }
+ | { state: 'legacy-unapproved' | 'invalid' };
+export interface ManagedPlugin {
+ instanceKey: string;
+ namespace?: string | null;
+ namespaceState?: 'confirmed' | 'unconfirmed' | 'pending';
+ manifest: ManagedPluginManifest;
+ enabled: boolean;
+ approval: PluginApproval;
+ iconDataUrl?: string;
+ builtin?: boolean;
+}
+export interface ManagedMarketItem {
+ pluginId: string;
+ ghostId: string;
+ namespace?: string | null;
+ name: string;
+ description: string | null;
+ author: string | null;
+ scope: 'public' | 'organization' | 'personal';
+ organizationId: string | null;
+ defaultInstall: boolean;
+ releaseId: string;
+ version: string;
+ publishedAt: string;
+ icon: { mimeType: string; sha256: string; sizeBytes: number; url: string; expiresAt: string } | null;
+ installState: 'not-installed' | 'installed' | 'update-available' | 'conflict';
+ enabled: boolean | null;
+ sourceType: 'server' | 'git-market' | 'local-market';
+ sourceMarketName: string | null;
+ updateRequiresConsent?: true;
+}
+export interface ManagedMarketDetail extends ManagedMarketItem {
+ /** Keep the complete Host manifest for custom-market expectedManifest checks. */
+ manifest: ManagedPluginManifest;
+}
+export interface PluginManagementSnapshot {
+ version: 1;
+ ghosts: ManagedPlugin[];
+ market: {
+ items: ManagedMarketItem[];
+ unavailableReason: string | null;
+ customSourceNames: string[];
+ unavailableCustomSourceNames: string[];
+ organizationAccessError?: string | null;
+ };
+ settingsPage?: true;
+}
+export interface PluginPermissionItem {
+ key: string;
+ kind: string;
+ labelKey: string;
+ labelArgs?: Record<string, string>;
+ detail?: string;
+ detailKey?: string;
+ detailArgs?: Record<string, string>;
+}
+export type PluginConsentFacts = {
+ ghostId: string; name: string; version: string;
+} & (
+ | { kind: 'install'; permissions: PluginPermissionItem[] }
+ | { kind: 'update'; previousVersion: string; added: PluginPermissionItem[];
+ removed: PluginPermissionItem[]; unchangedCount: number; builtinOauthClientChanged: boolean }
+);
+export interface PluginManagementReceipt {
+ operationId: string;
+ phase: 'running' | 'confirmation' | 'succeeded' | 'cancelled' | 'failed';
+ errorCode?: string;
+ consent?: {
+ requestId: string;
+ initiator: 'user' | 'agent';
+ origin: 'market' | 'custom-market' | 'local-file' | 'forge';
+ originLabel?: string;
+ purpose?: 'task-capability';
+ facts: PluginConsentFacts;
+ };
+}
+
+const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
+const str = (v: unknown, max = 1024): v is string => typeof v === 'string' && v.length > 0 && v.length <= max && !v.includes('\0');
+const nullableString = (v: unknown): boolean => v === null || (typeof v === 'string' && v.length <= 32768);
+const oneOf = (v: unknown, values: string[]): boolean => typeof v === 'string' && values.includes(v);
+const optionalString = (v: unknown): boolean => v === undefined || typeof v === 'string';
+
+/** Bound foreign declarations before traversal; poison keys and non-JSON objects never reach consumers. */
+export function isBoundedPluginResponse(value: unknown): boolean {
+ let nodes = 50_000, chars = 8_000_000;
+ const visit = (v: unknown, depth: number): boolean => {
+ if (--nodes < 0 || depth > 24) return false;
+ if (typeof v === 'string') return (chars -= v.length) >= 0;
+ if (v === null || typeof v === 'boolean') return true;
+ if (typeof v === 'number') return Number.isFinite(v);
+ if (!v || typeof v !== 'object') return false;
+ if (!Array.isArray(v) && Object.getPrototypeOf(v) !== Object.prototype && Object.getPrototypeOf(v) !== null) return false;
+ return Object.entries(v).every(([key, child]) => {
+ chars -= key.length;
+ return chars >= 0 && !['__proto__', 'constructor', 'prototype'].includes(key) && visit(child, depth + 1);
+ });
+ };
+ return visit(value, 0);
+}
+function invalid(): never { throw new Error('INVALID_RESPONSE'); }
+function manifest(v: unknown): v is ManagedPluginManifest {
+ return record(v) && (v.schemaVersion === 2 || v.schemaVersion === 3) && str(v.id) && str(v.name) && str(v.version)
+ && optionalString(v.description) && optionalString(v.author);
+}
+function namespace(v: Record<string, unknown>): boolean {
+ return v.namespace === undefined || v.namespace === null || str(v.namespace);
+}
+const revision = (v: unknown): v is string => typeof v === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(v);
+function installed(v: unknown): v is ManagedPlugin {
+ return record(v) && str(v.instanceKey) && namespace(v) && manifest(v.manifest) && typeof v.enabled === 'boolean'
+ && (v.namespaceState === undefined || oneOf(v.namespaceState, ['confirmed', 'unconfirmed', 'pending']))
+ && record(v.approval) && (v.approval.state === 'approved' ? revision(v.approval.revision) : oneOf(v.approval.state, ['legacy-unapproved', 'invalid']))
+ && optionalString(v.iconDataUrl) && (v.builtin === undefined || typeof v.builtin === 'boolean');
+}
+function marketItem(v: unknown): v is ManagedMarketItem {
+ if (!record(v) || !str(v.pluginId) || !str(v.ghostId) || !str(v.releaseId) || !str(v.name) || !str(v.version)
+ || !namespace(v) || !nullableString(v.description) || !nullableString(v.author) || !nullableString(v.organizationId)
+ || !oneOf(v.scope, ['public', 'organization', 'personal']) || typeof v.defaultInstall !== 'boolean'
+ || typeof v.publishedAt !== 'string' || !oneOf(v.installState, ['not-installed', 'installed', 'update-available', 'conflict'])
+ || (v.enabled !== null && typeof v.enabled !== 'boolean') || !oneOf(v.sourceType, ['server', 'git-market', 'local-market'])
+ || !nullableString(v.sourceMarketName) || (v.updateRequiresConsent !== undefined && v.updateRequiresConsent !== true)) return false;
+ const icon = v.icon;
+ return icon === null || (record(icon) && str(icon.mimeType) && str(icon.sha256) && Number.isSafeInteger(icon.sizeBytes)
+ && (icon.sizeBytes as number) > 0 && str(icon.url, 32768) && str(icon.expiresAt));
+}
+function strings(v: unknown): v is string[] { return Array.isArray(v) && v.every((item) => str(item)); }
+function safeMarketItem<T extends ManagedMarketItem>(v: T): T {
+ // This target-local icon lookup key must never resolve against the controller's filesystem.
+ const safe = { ...v } as T & { customIconKey?: unknown };
+ delete safe.customIconKey;
+ return safe;
+}
+export function parsePluginManagementSnapshot(value: unknown): PluginManagementSnapshot {
+ if (!isBoundedPluginResponse(value) || !record(value) || value.version !== 1 || !Array.isArray(value.ghosts)
+ || !value.ghosts.every(installed) || !record(value.market) || !Array.isArray(value.market.items)
+ || !value.market.items.every(marketItem) || !nullableString(value.market.unavailableReason)
+ || !strings(value.market.customSourceNames) || !strings(value.market.unavailableCustomSourceNames)
+ || (value.market.organizationAccessError !== undefined && !nullableString(value.market.organizationAccessError))
+ || (value.settingsPage !== undefined && value.settingsPage !== true)
+ || new Set(value.ghosts.map((g) => g.instanceKey)).size !== value.ghosts.length) return invalid();
+ const data = value as unknown as PluginManagementSnapshot;
+ return { version: 1, ghosts: data.ghosts.map((g) => ({ ...g })), market: { ...data.market, items: data.market.items.map(safeMarketItem) },
+ ...(data.settingsPage ? { settingsPage: true } : {}) };
+}
+export function parsePluginManagementDetail(value: unknown): ManagedMarketDetail {
+ if (!isBoundedPluginResponse(value) || !marketItem(value) || !manifest((value as ManagedMarketDetail).manifest)) return invalid();
+ const detail = value as ManagedMarketDetail;
+ if (detail.manifest.id !== detail.ghostId || detail.manifest.version !== detail.version) return invalid();
+ return safeMarketItem(detail);
+}
+function permission(v: unknown): boolean {
+ if (!record(v) || !str(v.key) || !str(v.kind) || !str(v.labelKey) || !optionalString(v.detail) || !optionalString(v.detailKey)) return false;
+ return [v.labelArgs, v.detailArgs].every((args) => args === undefined || (record(args) && Object.values(args).every((value) => typeof value === 'string')));
+}
+export function parsePluginManagementReceipt(value: unknown, operationId: string): PluginManagementReceipt {
+ if (!isBoundedPluginResponse(value) || !record(value) || value.operationId !== operationId
+ || !oneOf(value.phase, ['running', 'confirmation', 'succeeded', 'cancelled', 'failed']) || !optionalString(value.errorCode)) return invalid();
+ if (value.consent !== undefined) {
+ const c = value.consent;
+ if (!record(c) || !str(c.requestId) || !oneOf(c.initiator, ['user', 'agent']) || !oneOf(c.origin, ['market', 'custom-market', 'local-file', 'forge'])
+ || !optionalString(c.originLabel) || (c.purpose !== undefined && c.purpose !== 'task-capability') || !record(c.facts)) return invalid();
+ const f = c.facts;
+ const permissions = (v: unknown) => Array.isArray(v) && v.every(permission);
+ if (!str(f.ghostId) || !str(f.name) || !str(f.version) || (f.kind === 'install' ? !permissions(f.permissions)
+ : f.kind !== 'update' || !str(f.previousVersion) || !permissions(f.added) || !permissions(f.removed)
+ || !Number.isSafeInteger(f.unchangedCount) || (f.unchangedCount as number) < 0 || typeof f.builtinOauthClientChanged !== 'boolean')) return invalid();
+ }
+ if (value.phase === 'confirmation' && !value.consent) return invalid();
+ return value as unknown as PluginManagementReceipt;
+}
+export function pluginApprovalToken(plugin: ManagedPlugin): string {
+ return plugin.approval.state === 'approved' ? `approved:${plugin.approval.revision}` : plugin.approval.state;
+}
+/** Never infer a namespace from a name/prefix. Legacy wire falls back only to the exact physical key. */
+export function marketItemMatchesPlugin(item: ManagedMarketItem, plugin: ManagedPlugin): boolean {
+ return item.ghostId === plugin.manifest.id && (item.namespace !== undefined && plugin.namespace !== undefined
+ ? item.namespace === plugin.namespace : plugin.instanceKey === item.ghostId);
+}
diff --git a/apps/mobile/src/plugins/pluginOauthLoopback.ts b/apps/mobile/src/plugins/pluginOauthLoopback.ts
new file mode 100644
index 0000000000..83026939f8
--- /dev/null
+++ b/apps/mobile/src/plugins/pluginOauthLoopback.ts
@@ -0,0 +1,88 @@
+import { parsePluginAuthorizationResult, type PluginOauthCallback } from "@cindy/device-link";
+export interface MobileLoopbackRequest { url: string; callbackUrl: string; state: string }
+export interface MobileLoopbackNative {
+ start(options: { id: string; callbackUrl: string; state: string; expiresAt: number }): Promise<void>;
+ wait(id: string): Promise<unknown>;
+ status(id: string): Promise<string>;
+ close(id: string): Promise<void>;
+}
+/** The receiver owns no provider credentials, browser cookies, verifier or token exchange. */
+export async function receivePluginOauthLoopback(input: {
+ request: MobileLoopbackRequest; expiresAt: number; signal?: AbortSignal;
+ native: MobileLoopbackNative | null; id: string; platform: string;
+ assertCurrent(): void;
+ openBrowser(url: string): Promise<{ type: string }>;
+ dismissBrowser(): Promise<void>;
+ onAppState(listener: (state: string) => void): () => void;
+ now?(): number;
+}): Promise<PluginOauthCallback> {
+ const now = input.now ?? Date.now;
+ const native = input.native;
+ if (!native) throw new Error("PLUGIN_OAUTH_UPDATE_REQUIRED");
+ const callback = new URL(input.request.callbackUrl);
+ if (callback.hostname !== "127.0.0.1" || callback.protocol !== "http:" ||
+ !callback.port || Number(callback.port) < 1024 || callback.username || callback.password ||
+ callback.search || callback.hash || !/^\/[A-Za-z0-9._~/-]*$/.test(callback.pathname))
+ throw new Error("PLUGIN_OAUTH_CALLBACK_UNSUPPORTED");
+ let closed = false, browserOpened = false, wentAway = false;
+ let returnTimer: ReturnType<typeof setTimeout> | undefined;
+ let rejectCancellation!: (error: Error) => void;
+ const cancelled = new Promise<never>((_, reject) => { rejectCancellation = reject; });
+ const fail = () => {
+ if (closed) return;
+ closed = true;
+ void native.close(input.id).catch(() => {});
+ rejectCancellation(new Error("PLUGIN_OAUTH_CLOSED"));
+ };
+ const check = () => {
+ input.assertCurrent();
+ if (closed || input.signal?.aborted || now() >= input.expiresAt) throw new Error("PLUGIN_OAUTH_CLOSED");
+ };
+ const removeAppState = input.onAppState((state) => {
+ if (!browserOpened) return;
+ if (state === "background") {
+ if (input.platform === "android") wentAway = true;
+ } else if (state === "active" && wentAway && input.platform === "android") {
+ wentAway = false;
+ // The browser may foreground Cindy just before the JS callback promise drains.
+ // Inspect the native receiver after that drain, never treat `opened` as done.
+ clearTimeout(returnTimer);
+ returnTimer = setTimeout(() => {
+ void native.status(input.id).then((status) => { if (status !== "received") fail(); }, fail);
+ }, 500);
+ }
+ });
+ input.signal?.addEventListener("abort", fail);
+ const ticker = setInterval(() => { try { check(); } catch { fail(); } }, 200);
+ try {
+ check();
+ const starting = native.start({ id: input.id, callbackUrl: input.request.callbackUrl, state: input.request.state, expiresAt: input.expiresAt });
+ // If owner/cancellation changes before a late bind resolves, close that bind too.
+ void starting.then(() => { if (closed) void native.close(input.id).catch(() => {}); }, () => {});
+ await Promise.race([starting, cancelled]);
+ check();
+ const received = native.wait(input.id);
+ browserOpened = true;
+ const browser = input.openBrowser(input.request.url).then((result) => {
+ if (result.type !== "opened") {
+ return native.status(input.id).then((status) => {
+ if (status !== "received") fail();
+ return new Promise<never>(() => {});
+ });
+ }
+ return new Promise<never>(() => {});
+ });
+ const raw = await Promise.race([received, browser, cancelled]);
+ check();
+ const parsed = parsePluginAuthorizationResult({ kind: "callback", ...(raw as object) });
+ if (parsed.kind !== "callback" || parsed.state !== input.request.state) throw new Error("PLUGIN_OAUTH_CLOSED");
+ const { kind: _, ...value } = parsed;
+ return value;
+ } finally {
+ closed = true;
+ clearInterval(ticker); clearTimeout(returnTimer);
+ input.signal?.removeEventListener("abort", fail); removeAppState();
+ await native.close(input.id).catch(() => {});
+ if (browserOpened && input.platform === "ios") await input.dismissBrowser().catch(() => {});
+ }
+}
diff --git a/apps/mobile/src/plugins/pluginOauthLoopbackNative.ts b/apps/mobile/src/plugins/pluginOauthLoopbackNative.ts
new file mode 100644
index 0000000000..d7c10236ea
--- /dev/null
+++ b/apps/mobile/src/plugins/pluginOauthLoopbackNative.ts
@@ -0,0 +1,19 @@
+import { requireOptionalNativeModule } from "expo-modules-core";
+import { randomUUID } from "expo-crypto";
+import * as WebBrowser from "expo-web-browser";
+import { AppState, Platform } from "react-native";
+import { receivePluginOauthLoopback, type MobileLoopbackNative, type MobileLoopbackRequest } from "./pluginOauthLoopback";
+export function receiveMobilePluginOauthLoopback(
+ request: MobileLoopbackRequest, expiresAt: number, assertCurrent: () => void, signal?: AbortSignal,
+) {
+ return receivePluginOauthLoopback({
+ request, expiresAt, signal, assertCurrent, id: randomUUID(), platform: Platform.OS,
+ native: requireOptionalNativeModule<MobileLoopbackNative>("CindyPluginOauth"),
+ openBrowser: (url) => WebBrowser.openBrowserAsync(url, { showTitle: true }),
+ dismissBrowser: async () => { await WebBrowser.dismissBrowser(); },
+ onAppState: (listener) => {
+ const subscription = AppState.addEventListener("change", listener);
+ return () => subscription.remove();
+ },
+ });
+}
diff --git a/apps/mobile/src/plugins/pluginSettingsAssets.ts b/apps/mobile/src/plugins/pluginSettingsAssets.ts
new file mode 100644
index 0000000000..545c0d05e2
--- /dev/null
+++ b/apps/mobile/src/plugins/pluginSettingsAssets.ts
@@ -0,0 +1,45 @@
+import type { PluginPageFile } from "@cindy/device-link";
+
+/** Host text resources include UTF-8 parameters; retain the full value for chunk checks. */
+export function pluginSettingsMediaType(value: unknown): string | undefined {
+ if (typeof value !== "string" || value.length > 128 || /[\r\n]/.test(value))
+ return undefined;
+ const match =
+ /^([a-z]+\/[a-z0-9.+-]+)(?:;[ \t]*charset=(?:utf-8|"utf-8"))?$/i.exec(
+ value,
+ );
+ return match?.[1].toLowerCase();
+}
+
+/** Validate every chunk against this lease's immutable declaration, including the decoded size. */
+export async function readPluginSettingsAsset(
+ file: PluginPageFile,
+ read: (path: string, offset: number) => Promise<unknown>,
+ assertCurrent: () => void,
+): Promise<Uint8Array> {
+ const bytes = new Uint8Array(file.size);
+ for (let offset = 0; offset < file.size; offset += 48 * 1024) {
+ assertCurrent();
+ const chunk = (await read(file.path, offset)) as {
+ base64?: unknown;
+ mime?: unknown;
+ };
+ assertCurrent();
+ const expected = Math.min(48 * 1024, file.size - offset);
+ if (
+ !chunk ||
+ chunk.mime !== file.mime ||
+ typeof chunk.base64 !== "string" ||
+ chunk.base64.length !== 4 * Math.ceil(expected / 3) ||
+ !/^[A-Za-z0-9+/]*={0,2}$/.test(chunk.base64)
+ )
+ throw new Error("PLUGIN_SETTINGS_ASSET_INVALID");
+ const decoded = atob(chunk.base64);
+ if (decoded.length !== expected)
+ throw new Error("PLUGIN_SETTINGS_ASSET_INVALID");
+ for (let i = 0; i < decoded.length; i++)
+ bytes[offset + i] = decoded.charCodeAt(i);
+ }
+ assertCurrent();
+ return bytes;
+}
diff --git a/apps/mobile/src/plugins/pluginSettingsBootstrap.generated.ts b/apps/mobile/src/plugins/pluginSettingsBootstrap.generated.ts
new file mode 100644
index 0000000000..4b744bc66f
--- /dev/null
+++ b/apps/mobile/src/plugins/pluginSettingsBootstrap.generated.ts
@@ -0,0 +1,2 @@
+// Generated by scripts/generate-mobile-settings-bootstrap.mjs. Edit pluginSettingsBootstrap.ts.
+export const PLUGIN_SETTINGS_BOOTSTRAP = "function settingsBootstrap(config) {\n const scope = window;\n const nativeFetch = window.fetch.bind(window);\n const quietConsole = Object.fromEntries([\n \"log\",\n \"info\",\n \"debug\",\n \"warn\",\n \"error\",\n \"assert\",\n \"trace\",\n \"table\",\n \"dir\",\n \"group\",\n \"groupEnd\",\n \"time\",\n \"timeEnd\",\n \"clear\",\n \"count\",\n ].map((name) => [name, () => { }]));\n Object.defineProperty(window, \"console\", {\n value: Object.freeze(quietConsole),\n });\n window.addEventListener(\"error\", (event) => event.preventDefault());\n window.addEventListener(\"unhandledrejection\", (event) => event.preventDefault());\n // The approved exception is transient input only. Never offer browser persistence or workers.\n const blockedStorage = Object.freeze({\n getItem: () => null,\n key: () => null,\n length: 0,\n setItem: () => {\n throw new DOMException(\"Settings storage disabled\", \"SecurityError\");\n },\n removeItem: () => { },\n clear: () => { },\n });\n for (const name of [\"localStorage\", \"sessionStorage\"])\n Object.defineProperty(window, name, { value: blockedStorage });\n for (const name of [\n \"indexedDB\",\n \"caches\",\n \"Worker\",\n \"SharedWorker\",\n \"RTCPeerConnection\",\n ])\n Object.defineProperty(window, name, { value: undefined });\n Object.defineProperty(navigator, \"serviceWorker\", { value: undefined });\n Object.defineProperty(navigator, \"credentials\", { value: undefined });\n Object.defineProperty(navigator, \"clipboard\", { value: undefined });\n navigator.sendBeacon = () => false;\n const sensitiveValues = new Set();\n const remember = (value) => {\n if (typeof value !== \"string\" || !value)\n return;\n sensitiveValues.add(value);\n if (sensitiveValues.size > 64)\n sensitiveValues.delete(sensitiveValues.values().next().value);\n };\n const containsSensitiveInput = (data) => {\n // Defense against accidental reuse of a credential form value in an old BC payload.\n // Arbitrary encoded/custom BC credentials still violate the author contract and are unsupported.\n document.querySelectorAll(\"input,textarea\").forEach((node) => {\n const input = node;\n if (input.type === \"password\" ||\n /secret|token|api.?key|password/i.test(input.id + \" \" + input.name))\n remember(input.value);\n });\n const json = JSON.stringify(data);\n return [...sensitiveValues].some((value) => json.includes(JSON.stringify(value).slice(1, -1)));\n };\n const pending = new Map();\n let sequence = 0, closed = false;\n const send = (command, timeout = 30_000) => {\n if (closed)\n return Promise.reject(new Error(\"PLUGIN_SETTINGS_CLOSED\"));\n return new Promise((resolve, reject) => {\n const id = ++sequence;\n const timer = setTimeout(() => {\n pending.delete(id);\n reject(new Error(\"PLUGIN_SETTINGS_RESULT_UNKNOWN\"));\n }, timeout);\n pending.set(id, { resolve, reject, timer });\n try {\n scope.ReactNativeWebView.postMessage(JSON.stringify({ settings: config.pageId, id, command }));\n }\n catch {\n clearTimeout(timer);\n pending.delete(id);\n reject(new Error(\"PLUGIN_SETTINGS_UNAVAILABLE\"));\n }\n });\n };\n const channels = new Map();\n let subscriptions = Promise.resolve();\n scope.__cindySettingsReceive = (value) => {\n if (closed)\n return;\n if (value.kind === \"reply\") {\n const work = pending.get(value.id);\n if (!work)\n return;\n clearTimeout(work.timer);\n pending.delete(value.id);\n if (value.ok)\n work.resolve(value.value);\n else\n work.reject(new Error(\"PLUGIN_SETTINGS_REQUEST_FAILED\"));\n }\n else if (value.kind === \"events\") {\n for (const event of value.events)\n for (const channel of channels.get(event.channel) ?? [])\n channel.deliver(event.data);\n }\n };\n scope.__cindySettingsTheme = (theme) => {\n const root = document.documentElement;\n root.classList.toggle(\"dark\", theme.dark);\n root.dataset.theme = theme.dark ? \"dark\" : \"light\";\n root.style.colorScheme = theme.dark ? \"dark\" : \"light\";\n for (const [name, value] of Object.entries(theme.colors))\n root.style.setProperty(\"--\" + name, value);\n window.dispatchEvent(new Event(\"cindy-theme-change\"));\n };\n scope.__cindySettingsTheme(config.theme);\n const urlFor = (input) => {\n const url = new URL(input, location.href);\n if (url.protocol === \"cindy-ghost:\" && url.hostname === config.manifestId)\n return new URL(url.pathname + url.search + url.hash, location.origin);\n if (url.origin !== location.origin)\n throw new Error(\"PLUGIN_SETTINGS_NETWORK_BLOCKED\");\n return url;\n };\n const api = (url) => /^\\/(kv|app-context|agent-models|media-models|secrets|oauth|connections|wake)(\\/|$)/.test(url.pathname);\n window.fetch = async (input, init) => {\n const request = input instanceof Request ? input : undefined;\n const url = urlFor(request?.url ?? String(input));\n const method = (init?.method ?? request?.method ?? \"GET\").toUpperCase();\n if (!api(url)) {\n if (method !== \"GET\" ||\n !config.files.includes(decodeURIComponent(url.pathname.slice(1))))\n throw new Error(\"PLUGIN_SETTINGS_NETWORK_BLOCKED\");\n return nativeFetch(url.href, init);\n }\n const body = init?.body === undefined\n ? request && method !== \"GET\"\n ? await request.text()\n : undefined\n : init.body;\n if (body !== undefined && body !== null && typeof body !== \"string\")\n throw new TypeError(\"String settings body required\");\n if (typeof body === \"string\" &&\n /^(\\/secrets\\/|\\/connections\\/|\\/oauth\\/)/.test(url.pathname)) {\n try {\n const values = JSON.parse(body);\n for (const [name, value] of Object.entries(values))\n if (url.pathname.startsWith(\"/secrets/\") ||\n /secret|token|password|api.?key/i.test(name))\n remember(value);\n }\n catch {\n /* The original Host executor validates malformed JSON; it is never logged. */\n }\n }\n const timeout = /^\\/oauth\\/[^/]+\\/connect$/.test(url.pathname)\n ? 330_000\n : url.pathname.startsWith(\"/connections/\") && method !== \"GET\"\n ? 120_000\n : 30_000;\n const result = await send({\n kind: \"fetch\",\n path: url.pathname + url.search,\n method,\n ...(body == null ? {} : { body }),\n }, timeout);\n // Host settings executors return PluginPageFetchResult, including Base64 bytes.\n const bytes = Uint8Array.from(atob(result.base64), (character) => character.charCodeAt(0));\n return new Response([204, 205, 304].includes(result.status) ? null : bytes, {\n status: result.status,\n headers: { \"content-type\": result.mime },\n });\n };\n class SettingsXHR extends EventTarget {\n static UNSENT = 0;\n static OPENED = 1;\n static HEADERS_RECEIVED = 2;\n static LOADING = 3;\n static DONE = 4;\n UNSENT = 0;\n OPENED = 1;\n HEADERS_RECEIVED = 2;\n LOADING = 3;\n DONE = 4;\n readyState = 0;\n status = 0;\n statusText = \"\";\n responseURL = \"\";\n responseType = \"\";\n response = null;\n timeout = 0;\n withCredentials = false;\n upload = new EventTarget();\n onreadystatechange = null;\n onload = null;\n onerror = null;\n onabort = null;\n onloadend = null;\n onloadstart = null;\n onprogress = null;\n ontimeout = null;\n text = \"\";\n method = \"GET\";\n url = \"\";\n mime = \"\";\n generation = 0;\n sent = false;\n get responseText() {\n if (this.responseType && this.responseType !== \"text\")\n throw new DOMException(\"Invalid response type\", \"InvalidStateError\");\n return this.text;\n }\n get responseXML() {\n return null;\n }\n emit(name) {\n const event = new Event(name);\n this[\"on\" + name]?.(event);\n this.dispatchEvent(event);\n }\n state(value) {\n this.readyState = value;\n this.emit(\"readystatechange\");\n }\n open(method, url, async = true, username, password) {\n if (!async || username || password)\n throw new DOMException(\"Unsupported settings request\", \"NotSupportedError\");\n this.generation++;\n this.method = method.toUpperCase();\n this.url = urlFor(String(url)).href;\n this.status = 0;\n this.text = \"\";\n this.response = null;\n this.mime = \"\";\n this.sent = false;\n this.state(1);\n }\n setRequestHeader(name, _value) {\n if (this.readyState !== 1 ||\n ![\"content-type\", \"accept\"].includes(name.toLowerCase()))\n throw new DOMException(\"Unsupported settings header\", \"NotSupportedError\");\n }\n getResponseHeader(name) {\n return this.readyState >= 2 && name.toLowerCase() === \"content-type\"\n ? this.mime\n : null;\n }\n getAllResponseHeaders() {\n return this.readyState >= 2 ? \"content-type: \" + this.mime + \"\\r\\n\" : \"\";\n }\n overrideMimeType(mime) {\n this.mime = mime;\n }\n send(body) {\n if (this.readyState !== 1 || this.sent)\n throw new DOMException(\"Request not opened\", \"InvalidStateError\");\n this.sent = true;\n const generation = this.generation;\n const controller = new AbortController();\n let timedOut = false;\n const timer = this.timeout > 0\n ? setTimeout(() => {\n if (generation !== this.generation)\n return;\n timedOut = true;\n controller.abort();\n this.generation++;\n this.status = 0;\n this.state(4);\n this.emit(\"timeout\");\n this.emit(\"loadend\");\n }, this.timeout)\n : undefined;\n this.emit(\"loadstart\");\n void window\n .fetch(this.url, {\n method: this.method,\n ...(body == null ? {} : { body }),\n signal: controller.signal,\n })\n .then(async (response) => {\n if (generation !== this.generation)\n return;\n this.status = response.status;\n this.statusText = response.statusText;\n this.responseURL = this.url;\n this.mime ||= response.headers.get(\"content-type\") ?? \"\";\n this.state(2);\n this.state(3);\n const bytes = await response.arrayBuffer();\n if (generation !== this.generation)\n return;\n const text = new TextDecoder().decode(bytes);\n this.text = text;\n this.response =\n this.responseType === \"json\"\n ? (() => {\n try {\n return JSON.parse(text);\n }\n catch {\n return null;\n }\n })()\n : this.responseType === \"arraybuffer\"\n ? bytes\n : this.responseType === \"blob\"\n ? new Blob([bytes], { type: this.mime })\n : text;\n this.state(4);\n this.emit(\"progress\");\n this.emit(\"load\");\n this.emit(\"loadend\");\n })\n .catch(() => {\n if (generation !== this.generation || timedOut)\n return;\n this.status = 0;\n this.state(4);\n this.emit(\"error\");\n this.emit(\"loadend\");\n })\n .finally(() => clearTimeout(timer));\n }\n abort() {\n this.generation++;\n this.status = 0;\n this.state(0);\n this.emit(\"abort\");\n this.emit(\"loadend\");\n }\n }\n scope.XMLHttpRequest = SettingsXHR;\n class RemoteChannel extends EventTarget {\n name;\n onmessage = null;\n onmessageerror = null;\n closed = false;\n constructor(name) {\n super();\n this.name = String(name);\n if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(this.name))\n throw new TypeError(\"Invalid channel\");\n const group = channels.get(this.name) ?? new Set();\n group.add(this);\n channels.set(this.name, group);\n subscriptions = subscriptions\n .catch(() => { })\n .then(() => send({ kind: \"subscribe\", channels: [this.name] }));\n void subscriptions.catch(() => this.error());\n }\n postMessage(data) {\n if (this.closed)\n throw new DOMException(\"Channel closed\", \"InvalidStateError\");\n const copy = JSON.parse(JSON.stringify(data));\n if (containsSensitiveInput(copy))\n throw new DOMException(\"Credential values cannot use BroadcastChannel\", \"SecurityError\");\n void subscriptions\n .then(() => send({ kind: \"post\", channel: this.name, data: copy }))\n .catch(() => this.error());\n }\n close() {\n if (this.closed)\n return;\n this.closed = true;\n const group = channels.get(this.name);\n group?.delete(this);\n if (!group?.size) {\n channels.delete(this.name);\n subscriptions = subscriptions\n .catch(() => { })\n .then(() => send({ kind: \"unsubscribe\", channel: this.name }));\n void subscriptions.catch(() => { });\n }\n }\n deliver(data) {\n if (!this.closed) {\n const event = new MessageEvent(\"message\", { data });\n this.onmessage?.(event);\n this.dispatchEvent(event);\n }\n }\n error() {\n if (!this.closed) {\n const event = new MessageEvent(\"messageerror\");\n this.onmessageerror?.(event);\n this.dispatchEvent(event);\n }\n }\n }\n scope.BroadcastChannel = RemoteChannel;\n let resizeObserver;\n let controlObserver;\n const adaptControlFonts = (root) => {\n const adapt = (control) => {\n if (control instanceof HTMLInputElement &&\n ![\n \"text\",\n \"password\",\n \"email\",\n \"number\",\n \"search\",\n \"tel\",\n \"url\",\n ].includes(control.type))\n return;\n // Small editable text triggers iOS focus zoom; preserve larger author typography.\n if (parseFloat(window.getComputedStyle(control).fontSize) < 16)\n control.style.fontSize = \"16px\";\n };\n if (root.matches(\"input,textarea,select\"))\n adapt(root);\n root.querySelectorAll(\"input,textarea,select\").forEach(adapt);\n };\n const adaptControls = () => {\n if (closed)\n return;\n adaptControlFonts(document.documentElement);\n controlObserver = new MutationObserver((records) => {\n if (closed)\n return;\n for (const record of records)\n for (const node of record.addedNodes)\n if (node instanceof Element)\n adaptControlFonts(node);\n });\n controlObserver.observe(document.documentElement, {\n childList: true,\n subtree: true,\n });\n };\n if (document.readyState === \"loading\")\n document.addEventListener(\"DOMContentLoaded\", adaptControls, {\n once: true,\n });\n else\n adaptControls();\n window.addEventListener(\"pagehide\", () => {\n closed = true;\n for (const work of pending.values()) {\n clearTimeout(work.timer);\n work.reject(new Error(\"PLUGIN_SETTINGS_CLOSED\"));\n }\n pending.clear();\n channels.clear();\n sensitiveValues.clear();\n resizeObserver?.disconnect();\n controlObserver?.disconnect();\n document.removeEventListener(\"DOMContentLoaded\", adaptControls);\n window.name = \"\";\n document.querySelectorAll(\"input,textarea\").forEach((input) => {\n input.value = \"\";\n });\n }, { once: true });\n const resize = () => {\n if (!closed)\n scope.ReactNativeWebView.postMessage(JSON.stringify({\n settings: config.pageId,\n height: Math.ceil(document.body?.scrollHeight ??\n document.documentElement.scrollHeight),\n }));\n };\n window.addEventListener(\"load\", resize);\n if (typeof ResizeObserver !== \"undefined\") {\n resizeObserver = new ResizeObserver(resize);\n resizeObserver.observe(document.documentElement);\n }\n}\n";
diff --git a/apps/mobile/src/plugins/pluginSettingsBootstrap.ts b/apps/mobile/src/plugins/pluginSettingsBootstrap.ts
new file mode 100644
index 0000000000..020d4cf801
--- /dev/null
+++ b/apps/mobile/src/plugins/pluginSettingsBootstrap.ts
@@ -0,0 +1,527 @@
+/** Compiled ahead of time: Hermes must never serialize Function#toString. No native imports. */
+export interface SettingsBootstrapConfig {
+ pageId: string;
+ manifestId: string;
+ files: string[];
+ theme: { dark: boolean; colors: Record<string, string> };
+}
+export function settingsBootstrap(config: SettingsBootstrapConfig) {
+ const scope = window as unknown as Record<string, any>;
+ const nativeFetch = window.fetch.bind(window);
+ const quietConsole = Object.fromEntries(
+ [
+ "log",
+ "info",
+ "debug",
+ "warn",
+ "error",
+ "assert",
+ "trace",
+ "table",
+ "dir",
+ "group",
+ "groupEnd",
+ "time",
+ "timeEnd",
+ "clear",
+ "count",
+ ].map((name) => [name, () => {}]),
+ );
+ Object.defineProperty(window, "console", {
+ value: Object.freeze(quietConsole),
+ });
+ window.addEventListener("error", (event) => event.preventDefault());
+ window.addEventListener("unhandledrejection", (event) =>
+ event.preventDefault(),
+ );
+ // The approved exception is transient input only. Never offer browser persistence or workers.
+ const blockedStorage = Object.freeze({
+ getItem: () => null,
+ key: () => null,
+ length: 0,
+ setItem: () => {
+ throw new DOMException("Settings storage disabled", "SecurityError");
+ },
+ removeItem: () => {},
+ clear: () => {},
+ });
+ for (const name of ["localStorage", "sessionStorage"])
+ Object.defineProperty(window, name, { value: blockedStorage });
+ for (const name of [
+ "indexedDB",
+ "caches",
+ "Worker",
+ "SharedWorker",
+ "RTCPeerConnection",
+ ])
+ Object.defineProperty(window, name, { value: undefined });
+ Object.defineProperty(navigator, "serviceWorker", { value: undefined });
+ Object.defineProperty(navigator, "credentials", { value: undefined });
+ Object.defineProperty(navigator, "clipboard", { value: undefined });
+ navigator.sendBeacon = () => false;
+ const sensitiveValues = new Set<string>();
+ const remember = (value: unknown) => {
+ if (typeof value !== "string" || !value) return;
+ sensitiveValues.add(value);
+ if (sensitiveValues.size > 64)
+ sensitiveValues.delete(sensitiveValues.values().next().value!);
+ };
+ const containsSensitiveInput = (data: unknown) => {
+ // Defense against accidental reuse of a credential form value in an old BC payload.
+ // Arbitrary encoded/custom BC credentials still violate the author contract and are unsupported.
+ document.querySelectorAll("input,textarea").forEach((node) => {
+ const input = node as HTMLInputElement;
+ if (
+ input.type === "password" ||
+ /secret|token|api.?key|password/i.test(input.id + " " + input.name)
+ )
+ remember(input.value);
+ });
+ const json = JSON.stringify(data);
+ return [...sensitiveValues].some((value) =>
+ json.includes(JSON.stringify(value).slice(1, -1)),
+ );
+ };
+ const pending = new Map<
+ number,
+ {
+ resolve(value: any): void;
+ reject(error: Error): void;
+ timer: ReturnType<typeof setTimeout>;
+ }
+ >();
+ let sequence = 0,
+ closed = false;
+ const send = (command: unknown, timeout = 30_000): Promise<any> => {
+ if (closed) return Promise.reject(new Error("PLUGIN_SETTINGS_CLOSED"));
+ return new Promise((resolve, reject) => {
+ const id = ++sequence;
+ const timer = setTimeout(() => {
+ pending.delete(id);
+ reject(new Error("PLUGIN_SETTINGS_RESULT_UNKNOWN"));
+ }, timeout);
+ pending.set(id, { resolve, reject, timer });
+ try {
+ scope.ReactNativeWebView.postMessage(
+ JSON.stringify({ settings: config.pageId, id, command }),
+ );
+ } catch {
+ clearTimeout(timer);
+ pending.delete(id);
+ reject(new Error("PLUGIN_SETTINGS_UNAVAILABLE"));
+ }
+ });
+ };
+ const channels = new Map<string, Set<RemoteChannel>>();
+ let subscriptions = Promise.resolve();
+ scope.__cindySettingsReceive = (value: any) => {
+ if (closed) return;
+ if (value.kind === "reply") {
+ const work = pending.get(value.id);
+ if (!work) return;
+ clearTimeout(work.timer);
+ pending.delete(value.id);
+ if (value.ok) work.resolve(value.value);
+ else work.reject(new Error("PLUGIN_SETTINGS_REQUEST_FAILED"));
+ } else if (value.kind === "events") {
+ for (const event of value.events)
+ for (const channel of channels.get(event.channel) ?? [])
+ channel.deliver(event.data);
+ }
+ };
+ scope.__cindySettingsTheme = (theme: SettingsBootstrapConfig["theme"]) => {
+ const root = document.documentElement;
+ root.classList.toggle("dark", theme.dark);
+ root.dataset.theme = theme.dark ? "dark" : "light";
+ root.style.colorScheme = theme.dark ? "dark" : "light";
+ for (const [name, value] of Object.entries(theme.colors))
+ root.style.setProperty("--" + name, value);
+ window.dispatchEvent(new Event("cindy-theme-change"));
+ };
+ scope.__cindySettingsTheme(config.theme);
+ const urlFor = (input: string) => {
+ const url = new URL(input, location.href);
+ if (url.protocol === "cindy-ghost:" && url.hostname === config.manifestId)
+ return new URL(url.pathname + url.search + url.hash, location.origin);
+ if (url.origin !== location.origin)
+ throw new Error("PLUGIN_SETTINGS_NETWORK_BLOCKED");
+ return url;
+ };
+ const api = (url: URL) =>
+ /^\/(kv|app-context|agent-models|media-models|secrets|oauth|connections|wake)(\/|$)/.test(
+ url.pathname,
+ );
+ window.fetch = async (input, init) => {
+ const request = input instanceof Request ? input : undefined;
+ const url = urlFor(request?.url ?? String(input));
+ const method = (init?.method ?? request?.method ?? "GET").toUpperCase();
+ if (!api(url)) {
+ if (
+ method !== "GET" ||
+ !config.files.includes(decodeURIComponent(url.pathname.slice(1)))
+ )
+ throw new Error("PLUGIN_SETTINGS_NETWORK_BLOCKED");
+ return nativeFetch(url.href, init);
+ }
+ const body =
+ init?.body === undefined
+ ? request && method !== "GET"
+ ? await request.text()
+ : undefined
+ : init.body;
+ if (body !== undefined && body !== null && typeof body !== "string")
+ throw new TypeError("String settings body required");
+ if (
+ typeof body === "string" &&
+ /^(\/secrets\/|\/connections\/|\/oauth\/)/.test(url.pathname)
+ ) {
+ try {
+ const values = JSON.parse(body);
+ for (const [name, value] of Object.entries(values))
+ if (
+ url.pathname.startsWith("/secrets/") ||
+ /secret|token|password|api.?key/i.test(name)
+ )
+ remember(value);
+ } catch {
+ /* The original Host executor validates malformed JSON; it is never logged. */
+ }
+ }
+ const timeout = /^\/oauth\/[^/]+\/connect$/.test(url.pathname)
+ ? 330_000
+ : url.pathname.startsWith("/connections/") && method !== "GET"
+ ? 120_000
+ : 30_000;
+ const result = await send(
+ {
+ kind: "fetch",
+ path: url.pathname + url.search,
+ method,
+ ...(body == null ? {} : { body }),
+ },
+ timeout,
+ );
+ // Host settings executors return PluginPageFetchResult, including Base64 bytes.
+ const bytes = Uint8Array.from(atob(result.base64), (character) =>
+ character.charCodeAt(0),
+ );
+ return new Response(
+ [204, 205, 304].includes(result.status) ? null : bytes,
+ {
+ status: result.status,
+ headers: { "content-type": result.mime },
+ },
+ );
+ };
+ class SettingsXHR extends EventTarget {
+ static readonly UNSENT = 0;
+ static readonly OPENED = 1;
+ static readonly HEADERS_RECEIVED = 2;
+ static readonly LOADING = 3;
+ static readonly DONE = 4;
+ readonly UNSENT = 0;
+ readonly OPENED = 1;
+ readonly HEADERS_RECEIVED = 2;
+ readonly LOADING = 3;
+ readonly DONE = 4;
+ readyState = 0;
+ status = 0;
+ statusText = "";
+ responseURL = "";
+ responseType = "";
+ response: any = null;
+ timeout = 0;
+ withCredentials = false;
+ upload = new EventTarget();
+ onreadystatechange: any = null;
+ onload: any = null;
+ onerror: any = null;
+ onabort: any = null;
+ onloadend: any = null;
+ onloadstart: any = null;
+ onprogress: any = null;
+ ontimeout: any = null;
+ private text = "";
+ private method = "GET";
+ private url = "";
+ private mime = "";
+ private generation = 0;
+ private sent = false;
+ get responseText() {
+ if (this.responseType && this.responseType !== "text")
+ throw new DOMException("Invalid response type", "InvalidStateError");
+ return this.text;
+ }
+ get responseXML() {
+ return null;
+ }
+ private emit(name: string) {
+ const event = new Event(name);
+ (this as any)["on" + name]?.(event);
+ this.dispatchEvent(event);
+ }
+ private state(value: number) {
+ this.readyState = value;
+ this.emit("readystatechange");
+ }
+ open(
+ method: string,
+ url: string,
+ async = true,
+ username?: string,
+ password?: string,
+ ) {
+ if (!async || username || password)
+ throw new DOMException(
+ "Unsupported settings request",
+ "NotSupportedError",
+ );
+ this.generation++;
+ this.method = method.toUpperCase();
+ this.url = urlFor(String(url)).href;
+ this.status = 0;
+ this.text = "";
+ this.response = null;
+ this.mime = "";
+ this.sent = false;
+ this.state(1);
+ }
+ setRequestHeader(name: string, _value: string) {
+ if (
+ this.readyState !== 1 ||
+ !["content-type", "accept"].includes(name.toLowerCase())
+ )
+ throw new DOMException(
+ "Unsupported settings header",
+ "NotSupportedError",
+ );
+ }
+ getResponseHeader(name: string) {
+ return this.readyState >= 2 && name.toLowerCase() === "content-type"
+ ? this.mime
+ : null;
+ }
+ getAllResponseHeaders() {
+ return this.readyState >= 2 ? "content-type: " + this.mime + "\r\n" : "";
+ }
+ overrideMimeType(mime: string) {
+ this.mime = mime;
+ }
+ send(body?: string) {
+ if (this.readyState !== 1 || this.sent)
+ throw new DOMException("Request not opened", "InvalidStateError");
+ this.sent = true;
+ const generation = this.generation;
+ const controller = new AbortController();
+ let timedOut = false;
+ const timer =
+ this.timeout > 0
+ ? setTimeout(() => {
+ if (generation !== this.generation) return;
+ timedOut = true;
+ controller.abort();
+ this.generation++;
+ this.status = 0;
+ this.state(4);
+ this.emit("timeout");
+ this.emit("loadend");
+ }, this.timeout)
+ : undefined;
+ this.emit("loadstart");
+ void window
+ .fetch(this.url, {
+ method: this.method,
+ ...(body == null ? {} : { body }),
+ signal: controller.signal,
+ })
+ .then(async (response) => {
+ if (generation !== this.generation) return;
+ this.status = response.status;
+ this.statusText = response.statusText;
+ this.responseURL = this.url;
+ this.mime ||= response.headers.get("content-type") ?? "";
+ this.state(2);
+ this.state(3);
+ const bytes = await response.arrayBuffer();
+ if (generation !== this.generation) return;
+ const text = new TextDecoder().decode(bytes);
+ this.text = text;
+ this.response =
+ this.responseType === "json"
+ ? (() => {
+ try {
+ return JSON.parse(text);
+ } catch {
+ return null;
+ }
+ })()
+ : this.responseType === "arraybuffer"
+ ? bytes
+ : this.responseType === "blob"
+ ? new Blob([bytes], { type: this.mime })
+ : text;
+ this.state(4);
+ this.emit("progress");
+ this.emit("load");
+ this.emit("loadend");
+ })
+ .catch(() => {
+ if (generation !== this.generation || timedOut) return;
+ this.status = 0;
+ this.state(4);
+ this.emit("error");
+ this.emit("loadend");
+ })
+ .finally(() => clearTimeout(timer));
+ }
+ abort() {
+ this.generation++;
+ this.status = 0;
+ this.state(0);
+ this.emit("abort");
+ this.emit("loadend");
+ }
+ }
+ scope.XMLHttpRequest = SettingsXHR;
+ class RemoteChannel extends EventTarget {
+ readonly name: string;
+ onmessage: ((event: MessageEvent) => void) | null = null;
+ onmessageerror: ((event: MessageEvent) => void) | null = null;
+ private closed = false;
+ constructor(name: string) {
+ super();
+ this.name = String(name);
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(this.name))
+ throw new TypeError("Invalid channel");
+ const group = channels.get(this.name) ?? new Set();
+ group.add(this);
+ channels.set(this.name, group);
+ subscriptions = subscriptions
+ .catch(() => {})
+ .then(() => send({ kind: "subscribe", channels: [this.name] }));
+ void subscriptions.catch(() => this.error());
+ }
+ postMessage(data: unknown) {
+ if (this.closed)
+ throw new DOMException("Channel closed", "InvalidStateError");
+ const copy = JSON.parse(JSON.stringify(data));
+ if (containsSensitiveInput(copy))
+ throw new DOMException(
+ "Credential values cannot use BroadcastChannel",
+ "SecurityError",
+ );
+ void subscriptions
+ .then(() => send({ kind: "post", channel: this.name, data: copy }))
+ .catch(() => this.error());
+ }
+ close() {
+ if (this.closed) return;
+ this.closed = true;
+ const group = channels.get(this.name);
+ group?.delete(this);
+ if (!group?.size) {
+ channels.delete(this.name);
+ subscriptions = subscriptions
+ .catch(() => {})
+ .then(() => send({ kind: "unsubscribe", channel: this.name }));
+ void subscriptions.catch(() => {});
+ }
+ }
+ deliver(data: unknown) {
+ if (!this.closed) {
+ const event = new MessageEvent("message", { data });
+ this.onmessage?.(event);
+ this.dispatchEvent(event);
+ }
+ }
+ private error() {
+ if (!this.closed) {
+ const event = new MessageEvent("messageerror");
+ this.onmessageerror?.(event);
+ this.dispatchEvent(event);
+ }
+ }
+ }
+ scope.BroadcastChannel = RemoteChannel;
+ let resizeObserver: ResizeObserver | undefined;
+ let controlObserver: MutationObserver | undefined;
+ const adaptControlFonts = (root: Element) => {
+ const adapt = (control: Element) => {
+ if (
+ control instanceof HTMLInputElement &&
+ ![
+ "text",
+ "password",
+ "email",
+ "number",
+ "search",
+ "tel",
+ "url",
+ ].includes(control.type)
+ )
+ return;
+ // Small editable text triggers iOS focus zoom; preserve larger author typography.
+ if (parseFloat(window.getComputedStyle(control).fontSize) < 16)
+ (control as HTMLElement).style.fontSize = "16px";
+ };
+ if (root.matches("input,textarea,select")) adapt(root);
+ root.querySelectorAll("input,textarea,select").forEach(adapt);
+ };
+ const adaptControls = () => {
+ if (closed) return;
+ adaptControlFonts(document.documentElement);
+ controlObserver = new MutationObserver((records) => {
+ if (closed) return;
+ for (const record of records)
+ for (const node of record.addedNodes)
+ if (node instanceof Element) adaptControlFonts(node);
+ });
+ controlObserver.observe(document.documentElement, {
+ childList: true,
+ subtree: true,
+ });
+ };
+ if (document.readyState === "loading")
+ document.addEventListener("DOMContentLoaded", adaptControls, {
+ once: true,
+ });
+ else adaptControls();
+ window.addEventListener(
+ "pagehide",
+ () => {
+ closed = true;
+ for (const work of pending.values()) {
+ clearTimeout(work.timer);
+ work.reject(new Error("PLUGIN_SETTINGS_CLOSED"));
+ }
+ pending.clear();
+ channels.clear();
+ sensitiveValues.clear();
+ resizeObserver?.disconnect();
+ controlObserver?.disconnect();
+ document.removeEventListener("DOMContentLoaded", adaptControls);
+ window.name = "";
+ document.querySelectorAll("input,textarea").forEach((input) => {
+ (input as HTMLInputElement).value = "";
+ });
+ },
+ { once: true },
+ );
+ const resize = () => {
+ if (!closed)
+ scope.ReactNativeWebView.postMessage(
+ JSON.stringify({
+ settings: config.pageId,
+ height: Math.ceil(
+ document.body?.scrollHeight ??
+ document.documentElement.scrollHeight,
+ ),
+ }),
+ );
+ };
+ window.addEventListener("load", resize);
+ if (typeof ResizeObserver !== "undefined") {
+ resizeObserver = new ResizeObserver(resize);
+ resizeObserver.observe(document.documentElement);
+ }
+}
diff --git a/apps/mobile/src/plugins/pluginSettingsClient.ts b/apps/mobile/src/plugins/pluginSettingsClient.ts
new file mode 100644
index 0000000000..a57cbcb473
--- /dev/null
+++ b/apps/mobile/src/plugins/pluginSettingsClient.ts
@@ -0,0 +1,328 @@
+import {
+ PLUGIN_PAGE_MAX_BUNDLE_BYTES,
+ PLUGIN_SETTINGS_ACTION,
+ REMOTE_RESOURCE_INVOKE_CHANNEL,
+ parsePluginSettingsRequest,
+ parsePluginOauthAction,
+ oauthId,
+ oauthGhostId,
+ type PluginOauthAction,
+ type PluginOauthRequest,
+ type PluginPageFile,
+ type PluginSettingsCommand,
+} from "@cindy/device-link";
+import { pluginSettingsMediaType } from "./pluginSettingsAssets";
+
+export interface PluginSettingsIdentity {
+ deviceId: string;
+ instanceId: string;
+ expectedInstalledApproval: string;
+}
+export interface PluginSettingsDocument {
+ pageId: string;
+ pluginId: string;
+ manifestId: string;
+ name: string;
+ entry: string;
+ files: PluginPageFile[];
+ controllerAuthorization?: true;
+}
+export interface PluginSettingsSession {
+ request(request: PluginOauthRequest): Promise<unknown>;
+ dispose(): void;
+}
+export interface PluginSettingsClientOptions {
+ identity: PluginSettingsIdentity;
+ /** Returns the direct mobile RemoteInvoke result, not a Desktop {ok,result} envelope. */
+ invokeTarget(channel: string, args: unknown[]): Promise<unknown>;
+ /** Use openMobilePluginOauthSession with this exact target and captured owner/connection. */
+ openSession(action: PluginOauthAction): Promise<PluginSettingsSession>;
+ assertCurrent(): void;
+ /** Owner/connection guard only, so a hidden/closed document can release its own old lease. */
+ assertCleanupCurrent?(): void;
+ /** Trusted native browser/device-code flow. The Host still exchanges tokens and saves them. */
+ onAuthorize?(action: PluginOauthAction): Promise<void>;
+ now?(): number;
+}
+const unavailable = () => new Error("PLUGIN_SETTINGS_UNAVAILABLE");
+const safePath = (path: unknown): path is string =>
+ typeof path === "string" &&
+ path.length <= 256 &&
+ path
+ .split("/")
+ .every((part) => /^[a-zA-Z0-9_][a-zA-Z0-9._-]{0,63}$/.test(part));
+
+export function parsePluginSettingsDocument(
+ raw: unknown,
+ instanceId: string,
+): PluginSettingsDocument {
+ const doc = raw as PluginSettingsDocument;
+ if (
+ !doc ||
+ !oauthId(doc.pageId) ||
+ doc.pluginId !== instanceId ||
+ !oauthId(doc.manifestId) ||
+ typeof doc.name !== "string" ||
+ doc.name.length > 160 ||
+ !safePath(doc.entry) ||
+ !Array.isArray(doc.files) ||
+ !doc.files.length ||
+ doc.files.length > 10_000
+ )
+ throw unavailable();
+ let total = 0;
+ const paths = new Set<string>();
+ for (const file of doc.files) {
+ if (
+ !file ||
+ !safePath(file.path) ||
+ paths.has(file.path) ||
+ !Number.isSafeInteger(file.size) ||
+ file.size < 0 ||
+ typeof file.mime !== "string" ||
+ !pluginSettingsMediaType(file.mime)
+ )
+ throw unavailable();
+ paths.add(file.path);
+ total += file.size;
+ }
+ if (
+ total > PLUGIN_PAGE_MAX_BUNDLE_BYTES ||
+ !doc.files.some(
+ (file) =>
+ file.path === doc.entry &&
+ pluginSettingsMediaType(file.mime) === "text/html",
+ )
+ )
+ throw unavailable();
+ // Copy the Host declaration so callers cannot change the asset/instance binding later.
+ return {
+ pageId: doc.pageId,
+ pluginId: doc.pluginId,
+ manifestId: doc.manifestId,
+ name: doc.name,
+ entry: doc.entry,
+ files: doc.files.map((file) => ({ ...file })),
+ ...(doc.controllerAuthorization === true ? { controllerAuthorization: true as const } : {}),
+ };
+}
+
+/** Same endpoint boundary as the target's original settings executor, never a general HTTP proxy. */
+export function isPluginSettingsFetch(path: string, method: string): boolean {
+ if (!path.startsWith("/") || path.startsWith("//")) return false;
+ const url = new URL(path, "https://plugin.invalid");
+ if (url.origin !== "https://plugin.invalid" || url.hash) return false;
+ if (method === "GET" && url.pathname.startsWith("/secrets/")) return false;
+ if (/^\/secrets\/[a-z][a-z0-9_]{0,31}\/check$/.test(url.pathname)) return method === "POST";
+ return (
+ ["GET", "PUT", "POST", "DELETE"].includes(method) &&
+ /^\/(?:kv|app-context|agent-models|media-models|secrets(?:\/[^/]+)?|oauth(?:\/[^/]+\/(?:client|default|insufficient-scopes|accounts\/[^/]+|connect))?|connections(?:\/[^/]+(?:\/[^/]+)?)?|wake)$/.test(
+ url.pathname,
+ )
+ );
+}
+
+/** One original settings lease. Commands are never retried after a possibly committed request. */
+export async function openPluginSettingsClient(
+ options: PluginSettingsClientOptions,
+) {
+ const identity = { ...options.identity };
+ if (
+ !oauthId(identity.deviceId) ||
+ !oauthGhostId(identity.instanceId) ||
+ typeof identity.expectedInstalledApproval !== "string" ||
+ identity.expectedInstalledApproval.length > 4096
+ )
+ throw unavailable();
+ const now = options.now ?? Date.now;
+ let closed = false;
+ const current = () => {
+ if (closed) throw unavailable();
+ options.assertCurrent();
+ };
+ current();
+ const response = await options.invokeTarget(REMOTE_RESOURCE_INVOKE_CHANNEL, [
+ {
+ client: {
+ protocolVersion: 1,
+ primitives: ["status", "markdown", "action", "form", "list"],
+ },
+ collectionId: "plugins",
+ actionId: "settings:open",
+ resourceRef: {
+ collectionId: "plugins",
+ kind: "plugin",
+ id: identity.instanceId,
+ },
+ input: { expectedInstalledApproval: identity.expectedInstalledApproval },
+ },
+ ]);
+ current();
+ const document = parsePluginSettingsDocument(
+ (response as { result?: unknown })?.result,
+ identity.instanceId,
+ );
+ type Exchange = {
+ session: PluginSettingsSession;
+ pending: number;
+ retired: boolean;
+ };
+ const sessions = new Set<Exchange>();
+ let exchange: Exchange | undefined;
+ let renewing: Promise<void> | undefined;
+ let renewedAt = 0,
+ sent = 0;
+ const connect = async () => {
+ current();
+ const next = await options.openSession({
+ requestId: document.pageId,
+ actionId: PLUGIN_SETTINGS_ACTION,
+ expectedRevision: 0,
+ });
+ try {
+ current();
+ } catch (error) {
+ next.dispose();
+ throw error;
+ }
+ const prior = exchange;
+ exchange = { session: next, pending: 0, retired: false };
+ sessions.add(exchange);
+ if (prior) {
+ prior.retired = true;
+ if (!prior.pending) {
+ prior.session.dispose();
+ sessions.delete(prior);
+ }
+ }
+ renewedAt = now();
+ sent = 0;
+ };
+ const send = async (command: PluginSettingsCommand): Promise<unknown> => {
+ current();
+ if (
+ !parsePluginSettingsRequest({
+ op: "settings",
+ id: document.pageId,
+ command,
+ })
+ )
+ throw unavailable();
+ while (!exchange || now() - renewedAt >= 240_000 || sent >= 1000) {
+ renewing ??= connect().finally(() => {
+ renewing = undefined;
+ });
+ await renewing;
+ current();
+ }
+ current();
+ sent++;
+ const active = exchange!;
+ active.pending++;
+ try {
+ const result = await active.session.request({
+ op: "settings",
+ id: document.pageId,
+ command,
+ });
+ current();
+ return result;
+ } catch (error) {
+ // Only a mutation handed to the encrypted transport can have an unknown result.
+ const mutation =
+ (command.kind === "fetch" && command.method !== "GET") ||
+ command.kind === "post" ||
+ command.kind === "authorize";
+ if (mutation)
+ throw Object.assign(error instanceof Error ? error : unavailable(), {
+ settingsOutcome: "unknown" as const,
+ });
+ throw error;
+ } finally {
+ active.pending--;
+ if (active.retired && !active.pending && sessions.delete(active))
+ active.session.dispose();
+ }
+ };
+ try {
+ await connect();
+ } catch (error) {
+ closed = true;
+ throw error;
+ }
+ return {
+ document,
+ assertCurrent: current,
+ async fetch(path: string, method = "GET", body?: string) {
+ if (!isPluginSettingsFetch(path, method))
+ throw new Error("PLUGIN_SETTINGS_ENDPOINT_BLOCKED");
+ if (/^\/oauth\/[^/]+\/connect$/.test(path) && method === "POST") {
+ if (!options.onAuthorize)
+ throw new Error("PLUGIN_SETTINGS_AUTHORIZATION_UNAVAILABLE");
+ current();
+ if (document.controllerAuthorization !== true)
+ throw new Error("PLUGIN_SETTINGS_HOST_UPDATE_REQUIRED");
+ const action = parsePluginOauthAction(
+ await send({
+ kind: "authorize",
+ path,
+ ...(body === undefined ? {} : { body }),
+ }),
+ );
+ body = undefined;
+ if (!action) throw unavailable();
+ let failure: unknown;
+ try {
+ await options.onAuthorize(action);
+ } catch (error) {
+ failure = error;
+ }
+ current();
+ try {
+ return await send({
+ kind: "authorization-result",
+ requestId: action.requestId,
+ });
+ } catch (error) {
+ throw failure ?? error;
+ }
+ }
+ return send({
+ kind: "fetch",
+ path,
+ method,
+ ...(body === undefined ? {} : { body }),
+ });
+ },
+ /** Only trusted native callers may answer prompts or read package assets. */
+ send,
+ async close() {
+ if (closed) return;
+ // Start best-effort lease cleanup before closing the local guard. Never reauthenticate to close.
+ let cleanup: Promise<unknown> | undefined;
+ try {
+ (options.assertCleanupCurrent ?? options.assertCurrent)();
+ if (exchange)
+ cleanup = exchange.session.request({
+ op: "settings",
+ id: document.pageId,
+ command: { kind: "close" },
+ });
+ } catch {
+ /* Owner/connection changes already revoke the Host lease. */
+ }
+ closed = true;
+ try {
+ await cleanup;
+ } catch {
+ /* Expiry is the fallback; a lost close is never replayed. */
+ } finally {
+ for (const exchange of sessions) exchange.session.dispose();
+ sessions.clear();
+ }
+ },
+ };
+}
+export type PluginSettingsClient = Awaited<
+ ReturnType<typeof openPluginSettingsClient>
+>;
diff --git a/apps/mobile/src/plugins/pluginSettingsHtml.ts b/apps/mobile/src/plugins/pluginSettingsHtml.ts
new file mode 100644
index 0000000000..e684756e72
--- /dev/null
+++ b/apps/mobile/src/plugins/pluginSettingsHtml.ts
@@ -0,0 +1,56 @@
+import type { PluginSettingsDocument } from "./pluginSettingsClient";
+import type { SettingsBootstrapConfig } from "./pluginSettingsBootstrap";
+import { PLUGIN_SETTINGS_BOOTSTRAP } from "./pluginSettingsBootstrap.generated";
+
+/** Desktop settings CSP plus frame/form/navigation isolation; scripts retain their original layout. */
+export const PLUGIN_SETTINGS_CSP =
+ "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; media-src 'self' data: blob:; connect-src 'self'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'";
+
+export function settingsBridgeAsset(
+ document: PluginSettingsDocument,
+ theme: SettingsBootstrapConfig["theme"],
+) {
+ let path = "__cindy_settings_bridge.js";
+ while (document.files.some((file) => file.path === path)) path = "_" + path;
+ const config: SettingsBootstrapConfig = {
+ pageId: document.pageId,
+ manifestId: document.manifestId,
+ files: document.files.map((file) => file.path),
+ theme,
+ };
+ return {
+ path,
+ text:
+ PLUGIN_SETTINGS_BOOTSTRAP +
+ "\nsettingsBootstrap(" +
+ JSON.stringify(config).replace(/</g, "\\u003c") +
+ ");",
+ };
+}
+
+/** Only package bytes are rewritten/persisted. Configuration and responses never enter this file. */
+export function prepareSettingsHtml(html: string, bridgePath: string): string {
+ const script = '<script src="/' + bridgePath + '"></script>';
+ // Same host defaults as Desktop's original settings surface; author styles remain intact.
+ const defaults =
+ '<style>body{margin:0;background:var(--settings-theme-card-bg,var(--surface));color:var(--text-primary);font-family:Inter,system-ui,-apple-system,"Segoe UI",sans-serif;font-size:13px}input::placeholder,textarea::placeholder{color:var(--text-placeholder);opacity:1}</style>';
+ const viewport = /<meta\s[^>]*name\s*=\s*["']?viewport\b/i.test(html)
+ ? ""
+ : '<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">';
+ const injection = script + defaults + viewport;
+ // Head-first injection executes before the original settings scripts, including ES modules.
+ return /<head(?:\s[^>]*)?>/i.test(html)
+ ? html.replace(/<head(?:\s[^>]*)?>/i, (head) => head + injection)
+ : injection + html;
+}
+
+export function settingsInjection(
+ method: "__cindySettingsReceive" | "__cindySettingsTheme",
+ value: unknown,
+): string {
+ const encoded = JSON.stringify(value)
+ .replace(/</g, "\\u003c")
+ .replace(/\u2028/g, "\\u2028")
+ .replace(/\u2029/g, "\\u2029");
+ return "window." + method + "?.(" + encoded + ");true;";
+}
diff --git a/apps/mobile/src/plugins/pluginSettingsResources.ts b/apps/mobile/src/plugins/pluginSettingsResources.ts
new file mode 100644
index 0000000000..e2f33caf77
--- /dev/null
+++ b/apps/mobile/src/plugins/pluginSettingsResources.ts
@@ -0,0 +1,114 @@
+import { Directory, File, Paths } from "expo-file-system";
+import { getRandomBytes } from "expo-crypto";
+import native from "../../modules/cindy-html-preview/src/CindyHtmlPreviewModule";
+import type { PluginSettingsClient } from "./pluginSettingsClient";
+import type { SettingsBootstrapConfig } from "./pluginSettingsBootstrap";
+import {
+ readPluginSettingsAsset,
+ pluginSettingsMediaType,
+} from "./pluginSettingsAssets";
+import {
+ PLUGIN_SETTINGS_CSP,
+ prepareSettingsHtml,
+ settingsBridgeAsset,
+} from "./pluginSettingsHtml";
+
+/** Serve only approved package bytes from an ephemeral, token-protected native loopback origin. */
+export async function preparePluginSettingsResources(
+ client: PluginSettingsClient,
+ theme: SettingsBootstrapConfig["theme"],
+ signal: AbortSignal,
+) {
+ if (!native) throw new Error("PLUGIN_SETTINGS_NATIVE_UNAVAILABLE");
+ const server = native;
+ const token = Array.from(getRandomBytes(24), (byte) =>
+ byte.toString(16).padStart(2, "0"),
+ ).join("");
+ const dir = new Directory(Paths.cache, "html-previews", token);
+ let closed = false;
+ let closing: Promise<void> | undefined;
+ let starting: Promise<string> | undefined;
+ const check = () => {
+ if (closed || signal.aborted) throw new Error("PLUGIN_SETTINGS_CLOSED");
+ client.assertCurrent();
+ };
+ const close = () => {
+ if (closing) return closing;
+ closed = true;
+ signal.removeEventListener("abort", abort);
+ closing = (async () => {
+ try {
+ if (starting) {
+ await starting.catch(() => {});
+ await server.stop(token);
+ }
+ } finally {
+ if (dir.exists) dir.delete();
+ }
+ })();
+ return closing;
+ };
+ const abort = () => {
+ void close().catch(() => {});
+ };
+ signal.addEventListener("abort", abort, { once: true });
+ try {
+ check();
+ dir.create({ intermediates: true });
+ const { document } = client;
+ const bridge = settingsBridgeAsset(document, theme);
+ const files: string[][] = [];
+ // Independent reads share the existing authenticated lease. Bound concurrency to
+ // avoid one network round trip per file without flooding the target computer.
+ for (let offset = 0; offset < document.files.length; offset += 4) {
+ check();
+ const batch = await Promise.all(
+ document.files
+ .slice(offset, offset + 4)
+ .map(async (declaration, index) => {
+ const mediaType = pluginSettingsMediaType(declaration.mime);
+ if (!mediaType) throw new Error("PLUGIN_SETTINGS_ASSET_INVALID");
+ const bytes = await readPluginSettingsAsset(
+ declaration,
+ (path, chunkOffset) =>
+ client.send({ kind: "asset", path, offset: chunkOffset }),
+ check,
+ );
+ check();
+ const file = new File(dir, String(offset + index));
+ file.create();
+ if (/^(text\/|application\/(javascript|json))/.test(mediaType)) {
+ let text = new TextDecoder("utf-8", { fatal: true })
+ .decode(bytes)
+ .split("cindy-ghost://" + document.manifestId + "/")
+ .join("/");
+ if (mediaType === "text/html")
+ text = prepareSettingsHtml(text, bridge.path);
+ file.write(text);
+ } else file.write(bytes);
+ // Keep Host MIME for validation; the native server takes a bare media type.
+ return [declaration.path, file.name, mediaType];
+ }),
+ );
+ files.push(...batch);
+ }
+ const script = new File(dir, String(files.length));
+ script.create();
+ script.write(bridge.text);
+ files.push([bridge.path, script.name, "application/javascript"]);
+ check();
+ starting = server.start(
+ decodeURIComponent(dir.uri.replace(/^file:\/\//, "")),
+ document.entry,
+ token,
+ PLUGIN_SETTINGS_CSP,
+ files,
+ );
+ const url = await starting;
+ check();
+ return { url, close };
+ } catch (error) {
+ await close();
+ throw error;
+ }
+}
diff --git a/apps/mobile/src/plugins/usePluginConsent.ts b/apps/mobile/src/plugins/usePluginConsent.ts
new file mode 100644
index 0000000000..96521dab28
--- /dev/null
+++ b/apps/mobile/src/plugins/usePluginConsent.ts
@@ -0,0 +1,48 @@
+import { useEffect, useRef } from "react";
+import {
+ getMobileAuthOwner,
+ isMobileAuthOwnerCurrent,
+} from "@/auth/authOwnerGeneration";
+import type {
+ PluginManagementController,
+ PluginManagementState,
+} from "./pluginManagementController";
+export interface PluginManagementConfirmationProps {
+ state: PluginManagementState;
+ controller: PluginManagementController;
+ deviceName: string;
+ active: boolean;
+}
+/** A late sheet callback cannot answer a different request or replacement controller. */
+export function usePluginConsent({
+ state,
+ controller,
+ active,
+}: PluginManagementConfirmationProps) {
+ const owner = useRef(getMobileAuthOwner()).current;
+ const live = useRef({ controller, active });
+ live.current = { controller, active };
+ useEffect(() => () => { live.current = { ...live.current, active: false }; }, []);
+ const consent = state.receipt?.consent;
+ const requestId = consent?.requestId;
+ const operationId = state.operationId;
+ return {
+ consent,
+ visible: active && state.outcome === "confirmation" && Boolean(consent),
+ answer: (accepted: boolean) => {
+ const current = controller.getState();
+ if (
+ !live.current.active ||
+ live.current.controller !== controller ||
+ !isMobileAuthOwnerCurrent(owner) ||
+ !current.online ||
+ current.busy ||
+ current.outcome !== "confirmation" ||
+ current.operationId !== operationId ||
+ current.receipt?.consent?.requestId !== requestId
+ )
+ return;
+ void controller.answer(accepted);
+ },
+ };
+}
diff --git a/apps/mobile/src/plugins/usePluginManagement.ts b/apps/mobile/src/plugins/usePluginManagement.ts
new file mode 100644
index 0000000000..adc6750a21
--- /dev/null
+++ b/apps/mobile/src/plugins/usePluginManagement.ts
@@ -0,0 +1,72 @@
+import { useEffect, useRef, useState } from "react";
+import { AppState } from "react-native";
+import { useAuth } from "@/auth/AuthContext";
+import { useDeviceLink } from "@/device-link/DeviceLinkContext";
+import { createPluginManagementClient } from "./pluginManagementClient";
+import {
+ createPluginManagementController,
+ type PluginManagementController,
+ type PluginManagementState,
+} from "./pluginManagementController";
+
+/** A screen owns one target. Visibility changes pause polling without replaying writes. */
+export function usePluginManagement(
+ deviceId: string | undefined,
+ online: boolean,
+ visible: boolean,
+ selectionKey?: string,
+) {
+ const { invoke } = useDeviceLink();
+ const { accountGeneration } = useAuth();
+ const [state, setState] = useState<PluginManagementState | null>(null);
+ const [controller, setController] =
+ useState<PluginManagementController | null>(null);
+ const [foreground, setForeground] = useState(
+ AppState.currentState === "active",
+ );
+ const scope = JSON.stringify([deviceId, accountGeneration, selectionKey]);
+ const liveScope = useRef(scope);
+ liveScope.current = scope;
+ const [publishedScope, setPublishedScope] = useState(scope);
+ const availability = useRef(online && visible && foreground);
+ availability.current = online && visible && foreground;
+ useEffect(() => {
+ const subscription = AppState.addEventListener("change", (next) =>
+ setForeground(next === "active"),
+ );
+ return () => subscription.remove();
+ }, []);
+ useEffect(() => {
+ setState(null);
+ setPublishedScope(scope);
+ if (!deviceId) {
+ setController(null);
+ return;
+ }
+ let disposed = false;
+ const client = createPluginManagementClient({
+ invoke,
+ deviceId,
+ isCurrent: () => !disposed && liveScope.current === scope,
+ });
+ const next = createPluginManagementController(client, {
+ online: availability.current,
+ onChange: (value) => {
+ if (!disposed && liveScope.current === scope) setState(value);
+ },
+ });
+ setController(next);
+ setState(next.getState());
+ void next.refresh();
+ return () => {
+ next.dispose();
+ disposed = true;
+ };
+ }, [deviceId, accountGeneration, invoke, selectionKey]);
+ useEffect(() => {
+ controller?.setOnline(availability.current);
+ }, [controller, online, visible, foreground]);
+ return publishedScope === scope
+ ? { state, controller }
+ : { state: null, controller: null };
+}
diff --git a/docs/design-evidence/2026-10-19/mobile-plugin-management-contract.md b/docs/design-evidence/2026-10-19/mobile-plugin-management-contract.md
new file mode 100644
index 0000000000..eda5ea1599
--- /dev/null
+++ b/docs/design-evidence/2026-10-19/mobile-plugin-management-contract.md
@@ -0,0 +1,162 @@
+# UI Implementation Contract: Mobile plugin management
+
+## Objective
+在手机查看目标电脑插件、安装/升级/卸载,以及直接编辑插件原设置页。
+
+## Inputs
+- 用户 2026-10-19 确认四项布局,并追加两个 Use it in 按钮吸底。
+- 用户随后授权开发,并明确允许原设置页中新输入凭证的限定 WebView 例外。
+- 统一开发基线 a83a9a0d1f3bda5e399dcd81844a567307de6663。
+
+## Scope
+- iOS / Android;Host 既有管理和加密设置接口。
+- 不包括文件导入、替换市场来源、服务端或新增原生依赖。
+- 存量插件无需重装、重授权或重新配置。
+
+## Current Implementation Map
+- PluginsScreen:目标电脑、详情读取、启停、导航与任务入口。
+- PluginDetailView(.ios):两端详情布局。
+- pluginDetailModel:Host 事实到展示状态;原权限缺少语义图标字段。
+- Host remotePluginManagement / mobilePageService:已有管理事务与 settings:open。
+
+## ASCII To Layout Contract
+1. 导航栏右侧齿轮菜单,按真实安装状态提供安装、升级、卸载。
+2. 页面顶部统一状态 Banner;无状态不预留空白。不在身份区重复。
+3. 插件身份、简介及目标电脑;保留启停开关。
+4. 头部下方独立配置卡,原 settingsHtml 负责字段和交互;高度随内容,窄屏可操作。
+5. 工具与权限;权限为 icon + 标题/说明的精简卡,无逐项展开。
+6. 按用户后续反馈恢复 Details:主标题下展示有值的作者、版本等详情,不渲染空字段。
+7. 两个使用按钮从正文移到底部固定操作区;留足安全区,不覆盖滚动内容,键盘出现时收起。
+8. 离线和旧 Host 保留可读信息;未知结果只查询原操作,不自动重做。
+
+## Platform Mapping
+| 区域 | iOS | Android |
+| --- | --- | --- |
+| 管理菜单 | reuse Stack.Toolbar.Menu 与系统 gearshape | reuse Material DropdownMenu |
+| 详情 | adapt SwiftUI List + RNHostView 原内容 | adapt RN ScrollView + 原生 Switch |
+| 原配置 | new 独立非持久 WebView + 加密桥 | new 同合同 WebView + 加密桥 |
+| 吸底按钮 | adapt 原生按钮,List 外布局 | adapt RN 按钮,ScrollView 外布局 |
+| 权限 | adapt Host kind/labelKey,未知用通用图标 | adapt 相同语义 |
+
+## File-Level Plan
+- 总控:PluginsScreen、PluginDetailView(.ios)、pluginDetailModel、必要小组件与五语文案。
+- T1:mobile 管理客户端、能力/回执解析、事务控制器及其测试。
+- T2:原配置 client/document/bootstrap/card 与独立测试。
+- T3:合成 fixture、Host 边界回归、权限 kind/labelKey 的兼容投影。
+- 三份独立 worktree;总控审核 diff 后集成一个预览分支,不覆盖旧脏树。
+
+## Validation Matrix
+- 真实组件测试:菜单、确认/取消、顶部状态、配置挂载、任务按钮与跨目标迟到失效。
+- 管理回执:未知/断线/过期/Host 重启不重放;取消不覆盖已提交结果。
+- 原配置:合成原 HTML 的读取/保存、主题、资源路径与桥,秘密不回读/不落盘。
+- 定向单测、受影响包 typecheck、mobile scope/smoke;提交前遵守仓库门禁。
+- 原生 iOS/Android:宽窄屏、滚动、键盘、安全区、菜单;Light/Dark 分别记录证据。
+- 未执行的实机 OAuth 或真实 Host 闭环单独标记,不以 mock 代替。
+
+## Known compatibility limits
+- 原 settings OAuth 的 127.0.0.1 固定端口 GET 回调由新原生包 CindyPluginOauth 接收,code 经原加密事务交回 Host,原 PKCE/redirect 不改;缺模块旧包提示更新。localhost/IPv6/CORS 回调仍拒绝。打开或关闭系统浏览器不算成功,须等待 Host 成功;Host 在原 deadline 内保活。第三方实机验收结果另记,不以单测代表登录成功。
+- 原页依赖浏览器本地存储/固定宽度等兼容缺口按实际结果记录。
+
+## Approval Gate
+- 页面实现已获用户授权,不再重复请求布局批准。
+- 新输入凭证只可瞬态存在隔离原设置页,走专用加密通道送目标;不入手机存储/日志/BC,不回读 vault。普通 mobile fetch 门禁不变。
+- 未授权 push/PR/合并;如实际改动触发原生冷更或插件基座合并门,按仓库规则处理。
+
+## Implementation and validation (2026-10-19)
+- 已集成安装/升级/卸载客户端、原设置卡、菜单/顶部 Banner/权限卡/吸底按钮及五语文案。
+- 目标与选择同步绑定;切电脑/插件的迟到菜单确认无效。成功回执后只有新快照读取成功才导航,读失败保留真实回执。
+- settings:open + 原 v3 密封请求;普通页面原有 fetch 门禁未放开。新输入只在隔离原页短暂存在,存储 API、页面日志、外部资源出网被禁;已存 vault 值不回读。
+- 设置页卸载时关闭租约;清理只绑定原账号/电脑/连接/安装批准,不因页面不可见拦住自己的关闭。普通命令仍要求当前页面有效。
+- 原页退后台后清理页面;浏览器授权返回重开原 HTML 读取目标事实,不重放保存。未提交输入不持久化,也不承诺后台草稿恢复。
+- Mobile 管理/设置/页面/原生组件定向共 144 项通过(10 文件 143 项 + 卡片生命周期 1 项)。Host 事务/权限投影 62 项通过。Mobile / Desktop typecheck、scope、smoke(2 项)、bootstrap --check 通过。
+- 系统 iOS QA 设备 423C9ECB-82C6-4398-AA64-ACC0FB65C306(iOS 26.5、402 pt)已从本 worktree 构建安装;原生指纹 5946001c5dbbe2ec1994a804dd2b88644536ebf6 匹配。首个 Metro 失败因忽略的 endpoint.dev.json 缺失,按仓库模板补齐后成功打包。
+- 原生 QA 使用 /plugin-management-preview 和显式 visual mock。原生组件/真实 WebView/原资源服务器均实际运行,后台为合成内存数据;不作为真实 Host、密码库或 OAuth 端到端证明。
+- iOS 已观察:Light/Dark 原页主题、原字段读回、长表单输入与保存后回读、长列表滚动、键盘弹出隐藏底部操作、齿轮原生菜单、底部安全区。修复 RNHostView 无界高度下 WebView 根容器坍缩:卡片根容器使用内容测量高度。
+- Maestro 最初点中了同名头部文字,随后 HideKeyboard/长列表 15 秒断言未通过;改用截图定位输入、系统完成按钮和足够滚动范围后,保存后的回读文本与 Light 模式断言通过。未把失败脚本算作通过。
+- 截图保存在仓库外验收目录 `mobile-plugin-management-2026-10-19/`。ios-detail-light.png、ios-detail-dark.png、ios-menu-dark.png、ios-keyboard-dark.png、ios-settings-readback.png。
+- 未验证:真实账号 B/C 隔离 Host 完整安装→配置→使用→升级→卸载、第三方 OAuth/MFA、320 pt/平板/旋转、真实两台电脑弱网与休眠。没有操作真实插件/凭证,没有提交、推送或 PR。
+
+## Final Android QA and review
+- Android 14 arm64 系统 AVD Cindy_Plugin_Detail_Acceptance(emulator-5554,1080×2400)已构建安装;APK 与当前 Expo Updates 开发指纹均为 c40ef6512351ecbd30a4a96d82ea8c94e8c5c623。没有修改原生配置、依赖声明或 lockfile。
+- 首次构建使用了尚未稳定的 Gradle 生成缓存;增量任务沿用旧 fingerprint。显式 Global 环境重新生成该构建资源并重新打包后匹配。QA App 遗留 localhost:8082 调试偏好已改为本 worktree 的 8081;没有读取 SecureStore。
+- Android 真实原生菜单、原 HTML/JS 表单、Light/Dark、字段输入、键盘出现时收起底部按钮、保存及回读已观察。Maestro 断言 Ordinary settings read back: QA Mac Android 及长表单滚动到 Permissions 通过;后台仍是合成数据,不代表真实目标电脑闭环。
+- Android 截图与 iOS 同目录:android-detail-light.png、android-menu-light.png、android-keyboard-light.png、android-settings-readback.png、android-detail-dark.png、android-permissions-dark.png。部分操作截图保留开发环境 Refreshing 提示,不作为生产 UI 内容。
+- 最终独立只读复核覆盖管理 controller/hook/页面的目标切换、取消、快照/回执与不重放,未发现可证实的严重问题;未把复核等同运行测试。
+- 最后一次 Mobile typecheck 退出 0;git diff --check 通过。全量单测未运行,未提交或发布。
+
+## Final runtime follow-up
+- iOS 最终核对出现开发指纹变化后,已按仓库脚本重新构建并安装同一系统 QA 模拟器;新包 fingerprint 为 d00d1303a3e13cbddacc58b12fb8698364e5b33c。构建/安装成功,脚本因文档更新使 Metro source label 陈旧而在启动检查返回 target-stale;随后单独刷新开发服务核对身份。
+- Android 17:47:28 在长表单底部输入派发出现一次 ANR(等待 5232 ms),当时 iOS 正在本机原生编译。主线程栈停在 ART/JNI 系统等待,JS 线程处于 Looper 等待;这些证据不能单独断言根因是编译资源竞争。
+- 编译结束后重启同一 QA App,完整重跑长表单滚动到 Permissions → 继续滚动 → 打开管理菜单,Maestro 全部通过,lastanr 时间未增加。没有为未证实的原因修改生产代码;保留该次 ANR 作为后续实机稳定性观察项。最终权限截图更新为此次复测结果。
+
+## Follow-up: native layout and production integration (2026-10-19)
+- 用户确认沿用现有 Expo SwiftUI 原生组件。iOS 顶部改为系统 Toolbar 菜单;配置、工具、权限、详情使用统一主标题层级。详情恢复非空元数据与版本。底部改为上下排列的原生主次按钮,渐变透明承托背景,文案明确新建任务或在已有任务中使用;键盘出现仍收起。
+- iOS 合成原页已目检浅色/深色、顶部菜单、Details 和底部按钮;这一轮 Android 布局尚未重新目检。截图:/tmp/plugin-details-footer-light.png、/tmp/plugin-details-footer-dark.png、/tmp/plugin-toolbar-light.png、/tmp/plugin-toolbar-dark.png、/tmp/plugin-menu-dark.png。
+- GPT-6.1 手机接线修复:市场已安装项只导航到快照唯一匹配的物理实例;旧菜单/Alert 绑定账号、选择代次及 controller;回读失败不使用旧快照导航;旧 Host 状态不得发布到新目标。生产 hook/controller/client 页面回归 38 项、controller 28 项通过,mobile typecheck 通过。transport 隔离测试不等于真实网络验收。
+- GPT-6.1 Host 修复:仅绑定在途授权在原 transaction deadline 内保活;取消、显式关闭、账号/控制端/approval 失效仍关闭;完成恢复普通 idle TTL。同一 requestId 在成功或失败后均不可重复执行。相关 5 文件 94 项测试通过,desktop typecheck 通过。没有扩大 OAuth 支持范围。
+- 总控复核发现并要求修复一次性 running 标记的回归;新增成功/失败重放断言先失败后通过。最终 git diff --check 通过。未运行提交前全量门禁,未提交/推送。
+- 当前专用 iOS 预览已关闭 EXPO_PUBLIC_CINDY_MOBILE_VISUAL_MOCK 与 EXPO_PUBLIC_CINDY_PLUGIN_DEMOS,并完整重开 App。正式入口停在真实登录页,等待用户自行登录;未复制账号令牌或读取凭证库。MCP 宿主存在真实插件,但尚未证明它与手机目标电脑相同。
+- 仍未完成:真实账号/目标电脑的管理能力发现、真实插件原表单读取、安装/升级/卸载及第三方 OAuth 闭环。上述单测和合成截图不作为这些项目通过的证据。
+
+## Real login and Host capability follow-up (2026-10-20)
+- 用户报告停在浏览器登录等待页。确认本任务 Metro 已因 `WS_ERR_TOO_MANY_BUFFERED_PARTS` 退出;使用标准脚本恢复并重开专用测试 App 后,用户确认真实登录成功。没有清除账号数据或读取登录令牌。
+- 只读内存复现确认 dev-middleware 所用 ws 7.5.12 未在消息结束重置片段计数:上限设 3 时第四条独立完整消息同样失败。当前仅恢复服务,未改依赖或原生指纹;开发服务长连接复发风险仍在。
+- GPT-6.1 修复登录等待页:捕获原生浏览器启动拒绝并显示既有错误;等待期间允许取消;过期原生结果返回 false,不污染新登录尝试或产生未处理拒绝。总控复核补强迟到结果测试,最终 148 项定向测试、mobile typecheck 和 diff 检查通过。真实用户登录成功发生在恢复服务后,不冒充故障注入运行验收;没有为测试退出用户账号。
+- 已目视确认真实目标「公司电脑-new」的 Google Calendar / Remotion 插件详情。Remotion 顶部明确显示目标电脑需更新才能管理插件,原设置仍为电脑端配置提示,齿轮禁用。因此真实详情读取已验证,当前目标尚未提供 management 能力,不能宣称安装/升级/卸载或原配置闭环通过。截图 /tmp/plugin-real-detail-top.png。
+
+## Real settings failure diagnosis and repair (2026-10-20, after login)
+- 本次实际目标回执已是 management `supported`、snapshot.settingsPage=true,且已匹配真实安装实例。前段记录的 unavailable 状态不能用于解释用户 10:37 的新截图;本次无需用户更新目标电脑。
+- 根因一:Host 资源声明使用 `text/html; charset=utf-8` 等完整 MIME,手机解析器只接受裸类型;TapTap Maker 的 13 个资源共 9,055,462 bytes,12 个文本资源因此被拒绝。修复为校验 UTF-8 参数并保留原声明用于逐块一致性校验;交给现有 native preview 的文件表转换为裸类型。未改 native 接口、依赖或指纹。
+- 根因二:配置内容已运行、WebView 已回报内容高度,但 iOS SwiftUI List 内嵌 VStack 中的 RNHostView 不显示配置子树(加载提示及临时原生文本也不可见)。配置承载视图改为独立 List 行,保留原生标题和原作者表单;真实 Google Calendar 与 TapTap Maker 均已显示。临时诊断文本和日志已移除。
+- 根因三:Host `fetchGhostSettings` 返回 `PluginPageFetchResult.base64`,原设置桥误读 `body`,原页无法解析账号状态。桥改为按协议还原字节后构造 Response,保留状态码、MIME、UTF-8 和无正文响应;合成预览及 smoke fixture 同步改用真实返回格式。桥测试先复现 OAuth 返回和 XHR JSON 两个失败,再修复通过。
+- 错误提示分开加载失败、操作未完成与提交结果未知;提供“重新加载设置”,只重新读取 Host 状态,不重放提交。未知结果只在变更请求交给加密传输后标记。
+- 验证:本次相关 5 文件 45 项测试通过,mobile typecheck、test:scope、bootstrap generator --check、git diff --check 通过。沿用此前登录修复的 148 项验证,未重跑无关全量测试。
+- 实际 iOS 正式入口、真实目标“公司电脑-new”:Google Calendar 原配置正常读回;TapTap Maker 原配置显示已连接状态和脱敏凭证摘要,能滚动到真实项目列表。Maestro 对“已连接 TapTap Maker”及长表单滚动通过。没有更改真实配置、点击连接/保存/安装/升级/卸载,也没有实际执行第三方 OAuth。配置包约 9 MB,首次资源读取仍有可感知等待,不能称为即时打开。
+- 真实 TapTap Maker 原页已目检 Light/Dark,主题切换后仍显示已连接状态;截图存于任务 artifacts 的 real-settings 子目录。这轮 Android 未复测。未提交、推送或发布。
+
+## Permission summary card correction (2026-10-20)
+- 用户再次明确:权限只显示主标题、无说明正文;逐项图标与 PC 语义一致,集中在一张卡片。iOS 原生 List 现在复用通用 PluginPermissionCard,取消之前重复的 SwiftUI 长描述/统一盾牌实现;窄屏标题自然换行,不截断权限含义。
+- GPT-6.1 只读复核确认移动端 20 项 kind 与 panelLeft / networkSecret* 特判均与 PC permissionItemIcon 一致;图标采用同款 Lucide、20dp 与手机轻描边 token,旧 Host 回退也使用 PC 的 Shield。
+- 真实目标仍缺 kind/labelKey:重新打开真实 TapTap Maker 后,9 项回执的两字段均为 undefined;normalizeRemoteBlocks 保留 data、model 未裁剪,不能把本地已改 Host 投影当作真实目标已运行。现有集成树 mobilePageService 已透传两字段并有回归,但目标 Host 尚须运行配套实现后重验逐项图标。没有按文案猜图标、没有为截图伪造类型。
+- 本轮真实 iOS 已看到单卡片且无描述;21 项原生视图测试、mobile typecheck、diff 检查通过。图标真实验收未通过(当前仍是兜底);Android 未做此次原生目检。未提交/推送或更新目标安装包。
+
+## Permission Host integration acceptance (2026-10-20)
+- 核实“公司电脑-new”是本机 /Applications/Cindy.app 正式实例,保持原进程 PID 67635 运行,没有更新、重启或改其插件数据。此前该实例的 9 项权限缺 kind/labelKey 的事实不变。
+- 复用既有隔离测试 profile remote-plugin-target-1015;标准入口 `pnpm restart:desktop:remote --region=global --isolated=remote-plugin-target-1015 --passive` 返回 DESKTOP_DEV_VERDICT=ready,desktop:whoami 的 match=true、分支 feat-mobile-plugin-management、HEAD a83a9a0d1 和当前未提交集成树一致。测试设备“插件测试 B · 目标端”在线且 remoteControlEnabled=true,无需复制正式凭证或重新登录。
+- 测试 profile 仅保留 TapTap Maker 历史数据,当前未装包。通过手机真实市场→齿轮 Install→真实权限确认→Allow and continue 安装 2.1.22;Host listSync 回读 `_root__taptap-maker`、namespace=null、enabled=true。测试范围仅这个隔离目标,未调用插件工具、保存配置、卸载或触发第三方 OAuth。
+- 手机真实详情回执的 9 项 kind/labelKey 已完整收到:node/nodeChildSpawn、node/nodeMcp、pick/pick、session-context/sessionContext、preview/preview、command/command、card/card、card/cardExternalLink、code/code。未根据文字猜测、未注入 mock 回执。临时只记录这两字段和目标/实例的诊断日志已从代码移除。
+- iOS 实际详情 Light/Dark 均目检:一张卡片只显示标题,无描述,9 项图标对应 PC 同款 Cpu、FolderOpen、MapPin、AppWindow、Terminal、LayoutTemplate、FileCode2;自然换行且图标左侧对齐。截图和精简回执在 artifacts/real-settings/permissions-testb-{dark.png,light.png,receipt.json}。此前 permissions-summary-*-host-metadata-pending.png 是正式旧 Host 的历史证据,不代表本次结果。
+- 复用已完成的 21 项权限原生视图测试及 mobile typecheck;此次没有再次改动正确映射或字段透传,git diff --check 通过,无提交/推送/发布。Android 此次未目检。
+- 配置失败定位仍保留上一节三项真实根因(MIME 参数、RNHostView 嵌套布局、base64 响应桥)与已验证的读取范围;真实配置写入/第三方 OAuth、升级/卸载及 Android 完整闭环仍未验收,不将本次权限与隔离首装通过扩大为全功能通过。正式实例仍需将来正常集成发布后获得字段透传。
+
+## Corrected whole-page layout check (2026-10-20)
+- 用户再次提供实测截图:原配置加载后头像移到屏幕外、标题消失、开关越界、设备名挤窄、描述横向裁切。总控在同一 iOS 模拟器、同一真实测试 B/TapTap Maker 页面复现。上一节仅核对权限卡及回执,未覆盖配置加载后的头部,不构成整页验收通过;该遗漏明确保留。
+- 具体责任点是 iOS 头像 RNHostView 的首 UIView 不稳定:fallback View 与加载后的 Image 互换,而 Expo ApplySizeFromYogaNode 的 StateObject 尺寸观察器仍持有首次 UIView。未改 Expo/native:用固定 72×72、collapsable=false 的 RN View 作为永久根,仅在其内部切换图片,并用 SwiftUI 72×72 外框约束头像。没有给整页加裁切或写死描述宽度来掩盖问题。
+- GPT-6.1 执行这一处修复,总控增加 fallback→remote image→fallback 根身份回归。22 项 pluginNativeViews 测试、mobile typecheck、git diff --check 通过。
+- 实机路径(系统 iOS 模拟器):真实列表重进 TapTap Maker→等 Connected to TapTap Maker 与完整原配置→配置中部→Tools→Permissions→Details/安装路径→回顶。Dark 与 Light 均执行、逐张目检;头像、标题、开关、描述恢复正常,滚动回顶未再横向溢出。原配置加载仍需等待,未修改凭证/配置、未执行授权或插件工具。
+- 前后及各模块截图在 artifacts/real-layout/{overflow-before.png,reopen-dark.png,reopen-light.png,form-*,tools-*,permissions-*,details-*,return-top-*}。当前仅证明上述 iOS 路径的布局修复;Android/iPad/大字体未在本轮验证,管理与 OAuth 其他未验项仍保留。无原生指纹改动,无提交/推送。
+
+
+## App Store information rows and bounded settings card (2026-10-20)
+- 按用户提供的 App Store Information 参考,iOS Details 使用左侧次要标签、右侧主值、50pt 行与细分隔线;包含内容和安装路径默认单行摘要,可分别展开完整 Host 原值。复用现有 Expo SwiftUI,不新增原生依赖。
+- 原生实测发现:同一 List row 内两个 DisclosureGroup 会一起响应;仅 plain buttonStyle 不足。改为每项独立 Section 子行后,Light/Dark 均验证内容与路径独立展开/收起,切换插件清除展开状态。没有删减原始详情字段。
+- 配置卡沿用页面 20pt 外侧对齐,统一 16pt 内边距。短表单随内容收缩;长表单外框上限为窗口高度一半且不超过 420pt(含内边距),超过后仅 WebView 内部滚动,保留主题滚动指示器。窗口尺寸变化不重开配置会话。
+- 真实 TapTap Maker 的原输入继承 13px,聚焦会触发 iOS 自动缩放及横向裁切。桥仅将小于 16px 的文本输入/textarea/select 字号提高到 16px,保留原本更大字号;新增控件同样处理,pagehide 解除观察,不读写输入值,不禁用手动缩放。真实原页重新打开后,聚焦 PAT 输入不再横向放大,退出聚焦恢复底部 CTA;未输入、保存或提交凭证。
+- 同一系统 iOS 模拟器、隔离目标“插件测试 B · 目标端”、真实已装 TapTap Maker:最终 Light/Dark 卡片边距、高度、内部滚动已目检;Details 独立展开/收起均实测。截图位于任务 artifacts/real-information-settings/。输入聚焦使用模拟器硬件键盘模式,仅验证焦点/原生工具条及布局,不声称软件键盘完整验收。
+- 本轮三个定向测试文件 36/36 通过,mobile typecheck、bootstrap generator --check 与 git diff --check 通过。未改 native fingerprint 输入、依赖或正式客户端;无提交/推送。Android、iPad、大字体本轮未目检;真实配置写入、第三方 OAuth、升级/卸载的既有未验范围保持不变。
+
+
+## Details directional motion correction (2026-10-20)
+- 用户要求 Details 向下展开、向上收起,不使用 bounce out。替换默认 DisclosureGroup 弹性事务为现有原生 Button + 受控有限高度,沿用 motionDuration.base 的 200ms easeInOut;系统减弱动态效果开启或尚未读取时不播放。
+- 此节更新前一节布局实现:Details 合为一个 List 行,内部各项仍独立原生 Button 和细分隔线。原先独立 List 行会在动画前先重排行高,造成标题跳位;List 级动画还会产生行快照重影。最终仅 Details 原生 VStack 一处动画、内容顶部锚定与裁切,所有后续信息行同步移动。切插件重挂载测量节点并清展开状态,关闭内容对辅助功能隐藏。
+- 真实测试 B/TapTap Maker 系统 iOS 模拟器录屏逐帧验证:最终展开分隔线从 y1226 单调增加至1343,收起从1343单调回1226(942px宽归一化帧);无超出终点或反向回弹。最终 Light 模式另验安装路径与包含内容独立展开/收起;完整原值保留。录屏和开合帧图位于 artifacts/real-information-settings/plugin-details-motion-accepted.mp4、plugin-motion-group-{open,close}.png。
+- 最终 23 项原生视图测试、mobile typecheck、git diff --check 通过。无原生指纹/依赖改动,无提交/推送。Android、本轮系统减弱动态效果开关的实机路径未验;既有配置写入/OAuth等未验范围不变。
+
+
+## Scoped plugin notices and native presentation (2026-10-20)
+- 用户确认同时修改提示 UI 与优先级。去除管理→配置→市场→状态→运行异常的跨区域互斥链:顶部只显示离线、详情读取失败、停用/安装恢复/运行暂停;配置状态和错误留配置区,管理事务单独显示,权限确认进入现有系统 sheet。加载使用进度,禁用由开关表达,未安装不再重复提示,普通通知/取消反馈使用不占位浮层。
+- iOS 使用现有 SwiftUI 图标、文字和按钮;提示为紧凑圆角,单操作放右侧,说明只在有额外信息时出现。Android 对应语义 token 实现。未知操作保留原 operationId,仅核对结果;离线+未知结果可以并存。确认包含来源、版本、增减权限及原风险说明,迟到确认绑定原账号/控制器/operation/request。
+- 复用系统 iOS 模拟器与隔离目标“插件测试 B · 目标端”。目标本轮退回登录页,经用户重新登录后恢复。真实 Gmail 原配置页 Light/Dark 已目检:需要配置提示在配置标题下,顶部无重复提示,原账号配置卡正常加载。
+- 对已核实的隔离 Host 进程短暂 SIGSTOP 并 finally SIGCONT 自动恢复,复现真实 settings 请求超时。55 秒内服务端 presence 未变为 offline,因此该证据仅证明配置读取失败,不作为新顶部离线态实测。发现并修复嵌套 Host 自测水平尺寸造成说明截断、Reload 不可见;现采用 RN 实宽约束与仅纵向测量。外层最小高度从160缩到44,保留原 Card 高度与lease规则。最终错误态 Light/Dark 说明完整换行、重新加载可见;点击 Reload settings 后成功读回真实 Gmail 原页。
+- 组件/Screen/原设置边界首轮69项、移动五语结构20项通过;后续新增尺寸回归后 native views 30项及原设置2项分别复跑通过。mobile typecheck、i18n/glossary与 git diff --check 通过。截图及源码指纹位于 artifacts/real-plugin-notices/。
+- 本轮未触发真实安装/升级权限确认、真实保存或第三方 OAuth;新确认弹层与离线+未知组合由组件回归覆盖,未声称原生全状态实测。Android/iPad/大字体本轮未目检。测试 B 已恢复,正式客户端及其数据未操作;未提交、推送或改动原生依赖/指纹。
diff --git a/docs/design-evidence/2026-10-21/plugin-authorization-routing-plan.md b/docs/design-evidence/2026-10-21/plugin-authorization-routing-plan.md
new file mode 100644
index 0000000000..34ecf3814e
--- /dev/null
+++ b/docs/design-evidence/2026-10-21/plugin-authorization-routing-plan.md
@@ -0,0 +1,203 @@
+# 插件原配置页移动端兼容:根因与统一方案
+
+日期:2026-10-21。状态:代码已实施,部分真实授权闭环仍未验收。
+
+以下调查与方案保留实施前事实;当前完成范围及验证限制以文末记录为准。
+
+## 范围修正:配置页必须可用,不只是可显示
+
+本方案现覆盖原配置页完整交互;下文授权调查是其中一个子问题。不能把支持 settingsHtml 等同于兼容原页面,也不能用新增一个 WebView 或少量合成表单测试证明完成。
+
+### 已确认的不同故障
+
+1. Outlook:原页标准 OAuth 在旧 Host 丢失远程上下文,落入电脑本机浏览器;现有能力协商不能识别该入口未接通。证据见下文。
+2. Mivo 1.7.9 普通链接:settings.html 的“前往控制台获取”是 HTTPS anchor,指向 aigc.xindong.com。Mobile PluginSettingsCard 的 onShouldStartLoadWithRequest 只允许本地包内 HTML,外链直接返回 false;onOpenWindow 是空处理,没有本机浏览器接管。无需 OAuth,更新 Host 也不会修复这个手机容器缺口。
+3. Mivo 凭证校验:原 settings.js 通过 BroadcastChannel('mivo') 发送 key-metadata-query,包含新输入值;手机 bootstrap 的 containsSensitiveInput 同步抛出 SecurityError。原脚本把“保存 → 元数据清理 → 回读 → 有效期查询”包在同一 try/catch,所以实际保存成功后也可能显示“保存失败”。这是兼容语义错误,不能靠删除错误文案或吞掉异常掩盖。
+
+隔离复现:已安装 Mivo 原 HTML/JS + 当前生产生成的 bootstrap + 内存假 Host;未发起网络、未读写真实凭证。结果为 PUT 次数 1、Host saved=true、元数据查询转发次数 0、页面 savedBadge=on,同时 status=“保存失败,请重试”。这证明桥与原脚本不兼容,不是原生设备完整验收。
+
+### 根因层次
+
+- 产品契约缺失:承诺“原配置页”,实现只接通部分浏览器/Host 能力,没有列清原页面实际依赖。
+- 交互归属缺失:外链应由当前控制设备打开、OAuth 应由原 Host 执行授权事务、电脑目录应留在目标电脑;现在部分动作直接丢弃,部分错误回落本机。
+- 数据契约冲突:普通 BC 被保留,但原页使用的凭证校验消息被字符串检测阻断。传输加密不等于接收端隔离;不能直接解除检测并宣称问题解决。
+- 失败不可见:全局 error/unhandledrejection 被 preventDefault,窗口事件空处理;页面可能不知道动作未执行,或把后续失败误当提交失败。
+- 验收粒度错误:测试桥协议与合成状态,没有逐个走真实配置流程,且把测试 Host 成功外推到不同正式 Host。
+
+### 已安装包静态盘点
+
+只读扫描当前正式 profile 下 12 个带原 settingsHtml 的插件及入口直接引用的脚本。此为入口盘点,不是动态兼容判定,也不涵盖惰性加载和所有平台。
+
+| 实际样本 | 已发现的交互 |
+| --- | --- |
+| Mivo | 获取 Key 外链、Secret 保存/清除、BC 有效期查询/缓存 |
+| XD Sites、Web Search、同程诚信 | 外部链接 |
+| Gmail、Google Calendar、Outlook | 标准 OAuth、账号回读/管理;Outlook bundle 的 clipboard 命中仍需区分库代码和实际入口 |
+| TapTap Maker | 原表单、频道、target=_blank 控制台入口;与标准邮箱授权不同 |
+| Remotion | 原表单与频道 |
+| XD Feishu | 频道与 OAuth |
+| GitLab、Baguette Simulator | 频道 |
+
+### 整体实施顺序
+
+**A. 先定义 Desktop/Mobile 共用的交互合同。** 以 PC 实际已支持的原设置页入口为准,逐项标明操作发起设备、执行设备、输入/返回、取消和恢复。对照 Desktop 本地与远程容器,区分 PC 已有缺口和手机新引入缺口。不要以“完整浏览器 API”作为无限范围承诺。
+
+| 类别 | 目标行为与实现落点 |
+| --- | --- |
+| 普通链接 / 新窗口 | anchor、target=_blank、window.open、用户触发 location 导航共用一个导航处理器,按 PC 既有 URL/确认规则交当前手机原生浏览器;禁止用开放任意 WebView 导航代替。包内页面/锚点仍在原文档。拒绝必须有可理解的即时反馈。 |
+| 表单 / fetch / XHR | 原 submit 监听器、按钮、返回码和异步回调保持语义;明确 Host API 与包内资源。不把所有 HTML form 都认定失败:JS preventDefault 后 fetch 与原生 form navigation 分开验证。 |
+| OAuth / 设备码 / CLI | 共用受信授权事务;手机负责用户交互,目标保管凭证并产生最终完成回执;旧能力不静默回落 PC。详见原授权方案。 |
+| BC / 原页与插件逻辑通信 | 保留原请求与响应关联、订阅顺序、错误和结束语义。凭证校验单独解决受信传递边界,不能把某个插件的消息名写进通用容器。 |
+| Host confirm / directory | 复用已接通的原生回调;目录明确选择目标电脑目录,取消不会误报成功;异步回复固定旧页面身份。 |
+| 剪贴板 / 文件 / 下载 | 先核对 PC 已支持和真实插件实际用法,按当前设备与目标电脑区分责任。现有 clipboard 禁用、下载拒绝不是完成适配;不能用关键词静态命中当成功或失败证据。 |
+| 浏览器往返 / 后台 | 普通外链与授权分别收口,回到页面重新核对 Host 事实;不得意外重放提交或把资源服务停止变成无声空白。未提交敏感输入按既定生命周期清理,不写磁盘来保草稿。 |
+| 出错与诊断 | 保留原页可观察错误/HTTP 结果;缺能力时给当前操作反馈,不增加常驻状态面板。诊断仅记录动作类别、阶段和受控错误码,不记录输入、完整 URL、频道内容或凭证。 |
+
+**B. 先补普通交互,再接通授权版本差异,统一验证生命周期。** 导航处理器放在配置容器与平台适配层;OAuth 修复落在共享 executor/能力协商;原页数据留在原协议。不是为每个插件增加按钮或重造表单。
+
+**C. 凭证频道冲突必须在编码前解决。** 当前任务限定例外明确“新输入凭证不入 BC”,而 Mivo 的实际原页正依赖该行为。当前实现无法同时保证“不改所有旧页、禁止这种原行为、完全兼容”三件事。不能把这个冲突交给用户点重试。
+
+优先研究复用 Host 的受控凭证校验能力,让原插件按声明引用或一次性保密请求完成校验、频道只返回结果。需核对 PC 与存量兼容,必要的作者 API/插件升级应明确列出;若不能在现有契约内无损兼容,就单独提交具体边界设计,而不是直接开放通用 BC 明文。该项尚未定稿,不声称 Mivo 完整兼容已经有可实施结论。
+
+**D. 以真实原包的完整用户流程验收。** Mivo 要完成“打开控制台 → 返回 → 输入 → 保存 → 有效期结果 → 重开回读 → 清除”;TapTap Maker 覆盖控制台新窗口、原表单与频道回执;邮箱覆盖授权;其余样本覆盖实际用到的能力。合成测试只用于制造取消、断链、失败时序,不替代原包操作。
+
+新增完成条件:手机可见的每个配置操作都有真实作用或准确的操作级失败;没有静默 no-op;没有 Host 已提交而容器造成页面假失败;PC 本机行为与旧数据不退化。执行矩阵记录 iOS/Android、实际 Host 构建与原生包,未验证项单列。
+
+本轮仅扩大诊断和方案,未放宽任何权限、未修改 Mivo 原包或运行代码。后续实现不得用“未知动作一律禁用”作为兼容交付。
+
+## 授权子问题的目标
+
+用户从手机插件原配置页点击授权,浏览器在当前手机打开;安装插件的目标电脑负责令牌交换、保存和账号事实。控制端不因目标缺能力而悄悄改为在目标电脑打开网页。
+
+沿用原 settingsHtml、原 HTTP 结果和现有 v3 加密事务;不按 Gmail / Outlook 名字分支,不重新制作配置表单,不要求存量用户重装插件或重新配置。
+
+## 本次实查
+
+- 模拟器当前 Outlook 页面显示目标「公司电脑-new」,并非之前 Gmail 验收使用的「插件测试 B · 目标端」。截图取自同一已启动模拟器,未发起第二次授权。
+- 当前运行正式进程为 /Applications/Cindy.app/Contents/MacOS/Cindy,包版本 0.1.112。
+- 只读检查该安装包 app.asar:原 OAuth HTTP handler 调用 connectAccount 的 options 含 assertCurrent、scopes、clientId、deliveryHosts,没有 remote。同包另一个 setup action 入口已有 remote,说明不是完全没有授权桥,而是入口接线不一致。
+- 当前 owner worktree 的 ghostOauthEndpoint.ts 已新增捕获并传递 RemoteOauthContext。这是通用 endpoint 修复,没有 Gmail 特判;但它尚不在正在运行的正式包中。
+- 已安装 Outlook 2.1.8 的 settings.js:添加邮箱 / 重连调用 POST /oauth/<key>/connect;没有 window.open 或 BroadcastChannel 发起此动作。
+- Outlook 声明两个提供方:global 使用 login.microsoftonline.com,china 使用 login.chinacloudapi.cn;都启用 PKCE,回调端口分别为 53687、53688。没有发现该按钮需要专用 Outlook 路由。
+- 目前 Host 的 capabilities 只有通用 encrypted / callback / authorizationV1 等能力,没有证明“原设置页 OAuth 入口完整转交控制端”的能力。手机据此不能识别上述半接通的旧版本。
+
+证据足以定位当前包的路由缺口,但本轮未复现 Microsoft 登录完成、未读用户令牌、未重启正式客户端。不能把静态定位写成 Outlook 修复验收通过。
+
+## 真实调用链与责任
+
+原 HTML fetch
+→ Mobile pluginSettingsClient 将 connect 转为 settings authorize
+→ MobilePluginPages 建立一次性 settings-oauth action
+→ v3 transaction 绑定 owner / controller / 安装实例 / approval
+→ runSettingsAuthorization 在受信远程上下文执行原 endpoint
+→ fetchGhostSettings → handleGhostOauthRequest
+→ GhostOauthAccountManager.connectAccount
+→ startGhostOauthFlow
+→ 控制端浏览器 / 回调接收器
+→ 加密 callback 回 Host
+→ 原令牌交换与持久化
+→ 原 HTTP 结果及 /oauth 事实回读。
+
+当前底层以 remote 是否存在决定打开位置:有 remote 请求控制端;缺失则调用 Host openExternal。旧 endpoint 漏传时,“远程请求”被误解释为“本地请求”。
+
+## 按机制盘点,不按插件名字补丁
+
+| 入口 / 机制 | 当前事实 | 统一处理 |
+| --- | --- | --- |
+| 原页 POST /oauth/<key>/connect | Gmail 与 Outlook 同类;旧包此入口漏传 remote | 由原 settings-oauth action 贯穿原 executor,复用共同引擎 |
+| 原生 setup / 授权卡 | 已有独立 action 与远程上下文接线 | 与原页共同验证控制端、回调和完成判据;不另建事务 |
+| OAuth code + PKCE / broker 回跳 | 目标持有交换信息;手机已有 loopback 原生接收模块 | 保持提供方登记的 redirect URI;回调回原 Host,不能把打开网页当成功 |
+| Device code / browser confirmation | 已有 typed authorization 与 Node 授权桥 | 控制端展示或打开,执行端继续实际轮询/finish;明确设备码与 callback 不是同一流程 |
+| 原页 BroadcastChannel → 插件逻辑 → Node/CLI | 普通 relay 转发不等于授权上下文透传;Node bridge 绑定 live RPC / callId | 逐入口核对真实绑定;不能把任意频道消息猜成授权,也不能把远程来源丢掉后当本机请求 |
+| 插件自行启动浏览器的外部 CLI / OS 操作 | 不能由手机 WebView 拦截来保证重定向 | 查是否使用现有受控 authorization API;未接入的标明边界,不能宣称任意旧 CLI 已适配 |
+| API Key / PAT / connection | 原表单专用加密 fetch,不是浏览器 OAuth | 保留现有读写与回显;不为这类增加外部授权状态 |
+| 普通外链导航 | 与授权不同;现有手机原页默认不允许任意跳转 | 不用放开 window.open / WebView 导航来掩盖 OAuth 缺口 |
+
+TapTap Maker 的 Runtime/频道路径与邮箱标准 OAuth 不能互相替代验收。需要逐条检查实际动作是否进入受控授权 API;本方案不假定其所有按钮都已支持。
+
+## 实施设计
+
+### 1. 保留共用引擎,明确动作来源
+
+在 Host settings 授权执行边界捕获受信的控制端上下文,显式送至原 OAuth executor。
+本地操作与远程操作在该边界明确区分;已知远程来源而缺失上下文时终止该动作,不能选择本地浏览器。
+来源只能由已验证的 Host action 建立,插件 HTML 或普通请求参数不能自行指定 controller。
+
+保留本机 PC 自己点击设置时的现有本机流程;不修改第三方 scope、clientId、redirect URI,也不增加服务商白名单或名称特判。
+应评估最小的内部参数传递方式,避免同时叠加第二套授权状态机。
+
+### 2. 协商整条入口的能力
+
+在既有 settings:open 文档追加可选 controllerAuthorization: true,由完整接通原设置页 OAuth 入口的 Host 声明。settings-page 加密会话仅允许 settings 命令,不在该会话调用通用 capabilities。
+手机在创建会触发外部副作用的授权动作前检查该能力及本机回调能力。
+
+缺失时:原表单保留,读取和其他已支持配置照常;这次授权返回原表单可显示的受控失败,准确说明需要更新哪台设备。不新增常驻 Banner,不自动重试,不转去 PC。
+通用 authorizationV1 或 settingsPage=true 不可当作这项能力的替代。
+这是客户端协议追加字段,无需因为此修复新增服务端;老客户端忽略字段,原本 PC 本地使用不退化。
+
+### 3. 浏览器与回调归属保持一致
+
+复用 CindyPluginOauth 和现有授权 controller。
+手机打开 → 手机接收 callback → v3 密封交原 Host → Host 交换/保存 → 原页回读。
+端口冲突、用户取消、后台、超时、断链、切目标与账号失效沿既有事务收口,不能将浏览器 dismiss 当成功。
+原始 state / code / token 不进入日志、普通 BroadcastChannel、通知或任务内容。
+
+### 4. 核对其它授权入口,修正能力承诺
+
+枚举原表单 HTTP、setup action、Node typed authorization、device authorization、BC/CLI 自定义授权路径的实际调用点与来源绑定。
+能够复用现有桥的只补缺失接线;真正缺少受控 API 的另列明确兼容边界,不通过嗅探页面 URL 或全局拦截 shell.openExternal 伪装支持。
+同时修正文档里“手机 loopback 尚不支持”等与已实现原生模块矛盾的旧表述,区分实现、安装包、验收三层事实。
+
+## 验证与交付
+
+| 验证 | 必须观察的结果 |
+| --- | --- |
+| 新手机 + 旧正式 Host 等价环境 | 授权前识别能力不足,目标电脑 openExternal 调用为零;表单读取不受影响 |
+| 新手机 + 配套 Host,Outlook global | 真正点击原页添加邮箱,手机显示 Microsoft 登录,PC 不打开;完成后同一目标实例回读账号 |
+| Outlook china | 独立覆盖其声明、端口及路由;无相应租户账号时标明登录完成未验证,不能借 global 代替 |
+| Gmail | 原页添加/重连仍在手机;Host 成功保存后回读,避免 Outlook 修复造成 Gmail 回归 |
+| PC 本机点击 | 原本 PC 浏览器流程仍可用,存量账号与配置不被清空 |
+| 配置页与 setup 卡 | 两种入口都经过生产接线验证,不只 mock connectAccount 或只测最终 controller |
+| 生命周期 | 双控制端互不串号;同名不同 namespace 不串实例;取消/断链后晚到结果不写入 |
+| 非标准入口 | 至少取真实 Runtime/CLI 插件核实是否使用授权桥,按已确认范围给结果 |
+
+测试顺序:生产入口级回归证明旧接线失败;新旧能力组合;隔离 Host + 同一模拟器的真实 Outlook/Gmail;再验证 PC 本机与移动端平台差异。
+旧 Host 的验证使用隔离环境,正式客户端仅只读核对,不为测试重启、替换或注入。
+登录由用户在浏览器完成,不索取密码/验证码;无需重复 Gmail 已授权操作,除非验证路径确实需要。
+验收证据记录目标设备、Host 构建、手机构建、插件版本、入口、打开浏览器所在端、Host 保存与回读。设备渲染截图和合成状态用例不得代替授权闭环。
+
+## 本轮交付边界
+
+2026-10-21 用户批准“改掉”后的实现:
+
+- 原配置页普通 HTTP(S) 链接和新窗口复用手机原生确认与浏览器入口;保留当前页面/账号/目标校验,覆盖时不接受新表单操作。包内 HTML/锚点继续留在容器,原生 `/__cindy/<token>` 初始入口仍可重定向到包内 HTML。
+- `settings:open` 增加可选 `controllerAuthorization: true`,只由包含原 OAuth endpoint remote context 接线的 Host 返回。手机在创建授权动作前检查它,旧 Host 缺字段时提示更新所选电脑,普通读写不受影响。不以通用 OAuth 能力代替原页路由能力。
+- iOS 26.5 专用模拟器 + 正式 Host 的真实 Mivo 1.7.9 原页:点击“前往控制台获取” → 原生确认 → 手机系统浏览器进入 Mivo SSO → 关闭返回原表单,已验证;未提交密钥。
+- 同一模拟器 + 公司电脑-new(旧正式 Host)的 Outlook 2.1.8:点击原页“添加邮箱”后显示更新目标电脑提示,未进入授权。无正式客户端替换/重启。
+- 同一模拟器 + 配套测试 B:刷新电脑目录后,真实 Gmail 已连接账号正常回读;点击原页 Connect another account → 手机原生确认 → 手机系统浏览器进入 Google 账号选择页。未选择账号或重新提交授权,本轮不重复声称登录回调验收。
+- 定向自动验证 52 项 Mobile、75 项 Host;Mobile/Desktop 类型检查、Mobile scope、术语检查通过。Bootstrap URL 回归先复现失败,再修复通过。以上不代表 Outlook 登录回调或 Android 真机已验收。
+
+该阶段尚未完成 Mivo 凭证校验 API;其后已完成实现及候选补丁,见下文。仍未完成新 Host 的 Outlook 双环境真实授权闭环、Android 外链验收。BC 凭证阻拦未放宽、未吞掉 Mivo 原错误,也未把新窗口单测算作全部插件的原生验收。未提交/推送。
+
+源码导航(相对仓库根):
+- apps/mobile/src/plugins/pluginSettingsClient.ts
+- apps/mobile/src/plugins/pluginAuthorizationController.ts
+- apps/mobile/modules/cindy-plugin-oauth/
+- apps/desktop/src/main/cindy-brain/mobilePageService.ts
+- apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts
+- apps/desktop/src/main/cindy-brain/runtime/ghostOauthEndpoint.ts
+- apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts
+- apps/desktop/src/main/cindy-brain/ghostOauthFlow.ts
+- apps/desktop/src/main/plugin-oauth/transactions.ts
+- apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts
+
+
+## 后续实现与再次复核(2026-10-21)
+
+- 通用凭证校验已实现:Host 接收一次性候选值,按批准清单请求并只返回有效性/有效期。Mivo 候选补丁区分保存和校验结果;旧 Host 保留保存能力并明确未校验。补丁保存在仓库外验收目录,未替换已安装插件;隔离原页测试不等于真实账号校验闭环。
+- 配置加载覆盖资源下载至 WebView 完成,包内资源最多四个并发读取,取消后禁止迟到写盘。正式目标 XD Sites 的原配置页已在 iOS 模拟器显示。开发热更新曾使手机内存身份为空;完整重开专用模拟器 App 后恢复,临时诊断钩子已全部移除,没有修改生产身份校验。
+- 再次复核修复包内导航的回包串页:同一租约下,新 HTML 文档会从头分配请求编号;按文档加载代次丢弃旧响应和旧错误。成功/失败两条回归均先失败、后通过。授权返回的资源重建合并到统一收尾路径,仍不重放提交。
+- 再次复核修复 Android 回调连接清理:取消同时关闭已接入连接;过期任务不再排在阻塞读取后,每次请求还有总读取期限。生产 Kotlin listener 的真实 loopback 测试先复现取消后连接残留,修复后取消、慢速请求过期、一次性回调均通过。测试仅替代 Expo Promise 桥,不复制 listener 实现。
+- 清理保留可复现预览、生成的 bootstrap 与回归夹具;它们有实际用途,不属于临时诊断代码。原生模块仍须冷更审核,插件基座仍须白名单放行;本轮未提交、推送、发布或替换正式客户端。
+
+本轮检查:14 个 Mobile 测试文件 361 项、7 个 Host 测试文件 198 项、协议包 11 个测试文件 168 项通过;Mobile/Desktop 类型检查、Mobile scope、bootstrap 生成一致性和 diff 空白检查通过。Swift 生产 listener 17 个场景及 Kotlin 生产 listener 的取消/过期/一次性回调通过;Android 原生模块 `:cindy-plugin-oauth:compileDebugKotlin` 编译通过。未运行整仓全量门禁,未把 loopback 测试或模块编译等同于 Android 设备上的第三方授权验收。
diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.md
index 91661689f9..ebfd71a1d2 100644
--- a/docs/design-rules/design-inventory.md
+++ b/docs/design-rules/design-inventory.md
@@ -65,7 +65,7 @@
| `mobile.home` | mobile | 主机与资源首页 | app/index.tsx / app/devices/index.tsx | AccountSwitcherSheet, AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, BotGroupAvatars, BotGroupCreateSheet, BotGroupList, CenteredScreen, CompanionChoice, CompanionCreateNativeView, CompanionCreateNativeView.ios, CompanionImportSheet, CompanionListRow, CompanionMemoryPage, CompanionMemoryPage.ios, CompanionModelChain, CompanionNativeContent.ios, CompanionPortraitPicker, CompanionPresenceRing, CompanionProfileArtifacts, CompanionProfileNativeView, CompanionProfileNativeView.ios, CompanionProfileSheet, CompanionSettingsRow, CompanionSettingsRow.ios, CompanionSheet, CompanionSheet.ios, ComposerMorphSource, ComposerMorphSource.ios, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ConversationSearchFilterSheet, DeviceLinkContext, ErrorNotice, FoldTouchpad, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeListVisuals, HomeModePanes, HomeModeSwitch, HomeNativeStackHeader, HomeNewTaskButton, HomeProjectMachineLabel, HomeSearchBar, HomeSessionInfoMeta, HomeStackHeader, HomeSurface, HomeUnreadContext, IncomingShareBridge, McpAppViews, MobileAgentMark, MobileAgentSwitcher, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobileModelPickerList.ios, MobileOutboxBridge, MobilePermissionPickerList, MobilePermissionPickerList.ios, MobilePrimitives, MobileProviderMark, MobileUserAvatar, MobileVendorIcon, ModalContentArea, ModelOptionsSheetView, ModelOptionsSheetView.ios, ModelPickerNativeHeader, ModelPickerNativeHeader.ios, ModelPickerSheet, MountOnFirstOpen, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, NativeErrorNotice.ios, NativeMcpAppSurface, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PluginMenuUnreadDot, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteAccessGuide, RemoteCompanionAvatar, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteHistoryPrefetchBridge, RemoteSourceMark, RemoteTaskSuggestions, RenameSessionModal, ResidentHomeList, SessionActionSheet, SessionActionSheetFrame, SessionActionSheetFrame.android, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionOptionsExpoSheet, SessionRightSpinner, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableProjectHeader, SwipeableSessionRow, SwipeableSessionRow.ios, TaskTags, TeammateCreateButton, TeammateGenerationLabel, TeammateHomeScreen, TeammateList, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, WorkingStatusText, _layout, gestureHandler, index, listDisclosureTransition, nativeToolbarMenuItems, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/index.tsx, apps/mobile/app/index.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/ErrorNotice.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileUserAvatar.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/NativeErrorNotice.ios.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/RemoteCompanionAvatar.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/ModalContentArea.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.android.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/HomeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/chrome/nativeToolbarMenuItems.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/plugins/PluginMenuUnreadDot.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/BotGroupAvatars.tsx, apps/mobile/src/session/BotGroupCreateSheet.tsx, apps/mobile/src/session/BotGroupList.tsx, apps/mobile/src/session/CompanionChoice.tsx, apps/mobile/src/session/CompanionCreateNativeView.ios.tsx, apps/mobile/src/session/CompanionCreateNativeView.tsx, apps/mobile/src/session/CompanionImportSheet.tsx, apps/mobile/src/session/CompanionListRow.tsx, apps/mobile/src/session/CompanionMemoryPage.ios.tsx, apps/mobile/src/session/CompanionMemoryPage.tsx, apps/mobile/src/session/CompanionModelChain.tsx, apps/mobile/src/session/CompanionNativeContent.ios.tsx, apps/mobile/src/session/CompanionPortraitPicker.tsx, apps/mobile/src/session/CompanionPresenceRing.tsx, apps/mobile/src/session/CompanionProfileArtifacts.tsx, apps/mobile/src/session/CompanionProfileNativeView.ios.tsx, apps/mobile/src/session/CompanionProfileNativeView.tsx, apps/mobile/src/session/CompanionProfileSheet.tsx, apps/mobile/src/session/CompanionSettingsRow.ios.tsx, apps/mobile/src/session/CompanionSettingsRow.tsx, apps/mobile/src/session/CompanionSheet.ios.tsx, apps/mobile/src/session/CompanionSheet.tsx, apps/mobile/src/session/ComposerMorphSource.ios.tsx, apps/mobile/src/session/ComposerMorphSource.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeListVisuals.tsx, apps/mobile/src/session/HomeModePanes.tsx, apps/mobile/src/session/HomeModeSwitch.tsx, apps/mobile/src/session/HomeNewTaskButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/HomeSessionInfoMeta.tsx, apps/mobile/src/session/HomeSurface.tsx, apps/mobile/src/session/HomeUnreadContext.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/McpAppViews.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileModelPickerList.ios.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/MobilePermissionPickerList.ios.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.ios.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerNativeHeader.ios.tsx, apps/mobile/src/session/ModelPickerNativeHeader.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/MountOnFirstOpen.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.tsx, apps/mobile/src/session/NativeMcpAppSurface.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx, apps/mobile/src/session/RemoteSourceMark.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionActionSheetFrame.android.tsx, apps/mobile/src/session/SessionActionSheetFrame.tsx, apps/mobile/src/session/SessionDetailsNative.ios.tsx, apps/mobile/src/session/SessionDetailsNative.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SessionRightSpinner.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SwipeableProjectHeader.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/session/TaskTags.tsx, apps/mobile/src/session/TeammateCreateButton.tsx, apps/mobile/src/session/TeammateGenerationLabel.tsx, apps/mobile/src/session/TeammateHomeScreen.tsx, apps/mobile/src/session/TeammateList.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/WorkingStatusText.tsx, apps/mobile/src/session/listDisclosureTransition.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 214 | 152 |
| `mobile.mail` | mobile | 邮件阅读与附件预览 | app/mail-preview.tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, HomeStackHeader, IncomingShareBridge, McpAppViews, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileMailHtmlPreview, MobileOutboxBridge, MobilePrimitives, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, NativeMcpAppSurface, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PluginCardRecipients, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteHistoryPrefetchBridge, ResidentHomeList, SheetModal, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, mail-preview, nativeToolbarMenuItems, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/mail-preview.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.android.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/HomeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/chrome/nativeToolbarMenuItems.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/plugins/MobileMailHtmlPreview.tsx, apps/mobile/src/plugins/PluginCardRecipients.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/McpAppViews.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.tsx, apps/mobile/src/session/NativeMcpAppSurface.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 214 | 57 |
| `mobile.overlay.connection-startup` | mobile | 根布局挂载的启动与连接反馈 | app/_layout.tsx → StartupSplashOverlay / ConnectionNoticeProvider;各页面 ConnectionBanner | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, ConnectionNoticeProvider, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, IncomingShareBridge, McpAppViews, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, NativeMcpAppSurface, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteHistoryPrefetchBridge, ResidentHomeList, SheetModal, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.android.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/McpAppViews.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.tsx, apps/mobile/src/session/NativeMcpAppSurface.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 214 | 52 |
-| `mobile.plugins` | mobile | 插件目录、页面与原生交互 | app/plugins.tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, CompanionNativeContent.ios, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, ErrorNotice, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, HomeStackHeader, HtmlBrowserChrome, HtmlBrowserChrome.ios, HtmlFileReader, HtmlWebsiteBrowser, ImageLightbox, IncomingShareBridge, McpAppViews, MobileAgentMark, MobileAgentSwitcher, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobileModelPickerList.ios, MobileOutboxBridge, MobilePermissionPickerList, MobilePermissionPickerList.ios, MobilePrimitives, MobileProviderMark, ModelOptionsSheetView, ModelOptionsSheetView.ios, ModelPickerNativeHeader, ModelPickerNativeHeader.ios, ModelPickerSheet, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, NativeErrorNotice.ios, NativeMcpAppSurface, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, NativeVideoPlayer, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PluginDetailView, PluginDetailView.ios, PluginDirectoryPicker, PluginDirectoryView, PluginDirectoryView.ios, PluginMediaViewer, PluginNativeIntent, PluginPage, PluginScheduleDraft, PluginTaskPicker, PluginTaskPickerView, PluginTaskPickerView.ios, PluginToolChips, PluginsScreen, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteHistoryPrefetchBridge, RemoteSourceMark, ResidentHomeList, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SystemNavigationBack, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, _layout, gestureHandler, mediaPlayerWebView, nativeToolbarMenuItems, peerFileTransport, plugins, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/plugins.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/ErrorNotice.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/NativeErrorNotice.ios.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.android.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/HomeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/chrome/SystemNavigationBack.tsx, apps/mobile/src/platform/chrome/nativeToolbarMenuItems.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/plugins/PluginDetailView.ios.tsx, apps/mobile/src/plugins/PluginDetailView.tsx, apps/mobile/src/plugins/PluginDirectoryPicker.tsx, apps/mobile/src/plugins/PluginDirectoryView.ios.tsx, apps/mobile/src/plugins/PluginDirectoryView.tsx, apps/mobile/src/plugins/PluginMediaViewer.tsx, apps/mobile/src/plugins/PluginNativeIntent.tsx, apps/mobile/src/plugins/PluginPage.tsx, apps/mobile/src/plugins/PluginScheduleDraft.tsx, apps/mobile/src/plugins/PluginTaskPicker.tsx, apps/mobile/src/plugins/PluginTaskPickerView.ios.tsx, apps/mobile/src/plugins/PluginTaskPickerView.tsx, apps/mobile/src/plugins/PluginToolChips.tsx, apps/mobile/src/plugins/PluginsScreen.tsx, apps/mobile/src/plugins/pluginPageHtml.ts, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/CompanionNativeContent.ios.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HtmlBrowserChrome.ios.tsx, apps/mobile/src/session/HtmlBrowserChrome.tsx, apps/mobile/src/session/HtmlFileReader.tsx, apps/mobile/src/session/HtmlWebsiteBrowser.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/McpAppViews.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileModelPickerList.ios.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/MobilePermissionPickerList.ios.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.ios.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerNativeHeader.ios.tsx, apps/mobile/src/session/ModelPickerNativeHeader.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.tsx, apps/mobile/src/session/NativeMcpAppSurface.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/NativeVideoPlayer.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx, apps/mobile/src/session/RemoteSourceMark.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 251 | 91 |
+| `mobile.plugins` | mobile | 插件目录、页面与原生交互 | app/plugins.tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, CompanionNativeContent.ios, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, ErrorNotice, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, HomeStackHeader, HtmlBrowserChrome, HtmlBrowserChrome.ios, HtmlFileReader, HtmlWebsiteBrowser, ImageLightbox, IncomingShareBridge, McpAppViews, MobileAgentMark, MobileAgentSwitcher, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobileModelPickerList.ios, MobileOutboxBridge, MobilePermissionPickerList, MobilePermissionPickerList.ios, MobilePrimitives, MobileProviderMark, ModelOptionsSheetView, ModelOptionsSheetView.ios, ModelPickerNativeHeader, ModelPickerNativeHeader.ios, ModelPickerSheet, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, NativeErrorNotice.ios, NativeMcpAppSurface, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, NativeVideoPlayer, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PluginDetailView, PluginDetailView.ios, PluginDirectoryPicker, PluginDirectoryView, PluginDirectoryView.ios, PluginManagementConfirmation, PluginManagementConfirmation.ios, PluginManagementMenu, PluginMediaViewer, PluginNativeIntent, PluginNotice, PluginNotice.ios, PluginOriginalSettings, PluginPage, PluginPermissionCard, PluginScheduleDraft, PluginSettingsCard, PluginTaskPicker, PluginTaskPickerView, PluginTaskPickerView.ios, PluginToolChips, PluginsScreen, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteHistoryPrefetchBridge, RemoteSourceMark, ResidentHomeList, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SystemNavigationBack, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, _layout, gestureHandler, mediaPlayerWebView, nativeToolbarMenuItems, peerFileTransport, plugins, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/plugins.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/ErrorNotice.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/NativeErrorNotice.ios.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.android.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/HomeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/chrome/SystemNavigationBack.tsx, apps/mobile/src/platform/chrome/nativeToolbarMenuItems.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/plugins/PluginDetailView.ios.tsx, apps/mobile/src/plugins/PluginDetailView.tsx, apps/mobile/src/plugins/PluginDirectoryPicker.tsx, apps/mobile/src/plugins/PluginDirectoryView.ios.tsx, apps/mobile/src/plugins/PluginDirectoryView.tsx, apps/mobile/src/plugins/PluginManagementConfirmation.ios.tsx, apps/mobile/src/plugins/PluginManagementConfirmation.tsx, apps/mobile/src/plugins/PluginManagementMenu.tsx, apps/mobile/src/plugins/PluginMediaViewer.tsx, apps/mobile/src/plugins/PluginNativeIntent.tsx, apps/mobile/src/plugins/PluginNotice.ios.tsx, apps/mobile/src/plugins/PluginNotice.tsx, apps/mobile/src/plugins/PluginOriginalSettings.tsx, apps/mobile/src/plugins/PluginPage.tsx, apps/mobile/src/plugins/PluginPermissionCard.tsx, apps/mobile/src/plugins/PluginScheduleDraft.tsx, apps/mobile/src/plugins/PluginSettingsCard.tsx, apps/mobile/src/plugins/PluginTaskPicker.tsx, apps/mobile/src/plugins/PluginTaskPickerView.ios.tsx, apps/mobile/src/plugins/PluginTaskPickerView.tsx, apps/mobile/src/plugins/PluginToolChips.tsx, apps/mobile/src/plugins/PluginsScreen.tsx, apps/mobile/src/plugins/pluginPageHtml.ts, apps/mobile/src/plugins/pluginSettingsHtml.ts, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/CompanionNativeContent.ios.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HtmlBrowserChrome.ios.tsx, apps/mobile/src/session/HtmlBrowserChrome.tsx, apps/mobile/src/session/HtmlFileReader.tsx, apps/mobile/src/session/HtmlWebsiteBrowser.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/McpAppViews.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileModelPickerList.ios.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/MobilePermissionPickerList.ios.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.ios.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerNativeHeader.ios.tsx, apps/mobile/src/session/ModelPickerNativeHeader.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.tsx, apps/mobile/src/session/NativeMcpAppSurface.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/NativeVideoPlayer.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx, apps/mobile/src/session/RemoteSourceMark.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 4 | 251 | 98 |
| `mobile.remote-desktop` | mobile | 远程桌面 | app/devices/desktop/[deviceId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, IncomingShareBridge, McpAppViews, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, NativeMcpAppSurface, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteHistoryPrefetchBridge, ResidentHomeList, SheetModal, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/desktop/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.android.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/McpAppViews.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.tsx, apps/mobile/src/session/NativeMcpAppSurface.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 214 | 52 |
| `mobile.resources` | mobile | 远程资源列表与详情 | app/resources/[collectionId].tsx / app/resources/[collectionId]/[resourceId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, CompanionChoice, CompanionCreateNativeView, CompanionCreateNativeView.ios, CompanionImportSheet, CompanionMemoryPage, CompanionMemoryPage.ios, CompanionModelChain, CompanionNativeContent.ios, CompanionPortraitPicker, CompanionProfileArtifacts, CompanionProfileNativeView, CompanionProfileNativeView.ios, CompanionProfileSheet, CompanionSettingsRow, CompanionSettingsRow.ios, CompanionSheet, CompanionSheet.ios, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, ErrorNotice, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, HomeStackHeader, IncomingShareBridge, McpAppViews, MobileAgentMark, MobileAgentSwitcher, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobileModelPickerList.ios, MobileOutboxBridge, MobilePermissionPickerList, MobilePermissionPickerList.ios, MobilePrimitives, MobileProviderMark, ModelOptionsSheetView, ModelOptionsSheetView.ios, ModelPickerNativeHeader, ModelPickerNativeHeader.ios, ModelPickerSheet, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, NativeErrorNotice.ios, NativeMcpAppSurface, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteCompanionAvatar, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteHistoryPrefetchBridge, RemoteSourceMark, ResidentHomeList, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, [collectionId], [resourceId], _layout, gestureHandler, nativeToolbarMenuItems, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/resources/[collectionId].tsx, apps/mobile/app/resources/[collectionId]/[resourceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/ErrorNotice.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/NativeErrorNotice.ios.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteCompanionAvatar.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.android.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/HomeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/chrome/nativeToolbarMenuItems.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/CompanionChoice.tsx, apps/mobile/src/session/CompanionCreateNativeView.ios.tsx, apps/mobile/src/session/CompanionCreateNativeView.tsx, apps/mobile/src/session/CompanionImportSheet.tsx, apps/mobile/src/session/CompanionMemoryPage.ios.tsx, apps/mobile/src/session/CompanionMemoryPage.tsx, apps/mobile/src/session/CompanionModelChain.tsx, apps/mobile/src/session/CompanionNativeContent.ios.tsx, apps/mobile/src/session/CompanionPortraitPicker.tsx, apps/mobile/src/session/CompanionProfileArtifacts.tsx, apps/mobile/src/session/CompanionProfileNativeView.ios.tsx, apps/mobile/src/session/CompanionProfileNativeView.tsx, apps/mobile/src/session/CompanionProfileSheet.tsx, apps/mobile/src/session/CompanionSettingsRow.ios.tsx, apps/mobile/src/session/CompanionSettingsRow.tsx, apps/mobile/src/session/CompanionSheet.ios.tsx, apps/mobile/src/session/CompanionSheet.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/McpAppViews.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileModelPickerList.ios.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/MobilePermissionPickerList.ios.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.ios.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerNativeHeader.ios.tsx, apps/mobile/src/session/ModelPickerNativeHeader.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.tsx, apps/mobile/src/session/NativeMcpAppSurface.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx, apps/mobile/src/session/RemoteSourceMark.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 214 | 88 |
| `mobile.settings` | mobile | 设置(含调试与日志上传可见入口) | app/settings.tsx / app/settings/device-name.tsx / app/settings/user-bubble.tsx / app/settings/voice-dictionary.tsx / app/settings/voice-speaker-filter.tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, HomeStackHeader, IncomingShareBridge, McpAppViews, MobileChoicePickerList, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, MobileUserAvatar, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, NativeMcpAppSurface, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteHistoryPrefetchBridge, ResidentHomeList, SettingsGroupRows, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, UserBubbleHueSlider, UserBubblePage, UserBubblePage.ios, UserBubbleSettings, UserBubbleSettings.ios, _layout, device-name, gestureHandler, listDisclosureTransition, nativeToolbarMenuItems, peerFileTransport, settings, useLocale, user-bubble, voice-dictionary, voice-speaker-filter | apps/mobile/app/_layout.tsx, apps/mobile/app/settings.tsx, apps/mobile/app/settings/device-name.tsx, apps/mobile/app/settings/user-bubble.tsx, apps/mobile/app/settings/voice-dictionary.tsx, apps/mobile/app/settings/voice-speaker-filter.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileUserAvatar.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.android.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/HomeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/chrome/nativeToolbarMenuItems.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/McpAppViews.tsx, apps/mobile/src/session/MobileChoicePickerList.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.tsx, apps/mobile/src/session/NativeMcpAppSurface.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SettingsGroupRows.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/listDisclosureTransition.tsx, apps/mobile/src/settings/UserBubbleHueSlider.tsx, apps/mobile/src/settings/UserBubblePage.ios.tsx, apps/mobile/src/settings/UserBubblePage.tsx, apps/mobile/src/settings/UserBubbleSettings.ios.tsx, apps/mobile/src/settings/UserBubbleSettings.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 214 | 71 |
@@ -161,6 +161,7 @@
| apps/mobile/app/_layout.tsx | layout; visible mounted feedback is a separate overlay surface |
| apps/mobile/app/automations/[deviceId].tsx | legacy automation link redirect; no screen |
| apps/mobile/app/listperf.tsx | __DEV__ list performance harness; not production UI |
+| apps/mobile/app/plugin-management-preview.tsx | gated plugin settings visual fixture; not production UI |
| apps/mobile/app/splash-preview.tsx | MOBILE_VISUAL_MOCK_ENABLED preview; not production UI |
Mobile 静态图跟随本地 import/reexport 与平台 TSX;根布局仅登记可见反馈,不把布局自身或资源实例另算 surface。服务端动态内容、运行期 import 拼接、原生系统呈现及未显式导入的消费者需人工复核;不宣称完整递归渲染图。
diff --git a/docs/remote-plugin-oauth.md b/docs/remote-plugin-oauth.md
index 19248826ab..4624e9bce2 100644
--- a/docs/remote-plugin-oauth.md
+++ b/docs/remote-plugin-oauth.md
@@ -184,8 +184,14 @@ gh-cli、oidc-token 或账号 vault 写入;临时 Node Secret 卡只允许其
卡片动作在提交前复核,插件 WebView、普通频道和通用 invoke 不能收取这些输入。
手机使用 Expo SecureStore 固定执行电脑公钥,按 realm/membership/本手机/执行电脑分域;
安全存储失败拒绝,已登记身份换钥直接拒绝,不能通过卡片信任或替换新钥。
- PKCE 和 loopback 回调仍需电脑端入口;手机不能把电脑 localhost 当作手机地址。
- 旧手机继续查看/取消并通过电脑入口完成。网站 Cookie/全量 vault 同步不在范围。
+ 新原生包通过独立 CindyPluginOauth 模块,在手机 127.0.0.1 上绑定原回调端口接收
+ 顶层 GET 回调;provider URL、clientId、redirect_uri 和 PKCE verifier 不改写。
+ 手机系统浏览器完成授权后,只把内存中的 code/error 经原 v3 密封交回执行 Host;
+ Host 完成交换与保存才显示成功。监听限定非特权固定端口、原 path/Host/state、期限和一次消费;
+ 端口冲突拒绝,不抢占或换端口。localhost、IPv6、带 Origin/CORS 的回调暂不支持。
+ iOS 使用 SFSafariViewController,Android 使用 CustomTabs;短暂切出处理两步验证不清监听,
+ 取消、owner 失效、超时或进程销毁清理。Android 回前台后才提交密文,不将 opened 当成功。
+ 缺少原生模块的旧包明确提示更新,不回退远端电脑开浏览器。网站 Cookie/全量 vault 同步不在范围。
新版路径尚须真实 iOS/Android 验收,单测不代表第三方实际授权成功。
- Auth、relay、CIS、Model Access 不需要本功能的新服务接口或部署;双方客户端需升级。
@@ -245,3 +251,30 @@ OAuth connect 为原 endpoint 创建一次性页面动作,复用浏览器授
撤权、断链或重装使旧页面失效,配置写入在原持久化边界再次检查;不重放未知写操作。
无假任务,无凭证复制。协议及验收边界见
[兼容合同](dev-rules/protocol-compatibility.md)与[实施记录](remote-plugin-management-implementation.md)。
+
+### 手机原配置页授权的增量能力
+
+`settings:open` 文档可选返回 `controllerAuthorization: true`,明确当前 Host 的原设置页
+`POST /oauth/:key/connect` 会携带来源控制端上下文。该标记与 `ghostOauthEndpoint` 的
+remote context 接线一同发布;通用 OAuth capabilities 存在不代表原设置页路由完整。
+手机缺少此标记时,在创建 `settings-oauth` 动作之前提示更新所选电脑,不调用旧 Host
+的 connect。配置读取、普通保存与既有账号不受影响。旧查看端忽略新增字段;无新 channel、
+无批准状态迁移、无本次新增原生指纹输入。此标记不代替原账号/实例/批准/页面租约校验。
+
+手机原配置页的 HTTP(S) 外链与新窗口请求复用同一个原生确认入口,在当前手机浏览器打开。
+包内 HTML 与锚点继续留在设置容器;协议/凭证 URL 被拒绝,目标电脑 loopback 链接明确提示
+在电脑打开,不把它当作手机本地服务。回退或切换身份后的迟到确认不打开浏览器。
+
+### 原配置页普通凭证校验
+
+可选的 `network.secrets[].check` 固定校验地址、JSON 请求模板和有限响应投影;
+只用于 user 凭证,目标同时命中 network.hosts 和该凭证 inject.hosts。
+`GET /secrets` 仅对已声明且 Host 支持的条目增加 `checkSupported:true`。
+原页 `POST /secrets/<key>/check {value}` 复用专用加密 settings fetch,
+不经过 BroadcastChannel 或通用 invoke 明文;本机 PC 复用同一 endpoint。
+Host 临时执行候选值 exchange/header 注入,不写保险库、全局 token 缓存或日志;
+只返回 `{valid,expiresAt?}`,不返回原响应。整个检查 15 秒、单实例最多 2 个并发、
+每次响应最多 64 KiB,禁止跟随重定向。取消页面/切身份后的结果作废。
+缺少 checkSupported 的旧 Host 仍可保存,作者页面应明确显示“已保存、未校验”,
+不得回退凭证 BC;保存与校验分别反馈,不能因后一步失败称前一步未保存。
+所有旧清单和既有凭证保持原样,不新增自动迁移或强制重新授权。
diff --git a/packages/plugin-protocol/src/index.ts b/packages/plugin-protocol/src/index.ts
index 96f8bcb263..313187f36d 100644
--- a/packages/plugin-protocol/src/index.ts
+++ b/packages/plugin-protocol/src/index.ts
@@ -4,3 +4,4 @@ export * from './recommendations.js';
export * from './delivery.js';
export * from './memberUpload.js';
export * from './usage.js';
+export * from './secretCheck.js';
diff --git a/packages/plugin-protocol/src/manifest.ts b/packages/plugin-protocol/src/manifest.ts
index 10e4143bb0..57dad578f7 100644
--- a/packages/plugin-protocol/src/manifest.ts
+++ b/packages/plugin-protocol/src/manifest.ts
@@ -1,3 +1,4 @@
+import { parseGhostSecretCheck, type GhostSecretCheckDecl } from './secretCheck.js';
import { parseGhostRoutineEvents, type GhostRoutineEvents } from './routineEvents.js';
/** `.cindy` 包根目录中的 manifest 文件名。 */
@@ -686,6 +687,8 @@ export interface GhostSecretDecl {
inject: GhostSecretInjectDecl;
/** 可选:key 换令牌二段式声明(见 GhostSecretExchangeDecl;与 oauth 互斥)。 */
exchange?: GhostSecretExchangeDecl;
+ /** Optional settings-only credential check; never returns the credential. */
+ check?: GhostSecretCheckDecl;
/** source: 'oauth' 时必填的授权详单(见 GhostSecretOauthDecl);其它来源禁止声明。 */
oauth?: GhostSecretOauthDecl;
/**
@@ -2792,6 +2795,12 @@ export function validateGhostManifest(value: unknown): ManifestValidation {
...(exTtl !== undefined ? { ttlSeconds: exTtl } : {}),
};
}
+ const check = s.check === undefined ? undefined : parseGhostSecretCheck(s.check,
+ (host) => hosts.some((pattern) => ghostNetworkHostMatches(pattern, host))
+ && (injectHosts ?? hosts).some((pattern) => ghostNetworkHostMatches(pattern, host)));
+ if (s.check !== undefined && (!check || (source !== undefined && source !== 'user'))) {
+ return { ok: false, reason: 'network.secrets[].check requires a user secret, a declared injection host, and a bounded response mapping' };
+ }
secrets.push({
key: s.key,
label: s.label,
@@ -2804,6 +2813,7 @@ export function validateGhostManifest(value: unknown): ManifestValidation {
...(injectHosts !== undefined ? { hosts: injectHosts } : {}),
},
...(exchange !== undefined ? { exchange } : {}),
+ ...(check ? { check } : {}),
...(oauth !== undefined ? { oauth } : {}),
});
}
diff --git a/packages/plugin-protocol/src/secretCheck.ts b/packages/plugin-protocol/src/secretCheck.ts
new file mode 100644
index 0000000000..aba88ed31b
--- /dev/null
+++ b/packages/plugin-protocol/src/secretCheck.ts
@@ -0,0 +1,32 @@
+/** A settings-only check of a transient user credential; no raw response projection. */
+export interface GhostSecretCheckDecl {
+ url: string;
+ bodyFormat: string;
+ validPath: string;
+ validValue: string | boolean;
+ expiresAtPath?: string;
+ expiresAtFormat?: 'iso' | 'unix-ms' | 'unix-seconds';
+}
+
+export function parseGhostSecretCheck(value: unknown, hostAllowed: (host: string) => boolean): GhostSecretCheckDecl | null {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
+ const v = value as Record<string, unknown>;
+ const path = (p: unknown): p is string => typeof p === 'string' && p.length <= 128 && /^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*$/.test(p)
+ && !p.split('.').some((part) => ['__proto__', 'prototype', 'constructor'].includes(part));
+ if (typeof v.url !== 'string' || v.url.length > 2048) return null;
+ try {
+ const url = new URL(v.url);
+ if (url.protocol !== 'https:' || url.port || url.username || url.password || url.hash || !hostAllowed(url.hostname)) return null;
+ } catch { return null; }
+ if (typeof v.bodyFormat !== 'string' || v.bodyFormat.length > 4096 || v.bodyFormat.split('{value}').length !== 2) return null;
+ try {
+ const body = JSON.parse(v.bodyFormat.replace('{value}', 'check-value'));
+ if (!body || typeof body !== 'object' || Array.isArray(body)) return null;
+ } catch { return null; }
+ if (!path(v.validPath) || !(typeof v.validValue === 'boolean' || (typeof v.validValue === 'string' && v.validValue.length > 0 && v.validValue.length <= 64))) return null;
+ if (v.expiresAtPath !== undefined && !path(v.expiresAtPath)) return null;
+ if (v.expiresAtFormat !== undefined && (!v.expiresAtPath || !['iso', 'unix-ms', 'unix-seconds'].includes(String(v.expiresAtFormat)))) return null;
+ return { url: v.url, bodyFormat: v.bodyFormat, validPath: v.validPath, validValue: v.validValue,
+ ...(v.expiresAtPath !== undefined ? { expiresAtPath: v.expiresAtPath as string } : {}),
+ ...(v.expiresAtFormat !== undefined ? { expiresAtFormat: v.expiresAtFormat as GhostSecretCheckDecl['expiresAtFormat'] } : {}) };
+}
diff --git a/scripts/__tests__/design-inventory.test.mjs b/scripts/__tests__/design-inventory.test.mjs
index 23f9f5f94a..79db0e969b 100644
--- a/scripts/__tests__/design-inventory.test.mjs
+++ b/scripts/__tests__/design-inventory.test.mjs
@@ -1283,6 +1283,11 @@ test('Mobile new, removed, renamed routes and missing dev gates cannot silently
assert.deepEqual(mobileRouteCoverage(temp,catalog).stale,['resources/[id].tsx']);
fs.writeFileSync(path.join(app,'listperf.tsx'),'export default function LiveScreen() { return <View />; }');
assert.ok(mobileRouteCoverage(temp,catalog).missing.includes('apps/mobile/app/listperf.tsx'));
+ const pluginPreview = path.join(app, 'plugin-management-preview.tsx');
+ fs.writeFileSync(pluginPreview, 'export default function Preview() { return <View />; }');
+ assert.ok(mobileRouteCoverage(temp,catalog).missing.includes('apps/mobile/app/plugin-management-preview.tsx'));
+ fs.writeFileSync(pluginPreview, 'const demosEnabled = __DEV__ && process.env.EXPO_PUBLIC_CINDY_PLUGIN_DEMOS === "1"; export default function Preview() { if (!MOBILE_VISUAL_MOCK_ENABLED && !demosEnabled) return <Redirect href="/" />; return <View />; }');
+ assert.equal(mobileRouteCoverage(temp,catalog).missing.includes('apps/mobile/app/plugin-management-preview.tsx'), false);
});
test('Mobile reexports, embedded viewer HTML, platform variants and codepoint ordering survive closure', async (t) => {
diff --git a/scripts/generate-mobile-settings-bootstrap.mjs b/scripts/generate-mobile-settings-bootstrap.mjs
new file mode 100644
index 0000000000..376e6f1dc8
--- /dev/null
+++ b/scripts/generate-mobile-settings-bootstrap.mjs
@@ -0,0 +1,41 @@
+/** Keep the isolated settings bridge executable on Hermes without runtime source serialization. */
+import fs from "node:fs";
+import ts from "typescript";
+import { fileURLToPath } from "node:url";
+const source = fileURLToPath(
+ new URL(
+ "../apps/mobile/src/plugins/pluginSettingsBootstrap.ts",
+ import.meta.url,
+ ),
+);
+const target = fileURLToPath(
+ new URL(
+ "../apps/mobile/src/plugins/pluginSettingsBootstrap.generated.ts",
+ import.meta.url,
+ ),
+);
+const compiled = ts
+ .transpileModule(fs.readFileSync(source, "utf8"), {
+ compilerOptions: {
+ target: ts.ScriptTarget.ES2022,
+ module: ts.ModuleKind.ESNext,
+ },
+ })
+ .outputText.replace(
+ "export function settingsBootstrap(",
+ "function settingsBootstrap(",
+ )
+ .replace(/export \{\};?\s*$/, "");
+const output =
+ "// Generated by scripts/generate-mobile-settings-bootstrap.mjs. Edit pluginSettingsBootstrap.ts.\n" +
+ "export const PLUGIN_SETTINGS_BOOTSTRAP = " +
+ JSON.stringify(compiled) +
+ ";\n";
+if (process.argv.includes("--check")) {
+ if (!fs.existsSync(target) || fs.readFileSync(target, "utf8") !== output) {
+ process.stderr.write(
+ "Mobile settings bootstrap is stale; run node scripts/generate-mobile-settings-bootstrap.mjs\n",
+ );
+ process.exitCode = 1;
+ }
+} else fs.writeFileSync(target, output);
diff --git a/scripts/shared/design-inventory.mjs b/scripts/shared/design-inventory.mjs
index f7bc721628..599d9b54f3 100644
--- a/scripts/shared/design-inventory.mjs
+++ b/scripts/shared/design-inventory.mjs
@@ -1452,6 +1452,7 @@ export function mobileRouteCoverage(repoRoot, catalog = mobileCatalogSurfaces())
['+native-intent.ts', 'native intent routing; no screen'],
['automations/[deviceId].tsx', 'legacy automation link redirect; no screen'],
['splash-preview.tsx', 'MOBILE_VISUAL_MOCK_ENABLED preview; not production UI'],
+ ['plugin-management-preview.tsx', 'gated plugin settings visual fixture; not production UI'],
['listperf.tsx', '__DEV__ list performance harness; not production UI'],
]);
const owners = new Map(catalog.flatMap(s => (s.mobileRoutes ?? []).map(r => [r, s.id])));
@@ -1462,6 +1463,9 @@ export function mobileRouteCoverage(repoRoot, catalog = mobileCatalogSurfaces())
if (excluded.has(route)) {
// Keep dev exclusions honest: removing their gate cannot silently hide a screen.
if (route === 'splash-preview.tsx' && !source.includes('if (!MOBILE_VISUAL_MOCK_ENABLED)')) missing.push(file);
+ if (route === 'plugin-management-preview.tsx' &&
+ (!source.includes('if (!MOBILE_VISUAL_MOCK_ENABLED && !demosEnabled)') ||
+ !source.includes('__DEV__ && process.env.EXPO_PUBLIC_CINDY_PLUGIN_DEMOS === "1"'))) missing.push(file);
if (route === 'listperf.tsx' && !source.includes('if (!__DEV__)')) missing.push(file);
exclusions.push({ path: file, reason: excluded.get(route) });
continue;
diff --git a/scripts/smoke-mobile-plugin-settings.mts b/scripts/smoke-mobile-plugin-settings.mts
new file mode 100644
index 0000000000..7b8bf270ff
--- /dev/null
+++ b/scripts/smoke-mobile-plugin-settings.mts
@@ -0,0 +1,107 @@
+/** Browser-only synthetic fixture. No plugin is installed and no user configuration is read. */
+import { createServer } from "node:http";
+import {
+ settingsBridgeAsset,
+ prepareSettingsHtml,
+ PLUGIN_SETTINGS_CSP,
+} from "../apps/mobile/src/plugins/pluginSettingsHtml";
+
+const html =
+ '<!doctype html><html><head><title>Original settings bridge check</title><link rel="stylesheet" href="./style.css"><script type="module" src="./main.js"></script></head><body><label>Region <input id="region" value="test"></label><button id="save">Save test value</button><output id="result">Loading original module…</output></body></html>';
+const module = `import { originalLabel } from './child.js';
+const result = document.querySelector('#result');
+const channel = new BroadcastChannel('fixture-dynamic');
+channel.onmessage = event => { document.body.dataset.channel = event.data.kind; };
+const xhr = new XMLHttpRequest();
+xhr.open('GET', '../kv'); xhr.responseType = 'json';
+xhr.onload = () => { document.body.dataset.xhr = xhr.response.region; result.textContent = originalLabel; };
+xhr.send();
+channel.postMessage({kind:'ready'});
+document.querySelector('#save').onclick = async () => {
+ await fetch('/kv', {method:'PUT',body:JSON.stringify({region:document.querySelector('#region').value})});
+ const value = await (await fetch('/kv')).json();
+ result.textContent = 'Saved on fake target: ' + value.region;
+};
+fetch('./data.json').then(r=>r.json()).then(value=>document.body.dataset.resource=value.original);
+fetch('https://example.invalid/kv').then(()=>document.body.dataset.escape='bad',()=>document.body.dataset.escape='blocked');`;
+const files = new Map([
+ ["ui/settings.html", { mime: "text/html", text: html }],
+ ["ui/main.js", { mime: "application/javascript", text: module }],
+ [
+ "ui/child.js",
+ {
+ mime: "application/javascript",
+ text: 'export const originalLabel = "Original nested module loaded";',
+ },
+ ],
+ [
+ "ui/style.css",
+ {
+ mime: "text/css",
+ text: "body{font:16px system-ui;color:var(--text-primary);background:var(--panel-bg);padding:16px}input,button{font:inherit;margin:8px}output{display:block;background-image:url(./icon.svg);padding:16px}",
+ },
+ ],
+ [
+ "ui/icon.svg",
+ {
+ mime: "image/svg+xml",
+ text: '<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"><path fill="none" d="M0 0"/></svg>',
+ },
+ ],
+ ["ui/data.json", { mime: "application/json", text: '{"original":"loaded"}' }],
+]);
+const document = {
+ pageId: "synthetic-settings",
+ pluginId: "synthetic",
+ manifestId: "synthetic",
+ name: "Synthetic",
+ entry: "ui/settings.html",
+ files: [...files].map(([path, file]) => ({
+ path,
+ mime: file.mime,
+ size: Buffer.byteLength(file.text),
+ })),
+};
+const bridge = settingsBridgeAsset(document, {
+ dark: false,
+ colors: { "panel-bg": "ivory", "text-primary": "black" },
+});
+// Replace only the native transport in this fixture. API requests reaching HTTP are a failure.
+const fakeNative = `(()=>{let kv={region:'test'};let seq=0;window.__fixtureCommands=[];
+window.ReactNativeWebView={postMessage(raw){const m=JSON.parse(raw);if(!m.command)return;
+window.__fixtureCommands.push(m.command);const c=m.command;
+queueMicrotask(()=>{let value={};if(c.kind==='fetch'){if(c.method==='PUT')kv=JSON.parse(c.body);value={status:200,mime:'application/json',base64:btoa(unescape(encodeURIComponent(JSON.stringify(kv))))}}
+window.__cindySettingsReceive({kind:'reply',id:m.id,ok:true,value});
+if(c.kind==='post')window.__cindySettingsReceive({kind:'events',events:[{sequence:++seq,channel:c.channel,data:c.data}]});});}};})();\n`;
+files.set(bridge.path, {
+ mime: "application/javascript",
+ text: fakeNative + bridge.text,
+});
+files.set(document.entry, {
+ mime: "text/html",
+ text: prepareSettingsHtml(html, bridge.path),
+});
+const server = createServer((request, response) => {
+ const path = new URL(request.url!, "http://localhost").pathname.slice(1);
+ const file = files.get(path);
+ if (request.method !== "GET" || !file) {
+ response.writeHead(404);
+ response.end();
+ return;
+ }
+ response.writeHead(200, {
+ "Content-Type": file.mime,
+ "Content-Security-Policy": PLUGIN_SETTINGS_CSP,
+ "Cache-Control": "no-store",
+ });
+ response.end(file.text);
+});
+server.listen(0, "127.0.0.1", () => {
+ const address = server.address();
+ if (address && typeof address === "object")
+ process.stdout.write(
+ `Synthetic original settings: http://127.0.0.1:${address.port}/${document.entry}\n`,
+ );
+});
+process.once("SIGINT", () => server.close());
+process.once("SIGTERM", () => server.close());
diff --git a/scripts/test-mobile-plugin-oauth-android.mjs b/scripts/test-mobile-plugin-oauth-android.mjs
new file mode 100644
index 0000000000..83682d01e2
--- /dev/null
+++ b/scripts/test-mobile-plugin-oauth-android.mjs
@@ -0,0 +1,88 @@
+/** Real loopback lifecycle regression using the production Kotlin listener.
+ * Only Expo's Promise bridge is stubbed. Requires kotlinc (or KOTLINC) and java.
+ * An embedded compiler can supply KOTLIN_STDLIB instead of bundling its runtime.
+ * Synthetic callbacks and compiler output live in a disposable directory.
+ */
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { execFileSync } from 'node:child_process';
+
+const source = fs.readFileSync(new URL('../apps/mobile/modules/cindy-plugin-oauth/android/src/main/java/expo/modules/cindypluginoauth/CindyPluginOauthModule.kt', import.meta.url), 'utf8');
+const marker = 'private class CallbackListener';
+if (!source.includes(marker)) throw new Error('Production listener not found');
+const imports = source.match(/^import java\..+$/gm).join('\n');
+const listener = source.slice(source.indexOf(marker));
+const driver = String.raw`
+class Promise {
+ @Volatile var value: Any? = null
+ @Volatile var error: String? = null
+ fun resolve(value: Any?) { this.value = value }
+ fun reject(code: String, message: String, cause: Throwable?) { error = code }
+}
+private val state = "synthetic-provider-state-123"
+private fun fixture(ttl: Long = 10000): Pair<CallbackListener, Int> {
+ val port = ServerSocket(0, 1, InetAddress.getByName("127.0.0.1")).use { it.localPort }
+ val listener = CallbackListener(mapOf("id" to "synthetic-listener-id", "state" to state,
+ "callbackUrl" to "http://127.0.0.1:$port/callback", "expiresAt" to System.currentTimeMillis() + ttl))
+ listener.start()
+ return Pair(listener, port)
+}
+private fun expectDisconnected(client: java.net.Socket) {
+ client.soTimeout = 1200
+ val closed = try { client.getInputStream().read() == -1 }
+ catch (error: java.net.SocketTimeoutException) { false }
+ catch (error: java.net.SocketException) { true }
+ check(closed) { "Accepted callback socket survived cancellation/expiry" }
+}
+fun main() {
+ val (listener, port) = fixture()
+ val pending = Promise()
+ try {
+ listener.waitForCallback(pending)
+ java.net.Socket("127.0.0.1", port).use { client ->
+ client.getOutputStream().write("G".toByteArray())
+ Thread.sleep(100) // Let the production worker enter its partial-header read.
+ listener.close()
+ expectDisconnected(client)
+ }
+ check(pending.error == "PLUGIN_OAUTH_CLOSED")
+ } finally { listener.close() }
+
+ val (expiring, expiringPort) = fixture(300)
+ try {
+ java.net.Socket("127.0.0.1", expiringPort).use { client ->
+ val writer = Thread {
+ try { repeat(100) { client.getOutputStream().write(71); Thread.sleep(20) } }
+ catch (_: Exception) { }
+ }
+ writer.start()
+ try { expectDisconnected(client); check(expiring.status() == "closed") }
+ finally { writer.interrupt(); writer.join(1000) }
+ }
+ } finally { expiring.close() }
+
+ val (valid, validPort) = fixture()
+ try {
+ val result = Promise(); valid.waitForCallback(result)
+ java.net.Socket("127.0.0.1", validPort).use { client ->
+ client.soTimeout = 2000
+ client.getOutputStream().write(("GET /callback?state=$state&code=fake-code HTTP/1.1\r\n" +
+ "Host: 127.0.0.1:$validPort\r\n\r\n").toByteArray())
+ check(client.getInputStream().bufferedReader().readText().startsWith("HTTP/1.1 200"))
+ }
+ check((result.value as Map<*, *>)["code"] == "fake-code")
+ val replay = Promise(); valid.waitForCallback(replay)
+ check(replay.error == "PLUGIN_OAUTH_CLOSED")
+ } finally { valid.close() }
+ println("Kotlin production listener: cancellation, slow-header expiry and single-use callback passed")
+}
+`;
+const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-plugin-oauth-android-'));
+try {
+ const file = path.join(directory, 'Main.kt'), jar = path.join(directory, 'test.jar');
+ fs.writeFileSync(file, imports + '\n' + driver + '\n' + listener);
+ const stdlib = process.env.KOTLIN_STDLIB;
+ execFileSync(process.env.KOTLINC || 'kotlinc', [file, ...(stdlib ? ['-classpath', stdlib] : ['-include-runtime']), '-d', jar], { stdio: 'inherit', timeout: 60000 });
+ execFileSync('java', stdlib ? ['-cp', [jar, stdlib].join(path.delimiter), 'MainKt'] : ['-jar', jar], { stdio: 'inherit', timeout: 15000 });
+} finally { fs.rmSync(directory, { recursive: true, force: true }); }
diff --git a/scripts/test-mobile-plugin-oauth-native.mjs b/scripts/test-mobile-plugin-oauth-native.mjs
new file mode 100644
index 0000000000..86c77cb94a
--- /dev/null
+++ b/scripts/test-mobile-plugin-oauth-native.mjs
@@ -0,0 +1,102 @@
+/** Runs the production Swift loopback listener against real local TCP requests.
+ * Expo's thin Promise/Record bridge is stubbed; the listener/parser is not copied.
+ * All callback material is synthetic and stays in a disposable directory.
+ */
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { execFileSync } from 'node:child_process';
+const source = fs.readFileSync(new URL('../apps/mobile/modules/cindy-plugin-oauth/ios/CindyPluginOauthModule.swift', import.meta.url), 'utf8');
+const marker = 'private final class PluginOauthListener';
+if (!source.includes(marker)) throw new Error('Production listener not found');
+const listener = source.slice(source.indexOf(marker)).replace(marker, 'final class PluginOauthListener');
+const driver = String.raw`
+import Foundation
+import Network
+import Darwin
+struct PluginOauthListenerOptions { var id: String; var callbackUrl: String; var state: String; var expiresAt: Double }
+final class Promise {
+ var value: [String: String]?; var error: String?
+ func resolve(_ value: Any?) { self.value = value as? [String: String] }
+ func reject(_ code: String, _ message: String) { error = code }
+}
+func require(_ condition: @autoclosure () -> Bool, _ message: String) { if !condition() { fatalError(message) } }
+func freePort() -> UInt16 {
+ let fd = Darwin.socket(AF_INET, SOCK_STREAM, 0); defer { Darwin.close(fd) }
+ var address = sockaddr_in(); address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size); address.sin_family = sa_family_t(AF_INET); address.sin_addr.s_addr = inet_addr("127.0.0.1")
+ let bound = withUnsafePointer(to: &address) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { Darwin.bind(fd, $0, socklen_t(MemoryLayout<sockaddr_in>.size)) } }
+ require(bound == 0, "port probe failed")
+ var length = socklen_t(MemoryLayout<sockaddr_in>.size)
+ _ = withUnsafeMutablePointer(to: &address) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { getsockname(fd, $0, &length) } }
+ return UInt16(bigEndian: address.sin_port)
+}
+let queue = DispatchQueue(label: "oauth.native.test")
+let state = "synthetic-provider-state-123"
+func create(ttl: Double = 10000) throws -> (PluginOauthListener, UInt16, PluginOauthListenerOptions) {
+ let port = freePort()
+ let options = PluginOauthListenerOptions(id: "synthetic-listener-id", callbackUrl: "http://127.0.0.1:\(port)/callback", state: state, expiresAt: Date().timeIntervalSince1970 * 1000 + ttl)
+ let server = try PluginOauthListener(options, queue: queue)
+ let ready = DispatchSemaphore(value: 0); var bound = false
+ queue.async { server.start { bound = $0; ready.signal() } }
+ require(ready.wait(timeout: .now() + 3) == .success && bound, "listener not ready")
+ return (server, port, options)
+}
+func send(_ port: UInt16, target: String, host: String? = nil, extra: String = "") -> String {
+ let fd = Darwin.socket(AF_INET, SOCK_STREAM, 0); defer { Darwin.close(fd) }
+ var timeout = timeval(tv_sec: 2, tv_usec: 0)
+ _ = withUnsafePointer(to: &timeout) { setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, $0, socklen_t(MemoryLayout<timeval>.size)) }
+ var address = sockaddr_in(); address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size); address.sin_family = sa_family_t(AF_INET); address.sin_addr.s_addr = inet_addr("127.0.0.1"); address.sin_port = port.bigEndian
+ let connected = withUnsafePointer(to: &address) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { Darwin.connect(fd, $0, socklen_t(MemoryLayout<sockaddr_in>.size)) } }
+ require(connected == 0, "test connection failed")
+ let bytes = Array("GET \(target) HTTP/1.1\r\nHost: \(host ?? "127.0.0.1:\(port)")\r\n\(extra)\r\n".utf8)
+ _ = bytes.withUnsafeBytes { Darwin.write(fd, $0.baseAddress, bytes.count) }
+ var response = [UInt8](repeating: 0, count: 4096)
+ let count = Darwin.read(fd, &response, response.count)
+ return count > 0 ? String(decoding: response.prefix(count), as: UTF8.self) : ""
+}
+let (server, port, options) = try create()
+let invalid: [(String, String?, String)] = [
+ ("/callback?state=wrong&code=fake-code", nil, ""),
+ ("/other?state=\(state)&code=fake-code", nil, ""),
+ ("/callback?state=\(state)&code=fake-code", "localhost:\(port)", ""),
+ ("/callback?state=\(state)&code=fake-code", nil, "Origin: https://accounts.example.com\r\n"),
+ ("/callback?state=\(state)&code=a&code=b", nil, ""),
+ ("/callback?state=\(state)&code=a&error=access_denied", nil, ""),
+ ("/callback?state=\(state)&state=\(state)&code=a", nil, ""),
+ ("/callback?state=\(state)&code=", nil, ""),
+ ("/callback?state=\(state)&code=fake-code", nil, "Content-Length: 1\r\n"),
+]
+for item in invalid { require(send(port, target: item.0, host: item.1, extra: item.2).hasPrefix("HTTP/1.1 400"), "invalid callback accepted") }
+// An occupied fixed port must fail, never reclaim or silently pick a new port.
+var conflict: PluginOauthListener?
+do { conflict = try PluginOauthListener(options, queue: queue) } catch {}
+if let conflict {
+ let ready = DispatchSemaphore(value: 0); var bound = true
+ queue.async { conflict.start { bound = $0; ready.signal() } }
+ require(ready.wait(timeout: .now() + 3) == .success && !bound, "occupied port accepted")
+ queue.sync { conflict.close() }
+}
+let first = Promise(); queue.sync { server.wait(first) }
+require(send(port, target: "/callback?state=\(state)&code=fake-code&scope=read").hasPrefix("HTTP/1.1 200"), "valid callback rejected")
+queue.sync { require(first.value?["code"] == "fake-code", "callback not delivered") }
+let second = Promise(); queue.sync { server.wait(second); require(second.error != nil, "callback consumed twice"); server.close() }
+let (expired, _, _) = try create(ttl: 100)
+Thread.sleep(forTimeInterval: 0.2)
+queue.sync { require(expired.status() == "closed", "expired listener still active"); expired.close() }
+let (unconsumed, unconsumedPort, _) = try create(ttl: 100)
+require(send(unconsumedPort, target: "/callback?state=\(state)&code=fake-code").hasPrefix("HTTP/1.1 200"), "valid pending callback rejected")
+Thread.sleep(forTimeInterval: 0.2)
+queue.sync { let late = Promise(); unconsumed.wait(late); require(late.error != nil && unconsumed.status() == "closed", "expired callback retained"); unconsumed.close() }
+let (_, _, base) = try create(ttl: 100)
+for bad in ["http://localhost:57123/callback", "http://[::1]:57123/callback", "http://127.0.0.1:80/callback"] {
+ var options = base; options.callbackUrl = bad
+ do { _ = try PluginOauthListener(options, queue: queue); fatalError("unsupported callback accepted") } catch {}
+}
+print("Swift production listener: 17 security scenarios passed")
+`;
+const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-plugin-oauth-native-'));
+try {
+ fs.writeFileSync(path.join(directory, 'main.swift'), driver + '\n' + listener);
+ execFileSync('xcrun', ['swiftc', '-swift-version', '5', path.join(directory, 'main.swift'), '-o', path.join(directory, 'test')], { stdio: 'inherit' });
+ execFileSync(path.join(directory, 'test'), [], { stdio: 'inherit', timeout: 20000 });
+} finally { fs.rmSync(directory, { recursive: true, force: true }); }