Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(mcp-apps): 支持标准 MCP Apps 与通用交互卡片 (#6057)
Lizi24320dc07eb0
diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 6909e8dc94..b460e187a4 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -31,6 +31,9 @@"ensure-deps": "node ../../scripts/ensure-deps.mjs","ensure-dev-runtime-assets": "node ../../scripts/ensure-dev-runtime-assets.mjs","test": "vitest run",+ "mcp-apps:mock": "node scripts/mcp-apps-mock.mjs",+ "test:mcp-apps:sandbox": "node scripts/mcp-apps-sandbox.verify.mjs",+ "test:mcp-apps:conformance": "vitest run src/main/mcp-apps/__tests__ --maxWorkers=2 && node scripts/mcp-apps-sandbox.verify.mjs && node scripts/mcp-apps-sandbox.verify.mjs --raw","test:git-integration": "pnpm --dir ../.. test:runner && node ../../scripts/test-workspaces.mjs --tier git-integration","test:db": "pnpm --dir ../.. test:runner && node ../../scripts/test-workspaces.mjs --tier db","test:db-proxy-perf": "cross-env XDT_DB_PROXY_PERF_STRICT=1 vitest run src/main/localDb/__tests__/drizzle-proxy-perf.test.ts",@@ -101,6 +104,7 @@"@fontsource-variable/jetbrains-mono": "^5.2.8","@google/model-viewer": "^4.0.0","@lezer/highlight": "^1.2.3",+ "@modelcontextprotocol/ext-apps": "1.7.5","@modelcontextprotocol/sdk": "^1.29.0","@napi-rs/canvas": "^0.1.100","@paralleldrive/cuid2": "^2.3.1",diff --git a/apps/desktop/scripts/mcp-apps-mock.d.mts b/apps/desktop/scripts/mcp-apps-mock.d.mtsnew file mode 100644index 0000000000..c6c1769ba2--- /dev/null+++ b/apps/desktop/scripts/mcp-apps-mock.d.mts@@ -0,0 +1,9 @@+import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+export const MOCK_RESOURCE: string;+export function mockAppHtml(): Promise<string>;+export function createMockAppServer(options?: { instructions?: string }): McpServer;+export function startMockAppServer(options?: { createServer?: () => McpServer }): Promise<{+ url: string;+ sseUrl: string;+ close(): Promise<void>;+}>;diff --git a/apps/desktop/scripts/mcp-apps-mock.mjs b/apps/desktop/scripts/mcp-apps-mock.mjsnew file mode 100644index 0000000000..6630f4350f--- /dev/null+++ b/apps/desktop/scripts/mcp-apps-mock.mjs@@ -0,0 +1,220 @@+/** Offline MCP Apps fixture. No account, production API or real message delivery. */+import http from 'node:http';+import path from 'node:path';+import { fileURLToPath, URL } from 'node:url';+import { Buffer } from 'node:buffer';+import process from 'node:process';+import console from 'node:console';+import { randomUUID } from 'node:crypto';+import { build } from 'esbuild';+import { z } from 'zod';+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';+import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';+import {+ registerAppTool,+ registerAppResource,+ getUiCapability,+ RESOURCE_MIME_TYPE,+} from '@modelcontextprotocol/ext-apps/server';++export const MOCK_RESOURCE = 'ui://cindy-mcp-apps-mock/application.html';+let htmlPromise;+export function mockAppHtml() {+ htmlPromise ??= build({+ bundle: true,+ write: false,+ format: 'iife',+ minify: true,+ stdin: {+ resolveDir: path.dirname(fileURLToPath(import.meta.url)),+ contents: `+ import { App, applyHostStyleVariables, applyDocumentTheme } from '@modelcontextprotocol/ext-apps/app-with-deps';+ void (async () => {+ const app = new App({name:'Cindy form example',version:'1.0.0'},{availableDisplayModes:['inline','fullscreen']});+ const title = document.querySelector('#title');+ const body = document.querySelector('#body');+ const status = document.querySelector('#status');+ const theme = context => { if(context.theme) applyDocumentTheme(context.theme); if(context.styles?.variables) applyHostStyleVariables(context.styles.variables); };+ app.onhostcontextchanged = theme;+ app.ontoolinput = ({arguments:args}) => { title.value=args?.title??''; body.value=args?.body??''; };+ app.ontoolresult = () => { status.textContent='核对并修改后可创建模拟申请'; };+ app.ontoolcancelled = () => { status.textContent='已取消'; };+ app.onteardown = async () => ({});+ const update = () => app.updateModelContext({structuredContent:{title:title.value,body:body.value}}).catch(() => {});+ title.addEventListener('input',update);body.addEventListener('input',update);+ document.querySelector('#submit').onclick=async()=>{+ const button=document.querySelector('#submit');button.disabled=true;+ try {const result=await app.callServerTool({name:'create_application',arguments:{title:title.value,body:body.value}});status.textContent=result.content.filter(item=>item.type==='text').map(item=>item.text).join(' ');}+ catch {status.textContent='申请结果未确认,请先核对状态。';}+ finally {button.disabled=false;}+ };+ document.querySelector('#ask').onclick=()=>app.sendMessage({role:'user',content:[{type:'text',text:'请根据表单当前内容继续修改。'}]}).catch(()=>{status.textContent='消息未发送,请检查连接。';});+ document.querySelector('#mode').onclick=async()=>{const result=await app.requestDisplayMode({mode:app.getHostContext()?.displayMode==='fullscreen'?'inline':'fullscreen'});status.textContent='显示模式:'+result.mode;};+ await app.connect();theme(app.getHostContext()??{});+ })();+ `,+ },+ }).then((result) =>+ `<!doctype html><html><head><meta charset="utf-8"><style>+ :root{color-scheme:light dark}body{font:14px var(--font-sans,system-ui);margin:0;padding:16px;color:var(--color-text-primary);background:var(--color-background-primary)}+ label{display:block;margin-bottom:12px}input,textarea{display:block;box-sizing:border-box;width:100%;padding:8px;border:1px solid var(--color-border-primary);border-radius:8px;color:inherit;background:var(--color-background-secondary)}+ textarea{min-height:96px}button{padding:8px 12px;min-height:36px;margin:0 8px 8px 0;color:inherit;background:var(--color-background-secondary);border:1px solid var(--color-border-primary);border-radius:8px}p{color:var(--color-text-secondary)}+ </style></head><body><label>标题<input id="title"></label><label>内容<textarea id="body"></textarea></label>+ <button id="submit">创建模拟申请</button><button id="ask">请 AI 继续修改</button><button id="mode">切换全屏</button>+ <p id="status">正在加载…</p><p>仅创建本地内存中的模拟申请,不发送真实站内信。</p>+ <script>__BUNDLE__</script></body></html>`.replace('__BUNDLE__', () =>+ result.outputFiles[0].text.replace(/<\/script/gi, '<\\/script'),+ ),+ );+ return htmlPromise;+}++export function createMockAppServer({ instructions } = {}) {+ const server = new McpServer({ name: 'cindy-mcp-apps-mock', version: '1.0.0' }, { instructions });+ let count = 0;+ registerAppTool(+ server,+ 'draft_form',+ {+ title: '模拟申请表',+ description: 'Display an editable application draft. Only the user can submit it.',+ inputSchema: { title: z.string(), body: z.string() },+ _meta: { ui: { resourceUri: MOCK_RESOURCE } },+ },+ async (args) => ({+ content: [{ type: 'text', text: 'Draft: ' + args.title }],+ structuredContent: args,+ _meta: {+ viewOnly: 'metadata-for-the-view',+ hostUi: getUiCapability(server.server.getClientCapabilities()),+ },+ }),+ );+ registerAppTool(+ server,+ 'create_application',+ {+ description: 'Create an in-memory simulated application. Does not send a message.',+ inputSchema: { title: z.string().min(1), body: z.string() },+ _meta: { ui: { visibility: ['app'] } },+ },+ async () => ({+ content: [{ type: 'text', text: '已创建模拟申请 ' + ++count + ',未发送站内信。' }],+ structuredContent: { applicationId: count, sent: false },+ }),+ );+ server.registerTool(+ 'model_only',+ { inputSchema: {}, _meta: { ui: { visibility: ['model'] } } },+ async () => ({ content: [{ type: 'text', text: 'model only' }] }),+ );+ registerAppResource(+ server,+ 'application',+ MOCK_RESOURCE,+ { mimeType: RESOURCE_MIME_TYPE },+ async () => ({+ contents: [+ {+ uri: MOCK_RESOURCE,+ mimeType: RESOURCE_MIME_TYPE,+ text: await mockAppHtml(),+ _meta: { ui: { csp: {}, prefersBorder: true } },+ },+ ],+ }),+ );+ return server;+}++/** Both HTTP and legacy SSE, allocated loopback port, independently disposable. */+export async function startMockAppServer({ createServer = createMockAppServer } = {}) {+ const transports = new Map();+ const servers = new Set();+ const listener = http.createServer(async (req, res) => {+ try {+ if (req.headers.origin) {+ res.writeHead(403).end();+ return;+ }+ const url = new URL(req.url, 'http://127.0.0.1');+ if (url.pathname === '/sse' && req.method === 'GET') {+ const transport = new SSEServerTransport('/messages', res);+ const server = createServer();+ servers.add(server);+ transports.set(transport.sessionId, transport);+ await server.connect(transport);+ return;+ }+ if (url.pathname === '/messages' && req.method === 'POST') {+ const transport = transports.get(url.searchParams.get('sessionId'));+ if (!(transport instanceof SSEServerTransport)) {+ res.writeHead(404).end();+ return;+ }+ await transport.handlePostMessage(req, res);+ return;+ }+ if (url.pathname !== '/mcp') {+ res.writeHead(404).end();+ return;+ }+ let body;+ if (req.method === 'POST') {+ const chunks = [];+ let size = 0;+ for await (const chunk of req) {+ size += chunk.length;+ if (size > 4 * 1024 * 1024) {+ res.writeHead(413).end();+ return;+ }+ chunks.push(chunk);+ }+ body = JSON.parse(Buffer.concat(chunks).toString('utf8'));+ }+ const id = req.headers['mcp-session-id'];+ let transport = typeof id === 'string' ? transports.get(id) : undefined;+ if (!transport && !id && body?.method === 'initialize') {+ transport = new StreamableHTTPServerTransport({+ sessionIdGenerator: () => randomUUID(),+ onsessioninitialized: (id) => transports.set(id, transport),+ });+ const server = createServer();+ servers.add(server);+ await server.connect(transport);+ }+ if (!(transport instanceof StreamableHTTPServerTransport)) {+ res.writeHead(404).end();+ return;+ }+ await transport.handleRequest(req, res, body);+ } catch {+ if (!res.headersSent) res.writeHead(400);+ res.end();+ }+ });+ await new Promise((resolve) => listener.listen(0, '127.0.0.1', resolve));+ const base = 'http://127.0.0.1:' + listener.address().port;+ return {+ url: base + '/mcp',+ sseUrl: base + '/sse',+ async close() {+ await Promise.allSettled([...servers].map((server) => server.close()));+ listener.closeAllConnections();+ await new Promise((resolve) => listener.close(resolve));+ },+ };+}+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ const createServer = process.argv.includes('--raw')+ ? (await import('./mcp-apps-raw-fixture.mjs')).createRawAppServer+ : createMockAppServer;+ const instance = await startMockAppServer({ createServer });+ console.log('MCP Apps mock HTTP: ' + instance.url + '\nMCP Apps mock SSE: ' + instance.sseUrl);+ for (const signal of ['SIGINT', 'SIGTERM'])+ process.once(signal, () => {+ void instance.close().then(() => process.exit(0));+ });+}diff --git a/apps/desktop/scripts/mcp-apps-raw-fixture.d.mts b/apps/desktop/scripts/mcp-apps-raw-fixture.d.mtsnew file mode 100644index 0000000000..94943d8bc6--- /dev/null+++ b/apps/desktop/scripts/mcp-apps-raw-fixture.d.mts@@ -0,0 +1,15 @@+import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+export const RAW_RESOURCE: string;+export const RAW_APP_HTML: string;+export interface RawAppOptions {+ encoding?: 'text' | 'blob';+ metadata?: 'list' | 'read';+ legacyUri?: boolean;+ csp?: {+ connectDomains?: string[];+ resourceDomains?: string[];+ frameDomains?: string[];+ baseUriDomains?: string[];+ };+}+export function createRawAppServer(options?: RawAppOptions): McpServer;diff --git a/apps/desktop/scripts/mcp-apps-raw-fixture.mjs b/apps/desktop/scripts/mcp-apps-raw-fixture.mjsnew file mode 100644index 0000000000..5b5a660bff--- /dev/null+++ b/apps/desktop/scripts/mcp-apps-raw-fixture.mjs@@ -0,0 +1,275 @@+/** A second, unrelated MCP App. Its View uses only standard JSON-RPC, with no SDK or Cindy APIs. */+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import { Buffer } from 'node:buffer';+import { setTimeout, clearTimeout } from 'node:timers';+import {+ ListToolsRequestSchema,+ CallToolRequestSchema,+ ReadResourceRequestSchema,+ ListResourcesRequestSchema,+ ListResourceTemplatesRequestSchema,+ ListPromptsRequestSchema,+ GetPromptRequestSchema,+ McpError,+ ErrorCode,+} from '@modelcontextprotocol/sdk/types.js';++export const RAW_RESOURCE = 'ui://independent-metrics/dashboard.html';+const mime = 'text/html;profile=mcp-app';+export const RAW_APP_HTML = `<!doctype html><html><head><meta charset="utf-8">+<style>body{font:14px var(--font-sans,system-ui);margin:0;padding:16px;color:var(--color-text-primary);background:var(--color-background-primary)}button,input{padding:8px;color:inherit;background:var(--color-background-secondary)}td,th{padding:8px;text-align:left}label{display:block;margin:12px 0}</style>+</head><body><h2>Independent metrics dashboard</h2><table><thead><tr><th>Metric</th><th>Value</th></tr></thead><tbody id="metrics"></tbody></table>+<label>Threshold <input id="threshold" type="number" value="50"></label>+<button id="refresh">Refresh metrics</button><button id="ask">Discuss these metrics</button><button id="mode">Change display mode</button><p id="status">Connecting</p>+<script>+(() => {+ let nextId=1;+ const pending=new Map();+ const state=window.rawApp={notifications:[],responses:[],hostContext:{},ready:false,teardown:false};+ const post=message=>window.parent.postMessage(message,'*');+ const request=(method,params={})=>new Promise((resolve,reject)=>{+ const id=nextId++;+ const timer=setTimeout(()=>{pending.delete(id);reject(new Error('RPC timeout'));},5000);+ pending.set(id,{resolve,reject,timer});post({jsonrpc:'2.0',id,method,params});+ });+ state.request=request;+ const context=patch=>{+ Object.assign(state.hostContext,patch);+ if(patch.theme){document.documentElement.dataset.theme=patch.theme;document.documentElement.style.colorScheme=patch.theme;}+ for(const [key,value] of Object.entries(patch.styles?.variables??{}))if(value!==undefined)document.documentElement.style.setProperty(key,value);+ };+ const render=result=>{+ state.result=result;+ document.querySelector('#metrics').replaceChildren(...Object.entries(result.structuredContent?.metrics??{}).map(([name,value])=>{+ const row=document.createElement('tr');for(const text of [name,value]){const cell=document.createElement('td');cell.textContent=String(text);row.appendChild(cell);}return row;+ }));+ document.querySelector('#status').textContent='Metrics ready';+ };+ window.addEventListener('message',event=>{+ if(event.source!==window.parent)return;+ const message=event.data;if(!message||message.jsonrpc!=='2.0')return;+ if(message.method){+ if(message.method==='ui/resource-teardown'){state.teardown=true;post({jsonrpc:'2.0',id:message.id,result:{}});return;}+ if(message.id!==undefined){post({jsonrpc:'2.0',id:message.id,error:{code:-32601,message:'Method not found'}});return;}+ state.notifications.push(message);+ if(message.method==='ui/notifications/host-context-changed')context(message.params);+ if(message.method==='ui/notifications/tool-input'){state.input=message.params.arguments;document.querySelector('#threshold').value=String(state.input.threshold);}+ if(message.method==='ui/notifications/tool-result')render(message.params);+ if(message.method==='ui/notifications/tool-cancelled')document.querySelector('#status').textContent='Cancelled';+ return;+ }+ const item=pending.get(message.id);if(!item)return;pending.delete(message.id);clearTimeout(item.timer);state.responses.push(message);+ if(message.error)item.reject(Object.assign(new Error(message.error.message),{code:message.error.code}));else item.resolve(message.result);+ });+ document.querySelector('#threshold').oninput=()=>request('ui/update-model-context',{content:[{type:'text',text:'Metrics threshold edited'}],structuredContent:{threshold:Number(document.querySelector('#threshold').value)}}).catch(error=>{state.error=String(error);});+ document.querySelector('#refresh').onclick=async()=>{try{render(await request('tools/call',{name:'refresh_metrics',arguments:{threshold:Number(document.querySelector('#threshold').value)}}));}catch(error){state.error=String(error);}};+ document.querySelector('#ask').onclick=()=>request('ui/message',{role:'user',content:{type:'text',text:'Discuss the current metrics.'}}).catch(error=>{state.error=String(error);});+ document.querySelector('#mode').onclick=()=>request('ui/request-display-mode',{mode:state.hostContext.displayMode==='fullscreen'?'inline':'fullscreen'}).then(result=>{state.mode=result.mode;});+ request('ui/initialize',{protocolVersion:'2026-01-26',appInfo:{name:'Independent metrics dashboard',version:'1.0.0'},appCapabilities:{availableDisplayModes:['inline','fullscreen']}}).then(result=>{+ state.initialize=result;context(result.hostContext??{});state.ready=true;post({jsonrpc:'2.0',method:'ui/notifications/initialized',params:{}});+ post({jsonrpc:'2.0',method:'ui/notifications/size-changed',params:{width:640,height:420}});+ }).catch(error=>{state.error=String(error);});+})();+</script></body></html>`;++/** Manual standard metadata and paginated MCP handlers, independent of ext-apps helpers. */+export function createRawAppServer({+ encoding = 'blob',+ metadata = 'list',+ legacyUri = false,+ csp = {},+} = {}) {+ const server = new McpServer(+ { name: 'independent-metrics', version: '1.0.0' },+ {+ capabilities: {+ tools: { listChanged: true },+ resources: { listChanged: true },+ prompts: { listChanged: true },+ },+ },+ );+ let refreshes = 0,+ cancelled = 0,+ slowStarted = 0,+ revision = 0;+ const ui = { csp, prefersBorder: false };+ const tools = () => [+ {+ name: 'open_metrics',+ title: 'Independent metrics',+ inputSchema: { type: 'object', properties: { threshold: { type: 'number' } } },+ _meta: legacyUri ? { 'ui/resourceUri': RAW_RESOURCE } : { ui: { resourceUri: RAW_RESOURCE } },+ },+ {+ name: 'refresh_metrics',+ title: 'Refresh ' + revision,+ inputSchema: { type: 'object', properties: { threshold: { type: 'number' } } },+ _meta: { ui: { visibility: ['app'] } },+ },+ {+ name: 'model_audit',+ inputSchema: { type: 'object' },+ _meta: { ui: { visibility: ['model'] } },+ },+ {+ name: 'slow_metrics',+ inputSchema: { type: 'object' },+ _meta: { ui: { visibility: ['app'] } },+ },+ {+ name: 'notify_change',+ inputSchema: { type: 'object' },+ _meta: { ui: { visibility: ['app'] } },+ },+ {+ name: 'error_metrics',+ inputSchema: { type: 'object' },+ _meta: { ui: { visibility: ['app'] } },+ },+ ];+ server.server.setRequestHandler(ListToolsRequestSchema, async ({ params }) => {+ const page = params?.cursor === undefined ? 0 : Number(params.cursor);+ if (![0, 2, 4].includes(page))+ throw new McpError(ErrorCode.InvalidParams, 'Invalid fixture cursor');+ return {+ tools: tools().slice(page, page + 2),+ ...(page < 4 ? { nextCursor: String(page + 2) } : {}),+ };+ });+ const result = (args) => ({+ content: [+ { type: 'text', text: 'Independent metrics loaded' },+ {+ type: 'image',+ mimeType: 'image/png',+ data: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a1e8AAAAASUVORK5CYII=',+ },+ {+ type: 'audio',+ mimeType: 'audio/wav',+ data: 'UklGRiYAAABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YQIAAAAAAA==',+ },+ {+ type: 'resource',+ resource: {+ uri: 'metrics://independent/note',+ mimeType: 'text/plain',+ text: 'Full embedded result',+ },+ },+ {+ type: 'resource',+ resource: {+ uri: 'metrics://independent/binary',+ mimeType: 'application/octet-stream',+ blob: 'AQID',+ },+ },+ {+ type: 'resource_link',+ uri: 'metrics://independent/latest',+ name: 'Latest metrics',+ mimeType: 'application/json',+ },+ ],+ structuredContent: { metrics: { requests: 120, threshold: args.threshold ?? 50, refreshes } },+ _meta: {+ viewOnly: 'independent-view-metadata',+ clientUi: server.server.getClientCapabilities()?.extensions?.['io.modelcontextprotocol/ui'],+ },+ });+ server.server.setRequestHandler(CallToolRequestSchema, async ({ params }, extra) => {+ if (params.name === 'open_metrics') return result(params.arguments ?? {});+ if (params.name === 'refresh_metrics') {+ refreshes++;+ return result(params.arguments ?? {});+ }+ if (params.name === 'model_audit')+ return { content: [{ type: 'text', text: 'Model-only audit' }] };+ if (params.name === 'error_metrics')+ return {+ isError: true,+ content: [{ type: 'text', text: 'Expected fixture tool error' }],+ _meta: { viewOnly: 'error-details' },+ };+ if (params.name === 'notify_change') {+ revision++;+ await server.server.sendToolListChanged();+ await server.server.sendResourceListChanged();+ await server.server.sendPromptListChanged();+ return { content: [{ type: 'text', text: 'Lists changed' }] };+ }+ if (params.name === 'slow_metrics') {+ slowStarted++;+ await new Promise((resolve, reject) => {+ const timer = setTimeout(resolve, 1000);+ extra.signal.addEventListener(+ 'abort',+ () => {+ clearTimeout(timer);+ cancelled++;+ reject(new Error('Fixture cancelled'));+ },+ { once: true },+ );+ });+ return result(params.arguments ?? {});+ }+ throw new McpError(ErrorCode.InvalidParams, 'Unknown fixture tool');+ });+ server.server.setRequestHandler(ReadResourceRequestSchema, async ({ params }) => {+ if (params.uri === RAW_RESOURCE)+ return {+ contents: [+ {+ uri: RAW_RESOURCE,+ mimeType: mime,+ ...(encoding === 'blob'+ ? { blob: Buffer.from(RAW_APP_HTML).toString('base64') }+ : { text: RAW_APP_HTML }),+ ...(metadata === 'read' ? { _meta: { ui } } : {}),+ },+ ],+ };+ if (params.uri === 'metrics://independent/state')+ return {+ contents: [+ {+ uri: params.uri,+ mimeType: 'application/json',+ text: JSON.stringify({ refreshes, cancelled, slowStarted, revision }),+ },+ ],+ };+ if (params.uri.startsWith('metrics://independent/'))+ return {+ contents: [+ { uri: params.uri, mimeType: 'text/plain', text: 'Metric resource: ' + params.uri },+ ],+ };+ throw new McpError(ErrorCode.InvalidParams, 'Unknown fixture resource');+ });+ server.server.setRequestHandler(ListResourcesRequestSchema, async ({ params }) =>+ params?.cursor === undefined+ ? {+ resources: [{ uri: 'metrics://independent/latest', name: 'Latest metrics' }],+ nextCursor: 'ui',+ }+ : {+ resources: [+ { uri: RAW_RESOURCE, name: 'Independent dashboard', mimeType: mime, _meta: { ui } },+ ],+ },+ );+ server.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => ({+ resourceTemplates: [{ uriTemplate: 'metrics://independent/{metric}', name: 'Metric' }],+ }));+ server.server.setRequestHandler(ListPromptsRequestSchema, async () => ({+ prompts: [{ name: 'explain_metrics', description: 'Explain the selected metrics' }],+ }));+ server.server.setRequestHandler(GetPromptRequestSchema, async () => ({+ messages: [{ role: 'user', content: { type: 'text', text: 'Explain these metrics.' } }],+ }));+ return server;+}diff --git a/apps/desktop/scripts/mcp-apps-sandbox.verify.mjs b/apps/desktop/scripts/mcp-apps-sandbox.verify.mjsnew file mode 100644index 0000000000..feb0fcbdfc--- /dev/null+++ b/apps/desktop/scripts/mcp-apps-sandbox.verify.mjs@@ -0,0 +1,321 @@+/** Explicit Electron integration check; never launches or restarts Cindy. */+import assert from 'node:assert/strict';+import { mkdtemp, writeFile, rm } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { createRequire } from 'node:module';+import { spawn } from 'node:child_process';+import http from 'node:http';+import process from 'node:process';+import { setTimeout, clearTimeout } from 'node:timers';+import { build } from 'esbuild';+import { startMockAppServer, createMockAppServer } from './mcp-apps-mock.mjs';+import { createRawAppServer } from './mcp-apps-raw-fixture.mjs';++const scriptDir = path.dirname(fileURLToPath(import.meta.url));+const temporary = await mkdtemp(path.join(os.tmpdir(), 'cindy-mcp-app-sandbox-'));+const independent = process.argv.includes('--raw');+const remoteView = process.argv.includes('--remote');+const measureMetrics = process.argv.includes('--metrics');+const assets = http.createServer((req, res) => {+ res.setHeader('Access-Control-Allow-Origin', '*');+ if (req.url === '/asset.js') {+ res.setHeader('Content-Type', 'text/javascript');+ res.end('window.allowedAssetLoaded=true;');+ } else if (req.url === '/frame') {+ res.setHeader('Content-Type', 'text/html');+ res.end('<!doctype html><body>Declared frame domain</body>');+ } else res.end('declared-domain');+});+await new Promise((resolve) => assets.listen(0, '127.0.0.1', resolve));+const allowed = 'http://127.0.0.1:' + assets.address().port;+const endpoint = await startMockAppServer({+ createServer: independent+ ? () =>+ createRawAppServer({+ csp: {+ connectDomains: [allowed],+ resourceDomains: [allowed],+ frameDomains: [allowed],+ baseUriDomains: [allowed],+ },+ })+ : createMockAppServer,+});+try {+ await writeFile(+ path.join(temporary, 'preload.cjs'),+ "require('electron').contextBridge.exposeInMainWorld('testHost', {invoke: input => require('electron').ipcRenderer.invoke('test:mcp-app', input)});",+ 'utf8',+ );+ const renderer = await build({+ bundle: true,+ write: false,+ format: 'iife',+ stdin: {+ resolveDir: scriptDir,+ contents: `+ import { McpAppController } from '@cindy/maker-shared/mcp-app-controller';+ window.testState = {};+ let frame;+ const controller = new McpAppController((_id,input)=>window.testHost.invoke(input),'task','card',+ message=>frame?.contentWindow?.postMessage(message,'*'),message=>{+ if(message.method==='ui/notifications/initialized')window.testState.initialized=true;+ if(message.method==='ui/notifications/size-changed'){window.testState.size=message.params;if(frame)frame.style.height=Math.min(1200,message.params.height)+'px';}+ if(message.method==='ui/notifications/host-context-changed'&&message.params.displayMode)window.testState.mode=message.params.displayMode;+ },error=>{window.testState.error=String(error);});+ window.testController=controller;+ window.addEventListener('message',event=>{+ if(event.source!==frame?.contentWindow)return;+ if(event.data?.method==='ui/notifications/sandbox-proxy-ready')controller.sandboxReady('cindy-mcp-app://'+controller.document.viewId+'-view/resource');+ else controller.receive(event.data);+ });+ controller.open({platform:'desktop',theme:'light',styles:{variables:{'--color-background-primary':'rgb(248,248,246)','--color-text-primary':'rgb(0,0,0)'}}}).then(doc=>{+ frame=document.createElement('iframe');frame.sandbox='allow-scripts allow-same-origin';frame.src='cindy-mcp-app://'+doc.viewId+'/sandbox';frame.style='width:700px;height:550px';document.body.appendChild(frame);+ });+ `,+ },+ });+ await writeFile(+ path.join(temporary, 'host.html'),+ '<!doctype html><html><body><script>' ++ renderer.outputFiles[0].text.replace(/<\/script/gi, '<\\/script') ++ '</script></body></html>',+ 'utf8',+ );+ await build({+ bundle: true,+ platform: 'node',+ format: 'cjs',+ outfile: path.join(temporary, 'verify.cjs'),+ external: ['electron'],+ plugins: [+ {+ name: 'test-only-owner',+ setup(builder) {+ builder.onResolve({ filter: /localDb\/client\/current\.js$/ }, () => ({+ path: 'test-owner',+ namespace: 'test-owner',+ }));+ builder.onLoad({ filter: /.*/, namespace: 'test-owner' }, () => ({+ contents: 'export const getCurrentDbClientSnapshot=()=>globalThis.mcpTestOwner;',+ }));+ },+ },+ ],+ stdin: {+ resolveDir: scriptDir,+ contents: `+ import assert from 'node:assert/strict';+ import http from 'node:http';+ import { app, BrowserWindow, protocol, ipcMain, net } from 'electron';+ import { McpAppsHost, appServerRevision } from '../src/main/mcp-apps/host.ts';+ import { AppConnection } from '../src/main/mcp-apps/connection.ts';+ import { createAppServerProxy } from '../src/main/mcp-apps/serverProxy.ts';+ import { setMcpAppsHost, registerAppServer } from '../src/main/mcp-apps/runtime.ts';+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';+ import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';+ import { createHash } from 'node:crypto';+ import { appCsp } from '../src/main/mcp-apps/protocol.ts';+ import { handleMcpAppOperation, handleMcpAppFrameOperation } from '../src/main/mcp-apps/operations.ts';+ import { RemoteMcpAppViews } from '../src/main/mcp-apps/remoteViews.ts';+ import { mcpAppSchemePrivilege, registerMcpAppProtocol, supplyMcpAppDocument, removeMcpAppDocument } from '../src/main/mcp-apps/sandboxProtocol.ts';+ app.setPath('userData',process.env.CINDY_MCP_APP_TEST_DIR+'/profile');+ protocol.registerSchemesAsPrivileged([mcpAppSchemePrivilege]);+ globalThis.mcpTestOwner={};+ let window, host, connection, forbidden, modelFacade, modelClient, stableCatalog, stableInstructions, runtimeMetrics, requests=0, stage='initialize';+ const wait=async predicate=>{const end=Date.now()+10000;while(Date.now()<end){if(await predicate())return;await new Promise(resolve=>setTimeout(resolve,25));}throw new Error('MCP App browser check timed out: '+stage);};+ void app.whenReady().then(async()=>{+ forbidden=http.createServer((_req,res)=>{requests++;res.setHeader('Access-Control-Allow-Origin','*');res.end('forbidden');});+ await new Promise(resolve=>forbidden.listen(0,'127.0.0.1',resolve));+ const denied='http://127.0.0.1:'+forbidden.address().port+'/exfil';+ const independent=process.env.CINDY_MCP_APP_TEST_RAW==='1';+ const allowed=process.env.CINDY_MCP_APP_TEST_ALLOWED;+ const config={id:'example',url:process.env.CINDY_MCP_APP_TEST_URL,transport:'http'};+ connection=new AppConnection(config);const client=await connection.getClient();+ const tool=(await connection.tools()).find(tool=>tool.name===(independent?'open_metrics':'draft_form'));+ const args=independent?{threshold:75}:{title:'AI draft',body:'Review before creating'};+ const result=await client.callTool({name:tool.name,arguments:args});+ let record={version:1,serverId:'example',serverRevision:appServerRevision(config),resourceUri:tool._meta.ui.resourceUri,tool,arguments:args,result};+ let turns=0;+ host=new McpAppsHost({owner:()=>globalThis.mcpTestOwner,config:()=>config,readCard:async()=>record,writeCard:async(_s,_c,value)=>{record=value;},authorizeTool:async()=>{},sendMessage:async()=>{turns++;},disposeDocument:removeMcpAppDocument});+ if(process.env.CINDY_MCP_APP_TEST_METRICS==='1'){+ setMcpAppsHost(host);registerAppServer(config.id,()=>config);+ const initialRecord=record;+ modelFacade=createAppServerProxy(()=>config,{agentKind:'codex',sessionId:'task',workingDir:''});+ modelClient=new Client({name:'metrics-model-boundary',version:'1'},{});+ const [modelTransport,facadeTransport]=InMemoryTransport.createLinkedPair();+ const initializedAt=performance.now();+ await modelFacade.connect(facadeTransport);await modelClient.connect(modelTransport);+ const facadeInitializeMs=performance.now()-initializedAt;+ stableCatalog=JSON.stringify(await modelClient.listTools());stableInstructions=modelClient.getInstructions();+ assert.equal(stableInstructions,client.getInstructions());+ const times={direct:[],facade:[]};let modelResultBytes=0,directResultBytes=0;+ for(let i=0;i<30;i++){+ let started=performance.now();+ const direct=await client.callTool({name:tool.name,arguments:args});times.direct.push(performance.now()-started);+ started=performance.now();+ const viaFacade=await modelClient.callTool({name:tool.name,arguments:args});times.facade.push(performance.now()-started);+ const expected={...direct};delete expected._meta;assert.deepEqual(viaFacade,expected);+ assert.equal(JSON.stringify(await modelClient.listTools()),stableCatalog);+ assert.equal(modelClient.getInstructions(),stableInstructions);+ directResultBytes=Buffer.byteLength(JSON.stringify(direct));modelResultBytes=Buffer.byteLength(JSON.stringify(viaFacade));+ }+ const stats=samples=>{const sorted=[...samples].sort((a,b)=>a-b);return {n:samples.length,meanMs:samples.reduce((a,b)=>a+b,0)/samples.length,p95Ms:sorted[Math.ceil(samples.length*.95)-1]};};+ runtimeMetrics={fixture:independent?'raw':'official-sdk',transport:'loopback HTTP plus SDK InMemory caller',storage:'in-memory callbacks',facadeInitializeMs,+ direct:stats(times.direct),facade:stats(times.facade),stableCatalogBytes:Buffer.byteLength(stableCatalog),+ stableCatalogSha256:createHash('sha256').update(stableCatalog).digest('hex'),catalogComparisons:30,resultComparisons:30,directResultBytes,modelResultBytes,+ actualModelCacheRate:null,actualModelTokenUsage:null};+ record=initialRecord;+ }+ record.connectionId=host.registerConnection(connection);+ registerMcpAppProtocol();+ const remoteViews=new RemoteMcpAppViews({owner:()=>globalThis.mcpTestOwner,closeEpoch:()=>0,+ invoke:async(device,session,input,preSend)=>{+ assert.equal(device,'fixture-device');preSend();+ return handleMcpAppOperation(host,'device:fixture-controller',session,input);+ },openLink:async()=>{}});+ ipcMain.handle('test:mcp-app',async(event,input)=>{+ assert.equal(event.senderFrame,event.sender.mainFrame);+ const caller='renderer:'+event.sender.id;+ if(process.env.CINDY_MCP_APP_TEST_REMOTE==='1')return remoteViews.control(caller,'fixture-device','task',input);+ return handleMcpAppOperation(host,caller,'task',input,{+ supply:(doc)=>supplyMcpAppDocument(doc,caller,raw=>handleMcpAppFrameOperation(host,caller,'task',doc.viewId,raw,async()=>{})),+ });+ });+ window=new BrowserWindow({show:false,width:800,height:700,webPreferences:{preload:process.env.CINDY_MCP_APP_TEST_DIR+'/preload.cjs',sandbox:true,contextIsolation:true,nodeIntegration:false,nodeIntegrationInSubFrames:false,nodeIntegrationInWorker:false,webSecurity:true,allowRunningInsecureContent:false,experimentalFeatures:false,plugins:false,navigateOnDragDrop:false}});+ window.webContents.setWindowOpenHandler(()=>({action:'deny'}));+ await window.loadFile(process.env.CINDY_MCP_APP_TEST_DIR+'/host.html');+ try { await wait(()=>window.webContents.executeJavaScript('window.testState.initialized===true')); }+ catch (error) { console.log('Frame state',window.webContents.mainFrame.framesInSubtree.map(frame=>frame.url),await window.webContents.executeJavaScript('window.testState')); throw error; }+ assert.deepEqual(await window.webContents.executeJavaScript(+ 'Object.keys(window.testController.document).sort()'),['prefersBorder','transport','viewId']);+ assert.equal(await window.webContents.executeJavaScript(+ 'window.testController.document.transport'),'sandbox');+ const inner=()=>window.webContents.mainFrame.framesInSubtree.find(frame=>frame.url.includes('-view/resource'));+ assert.equal(await window.webContents.executeJavaScript(+ "window.testHost.invoke({op:'message',viewId:window.testController.document.viewId,message:{jsonrpc:'2.0',id:'forged',method:'tools/list'}}).then(()=>false,()=>true)"),true);+ stage='tool input and result';+ await wait(()=>inner()?.executeJavaScript(independent?"document.querySelector('#status').textContent==='Metrics ready'":"document.querySelector('#status').textContent.includes('核对')"));+ if(independent){+ assert.equal(await inner().executeJavaScript("document.querySelector('#threshold').value"),'75');+ assert.equal(await inner().executeJavaScript("window.rawApp.result._meta.viewOnly"),'independent-view-metadata');+ assert.equal(await inner().executeJavaScript("window.rawApp.initialize.protocolVersion"),'2026-01-26');+ stage='size-changed';+ await wait(()=>window.webContents.executeJavaScript("window.testState.size?.height===420&&document.querySelector('iframe').style.height==='420px'"));+ }else assert.deepEqual(await inner().executeJavaScript("[document.querySelector('#title').value,document.querySelector('#body').value]"),['AI draft','Review before creating']);+ assert.deepEqual(await inner().executeJavaScript("[typeof window.testHost,typeof window.require,typeof window.process]"),['undefined','undefined','undefined']);+ assert.deepEqual(await inner().executeJavaScript("(()=>{const policy=document.permissionsPolicy??document.featurePolicy;return ['camera','microphone','geolocation','clipboard-write'].map(name=>policy.allowsFeature(name));})()"),[false,false,false,false]);+ assert.equal(await inner().executeJavaScript("Notification.requestPermission()"),'denied');+ assert.equal(await inner().executeJavaScript("(()=>{try{window.parent.document.body;return false;}catch{return true;}})()"),true);+ assert.equal(await inner().executeJavaScript("getComputedStyle(document.body).backgroundColor"),'rgb(248, 248, 246)');+ stage='reject App-originated Host context';+ const previousMode=await window.webContents.executeJavaScript('window.testState.mode');+ await inner().executeJavaScript("window.parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/host-context-changed',params:{displayMode:'fullscreen'}},'*');window.parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/size-changed',params:{height:421}},'*');");+ await wait(()=>window.webContents.executeJavaScript('window.testState.size?.height===421'));+ assert.equal(await window.webContents.executeJavaScript('window.testState.mode'),previousMode);+ stage='theme change';+ await window.webContents.executeJavaScript("window.testController.context({theme:'dark',styles:{variables:{'--color-background-primary':'rgb(31,31,30)','--color-text-primary':'rgb(255,255,255)'}}})");+ await wait(async()=>await inner().executeJavaScript("getComputedStyle(document.body).backgroundColor")==='rgb(31, 31, 30)');+ if(independent){+ stage='update-model-context';+ await inner().executeJavaScript("document.querySelector('#threshold').value='88';document.querySelector('#threshold').dispatchEvent(new Event('input'))");+ await wait(async()=> (await host.modelContext('task')).text.includes('88'));assert.equal(turns,0);+ stage='App tool call';await inner().executeJavaScript("document.querySelector('#refresh').click()");+ await wait(()=>inner().executeJavaScript("window.rawApp.result.structuredContent.metrics.threshold===88&&window.rawApp.result.structuredContent.metrics.refreshes===1"));assert.equal(turns,0);+ stage='ui/message';await inner().executeJavaScript("document.querySelector('#ask').click()");await wait(()=>turns===1);+ stage='display mode';await inner().executeJavaScript("document.querySelector('#mode').click()");await wait(()=>window.webContents.executeJavaScript("window.testState.mode==='fullscreen'"));+ assert.equal(await inner().executeJavaScript("window.rawApp.request('ui/request-display-mode',{mode:'pip'}).then(result=>result.mode)"),'fullscreen');+ stage='Escape from focused App input';+ await inner().executeJavaScript("document.querySelector('#threshold').focus()");+ window.webContents.sendInputEvent({type:'keyDown',keyCode:'Escape'});+ window.webContents.sendInputEvent({type:'keyUp',keyCode:'Escape'});+ await wait(()=>inner().executeJavaScript("window.rawApp.hostContext.displayMode==='inline'"));+ stage='declared connect and resource domains';+ assert.equal(await inner().executeJavaScript('fetch('+JSON.stringify(allowed+'/api')+').then(response=>response.text())'),'declared-domain');+ await inner().executeJavaScript('new Promise((resolve,reject)=>{const script=document.createElement("script");script.src='+JSON.stringify(allowed+'/asset.js')+';script.onload=()=>resolve(true);script.onerror=()=>reject(new Error("Declared script failed"));document.body.appendChild(script);})');+ assert.equal(await inner().executeJavaScript('window.allowedAssetLoaded'),true);+ stage='declared frame domain';await inner().executeJavaScript('(()=>{const frame=document.createElement("iframe");frame.src='+JSON.stringify(allowed+'/frame')+';document.body.appendChild(frame);})()');+ await wait(()=>window.webContents.mainFrame.framesInSubtree.some(frame=>frame.url===allowed+'/frame'));+ const nested=window.webContents.mainFrame.framesInSubtree.find(frame=>frame.url===allowed+'/frame');+ await nested.executeJavaScript('location.href='+JSON.stringify(denied));+ // Chromium may commit an error-page URL for a CSP-blocked frame; the+ // invariant is that no request reaches the undeclared origin.+ await new Promise(resolve=>setTimeout(resolve,150));assert.equal(requests,0);+ assert.equal(await inner().executeJavaScript('(()=>{const base=document.createElement("base");base.href='+JSON.stringify(allowed+'/base/')+';document.head.appendChild(base);return document.baseURI;})()'),allowed+'/base/');+ }else{+ await inner().executeJavaScript("document.querySelector('#title').value='用户核对后的申请';document.querySelector('#title').dispatchEvent(new Event('input'))");+ await wait(async()=> (await host.modelContext('task')).text.includes('用户核对后的申请'));assert.equal(turns,0);+ await inner().executeJavaScript("document.querySelector('#submit').click()");+ await wait(()=>inner().executeJavaScript("document.querySelector('#status').textContent.includes('已创建模拟申请')"));assert.equal(turns,0);+ }+ if(runtimeMetrics){+ const currentContext=await host.modelContext('task');await currentContext.assertCurrent();+ runtimeMetrics.appContextBytes=Buffer.byteLength(currentContext.text);+ assert.ok(currentContext.text);assert.equal(turns,independent?1:0);+ runtimeMetrics.contextUpdatesStartedModelTurns=0;runtimeMetrics.explicitMessageTurns=turns;+ currentContext.consume();assert.equal((await host.modelContext('task')).text,'');runtimeMetrics.contextConsumedOnce=true;+ assert.equal(JSON.stringify(await modelClient.listTools()),stableCatalog);assert.equal(modelClient.getInstructions(),stableInstructions);+ runtimeMetrics.catalogStableAfterAppUpdates=true;+ console.log('MCP_APPS_RUNTIME_METRICS='+JSON.stringify(runtimeMetrics));+ }+ assert.equal(await inner().executeJavaScript('fetch('+JSON.stringify(denied)+').then(()=>false,()=>true)'),true);+ await inner().executeJavaScript("window.parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/sandbox-resource-ready',params:{html:'forged'}},'*')");+ const appFrame=inner();+ const viewId=await window.webContents.executeJavaScript('window.testController.document.viewId');+ await window.webContents.executeJavaScript('window.testController.close()');+ if(independent)assert.equal(await appFrame.executeJavaScript('window.rawApp.teardown'),true);+ assert.equal((await net.fetch('cindy-mcp-app://'+viewId+'-view/resource')).status,404);+ await appFrame.executeJavaScript('location.href='+JSON.stringify(denied));+ await new Promise(resolve=>setTimeout(resolve,150));assert.equal(requests,0);+ const doc={viewId,html:'<!doctype html><body>owner test',csp:appCsp().header,prefersBorder:true};supplyMcpAppDocument(doc);globalThis.mcpTestOwner={};+ assert.equal((await net.fetch('cindy-mcp-app://'+viewId+'-view/resource')).status,404);+ if(process.env.CINDY_MCP_APP_TEST_REMOTE==='1')console.log('MCP_APPS_REMOTE_FRAME_VERDICT=passed (Main-bound remote View, authenticated frame RPC, rejected Renderer forgery, remote teardown)');+ console.log(independent?'MCP_APPS_RAW_SANDBOX_VERDICT=passed (SDK-free dashboard, blob/list, tool/message/context, display/size, Light/Dark, declared CSP domains, teardown, owner)':'MCP_APPS_SANDBOX_VERDICT=passed (official App, edit/create, Light/Dark, origins, preload, CSP, navigation, teardown, owner)');+ }).catch(error=>{console.error(error);process.exitCode=1;}).finally(async()=>{+ await modelClient?.close();await modelFacade?.close();await host?.reset();await connection?.close();forbidden?.close();window?.destroy();app.exit(process.exitCode??0);+ });+ `,+ },+ });+ const environment = {+ ...process.env,+ CINDY_MCP_APP_TEST_DIR: temporary,+ CINDY_MCP_APP_TEST_URL: endpoint.url,+ CINDY_MCP_APP_TEST_RAW: independent ? '1' : '0',+ CINDY_MCP_APP_TEST_REMOTE: remoteView ? '1' : '0',+ CINDY_MCP_APP_TEST_METRICS: measureMetrics ? '1' : '0',+ CINDY_MCP_APP_TEST_ALLOWED: allowed,+ };+ delete environment.ELECTRON_RUN_AS_NODE;+ const electron = createRequire(import.meta.url)('electron');+ const code = await new Promise((resolve, reject) => {+ const child = spawn(electron, [path.join(temporary, 'verify.cjs')], {+ env: environment,+ windowsHide: true,+ stdio: 'inherit',+ });+ const timer = setTimeout(() => {+ child.kill();+ reject(new Error('隔离沙箱验证超时,测试进程已停止。'));+ }, 60_000);+ child.once('error', (error) => {+ clearTimeout(timer);+ reject(error);+ });+ child.once('exit', (code) => {+ clearTimeout(timer);+ resolve(code);+ });+ });+ assert.equal(code, 0, '隔离 Electron 沙箱验证失败');+} finally {+ await endpoint.close();+ assets.closeAllConnections();+ await new Promise((resolve) => assets.close(resolve));+ // mkdtemp guarantees a private task directory under os.tmpdir().+ assert.equal(path.dirname(path.resolve(temporary)), path.resolve(os.tmpdir()));+ assert.ok(path.basename(temporary).startsWith('cindy-mcp-app-sandbox-'));+ await rm(temporary, { recursive: true, force: true });+}diff --git a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.tsindex 6deb42d9be..d5b82d6830 100644--- a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts@@ -110,6 +110,7 @@ import {type DeviceLinkIpcDeps,} from '../device-link/ipc';import { DeviceLinkError, PLUGIN_OAUTH_CHANNEL, PLUGIN_SECRET_LOCAL_CHANNEL } from '@cindy/device-link';+import { MCP_APPS_INVOKE } from '../../shared/mcpApps.js';import { invokeWithClosedLinkRecovery } from '../device-link/linkRecovery';import { ServerApiError } from '../serverApiClient';import { createIpcError } from '../../shared/ipc-errors';@@ -1033,6 +1034,14 @@ describe('device-link controller handlers', () => {/\[INVALID_PARAMS\]/,);});+ it.each(['open', 'message', 'poll', 'context', 'authorize-link', 'teardown'])(+ 'forbids the general Renderer bridge from bypassing remote App frame authentication: %s', async (op) => {+ const deps = makeDeps();+ await expect(handleInvoke(deps, 'dev-2', MCP_APPS_INVOKE, ['task', { op, viewId: 'forged' }]))+ .rejects.toThrow('MCP_APP_FRAME_REQUIRED');+ expect(deps.invoke).not.toHaveBeenCalled();+ },+ );it('subscribe:校验 + 成功 + 转发 topics', async () => {const deps = makeDeps();diff --git a/apps/desktop/src/main/__tests__/safeStorageCompanionBoundary.test.ts b/apps/desktop/src/main/__tests__/safeStorageCompanionBoundary.test.tsindex eaf16716f5..74268d51cf 100644--- a/apps/desktop/src/main/__tests__/safeStorageCompanionBoundary.test.ts+++ b/apps/desktop/src/main/__tests__/safeStorageCompanionBoundary.test.ts@@ -5,7 +5,8 @@ import { ScriptTarget, transpileModule } from 'typescript';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { companionEnvironmentKey } from '../bot-import/environment.js';import { isRendererAccessibleSafeStorageKey, isCustomProviderRuntimeKeyStorageKey,- customProviderSecretStorageKey, customMcpSecretStorageKey, providerOAuthStorageKey } from '../../shared/providerSecrets.js';+ customProviderSecretStorageKey, customMcpSecretStorageKey, providerOAuthStorageKey,+ MCP_APP_REVISION_KEY_STORAGE_KEY } from '../../shared/providerSecrets.js';// Execute the production registrations with fake Electron dependencies, without// launching Desktop or reproducing the IPC handlers in a test implementation.@@ -59,10 +60,11 @@ describe('generic safeStorage companion boundary', () => {// writes/deletes must not corrupt either old or chunked environment files.const original = Buffer.from('fixture:{"env":{"KEY":"fixture-private-token"}}').toString('base64');fs.writeFileSync(file, original);- for (const variant of [key, key.toUpperCase(), 'bot_environment_future_format', 'bot_environment_']) {+ for (const variant of [key, key.toUpperCase(), 'bot_environment_future_format', 'bot_environment_',+ MCP_APP_REVISION_KEY_STORAGE_KEY, MCP_APP_REVISION_KEY_STORAGE_KEY.toUpperCase()]) {expect(await api.invoke(String(operation), variant, 'replacement')).toEqual(result);}- expect(api.assertTrustedAppRendererEvent).toHaveBeenCalledTimes(4);+ expect(api.assertTrustedAppRendererEvent).toHaveBeenCalledTimes(6);expect(api.resolveOwnerScopedSecretStorageKey).not.toHaveBeenCalled();expect(api.safeStorage.isEncryptionAvailable).not.toHaveBeenCalled();expect(api.safeStorage.decryptString).not.toHaveBeenCalled();diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 3d2b6419c6..efd2cc7dda 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -1,4 +1,5 @@import { registerAccessibilitySupportIpc } from './accessibility-support-ipc.js';+import { mcpAppSchemePrivilege, registerMcpAppProtocol } from './mcp-apps/sandboxProtocol.js';import { prepareImportedAutomation, finishImportedAutomation } from './bot-import/automationRuntime.js';import { ensureImportedAutomationReady, recoverCompanionImports } from './bot-import/host.js';import { listWorktreeRecycleStatus, controlWorktreeRecycle } from './worktree/recycleControls';@@ -2557,6 +2558,7 @@ protocol.registerSchemesAsPrivileged([remoteMediaSchemePrivilege,cindyGhostSchemePrivilege,cindyMediaSchemePrivilege,+ mcpAppSchemePrivilege,]);import started from 'electron-squirrel-startup';@@ -9028,6 +9030,7 @@ app.on('ready', async () => {registerModelProtocolHandler();registerRemoteMediaProtocolHandler();registerCindyMediaProtocolHandler();+ registerMcpAppProtocol();// Inject a Content-Security-Policy response header onto the app's own// top-level document (defaultSession mainFrame) before any window loads.diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskMcpApps.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskMcpApps.test.tsnew file mode 100644index 0000000000..dbc0f442c9--- /dev/null+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskMcpApps.test.ts@@ -0,0 +1,69 @@+import { describe, expect, it } from 'vitest';+import { parseMcpAppRecord } from '@cindy/maker-shared/mcp-apps';+import { redactMessageRowForSharedGuest } from '../sharedTaskMessageOrigin';++describe('shared guest MCP App history projection', () => {+ const card = {+ version: 1,+ serverId: 'private-server',+ serverRevision: 'private-revision',+ resourceUri: 'ui://private/app',+ tool: { name: 'draft', inputSchema: { type: 'object' } },+ arguments: { private: 'input' },+ };++ it.each([false, true])(+ 'retains a pending card name without private inputs (serialized=%s)',+ (serialized) => {+ const original = { mcpApp: card };+ const row = {+ content: serialized ? JSON.stringify(original) : original,+ agentMeta: { mcpApp: true },+ };+ const projected = redactMessageRowForSharedGuest(row);+ expect(projected.content).toEqual({+ mcpAppHistory: { version: 1, title: 'draft', text: '' },+ });+ expect(parseMcpAppRecord(projected.content)).toBeUndefined();+ expect(row.content).toEqual(serialized ? JSON.stringify(original) : original);+ },+ );++ it.each([+ { mcpApp: { ...card, version: 2, private: 'future' } },+ { mcpApp: { ...card, result: { content: 'private-invalid' } } },+ { mcpApp: null, private: 'envelope' },+ '{private-invalid-json',+ ])('does not leak malformed or unsupported card records: %j', (content) => {+ expect(+ redactMessageRowForSharedGuest({ content, agentMeta: { mcpApp: true } }).content,+ ).toEqual({ mcpAppHistory: { version: 1, title: '', text: '' } });+ });++ it('reprojects cached public cards using a whitelist without retaining additive data', () => {+ const row = {+ content: {+ mcpAppHistory: { version: 1, title: 'Draft', text: 'Saved', private: 'summary' },+ private: 'envelope',+ },+ agentMeta: { mcpApp: true },+ };+ const projected = redactMessageRowForSharedGuest(row);+ expect(projected.content).toEqual({+ mcpAppHistory: { version: 1, title: 'Draft', text: 'Saved' },+ });+ expect(redactMessageRowForSharedGuest(projected)).toEqual(projected);+ });++ it('preserves ordinary messages and source rows', () => {+ const row = { role: 'assistant', content: 'Ordinary result', agentMeta: {} };+ expect(redactMessageRowForSharedGuest(row)).toBe(row);+ });+ it.each([+ { mcpApp: null, text: 'Ordinary result' },+ { mcpAppHistory: { version: 1, title: 'User data', text: 'Saved', extra: 'preserve me' } },+ ])('keeps unmarked App-shaped ordinary results intact for guests: %j', (content) => {+ const row = { role: 'assistant', content, agentMeta: { mcpApp: false } };+ expect(redactMessageRowForSharedGuest(row)).toBe(row);+ });+});diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.tsindex eeb6cafcae..277c74ed0b 100644--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.ts@@ -310,6 +310,118 @@ describe('shared task guests never see the owner private message sources', () =>});});+describe('shared task MCP App data stays at the owner boundary', () => {+ const message = {+ clientId: 'app-card',+ sessionId: 'task-a',+ role: 'assistant',+ agentMeta: { mcpApp: true },+ content: {+ mcpApp: {+ version: 1,+ serverId: 'private-server',+ serverRevision: 'private-revision',+ resourceUri: 'ui://private/app',+ connectionId: 'private-connection',+ tool: {+ name: 'draft',+ title: 'Draft form',+ inputSchema: { type: 'object', description: 'private-schema' },+ _meta: { private: 'tool' },+ },+ arguments: { private: 'input' },+ result: {+ content: [+ { type: 'text', text: 'Saved result', _meta: { private: 'block' } },+ { type: 'resource', resource: { text: 'private-html' } },+ { type: 'image', data: 'private-image' },+ { type: 'text', text: 'Second paragraph' },+ ],+ structuredContent: { private: 'structured' },+ _meta: { private: 'view-only' },+ },+ future: 'private-future',+ },+ future: 'private-envelope',+ },+ };+ const expected = {+ mcpAppHistory: { version: 1, title: 'Draft form', text: 'Saved result\n\nSecond paragraph' },+ };++ it.each(['online', 'reconnecting'])(+ 'redacts %s pushes before delivery or offline queueing',+ async (status) => {+ const transport = client();+ transport.getStatus.mockReturnValue(status);+ __testing.setActiveClient(transport as never);+ subscriptions.subscribe(guestA, ['session:task-a']);+ subscriptions.subscribe('own-task', ['session:task-a']);+ __testing.forwardPush('local-db:messages:created', { sessionId: 'task-a', message });+ await vi.advanceTimersByTimeAsync(300);+ const payload = (peer: string) =>+ status === 'online'+ ? transport.sendPush.mock.calls.find((call) => call[0] === peer)![2]+ : __testing.queuedPushesFor(peer)[0].payload;+ expect(payload(guestA).message.content).toEqual(expected);+ expect(JSON.stringify(payload(guestA))).not.toMatch(+ /private-|structuredContent|arguments|_meta/,+ );+ expect(payload('own-task').message.content).toEqual(message.content);+ expect(message.content.mcpApp.arguments).toEqual({ private: 'input' });+ },+ );++ it.each(['local-db:messages:list', 'local-db:messages:view', 'local-db:messages:work-details'])(+ 'redacts %s history while preserving same-account results',+ (channel) => {+ const transport = client();+ __testing.setActiveClient(transport as never);+ const page =+ channel === 'local-db:messages:list'+ ? [message]+ : {+ messages: [message],+ items: [+ {+ type: 'work',+ key: 'work',+ summary: {},+ children: [{ type: 'messages', key: 'prose', messages: [message] }],+ },+ ],+ };+ __testing.sendInvokeResultSafe(+ transport as never,+ guestA,+ 'guest',+ { ok: true, result: page },+ channel,+ ['task-a'],+ );+ __testing.sendInvokeResultSafe(+ transport as never,+ 'own-task',+ 'owner',+ { ok: true, result: page },+ channel,+ ['task-a'],+ );+ const results = new Map(+ transport.sendInvokeResult.mock.calls.map((call) => [call[1], call[2].result]),+ );+ const guest = results.get('guest');+ expect(+ channel === 'local-db:messages:list' ? guest[0].content : guest.messages[0].content,+ ).toEqual(expected);+ if (channel !== 'local-db:messages:list')+ expect(guest.items[0].children[0].messages[0].content).toEqual(expected);+ expect(JSON.stringify(guest)).not.toMatch(/private-|structuredContent|arguments|_meta/);+ expect(results.get('owner')).toEqual(page);+ },+ );+});+describe('shared task workdir watch', () => {it('delivers file tree events only to the guest whose admitted watch matches, and stops after revoke', async () => {const transport = client();diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex bc8a9c79a7..849a8979cc 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -1647,6 +1647,11 @@ async function ensureOnlineForRequest(): Promise<void> {/** closeRemoteLink 的取消代次(per-device):翻代使在途建链等待在发送前失效。 */const openLinkCloseEpochs = new Map<string, number>();+/** Long-lived consumers bind to this generation so later reads cannot undo an explicit close. */+export function getRemoteLinkCloseEpoch(deviceId: string): number {+ return openLinkCloseEpochs.get(deviceId) ?? 0;+}+/*** 控制端:向目标设备发起控制链路(link-open → link-accept)。*@@ -1733,7 +1738,8 @@ export function closeRemoteLink(deviceId: string): void {// 3. 订阅重放收敛循环(翻代 + 清定时器);// 4. 在途建链(登记删除 + closeEpochs 翻代拦 park 中的等待);// 5. remoteInvoke / remoteSubscribe 在途调用(经 4 的代次在发送/重开前自败);- // 6. OAuth 授权事务与本机回调监听(翻代后在后续操作前自败)。+ // 6. OAuth 授权事务与本机回调监听(翻代后在后续操作前自败);+ // 7. MCP App View 的跨调用轮询与清理(绑定打开时的代次,翻代后自败)。// 新增任何 per-device 重试/恢复机制时必须同步登记到本清单。transportTimeoutReopen.cancel(deviceId);cancelSubscriptionReplay(deviceId);diff --git a/apps/desktop/src/main/device-link/ipc.ts b/apps/desktop/src/main/device-link/ipc.tsindex 85878c5865..2a18d25efe 100644--- a/apps/desktop/src/main/device-link/ipc.ts+++ b/apps/desktop/src/main/device-link/ipc.ts@@ -7,6 +7,7 @@import { createHash, randomBytes } from 'node:crypto';import { ipcMain, shell, clipboard } from 'electron';+import { MCP_APPS_INVOKE } from '../../shared/mcpApps.js';import { currentOauthIdentityScope, trustOauthPeer } from '../plugin-oauth/desktopIdentity.js';import { RemotePluginOauthUnsupportedError, resolveOauthPeerIdentity } from '../plugin-oauth/identityResolver.js';import { getDeviceId } from '../authManager.js';@@ -375,8 +376,7 @@ export function handleListDevices(const directoryRequestSequence = deps.beginControllerDisplayNameDirectoryRefresh();const requestEpoch = deps.captureControllerDisplayNameRequestEpoch();const presenceRequestEpoch = deps.captureControllerPresenceRequestEpoch();- let request!: Promise<DeviceListResult>;- request = deps.apiFetch<{ devices: DeviceLinkServerDeviceView[] }>(+ const request = deps.apiFetch<{ devices: DeviceLinkServerDeviceView[] }>('/api/device-link/devices',).then(async (result) => {@@ -602,6 +602,9 @@ export async function handleInvoke(if (typeof channel !== 'string' || !channel.trim()) {throwIpcError('INVALID_PARAMS', 'channel is required');}+ // App RPCs require the dedicated Main/frame binding, including for remote cards.+ // Never forward Renderer-supplied View IDs through the general preload bridge.+ if (channel === MCP_APPS_INVOKE) throwIpcError('PERMISSION_DENIED', 'MCP_APP_FRAME_REQUIRED');if (channel === PLUGIN_OAUTH_CHANNEL || channel === PLUGIN_SECRET_LOCAL_CHANNEL || channel === PLUGIN_CONNECTION_LOCAL_CHANNEL|| channel === INPUT_HANDOFF_LOCAL_CHANNEL || channel === INPUT_HANDOFF_REMOTE_LOCAL_CHANNEL|| channel === INPUT_HANDOFF_LOCAL_PICTURE_CHANNEL || channel === INPUT_HANDOFF_REMOTE_PICTURE_CHANNELdiff --git a/apps/desktop/src/main/device-link/sharedTaskMessageOrigin.ts b/apps/desktop/src/main/device-link/sharedTaskMessageOrigin.tsindex 10f59bb00a..acc4f324a8 100644--- a/apps/desktop/src/main/device-link/sharedTaskMessageOrigin.ts+++ b/apps/desktop/src/main/device-link/sharedTaskMessageOrigin.ts@@ -1,5 +1,6 @@import { readMessageSourceGroup } from '@cindy/maker-shared/message-source';import { queueItemVisibleText } from '@cindy/maker-shared/queue';+import { projectMcpAppContent } from '@cindy/maker-shared/mcp-apps';const HOOK_SCHEDULE_ID_PREFIX = 'hook:';@@ -52,17 +53,21 @@ export function redactMessageOriginForSharedGuest(agentMeta: unknown): unknown {return hidden ? rest : agentMeta;}-/** 对单条消息行套用 {@link redactMessageOriginForSharedGuest};无需改动时返回原引用。 */+/** Strip private attribution and MCP App data from message rows; never mutate stored history. */export function redactMessageRowForSharedGuest<T>(message: T): T {if (!message || typeof message !== 'object' || Array.isArray(message)) return message;const record = message as Record<string, unknown>;let agentMeta = redactMessageOriginForSharedGuest(record.agentMeta);+ const content = projectMcpAppContent(record.content,+ !!record.agentMeta && typeof record.agentMeta === 'object' &&+ (record.agentMeta as Record<string, unknown>).mcpApp === true);// Preserve independent reply visibility without disclosing source identity// or sealing unrelated prose in the canonical model turn.if (record.role === 'assistant' && readMessageSourceGroup(record.agentMeta)) {agentMeta = { ...(agentMeta as Record<string, unknown>), explicitDelivery: true };}- return agentMeta === record.agentMeta ? message : ({ ...record, agentMeta } as T);+ return agentMeta === record.agentMeta && content === record.content+ ? message : ({ ...record, agentMeta, content } as T);}/**diff --git a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts b/apps/desktop/src/main/goal-host/__tests__/controller.test.tsindex 4b29ea17dd..91813c9aa5 100644--- a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts+++ b/apps/desktop/src/main/goal-host/__tests__/controller.test.ts@@ -18,6 +18,7 @@ import {import { buildContinuationDirective, buildFirstTurnDirective } from '../directive';import { MAX_CONSECUTIVE_OVERLOAD_TURNS } from '../usageLimit';import { publishUiSessionIntervention, resetUiContinuationListenersForTest } from '../../maker-ipc/uiContinuationSignal';+import { MCP_APP_MESSAGE_GUARD } from '../../mcp-apps/message.js';import type {AccountLimitInfo,GoalCompletionSummary,@@ -70,6 +71,7 @@ function productionSteer(session: FakeSession, deliver: () => Promise<void>, rej},MAIN_OWNED_SEND_CONTEXT: Symbol(), AUTO_REVIEW_SOURCE_CONTENT: Symbol(),AUTO_REVIEW_DELEGATED_CONTINUATION: Symbol(), AUTO_REVIEW_USER_INTENT: Symbol(),+ MCP_APP_MESSAGE_GUARD,publishUiSessionIntervention,noteInteractionRouteSteer: () => {},summarizeIpcUserMessage: () => ({}),diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex 9bb9805a75..edee9c2a3e 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -2515,8 +2515,14 @@ describe('Bot canonical Session lifecycle', () => {});it('validates a settings grant against the model chain saved in the same update', async () => {- h.customMcpConfigs.push({ id: 'events', name: 'Events', transport: 'sse', url: 'https://example.invalid/sse', headers: {} });+ const eventsConfig = { id: 'events', name: 'Events', transport: 'sse' as const, url: 'https://example.invalid/sse', headers: {} };+ h.customMcpConfigs.push(eventsConfig);await refreshCustomMcpProviders();+ // Keep this test on the legacy direct provider path so the model-route+ // admission guard still covers a transport unavailable to Codex.+ const eventsProviderIndex = h.mcpProviders.findIndex((provider) => provider.name === eventsConfig.id);+ expect(eventsProviderIndex).toBeGreaterThanOrEqual(0);+ h.mcpProviders[eventsProviderIndex] = new CustomMcpProvider(eventsConfig, () => null);const chain: BotModelRoute[] = [{ harness: 'claude', model: 'claude-x', providerId: null, effort: '', fastMode: false }];await invoke('local-db:bots:update', { id: 'bot-1', capabilities: { modelChain: chain } });const created = await invoke('local-db:bots:create-canonical-session', {@@ -2554,8 +2560,14 @@ describe('Bot canonical Session lifecycle', () => {it('validates model-side grants against the next configured route while the old turn is running', async () => {let chain: BotModelRoute[] = [{ harness: 'claude', model: 'claude-x', providerId: null, effort: '', fastMode: false }];- h.customMcpConfigs.push({ id: 'events', name: 'Events', transport: 'sse', url: 'https://example.invalid/sse', headers: {} });+ const eventsConfig = { id: 'events', name: 'Events', transport: 'sse' as const, url: 'https://example.invalid/sse', headers: {} };+ h.customMcpConfigs.push(eventsConfig);await refreshCustomMcpProviders();+ // The production registry mounts the Apps facade for every harness. Use a+ // direct provider here to exercise the route-change rejection itself.+ const eventsProviderIndex = h.mcpProviders.findIndex((provider) => provider.name === eventsConfig.id);+ expect(eventsProviderIndex).toBeGreaterThanOrEqual(0);+ h.mcpProviders[eventsProviderIndex] = new CustomMcpProvider(eventsConfig, () => null);await invoke('local-db:bots:update', { id: 'bot-1', capabilities: { modelChain: chain } });const created = await invoke('local-db:bots:create-canonical-session', {botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 2,@@ -2653,7 +2665,7 @@ describe('Bot canonical Session lifecycle', () => {it.each([{ id: 'pi-sse', transport: 'sse' as const, url: 'https://example.invalid/mcp' },{ id: 'pi-public-http', transport: 'http' as const, url: 'http://example.invalid/mcp' },- ])('keeps Pi-incompatible $id discoverable but unjoinable and removable', async (config) => {+ ])('exposes $id through the MCP Apps facade on Pi', async (config) => {h.customMcpConfigs.push({ ...config, name: config.id, headers: {} });await refreshCustomMcpProviders();await invoke('local-db:bots:update', {@@ -2666,9 +2678,9 @@ describe('Bot canonical Session lifecycle', () => {const input = { callerSessionId: created.session.id, kind: 'mcp' as const, id: config.id };await expect(findBotCapabilities(input)).resolves.toMatchObject({capabilities: expect.arrayContaining([{ id: config.id, name: config.id,- description: config.transport, available: false, joined: true }]),+ description: config.transport, available: true, joined: true }]),});- await expect(selectBotCapability({ ...input, joined: true })).resolves.toMatchObject({ ok: false, errorCode: 'CAPABILITY_UNAVAILABLE' });+ await expect(selectBotCapability({ ...input, joined: true })).resolves.toMatchObject({ ok: true, joined: true });await expect(selectBotCapability({ ...input, joined: false })).resolves.toMatchObject({ ok: true, joined: false });});diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/messagesWriteReadback.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/messagesWriteReadback.test.tsindex 2d3eb87cac..01e795f4a3 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/messagesWriteReadback.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/messagesWriteReadback.test.ts@@ -69,7 +69,8 @@ vi.mock('../../client/current', () => ({getDbClient: () => h.client,}));-import { createMessage, updateMessageContent } from '../messages';+import { broadcastMessageRow, createMessage, updateMessageContent } from '../messages';+import { messageToCamel } from '../../mapper';function setupDb(): void {const sqlite = new Database(':memory:', { verbose: (sql) => h.queries.push(String(sql)) });@@ -121,6 +122,33 @@ describe('message write paths avoid large-content readback', () => {setupDb();});+ it('keeps View-only MCP App data out of create, reload and owner broadcasts', async () => {+ const { tapWindowBroadcast } = await import('../../../device-link/broadcast-tap');+ vi.mocked(tapWindowBroadcast).mockClear();+ const content = { mcpApp: {+ version: 1, serverId: 'private-server', serverRevision: 'private-revision',+ resourceUri: 'ui://private/app',+ tool: { name: 'form', title: 'Draft', inputSchema: { type: 'object', private: 'schema' } },+ arguments: { private: 'input' },+ result: { content: [{ type: 'text', text: 'Saved', _meta: { private: 'block' } }],+ structuredContent: { private: 'structured' }, _meta: { private: 'view-only' } },+ } };+ const publicContent = { mcpAppHistory: { version: 1, title: 'Draft', text: 'Saved' } };+ const created = await createMessage('s1', { clientId: 'app-card', role: 'assistant', content, agentMeta: { mcpApp: true } });+ expect(created.content).toEqual(publicContent);+ const row = (await h.db!.select().from(messages))[0]!;+ expect(JSON.parse(row.content)).toEqual(content);+ expect(messageToCamel(row).content).toEqual(publicContent);+ expect(tapWindowBroadcast).toHaveBeenCalledWith('local-db:messages:created',+ expect.objectContaining({ message: expect.objectContaining({ clientId: 'app-card', content: publicContent }) }));+ vi.mocked(tapWindowBroadcast).mockClear();+ // The shared broadcaster also accepts Main-created rows without the DB mapper.+ broadcastMessageRow('s1', { ...created, content });+ expect(tapWindowBroadcast).toHaveBeenLastCalledWith('local-db:messages:created',+ expect.objectContaining({ message: expect.objectContaining({ content: publicContent }) }));+ expect(content.mcpApp.result._meta).toEqual({ private: 'view-only' });+ });+it.each([false, true])('publishes only after the post-write guard succeeds (revoked=%s)', async revoked => {const { tapWindowBroadcast } = await import('../../../device-link/broadcast-tap');const { onMessageCreated } = await import('../../../embedders/chat-history-embedder');diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.tsindex 8e29fa4159..583319283b 100644--- a/apps/desktop/src/main/localDb/ipc/messages.ts+++ b/apps/desktop/src/main/localDb/ipc/messages.ts@@ -25,6 +25,7 @@ import {import { createId } from '@paralleldrive/cuid2';import { historyOutlineContent, historyOutlineContentStamp, withHistoryArtifacts } from './historyViewOutline';import { historyViewLeaves, isHistoryViewUnavailable } from '@cindy/maker-shared/message-window';+import { projectMcpAppContent } from '@cindy/maker-shared/mcp-apps';import { getDbClient, getCurrentDbClientSnapshot } from '../client/current';import type { ContextRebuildArgs } from '../client/tx/types';@@ -852,7 +853,11 @@ export function broadcastMessageRow(msg: Message,ownerScope?: DataOwnerBroadcastScope | null,): void {- broadcastOwnedPayload('local-db:messages:created', { sessionId, message: msg }, ownerScope);+ // Main-created rows may bypass the DB mapper. Never broadcast View-only data+ // to top-level renderers or same-account control devices.+ const content = projectMcpAppContent(msg.content, msg.agentMeta?.mcpApp === true);+ const message = content === msg.content ? msg : { ...msg, content };+ broadcastOwnedPayload('local-db:messages:created', { sessionId, message }, ownerScope);if (msg.role === 'user' || msg.role === 'assistant') {scheduleBotRemoteResourceChangedForSession(sessionId, ownerScope?.ownerScopeKey);}diff --git a/apps/desktop/src/main/localDb/mapper.ts b/apps/desktop/src/main/localDb/mapper.tsindex 9caf3178f6..07c8605f72 100644--- a/apps/desktop/src/main/localDb/mapper.ts+++ b/apps/desktop/src/main/localDb/mapper.ts@@ -12,6 +12,7 @@ import { hasPendingSessionInterruption } from '@cindy/maker-shared/session-activimport { DESKTOP_VISIBLE_SESSION_SOURCES } from '../../shared/sessionSource.js';import { getSessionInterruptionBootAt } from './sessionInterruptionBoot';import { stripInternalWebCitations } from '@cindy/maker-shared/internal-citation';+import { projectMcpAppContent } from '@cindy/maker-shared/mcp-apps';import { markdownPreviewText } from '../../shared/markdownPreviewText.js';import {parseOrcaRemoteLead,@@ -335,7 +336,7 @@ export function messageToCamel(row: MessageRow): Message {clientId: row.clientId,sessionId: row.sessionId,role: row.role as MessageRole,- content,+ content: projectMcpAppContent(content, agentMeta?.mcpApp === true),toolUseId: row.toolUseId,agentMeta,agentKind: (row.agentKind as 'cc' | 'codex' | 'pi' | null) ?? null,diff --git a/apps/desktop/src/main/maker-host/botMcpCatalog.ts b/apps/desktop/src/main/maker-host/botMcpCatalog.tsindex 1a0e54640b..9237bf42ea 100644--- a/apps/desktop/src/main/maker-host/botMcpCatalog.ts+++ b/apps/desktop/src/main/maker-host/botMcpCatalog.ts@@ -1,6 +1,7 @@import type { McpProvider, McpProviderContext } from '@cindy/maker-core';import type { McpTransport } from '../../shared/customMcp.js';import { isPiCustomMcpProviderAvailable } from '../mcp-integrations/piMcpTransport.js';+import { CustomMcpProvider } from '../mcp-integrations/custom-mcp-provider.js';function isCustomMcpAvailable(input: {agentKind: McpProviderContext['agentKind'];@@ -8,6 +9,9 @@ function isCustomMcpAvailable(input: {provider: McpProvider;custom?: { transport: McpTransport };}): boolean {+ // The Apps facade is carried by the authenticated Host bridge for every+ // harness, including SSH. Direct-transport limitations do not apply to it.+ if (input.provider instanceof CustomMcpProvider && input.provider.supportsApps) return true;// SSH Codex receives only REMOTE_ALLOWED_SERVER_NAMES; user configs are not// written into its daemon. Remote Claude serializes http/sse into startParams.// Remote Pi connects to custom HTTP MCPs directly (`s.remote` is not tunneled).diff --git a/apps/desktop/src/main/maker-host/cc-remote-mcp.ts b/apps/desktop/src/main/maker-host/cc-remote-mcp.tsindex 1a99174014..185c8ae8fe 100644--- a/apps/desktop/src/main/maker-host/cc-remote-mcp.ts+++ b/apps/desktop/src/main/maker-host/cc-remote-mcp.ts@@ -204,7 +204,9 @@ export async function buildCcRemoteHttpMcpServers(// 这个改动只会**收窄**注入(allowed 键不存在时行为逐字不变),不会放开任何原本// 被禁的东西。names 变化会经 computeRemoteMcpFingerprint 变成新代际,策略变更// 触发 forceFresh 正是既定语义。+ const mounted = vendorOptions?.cindyRuntimeMcpServerNames;const names = selectRemoteInjectableServerNames(started.serverNames, {+ appServerNames: args.botSession ? (Array.isArray(mounted) ? mounted.filter((name): name is string => typeof name === 'string') : []) : undefined,collabEnabled:(deps.isCollabEnabled?.() ?? true) && isFrozenBuiltinPluginAllowed(vendorOptions, 'collab'),memoryEnabled: args.makerMemoryEnabled === true,diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex 5e19dfa1f3..db3e89bb58 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -1820,12 +1820,13 @@ export function getMaker(): Maker {extraEnv: {},codexProxyActive: false,codexBrowserUseAvailable: true,- buildSessionMcpConfig: (instance: string) =>+ buildSessionMcpConfig: (instance: string, session?: { vendorOptions?: Record<string, unknown> }) =>buildRemoteCodexSessionMcpConfig(ctx.remoteHostId!, instance, {bridgeInstanceId: getActiveCodexBridgeInstanceId(),serverNames: getActiveCodexBridgeServerNames() ?? [],collabEnabled: pluginRegistry.isEnabled('collab'),makerMemoryEnabled: _maker?.makerMemory?.isEnabled() ?? false,+ vendorOptions: session?.vendorOptions,}),};}diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.tsindex a62c465eb3..a3d0f5a622 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts@@ -8,6 +8,7 @@ import { AUTO_REVIEW_DELEGATED_CONTINUATION, restoreAutoReviewUserIntent, type Aimport { createPluginTaskReviewResolver, type PluginReviewSnapshot } from '../pluginTaskReviewContext.js';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { AgentInputCoordinator } from '../agent-input-coordinator.js';+import { MCP_APP_MESSAGE_CLIENT_PREFIX, MCP_APP_MESSAGE_GUARD } from '../../mcp-apps/message.js';import { hasAcceptedUserTaskInput } from '../pluginTaskInput.js';import { runSchedulerQueuedPreparation } from '../schedulerQueuedPreparation.js';import {@@ -72,6 +73,210 @@ const mocks = vi.hoisted(() => {};});+describe('MCP App queued message grants', () => {+ function appItem(guard: () => Promise<void>) {+ return {+ ...makeItem(`${MCP_APP_MESSAGE_CLIENT_PREFIX}fixture`, '\\/compact'),+ sourcePlugin: { pluginId: 'mcp-app:example', name: 'example' },+ autoReviewUserText: { kind: 'delegated-continuation' as const },+ [MCP_APP_MESSAGE_GUARD]: guard,+ };+ }++ function guardedHarness() {+ const h = createHarness();+ const dispatched = vi.fn();+ h.sendToAgent.mockImplementation(async (_id, _message, _opts, sendOpts) => {+ await sendOpts[MCP_APP_MESSAGE_GUARD]?.();+ dispatched();+ return sendSuccess();+ });+ h.steerToAgent.mockImplementation(async (_id, _message, sendOpts) => {+ await sendOpts[MCP_APP_MESSAGE_GUARD]?.();+ dispatched();+ });+ return { ...h, dispatched };+ }++ it.each([+ { persisted: false, returned: false },+ { persisted: true, returned: false },+ { persisted: false, returned: true },+ { persisted: true, returned: true },+ ])('discards a revoked App input and dispatches the following user message: %j', async ({ persisted, returned }) => {+ const h = guardedHarness(), sid = 'app-busy';+ let visible = true;+ const guard = vi.fn(async () => { if (!visible) throw new Error('MCP_APP_CARD_UNAVAILABLE'); });+ const send = h.sendToAgent.getMockImplementation()!;+ h.sendToAgent.mockImplementation(async (sessionId, message, createOpts, sendOpts) => {+ if (persisted && sendOpts[MCP_APP_MESSAGE_GUARD]) {+ await sendOpts.persistUserMessage?.onPersisted?.();+ }+ try {+ return await send(sessionId, message, createOpts, sendOpts);+ } catch (error) {+ if (!returned) throw error;+ return { kind: 'session-dispatch', source: 'test', dispatched: false,+ reason: 'cancelled-before-dispatch', message: String(error), context: 'send' };+ }+ });+ await h.coordinator.ensureQueueRestored(sid);+ h.setRunning(true);+ h.coordinator.enqueue(sid, appItem(guard));+ h.coordinator.enqueue(sid, makeItem('following', 'Next user message'));+ expect(Object.getOwnPropertySymbols(h.coordinator.getProjection(sid).pendingQueue[0]!)).not.toContain(MCP_APP_MESSAGE_GUARD);+ await flush();+ expect(h.sendToAgent).not.toHaveBeenCalled();+ visible = false;+ h.setRunning(false);+ h.coordinator.wakeSession(sid, 'app-fixture-idle');+ await vi.waitFor(() => expect(h.dispatched).toHaveBeenCalledOnce());+ await flush();+ expect(guard).toHaveBeenCalledOnce();+ expect(h.dispatched).toHaveBeenCalledOnce();+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ expect(h.sendToAgent.mock.calls[1]![3].persistUserMessage?.clientId).toBe('following');+ const revoked = expect.objectContaining({ clientId: `${MCP_APP_MESSAGE_CLIENT_PREFIX}fixture` });+ expect(h.onRejectedUserTurn).toHaveBeenCalledExactlyOnceWith(sid, revoked);+ if (persisted) {+ expect(h.onUndispatchedUserTurn).toHaveBeenCalledExactlyOnceWith(sid, revoked, 'failed');+ expect(h.onDiscardedQueuedMessage).not.toHaveBeenCalled();+ } else {+ expect(h.onDiscardedQueuedMessage).toHaveBeenCalledExactlyOnceWith(sid, revoked);+ expect(h.onUndispatchedUserTurn).not.toHaveBeenCalled();+ }+ expect(h.coordinator.getProjection(sid)).toMatchObject({ error: null, recovery: null, pendingQueue: [] });+ expect(latestSnapshotClientIds(h.persistQueueSnapshot)).not.toContain(`${MCP_APP_MESSAGE_CLIENT_PREFIX}fixture`);+ });++ it('settles an App-only queue after revocation without requiring retry before the next user message', async () => {+ const h = guardedHarness(), sid = 'app-revoked-only';+ const guard = vi.fn(async () => { throw new Error('MCP_APP_CARD_UNAVAILABLE'); });+ await h.coordinator.ensureQueueRestored(sid);+ h.coordinator.enqueue(sid, appItem(guard));+ await flush();+ expect(guard).toHaveBeenCalledOnce();+ expect(h.coordinator.getProjection(sid)).toMatchObject({ error: null, recovery: null, pendingQueue: [] });+ expect(h.coordinator.hasPendingQueuedWork(sid)).toBe(false);+ expect(latestSnapshotClientIds(h.persistQueueSnapshot)).toEqual([]);+ h.coordinator.wakeSession(sid, 'later-idle');+ h.coordinator.enqueue(sid, makeItem('later', 'Next user message'));+ await flush();+ expect(h.dispatched).toHaveBeenCalledOnce();+ expect(guard).toHaveBeenCalledOnce();+ expect(h.sendToAgent.mock.calls[1]![3].persistUserMessage?.clientId).toBe('later');+ });++ it('keeps send failures retryable when the live App guard itself succeeded', async () => {+ const h = guardedHarness(), sid = 'app-send-failure';+ const guard = vi.fn(async () => {});+ h.sendToAgent.mockImplementationOnce(async (_id, _message, _opts, sendOpts) => {+ await sendOpts[MCP_APP_MESSAGE_GUARD]?.();+ throw new Error('MCP_APP_CARD_UNAVAILABLE');+ });+ await h.coordinator.ensureQueueRestored(sid);+ h.coordinator.enqueue(sid, appItem(guard));+ await flush();+ expect(guard).toHaveBeenCalledOnce();+ expect(h.onDiscardedQueuedMessage).not.toHaveBeenCalled();+ expect(h.coordinator.getProjection(sid).recovery).toEqual({ kind: 'queue-head', clientId: `${MCP_APP_MESSAGE_CLIENT_PREFIX}fixture` });+ expect(h.coordinator.getProjection(sid).pendingQueue).toHaveLength(1);+ });++ it('keeps the grant through queue copies and asynchronous drain preparation', async () => {+ const h = guardedHarness(), sid = 'app-preparing';+ let visible = true;+ const guard = vi.fn(async () => { if (!visible) throw new Error('MCP_APP_CARD_UNAVAILABLE'); });+ h.getSdkSessionId.mockImplementationOnce(async () => { visible = false; return 'sdk-session'; });+ await h.coordinator.ensureQueueRestored(sid);+ h.coordinator.enqueue(sid, appItem(guard));+ await flush();+ expect(guard).toHaveBeenCalledOnce();+ expect(h.dispatched).not.toHaveBeenCalled();+ });++ it.each([false, true])('drops crash-restored App grants and lets the following message run (legacy=%s)', async (legacy) => {+ const h = guardedHarness(), sid = 'app-restored';+ const guard = vi.fn(async () => {});+ const restored = JSON.parse(JSON.stringify(appItem(guard)));+ if (legacy) restored.clientId = 'legacy-app-row';+ else delete restored.sourcePlugin;+ h.setLoadQueueSnapshot(async () => [restored, makeItem('following', 'Next user message')]);+ await h.coordinator.ensureQueueRestored(sid);+ expect(h.coordinator.getProjection(sid).pendingQueue.map(item => item.clientId)).toEqual(['following']);+ expect(h.onDiscardedQueuedMessage).toHaveBeenCalledExactlyOnceWith(sid, restored);+ h.coordinator.resume(sid);+ await flush();+ expect(h.dispatched).toHaveBeenCalledOnce();+ expect(h.sendToAgent.mock.calls[0]![3].persistUserMessage?.clientId).toBe('following');+ expect(guard).not.toHaveBeenCalled();+ expect(h.coordinator.getProjection(sid)).toMatchObject({ error: null, recovery: null, pendingQueue: [] });+ expect(latestSnapshotClientIds(h.persistQueueSnapshot)).not.toContain(restored.clientId);+ });++ it('drops crash-restored App-only snapshots without pausing or creating retry recovery', async () => {+ const h = guardedHarness(), sid = 'app-restored-only';+ const restored = JSON.parse(JSON.stringify(appItem(async () => {})));+ h.setLoadQueueSnapshot(async () => [restored]);+ await h.coordinator.ensureQueueRestored(sid);+ await flush();+ expect(h.coordinator.getProjection(sid)).toMatchObject({+ error: null, recovery: null, pendingQueue: [], queuePaused: false,+ });+ expect(h.onDiscardedQueuedMessage).toHaveBeenCalledExactlyOnceWith(sid, restored);+ expect(latestSnapshotClientIds(h.persistQueueSnapshot)).toEqual([]);+ expect(h.dispatched).not.toHaveBeenCalled();+ });++ it('dispatches a live App queue grant while keeping it out of queue snapshots', async () => {+ const h = guardedHarness(), sid = 'app-live';+ const guard = vi.fn(async () => {});+ await h.coordinator.ensureQueueRestored(sid);+ h.coordinator.enqueue(sid, appItem(guard));+ await flush();+ expect(guard).toHaveBeenCalledOnce();+ expect(h.dispatched).toHaveBeenCalledOnce();+ const snapshots = JSON.stringify(h.persistQueueSnapshot.mock.calls);+ expect(snapshots).not.toContain('MCP_APP_MESSAGE_GUARD');+ });++ it.each([true, false])('uses the Main-owned App row when a projection is steered (visible=%s)', async (visible) => {+ const h = guardedHarness(), sid = 'app-steer';+ const guard = vi.fn(async () => { if (!visible) throw new Error('MCP_APP_CARD_UNAVAILABLE'); });+ await h.coordinator.ensureQueueRestored(sid);+ h.setRunning(true);+ h.coordinator.enqueue(sid, appItem(guard));+ const projected = JSON.parse(JSON.stringify(h.coordinator.getProjection(sid).pendingQueue[0]));+ expect(await h.coordinator.steer(sid, projected, { removeFromQueue: true })).toBe(visible);+ expect(guard).toHaveBeenCalledOnce();+ expect(h.dispatched).toHaveBeenCalledTimes(visible ? 1 : 0);+ expect(h.sendToAgent).not.toHaveBeenCalled();+ });++ it('checks the live App row after asynchronous steer preparation', async () => {+ const h = guardedHarness(), sid = 'app-steer-preparing';+ let visible = true;+ const guard = vi.fn(async () => { if (!visible) throw new Error('MCP_APP_CARD_UNAVAILABLE'); });+ const prepared = deferred<void>();+ h.steerToAgent.mockImplementationOnce(async (_id, _message, sendOpts) => {+ await prepared.promise;+ await sendOpts[MCP_APP_MESSAGE_GUARD]?.();+ h.dispatched();+ });+ await h.coordinator.ensureQueueRestored(sid);+ h.setRunning(true);+ h.coordinator.enqueue(sid, appItem(guard));+ const projected = JSON.parse(JSON.stringify(h.coordinator.getProjection(sid).pendingQueue[0]));+ const steering = h.coordinator.steer(sid, projected, { removeFromQueue: true });+ await vi.waitFor(() => expect(h.steerToAgent).toHaveBeenCalledOnce());+ visible = false;+ prepared.resolve();+ expect(await steering).toBe(false);+ expect(guard).toHaveBeenCalledOnce();+ expect(h.dispatched).not.toHaveBeenCalled();+ });+});+describe('INPUT_ENQUEUE crash-restored remote Worker pause', () => {const source = readFileSync(new URL('../register.ts', import.meta.url), 'utf8').replace(/\r\n/g, '\n');const start = source.indexOf(' MAKER_INVOKE.INPUT_ENQUEUE,');diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.tsindex 6dc1eafc6a..a4a16ea0db 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts@@ -16,7 +16,8 @@ import { formatQuotesForSend, stripChatQuoteMarkerLines } from '@cindy/maker-shaimport type { AgentInputQueuedMessage } from '../../../shared/agentInputQueue';import { parseOrcaRemoteLead } from '../../../shared/orcaRemoteWorker';import { describe, expect, it, vi } from 'vitest';-import { AUTO_REVIEW_DELEGATED_CONTINUATION, type AutoReviewHistoryMessage } from '../autoReviewUserIntent.js';+import { AUTO_REVIEW_DELEGATED_CONTINUATION, restoreAutoReviewUserIntent, type AutoReviewHistoryMessage } from '../autoReviewUserIntent.js';+import { appMessageInput, MCP_APP_MESSAGE_GUARD } from '../../mcp-apps/message.js';import {createMakerSendTransaction,restoreTrustedDesktopQueuedOrigin,@@ -39,6 +40,7 @@ import { buildCindyMakeTaskNote } from '../../cindy-make/taskNote';import { getResolvedMainLocale } from '../../i18n';import { buildMobileClientPromptNote } from '../mobileClientPromptNote';import { buildUiLanguageErrorNote } from '../uiLanguageErrorNote';+import * as mcpApps from '../../mcp-apps/runtime.js';import { createWireNoteMemory } from '../wireNoteMemory';import {applyPendingAgentSwitchIfIdle,@@ -59,6 +61,179 @@ function withUiLanguageNote(content: string): string {function withUiLanguageUserMessage(content: string): { type: 'user'; content: string } {return { type: 'user', content: withUiLanguageNote(content) };}+describe('MCP App next-turn context', () => {+ it('keeps ordinary user intent when validating App context without a replacement intent', async () => {+ const assertCurrent = vi.fn(async () => {});+ const read = vi.spyOn(mcpApps, 'mcpAppModelContext').mockResolvedValue({+ text: 'App says deploy.', consume() {}, assertCurrent,+ });+ try {+ const { deps, session } = createDeps();+ await createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'Read only.');+ const [message, opts] = vi.mocked(session.send).mock.calls[0];+ expect(JSON.stringify(message)).toContain('App says deploy.');+ expect(opts?.[AUTO_REVIEW_USER_INTENT]).toBeUndefined();+ expect(await opts?.resolveAutoReviewUserIntent?.()).toBeUndefined();+ expect(assertCurrent).toHaveBeenCalled();+ expect(appendAutoReviewUserIntent('Earlier owner restriction', 'App says deploy.', opts)).toEqual({+ earlierUserMessages: ['Earlier owner restriction'],+ currentUserMessage: 'Read only.',+ });+ } finally {+ read.mockRestore();+ }+ });++ it.each(['metadata', 'before-provider', 'vision'] as const)(+ 'revalidates context revoked during %s preparation before sending to the provider',+ async (phase) => {+ let captured = false;+ let valid = true;+ const consume = vi.fn();+ const assertCurrent = vi.fn(async () => {+ if (!valid) throw new Error('MCP_APP_CARD_UNAVAILABLE');+ });+ const read = vi.spyOn(mcpApps, 'mcpAppModelContext').mockImplementation(async () => {+ captured = true;+ return { text: 'PRIVATE_APP_DRAFT', consume, assertCurrent };+ });+ const provider = vi.fn();+ const { deps, session } = createDeps({+ getSessionMeta: vi.fn(async () => {+ if (captured && phase === 'metadata') valid = false;+ return { title: 'Test' };+ }),+ });+ vi.mocked(session.send).mockImplementation(async (_message, opts) => {+ if (phase === 'before-provider') valid = false;+ await opts?.beforeProviderStart?.();+ await opts?.onAccepted?.();+ if (phase === 'vision') valid = false;+ await opts?.resolveAutoReviewUserIntent?.();+ provider();+ return { accepted: true };+ });+ try {+ await expect(+ createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'Continue'),+ ).rejects.toThrow('MCP_APP_CARD_UNAVAILABLE');+ expect(provider).not.toHaveBeenCalled();+ expect(consume).not.toHaveBeenCalled();+ expect(assertCurrent).toHaveBeenCalled();+ } finally {+ read.mockRestore();+ }+ },+ );++ it('adds the latest App context to the agent wire while keeping the persisted user message intact', async () => {+ const context =+ '\n[MCP App context: external application data]\n{"draft":"updated"}\n[/MCP App context]';+ const consume = vi.fn();+ const read = vi+ .spyOn(mcpApps, 'mcpAppModelContext')+ .mockResolvedValueOnce({ text: context, consume, assertCurrent: async () => {} });+ try {+ const { deps, session } = createDeps();+ await createMakerSendTransaction(deps).sendToAgentAccepted(+ 'session-1',+ 'Continue',+ undefined,+ {+ persistUserMessage: { clientId: 'input', content: 'Continue' },+ },+ );+ expect(read).toHaveBeenCalledWith('session-1');+ const call = vi.mocked(session.send).mock.calls[0][0];+ const wire = typeof call === 'string' ? call : call.content;+ expect(JSON.stringify(wire)).toContain('updated');+ expect(JSON.stringify(wire)).toContain('Continue');+ expect(deps.createDbMessage).toHaveBeenCalledWith(+ 'session-1',+ expect.objectContaining({ content: 'Continue' }),+ undefined,+ );+ expect(consume).toHaveBeenCalledOnce();+ } finally {+ read.mockRestore();+ }+ });+ it.each(['rejected', 'throws'] as const)(+ 'keeps context when dispatch %s, consumes it on accepted retry and omits it afterwards',+ async (failure) => {+ let pending = true;+ const consume = vi.fn(() => {+ pending = false;+ });+ const read = vi+ .spyOn(mcpApps, 'mcpAppModelContext')+ .mockImplementation(async () =>+ pending+ ? { text: 'APP_DRAFT', consume, assertCurrent: async () => {} }+ : { text: '', consume() {}, assertCurrent: async () => {} },+ );+ let first = true;+ const session = createSession({+ send: vi.fn(async (+ _message: UserMessage | string,+ options?: SessionSendOptions,+ ): Promise<SessionSendResult> => {+ await options?.onAccepted?.();+ if (first) {+ first = false;+ if (failure === 'throws') throw new Error('Dispatch failed');+ return { accepted: false, reason: 'cancelled-before-dispatch' };+ }+ return { accepted: true };+ }),+ });+ const memory = createWireNoteMemory();+ const { deps } = createDeps({+ getSession: () => session,+ planRepeatableWireNotes: (sessionId, notes, opts) => memory.plan(sessionId, notes, opts),+ });+ const transaction = createMakerSendTransaction(deps);+ try {+ const attempt = transaction.sendToAgentAccepted('session-1', 'Continue', undefined, {+ persistUserMessage: { clientId: 'input', content: 'Continue' },+ });+ if (failure === 'throws') await expect(attempt).rejects.toThrow('Dispatch failed');+ else await expect(attempt).resolves.toMatchObject({ accepted: false });+ expect(consume).not.toHaveBeenCalled();+ expect(JSON.stringify(vi.mocked(session.send).mock.calls[0][0])).toContain(uiLanguageNote());+ await expect(transaction.sendToAgentAccepted('session-1', 'Retry')).resolves.toMatchObject({+ accepted: true,+ });+ expect(JSON.stringify(vi.mocked(session.send).mock.calls[1][0])).toContain('APP_DRAFT');+ expect(JSON.stringify(vi.mocked(session.send).mock.calls[1][0])).toContain(uiLanguageNote());+ expect(consume).toHaveBeenCalledOnce();+ await transaction.sendToAgentAccepted('session-1', 'Next');+ expect(JSON.stringify(vi.mocked(session.send).mock.calls[2][0])).not.toContain('APP_DRAFT');+ expect(JSON.stringify(vi.mocked(session.send).mock.calls[2][0])).not.toContain(uiLanguageNote());+ } finally {+ read.mockRestore();+ }+ },+ );+ it.each([+ ['claude-code', '/compact'],+ ['pi', '/skill:git'],+ ] as const)('leaves context pending for the %s native command %s', async (agentKind, command) => {+ const consume = vi.fn();+ const read = vi+ .spyOn(mcpApps, 'mcpAppModelContext')+ .mockResolvedValue({ text: 'APP_DRAFT', consume, assertCurrent: async () => {} });+ try {+ const session = createSession({ agentKind });+ const { deps } = createDeps({ getSession: () => session });+ await createMakerSendTransaction(deps).sendToAgentAccepted('session-1', command);+ expect(read).not.toHaveBeenCalled();+ expect(consume).not.toHaveBeenCalled();+ } finally {+ read.mockRestore();+ }+ });+});function createSession(overrides: Partial<MakerSendTransactionSession> = {}): MakerSendTransactionSession {return {@@ -74,6 +249,7 @@ function createSession(overrides: Partial<MakerSendTransactionSession> = {}): Ma_message: UserMessage | string,opts?: SessionSendOptions,) => {+ await opts?.beforeProviderStart?.();await opts?.onAccepted?.();await opts?.onTranscriptUserEntry?.('pi-user-entry');await opts?.resolveAutoReviewUserIntent?.();@@ -132,6 +308,99 @@ function createDeps(overrides: Partial<MakerSendTransactionDeps> = {}) {return { deps, session };}+describe('MCP App message authorization', () => {+ it.each(['claude-code', 'pi', 'codex'] as const)(+ 'keeps App slash text literal and includes its source note for %s',+ async (agentKind) => {+ const { deps, session } = createDeps();+ session.agentKind = agentKind;+ const { blocks, persistedContent } = appMessageInput([{ type: 'text', text: '/compact' }]);+ const sourcePlugin = { pluginId: 'mcp-app:example', name: 'example' };+ await createMakerSendTransaction(deps).sendToAgentAccepted(+ 'session-1', { type: 'user', content: blocks }, undefined, {+ [AUTO_REVIEW_DELEGATED_CONTINUATION]: true,+ persistUserMessage: { clientId: 'app-input', content: persistedContent, sourcePlugin },+ },+ );+ const sent = vi.mocked(session.send).mock.calls[0][0];+ const wire = JSON.stringify(typeof sent === 'string' ? sent : sent.content);+ expect(wire).toContain('[消息来源]');+ expect(wire).toContain('mcp_server_id: example');+ expect(wire).toContain('\\\\/compact');+ expect(deps.createDbMessage).toHaveBeenCalledWith(+ 'session-1', expect.objectContaining({ content: '/compact', agentMeta: expect.objectContaining({ sourcePlugin }) }),+ undefined,+ );+ },+ );++ it('rejects revocation during metadata loading before persisting an App turn', async () => {+ let visible = true;+ const dispatch = vi.fn();+ const guard = vi.fn(async () => { if (!visible) throw new Error('MCP_APP_CARD_UNAVAILABLE'); });+ const { deps } = createDeps({+ prepareProductTurn: () => dispatch,+ getSessionMeta: async () => { visible = false; return { title: 'Task' }; },+ });+ await expect(createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'App text', undefined, {+ [AUTO_REVIEW_DELEGATED_CONTINUATION]: true,+ [MCP_APP_MESSAGE_GUARD]: guard,+ persistUserMessage: { clientId: 'app-input', content: 'App text' },+ })).rejects.toThrow('MCP_APP_CARD_UNAVAILABLE');+ expect(deps.createDbMessage).not.toHaveBeenCalled();+ expect(dispatch).not.toHaveBeenCalled();+ });++ it('rechecks card authorization after accepted persistence and blocks vendor dispatch', async () => {+ let visible = true;+ const dispatch = vi.fn();+ const guard = vi.fn(async () => { if (!visible) throw new Error('MCP_APP_CARD_UNAVAILABLE'); });+ const { deps, session } = createDeps({+ prepareProductTurn: () => dispatch,+ createDbMessage: vi.fn(async () => { visible = false; }),+ });+ await expect(createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'App text', undefined, {+ [AUTO_REVIEW_DELEGATED_CONTINUATION]: true,+ [MCP_APP_MESSAGE_GUARD]: guard,+ persistUserMessage: { clientId: 'app-input', content: 'App text' },+ })).rejects.toThrow('MCP_APP_CARD_UNAVAILABLE');+ expect(guard).toHaveBeenCalledTimes(2);+ expect(session.send).toHaveBeenCalledOnce();+ expect(dispatch).not.toHaveBeenCalled();+ });++ it('awaits the final card guard and preserves the owner intent without leaking the callback', async () => {+ const dispatch = vi.fn();+ let finish!: () => void;+ const guard = vi.fn()+ .mockResolvedValueOnce(undefined)+ .mockImplementationOnce(() => new Promise<void>((resolve) => { finish = resolve; }));+ let intent: unknown;+ const session = createSession({ send: vi.fn(async (_message, opts) => {+ await opts?.beforeProviderStart?.();+ await opts?.onAccepted?.();+ intent = await opts?.resolveAutoReviewUserIntent?.();+ opts?.onDispatching?.();+ return { accepted: true } satisfies SessionSendResult;+ }) });+ const { deps } = createDeps({ getSession: () => session, prepareProductTurn: () => dispatch });+ const pending = createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'App text', undefined, {+ [AUTO_REVIEW_DELEGATED_CONTINUATION]: true,+ [MCP_APP_MESSAGE_GUARD]: guard,+ persistUserMessage: { clientId: 'app-input', content: 'App text' },+ });+ await vi.waitFor(() => expect(finish).toBeDefined());+ expect(dispatch).not.toHaveBeenCalled();+ finish();+ await expect(pending).resolves.toMatchObject({ accepted: true });+ expect(dispatch).toHaveBeenCalledOnce();+ expect(intent).toEqual(restoreAutoReviewUserIntent([]));+ expect(Object.getOwnPropertySymbols(vi.mocked(session.send).mock.calls[0][1]!))+ .not.toContain(MCP_APP_MESSAGE_GUARD);+ expect(JSON.stringify(vi.mocked(session.send).mock.calls[0][0])).not.toContain('MCP_APP_MESSAGE_GUARD');+ });+});+describe('maker SEND transaction', () => {it.each([false, true])('captures product state before preparation and resumes only at dispatch (persist=%s)',diff --git a/apps/desktop/src/main/maker-ipc/__tests__/mcpHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/mcpHandlers.test.tsindex e79a46dc89..544cd27de2 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/mcpHandlers.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/mcpHandlers.test.ts@@ -123,9 +123,8 @@ describe('mcp:custom:* CRUD handlers', () => {const result = await harness.invoke(MAKER_INVOKE.MCP_CUSTOM_LIST, { agentKind });expect(deps.listMcpServers).toHaveBeenCalledWith({ agentKind });expect(result).toEqual({ agentKind, servers: rawList.map((server) => ({- ...server, available: ['mytools', 'local-http'].includes(server.id)- || (server.id === 'events' && agentKind === 'claude-code')- || (server.id === 'public-http' && agentKind !== 'pi'),+ // Registered custom MCPs now use the Main-owned Apps facade for every harness.+ ...server, available: ['mytools', 'local-http', 'events', 'public-http'].includes(server.id),})) });},);@@ -174,7 +173,7 @@ describe('mcp:custom:* CRUD handlers', () => {agentKind: 'claude-code', botSessionId: 'canonical',});expect(deps.listMcpServers).toHaveBeenCalledWith({ agentKind, remoteHostId: 'ssh-host' });- expect(result).toEqual({ agentKind, servers: [expect.objectContaining({ id: 'mytools', available: agentKind !== 'codex' })] });+ expect(result).toEqual({ agentKind, servers: [expect.objectContaining({ id: 'mytools', available: true })] });});it.each([null, {}, { agentKind: 'unknown' },diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskAuthorshipWiring.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskAuthorshipWiring.test.tsindex 239f310641..bbecba231f 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskAuthorshipWiring.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskAuthorshipWiring.test.ts@@ -5,6 +5,7 @@ import { expect, it, vi } from 'vitest';import { appendAutoReviewUserIntent, AUTO_REVIEW_DELEGATED_CONTINUATION, AUTO_REVIEW_SOURCE_CONTENT, AUTO_REVIEW_USER_INTENT, MAIN_OWNED_SEND_CONTEXT, type SendOptions } from '@cindy/maker-core';import { HOST_ONLY_AGENT_PREFIX, buildMakerUserMessage, sanitizeQueuedMessageForPersistence } from '../../../shared/agentInputQueue.js';import { redactInputProjectionForSharedGuest } from '../../device-link/sharedTaskMessageOrigin.js';+import { MCP_APP_MESSAGE_GUARD } from '../../mcp-apps/message.js';const source = readFileSync(resolve(__dirname, '..', 'register.ts'), 'utf8');const compile = (code: string) => ts.transpileModule(code, {@@ -16,7 +17,7 @@ it.each(['Do not publish.', '', undefined])('keeps live authority through the fiexpect(start).toBeGreaterThan(0);const end = source.indexOf('\n });', start) + '\n });'.length;const deliver = new Function('sess', 'steerPayload', 'so', 'meta', 'restoredSteerIntent',- 'MAIN_OWNED_SEND_CONTEXT', 'AUTO_REVIEW_SOURCE_CONTENT', 'AUTO_REVIEW_USER_INTENT', 'AUTO_REVIEW_DELEGATED_CONTINUATION',+ 'MAIN_OWNED_SEND_CONTEXT', 'AUTO_REVIEW_SOURCE_CONTENT', 'AUTO_REVIEW_USER_INTENT', 'AUTO_REVIEW_DELEGATED_CONTINUATION', 'MCP_APP_MESSAGE_GUARD', 'appContext',compile(`return (async () => { ${source.slice(start, end)} })();`));const invoke = async (delegated: boolean) => {let result;@@ -25,7 +26,7 @@ it.each(['Do not publish.', '', undefined])('keeps live authority through the fi});await deliver({ steer }, 'Publish now', { [AUTO_REVIEW_SOURCE_CONTENT]: '',...(delegated ? { [AUTO_REVIEW_DELEGATED_CONTINUATION]: true } : {}) }, {}, 'Old persisted permission',- MAIN_OWNED_SEND_CONTEXT, AUTO_REVIEW_SOURCE_CONTENT, AUTO_REVIEW_USER_INTENT, AUTO_REVIEW_DELEGATED_CONTINUATION);+ MAIN_OWNED_SEND_CONTEXT, AUTO_REVIEW_SOURCE_CONTENT, AUTO_REVIEW_USER_INTENT, AUTO_REVIEW_DELEGATED_CONTINUATION, MCP_APP_MESSAGE_GUARD);expect(steer).toHaveBeenCalledOnce();return result;};@@ -33,6 +34,51 @@ it.each(['Do not publish.', '', undefined])('keeps live authority through the fiexpect(await invoke(false)).toEqual('Old persisted permission');});+it.each(['context', 'message', 'none'] as const)(+ 'revalidates App steer authority after async preparation (%s revocation)',+ async (revocation) => {+ const start = source.indexOf('await sess.steer(steerPayload as never, {');+ const marker = ' appContext?.consume();';+ const end = source.indexOf(marker, start) + marker.length;+ expect(start).toBeGreaterThan(0);+ expect(end).toBeGreaterThan(start);+ const deliver = new Function('sess', 'steerPayload', 'so', 'meta', 'restoredSteerIntent',+ 'MAIN_OWNED_SEND_CONTEXT', 'AUTO_REVIEW_SOURCE_CONTENT', 'AUTO_REVIEW_USER_INTENT', 'AUTO_REVIEW_DELEGATED_CONTINUATION', 'MCP_APP_MESSAGE_GUARD', 'appContext',+ compile(`return (async () => { ${source.slice(start, end)} })();`));+ let prepared = false;+ const provider = vi.fn();+ const messageGuard = vi.fn(async () => {+ if (prepared && revocation === 'message') throw new Error('MCP_APP_CARD_UNAVAILABLE');+ });+ const context = {+ text: 'PRIVATE_APP_DRAFT',+ assertCurrent: vi.fn(async () => {+ if (prepared && revocation === 'context') throw new Error('MCP_APP_CARD_UNAVAILABLE');+ }),+ consume: vi.fn(),+ };+ const steer = vi.fn(async (_content: unknown, opts: { beforeProviderStart?: () => Promise<void> }) => {+ await Promise.resolve();+ prepared = true;+ await opts.beforeProviderStart?.();+ provider();+ });+ const pending = deliver({ steer }, 'Continue', { [MCP_APP_MESSAGE_GUARD]: messageGuard }, {}, '',+ MAIN_OWNED_SEND_CONTEXT, AUTO_REVIEW_SOURCE_CONTENT, AUTO_REVIEW_USER_INTENT, AUTO_REVIEW_DELEGATED_CONTINUATION, MCP_APP_MESSAGE_GUARD, context);+ if (revocation === 'none') {+ await pending;+ expect(provider).toHaveBeenCalledOnce();+ expect(context.consume).toHaveBeenCalledOnce();+ expect(context.assertCurrent).toHaveBeenCalledOnce();+ } else {+ await expect(pending).rejects.toThrow('MCP_APP_CARD_UNAVAILABLE');+ expect(provider).not.toHaveBeenCalled();+ expect(context.consume).not.toHaveBeenCalled();+ }+ expect(messageGuard).toHaveBeenCalledOnce();+ },+);+it('restores human authorization for both live and cold internal delegated sends', () => {for(const target of ['live','session']) {const start=source.lastIndexOf(`sendUserMessageWithAwaitedGitBaseline(${target}, message, clientId, {`);diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.tsindex ef58c8a226..e959502994 100644--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts@@ -3,6 +3,7 @@ import { getDeviceLinkInvokeContext } from '../device-link/invoke-context.js';import { assertSharedTaskQueueMutation } from './sharedTaskInput.js';import { isBotGroupClientId } from '../../shared/botGroupChat.js';import { SchedulerQueuedPreparationError } from './schedulerQueuedPreparation.js';+import { MCP_APP_MESSAGE_GUARD, isUnrestorableMcpAppMessage, queuedAppMessageGuard, type McpAppMessageGuard } from '../mcp-apps/message.js';/*** AgentInputCoordinator — main 侧排队输入事务协调器。*@@ -205,6 +206,8 @@ function hasRetryableQueuedContent(item: AgentInputQueuedMessage): boolean {}export interface AgentInputSendOpts {+ /** Main-only App grant, checked by the send/steer transaction at dispatch. */+ readonly [MCP_APP_MESSAGE_GUARD]?: McpAppMessageGuard;readonly [AUTO_REVIEW_DELEGATED_CONTINUATION]?: true;/** Main-owned identity of the zero-output user turn being replaced. */retryUserClientId?: string;@@ -1577,7 +1580,17 @@ export class AgentInputCoordinator {// have lost the originating execution's callbacks; a new claim on this// lane must never authorize their prompts (including restored plan inputs).const staleGroupItems = restorable.filter((item) => isBotGroupClientId(item.clientId));- const restored = restorable.filter((item) => item.origin?.kind !== 'scheduler' && !isBotGroupClientId(item.clientId));+ // App grants are Main-only Symbols, lost across JSON persistence. Drop the+ // stale row instead of putting a permanent authorization error at the queue+ // head. Its normal discard settlement runs exactly once, even if another+ // non-restorable origin also applies.+ const staleAppItems = restorable.filter((item) =>+ item.origin?.kind !== 'scheduler' && !isBotGroupClientId(item.clientId) && isUnrestorableMcpAppMessage(item));+ const restored = restorable.filter((item) =>+ item.origin?.kind !== 'scheduler' && !isBotGroupClientId(item.clientId) && !isUnrestorableMcpAppMessage(item));+ for (const item of staleAppItems) {+ this.deps.onDiscardedQueuedMessage?.(sessionId, item);+ }for (const item of staleGroupItems) {if (item.origin?.kind !== 'scheduler') this.deps.onDiscardedQueuedMessage?.(sessionId, item);}@@ -2537,7 +2550,9 @@ export class AgentInputCoordinator {item.persistedContent,referenceContexts,);+ const appMessageGuard = queuedAppMessageGuard(item);await this.deps.steerToAgent(sessionId, buildMakerUserMessage(item, referenceContexts), {+ ...(appMessageGuard ? { [MCP_APP_MESSAGE_GUARD]: appMessageGuard } : {}),...(item.sharedTaskAuthor ? { sharedTaskAuthor: item.sharedTaskAuthor } : {}),[AUTO_REVIEW_SOURCE_CONTENT]: queuedAutoReviewText(item),...(item.autoReviewUserText && typeof item.autoReviewUserText === 'object' && item.autoReviewUserText.kind === 'delegated-continuation'@@ -4399,6 +4414,7 @@ export class AgentInputCoordinator {/** Renderer projection may carry routing hints, but never quoted history bodies. */private toProjectedItem(item: AgentInputQueuedMessage): AgentInputQueuedMessage {const projected = { ...item };+ Reflect.deleteProperty(projected, MCP_APP_MESSAGE_GUARD);delete projected[HOST_ONLY_AGENT_PREFIX];delete projected.hostAcceptedAtMs;delete projected.autoReviewUserText;@@ -4895,6 +4911,7 @@ export class AgentInputCoordinator {state.activeTurn = active;this.emit(sessionId);+ let appMessageGuardRejected = false;try {// 意识拦截钩(订阅槽①):落库/派发之前问一遍——block 即丢弃本项// (不入库不起 turn),通知宿主降级气泡,继续放行后续排队消息;@@ -4962,7 +4979,16 @@ export class AgentInputCoordinator {// may synchronously emit the new turn's started marker before it returns;// post-dispatch acknowledgements must remain older than that marker.const preVendorDispatchAt = Math.max(0, Date.now() - 1);+ const appMessageGuard = queuedAppMessageGuard(head);const result = await this.deps.sendToAgent(sessionId, makerUserMessage, head.createOpts, {+ ...(appMessageGuard ? { [MCP_APP_MESSAGE_GUARD]: async () => {+ try {+ await appMessageGuard();+ } catch (error) {+ appMessageGuardRejected = true;+ throw error;+ }+ } } : {}),...(head.supersedesUserClientId ? { retryUserClientId: head.supersedesUserClientId } : {}),[AUTO_REVIEW_SOURCE_CONTENT]: queuedAutoReviewText(head),...(head.autoReviewUserText && typeof head.autoReviewUserText === 'object' && head.autoReviewUserText.kind === 'delegated-continuation'@@ -5056,6 +5082,10 @@ export class AgentInputCoordinator {if (this.discardOnStaleActiveTurn(sessionId, active, isSendDispatched(result))) return;active.persisting = false;if (!isSendDispatched(result)) {+ if (appMessageGuardRejected) {+ this.discardRevokedAppInput(sessionId, active, head);+ return;+ }const rewound = await this.rewindSchedulerPreparationFailure(sessionId, active, head, result);if (this.discardOnStaleActiveTurn(sessionId, active)) return;this.handleSendNotDispatched(sessionId, active, head, result, rewound);@@ -5109,6 +5139,10 @@ export class AgentInputCoordinator {this.emit(sessionId);} catch (err) {if (this.discardOnStaleActiveTurn(sessionId, active)) return;+ if (appMessageGuardRejected) {+ this.discardRevokedAppInput(sessionId, active, head);+ return;+ }// 派发 / 落库失败(含 SESSION_RUNNING 让位):暂存的 error 候选到此作废,补落它的行。// 放在分支之前 —— 三条出口都不会再走到接管决策。this.discardDeferredResumableCandidate(sessionId, active);@@ -5198,6 +5232,27 @@ export class AgentInputCoordinator {}}+ /** A failed live View grant cannot become valid again by retrying this item. */+ private discardRevokedAppInput(+ sessionId: string,+ active: ActiveTurn,+ item: AgentInputQueuedMessage,+ ): void {+ const state = this.getState(sessionId);+ this.discardDeferredResumableCandidate(sessionId, active);+ state.activeTurn = null;+ this.clearCredentialSwitchWait(state);+ this.notifyRejectedUserTurn(sessionId, item);+ if (active.persisted) {+ this.notifyUndispatchedUserTurn(sessionId, item, 'failed');+ } else {+ this.deps.onDiscardedQueuedMessage?.(sessionId, item);+ }+ this.emit(sessionId);+ this.scheduleDrain(sessionId, 'mcp-app-grant-revoked');+ this.deps.onQueueEmptied?.(sessionId);+ }+/** Only proven preparation rejection can erase a scheduled continuation row.* The coordinator owns its clientId even when dispatch beats enqueue's return.* Unknown vendor outcomes and interactive messages keep their existing history.diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.tsindex cd04443b71..5e125e98f9 100644--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts@@ -56,6 +56,8 @@ import type { MakerSessionCreateOpts } from './sessionRequest.js';import { channelTurnSourceFor, withChannelTurnSource } from './channelTurnSignal.js';import type { CindyLearnInvocationGrant } from '../learn-host/invocationGrant.js';import { AUTO_REVIEW_DELEGATED_CONTINUATION, currentAutoReviewResourceIntent, readAutoReviewUserText, restoreAutoReviewUserIntent, type AutoReviewHistoryMessage } from './autoReviewUserIntent.js';+import { mcpAppModelContext } from '../mcp-apps/runtime.js';+import { MCP_APP_MESSAGE_GUARD, type McpAppMessageGuard } from '../mcp-apps/message.js';type CreateOpts = MakerSessionCreateOpts;@@ -246,6 +248,8 @@ export function revokeTrustedDesktopQueuedOrigin(item: AgentInputQueuedMessage):}type MakerSendOptions = {+ /** Main-only live card guard, never serialized to queue history or provider options. */+ readonly [MCP_APP_MESSAGE_GUARD]?: McpAppMessageGuard;readonly [AUTO_REVIEW_DELEGATED_CONTINUATION]?: true;retryUserClientId?: string;toolsDisabled?: boolean;@@ -1392,9 +1396,21 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Makeconst withCindyMakeNote = plannedNotes['cindy-make']? prependNoteToWireUserMessage(withMobileNote as HandoffWireMessage, plannedNotes['cindy-make']): withMobileNote;- const outgoing = plannedNotes['ui-language']+ let outgoing = plannedNotes['ui-language']? prependNoteToWireUserMessage(withCindyMakeNote as HandoffWireMessage, plannedNotes['ui-language']): withCindyMakeNote;+ const appContext = shouldPrependMobileClientPromptNote(normalized, sess.agentKind)+ ? await mcpAppModelContext(sessionId)+ : undefined;+ if (appContext?.text) {+ outgoing = prependNoteToWireUserMessage(outgoing as HandoffWireMessage, appContext.text);+ }+ const assertAppCurrent = so[MCP_APP_MESSAGE_GUARD] || appContext?.text+ ? async () => {+ await so[MCP_APP_MESSAGE_GUARD]?.();+ await appContext?.assertCurrent();+ }+ : undefined;const meta = await deps.getSessionMeta(sessionId).catch(() => null);let persistUserMessage = readPersistUserMessageOption(so);const trustedDesktopQueueReceipt = readTrustedDesktopQueueReceipt(persistUserMessage);@@ -1590,7 +1606,22 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): MakepersistUserMessage?.botTaskCoordination !== undefined,), () => sess.send(outgoing as never, {...(retryTranscriptUserEntryId ? { retryTranscriptUserEntryId } : {}),- ...(resolveScheduledIntent ? { resolveAutoReviewUserIntent: resolveScheduledIntent } : {}),+ ...(assertAppCurrent+ ? {+ beforeProviderStart: assertAppCurrent,+ resolveAutoReviewUserIntent: async () => {+ const intent = resolveScheduledIntent+ ? await resolveScheduledIntent()+ : restoredAutoReviewIntent ?? (so[MCP_APP_MESSAGE_GUARD]+ ? restoreAutoReviewUserIntent([])+ : undefined);+ // Session awaits this existing authorization hook after all+ // preparation (including vision), immediately before dispatch.+ await assertAppCurrent();+ return intent;+ },+ }+ : resolveScheduledIntent ? { resolveAutoReviewUserIntent: resolveScheduledIntent } : {}),[AUTO_REVIEW_SOURCE_CONTENT]: autoReviewSourceContent,...(so[AUTO_REVIEW_DELEGATED_CONTINUATION] ? { [AUTO_REVIEW_DELEGATED_CONTINUATION]: true as const } : {}),...(so[INHERITED_CAPABILITY_SELECTION] !== undefined@@ -1759,6 +1790,7 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make}));sendAccepted = sendResult.accepted;if (sendAccepted) {+ appContext?.consume();cleanupAfterAcceptance?.();await cleanupAcceptedNonPersistedMaterialization();} else {diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 2b0470424b..5ecbb7d2c7 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -21,6 +21,10 @@ import { createHash as pluginTaskConfigHash } from 'node:crypto';import { finishCompanionEnvironmentRemoval } from '../bot-import/runtime.js';import { setImportProbeConfirmation } from '../bot-import/probeAuthorization.js';import { requestHostInteraction } from './interactionRouter.js';+import { registerMcpAppsIpc } from '../mcp-apps/ipc.js';+import { createAppMessageSender } from '../mcp-apps/messageSender.js';+import { MCP_APP_MESSAGE_GUARD, type McpAppMessageGuard } from '../mcp-apps/message.js';+import { mcpAppModelContext } from '../mcp-apps/runtime.js';import { prepareCompanionImportDeletion } from '../bot-import/host.js';import { createBotMessageTransport } from './botMessageTransport.js';import { MANAGED_LLAMACPP_PROVIDER_ID, llamaCppModelPreset, llamaCppMaxContextSize } from '../../shared/llamaCpp.js';@@ -16711,6 +16715,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)readonly [AUTO_REVIEW_SOURCE_CONTENT]?: string;readonly [AUTO_REVIEW_DELEGATED_CONTINUATION]?: true;readonly [AUTO_REVIEW_USER_INTENT]?: string;+ readonly [MCP_APP_MESSAGE_GUARD]?: McpAppMessageGuard;};const readCurrentSteerSession = () => {const current = maker.getSession(sessionId);@@ -16815,9 +16820,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const withSteerNote = steerPlannedNotes['client-environment']? prependNoteToWireUserMessage(withSteerSourceNote as HandoffWireMessage, steerPlannedNotes['client-environment']): withSteerSourceNote;- const steerPayload = steerPlannedNotes['ui-language']+ let steerPayload = steerPlannedNotes['ui-language']? prependNoteToWireUserMessage(withSteerNote as HandoffWireMessage, steerPlannedNotes['ui-language']): withSteerNote;+ const appContext = shouldPrependMobileClientPromptNote(normalized, sess.agentKind)+ ? await mcpAppModelContext(sessionId)+ : undefined;+ if (appContext?.text) {+ steerPayload = prependNoteToWireUserMessage(steerPayload as HandoffWireMessage, appContext.text);+ }try {const remote = isDeviceLinkInvoke();assertRemoteInputClearNotInFlight(sessionId, remote);@@ -16826,6 +16837,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)assertCurrentInputClearBoundary(sessionId, precondition.expected);}assertCurrentInputGeneration(sessionId, readExpectedInputGeneration(sendOpts));+ if (so[MCP_APP_MESSAGE_GUARD]) await so[MCP_APP_MESSAGE_GUARD]!();sess = readCurrentSteerSession();// 同轮插话也属于新输入。必须在 vendor await 前通知,旧轮可能先于 steer ack 结束。// 共用入口同时覆盖 INPUT_STEER、队列提升和旧 STEER IPC。@@ -16833,6 +16845,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// A channel route vouches only for its triggering sender; steered input ends that.noteInteractionRouteSteer(sess);await sess.steer(steerPayload as never, {+ ...(so[MCP_APP_MESSAGE_GUARD] || appContext?.text ? {+ beforeProviderStart: async () => {+ await so[MCP_APP_MESSAGE_GUARD]?.();+ await appContext?.assertCurrent();+ },+ } : {}),logTitle: meta?.title,messageUuid: so.messageUuid,userName: so.userName,@@ -16842,6 +16860,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)[AUTO_REVIEW_DELEGATED_CONTINUATION]: so[AUTO_REVIEW_DELEGATED_CONTINUATION],[AUTO_REVIEW_USER_INTENT]: restoredSteerIntent,});+ appContext?.consume();steerNotePlan?.commit();log.info('steer: delivered', { sessionId, agentKind: sess.agentKind });} catch (err) {@@ -16899,6 +16918,25 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)sendToAgentAccepted(sessionId, message, createOpts, attachTrustedDesktopSendContext(message, sendOpts)),(sessionId) => inputCoordinator.getClearBoundaryMs(sessionId),);+ registerMcpAppsIpc(createAppMessageSender({+ owner: getCurrentDbClientSnapshot,+ readClearBoundary: async (sessionId) => normalizeAgentInputClearBoundaryMs(+ (await getSessionRowSnapshotStrict(sessionId))?.clearedAt,+ ),+ restoreQueue: (sessionId) => inputCoordinator.ensureQueueRestored(sessionId),+ clearBoundary: (sessionId) => inputCoordinator.getClearBoundaryMs(sessionId),+ shouldQueue: (sessionId) => inputCoordinator.shouldQueueNewTurn(sessionId),+ getSessionMeta: (sessionId) => maker.getSessionMeta(sessionId),+ createClientId: createId,+ buildQueueItem: buildSessionControlInputItem,+ enqueue: (sessionId, item) => { inputCoordinator.enqueue(sessionId, item); },+ sendToAgentAccepted,+ }), async (sessionId, request, signal) => {+ const session = maker.getSession(sessionId) ?? { id: sessionId, setInteractionListener: () => {} };+ // Historical Apps use the same permission cards without starting an Agent turn.+ installDesktopInteractionListener(session);+ return requestHostInteraction(session, request, signal);+ });registerMakerSessionSendHandler({handle(channel, handler) {diff --git a/apps/desktop/src/main/mcp-apps/__tests__/conformance.test.ts b/apps/desktop/src/main/mcp-apps/__tests__/conformance.test.tsnew file mode 100644index 0000000000..0d802c4094--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/__tests__/conformance.test.ts@@ -0,0 +1,629 @@+import { afterEach, afterAll, beforeAll, describe, expect, it, vi } from 'vitest';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';+import {+ CallToolResultSchema,+ type CallToolResult,+ type JSONRPCMessage,+ type Tool,+} from '@modelcontextprotocol/sdk/types.js';+import { startMockAppServer } from '../../../../scripts/mcp-apps-mock.mjs';+import {+ createRawAppServer,+ RAW_RESOURCE,+ RAW_APP_HTML,+} from '../../../../scripts/mcp-apps-raw-fixture.mjs';+import { AppConnection } from '../connection.js';+import { handleMcpAppOperation } from '../operations.js';+import { McpAppsHost, appServerRevision } from '../host.js';+import { createAppServerProxy } from '../serverProxy.js';+import { registerAppServer, setMcpAppsHost, clearAppServerConfigs } from '../runtime.js';+import type { McpAppRecord, McpAppDocument } from '../../../shared/mcpApps.js';++type Rpc = JSONRPCMessage;+type Init = {+ protocolVersion: string;+ hostInfo: { name: string };+ hostCapabilities: Record<string, unknown>;+ hostContext: Record<string, unknown>;+};+let endpoint: Awaited<ReturnType<typeof startMockAppServer>>;+let textEndpoint: typeof endpoint;+const cleanup: Array<() => Promise<unknown>> = [];+beforeAll(async () => {+ endpoint = await startMockAppServer({ createServer: createRawAppServer });+ textEndpoint = await startMockAppServer({+ createServer: () => createRawAppServer({ encoding: 'text', metadata: 'read', legacyUri: true }),+ });+});+afterAll(async () => {+ await endpoint.close();+ await textEndpoint.close();+});+afterEach(async () => {+ for (const close of cleanup.splice(0).reverse()) await close();+ clearAppServerConfigs();+});++/** Independent JSON-RPC peer. No View SDK and no access to Host internals. */+class RawPeer {+ readonly notifications: Rpc[] = [];+ readonly hostRequests: Rpc[] = [];+ readonly links: string[] = [];+ linkSuccess = true;+ private nextId = 1;+ private active = true;+ private readonly pending = new Map<+ number,+ {+ resolve(value: unknown): void;+ reject(error: Error): void;+ timer: ReturnType<typeof setTimeout>;+ }+ >();+ constructor(+ private readonly host: McpAppsHost,+ readonly viewId: string,+ ) {+ void this.poll();+ }+ async notify(method: string, params: Record<string, unknown> = {}) {+ await this.host.dispatch('renderer:conformance', 'task', this.viewId, {+ jsonrpc: '2.0',+ method,+ params,+ });+ }+ request<T = Record<string, unknown>>(+ method: string,+ params: Record<string, unknown> = {},+ ): Promise<T> {+ const id = this.nextId++;+ const result = new Promise<unknown>((resolve, reject) => {+ const timer = setTimeout(() => {+ this.pending.delete(id);+ reject(new Error('Fixture RPC timed out: ' + method));+ }, 3_000);+ this.pending.set(id, { resolve, reject, timer });+ });+ void this.host+ .dispatch('renderer:conformance', 'task', this.viewId, { jsonrpc: '2.0', id, method, params })+ .catch((error) => {+ const item = this.pending.get(id);+ if (item) {+ clearTimeout(item.timer);+ this.pending.delete(id);+ item.reject(error);+ }+ });+ return result as Promise<T>;+ }+ get lastRequestId() {+ return this.nextId - 1;+ }+ async cancel(id: number) {+ const item = this.pending.get(id);+ if (item) {+ clearTimeout(item.timer);+ this.pending.delete(id);+ item.reject(new Error('Request cancelled'));+ }+ await this.notify('notifications/cancelled', { requestId: id, reason: 'User cancelled' });+ }+ private async poll() {+ let after = 0;+ while (this.active) {+ let events;+ try {+ events = await this.host.poll('renderer:conformance', 'task', this.viewId, after);+ } catch {+ return;+ }+ for (const event of events) {+ after = event.seq;+ if (event.openLink) {+ this.links.push(event.openLink.url);+ this.host.linkResult(+ 'renderer:conformance',+ 'task',+ this.viewId,+ event.openLink.id,+ this.linkSuccess,+ );+ continue;+ }+ const message = event.message;+ if ('method' in message) {+ if ('id' in message) {+ this.hostRequests.push(message);+ await this.host.dispatch('renderer:conformance', 'task', this.viewId, {+ jsonrpc: '2.0',+ id: message.id,+ result: {},+ });+ } else this.notifications.push(message);+ } else if (typeof message.id === 'number') {+ const item = this.pending.get(message.id);+ if (item) {+ clearTimeout(item.timer);+ this.pending.delete(message.id);+ if ('error' in message)+ item.reject(+ Object.assign(new Error(message.error.message), { code: message.error.code }),+ );+ else item.resolve(message.result);+ }+ }+ }+ }+ }+ stop() {+ this.active = false;+ this.pending.forEach((item) => clearTimeout(item.timer));+ this.pending.clear();+ }+}++async function fixture(+ transport: 'http' | 'sse' = 'http',+ initialize = true,+ appModes = ['inline', 'fullscreen'],+ source = endpoint,+) {+ const config = {+ id: 'independent-metrics',+ url: transport === 'http' ? source.url : source.sseUrl,+ transport,+ };+ const connection = new AppConnection(config);+ const client = await connection.getClient();+ const tool = (await connection.tools()).find((tool) => tool.name === 'open_metrics')!;+ const args = { threshold: 75 };+ const result = (await client.callTool(+ { name: 'open_metrics', arguments: args },+ CallToolResultSchema,+ )) as CallToolResult;+ const cards = new Map<string, McpAppRecord>();+ const record: McpAppRecord = {+ version: 1,+ serverId: config.id,+ serverRevision: appServerRevision(config),+ resourceUri: RAW_RESOURCE,+ tool,+ arguments: args,+ result,+ };+ cards.set('card', record);+ const owner = {};+ const authorize = vi.fn(async () => {}),+ send = vi.fn(async () => {}),+ audit = vi.fn();+ const host = new McpAppsHost({+ owner: () => owner,+ config: () => config,+ readCard: async (_session, id) => {+ const value = cards.get(id);+ if (!value) throw new Error('MCP_APP_CARD_UNAVAILABLE');+ return value;+ },+ writeCard: async (_session, id, value) => {+ cards.set(id, value);+ },+ authorizeTool: authorize,+ sendMessage: send,+ audit,+ });+ record.connectionId = host.registerConnection(connection);+ const document = (await handleMcpAppOperation(host, 'renderer:conformance', 'task', {+ op: 'open',+ clientId: 'card',+ context: {+ platform: 'desktop',+ theme: 'light',+ locale: 'zh-CN',+ timeZone: 'Asia/Shanghai',+ styles: { variables: { '--color-text-primary': 'rgb(0,0,0)' } },+ containerDimensions: { width: 640, maxHeight: 1_200 },+ safeAreaInsets: { top: 10, right: 0, bottom: 20, left: 0 },+ },+ })) as McpAppDocument;+ const peer = new RawPeer(host, document.viewId);+ cleanup.push(async () => {+ await host.reset();+ peer.stop();+ await connection.close();+ });+ let init: Init | undefined;+ if (initialize) {+ init = await peer.request<Init>('ui/initialize', {+ protocolVersion: '2026-01-26',+ appInfo: { name: 'Independent raw peer', version: '1' },+ appCapabilities: { availableDisplayModes: appModes },+ });+ await peer.notify('ui/notifications/initialized');+ await vi.waitFor(() =>+ expect(+ peer.notifications.some(+ (message) => 'method' in message && message.method === 'ui/notifications/tool-result',+ ),+ ).toBe(true),+ );+ }+ const state = async () => {+ const data = await client.readResource({ uri: 'metrics://independent/state' });+ return JSON.parse('text' in data.contents[0] ? data.contents[0].text : '') as {+ cancelled: number;+ slowStarted: number;+ refreshes: number;+ };+ };+ return {+ host,+ peer,+ document,+ record,+ result,+ init,+ client,+ connection,+ config,+ cards,+ authorize,+ send,+ audit,+ state,+ };+}++describe('2026-01-26 MCP Apps conformance against an independent local server', () => {+ it.each(['http', 'sse'] as const)(+ '%s: also loads legacy resourceUri with text HTML and read-level metadata',+ async (transport) => {+ const f = await fixture(transport, true, ['inline', 'fullscreen'], textEndpoint);+ expect(f.record.tool._meta).toEqual({ 'ui/resourceUri': RAW_RESOURCE });+ expect(f.document.html).toBe(RAW_APP_HTML);+ expect(f.document.prefersBorder).toBe(false);+ expect(f.init!.protocolVersion).toBe('2026-01-26');+ },+ );+ it.each(['http', 'sse'] as const)(+ '%s: negotiates the stable protocol with an SDK-free App and blob/list resource metadata',+ async (transport) => {+ const f = await fixture(transport);+ expect(f.document.html).toBe(RAW_APP_HTML);+ expect(f.document.prefersBorder).toBe(false);+ expect(f.init).toMatchObject({+ protocolVersion: '2026-01-26',+ hostInfo: { name: 'Cindy' },+ hostContext: {+ theme: 'light',+ locale: 'zh-CN',+ timeZone: 'Asia/Shanghai',+ toolInfo: { tool: { name: 'open_metrics' } },+ containerDimensions: { width: 640, maxHeight: 1_200 },+ safeAreaInsets: { top: 10, bottom: 20 },+ },+ });+ expect(f.init!.hostCapabilities).toMatchObject({+ serverTools: { listChanged: true },+ serverResources: { listChanged: true },+ sandbox: { permissions: {}, csp: { frameDomains: [] } },+ });+ expect(f.result._meta?.clientUi).toEqual({ mimeTypes: ['text/html;profile=mcp-app'] });+ const input = f.peer.notifications.find(+ (message) => 'method' in message && message.method === 'ui/notifications/tool-input',+ );+ const output = f.peer.notifications.find(+ (message) => 'method' in message && message.method === 'ui/notifications/tool-result',+ );+ expect(input).toMatchObject({ params: { arguments: { threshold: 75 } } });+ expect(output).toMatchObject({ params: f.result });+ expect(f.peer.notifications.indexOf(input!)).toBeLessThan(+ f.peer.notifications.indexOf(output!),+ );+ expect(f.result.content.map((item) => item.type)).toEqual([+ 'text',+ 'image',+ 'audio',+ 'resource',+ 'resource',+ 'resource_link',+ ]);+ },+ );+ it('rejects pre-initialization calls and waits for initialized before sending lifecycle notifications', async () => {+ const f = await fixture('http', false);+ await expect(+ f.peer.request('tools/call', { name: 'refresh_metrics', arguments: {} }),+ ).rejects.toThrow('MCP_APP_NOT_INITIALIZED');+ const result = await f.peer.request<Init>('ui/initialize', {+ protocolVersion: '2026-01-26',+ appInfo: { name: 'Raw', version: '1' },+ appCapabilities: {},+ });+ expect(result.protocolVersion).toBe('2026-01-26');+ expect(f.peer.notifications).toEqual([]);+ await f.peer.notify('ui/notifications/initialized');+ await vi.waitFor(() =>+ expect(f.peer.notifications).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ method: 'ui/notifications/tool-input' }),+ expect.objectContaining({ method: 'ui/notifications/tool-result' }),+ ]),+ ),+ );+ await expect(+ f.peer.request('ui/initialize', {+ protocolVersion: '2026-01-26',+ appInfo: { name: 'Raw', version: '1' },+ appCapabilities: {},+ }),+ ).rejects.toThrow('MCP_APP_ALREADY_INITIALIZED');+ expect(await f.peer.request('ping')).toEqual({});+ });+ it('negotiates an unknown requested version to the actual supported stable version', async () => {+ const f = await fixture('http', false);+ expect(+ await f.peer.request<Init>('ui/initialize', {+ protocolVersion: '1900-01-01',+ appInfo: { name: 'Future View', version: '1' },+ appCapabilities: {},+ }),+ ).toMatchObject({ protocolVersion: '2026-01-26' });+ });+ it('proxies paginated discovery, resource templates and prompts to the App without model-only tools', async () => {+ const f = await fixture();+ const tools = await f.peer.request<{ tools: Tool[] }>('tools/list');+ expect(tools.tools.map((tool) => tool.name)).toEqual([+ 'open_metrics',+ 'refresh_metrics',+ 'slow_metrics',+ 'notify_change',+ 'error_metrics',+ ]);+ await expect(+ f.peer.request('tools/call', { name: 'model_audit', arguments: {} }),+ ).rejects.toThrow('MCP_APP_TOOL_NOT_VISIBLE');+ const page = await f.peer.request<{ resources: unknown[]; nextCursor: string }>(+ 'resources/list',+ );+ expect(page.nextCursor).toBe('ui');+ expect(await f.peer.request('resources/list', { cursor: page.nextCursor })).toMatchObject({+ resources: [{ uri: RAW_RESOURCE }],+ });+ expect(await f.peer.request('resources/templates/list')).toMatchObject({+ resourceTemplates: [{ uriTemplate: 'metrics://independent/{metric}' }],+ });+ expect(+ await f.peer.request('resources/read', { uri: 'metrics://independent/requests' }),+ ).toMatchObject({ contents: [{ text: 'Metric resource: metrics://independent/requests' }] });+ expect(await f.peer.request('prompts/list')).toMatchObject({+ prompts: [{ name: 'explain_metrics' }],+ });+ });+ it.each(['http', 'sse'] as const)('%s: reconnects an open View for each later server operation', async (transport) => {+ const f = await fixture(transport);+ const operations = [+ ['tools/call', { name: 'refresh_metrics', arguments: { threshold: 42 } },+ { structuredContent: { metrics: { threshold: 42, refreshes: 1 } } }],+ ['resources/read', { uri: 'metrics://independent/requests' },+ { contents: [{ text: 'Metric resource: metrics://independent/requests' }] }],+ ['resources/list', { cursor: 'ui' }, { resources: [{ uri: RAW_RESOURCE }] }],+ ['resources/templates/list', {}, { resourceTemplates: [{ uriTemplate: 'metrics://independent/{metric}' }] }],+ ['prompts/list', {}, { prompts: [{ name: 'explain_metrics' }] }],+ ] as const;+ for (const [method, params, expected] of operations) {+ const previous = await f.connection.getClient();+ // Simulate the transport's close event without permanently closing the+ // shared AppConnection, so the next request must create a new client.+ previous.onclose?.();+ await previous.close();+ expect(await f.peer.request(method, params)).toMatchObject(expected);+ expect(await f.connection.getClient()).not.toBe(previous);+ }+ expect(f.authorize).toHaveBeenCalledOnce();+ });+ it('fans out standard list_changed notifications and exposes refreshed tool definitions', async () => {+ const f = await fixture();+ await f.peer.request('tools/call', { name: 'notify_change', arguments: {} });+ await vi.waitFor(() =>+ expect(f.peer.notifications).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ method: 'notifications/tools/list_changed' }),+ expect.objectContaining({ method: 'notifications/resources/list_changed' }),+ expect.objectContaining({ method: 'notifications/prompts/list_changed' }),+ ]),+ ),+ );+ const tools = await f.peer.request<{ tools: Tool[] }>('tools/list');+ expect(tools.tools.find((tool) => tool.name === 'refresh_metrics')?.title).toBe('Refresh 1');+ });+ it('keeps full results in the View, enforces permission and preserves isError', async () => {+ const f = await fixture();+ expect(+ await f.peer.request<CallToolResult>('tools/call', {+ name: 'refresh_metrics',+ arguments: { threshold: 99 },+ }),+ ).toMatchObject({+ structuredContent: { metrics: { threshold: 99, refreshes: 1 } },+ _meta: { viewOnly: 'independent-view-metadata' },+ });+ expect(f.authorize).toHaveBeenCalledWith(+ 'task',+ expect.objectContaining({ name: 'refresh_metrics' }),+ { threshold: 99 },+ expect.any(AbortSignal),+ );+ expect(+ await f.peer.request('tools/call', { name: 'error_metrics', arguments: {} }),+ ).toMatchObject({ isError: true, _meta: { viewOnly: 'error-details' } });+ f.authorize.mockRejectedValueOnce(new Error('MCP_APP_TOOL_DENIED'));+ await expect(+ f.peer.request('tools/call', { name: 'refresh_metrics', arguments: {} }),+ ).rejects.toThrow('MCP_APP_TOOL_DENIED');+ expect((await f.state()).refreshes).toBe(1);+ });+ it('preserves user message content, replaces model context and rejects unadvertised modalities', async () => {+ const f = await fixture();+ await f.peer.request('ui/update-model-context', {+ content: [{ type: 'text', text: 'old' }],+ structuredContent: { threshold: 1 },+ });+ await f.peer.request('ui/update-model-context', {+ content: [{ type: 'text', text: 'latest' }],+ structuredContent: { threshold: 2 },+ });+ expect((await f.host.modelContext('task')).text).toContain('latest');+ expect((await f.host.modelContext('task')).text).not.toContain('"text":"old"');+ expect(f.send).not.toHaveBeenCalled();+ await f.peer.request('ui/message', {+ role: 'user',+ content: { type: 'text', text: 'Stable message' },+ });+ await f.peer.request('ui/message', {+ role: 'user',+ content: [{ type: 'resource_link', uri: 'metrics://independent/latest', name: 'Metrics' }],+ });+ expect(f.send).toHaveBeenNthCalledWith(1, 'task', expect.anything(), [+ { type: 'text', text: 'Stable message' },+ ], expect.any(Function));+ expect(f.send).toHaveBeenNthCalledWith(2, 'task', expect.anything(), [+ { type: 'resource_link', uri: 'metrics://independent/latest', name: 'Metrics' },+ ], expect.any(Function));+ await expect(+ f.peer.request('ui/message', {+ role: 'user',+ content: [{ type: 'image', mimeType: 'image/png', data: 'AQID' }],+ }),+ ).rejects.toThrow('MCP_APP_MESSAGE_CONTENT_UNSUPPORTED');+ await expect(+ f.peer.request('ui/update-model-context', {+ content: [{ type: 'audio', mimeType: 'audio/wav', data: 'AQID' }],+ }),+ ).rejects.toThrow('MCP_APP_CONTEXT_CONTENT_UNSUPPORTED');+ expect(f.send).toHaveBeenCalledTimes(2);+ });+ it('returns success and failure for controller link actions and rejects unsafe URLs', async () => {+ const f = await fixture();+ expect(await f.peer.request('ui/open-link', { url: 'https://example.org/metrics' })).toEqual(+ {},+ );+ f.peer.linkSuccess = false;+ await expect(+ f.peer.request('ui/open-link', { url: 'https://example.org/denied' }),+ ).rejects.toThrow('MCP_APP_LINK_OPEN_FAILED');+ await expect(f.peer.request('ui/open-link', { url: 'javascript:alert(1)' })).rejects.toThrow(+ 'MCP_APP_INVALID_LINK',+ );+ expect(f.peer.links).toEqual(['https://example.org/metrics', 'https://example.org/denied']);+ });+ it('honors App mode restrictions and sends updated environment as partial Host context', async () => {+ const f = await fixture('http', true, ['inline']);+ expect(await f.peer.request('ui/request-display-mode', { mode: 'fullscreen' })).toEqual({+ mode: 'inline',+ });+ expect(await f.peer.request('ui/request-display-mode', { mode: 'pip' })).toEqual({+ mode: 'inline',+ });+ f.host.context('renderer:conformance', 'task', f.document.viewId, {+ theme: 'dark',+ locale: 'en-US',+ });+ await vi.waitFor(() =>+ expect(f.peer.notifications).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ method: 'ui/notifications/host-context-changed',+ params: expect.objectContaining({ theme: 'dark', locale: 'en-US' }),+ }),+ ]),+ ),+ );+ await f.peer.notify('ui/notifications/size-changed', { width: 640, height: 420 });+ await f.peer.notify('notifications/message', {+ level: 'info',+ data: 'Fixture content should never be logged',+ });+ expect(f.audit.mock.calls.flat()).not.toContain('Fixture content should never be logged');+ });+ it('does not advertise unsupported capabilities and returns standard unknown-method errors', async () => {+ const f = await fixture();+ for (const capability of ['sampling', 'downloadFile'])+ expect(f.init!.hostCapabilities).not.toHaveProperty(capability);+ for (const method of ['sampling/createMessage', 'ui/download-file', 'future/unknown']) {+ await expect(f.peer.request(method)).rejects.toMatchObject({ code: -32601 });+ }+ expect(f.audit).toHaveBeenCalledWith('unknown');+ });+ it('propagates standard cancellation to an in-flight App tool without retrying it', async () => {+ const f = await fixture();+ const pending = f.peer.request<CallToolResult>('tools/call', {+ name: 'slow_metrics',+ arguments: {},+ });+ const id = f.peer.lastRequestId;+ const rejection = expect(pending).rejects.toThrow('Request cancelled');+ await vi.waitFor(async () => expect((await f.state()).slowStarted).toBe(1));+ await f.peer.cancel(id);+ await vi.waitFor(async () => expect((await f.state()).cancelled).toBe(1));+ await rejection;+ expect((await f.state()).slowStarted).toBe(1);+ });+ it('completes the standard teardown handshake before the View is released', async () => {+ const f = await fixture();+ await f.host.teardown('renderer:conformance', 'task', f.document.viewId);+ expect(f.peer.hostRequests).toEqual([+ expect.objectContaining({ method: 'ui/resource-teardown' }),+ ]);+ await expect(f.host.poll('renderer:conformance', 'task', f.document.viewId, 0)).rejects.toThrow(+ 'MCP_APP_VIEW_UNAVAILABLE',+ );+ });+ it('uses the same model facade for a different App and strips only View metadata', async () => {+ const f = await fixture();+ setMcpAppsHost(f.host);+ registerAppServer(f.config.id, () => f.config);+ const proxy = createAppServerProxy(() => f.config, {+ agentKind: 'codex',+ sessionId: 'task',+ workingDir: '',+ });+ const model = new Client({ name: 'Independent model client', version: '1' });+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ await proxy.connect(serverTransport);+ await model.connect(clientTransport);+ cleanup.push(async () => {+ await model.close();+ await proxy.close();+ });+ expect((await model.listTools()).tools.map((tool) => tool.name)).toEqual([+ 'open_metrics',+ 'model_audit',+ ]);+ const result = await model.callTool(+ { name: 'open_metrics', arguments: { threshold: 10 } },+ CallToolResultSchema,+ );+ expect(result).not.toHaveProperty('_meta');+ expect(result.content).toEqual(f.result.content);+ const card = [...f.cards.values()].find((card) => card.arguments.threshold === 10)!;+ expect(card.result?._meta).toMatchObject({ viewOnly: 'independent-view-metadata' });+ const second = await f.host.open(+ 'renderer:conformance',+ 'task',+ [...f.cards.entries()].find(([, value]) => value === card)![0],+ { platform: 'desktop' },+ );+ expect(second.html).toBe(RAW_APP_HTML);+ await expect(model.callTool({ name: 'refresh_metrics', arguments: {} })).rejects.toThrow(+ 'MCP_APP_TOOL_NOT_VISIBLE',+ );+ expect(await model.getPrompt({ name: 'explain_metrics' })).toMatchObject({+ messages: [{ role: 'user', content: { text: 'Explain these metrics.' } }],+ });+ expect(await model.listResourceTemplates()).toMatchObject({+ resourceTemplates: [{ name: 'Metric' }],+ });+ });+});diff --git a/apps/desktop/src/main/mcp-apps/__tests__/connection.test.ts b/apps/desktop/src/main/mcp-apps/__tests__/connection.test.tsnew file mode 100644index 0000000000..6efe126aef--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/__tests__/connection.test.ts@@ -0,0 +1,107 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { AppConnection } from '../connection.js';++afterEach(() => vi.restoreAllMocks());+const config = { id: 'example', url: 'https://mcp.example.invalid', transport: 'http' as const };++describe('MCP App connection recovery', () => {+ it('retries a failed connection only for a later independent request', async () => {+ const connect = vi.spyOn(Client.prototype, 'connect')+ .mockRejectedValueOnce(new Error('offline')).mockResolvedValue(undefined);+ vi.spyOn(Client.prototype, 'close').mockResolvedValue(undefined);+ const connection = new AppConnection(config);+ await expect(connection.getClient()).rejects.toThrow('offline');+ expect(connect).toHaveBeenCalledTimes(1);+ expect(connection.isClosed).toBe(false);+ const [first, second] = await Promise.all([connection.getClient(), connection.getClient()]);+ expect(first).toBe(second);+ expect(connect).toHaveBeenCalledTimes(2);+ await connection.close();+ await expect(connection.getClient()).rejects.toThrow('MCP_APP_CONNECTION_CLOSED');+ expect(connect).toHaveBeenCalledTimes(2);+ });++ it('does not replay an in-flight tool when the transport closes, or retire its replacement', async () => {+ const connect = vi.spyOn(Client.prototype, 'connect').mockResolvedValue(undefined);+ vi.spyOn(Client.prototype, 'close').mockResolvedValue(undefined);+ const connection = new AppConnection(config);+ const first = await connection.getClient();+ const call = vi.spyOn(first, 'callTool').mockImplementation(async () => {+ first.onclose?.();+ throw new Error('connection lost after send');+ });+ await expect(first.callTool({ name: 'submit' })).rejects.toThrow('connection lost');+ expect(call).toHaveBeenCalledOnce();+ expect(connect).toHaveBeenCalledOnce();+ const second = await connection.getClient();+ expect(second).not.toBe(first);+ first.onclose?.();+ expect(await connection.getClient()).toBe(second);+ expect(connect).toHaveBeenCalledTimes(2);+ expect(call).toHaveBeenCalledOnce();+ await connection.close();+ });++ it('never revives a connection closed while initialization was pending', async () => {+ let finish!: () => void;+ vi.spyOn(Client.prototype, 'connect').mockImplementation(() => new Promise<void>((resolve) => { finish = resolve; }));+ vi.spyOn(Client.prototype, 'close').mockResolvedValue(undefined);+ const connection = new AppConnection(config);+ const pending = connection.getClient();+ await connection.close();+ finish();+ await expect(pending).rejects.toThrow('MCP_APP_CONNECTION_CLOSED');+ await expect(connection.getClient()).rejects.toThrow('MCP_APP_CONNECTION_CLOSED');+ });+});++describe.each(['http', 'sse'] as const)('MCP App %s discovery cancellation', (transport) => {+ it('does not establish an authenticated connection for an already cancelled request', async () => {+ const connect = vi.spyOn(Client.prototype, 'connect').mockResolvedValue(undefined);+ vi.spyOn(Client.prototype, 'close').mockResolvedValue(undefined);+ vi.spyOn(Client.prototype, 'listTools').mockResolvedValue({ tools: [] });+ const connection = new AppConnection({ ...config, transport });+ const cancelled = new AbortController();+ const reason = new Error('discovery cancelled before connect');+ cancelled.abort(reason);+ try {+ await expect(connection.tools(cancelled.signal)).rejects.toBe(reason);+ expect(connect).not.toHaveBeenCalled();+ } finally {+ await connection.close();+ }+ });++ it.each([false, true])('cancels one initialization waiter without cancelling its peer (reconnect=%s)', async (reconnect) => {+ let finish!: () => void;+ const connect = vi.spyOn(Client.prototype, 'connect').mockResolvedValue(undefined);+ vi.spyOn(Client.prototype, 'close').mockResolvedValue(undefined);+ const list = vi.spyOn(Client.prototype, 'listTools').mockResolvedValue({ tools: [] });+ const connection = new AppConnection({ ...config, transport });+ if (reconnect) (await connection.getClient()).onclose?.();+ connect.mockImplementationOnce(() => new Promise<void>((resolve) => { finish = resolve; }));+ const cancelled = new AbortController();+ const reason = new Error('discovery cancelled during connect');+ const pending = connection.tools(cancelled.signal);+ const peer = connection.tools();+ try {+ const settled = pending.then(() => 'resolved', (error: unknown) => error);+ cancelled.abort(reason);+ // Initialization deliberately stays pending: no wall-clock timeout can mask it.+ for (let i = 0; i < 8; i++) await Promise.resolve();+ expect(await Promise.race([settled, Promise.resolve('still waiting')])).toBe(reason);+ expect(list).not.toHaveBeenCalled();+ finish();+ await expect(peer).resolves.toEqual([]);+ expect(list).toHaveBeenCalledOnce();+ expect(connect).toHaveBeenCalledTimes(reconnect ? 2 : 1);+ await expect(connection.tools()).resolves.toEqual([]);+ expect(connect).toHaveBeenCalledTimes(reconnect ? 2 : 1);+ } finally {+ finish();+ await Promise.allSettled([pending, peer]);+ await connection.close();+ }+ });+});diff --git a/apps/desktop/src/main/mcp-apps/__tests__/contextBudget.test.ts b/apps/desktop/src/main/mcp-apps/__tests__/contextBudget.test.tsnew file mode 100644index 0000000000..ed84f7eff8--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/__tests__/contextBudget.test.ts@@ -0,0 +1,476 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { AppBridge } from '@modelcontextprotocol/ext-apps/app-bridge';+import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';+import type { AppConnection } from '../connection.js';+import type { McpAppRecord } from '../../../shared/mcpApps.js';+import { McpAppsHost, appServerRevision } from '../host.js';++type ContextParams = { structuredContent: { draft: string } };+const hosts: McpAppsHost[] = [];++afterEach(async () => {+ await Promise.all(hosts.splice(0).map((host) => host.reset()));+ vi.restoreAllMocks();+});++function sizedContext(bytes: number, unit = '汉'): ContextParams {+ const empty = { structuredContent: { draft: '' } };+ const available = bytes - Buffer.byteLength(JSON.stringify(empty), 'utf8');+ const unitBytes =+ Buffer.byteLength(JSON.stringify({ structuredContent: { draft: unit } }), 'utf8') -+ Buffer.byteLength(JSON.stringify(empty), 'utf8');+ return {+ structuredContent: {+ draft: unit.repeat(Math.floor(available / unitBytes)) + 'x'.repeat(available % unitBytes),+ },+ };+}++function contextValue(params: ContextParams) {+ return { app: 'example', resourceUri: 'ui://form', ...params };+}++function contextJson(text: string) {+ return text.split('\n')[2];+}++function fixture() {+ let owner = {};+ let visible = true;+ let enabled = true;+ const cards = new Map<string, McpAppRecord>();+ const archived = new Set<string>();+ const config = { id: 'example', url: 'https://mcp.example.invalid', transport: 'http' as const };+ const tool = {+ name: 'form',+ inputSchema: { type: 'object' as const },+ _meta: { ui: { resourceUri: 'ui://form' } },+ };+ const record = {+ version: 1 as const,+ serverId: config.id,+ serverRevision: appServerRevision(config),+ resourceUri: 'ui://form',+ tool,+ arguments: {},+ };+ const connection = {+ getClient: async () => ({ getServerCapabilities: () => ({}) }),+ tools: async () => [tool],+ resource: async () => ({+ result: {+ contents: [{ uri: 'ui://form', mimeType: 'text/html;profile=mcp-app', text: '' }],+ },+ }),+ listen: () => () => {},+ close: async () => {},+ } as unknown as AppConnection;+ const outgoing: JSONRPCMessage[] = [];+ const connect = AppBridge.prototype.connect;+ vi.spyOn(AppBridge.prototype, 'connect').mockImplementation(function (+ this: AppBridge,+ transport,+ ) {+ const send = transport.send.bind(transport);+ transport.send = async (message, options) => {+ outgoing.push(message);+ await send(message, options);+ };+ return connect.call(this, transport);+ });+ // Context budgeting does not exercise the separate teardown handshake.+ vi.spyOn(AppBridge.prototype, 'teardownResource').mockResolvedValue({});+ const readCard = vi.fn(async (sessionId: string, clientId: string) => {+ if (!visible) throw new Error('MCP_APP_CARD_UNAVAILABLE');+ if (archived.has(sessionId)) throw new Error('MCP_APP_SESSION_UNAVAILABLE');+ const card = cards.get(`${sessionId}:${clientId}`);+ if (!card) throw new Error('MCP_APP_CARD_UNAVAILABLE');+ return card;+ });+ const host = new McpAppsHost({+ owner: () => owner,+ config: () => (enabled ? config : undefined),+ readCard,+ writeCard: async () => {},+ authorizeTool: async () => {},+ sendMessage: async () => {},+ connection: () => connection,+ });+ hosts.push(host);+ let requestId = 0;+ return {+ host,+ readCard,+ cards,+ archived,+ changeOwner() {+ owner = {};+ },+ revoke(kind: 'card' | 'owner' | 'server' | 'config') {+ if (kind === 'card') visible = false;+ if (kind === 'owner') owner = {};+ if (kind === 'server') enabled = false;+ if (kind === 'config') config.url = 'https://changed.example.invalid';+ },+ async open(clientId: string, sessionId = 'task') {+ cards.set(`${sessionId}:${clientId}`, {+ ...record,+ serverRevision: appServerRevision(config),+ });+ const document = await host.open('renderer:1', sessionId, clientId, {});+ const request = async (method: string, params: Record<string, unknown>) => {+ const id = ++requestId;+ await host.dispatch('renderer:1', sessionId, document.viewId, {+ jsonrpc: '2.0',+ id,+ method,+ params,+ });+ await vi.waitFor(() => expect(outgoing).toContainEqual(expect.objectContaining({ id })), {+ interval: 1,+ });+ return outgoing.find((message) => 'id' in message && message.id === id)!;+ };+ await request('ui/initialize', {+ protocolVersion: '2026-01-26',+ appInfo: { name: 'Context budget fixture', version: '1' },+ appCapabilities: {},+ });+ await host.dispatch('renderer:1', sessionId, document.viewId, {+ jsonrpc: '2.0',+ method: 'ui/notifications/initialized',+ });+ return Object.assign((params: ContextParams) => request('ui/update-model-context', params), {+ close: () => host.teardown('renderer:1', sessionId, document.viewId),+ });+ },+ };+}++describe('MCP App UTF-8 model-context budgets', () => {+ it.each(['removed', 'replaced'] as const)(+ 'reclaims aggregate bytes from a %s card without waiting for another model turn',+ async (kind) => {+ const f = fixture();+ const large = sizedContext(127_800);+ for (let index = 0; index < 4; index++) {+ const update = await f.open(`card-${index}`);+ expect(await update(large)).toHaveProperty('result');+ await update.close();+ }+ if (kind === 'removed') f.cards.delete('task:card-0');+ else+ f.cards.set('task:card-0', { ...f.cards.get('task:card-0')!, serverRevision: 'obsolete' });+ const update = await f.open('new-card');+ expect(await update(large)).toHaveProperty('result');+ expect(JSON.parse(contextJson((await f.host.modelContext('task')).text))).toEqual(+ Array.from({ length: 4 }, () => contextValue(large)),+ );+ },+ );++ it.each(['replacement', 'requesting-card', 'budget-refilled'] as const)(+ 'revalidates %s after aggregate-byte cleanup awaits another card',+ async (race) => {+ const f = fixture();+ const large = sizedContext(127_800);+ for (let index = 0; index < 4; index++) {+ const update = await f.open(`card-${index}`);+ expect(await update(large)).toHaveProperty('result');+ await update.close();+ }+ const replace = await f.open('card-0');+ const update = await f.open('new-card');+ f.cards.delete('task:card-1');+ const read = f.readCard.getMockImplementation()!;+ let finish!: () => void;+ let paused = false;+ f.readCard.mockImplementation(async (...args) => {+ if (args[1] === 'card-0' && !paused) {+ paused = true;+ await new Promise<void>((resolve) => {+ finish = resolve;+ });+ if (race === 'replacement') throw new Error('MCP_APP_CARD_UNAVAILABLE');+ }+ return read(...args);+ });+ const pending = update(large);+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'));+ if (race === 'replacement') {+ expect(await replace({ structuredContent: { draft: 'replacement' } })).toHaveProperty(+ 'result',+ );+ } else if (race === 'requesting-card') {+ f.cards.delete('task:new-card');+ } else {+ const refill = await f.open('refill');+ expect(await refill(large)).toHaveProperty('result');+ }+ finish();+ if (race === 'replacement') {+ expect(await pending).toHaveProperty('result');+ expect(JSON.parse(contextJson((await f.host.modelContext('task')).text))[0]).toEqual(+ contextValue({ structuredContent: { draft: 'replacement' } }),+ );+ } else {+ const error =+ race === 'requesting-card' ? 'MCP_APP_CARD_UNAVAILABLE' : 'MCP_APP_CONTEXT_TOO_LARGE';+ expect(await pending).toHaveProperty('error.message', expect.stringContaining(error));+ expect(JSON.parse(contextJson((await f.host.modelContext('task')).text))).toHaveLength(+ race === 'budget-refilled' ? 4 : 3,+ );+ }+ },+ );++ it.each(['card', 'session', 'config', 'owner'] as const)(+ 'reclaims the global context cap after %s revocation without another turn in the old tasks',+ async (kind) => {+ const f = fixture();+ for (let index = 0; index < 256; index++) {+ const update = await f.open('card', `task-${index}`);+ expect(await update({ structuredContent: { draft: `draft-${index}` } })).toHaveProperty(+ 'result',+ );+ await update.close();+ }+ if (kind === 'card') f.cards.delete('task-0:card');+ if (kind === 'session') f.archived.add('task-0');+ if (kind === 'config') f.revoke('config');+ if (kind === 'owner') f.revoke('owner');+ const update = await f.open('new-card', 'new-task');+ expect(await update({ structuredContent: { draft: 'new draft' } })).toHaveProperty('result');+ expect(JSON.parse(contextJson((await f.host.modelContext('new-task')).text))).toEqual([+ contextValue({ structuredContent: { draft: 'new draft' } }),+ ]);+ if (kind === 'card' || kind === 'session') {+ expect(JSON.parse(contextJson((await f.host.modelContext('task-1')).text))).toEqual([+ contextValue({ structuredContent: { draft: 'draft-1' } }),+ ]);+ }+ },+ 20_000,+ );++ it('preserves valid contexts at the global cap and still allows their replacement', async () => {+ const f = fixture();+ for (let index = 0; index < 256; index++) {+ const update = await f.open('card', `task-${index}`);+ expect(await update({ structuredContent: { draft: `draft-${index}` } })).toHaveProperty(+ 'result',+ );+ await update.close();+ }+ const overflow = await f.open('new-card', 'new-task');+ expect(await overflow({ structuredContent: { draft: 'overflow' } })).toHaveProperty(+ 'error.message',+ expect.stringContaining('MCP_APP_CONTEXT_LIMIT'),+ );+ const replace = await f.open('card', 'task-0');+ expect(await replace({ structuredContent: { draft: 'replacement' } })).toHaveProperty('result');+ expect(JSON.parse(contextJson((await f.host.modelContext('task-0')).text))).toEqual([+ contextValue({ structuredContent: { draft: 'replacement' } }),+ ]);+ }, 20_000);++ it.each(['replacement', 'requesting-card'] as const)(+ 'revalidates %s after the context-cap cleanup reads other cards',+ async (race) => {+ const f = fixture();+ for (let index = 0; index < 256; index++) {+ const update = await f.open('card', `task-${index}`);+ expect(await update({ structuredContent: { draft: `draft-${index}` } })).toHaveProperty(+ 'result',+ );+ await update.close();+ }+ const replace = await f.open('card', 'task-0');+ const update = await f.open('new-card', 'new-task');+ f.cards.delete('task-1:card');+ const read = f.readCard.getMockImplementation()!;+ let finish!: () => void;+ let paused = false;+ f.readCard.mockImplementation(async (...args) => {+ if (args[0] === 'task-0' && !paused) {+ paused = true;+ await new Promise<void>((resolve) => {+ finish = resolve;+ });+ throw new Error('MCP_APP_CARD_UNAVAILABLE');+ }+ return read(...args);+ });+ const pending = update({ structuredContent: { draft: 'new draft' } });+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'));+ if (race === 'replacement') {+ expect(await replace({ structuredContent: { draft: 'replacement' } })).toHaveProperty(+ 'result',+ );+ } else {+ f.cards.delete('new-task:new-card');+ }+ finish();+ if (race === 'replacement') {+ expect(await pending).toHaveProperty('result');+ expect(JSON.parse(contextJson((await f.host.modelContext('task-0')).text))).toEqual([+ contextValue({ structuredContent: { draft: 'replacement' } }),+ ]);+ } else {+ expect(await pending).toHaveProperty(+ 'error.message',+ expect.stringContaining('MCP_APP_CARD_UNAVAILABLE'),+ );+ expect((await f.host.modelContext('new-task')).text).toBe('');+ }+ },+ 20_000,+ );++ it.each(['card', 'owner', 'server', 'config'] as const)(+ 'rejects a captured context after %s revocation',+ async (kind) => {+ const f = fixture();+ const update = await f.open('card');+ expect(await update({ structuredContent: { draft: 'private draft' } })).toHaveProperty(+ 'result',+ );+ const snapshot = await f.host.modelContext('task');+ f.revoke(kind);+ await expect(snapshot.assertCurrent()).rejects.toThrow('MCP_APP_');+ },+ );++ it.each(['owner', 'server', 'config'] as const)(+ 'rejects %s revocation while the final context validation is reading its cards',+ async (kind) => {+ const f = fixture();+ const update = await f.open('card');+ expect(await update({ structuredContent: { draft: 'private draft' } })).toHaveProperty(+ 'result',+ );+ const snapshot = await f.host.modelContext('task');+ const read = f.readCard.getMockImplementation()!;+ let finish!: () => void;+ f.readCard.mockImplementationOnce(async (...args) => {+ const card = await read(...args);+ await new Promise<void>((resolve) => {+ finish = resolve;+ });+ return card;+ });+ const rejected = expect(snapshot.assertCurrent()).rejects.toThrow('MCP_APP_');+ await vi.waitFor(() => expect(finish).toBeDefined());+ f.revoke(kind);+ finish();+ await rejected;+ },+ );++ it('validates a captured value without consuming or replacing a newer App update', async () => {+ const f = fixture();+ const update = await f.open('card');+ expect(await update({ structuredContent: { draft: 'first' } })).toHaveProperty('result');+ const snapshot = await f.host.modelContext('task');+ expect(await update({ structuredContent: { draft: 'second' } })).toHaveProperty('result');+ await expect(snapshot.assertCurrent()).resolves.toBeUndefined();+ expect(JSON.parse(contextJson(snapshot.text))).toEqual([+ contextValue({ structuredContent: { draft: 'first' } }),+ ]);+ snapshot.consume();+ expect(JSON.parse(contextJson((await f.host.modelContext('task')).text))).toEqual([+ contextValue({ structuredContent: { draft: 'second' } }),+ ]);+ });++ it.each(['汉', '🧩', '"', '\u0001'])(+ 'counts serialized UTF-8 bytes for %j at the per-update boundary',+ async (unit) => {+ const f = fixture();+ const update = await f.open('card');+ const params = sizedContext(128_000, unit);+ expect(Buffer.byteLength(JSON.stringify(params), 'utf8')).toBe(128_000);+ expect(await update(params)).toHaveProperty('result');+ const accepted = await f.host.modelContext('task');+ expect(JSON.parse(contextJson(accepted.text))).toEqual([contextValue(params)]);++ const oversized = { structuredContent: { draft: params.structuredContent.draft + 'x' } };+ expect(await update(oversized)).toHaveProperty(+ 'error.message',+ expect.stringContaining('MCP_APP_CONTEXT_TOO_LARGE'),+ );+ expect((await f.host.modelContext('task')).text).toBe(accepted.text);+ },+ );++ it('includes the full context array and preserves valid values after an aggregate overflow', async () => {+ const f = fixture();+ const maximum = sizedContext(128_000, '🧩');+ const previous = [];+ for (let index = 0; index < 3; index++) {+ const update = await f.open(`card-${index}`);+ expect(await update(maximum)).toHaveProperty('result');+ previous.push(contextValue(maximum));+ }+ const update = await f.open('card-3');+ const empty = { structuredContent: { draft: '' } };+ const available =+ 512_000 - Buffer.byteLength(JSON.stringify([...previous, contextValue(empty)]), 'utf8');+ const exact = sizedContext(Buffer.byteLength(JSON.stringify(empty), 'utf8') + available);+ const oversized = { structuredContent: { draft: exact.structuredContent.draft + 'x' } };+ expect(Buffer.byteLength(JSON.stringify(oversized), 'utf8')).toBeLessThan(128_000);+ expect(await update(oversized)).toHaveProperty(+ 'error.message',+ expect.stringContaining('MCP_APP_CONTEXT_TOO_LARGE'),+ );+ expect(JSON.parse(contextJson((await f.host.modelContext('task')).text))).toEqual(previous);+ expect(await update(exact)).toHaveProperty('result');+ const full = await f.host.modelContext('task');+ expect(Buffer.byteLength(contextJson(full.text), 'utf8')).toBe(512_000);+ expect(JSON.parse(contextJson(full.text))).toEqual([...previous, contextValue(exact)]);++ const otherTask = await f.open('card-0', 'another-task');+ expect(await otherTask(maximum)).toHaveProperty('result');+ expect(JSON.parse(contextJson((await f.host.modelContext('another-task')).text))).toEqual([+ contextValue(maximum),+ ]);+ expect((await f.host.modelContext('task')).text).toBe(full.text);+ });++ it('reclaims the replaced context budget without consuming a later update', async () => {+ const f = fixture();+ const update = await f.open('card');+ const large = sizedContext(128_000);+ for (let index = 0; index < 3; index++) {+ const other = await f.open(`other-${index}`);+ expect(await other(large)).toHaveProperty('result');+ }+ const first = sizedContext(64_000);+ expect(await update(first)).toHaveProperty('result');+ const snapshot = await f.host.modelContext('task');+ const replacement = sizedContext(100_000);+ expect(await update(replacement)).toHaveProperty('result');+ snapshot.consume();+ expect(JSON.parse(contextJson((await f.host.modelContext('task')).text))).toEqual([+ contextValue(replacement),+ ]);+ const next = await f.open('next');+ expect(await next(large)).toHaveProperty('result');+ });++ it('keeps context budgets separate across accounts', async () => {+ const f = fixture();+ const maximum = sizedContext(128_000);+ for (let index = 0; index < 3; index++) {+ const update = await f.open(`card-${index}`);+ expect(await update(maximum)).toHaveProperty('result');+ }+ f.changeOwner();+ expect((await f.host.modelContext('task')).text).toBe('');+ const update = await f.open('new-account-card');+ expect(await update(maximum)).toHaveProperty('result');+ expect(JSON.parse(contextJson((await f.host.modelContext('task')).text))).toEqual([+ contextValue(maximum),+ ]);+ });+});diff --git a/apps/desktop/src/main/mcp-apps/__tests__/interop.test.ts b/apps/desktop/src/main/mcp-apps/__tests__/interop.test.tsnew file mode 100644index 0000000000..e37f7738b9--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/__tests__/interop.test.ts@@ -0,0 +1,788 @@+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';+import { Script } from 'node:vm';+import { App } from '@modelcontextprotocol/ext-apps';+import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';+import {+ CallToolResultSchema,+ type CallToolResult,+ type JSONRPCMessage,+} from '@modelcontextprotocol/sdk/types.js';+import {+ createMockAppServer,+ startMockAppServer,+ MOCK_RESOURCE,+} from '../../../../scripts/mcp-apps-mock.mjs';+import { AppConnection } from '../connection.js';+import { McpAppsHost, appServerRevision, type McpAppsHostDeps } from '../host.js';+import { setMcpAppsHost, registerAppServer } from '../runtime.js';+import { createAppServerProxy } from '../serverProxy.js';+import { MCP_APPS_MAX_BYTES, MCP_APPS_MAX_CARD_BYTES } from '../protocol.js';+import type { McpAppRecord } from '../../../shared/mcpApps.js';++let endpoint: Awaited<ReturnType<typeof startMockAppServer>>;+const serverInstructions =+ 'Review the draft before calling create_application.\nKeep application data unchanged.';+const cleanups: Array<() => Promise<unknown>> = [];+beforeAll(async () => {+ endpoint = await startMockAppServer({+ createServer: () => createMockAppServer({ instructions: serverInstructions }),+ });+});+afterAll(async () => {+ await endpoint.close();+});+afterEach(async () => {+ await Promise.allSettled(cleanups.splice(0).map((close) => close()));+});++/** Independent official View SDK, using the production Host transport operations. */+class TestViewTransport implements Transport {+ onmessage?: Transport['onmessage'];+ onclose?: Transport['onclose'];+ onerror?: Transport['onerror'];+ failure?: unknown;+ private active = true;+ constructor(+ private host: McpAppsHost,+ private viewId: string,+ private caller = 'renderer:1',+ private openLink: (url: string) => Promise<void> = async () => {},+ ) {}+ async start() {+ void (async () => {+ let after = 0;+ while (this.active) {+ try {+ const events = await this.host.poll(this.caller, 'task', this.viewId, after);+ for (const event of events) {+ after = event.seq;+ if (event.openLink) {+ await this.openLink(event.openLink.url);+ this.host.linkResult(this.caller, 'task', this.viewId, event.openLink.id, true);+ } else this.onmessage?.(event.message);+ }+ } catch (error) {+ if (this.active) {+ this.failure = error;+ await this.close();+ }+ return;+ }+ }+ })();+ }+ async send(message: JSONRPCMessage) {+ await this.host.dispatch(this.caller, 'task', this.viewId, message);+ }+ async close() {+ if (!this.active) return;+ this.active = false;+ this.onclose?.();+ }+}++async function fixture(+ transport: 'http' | 'sse' = 'http',+ options: {+ cancelled?: boolean;+ pending?: boolean;+ platform?: 'mobile' | 'desktop';+ appModes?: ('inline' | 'fullscreen')[];+ duringResource?: 'result' | 'cancelled' | 'clear' | 'server';+ revisionKey?: () => string;+ } = {},+) {+ const config = {+ id: 'example',+ url: transport === 'http' ? endpoint.url : endpoint.sseUrl,+ transport,+ };+ let owner: object = {};+ let visible = true;+ let enabled = true;+ const connection = new AppConnection(config);+ const client = await connection.getClient();+ const tool = (await connection.tools()).find((tool) => tool.name === 'draft_form')!;+ const input = { title: 'Draft', body: 'Review first' };+ const result = (await client.callTool(+ { name: 'draft_form', arguments: input },+ CallToolResultSchema,+ )) as CallToolResult;+ let card: McpAppRecord = {+ version: 1,+ serverId: config.id,+ serverRevision: appServerRevision(config, options.revisionKey?.()),+ resourceUri: MOCK_RESOURCE,+ tool,+ arguments: input,+ ...(options.cancelled ? { cancelled: 'User cancelled' } : options.pending ? {} : { result }),+ };+ const authorize = vi.fn(async () => {});+ const sendMessage = vi.fn<McpAppsHostDeps['sendMessage']>(async () => {});+ const openLink = vi.fn(async () => {});+ const dispose = vi.fn();+ const write = vi.fn(async (_session: string, _client: string, record: McpAppRecord) => {+ card = record;+ });+ const host = new McpAppsHost({+ owner: () => owner,+ config: () => (enabled ? config : undefined),+ revisionKey: options.revisionKey,+ readCard: async () => {+ if (!visible) throw new Error('MCP_APP_CARD_UNAVAILABLE');+ return card;+ },+ writeCard: write,+ authorizeTool: authorize,+ sendMessage,+ disposeDocument: dispose,+ });+ card.connectionId = host.registerConnection(connection);+ if (options.duringResource) {+ if (options.duringResource === 'result' || options.duringResource === 'cancelled')+ delete card.result;+ const readResource = connection.resource.bind(connection);+ vi.spyOn(connection, 'resource').mockImplementationOnce(async (uri) => {+ const resource = await readResource(uri);+ if (options.duringResource === 'result')+ await host.updateResult('task', 'card', { ...card, result });+ if (options.duringResource === 'cancelled')+ await host.updateResult('task', 'card', { ...card, cancelled: 'User cancelled' });+ if (options.duringResource === 'clear') visible = false;+ if (options.duringResource === 'server') enabled = false;+ return resource;+ });+ }+ const document = await host+ .open('renderer:1', 'task', 'card', {+ theme: 'dark',+ platform: options.platform ?? 'desktop',+ })+ .catch(async (error) => {+ await host.reset();+ await connection.close();+ throw error;+ });+ const app = new App(+ { name: 'Official SDK View', version: '1.0.0' },+ { availableDisplayModes: options.appModes ?? ['inline', 'fullscreen'] },+ { autoResize: false },+ );+ const messages: string[] = [];+ const inputs: unknown[] = [],+ results: unknown[] = [];+ app.ontoolinput = (params) => {+ messages.push('input');+ inputs.push(params);+ };+ app.ontoolresult = (params) => {+ messages.push('result');+ results.push(params);+ };+ app.ontoolcancelled = () => {+ messages.push('cancelled');+ };+ const teardown = vi.fn(async () => ({}));+ app.onteardown = teardown;+ const viewTransport = new TestViewTransport(host, document.viewId, 'renderer:1', openLink);+ await app.connect(viewTransport);+ cleanups.push(async () => {+ await host.reset();+ await app.close();+ await connection.close();+ });+ return {+ host,+ app,+ viewTransport,+ client,+ card,+ document,+ config,+ messages,+ inputs,+ results,+ authorize,+ sendMessage,+ openLink,+ write,+ teardown,+ dispose,+ clear() {+ visible = false;+ },+ revoke() {+ enabled = false;+ },+ changeOwner() {+ owner = {};+ },+ };+}++describe('official MCP Apps interoperability', () => {+ it.each(['http', 'sse'] as const)('cancels a %s App resource request waiting for reconnect without disturbing a peer', async (transport) => {+ const f = await fixture(transport);+ await vi.waitFor(() => expect(f.inputs).toHaveLength(1));+ await f.client.close();+ const acquiring = vi.spyOn(AppConnection.prototype, 'getClient');+ const read = vi.spyOn(Client.prototype, 'readResource');+ const connect = Client.prototype.connect;+ let release: (() => void) | undefined;+ cleanups.push(async () => release?.());+ // Exercise the real shared connection attempt and per-waiter cancellation.+ vi.spyOn(Client.prototype, 'connect').mockImplementationOnce(function (this: Client, ...args: Parameters<Client['connect']>) {+ return new Promise<void>((resolve, reject) => {+ release = () => {+ release = undefined;+ void connect.call(this, ...args).then(resolve, reject);+ };+ });+ });+ const abort = new AbortController();+ const pending = f.app.readServerResource({ uri: MOCK_RESOURCE }, { signal: abort.signal });+ const rejected = expect(pending).rejects.toThrow();+ await vi.waitFor(() => expect(release).toBeDefined());+ const cancelled = vi.fn();+ const waiter = acquiring.mock.results.at(-1)!.value as Promise<Client>;+ void waiter.catch(cancelled);+ abort.abort();+ await rejected;+ await vi.waitFor(() => expect(cancelled).toHaveBeenCalledOnce());+ expect(read).not.toHaveBeenCalled();++ const healthy = f.app.readServerResource({ uri: MOCK_RESOURCE });+ const completed = expect(healthy).resolves.toMatchObject({ contents: [{ uri: MOCK_RESOURCE }] });+ await vi.waitFor(() => expect(acquiring).toHaveBeenCalledTimes(2));+ release!();+ await completed;+ expect(read).toHaveBeenCalledOnce();+ });++ it('stores and delivers a bounded oversized-result failure to live and reopened remote Views', async () => {+ const f = await fixture('http', { pending: true });+ await vi.waitFor(() => expect(f.inputs).toHaveLength(1));+ const oversized: CallToolResult = {+ content: [{ type: 'image', mimeType: 'image/png', data: 'A'.repeat(MCP_APPS_MAX_BYTES) }],+ structuredContent: { original: true },+ _meta: { viewOnly: 'must not be persisted with the rejected payload' },+ };+ await f.host.updateResult('task', 'card', { ...f.card, result: oversized });+ const persisted = f.write.mock.calls.at(-1)![2];+ const failure = {+ isError: true,+ content: [{ type: 'text', text: 'MCP_APP_RESULT_TOO_LARGE' }],+ };+ expect(persisted.result).toEqual(failure);+ expect(Buffer.byteLength(JSON.stringify({ mcpApp: persisted }))).toBeLessThan(+ MCP_APPS_MAX_CARD_BYTES,+ );+ // A history row transports content as a JSON-escaped string, not as the raw card object.+ expect(+ Buffer.byteLength(JSON.stringify({ content: JSON.stringify({ mcpApp: persisted }) })),+ ).toBeLessThan(MCP_APPS_MAX_BYTES);+ await vi.waitFor(() => expect(f.results).toEqual([failure]));+ expect(oversized.content[0]).toHaveProperty('data', 'A'.repeat(MCP_APPS_MAX_BYTES));+ await f.host.teardown('renderer:1', 'task', f.document.viewId);++ const document = await f.host.open('device:phone', 'task', 'card', {+ platform: 'mobile',+ theme: 'dark',+ });+ const reopened = new App(+ { name: 'Reopened remote View', version: '1.0.0' },+ {},+ { autoResize: false },+ );+ const results: unknown[] = [];+ reopened.ontoolresult = (result) => {+ results.push(result);+ };+ cleanups.push(async () => {+ await reopened.close();+ });+ await reopened.connect(new TestViewTransport(f.host, document.viewId, 'device:phone'));+ await vi.waitFor(() => expect(results).toEqual([failure]));+ });+ it('rejects oversized card input before writing history', async () => {+ const f = await fixture('http', { pending: true });+ await expect(+ f.host.updateResult('task', 'card', {+ ...f.card,+ arguments: { draft: 'x'.repeat(MCP_APPS_MAX_CARD_BYTES) },+ }),+ ).rejects.toThrow('MCP_APP_CARD_TOO_LARGE');+ expect(f.write).not.toHaveBeenCalled();+ });+ it('keeps the original oversized model result while persisting only the bounded App failure', async () => {+ const f = await fixture();+ setMcpAppsHost(f.host);+ registerAppServer(f.config.id, () => f.config);+ const upstream: CallToolResult = {+ content: [{ type: 'image', mimeType: 'image/png', data: 'A'.repeat(MCP_APPS_MAX_BYTES) }],+ structuredContent: { original: true },+ _meta: { viewOnly: 'private to the View' },+ };+ const getClient = vi.spyOn(AppConnection.prototype, 'getClient').mockResolvedValue(f.client);+ const callTool = vi.spyOn(f.client, 'callTool').mockResolvedValueOnce(upstream);+ const facade = createAppServerProxy(() => f.config, {+ agentKind: 'codex',+ sessionId: 'task',+ workingDir: '',+ });+ const client = new Client({ name: 'model-client', version: '1' });+ cleanups.push(async () => {+ await client.close();+ await facade.close();+ });+ try {+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ await facade.connect(serverTransport);+ await client.connect(clientTransport);+ const result = await client.callTool({+ name: 'draft_form',+ arguments: { title: 'Draft', body: 'Review' },+ });+ expect(result.content).toEqual(upstream.content);+ expect(result.structuredContent).toEqual(upstream.structuredContent);+ expect(result).not.toHaveProperty('_meta');+ expect(upstream._meta).toEqual({ viewOnly: 'private to the View' });+ expect(f.write).toHaveBeenCalledTimes(2);+ for (const [, , record] of f.write.mock.calls)+ expect(Buffer.byteLength(JSON.stringify({ mcpApp: record }))).toBeLessThanOrEqual(+ MCP_APPS_MAX_CARD_BYTES,+ );+ expect(f.write.mock.calls.at(-1)![2].result).toEqual({+ isError: true,+ content: [{ type: 'text', text: 'MCP_APP_RESULT_TOO_LARGE' }],+ });+ } finally {+ callTool.mockRestore();+ getClient.mockRestore();+ }+ });+ it.each(['result', 'cancelled'] as const)(+ 'delivers %s when execution finishes while the App resource is loading',+ async (duringResource) => {+ const f = await fixture('http', { duringResource });+ await vi.waitFor(() => expect(f.messages).toEqual(['input', duringResource]));+ if (duringResource === 'result') expect(f.results).toEqual([f.card.result]);+ },+ );+ it.each([+ ['clear', 'MCP_APP_CARD_UNAVAILABLE'],+ ['server', 'MCP_APP_SERVER_CHANGED'],+ ] as const)(+ 'refuses a View revoked by %s while its resource is loading',+ async (duringResource, error) => {+ await expect(fixture('http', { duringResource })).rejects.toThrow(error);+ },+ );+ it.each(['http', 'sse'] as const)(+ '%s negotiates the official View and sends input before full result',+ async (transport) => {+ const f = await fixture(transport);+ await vi.waitFor(() => expect(f.messages).toEqual(['input', 'result']));+ expect(f.inputs).toEqual([{ arguments: f.card.arguments }]);+ expect(f.results).toEqual([f.card.result]);+ expect(f.card.result?._meta?.hostUi).toMatchObject({+ mimeTypes: ['text/html;profile=mcp-app'],+ });+ expect(f.app.getHostContext()).toMatchObject({+ theme: 'dark',+ displayMode: 'inline',+ availableDisplayModes: ['inline', 'fullscreen'],+ });+ expect(f.app.getHostCapabilities()).toMatchObject({+ sandbox: { permissions: {} },+ serverTools: {},+ });+ expect(f.document.html).toContain('创建模拟申请');+ expect(+ () => new Script(f.document.html.match(/<script>([\s\S]*)<\/script>/i)![1]),+ ).not.toThrow();+ },+ );+ it('App-only submit stays outside the model surface and model-only calls are rejected', async () => {+ const f = await fixture();+ const result = await f.app.callServerTool({+ name: 'create_application',+ arguments: { title: 'Edited', body: 'Application only' },+ });+ expect(result.structuredContent).toEqual({ applicationId: 1, sent: false });+ expect(f.authorize).toHaveBeenCalledOnce();+ await expect(f.app.callServerTool({ name: 'model_only', arguments: {} })).rejects.toThrow(+ 'MCP_APP_TOOL_NOT_VISIBLE',+ );+ const resource = await f.app.readServerResource({ uri: MOCK_RESOURCE });+ expect(resource.contents[0].mimeType).toBe('text/html;profile=mcp-app');+ });+ it('context updates replace old values, do not start a model turn, and disappear after clear', async () => {+ const f = await fixture();+ await f.app.updateModelContext({ structuredContent: { draft: 'old' } });+ await f.app.updateModelContext({ structuredContent: { draft: 'new' } });+ const context = await f.host.modelContext('task');+ expect(context.text).toContain('new');+ expect(context.text).not.toContain('old');+ expect(f.sendMessage).not.toHaveBeenCalled();+ await f.app.sendMessage({+ role: 'user',+ content: [{ type: 'text', text: 'Continue editing' }],+ });+ expect(f.sendMessage).toHaveBeenCalledWith('task', expect.anything(), [+ { type: 'text', text: 'Continue editing' },+ ], expect.any(Function));+ f.clear();+ expect((await f.host.modelContext('task')).text).toBe('');+ await expect(+ f.app.callServerTool({ name: 'create_application', arguments: { title: 'x', body: '' } }),+ ).rejects.toThrow('Connection closed');+ expect(f.viewTransport.failure).toMatchObject({ message: 'MCP_APP_CARD_UNAVAILABLE' });+ expect(f.authorize).not.toHaveBeenCalled();+ });+ it.each(['card', 'owner', 'server'] as const)(+ 'rechecks the live View after %s revocation during App-message preparation',+ async (kind) => {+ const f = await fixture();+ let finish!: () => void;+ let completed!: () => void;+ const completion = new Promise<void>((resolve) => {+ completed = resolve;+ });+ let failure: unknown;+ const dispatched = vi.fn();+ f.sendMessage.mockImplementationOnce(async (_id, _record, _content, assertCurrent) => {+ await new Promise<void>((resolve) => {+ finish = resolve;+ });+ try {+ await assertCurrent();+ dispatched();+ } catch (error) {+ failure = error;+ throw error;+ } finally {+ completed();+ }+ });+ const rejected = expect(+ f.app.sendMessage({ role: 'user', content: [{ type: 'text', text: 'Continue editing' }] }),+ ).rejects.toThrow('Connection closed');+ await vi.waitFor(() => expect(finish).toBeDefined());+ if (kind === 'card') f.clear();+ else if (kind === 'owner') f.changeOwner();+ else f.revoke();+ finish();+ await completion;+ expect(failure).toBeInstanceOf(Error);+ expect((failure as Error).message).toMatch(+ /MCP_APP_(CARD_UNAVAILABLE|VIEW_UNAVAILABLE|SERVER_CHANGED)/,+ );+ await rejected;+ expect(f.viewTransport.failure).toBeInstanceOf(Error);+ expect((f.viewTransport.failure as Error).message).toMatch(+ /MCP_APP_(CARD_UNAVAILABLE|VIEW_UNAVAILABLE|SERVER_CHANGED)/,+ );+ expect(dispatched).not.toHaveBeenCalled();+ expect(f.sendMessage).toHaveBeenCalledOnce();+ },+ );++ it('consumes a captured context once and leaves later updates for the next send', async () => {+ const f = await fixture();+ await f.app.updateModelContext({ structuredContent: { draft: 'first' } });+ const first = await f.host.modelContext('task');+ expect(first.text).toContain('first');+ // Reading prepares a send but must not consume data if dispatch later fails.+ expect((await f.host.modelContext('task')).text).toBe(first.text);+ first.consume();+ expect((await f.host.modelContext('task')).text).toBe('');++ await f.app.updateModelContext({ structuredContent: { draft: 'second' } });+ const second = await f.host.modelContext('task');+ await f.app.updateModelContext({ structuredContent: { draft: 'third' } });+ second.consume();+ first.consume();+ const third = await f.host.modelContext('task');+ expect(third.text).toContain('third');+ expect(third.text).not.toContain('second');+ third.consume();+ expect((await f.host.modelContext('task')).text).toBe('');+ });+ it('keeps a newer update even when its contents match the accepted snapshot', async () => {+ const f = await fixture();+ const update = { structuredContent: { draft: 'same' } };+ await f.app.updateModelContext(update);+ const previous = await f.host.modelContext('task');+ await f.app.updateModelContext(update);+ previous.consume();+ const next = await f.host.modelContext('task');+ expect(next.text).toBe(previous.text);+ next.consume();+ expect((await f.host.modelContext('task')).text).toBe('');+ });+ it('supports the stable single-block ui/message shape', async () => {+ const f = await fixture();+ await f.host.dispatch('renderer:1', 'task', f.document.viewId, {+ jsonrpc: '2.0',+ id: 'legacy-message',+ method: 'ui/message',+ params: { role: 'user', content: { type: 'text', text: 'Stable spec' } },+ });+ await vi.waitFor(() =>+ expect(f.sendMessage).toHaveBeenCalledWith('task', expect.anything(), [+ { type: 'text', text: 'Stable spec' },+ ], expect.any(Function)),+ );+ });+ it('opens links on the controller, without forwarding the host action to the View', async () => {+ const f = await fixture();+ await f.app.openLink({ url: 'https://example.org/help' });+ expect(f.openLink).toHaveBeenCalledWith('https://example.org/help');+ await expect(f.app.openLink({ url: 'file:///C:/private' })).rejects.toThrow(+ 'MCP_APP_INVALID_LINK',+ );+ expect(f.openLink).toHaveBeenCalledOnce();+ });+ it('host-initiated display changes use context notifications and preserve identity', async () => {+ const f = await fixture();+ await f.app.requestDisplayMode({ mode: 'fullscreen' });+ f.host.displayMode('renderer:1', 'task', f.document.viewId, 'inline');+ await vi.waitFor(() => expect(f.app.getHostContext()?.displayMode).toBe('inline'));+ f.host.context('renderer:1', 'task', f.document.viewId, { locale: 'zh-CN' });+ await vi.waitFor(() =>+ expect(f.app.getHostContext()).toMatchObject({+ theme: 'dark',+ locale: 'zh-CN',+ toolInfo: { id: 'card' },+ }),+ );+ });+ it('returns the actual negotiated display mode and sends host context changes', async () => {+ const f = await fixture('http', { platform: 'mobile' });+ expect(await f.app.requestDisplayMode({ mode: 'fullscreen' })).toEqual({ mode: 'inline' });+ f.host.context('renderer:1', 'task', f.document.viewId, { theme: 'light', locale: 'zh-CN' });+ await vi.waitFor(() =>+ expect(f.app.getHostContext()).toMatchObject({ theme: 'light', locale: 'zh-CN' }),+ );+ const desktop = await fixture();+ expect(await desktop.app.requestDisplayMode({ mode: 'fullscreen' })).toEqual({+ mode: 'fullscreen',+ });+ expect(await desktop.app.requestDisplayMode({ mode: 'pip' })).toEqual({ mode: 'fullscreen' });+ });+ it('delivers cancellation and completes official teardown before disposing the document', async () => {+ const f = await fixture('http', { cancelled: true });+ await vi.waitFor(() => expect(f.messages).toEqual(['input', 'cancelled']));+ await f.host.teardown('renderer:1', 'task', f.document.viewId);+ expect(f.teardown).toHaveBeenCalledOnce();+ expect(f.dispose).toHaveBeenCalledWith(f.document.viewId);+ await expect(f.host.poll('renderer:1', 'task', f.document.viewId, 0)).rejects.toThrow(+ 'MCP_APP_VIEW_UNAVAILABLE',+ );+ });+ it('binds requests to the exact task, controller and signed-in owner', async () => {+ const f = await fixture();+ await expect(+ f.host.dispatch('device:other', 'task', f.document.viewId, {+ jsonrpc: '2.0',+ id: 1,+ method: 'ping',+ }),+ ).rejects.toThrow('MCP_APP_VIEW_UNAVAILABLE');+ await expect(f.host.poll('renderer:1', 'another-task', f.document.viewId, 0)).rejects.toThrow(+ 'MCP_APP_VIEW_UNAVAILABLE',+ );+ f.changeOwner();+ expect((await f.host.modelContext('task')).text).toBe('');+ await expect(+ f.host.dispatch('renderer:1', 'task', f.document.viewId, {+ jsonrpc: '2.0',+ id: 1,+ method: 'ping',+ }),+ ).rejects.toThrow('MCP_APP_VIEW_UNAVAILABLE');+ });+ it('revokes a View when its configured server is removed', async () => {+ const f = await fixture();+ f.revoke();+ await expect(+ f.app.callServerTool({ name: 'create_application', arguments: { title: 'x', body: '' } }),+ ).rejects.toThrow('MCP_APP_SERVER_CHANGED');+ expect(f.authorize).not.toHaveBeenCalled();+ });+ it('persists the injected private revision through the facade and revokes Views when the key changes', async () => {+ let key = 'a'.repeat(64);+ const f = await fixture('http', { revisionKey: () => key });+ setMcpAppsHost(f.host);+ registerAppServer(f.config.id, () => f.config);+ const facade = createAppServerProxy(() => f.config, {+ agentKind: 'codex', sessionId: 'task', workingDir: '',+ });+ const client = new Client({ name: 'model-client', version: '1' });+ cleanups.push(async () => { await client.close(); await facade.close(); });+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ await facade.connect(serverTransport);+ await client.connect(clientTransport);+ await client.callTool({ name: 'draft_form', arguments: { title: 'Draft', body: 'Review' } });+ const persisted = f.write.mock.calls.at(-1)![2];+ expect(persisted.serverRevision).toBe(appServerRevision(f.config, key));+ expect(persisted.serverRevision).not.toBe(appServerRevision(f.config));+ key = 'b'.repeat(64);+ await expect(+ f.app.callServerTool({ name: 'create_application', arguments: { title: 'x', body: '' } }),+ ).rejects.toThrow('MCP_APP_SERVER_CHANGED');+ expect(f.authorize).not.toHaveBeenCalled();+ });+ it('registers only used model facades and releases their connections on shutdown', async () => {+ const f = await fixture();+ setMcpAppsHost(f.host);+ registerAppServer(f.config.id, () => f.config);+ const register = vi.spyOn(f.host, 'registerConnection');+ const release = vi.spyOn(f.host, 'releaseConnection');+ // Unused first instances from retired bridge generations exceed the Host limit.+ const facades = Array.from({ length: 300 }, () =>+ createAppServerProxy(() => f.config, {+ agentKind: 'codex',+ sessionId: 'task',+ workingDir: '',+ }),+ );+ cleanups.push(async () => {+ await Promise.allSettled(facades.map((facade) => facade.close()));+ });+ expect(register).not.toHaveBeenCalled();++ const facade = facades[facades.length - 1];+ const client = new Client({ name: 'model-client', version: '1' });+ cleanups.push(async () => {+ await client.close();+ });+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ await facade.connect(serverTransport);+ await client.connect(clientTransport);+ expect(register).toHaveBeenCalledOnce();+ expect((await client.listTools()).tools.map((tool) => tool.name)).toContain('draft_form');+ expect(register).toHaveBeenCalledTimes(2);+ const connection = register.mock.calls[0][0];+ expect(connection.isClosed).toBe(false);+ await client.listTools();+ expect(register.mock.results[1].value).toBe(register.mock.results[0].value);+ await facade.close();+ await vi.waitFor(() => expect(connection.isClosed).toBe(true));+ expect(release).toHaveBeenCalledWith(connection);+ });+ it('keeps ordinary MCP requests usable while the persistent App revision vault is unavailable', async () => {+ let vaultAvailable = true;+ const f = await fixture('http', {+ revisionKey: () => {+ if (!vaultAvailable) throw new Error('MCP_APP_REVISION_KEY_UNAVAILABLE');+ return 'a'.repeat(64);+ },+ });+ vaultAvailable = false;+ setMcpAppsHost(f.host);+ registerAppServer(f.config.id, () => f.config);+ const facade = createAppServerProxy(() => f.config, {+ agentKind: 'codex', sessionId: 'task', workingDir: '',+ });+ const client = new Client({ name: 'model-client', version: '1' });+ cleanups.push(async () => { await client.close(); await facade.close(); });+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ await facade.connect(serverTransport);+ await client.connect(clientTransport);+ expect((await client.listTools()).tools.map((tool) => tool.name)).toEqual(['draft_form', 'model_only']);+ f.write.mockClear();+ expect((await client.callTool({ name: 'model_only', arguments: {} })).isError).not.toBe(true);+ const result = await client.callTool({+ name: 'draft_form', arguments: { title: 'Vault unavailable', body: 'Keep tool execution' },+ });+ expect(result.content).toEqual([{ type: 'text', text: 'Draft: Vault unavailable' }]);+ expect(result).not.toHaveProperty('_meta');+ expect(f.write).not.toHaveBeenCalled();+ // No transient revision is persisted as a substitute for the inaccessible vault.+ await expect(f.host.open('renderer:1', 'task', 'card', {}))+ .rejects.toThrow('MCP_APP_REVISION_KEY_UNAVAILABLE');+ f.config.url += '/changed';+ await expect(client.listTools()).rejects.toThrow('MCP_APP_SERVER_CHANGED');+ });+ it.each(['http', 'sse'] as const)(+ 'preserves upstream instructions in the %s model initialize response',+ async (transport) => {+ const f = await fixture(transport);+ setMcpAppsHost(f.host);+ registerAppServer(f.config.id, () => f.config);+ const facade = createAppServerProxy(() => f.config, {+ agentKind: 'claude-code',+ sessionId: 'task',+ workingDir: '',+ });+ const client = new Client({ name: 'model-client', version: '1' });+ cleanups.push(async () => {+ await client.close();+ await facade.close();+ });+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ await facade.connect(serverTransport);+ await client.connect(clientTransport);+ expect(client.getInstructions()).toBe(serverInstructions);+ expect(client.getServerVersion()).toEqual({ name: f.config.id, version: '1.0.0' });+ expect(client.getServerCapabilities()).toMatchObject({ tools: { listChanged: true } });+ await client.listTools();+ expect(client.getInstructions()).toBe(serverInstructions);+ },+ );+ it('rejects initialization after an owner change without leaving the client waiting', async () => {+ const f = await fixture();+ setMcpAppsHost(f.host);+ registerAppServer(f.config.id, () => f.config);+ const facade = createAppServerProxy(() => f.config, {+ agentKind: 'codex',+ sessionId: 'task',+ workingDir: '',+ });+ const client = new Client({ name: 'model-client', version: '1' });+ cleanups.push(async () => {+ await client.close();+ await facade.close();+ });+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ await facade.connect(serverTransport);+ f.changeOwner();+ await expect(client.connect(clientTransport)).rejects.toThrow('MCP_APP_INITIALIZE_FAILED');+ });+ it('the model facade strips UI metadata and never turns card-write failure into tool failure', async () => {+ const f = await fixture();+ setMcpAppsHost(f.host);+ registerAppServer(f.config.id, () => f.config);+ const facade = createAppServerProxy(() => f.config, {+ agentKind: 'codex',+ sessionId: 'task',+ workingDir: '',+ });+ const client = new Client({ name: 'model-client', version: '1' });+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ await facade.connect(serverTransport);+ await client.connect(clientTransport);+ cleanups.push(async () => {+ await client.close();+ await facade.close();+ });+ expect((await client.listTools()).tools.map((tool) => tool.name)).toEqual([+ 'draft_form',+ 'model_only',+ ]);+ f.write.mockRejectedValueOnce(new Error('DB not available'));+ const result = await client.callTool({+ name: 'draft_form',+ arguments: { title: 'x', body: 'y' },+ });+ expect(result.content).toEqual([{ type: 'text', text: 'Draft: x' }]);+ expect(result).not.toHaveProperty('_meta');+ await expect(+ client.callTool({ name: 'create_application', arguments: { title: 'x', body: 'y' } }),+ ).rejects.toThrow('MCP_APP_TOOL_NOT_VISIBLE');+ });+});diff --git a/apps/desktop/src/main/mcp-apps/__tests__/ipc.test.ts b/apps/desktop/src/main/mcp-apps/__tests__/ipc.test.tsnew file mode 100644index 0000000000..609bf38cae--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/__tests__/ipc.test.ts@@ -0,0 +1,322 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { SQLiteSyncDialect } from 'drizzle-orm/sqlite-core';+import type { SQL } from 'drizzle-orm';+import type { McpAppsHostDeps } from '../host.js';+const state = vi.hoisted(() => ({+ owner: null as object | null,+ deps: undefined as McpAppsHostDeps | undefined,+ session: {+ id: 'task',+ status: 'active',+ clearedAt: null as number | null,+ permissionMode: 'default',+ },+ row: null as Record<string, unknown> | null,+ updateResult: [] as Record<string, unknown>[],+ predicates: [] as SQL[],+ duringUpdate: () => {},+ beforePublish: () => {},+ broadcast: vi.fn(),+ create: vi.fn(),+ trusted: vi.fn(),+ invoke: vi.fn(),+ open: vi.fn(),+ dispatch: vi.fn(),+ revisionKey: vi.fn(() => 'a'.repeat(64)),+ remote: undefined as { controllerDeviceId: string; sharedTask?: object } | undefined,+ handle: undefined as+ ((event: unknown, session: unknown, input: unknown) => Promise<unknown>) | undefined,+}));+vi.mock('electron', () => ({+ ipcMain: {+ removeHandler: vi.fn(),+ handle: (_name: string, handler: typeof state.handle) => {+ state.handle = handler;+ },+ },+ shell: { openExternal: vi.fn() },+}));+vi.mock('../host.js', () => ({+ McpAppsHost: class {+ open = state.open;+ dispatch = state.dispatch;+ constructor(deps: McpAppsHostDeps) {+ state.deps = deps;+ }+ },+}));+vi.mock('../runtime.js', () => ({ setMcpAppsHost: vi.fn(), readAppServer: vi.fn() }));+vi.mock('../../secrets/providerSecretStore.js', () => ({ getMcpAppRevisionKey: state.revisionKey }));+vi.mock('../sandboxProtocol.js', () => ({+ supplyMcpAppDocument: vi.fn(),+ removeMcpAppDocument: vi.fn(),+ mountRemoteAppDocument: vi.fn(),+ unmountRemoteAppDocument: vi.fn(),+ assertMcpAppDocumentCaller: vi.fn(),+ setMcpAppCallerCleanup: vi.fn(),+}));+vi.mock('../../device-link/index.js', () => ({ remoteInvoke: state.invoke, getRemoteLinkCloseEpoch: () => 0 }));+vi.mock('../../appCapabilities.js', () => ({ getAppCapabilities: () => ({ canUseDeviceLink: true }) }));+vi.mock('../../localDb/client/current.js', () => ({+ getCurrentDbClientSnapshot: () => state.owner,+}));+vi.mock('../../localDb/ipc/messages.js', () => ({+ broadcastMessageRow: state.broadcast,+ createMessage: (...args: unknown[]) => state.create(...args),+}));+vi.mock('../../device-link/broadcast-tap.js', () => ({+ captureDataOwnerBroadcastScope: () => ({ owner: state.owner }),+}));+vi.mock('../../security/trustedAppRenderer.js', () => ({+ assertTrustedAppRendererEvent: state.trusted,+}));+vi.mock('../../device-link/invoke-context.js', () => ({+ getDeviceLinkInvokeContext: () => state.remote,+}));+vi.mock('../../utils/ipcValidate.js', () => ({+ throwIpcError: (code: string, message: string) => {+ throw new Error('[' + code + '] ' + message);+ },+}));+import { sessions } from '../../localDb/schema.js';+import { registerMcpAppsIpc } from '../ipc.js';+import { mountRemoteAppDocument } from '../sandboxProtocol.js';+const record = {+ version: 1 as const,+ serverId: 'example',+ serverRevision: 'revision',+ resourceUri: 'ui://example/app',+ tool: { name: 'form', inputSchema: { type: 'object' as const } },+ arguments: {},+};+const request = vi.fn(async () => ({ kind: 'permission' as const, behavior: 'allow' as const }));+beforeEach(() => {+ vi.clearAllMocks();+ state.remote = undefined;+ state.predicates = [];+ state.duringUpdate = () => {};+ state.beforePublish = () => {};+ state.session = { id: 'task', status: 'active', clearedAt: null, permissionMode: 'default' };+ state.row = {+ id: 'row',+ sessionId: 'task',+ clientId: 'card',+ createdAt: 200,+ role: 'assistant',+ rewindAt: null,+ agentMeta: JSON.stringify({ mcpApp: true }),+ content: JSON.stringify({ mcpApp: record }),+ };+ state.updateResult = [state.row];+ state.owner = {+ client: {+ drizzle: {+ select: () => ({+ from: (table: unknown) => ({+ where: (condition: SQL) => ({+ limit: async () => {+ state.predicates.push(condition);+ return table === sessions+ ? [state.session]+ : state.row+ ? [{ ...state.row, meta: state.row.agentMeta }]+ : [];+ },+ }),+ }),+ }),+ update: () => ({+ set: () => ({+ where: (condition: SQL) => ({+ returning: async () => {+ state.predicates.push(condition);+ state.duringUpdate();+ return state.updateResult;+ },+ }),+ }),+ }),+ },+ },+ };+ state.create.mockImplementation(+ async (_id: string, _body: unknown, options: { beforePublish: () => Promise<void> }) => {+ state.beforePublish();+ await options.beforePublish();+ },+ );+ registerMcpAppsIpc(async () => {}, request);+});+describe('MCP App persistence and IPC wiring', () => {+ it('injects the persistent vault key lazily instead of using a transient Host key', () => {+ expect(state.revisionKey).not.toHaveBeenCalled();+ expect(state.deps!.revisionKey!()).toBe('a'.repeat(64));+ expect(state.revisionKey).toHaveBeenCalledOnce();+ });+ it('reads only host-marked visible assistant cards and uses the task clear boundary', async () => {+ state.session.clearedAt = 100;+ expect(await state.deps!.readCard('task', 'card')).toEqual(record);+ const query = new SQLiteSyncDialect().sqlToQuery(state.predicates[1]);+ expect(query.params).toContain('assistant');+ expect(query.sql).toContain('sessions.cleared_at');+ expect(query.sql).toContain('EXISTS');+ expect(query.sql).toContain('rewind_at');+ state.row!.agentMeta = '{}';+ await expect(state.deps!.readCard('task', 'card')).rejects.toThrow('MCP_APP_CARD_UNAVAILABLE');+ });+ it('uses a guarded update and broadcasts only a successful same-owner result', async () => {+ await state.deps!.writeCard('task', 'card', record);+ expect(state.broadcast).toHaveBeenCalledOnce();+ const query = new SQLiteSyncDialect().sqlToQuery(state.predicates.at(-1)!);+ expect(query.sql).toContain('EXISTS');+ expect(query.sql).toContain("sessions.status = 'active'");+ expect(query.sql).toContain('sessions.cleared_at');+ expect(query.sql).toContain('rewind_at');+ state.broadcast.mockClear();+ state.updateResult = [];+ await expect(state.deps!.writeCard('task', 'card', record)).rejects.toThrow(+ 'MCP_APP_CARD_UNAVAILABLE',+ );+ expect(state.broadcast).not.toHaveBeenCalled();+ });+ it('rejects owner changes after asynchronous writes without publishing their result', async () => {+ state.duringUpdate = () => {+ state.owner = {};+ };+ await expect(state.deps!.writeCard('task', 'card', record)).rejects.toThrow(+ 'MCP_APP_CARD_UNAVAILABLE',+ );+ expect(state.broadcast).not.toHaveBeenCalled();+ });+ it('fences creation before publication when the task is cleared', async () => {+ state.row = null;+ state.beforePublish = () => {+ state.session = { ...state.session, clearedAt: 300 };+ };+ await expect(state.deps!.writeCard('task', 'card', record)).rejects.toThrow(+ 'MCP_APP_CARD_UNAVAILABLE',+ );+ expect(state.create).toHaveBeenCalledWith(+ 'task',+ expect.objectContaining({ agentMeta: { mcpApp: true } }),+ expect.objectContaining({ beforePublish: expect.any(Function) }),+ );+ expect(state.create.mock.calls[0][2]).not.toHaveProperty('expectedClearBoundaryMs');+ });+ it.each([+ { result: { content: [{ type: 'text' as const, text: 'Late result' }] } },+ { cancelled: 'Tool execution cancelled' },+ ])('does not recreate a deleted card when completion arrives: %j', async (completion) => {+ state.row = null;+ await expect(+ state.deps!.writeCard('task', 'card', { ...record, ...completion }),+ ).rejects.toThrow('MCP_APP_CARD_UNAVAILABLE');+ expect(state.create).not.toHaveBeenCalled();+ expect(state.broadcast).not.toHaveBeenCalled();+ });+ it('keeps View-only MCP App results in Main while broadcasting public history', async () => {+ const full = { ...record,+ arguments: { private: 'app-input' },+ result: {+ content: [{ type: 'text', text: 'Saved result', _meta: { private: 'block' } }],+ structuredContent: { private: 'structured' },+ _meta: { private: 'view-only' },+ },+ };+ state.row!.content = JSON.stringify({ mcpApp: full });+ state.updateResult = [state.row!];+ await state.deps!.writeCard('task', 'card', full);+ expect(state.broadcast.mock.calls[0]![1].content).toEqual({+ mcpAppHistory: { version: 1, title: 'form', text: 'Saved result' },+ });+ expect(await state.deps!.readCard('task', 'card')).toEqual(full);+ expect(JSON.parse(state.row!.content as string)).toEqual({ mcpApp: full });+ });+ it('allows a new pending card to be created before tool execution', async () => {+ state.row = null;+ await state.deps!.writeCard('task', 'card', record);+ expect(state.create).toHaveBeenCalledWith(+ 'task',+ { clientId: 'card', role: 'assistant', content: { mcpApp: record }, agentMeta: { mcpApp: true } },+ expect.objectContaining({ beforePublish: expect.any(Function) }),+ );+ });+ it('blocks archived tasks and checks tool permission through the existing approval route', async () => {+ state.session.status = 'archived';+ await expect(state.deps!.readCard('task', 'card')).rejects.toThrow(+ 'MCP_APP_SESSION_UNAVAILABLE',+ );+ state.session.status = 'active';+ await state.deps!.authorizeTool(+ 'task',+ record.tool,+ { title: 'edited' },+ new AbortController().signal,+ );+ expect(request).toHaveBeenCalledWith(+ 'task',+ expect.objectContaining({+ kind: 'permission',+ toolName: 'MCP App: form',+ input: { title: 'edited' },+ }),+ expect.any(AbortSignal),+ );+ state.session.permissionMode = 'bypassPermissions';+ request.mockClear();+ await state.deps!.authorizeTool('task', record.tool, {}, new AbortController().signal);+ expect(request).not.toHaveBeenCalled();+ });+ it('checks a real local sender, refuses shared-task guests, and returns only public errors', async () => {+ await expect(+ state.handle!({ sender: { id: 1 } }, 'task', { op: 'unknown', secret: 'must-not-return' }),+ ).rejects.toThrow('[PRECONDITION_FAILED] MCP_APP_INVALID_REQUEST');+ expect(state.trusted).toHaveBeenCalledOnce();+ state.remote = { controllerDeviceId: 'guest', sharedTask: {} };+ await expect(state.handle!({}, 'task', { op: 'open', clientId: 'card' })).rejects.toThrow(+ 'MCP_APP_OWNER_ONLY',+ );+ });+ it('routes remote cards through the dedicated Main control boundary and forbids remote relay pivots', async () => {+ const event = { sender: { id: 1 } };+ await expect(state.handle!(event, 'task', {+ deviceId: 'other-computer', op: 'message', viewId: 'remote-view',+ message: { jsonrpc: '2.0', id: 1, method: 'tools/call' },+ })).rejects.toThrow('MCP_APP_FRAME_REQUIRED');+ expect(state.trusted).toHaveBeenCalledOnce();+ expect(state.invoke).not.toHaveBeenCalled();+ state.remote = { controllerDeviceId: 'phone' };+ await expect(state.handle!({}, 'task', { deviceId: 'other-computer', op: 'open', clientId: 'card' }))+ .rejects.toThrow('MCP_APP_INVALID_REQUEST');+ expect(state.invoke).not.toHaveBeenCalled();+ });+ it('keeps remote RPCs in Main while preserving the incoming Mobile Host contract', async () => {+ const document = { viewId: 'remote-view', html: '<p>Private App</p>', csp: "default-src 'none'",+ prefersBorder: true, policy: { connectDomains: ['https://private-app.example.invalid'] } };+ state.invoke.mockImplementation(async (_device, _channel, _args, options) => {+ options.preSend();+ return { ok: true, result: document };+ });+ vi.mocked(mountRemoteAppDocument).mockReturnValueOnce('local-view');+ expect(await state.handle!({ sender: { id: 1 } }, 'task', {+ deviceId: 'other-computer', op: 'open', clientId: 'card', openId: 'attempt',+ })).toEqual({ viewId: 'local-view', transport: 'sandbox', prefersBorder: true });+ const message = { jsonrpc: '2.0', id: 2, method: 'tools/call' };+ const frame = vi.mocked(mountRemoteAppDocument).mock.calls.at(-1)![2]!;+ await frame({ op: 'message', viewId: 'forged', message });+ expect(state.invoke).toHaveBeenLastCalledWith('other-computer', 'maker:mcp-apps:v1',+ ['task', { op: 'message', viewId: 'remote-view', message }], { preSend: expect.any(Function) });++ state.open.mockResolvedValue(document);+ expect(await state.handle!({ sender: { id: 1 } }, 'task', { op: 'open', clientId: 'card' }))+ .toEqual({ viewId: 'remote-view', transport: 'sandbox', prefersBorder: true });++ // Mobile still reaches the execution Host over the existing same-account channel.+ state.remote = { controllerDeviceId: 'phone' };+ state.open.mockResolvedValue(document);+ expect(await state.handle!({}, 'task', { op: 'open', clientId: 'card' })).toEqual(document);+ expect(state.open).toHaveBeenCalledWith('device:phone', 'task', 'card', {}, undefined);+ await state.handle!({}, 'task', { op: 'message', viewId: 'remote-view', message });+ expect(state.dispatch).toHaveBeenCalledWith('device:phone', 'task', 'remote-view', message);+ });+});diff --git a/apps/desktop/src/main/mcp-apps/__tests__/messageSender.test.ts b/apps/desktop/src/main/mcp-apps/__tests__/messageSender.test.tsnew file mode 100644index 0000000000..e3fbc74f17--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/__tests__/messageSender.test.ts@@ -0,0 +1,181 @@+import { describe, expect, it, vi } from 'vitest';+import type { AgentInputQueuedMessage } from '../../../shared/agentInputQueue.js';+import type { McpAppRecord } from '../../../shared/mcpApps.js';+import { AUTO_REVIEW_DELEGATED_CONTINUATION } from '../../maker-ipc/autoReviewUserIntent.js';+import { appMessageInput, MCP_APP_MESSAGE_CLIENT_PREFIX, MCP_APP_MESSAGE_GUARD, queuedAppMessageGuard, type McpAppMessageGuard } from '../message.js';+import { createAppMessageSender } from '../messageSender.js';++const record: McpAppRecord = {+ version: 1, serverId: 'example', serverRevision: 'revision', resourceUri: 'ui://example/app',+ tool: { name: 'form', inputSchema: { type: 'object' } }, arguments: {},+};+const content = [{ type: 'text', text: '/compact' }];++function fixture(queue: boolean) {+ let owner: object = {}, boundary: number | null = null, visible = true;+ let waitingStage = '';+ let started!: () => void, release!: () => void;+ let barrier: Promise<void>;+ const wait = async (stage: string) => {+ if (stage !== waitingStage) return;+ started();+ await barrier;+ };+ const delivered = vi.fn();+ const sendToAgentAccepted = vi.fn();+ sendToAgentAccepted.mockImplementation(async (+ _id: string, _message: unknown, _create: unknown, options: Record<PropertyKey, unknown>,+ ) => {+ await wait('send');+ await (options[MCP_APP_MESSAGE_GUARD] as McpAppMessageGuard)();+ delivered();+ return { accepted: true };+ });+ const deps = {+ owner: () => owner,+ readClearBoundary: vi.fn(async () => { await wait('session'); return boundary; }),+ restoreQueue: vi.fn(async () => { await wait('queue'); }),+ clearBoundary: () => boundary,+ shouldQueue: () => queue,+ getSessionMeta: vi.fn(async () => { await wait('meta'); return { title: 'Task' }; }),+ createClientId: () => 'input',+ buildQueueItem: vi.fn(async (params: unknown) => {+ await wait('build');+ return params as AgentInputQueuedMessage;+ }),+ enqueue: vi.fn(),+ sendToAgentAccepted,+ };+ const guard = vi.fn(async () => {+ if (!visible) throw new Error('MCP_APP_CARD_UNAVAILABLE');+ });+ const send = createAppMessageSender(deps);+ return {+ deps, guard, delivered, send: () => send('task', record, content, guard),+ revokeCard: () => { visible = false; },+ changeOwner: () => { owner = {}; },+ clearTask: () => { boundary = 100; },+ hold(stage: string) {+ waitingStage = stage;+ const ready = new Promise<void>((resolve) => { started = resolve; });+ barrier = new Promise<void>((resolve) => { release = resolve; });+ return { ready, release: () => release() };+ },+ };+}++describe('MCP App message input and dispatch', () => {+ it.each(['/compact', ' /compact focus', '\n/plugin install', '/'])+ ('escapes App-authored native command %j while preserving its authored history', (text) => {+ const input = appMessageInput([{ type: 'text', text }]);+ expect(input.text.trimStart()).toMatch(/^\\\//);+ expect(input.persistedContent).toBe(text);+ expect(input.blocks[0].text).toBe(input.text);+ });++ it('escapes every text block, including commands supplied through resource-link names', () => {+ const input = appMessageInput([+ { type: 'text', text: '' },+ { type: 'text', text: '/compact' },+ { type: 'resource_link', name: '/extension', uri: 'https://example.org' },+ ]);+ expect(input.blocks.map((block) => block.text)).toEqual([+ '', '\\/compact', '\\/extension: https://example.org',+ ]);+ expect(input.persistedContent).toBe('\n/compact\n/extension: https://example.org');+ });++ it.each([false, true])('keeps Main-stamped provenance and authored history (queue=%s)', async (queue) => {+ const f = fixture(queue);+ await f.send();+ const sourcePlugin = { pluginId: 'mcp-app:example', name: 'example' };+ if (queue) {+ expect(f.deps.buildQueueItem).toHaveBeenCalledWith(expect.objectContaining({+ message: '\\/compact', persistedContent: '/compact', sourcePlugin,+ autoReviewUserText: { kind: 'delegated-continuation' },+ }));+ expect(f.deps.enqueue).toHaveBeenCalledOnce();+ expect(f.deps.sendToAgentAccepted).not.toHaveBeenCalled();+ } else {+ expect(f.deps.sendToAgentAccepted).toHaveBeenCalledWith(+ 'task', { type: 'user', content: [{ type: 'text', text: '\\/compact' }] }, undefined,+ expect.objectContaining({+ [MCP_APP_MESSAGE_GUARD]: expect.any(Function),+ [AUTO_REVIEW_DELEGATED_CONTINUATION]: true,+ persistUserMessage: expect.objectContaining({ content: '/compact', sourcePlugin }),+ }),+ );+ expect(f.delivered).toHaveBeenCalledOnce();+ }+ });++ it.each(['session', 'queue', 'meta', 'build'])+ ('rejects a card revoked during %s preparation before enqueuing it', async (stage) => {+ const f = fixture(true);+ const held = f.hold(stage);+ const rejected = expect(f.send()).rejects.toThrow('MCP_APP_CARD_UNAVAILABLE');+ await held.ready;+ f.revokeCard();+ held.release();+ await rejected;+ expect(f.deps.enqueue).not.toHaveBeenCalled();+ expect(f.deps.sendToAgentAccepted).not.toHaveBeenCalled();+ });++ it('passes a live guard through direct-send preparation instead of accepting a stale View', async () => {+ const f = fixture(false);+ const held = f.hold('send');+ const rejected = expect(f.send()).rejects.toThrow('MCP_APP_CARD_UNAVAILABLE');+ await held.ready;+ f.revokeCard();+ held.release();+ await rejected;+ expect(f.delivered).not.toHaveBeenCalled();+ expect(f.deps.sendToAgentAccepted).toHaveBeenCalledOnce();+ });++ it.each(['owner', 'clear'] as const)('preserves the %s boundary after queued preparation', async (kind) => {+ const f = fixture(true);+ const held = f.hold('build');+ const rejected = expect(f.send()).rejects.toThrow('MCP_APP_CARD_UNAVAILABLE');+ await held.ready;+ if (kind === 'owner') f.changeOwner();+ else f.clearTask();+ held.release();+ await rejected;+ expect(f.deps.enqueue).not.toHaveBeenCalled();+ });++ it('keeps the live grant on a queued message and rejects revocation after enqueue', async () => {+ const f = fixture(true);+ await f.send();+ const item = f.deps.enqueue.mock.calls[0][1];+ expect(item.clientId).toBe(`${MCP_APP_MESSAGE_CLIENT_PREFIX}input`);+ const guard = queuedAppMessageGuard(item);+ expect(guard).toBeTypeOf('function');+ await expect(guard!()).resolves.toBeUndefined();+ f.revokeCard();+ await expect(guard!()).rejects.toThrow('MCP_APP_CARD_UNAVAILABLE');+ });++ it.each(['JSON', 'IPC'])('rejects a queued App grant lost across %s serialization', async (kind) => {+ const f = fixture(true);+ await f.send();+ const item = f.deps.enqueue.mock.calls[0][1];+ const restored = kind === 'JSON' ? JSON.parse(JSON.stringify(item)) : structuredClone(item);+ expect(Object.getOwnPropertySymbols(restored)).toHaveLength(0);+ expect(JSON.stringify(restored)).not.toContain('MCP_APP_MESSAGE_GUARD');+ await expect(queuedAppMessageGuard(restored)!()).rejects.toThrow('MCP_APP_CARD_UNAVAILABLE');+ });++ it('does not create a card guard for ordinary owner queue input', () => {+ expect(queuedAppMessageGuard({ clientId: 'owner-input' })).toBeUndefined();+ expect(queuedAppMessageGuard({ clientId: 'plugin-input', sourcePlugin: { pluginId: 'other-plugin' } })).toBeUndefined();+ });++ it('rejects legacy App queue rows without treating display provenance as a live grant', async () => {+ await expect(queuedAppMessageGuard({+ clientId: 'legacy-input', sourcePlugin: { pluginId: 'mcp-app:example' },+ })!()).rejects.toThrow('MCP_APP_CARD_UNAVAILABLE');+ });+});diff --git a/apps/desktop/src/main/mcp-apps/__tests__/openLifecycle.test.ts b/apps/desktop/src/main/mcp-apps/__tests__/openLifecycle.test.tsnew file mode 100644index 0000000000..aa28bb99c6--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/__tests__/openLifecycle.test.ts@@ -0,0 +1,184 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { McpAppsHost, appServerRevision } from '../host.js';+import type { AppConnection } from '../connection.js';++const hosts: McpAppsHost[] = [];+afterEach(async () => {+ vi.useRealTimers();+ await Promise.all(hosts.splice(0).map((host) => host.reset()));+});+function fixture() {+ const owner = {};+ const config = { id: 'example', url: 'https://mcp.example.invalid', transport: 'http' as const };+ const tool = { name: 'form', inputSchema: { type: 'object' as const }, _meta: { ui: { resourceUri: 'ui://form' } } };+ const record = { version: 1 as const, serverId: config.id, serverRevision: appServerRevision(config), resourceUri: 'ui://form', tool, arguments: {} };+ const resource = vi.fn<AppConnection['resource']>(async () => ({+ result: { contents: [{ uri: record.resourceUri, mimeType: 'text/html;profile=mcp-app', text: '<html>form</html>' }] },+ }));+ const connection = {+ getClient: async () => ({ getServerCapabilities: () => ({}) }),+ tools: async () => [tool], resource, listen: () => () => {}, close: vi.fn(async () => {}),+ } as unknown as AppConnection;+ const disposeDocument = vi.fn();+ const host = new McpAppsHost({ owner: () => owner, config: () => config, readCard: async () => record,+ writeCard: async () => {}, authorizeTool: async () => {}, sendMessage: async () => {},+ connection: () => connection, disposeDocument });+ hosts.push(host);+ return { host, resource, disposeDocument, connection };+}+async function initialize(host: McpAppsHost, viewId: string) {+ await host.dispatch('device:phone', 'task', viewId, {+ jsonrpc: '2.0', id: 1, method: 'ui/initialize', params: {+ protocolVersion: '2026-01-26', appInfo: { name: 'link-test', version: '1' }, appCapabilities: {},+ },+ });+ await host.dispatch('device:phone', 'task', viewId, { jsonrpc: '2.0', method: 'ui/notifications/initialized' });+ await vi.advanceTimersByTimeAsync(0);+}+describe('MCP App open cancellation', () => {+ it('reserves a pending link before its original timeout and accepts its delayed result once', async () => {+ const f = fixture();+ const doc = await f.host.open('device:phone', 'task', 'card', {});+ vi.useFakeTimers();+ await initialize(f.host, doc.viewId);+ await f.host.dispatch('device:phone', 'task', doc.viewId, {+ jsonrpc: '2.0', id: 2, method: 'ui/open-link', params: { url: 'https://example.org/' },+ });+ await vi.advanceTimersByTimeAsync(0);+ const events = await f.host.poll('device:phone', 'task', doc.viewId, 0);+ const link = events.find((event) => event.openLink)!;+ expect(link.openLink).toBeDefined();+ await vi.advanceTimersByTimeAsync(9_999);+ await f.host.authorizeLink('device:phone', 'task', doc.viewId, link.openLink!.id);+ await vi.advanceTimersByTimeAsync(2);+ const delivered = vi.fn();+ const pending = f.host.poll('device:phone', 'task', doc.viewId, link.seq).then(delivered);+ await vi.advanceTimersByTimeAsync(0);+ expect(delivered).not.toHaveBeenCalled();+ f.host.linkResult('device:phone', 'task', doc.viewId, link.openLink!.id, true);+ await vi.advanceTimersByTimeAsync(0);+ await pending;+ expect(delivered.mock.calls[0][0]).toContainEqual(expect.objectContaining({+ message: expect.objectContaining({ id: 2, result: {} }),+ }));+ await expect(f.host.authorizeLink('device:phone', 'task', doc.viewId, link.openLink!.id))+ .rejects.toThrow('MCP_APP_LINK_UNAVAILABLE');+ });+ it('grants a pending link once and expires the bounded reservation if no result arrives', async () => {+ const f = fixture();+ const doc = await f.host.open('device:phone', 'task', 'card', {});+ vi.useFakeTimers();+ await initialize(f.host, doc.viewId);+ await f.host.dispatch('device:phone', 'task', doc.viewId, {+ jsonrpc: '2.0', id: 2, method: 'ui/open-link', params: { url: 'https://example.org/' },+ });+ await vi.advanceTimersByTimeAsync(0);+ const link = (await f.host.poll('device:phone', 'task', doc.viewId, 0)).find((event) => event.openLink)!;+ expect(await f.host.authorizeLink('device:phone', 'task', doc.viewId, link.openLink!.id))+ .toEqual({ authorized: true, validForMs: 30_000 });+ await expect(f.host.authorizeLink('device:phone', 'task', doc.viewId, link.openLink!.id))+ .rejects.toThrow('MCP_APP_LINK_ALREADY_AUTHORIZED');+ await vi.advanceTimersByTimeAsync(30_000);+ const events = await f.host.poll('device:phone', 'task', doc.viewId, link.seq);+ expect(events).toContainEqual(expect.objectContaining({+ message: expect.objectContaining({ id: 2, error: expect.objectContaining({ message: expect.stringContaining('MCP_APP_LINK_OPEN_FAILED') }) }),+ }));+ await expect(f.host.authorizeLink('device:phone', 'task', doc.viewId, link.openLink!.id))+ .rejects.toThrow('MCP_APP_LINK_UNAVAILABLE');+ });+ it('reclaims a reloaded caller quota immediately without closing shared connections', async () => {+ const f = fixture();+ const old = [];+ for (let i = 0; i < 16; i++) old.push(await f.host.open('renderer:1', 'task', 'card', {}));+ const other = await f.host.open('renderer:2', 'task', 'card', {});+ const phone = await f.host.open('device:phone', 'task', 'card', {});+ await expect(f.host.open('renderer:1', 'task', 'card', {})).rejects.toThrow('MCP_APP_VIEW_LIMIT');++ const cleanup = f.host.releaseCaller('renderer:1');+ // No sweep, asynchronous iframe teardown or connection shutdown may delay reuse.+ expect(f.disposeDocument).toHaveBeenCalledTimes(16);+ for (const document of old) {+ expect(f.disposeDocument).toHaveBeenCalledWith(document.viewId);+ expect(() => f.host.context('renderer:1', 'task', document.viewId, {})).toThrow('MCP_APP_VIEW_UNAVAILABLE');+ }+ for (let i = 0; i < 16; i++) await f.host.open('renderer:1', 'task', 'card', {});+ await cleanup;+ expect(() => f.host.context('renderer:2', 'task', other.viewId, {})).not.toThrow();+ expect(() => f.host.context('device:phone', 'task', phone.viewId, {})).not.toThrow();+ expect(f.connection.close).not.toHaveBeenCalled();+ });++ it('cancels only the exiting caller pending loads and refuses their late Views', async () => {+ const f = fixture();+ const data = await f.resource('ui://form');+ let finish!: () => void;+ f.resource.mockImplementationOnce(() => new Promise((resolve) => { finish = () => resolve(data); }));+ const slow = f.host.open('renderer:1', 'task', 'card', {}, 'old');+ const rejected = expect(slow).rejects.toThrow('MCP_APP_OPEN_CANCELLED');+ await vi.waitFor(() => expect(finish).toBeDefined());+ const other = await f.host.open('renderer:2', 'task', 'card', {});+ let finishOther!: () => void;+ f.resource.mockImplementationOnce(() => new Promise((resolve) => { finishOther = () => resolve(data); }));+ const otherPending = f.host.open('device:phone', 'task', 'card', {});+ await vi.waitFor(() => expect(finishOther).toBeDefined());+ await f.host.releaseCaller('renderer:1');+ await rejected;+ finish();+ finishOther();+ expect(await otherPending).toHaveProperty('viewId');+ expect(() => f.host.context('renderer:2', 'task', other.viewId, {})).not.toThrow();+ expect(f.disposeDocument).not.toHaveBeenCalled();+ expect(f.connection.close).not.toHaveBeenCalled();+ for (let i = 0; i < 16; i++) await f.host.open('renderer:1', 'task', 'card', {}, `replacement-${i}`);+ });++ it('cancels a pending open without touching another controller or replaying anything', async () => {+ const f = fixture();+ const healthy = await f.host.open('device:healthy', 'task', 'card', {}, 'same-id');+ const data = await f.resource('ui://form');+ let finish!: () => void;+ f.resource.mockImplementationOnce(() => new Promise((resolve) => { finish = () => resolve(data); }));+ const slow = f.host.open('device:slow', 'task', 'card', {}, 'same-id');+ const rejected = expect(slow).rejects.toThrow('MCP_APP_OPEN_CANCELLED');+ await vi.waitFor(() => expect(finish).toBeDefined());+ await f.host.cancelOpen('device:slow', 'task', 'same-id');+ await rejected;+ finish();+ await Promise.resolve();+ expect(() => f.host.context('device:healthy', 'task', healthy.viewId, { theme: 'dark' })).not.toThrow();+ expect(f.disposeDocument).not.toHaveBeenCalledWith(healthy.viewId);+ expect(f.resource).toHaveBeenCalledTimes(3);+ });+ it('reclaims a View when its open response was lost, scoped to caller and task', async () => {+ const f = fixture();+ const doc = await f.host.open('device:phone', 'task', 'card', {}, 'attempt');+ await f.host.cancelOpen('device:other', 'task', 'attempt');+ await f.host.cancelOpen('device:phone', 'other-task', 'attempt');+ expect(() => f.host.context('device:phone', 'task', doc.viewId, {})).not.toThrow();+ await f.host.cancelOpen('device:phone', 'task', 'attempt');+ expect(f.disposeDocument).toHaveBeenCalledWith(doc.viewId);+ expect(() => f.host.context('device:phone', 'task', doc.viewId, {})).toThrow('MCP_APP_VIEW_UNAVAILABLE');+ });+ it('remembers cancellation that arrives before open and permits a different attempt', async () => {+ const f = fixture();+ await f.host.cancelOpen('device:phone', 'task', 'old');+ await expect(f.host.open('device:phone', 'task', 'card', {}, 'old')).rejects.toThrow('MCP_APP_OPEN_CANCELLED');+ expect(f.resource).not.toHaveBeenCalled();+ expect(await f.host.open('device:phone', 'task', 'card', {}, 'new')).toHaveProperty('viewId');+ });+ it('bounds loading at 90 seconds and never publishes a late document', async () => {+ vi.useFakeTimers();+ const f = fixture();+ let aborted = false;+ f.resource.mockImplementationOnce((_uri, signal) => new Promise((_resolve, reject) => {+ signal!.addEventListener('abort', () => { aborted = true; reject(signal!.reason); });+ }));+ const pending = f.host.open('device:phone', 'task', 'card', {}, 'attempt');+ const rejected = expect(pending).rejects.toThrow('MCP_APP_OPEN_TIMEOUT');+ await vi.advanceTimersByTimeAsync(90_000);+ await rejected;+ expect(aborted).toBe(true);+ expect(f.disposeDocument).not.toHaveBeenCalled();+ expect(f.connection.close).toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/mcp-apps/__tests__/operations.test.ts b/apps/desktop/src/main/mcp-apps/__tests__/operations.test.tsnew file mode 100644index 0000000000..efd4a18944--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/__tests__/operations.test.ts@@ -0,0 +1,119 @@+import { describe, expect, it, vi } from 'vitest';+import { handleMcpAppOperation, handleMcpAppFrameOperation } from '../operations.js';+import type { McpAppsHost } from '../host.js';+function fixture() {+ const document = { viewId: 'view', html: '<!doctype html><p>Private App content</p>',+ csp: "default-src 'none'; connect-src https://private-app.example.invalid", prefersBorder: true,+ policy: { connectDomains: ['https://private-app.example.invalid'] } };+ const api = {+ open: vi.fn(async () => document),+ dispatch: vi.fn(),+ poll: vi.fn(async () => []),+ context: vi.fn(),+ teardown: vi.fn(),+ cancelOpen: vi.fn(),+ displayMode: vi.fn(),+ linkResult: vi.fn(),+ authorizeLink: vi.fn(async () => ({ authorized: true, validForMs: 30_000 })),+ };+ const host = api as unknown as McpAppsHost;+ const local = {+ supply: vi.fn(),+ mount: vi.fn(() => 'mounted'),+ unmount: vi.fn(),+ assertCaller: vi.fn(),+ openLink: vi.fn(async () => {}),+ };+ return { host, api, local, document };+}+describe('task-bound MCP App operations', () => {+ it('binds every operation to the verified caller and exact task', async () => {+ const f = fixture();+ expect(+ await handleMcpAppOperation(+ f.host,+ 'renderer:1',+ 'task',+ { op: 'open', clientId: 'card', context: { theme: 'dark' } },+ f.local,+ ),+ ).toEqual({ viewId: 'view', transport: 'sandbox', prefersBorder: true });+ expect(f.api.open).toHaveBeenCalledWith('renderer:1', 'task', 'card', { theme: 'dark' }, undefined);+ expect(f.local.supply).toHaveBeenCalledWith(f.document, 'renderer:1');+ await handleMcpAppOperation(f.host, 'device:phone', 'task', {+ op: 'poll',+ viewId: 'view',+ after: 4,+ });+ expect(f.api.poll).toHaveBeenCalledWith('device:phone', 'task', 'view', 4);+ await handleMcpAppOperation(f.host, 'device:phone', 'task', {+ op: 'link-result',+ viewId: 'view',+ linkId: 'link',+ success: false,+ });+ expect(f.api.linkResult).toHaveBeenCalledWith('device:phone', 'task', 'view', 'link', false);+ await handleMcpAppOperation(f.host, 'device:phone', 'task', { op: 'cancel-open', openId: 'attempt' });+ expect(f.api.cancelOpen).toHaveBeenCalledWith('device:phone', 'task', 'attempt');+ });+ it('keeps the complete document on the authenticated device transport for Mobile', async () => {+ const f = fixture();+ expect(await handleMcpAppOperation(f.host, 'device:phone', 'task', {+ op: 'open', clientId: 'card',+ })).toEqual(f.document);+ expect(f.api.open).toHaveBeenCalledWith('device:phone', 'task', 'card', {}, undefined);+ expect(f.local.supply).not.toHaveBeenCalled();+ });+ it.each([+ { op: 'message', viewId: 'view', message: { jsonrpc: '2.0', id: 1, method: 'tools/call' } },+ { op: 'poll', viewId: 'view' },+ { op: 'link-result', viewId: 'view', linkId: 'link', success: true },+ { op: 'authorize-link', viewId: 'view', linkId: 'link' },+ { op: 'mount-remote', document: { viewId: 'view', html: '<p>forged</p>' } },+ { op: 'unmount-remote', viewId: 'view' },+ { op: 'open-link', viewId: 'view', url: 'https://example.org' },+ ])('rejects top-Renderer access to the App transport: %j', async (input) => {+ const f = fixture();+ await expect(handleMcpAppOperation(f.host, 'renderer:1', 'task', input, f.local))+ .rejects.toThrow('MCP_APP_FRAME_REQUIRED');+ Object.values(f.api).forEach((call) => expect(call).not.toHaveBeenCalled());+ });+ it('binds frame messages to the Main-held View and limits the channel to transport operations', async () => {+ const f = fixture();+ const message = { jsonrpc: '2.0', id: 1, method: 'tools/list' };+ await handleMcpAppFrameOperation(f.host, 'renderer:1', 'task', 'view',+ { op: 'message', viewId: 'forged-view', sessionId: 'forged-task', message }, f.local.openLink);+ expect(f.api.dispatch).toHaveBeenCalledWith('renderer:1', 'task', 'view', message);+ await expect(handleMcpAppFrameOperation(f.host, 'renderer:1', 'task', 'view',+ { op: 'open', clientId: 'other-card' }, f.local.openLink)).rejects.toThrow('MCP_APP_INVALID_REQUEST');+ expect(f.api.open).not.toHaveBeenCalled();+ });+ it.each([+ { op: 'poll', viewId: 'view', after: -1 },+ { op: 'poll', viewId: 'view', after: 1.5 },+ { op: 'authorize-link', viewId: 'view', linkId: '' },+ { op: 'open', clientId: '' },+ { op: 'open', clientId: 'card', context: { theme: 'other' } },+ { op: 'teardown', viewId: 'view', alreadyNotified: 'true' },+ { op: 'context', viewId: 'view', context: { deviceCapabilities: { touch: 'yes' } } },+ { op: 'display-mode', viewId: 'view', mode: 'window' },+ { op: 'arbitrary-shell', command: 'echo' },+ ])('rejects malformed operations before reaching the Host: %j', async (raw) => {+ const f = fixture();+ await expect(handleMcpAppOperation(f.host, 'renderer:1', 'task', raw, f.local)).rejects.toThrow(+ 'MCP_APP_INVALID_REQUEST',+ );+ Object.values(f.api).forEach((call) => expect(call).not.toHaveBeenCalled());+ });+ it('forbids remote requests from mounting HTML or opening links on the execution computer', async () => {+ const f = fixture();+ for (const raw of [+ { op: 'mount-remote', document: f.document },+ { op: 'unmount-remote', viewId: 'view' },+ { op: 'open-link', viewId: 'view', url: 'https://example.org' },+ ])+ await expect(handleMcpAppOperation(f.host, 'device:phone', 'task', raw)).rejects.toThrow(+ 'MCP_APP_INVALID_REQUEST',+ );+ });+});diff --git a/apps/desktop/src/main/mcp-apps/__tests__/preCallValidation.test.ts b/apps/desktop/src/main/mcp-apps/__tests__/preCallValidation.test.tsnew file mode 100644index 0000000000..41809d279e--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/__tests__/preCallValidation.test.ts@@ -0,0 +1,213 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';+import { CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js';+import type { McpAppRecord } from '../../../shared/mcpApps.js';+import { AppConnection } from '../connection.js';+import { McpAppsHost } from '../host.js';+import { createAppServerProxy } from '../serverProxy.js';+import { setMcpAppsHost, registerAppServer, clearAppServerConfigs } from '../runtime.js';++const cleanup: Array<() => Promise<void>> = [];+const tool = {+ name: 'form',+ inputSchema: { type: 'object' as const },+ _meta: { ui: { resourceUri: 'ui://form' } },+};++afterEach(async () => {+ for (const close of cleanup.splice(0).reverse()) await close();+ clearAppServerConfigs();+ vi.restoreAllMocks();+});++function deferred() {+ let resolve!: () => void;+ const promise = new Promise<void>((done) => {+ resolve = done;+ });+ return { promise, resolve };+}++async function fixture() {+ const config = { id: 'example', url: 'https://mcp.example.invalid', transport: 'http' as const };+ let owner = {};+ const cards = new Map<string, McpAppRecord>();+ const writeCard = vi.fn(async (_session: string, id: string, record: McpAppRecord) => {+ cards.set(id, record);+ });+ const tools = vi.spyOn(AppConnection.prototype, 'tools').mockResolvedValue([tool]);+ const result = { content: [{ type: 'text' as const, text: 'complete' }] };+ const callTool = vi.fn(async () => result);+ vi.spyOn(AppConnection.prototype, 'getClient').mockResolvedValue({+ getServerCapabilities: () => ({ tools: {} }),+ getInstructions: () => undefined,+ callTool,+ } as unknown as Client);+ const host = new McpAppsHost({+ owner: () => owner,+ config: () => config,+ readCard: async (_session, id) => {+ const card = cards.get(id);+ if (!card) throw new Error('MCP_APP_CARD_UNAVAILABLE');+ return card;+ },+ writeCard,+ authorizeTool: async () => {},+ sendMessage: async () => {},+ });+ setMcpAppsHost(host);+ registerAppServer(config.id, () => config);+ const facade = createAppServerProxy(() => config, {+ agentKind: 'codex',+ sessionId: 'task',+ workingDir: '',+ });+ const client = new Client({ name: 'Pre-call fixture', version: '1' });+ cleanup.push(async () => {+ await client.close();+ await facade.close();+ await host.reset();+ });+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ await facade.connect(serverTransport);+ await client.connect(clientTransport);+ return {+ client,+ tools,+ cards,+ writeCard,+ callTool,+ result,+ revoke(kind: 'owner' | 'server' | 'config') {+ if (kind === 'owner') owner = {};+ if (kind === 'server') clearAppServerConfigs();+ if (kind === 'config')+ registerAppServer(config.id, () => ({ ...config, url: 'https://changed.example.invalid' }));+ },+ };+}++describe('MCP App pre-call validation and card finalization', () => {+ it.each(['owner', 'server', 'config'] as const)(+ 'discards the model tool list after %s revocation during discovery',+ async (kind) => {+ const f = await fixture();+ const discovery = deferred();+ f.tools.mockImplementationOnce(async () => {+ await discovery.promise;+ return [tool];+ });+ const rejected = expect(f.client.listTools()).rejects.toThrow('MCP_APP_');+ await vi.waitFor(() => expect(f.tools).toHaveBeenCalledOnce());+ f.revoke(kind);+ discovery.resolve();+ await rejected;+ expect(f.tools).toHaveBeenCalledOnce();+ expect(f.writeCard).not.toHaveBeenCalled();+ expect(f.callTool).not.toHaveBeenCalled();+ },+ );++ it('returns the model tool list once after slow discovery while still authorized', async () => {+ const f = await fixture();+ const discovery = deferred();+ f.tools.mockImplementationOnce(async () => {+ await discovery.promise;+ return [tool];+ });+ const pending = f.client.listTools();+ await vi.waitFor(() => expect(f.tools).toHaveBeenCalledOnce());+ discovery.resolve();+ await expect(pending).resolves.toEqual({ tools: [tool] });+ expect(f.tools).toHaveBeenCalledOnce();+ });++ it.each(['owner', 'server', 'config'] as const)(+ 'does not create a pending card after %s revocation during tool discovery',+ async (kind) => {+ const f = await fixture();+ const discovery = deferred();+ f.tools.mockImplementationOnce(async () => {+ await discovery.promise;+ return [tool];+ });+ const rejected = expect(f.client.callTool({ name: tool.name })).rejects.toThrow('MCP_APP_');+ await vi.waitFor(() => expect(f.tools).toHaveBeenCalledOnce());+ f.revoke(kind);+ discovery.resolve();+ await rejected;+ expect(f.writeCard).not.toHaveBeenCalled();+ expect(f.cards.size).toBe(0);+ expect(f.callTool).not.toHaveBeenCalled();+ },+ );++ it.each(['server', 'config'] as const)(+ 'finalizes the pending card after %s revocation while it is being stored',+ async (kind) => {+ const f = await fixture();+ const persistence = deferred();+ f.writeCard.mockImplementationOnce(async (_session, id, record) => {+ f.cards.set(id, record);+ await persistence.promise;+ });+ const rejected = expect(f.client.callTool({ name: tool.name })).rejects.toThrow(+ 'MCP_APP_SERVER_CHANGED',+ );+ await vi.waitFor(() => expect(f.writeCard).toHaveBeenCalledOnce());+ f.revoke(kind);+ persistence.resolve();+ await rejected;+ expect(f.callTool).not.toHaveBeenCalled();+ expect(f.writeCard).toHaveBeenCalledTimes(2);+ expect([...f.cards.values()]).toEqual([+ expect.objectContaining({+ result: {+ isError: true,+ content: [{ type: 'text', text: 'MCP App tool execution failed' }],+ },+ }),+ ]);+ },+ );++ it('records cancellation during the initial card write without calling or replaying the tool', async () => {+ const f = await fixture();+ const persistence = deferred();+ f.writeCard.mockImplementationOnce(async (_session, id, record) => {+ f.cards.set(id, record);+ await persistence.promise;+ });+ const abort = new AbortController();+ const rejected = expect(+ f.client.callTool({ name: tool.name }, CallToolResultSchema, { signal: abort.signal }),+ ).rejects.toThrow();+ await vi.waitFor(() => expect(f.writeCard).toHaveBeenCalledOnce());+ abort.abort();+ await rejected;+ persistence.resolve();+ await vi.waitFor(() => expect(f.writeCard).toHaveBeenCalledTimes(2));+ expect([...f.cards.values()]).toEqual([+ expect.objectContaining({ cancelled: 'Tool execution cancelled' }),+ ]);+ expect(f.callTool).not.toHaveBeenCalled();+ });++ it('executes once and records the result after a slow authorized card write', async () => {+ const f = await fixture();+ const persistence = deferred();+ f.writeCard.mockImplementationOnce(async (_session, id, record) => {+ f.cards.set(id, record);+ await persistence.promise;+ });+ const pending = f.client.callTool({ name: tool.name });+ await vi.waitFor(() => expect(f.writeCard).toHaveBeenCalledOnce());+ expect(f.callTool).not.toHaveBeenCalled();+ persistence.resolve();+ await expect(pending).resolves.toEqual(f.result);+ expect(f.callTool).toHaveBeenCalledOnce();+ expect(f.writeCard).toHaveBeenCalledTimes(2);+ expect([...f.cards.values()]).toEqual([expect.objectContaining({ result: f.result })]);+ });+});diff --git a/apps/desktop/src/main/mcp-apps/__tests__/protocol.test.ts b/apps/desktop/src/main/mcp-apps/__tests__/protocol.test.tsnew file mode 100644index 0000000000..30113a6ae4--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/__tests__/protocol.test.ts@@ -0,0 +1,199 @@+import { describe, expect, it } from 'vitest';+import type { Tool } from '@modelcontextprotocol/sdk/types.js';+import type { McpAppRecord } from '../../../shared/mcpApps.js';+import {+ appCsp,+ boundedAppRecord,+ readAppResource,+ safeAppLink,+ toolVisibleTo,+ uiToolUri,+ MCP_APPS_MAX_BYTES,+ MCP_APPS_MAX_CARD_BYTES,+} from '../protocol.js';++const tool = (ui: unknown): Tool => ({+ name: 'example',+ inputSchema: { type: 'object' },+ _meta: { ui },+});+const uri = 'ui://example/app.html';+const card = (result: NonNullable<McpAppRecord['result']>): McpAppRecord => ({+ version: 1,+ serverId: 'example',+ serverRevision: 'revision',+ resourceUri: uri,+ tool: tool({ resourceUri: uri }),+ arguments: {},+ result,+});+describe('standard MCP Apps metadata and policy', () => {+ it('preserves a complete card at the byte limit and replaces a result one byte over it', () => {+ const record = card({ content: [{ type: 'text', text: '' }], _meta: { viewOnly: true } });+ const overhead = Buffer.byteLength(JSON.stringify({ mcpApp: record }));+ record.result!.content = [+ { type: 'text', text: 'x'.repeat(MCP_APPS_MAX_CARD_BYTES - overhead) },+ ];+ expect(Buffer.byteLength(JSON.stringify({ mcpApp: record }))).toBe(MCP_APPS_MAX_CARD_BYTES);+ expect(boundedAppRecord(record)).toBe(record);+ const oversized = {+ ...record,+ result: {+ ...record.result!,+ content: [{ type: 'text', text: 'x'.repeat(MCP_APPS_MAX_CARD_BYTES - overhead + 1) }],+ },+ };+ expect(Buffer.byteLength(JSON.stringify({ mcpApp: oversized }))).toBe(+ MCP_APPS_MAX_CARD_BYTES + 1,+ );+ expect(boundedAppRecord(oversized).result).toEqual({+ isError: true,+ content: [{ type: 'text', text: 'MCP_APP_RESULT_TOO_LARGE' }],+ });+ expect(record.result!._meta).toEqual({ viewOnly: true });+ });+ it.each(['multibyte text', 'View-only metadata'] as const)(+ 'includes %s in the serialized byte budget',+ (kind) => {+ const record = card(+ kind === 'multibyte text'+ ? { content: [{ type: 'text', text: '汉'.repeat(MCP_APPS_MAX_CARD_BYTES / 2) }] }+ : {+ content: [{ type: 'text', text: 'small' }],+ _meta: { viewOnly: 'x'.repeat(MCP_APPS_MAX_CARD_BYTES) },+ },+ );+ if (kind === 'multibyte text')+ expect(JSON.stringify({ mcpApp: record }).length).toBeLessThan(MCP_APPS_MAX_CARD_BYTES);+ expect(boundedAppRecord(record).result).toEqual({+ isError: true,+ content: [{ type: 'text', text: 'MCP_APP_RESULT_TOO_LARGE' }],+ });+ },+ );+ it('bounds the whole card when input and result each fit separately', () => {+ const record = card({+ content: [{ type: 'text', text: 'x'.repeat(MCP_APPS_MAX_CARD_BYTES / 2) }],+ });+ record.arguments = { draft: 'y'.repeat(MCP_APPS_MAX_CARD_BYTES / 2) };+ expect(Buffer.byteLength(JSON.stringify(record.result))).toBeLessThan(MCP_APPS_MAX_CARD_BYTES);+ const bounded = boundedAppRecord(record);+ expect(bounded.arguments).toEqual(record.arguments);+ expect(bounded.result!.isError).toBe(true);+ expect(Buffer.byteLength(JSON.stringify({ mcpApp: bounded }))).toBeLessThanOrEqual(+ MCP_APPS_MAX_CARD_BYTES,+ );+ });+ it('uses the standard same-origin base URI default for omitted and empty declarations', () => {+ expect(appCsp().header).toContain("base-uri 'self'");+ expect(appCsp({ csp: { baseUriDomains: [] } }).header).toContain("base-uri 'self'");+ expect(appCsp({ csp: { baseUriDomains: ['https://assets.example.org'] } }).header).toContain(+ 'base-uri https://assets.example.org',+ );+ });+ it('defaults tools to both audiences and enforces explicit visibility', () => {+ expect(toolVisibleTo(tool({}), 'app')).toBe(true);+ expect(toolVisibleTo(tool({}), 'model')).toBe(true);+ expect(toolVisibleTo(tool({ visibility: ['app'] }), 'model')).toBe(false);+ expect(toolVisibleTo(tool({ visibility: ['model'] }), 'app')).toBe(false);+ expect(toolVisibleTo(tool({ visibility: 'app' }), 'app')).toBe(false);+ expect(uiToolUri(tool({ resourceUri: uri }))).toBe(uri);+ expect(uiToolUri({ ...tool({}), _meta: { 'ui/resourceUri': uri } })).toBe(uri);+ expect(uiToolUri(tool({ resourceUri: 'https://example.org/app' }))).toBeUndefined();+ });+ it('reads text or base64 HTML and honors read metadata before list metadata', () => {+ const html = '<!doctype html><html><body>标准应用</body></html>';+ for (const data of [{ text: html }, { blob: Buffer.from(html).toString('base64') }]) {+ expect(+ readAppResource(+ { contents: [{ uri, mimeType: 'text/html;profile=mcp-app', ...data }] },+ uri,+ { prefersBorder: false },+ ),+ ).toEqual({ html, meta: { prefersBorder: false } });+ }+ expect(+ readAppResource(+ {+ contents: [+ {+ uri,+ mimeType: 'text/html;profile=mcp-app',+ text: html,+ _meta: { ui: { prefersBorder: true } },+ },+ ],+ },+ uri,+ { prefersBorder: false },+ ).meta.prefersBorder,+ ).toBe(true);+ });+ it('rejects wrong URI, MIME, invalid base64 and oversized resource bytes', () => {+ expect(() =>+ readAppResource({ contents: [{ uri, text: '', mimeType: 'text/html' }] }, uri),+ ).toThrow('MCP_APP_RESOURCE_MISSING');+ expect(() =>+ readAppResource(+ { contents: [{ uri: 'ui://other', text: '', mimeType: 'text/html;profile=mcp-app' }] },+ uri,+ ),+ ).toThrow('MCP_APP_RESOURCE_MISSING');+ expect(() =>+ readAppResource(+ { contents: [{ uri, blob: '!!invalid!!', mimeType: 'text/html;profile=mcp-app' }] },+ uri,+ ),+ ).toThrow('MCP_APP_INVALID_RESOURCE');+ expect(() =>+ readAppResource(+ {+ contents: [+ {+ uri,+ text: '汉'.repeat(MCP_APPS_MAX_BYTES / 3 + 1),+ mimeType: 'text/html;profile=mcp-app',+ },+ ],+ },+ uri,+ ),+ ).toThrow('MCP_APP_RESOURCE_TOO_LARGE');+ });+ it('restricts omitted domains and keeps each declared domain in its directive', () => {+ expect(appCsp().header).toContain("connect-src 'none'; frame-src 'none'; base-uri 'self'");+ const policy = appCsp({+ csp: {+ connectDomains: ['https://api.example.org', 'wss://*.example.org:443'],+ resourceDomains: ['https://cdn.example.org'],+ frameDomains: ['https://frame.example.org'],+ baseUriDomains: ['https://base.example.org'],+ },+ });+ expect(policy.header).toContain('connect-src https://api.example.org wss://*.example.org:443');+ expect(policy.header).toContain('frame-src https://frame.example.org');+ expect(policy.header).toContain('base-uri https://base.example.org');+ expect(policy.header).not.toContain("'unsafe-eval'");+ });+ it.each([+ 'https://example.org; script-src *',+ '*',+ 'file://local',+ 'data:',+ 'https://user:[email protected]',+ 'https://example.org/path',+ "https://example.org 'unsafe-eval'",+ 'https://example.org:99999',+ ])('rejects CSP source injection: %s', (source) => {+ expect(() => appCsp({ csp: { connectDomains: [source] } })).toThrow();+ });+ it.each([+ 'file:///C:/secret',+ 'javascript:alert(1)',+ 'data:text/html,x',+ 'https://user:[email protected]',+ 'not a URL',+ ])('rejects privileged or malformed links: %s', (url) => {+ expect(() => safeAppLink(url)).toThrow('MCP_APP_INVALID_LINK');+ });+});diff --git a/apps/desktop/src/main/mcp-apps/__tests__/remoteAuthorization.test.ts b/apps/desktop/src/main/mcp-apps/__tests__/remoteAuthorization.test.tsnew file mode 100644index 0000000000..156cf76a6e--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/__tests__/remoteAuthorization.test.ts@@ -0,0 +1,375 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import type { Logger } from '@cindy/maker-core';+import { getLiziMcpSessionContext } from '@cindy/mcps';+import { registerAppServer, clearAppServerConfigs } from '../runtime.js';+import {+ startCodexHttpBridge,+ selectRemoteInjectableServerNames,+ type CodexHttpBridge,+} from '../../mcp-integrations/codexHttpBridge.js';+import { CODEX_ALLOWED_BUILTIN_PLUGIN_IDS_KEY } from '../../mcp-integrations/codexBuiltinToolPolicy.js';+let bridge: CodexHttpBridge | undefined;+const receivedNotification = vi.fn();+const log = {+ trace() {},+ debug() {},+ info() {},+ warn() {},+ error() {},+ fatal() {},+ child() {+ return this;+ },+} as Logger;+function server() {+ const server = new McpServer({ name: 'example', version: '1' });+ server.server.fallbackNotificationHandler = async (notification) => {+ receivedNotification(notification, getLiziMcpSessionContext()?.sessionInstanceId);+ };+ server.tool('context', {}, async () => ({+ content: [{ type: 'text', text: getLiziMcpSessionContext()?.sessionInstanceId ?? 'unbound' }],+ }));+ return server;+}+const createAppServer = vi.fn(server);+afterEach(async () => {+ clearAppServerConfigs();+ await bridge?.shutdown();+ bridge = undefined;+ receivedNotification.mockClear();+ createAppServer.mockClear();+});+const headers = {+ authorization: 'Bearer invalid-test-only-remote-token',+ accept: 'application/json, text/event-stream',+ 'content-type': 'application/json',+};+async function fixture(vendorOptions: Record<string, unknown> = {}) {+ for (const id of ['example', 'not-mounted'])+ registerAppServer(id, () => ({ id, url: 'http://127.0.0.1:1/mcp', transport: 'http' }));+ bridge = await startCodexHttpBridge({+ serverFactories: { example: createAppServer, 'not-mounted': server, cindy_ssh: server },+ appServerNames: ['example'],+ additionalBearerTokens: () => ['invalid-test-only-remote-token'],+ logger: log,+ });+ const setPolicy = (vendorOptions: Record<string, unknown>) => bridge!.registerSessionCtx('task', {+ agentKind: 'claude-code',+ sessionId: 'task',+ sessionInstanceId: 'instance',+ workingDir: '/remote',+ remoteHostId: 'host',+ vendorOptions,+ });+ setPolicy(vendorOptions);+ const base = bridge.url('example');+ const bound = base + '?session=task&instance=instance';+ const init = await fetch(bound, {+ method: 'POST',+ headers,+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'initialize',+ params: {+ protocolVersion: '2024-11-05',+ capabilities: {},+ clientInfo: { name: 'test', version: '1' },+ },+ }),+ });+ expect(init.status).toBe(200);+ const id = init.headers.get('mcp-session-id')!;+ await init.text();+ const request = async (url: string, body: unknown) =>+ fetch(url, {+ method: 'POST',+ headers: { ...headers, 'mcp-session-id': id },+ body: JSON.stringify(body),+ });+ return { base, bound, request, setPolicy };+}+const list = { jsonrpc: '2.0', id: 2, method: 'tools/list' };+const call = {+ jsonrpc: '2.0',+ id: 3,+ method: 'tools/call',+ params: { name: 'context', arguments: {} },+};+describe('MCP Apps over the existing remote bridge', () => {+ it('permits the configured custom server only with the actual Session instance', async () => {+ const f = await fixture();+ const reply = await f.request(f.bound, call);+ expect(reply.status).toBe(200);+ expect(await reply.text()).toContain('instance');+ for (const url of [f.base, f.base + '?session=task', f.base + '?session=task&instance=stale']) {+ const denied = await f.request(url, call);+ expect(denied.status).toBe(401);+ await denied.text();+ }+ });+ it('rejects unbound discovery, resource access and a batch containing execution', async () => {+ const f = await fixture();+ const discovery = await f.request(f.base, list);+ expect(discovery.status).toBe(401);+ await discovery.text();+ for (const body of [+ { jsonrpc: '2.0', id: 5, method: 'resources/read', params: { uri: 'ui://example/app' } },+ [list, call],+ ]) {+ const denied = await f.request(f.base, body);+ expect(denied.status).toBe(401);+ await denied.text();+ }+ });+ it('requires a Session for standard and extension notifications, including mixed batches', async () => {+ const f = await fixture();+ const notifications = [+ { jsonrpc: '2.0', method: 'notifications/cancelled', params: { requestId: 42 } },+ { jsonrpc: '2.0', method: 'notifications/progress', params: { progressToken: 'test', progress: 1 } },+ { jsonrpc: '2.0', method: 'example/side-effect', params: { value: 'test' } },+ ];+ for (const body of [...notifications, [list, notifications[2]]]) {+ const denied = await f.request(f.base, body);+ expect(denied.status).toBe(401);+ await denied.text();+ }+ expect(receivedNotification).not.toHaveBeenCalled();+ });+ it('requires a bound route for the initialization notification as well', async () => {+ const f = await fixture();+ const initialized = { jsonrpc: '2.0', method: 'notifications/initialized' };+ const unbound = await f.request(f.base, initialized);+ expect(unbound.status).toBe(401);+ await unbound.text();+ const allowed = await f.request(f.bound, initialized);+ expect(allowed.status).toBe(202);+ await allowed.text();+ // A method name alone must not turn a request into a handshake exemption.+ const denied = await f.request(f.base, { ...initialized, id: 4 });+ expect(denied.status).toBe(401);+ await denied.text();+ });+ it('forwards a notification with the verified Session context and rejects revoked routes', async () => {+ const f = await fixture();+ const notification = { jsonrpc: '2.0', method: 'example/side-effect', params: { value: 'test' } };+ const allowed = await f.request(f.bound, notification);+ expect(allowed.status).toBe(202);+ await allowed.text();+ await vi.waitFor(() => expect(receivedNotification).toHaveBeenCalledWith(notification, 'instance'));+ receivedNotification.mockClear();+ for (const url of [f.base + '?session=task', f.base + '?session=task&instance=stale']) {+ const denied = await f.request(url, notification);+ expect(denied.status).toBe(401);+ await denied.text();+ }+ bridge!.unregisterSessionCtx('task');+ const revoked = await f.request(f.bound, notification);+ expect(revoked.status).toBe(401);+ await revoked.text();+ expect(receivedNotification).not.toHaveBeenCalled();+ });+ it('enforces the frozen custom-server mount for notifications as well', async () => {+ const f = await fixture();+ f.setPolicy({+ [CODEX_ALLOWED_BUILTIN_PLUGIN_IDS_KEY]: [],+ cindyRuntimeMcpServerNames: [],+ });+ const notification = { jsonrpc: '2.0', method: 'example/side-effect' };+ const denied = await f.request(f.bound, notification);+ expect(denied.status).toBe(403);+ await denied.text();+ expect(receivedNotification).not.toHaveBeenCalled();+ });+ it('never exposes unrelated local servers or a custom server absent from this bridge', async () => {+ const f = await fixture();+ for (const name of ['not-mounted', 'cindy_ssh']) {+ const denied = await f.request(bridge!.url(name), list);+ expect(denied.status).toBe(403);+ await denied.text();+ }+ clearAppServerConfigs();+ const revoked = await f.request(f.bound, call);+ expect(revoked.status).toBe(403);+ await revoked.text();+ });+ it('applies frozen Bot policy to discovery and execution together', async () => {+ const f = await fixture();+ f.setPolicy({+ [CODEX_ALLOWED_BUILTIN_PLUGIN_IDS_KEY]: [],+ cindyRuntimeMcpServerNames: [],+ });+ for (const body of [list, call]) {+ const denied = await f.request(f.bound, body);+ expect(denied.status).toBe(403);+ await denied.text();+ }+ bridge!.registerSessionCtx('task', {+ agentKind: 'claude-code',+ sessionId: 'task',+ sessionInstanceId: 'instance',+ workingDir: '/remote',+ remoteHostId: 'host',+ vendorOptions: {+ [CODEX_ALLOWED_BUILTIN_PLUGIN_IDS_KEY]: [],+ cindyRuntimeMcpServerNames: ['example'],+ },+ });+ for (const body of [list, call]) {+ const allowed = await f.request(f.bound, body);+ expect(allowed.status).toBe(200);+ await allowed.text();+ }+ });+ it.each(['?session=task', '?session=task&instance=instance'])(+ 'rejects scoped Bot initialization before creating an excluded facade: %s',+ async (query) => {+ const f = await fixture();+ f.setPolicy({+ [CODEX_ALLOWED_BUILTIN_PLUGIN_IDS_KEY]: [],+ cindyRuntimeMcpServerNames: [],+ });+ const created = createAppServer.mock.calls.length;+ const initialize = {+ jsonrpc: '2.0', id: 1, method: 'initialize',+ params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'test', version: '1' } },+ };+ const denied = await fetch(f.base + query, { method: 'POST', headers, body: JSON.stringify(initialize) });+ expect(denied.status).toBe(403);+ expect(await denied.text()).toBe('MCP server is not mounted for this Session');+ expect(createAppServer).toHaveBeenCalledTimes(created);+ f.setPolicy({+ [CODEX_ALLOWED_BUILTIN_PLUGIN_IDS_KEY]: [],+ cindyRuntimeMcpServerNames: ['example'],+ });+ const allowed = await fetch(f.base + query, { method: 'POST', headers, body: JSON.stringify(initialize) });+ expect(allowed.status).toBe(200);+ await allowed.text();+ expect(createAppServer).toHaveBeenCalledTimes(created + 1);+ },+ );+ it('does not create a credentialed facade for a process-wide remote App URL', async () => {+ const f = await fixture();+ const created = createAppServer.mock.calls.length;+ const response = await fetch(f.base, {+ method: 'POST', headers, body: JSON.stringify({+ jsonrpc: '2.0', id: 1, method: 'initialize',+ params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'test', version: '1' } },+ }),+ });+ expect(response.status).toBe(401);+ await response.text();+ expect(createAppServer).toHaveBeenCalledTimes(created);+ });+ it('enforces the same mount boundary for local Codex primary-token discovery and execution', async () => {+ const f = await fixture();+ const localHeaders = { ...headers, authorization: `Bearer ${bridge!.token}` };+ const url = f.base + '?instance=local-instance';+ const context = {+ agentKind: 'codex' as const, sessionId: 'local-task', sessionInstanceId: 'local-instance',+ workingDir: '/local',+ vendorOptions: { [CODEX_ALLOWED_BUILTIN_PLUGIN_IDS_KEY]: [], cindyRuntimeMcpServerNames: [] as string[] },+ };+ const initialize = {+ jsonrpc: '2.0', id: 1, method: 'initialize',+ params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'test', version: '1' } },+ };+ const created = createAppServer.mock.calls.length;+ const unbound = await fetch(f.base, { method: 'POST', headers: localHeaders, body: JSON.stringify(initialize) });+ expect(unbound.status).toBe(401);+ await unbound.text();+ await bridge!.withDiscoveryContext(context, async () => {+ const excluded = await fetch(url, { method: 'POST', headers: localHeaders, body: JSON.stringify(initialize) });+ expect(excluded.status).toBe(403);+ await excluded.text();+ });+ expect(createAppServer).toHaveBeenCalledTimes(created);+ context.vendorOptions.cindyRuntimeMcpServerNames = ['example'];+ let id = '';+ const request = async (body: unknown) => fetch(url, {+ method: 'POST', headers: { ...localHeaders, 'mcp-session-id': id }, body: JSON.stringify(body),+ });+ await bridge!.withDiscoveryContext(context, async () => {+ const response = await fetch(url, { method: 'POST', headers: localHeaders, body: JSON.stringify(initialize) });+ expect(response.status).toBe(200);+ id = response.headers.get('mcp-session-id')!;+ await response.text();+ const listed = await request(list);+ expect(listed.status).toBe(200);+ await listed.text();+ const premature = await request(call);+ expect(premature.status).toBe(401);+ await premature.text();+ });+ bridge!.registerThreadContext('local-thread', context);+ const called = await request(call);+ expect(called.status).toBe(200);+ expect(await called.text()).toContain('local-instance');+ context.vendorOptions.cindyRuntimeMcpServerNames = [];+ for (const body of [list, call]) {+ const excluded = await request(body);+ expect(excluded.status).toBe(403);+ await excluded.text();+ }+ });+ it('binds remote Codex startup discovery to its frozen Session and revokes the lease', async () => {+ const f = await fixture();+ const url = f.base + '?instance=codex-instance';+ const context = {+ agentKind: 'codex' as const, sessionId: 'codex-task', sessionInstanceId: 'codex-instance',+ workingDir: '/remote', remoteHostId: 'host',+ vendorOptions: { [CODEX_ALLOWED_BUILTIN_PLUGIN_IDS_KEY]: [], cindyRuntimeMcpServerNames: [] as string[] },+ };+ const initialize = {+ jsonrpc: '2.0', id: 1, method: 'initialize',+ params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'test', version: '1' } },+ };+ const created = createAppServer.mock.calls.length;+ await bridge!.withDiscoveryContext(context, async () => {+ const denied = await fetch(url, { method: 'POST', headers, body: JSON.stringify(initialize) });+ expect(denied.status).toBe(403);+ await denied.text();+ expect(createAppServer).toHaveBeenCalledTimes(created);+ });+ context.vendorOptions.cindyRuntimeMcpServerNames = ['example'];+ let id = '';+ const request = async (body: unknown) => fetch(url, {+ method: 'POST', headers: { ...headers, 'mcp-session-id': id }, body: JSON.stringify(body),+ });+ await bridge!.withDiscoveryContext(context, async () => {+ const response = await fetch(url, { method: 'POST', headers, body: JSON.stringify(initialize) });+ expect(response.status).toBe(200);+ id = response.headers.get('mcp-session-id')!;+ await response.text();+ const discovery = await request(list);+ expect(discovery.status).toBe(200);+ expect(await discovery.text()).toContain('context');+ const execution = await request(call);+ expect(execution.status).toBe(401);+ await execution.text();+ });+ const expired = await request(list);+ expect(expired.status).toBe(401);+ await expired.text();+ bridge!.registerThreadContext('codex-thread', context);+ const execution = await request(call);+ expect(execution.status).toBe(200);+ expect(await execution.text()).toContain('codex-instance');+ bridge!.unregisterThreadContext('codex-thread', 'codex-instance');+ const revoked = await request(list);+ expect(revoked.status).toBe(401);+ await revoked.text();+ });+ it('keeps injection inside both the configured and frozen custom-server sets', async () => {+ await fixture();+ const gates = { collabEnabled: false, memoryEnabled: false };+ expect(selectRemoteInjectableServerNames(['example', 'cindy_ssh'], gates)).toEqual(['example']);+ expect(+ selectRemoteInjectableServerNames(['example'], { ...gates, appServerNames: [] }),+ ).toEqual([]);+ expect(+ selectRemoteInjectableServerNames(['example'], { ...gates, appServerNames: ['example'] }),+ ).toEqual(['example']);+ });+});diff --git a/apps/desktop/src/main/mcp-apps/__tests__/remoteViews.test.ts b/apps/desktop/src/main/mcp-apps/__tests__/remoteViews.test.tsnew file mode 100644index 0000000000..1fa3848b60--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/__tests__/remoteViews.test.ts@@ -0,0 +1,340 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { readFileSync } from 'node:fs';+import ts from 'typescript';+import type { McpAppDocument, McpAppSandboxView } from '../../../shared/mcpApps.js';+const state = vi.hoisted(() => ({+ next: 0,+ mounts: new Map<string, { caller: string; document: McpAppDocument; frame: (raw: unknown) => Promise<unknown>; dispose: () => void }>(),+}));+vi.mock('../sandboxProtocol.js', () => ({+ mountRemoteAppDocument(document: McpAppDocument, caller: string, frame: (raw: unknown) => Promise<unknown>, dispose: () => void) {+ const id = `local-${++state.next}`;+ state.mounts.set(id, { caller, document, frame, dispose });+ return id;+ },+ assertMcpAppDocumentCaller(id: string, caller: string) {+ if (state.mounts.get(id)?.caller !== caller) throw new Error('MCP_APP_VIEW_UNAVAILABLE');+ },+ unmountRemoteAppDocument(id: string, caller: string) {+ const entry = state.mounts.get(id);+ if (entry?.caller !== caller) throw new Error('MCP_APP_VIEW_UNAVAILABLE');+ state.mounts.delete(id);+ entry.dispose();+ },+}));+import { RemoteMcpAppViews } from '../remoteViews.js';+const document = { viewId: 'remote-view', html: '<p>Private server-authored App</p>',+ csp: "default-src 'none'; connect-src https://private-app.example.invalid", prefersBorder: true,+ policy: { connectDomains: ['https://private-app.example.invalid'] } };+// Exercise the production close generation without starting Electron's device-link singleton.+const linkSource = ts.createSourceFile('index.ts', readFileSync(new URL('../../device-link/index.ts', import.meta.url), 'utf8'), ts.ScriptTarget.Latest, true);+const closeCode = ts.transpileModule(linkSource.statements.filter((node): node is ts.FunctionDeclaration =>+ ts.isFunctionDeclaration(node) && ['getRemoteLinkCloseEpoch', 'closeRemoteLink'].includes(node.name?.text ?? ''))+ .map((node) => node.getText(linkSource).replace(/^export /, '')).join('\n'), {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+}).outputText;+function linkFixture(): { closeEpoch: (device: string) => number; close: (device: string) => void; closeLink: ReturnType<typeof vi.fn> } {+ const closeLink = vi.fn();+ const deps = {+ openLinkCloseEpochs: new Map<string, number>(), openLinkInFlight: new Map(),+ invalidatePluginOauth: vi.fn(), transportTimeoutReopen: { cancel: vi.fn() },+ cancelSubscriptionReplay: vi.fn(), client: { closeLink },+ };+ const api = new Function(...Object.keys(deps), closeCode ++ '; return { closeEpoch: getRemoteLinkCloseEpoch, close: closeRemoteLink };')(...Object.values(deps));+ return { ...api, closeLink };+}+function fixture() {+ let owner: object | undefined = {};+ const link = linkFixture();+ const invoke = vi.fn(async (_device: string, _session: string, input: Record<string, unknown>, preSend: () => void): Promise<unknown> => {+ preSend();+ if (input.op === 'open') return document;+ if (input.op === 'poll') return [];+ return {};+ });+ const openLink = vi.fn(async () => {});+ const views = new RemoteMcpAppViews({ owner: () => owner, closeEpoch: link.closeEpoch, invoke, openLink });+ const control = (input: Record<string, unknown>, caller = 'renderer:1', device = 'device-a', session = 'task') =>+ views.control(caller, device, session, input);+ const open = async () => await control({ op: 'open', clientId: 'card', openId: 'attempt', context: {} }) as McpAppSandboxView;+ return { invoke, openLink, views, control, open, link, changeOwner: () => { owner = {}; } };+}+beforeEach(() => { state.mounts.clear(); state.next = 0; });+afterEach(() => { vi.restoreAllMocks(); vi.useRealTimers(); });++describe('Main-bound remote MCP App Views', () => {+ it.each(['sleeping', 'in-flight failure', 'in-flight success'])(+ 'never reconnects an explicitly closed View after a %s poll, including later frame calls and cleanup', async (stage) => {+ const f = fixture();+ const local = await f.open();+ const other = await f.control({ op: 'open', clientId: 'other' }, 'renderer:2', 'device-b') as McpAppSandboxView;+ const frame = state.mounts.get(local.viewId)!.frame;+ const otherFrame = state.mounts.get(other.viewId)!.frame;+ vi.useFakeTimers();+ let finish!: () => void;+ f.invoke.mockImplementationOnce(() => stage === 'sleeping'+ ? Promise.reject(new Error('[DEVICE_LINK_TIMEOUT] temporary'))+ : new Promise((resolve, reject) => { finish = () => stage === 'in-flight success'+ ? resolve([]) : reject(new Error('[LINK_NOT_OPEN] link closed')); }));+ const failed = expect(frame({ op: 'poll' })).rejects.toThrow('MCP_APP_LINK_CLOSED');+ await vi.advanceTimersByTimeAsync(0);+ f.link.close('device-a');+ if (stage !== 'sleeping') finish();+ const calls = f.invoke.mock.calls.length;+ await vi.advanceTimersByTimeAsync(35_000);+ await failed;+ await expect(frame({ op: 'poll' })).rejects.toThrow('MCP_APP_LINK_CLOSED');+ await expect(f.control({ op: 'context', viewId: local.viewId, context: {} })).rejects.toThrow('MCP_APP_LINK_CLOSED');+ await f.views.releaseCaller('renderer:1');+ expect(f.invoke.mock.calls).toHaveLength(calls);+ expect(state.mounts.has(local.viewId)).toBe(false);+ expect(await otherFrame({ op: 'poll' })).toEqual([]);+ expect(f.link.closeLink).toHaveBeenCalledExactlyOnceWith('device-a', 'user');+ // A fresh explicit open can use the new generation; the old frame stays revoked.+ expect(await f.open()).toHaveProperty('transport', 'sandbox');+ await expect(frame({ op: 'poll' })).rejects.toThrow('MCP_APP_LINK_CLOSED');+ },+ );+ it('discards an open result received after explicit close without reconnecting for cleanup', async () => {+ const f = fixture();+ let finish!: (value: unknown) => void;+ f.invoke.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));+ const failed = expect(f.open()).rejects.toThrow('MCP_APP_LINK_CLOSED');+ f.link.close('device-a');+ finish(document);+ await failed;+ expect(state.mounts.size).toBe(0);+ expect(f.invoke).toHaveBeenCalledOnce();+ });+ it('rechecks the View generation at actual dispatch after it waited in the invoke queue', async () => {+ const f = fixture();+ const local = await f.open();+ const send = vi.fn();+ f.invoke.mockImplementationOnce(async (_device, _session, _input, preSend) => {+ f.link.close('device-a');+ preSend();+ send();+ return {};+ });+ await expect(state.mounts.get(local.viewId)!.frame({ op: 'message',+ message: { jsonrpc: '2.0', id: 1, method: 'ping' } })).rejects.toThrow('MCP_APP_LINK_CLOSED');+ expect(send).not.toHaveBeenCalled();+ });+ it.each([+ { op: 'message', viewId: 'remote-view', message: { jsonrpc: '2.0', id: 1, method: 'tools/call' } },+ { op: 'poll', viewId: 'remote-view' },+ { op: 'authorize-link', viewId: 'remote-view', linkId: 'link' },+ { op: 'link-result', viewId: 'remote-view', linkId: 'link', success: true },+ { op: 'open-link', viewId: 'remote-view', url: 'https://example.org' },+ { op: 'mount-remote', document },+ ])('denies top Renderer transport operations without sending them: %j', async (input) => {+ const f = fixture();+ await f.open();+ f.invoke.mockClear();+ await expect(f.control(input)).rejects.toThrow('MCP_APP_FRAME_REQUIRED');+ expect(f.invoke).not.toHaveBeenCalled();+ });+ it('keeps private documents in Main, exposes only UI metadata, and binds frame RPCs to Main-held IDs', async () => {+ const f = fixture();+ const local = await f.open();+ expect(local).toEqual({ viewId: 'local-1', transport: 'sandbox', prefersBorder: true });+ expect(state.mounts.get(local.viewId)?.document).toEqual(document);+ const frame = state.mounts.get(local.viewId)!.frame;+ const message = { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'app-only' } };+ await frame({ op: 'message', viewId: 'forged', deviceId: 'forged', sessionId: 'forged', message });+ expect(f.invoke).toHaveBeenLastCalledWith('device-a', 'task',+ { op: 'message', viewId: 'remote-view', message }, expect.any(Function));+ await expect(frame({ op: 'open', clientId: 'forged' })).rejects.toThrow('MCP_APP_INVALID_REQUEST');+ for (const [caller, device, session] of [+ ['renderer:2', 'device-a', 'task'], ['renderer:1', 'device-b', 'task'], ['renderer:1', 'device-a', 'other'],+ ]) await expect(f.control({ op: 'context', viewId: local.viewId, context: {} }, caller, device, session))+ .rejects.toThrow('MCP_APP_VIEW_UNAVAILABLE');+ });+ it('checks owner and the still-mounted View at the actual send and result boundaries', async () => {+ const f = fixture();+ const local = await f.open();+ const frame = state.mounts.get(local.viewId)!.frame;+ f.invoke.mockImplementationOnce(async (_device, _session, _input, preSend) => {+ f.changeOwner();+ preSend();+ return {};+ });+ await expect(frame({ op: 'message', message: { jsonrpc: '2.0', id: 1, method: 'tools/call' } }))+ .rejects.toThrow('MCP_APP_OWNER_CHANGED');+ await expect(frame({ op: 'poll' })).rejects.toThrow('MCP_APP_VIEW_UNAVAILABLE');+ });+ it('authorizes only a polled link immediately before opening the viewing computer browser', async () => {+ const f = fixture();+ const local = await f.open();+ const frame = state.mounts.get(local.viewId)!.frame;+ const link = { id: 'link', url: 'https://example.org/' };+ f.invoke.mockResolvedValueOnce([{ seq: 1, openLink: link }]);+ await frame({ op: 'poll' });+ await expect(frame({ op: 'open-link', linkId: 'link', url: 'https://forged.invalid' })).rejects.toThrow('MCP_APP_INVALID_LINK');+ // Old Hosts/missing receipts cannot grant the browser action.+ await expect(frame({ op: 'open-link', linkId: 'link', url: link.url })).rejects.toThrow('MCP_APP_LINK_NOT_AUTHORIZED');+ expect(f.openLink).not.toHaveBeenCalled();+ await expect(frame({ op: 'open-link', linkId: 'link', url: link.url })).rejects.toThrow('MCP_APP_INVALID_LINK');+ f.invoke.mockResolvedValueOnce([{ seq: 2, openLink: link }]);+ await frame({ op: 'poll' });+ f.invoke.mockResolvedValueOnce({ authorized: true, validForMs: 30_000 });+ await frame({ op: 'open-link', linkId: 'link', url: link.url });+ expect(f.invoke).toHaveBeenLastCalledWith('device-a', 'task',+ { op: 'authorize-link', viewId: 'remote-view', linkId: 'link' }, expect.any(Function));+ expect(f.openLink).toHaveBeenCalledExactlyOnceWith(link.url);+ await frame({ op: 'link-result', linkId: 'link', success: true });+ await expect(frame({ op: 'open-link', linkId: 'link', url: link.url })).rejects.toThrow('MCP_APP_INVALID_LINK');+ });+ it('drops a link authorization returned after owner revocation without opening or replaying it', async () => {+ const f = fixture();+ const local = await f.open();+ const frame = state.mounts.get(local.viewId)!.frame;+ f.invoke.mockResolvedValueOnce([{ seq: 1, openLink: { id: 'link', url: 'https://example.org/' } }]);+ await frame({ op: 'poll' });+ f.invoke.mockImplementationOnce(async () => { f.changeOwner(); return { authorized: true, validForMs: 30_000 }; });+ await expect(frame({ op: 'open-link', linkId: 'link', url: 'https://example.org/' })).rejects.toThrow('MCP_APP_VIEW_UNAVAILABLE');+ expect(f.openLink).not.toHaveBeenCalled();+ });+ it('rejects an expired authorization response and never retries the browser action', async () => {+ let elapsed = 0;+ vi.spyOn(performance, 'now').mockImplementation(() => elapsed);+ const f = fixture();+ const local = await f.open();+ const frame = state.mounts.get(local.viewId)!.frame;+ f.invoke.mockResolvedValueOnce([{ seq: 1, openLink: { id: 'link', url: 'https://example.org/' } }]);+ await frame({ op: 'poll' });+ f.invoke.mockImplementationOnce(async () => {+ elapsed = 30_000;+ return { authorized: true, validForMs: 30_000 };+ });+ await expect(frame({ op: 'open-link', linkId: 'link', url: 'https://example.org/' }))+ .rejects.toThrow('MCP_APP_LINK_NOT_AUTHORIZED');+ expect(f.openLink).not.toHaveBeenCalled();+ await expect(frame({ op: 'open-link', linkId: 'link', url: 'https://example.org/' }))+ .rejects.toThrow('MCP_APP_INVALID_LINK');+ expect(f.openLink).not.toHaveBeenCalled();+ vi.restoreAllMocks();+ });+ it('retains the local frame during remote teardown and releases it once', async () => {+ const f = fixture();+ const local = await f.open();+ let finish!: (result: unknown) => void;+ f.invoke.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));+ const close = f.control({ op: 'teardown', viewId: local.viewId, alreadyNotified: true });+ expect(state.mounts.has(local.viewId)).toBe(true);+ finish({});+ await close;+ expect(state.mounts.has(local.viewId)).toBe(false);+ expect(f.invoke.mock.calls.filter((call) => call[2].op === 'teardown')).toHaveLength(1);+ expect(f.invoke).toHaveBeenLastCalledWith('device-a', 'task',+ { op: 'teardown', viewId: 'remote-view' }, expect.any(Function));+ });+ it('does not open a late authorized link while the retained frame is closing', async () => {+ const f = fixture();+ const local = await f.open();+ const frame = state.mounts.get(local.viewId)!.frame;+ f.invoke.mockResolvedValueOnce([{ seq: 1, openLink: { id: 'link', url: 'https://example.org/' } }]);+ await frame({ op: 'poll' });+ let authorize!: (result: unknown) => void;+ let finishClose!: (result: unknown) => void;+ f.invoke.mockImplementationOnce(() => new Promise((resolve) => { authorize = resolve; }));+ const late = frame({ op: 'open-link', linkId: 'link', url: 'https://example.org/' });+ f.invoke.mockImplementationOnce(() => new Promise((resolve) => { finishClose = resolve; }));+ const closing = f.control({ op: 'teardown', viewId: local.viewId });+ expect(state.mounts.has(local.viewId)).toBe(true);+ authorize({ authorized: true, validForMs: 30_000 });+ await expect(late).rejects.toThrow('MCP_APP_VIEW_UNAVAILABLE');+ expect(f.openLink).not.toHaveBeenCalled();+ finishClose({});+ await closing;+ });+ it('namespaces pending opens and cancels late Views only for the exiting caller', async () => {+ const f = fixture();+ let finish!: (result: unknown) => void;+ f.invoke.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));+ const pending = f.open();+ const rejected = expect(pending).rejects.toThrow('MCP_APP_OPEN_CANCELLED');+ const remoteOpenId = f.invoke.mock.calls[0][2].openId;+ expect(remoteOpenId).not.toBe('attempt');+ const other = await f.control({ op: 'open', clientId: 'other', openId: 'attempt' }, 'renderer:2') as McpAppSandboxView;+ await f.views.releaseCaller('renderer:1');+ finish(document);+ await rejected;+ expect(f.invoke).toHaveBeenCalledWith('device-a', 'task',+ { op: 'cancel-open', openId: remoteOpenId }, expect.any(Function));+ expect(state.mounts.has(other.viewId)).toBe(true);+ expect(state.mounts.size).toBe(1);+ });+ it('retries only the failing View read while another controller continues without interruption', async () => {+ const f = fixture();+ const local = await f.open();+ const other = await f.control({ op: 'open', clientId: 'card' }, 'renderer:2', 'device-b') as McpAppSandboxView;+ const frame = state.mounts.get(local.viewId)!.frame;+ const otherFrame = state.mounts.get(other.viewId)!.frame;+ vi.useFakeTimers();+ f.invoke.mockRejectedValueOnce(new Error('[DEVICE_LINK_TIMEOUT] transport stalled'));+ const retrying = frame({ op: 'poll' });+ await vi.advanceTimersByTimeAsync(0);+ expect(await otherFrame({ op: 'poll' })).toEqual([]);+ expect(state.mounts.size).toBe(2);+ const calls = f.invoke.mock.calls.length;+ await vi.advanceTimersByTimeAsync(500);+ expect(await retrying).toEqual([]);+ expect(f.invoke.mock.calls.slice(calls).map((call) => [call[0], call[2].op])).toEqual([['device-a', 'poll']]);+ expect(f.invoke.mock.calls.some((call) => ['teardown', 'cancel-open'].includes(String(call[2].op)))).toBe(false);+ });+ it('never replays App writes after a transport failure', async () => {+ const f = fixture();+ const local = await f.open();+ vi.useFakeTimers();+ f.invoke.mockClear();+ f.invoke.mockRejectedValueOnce(new Error('[DEVICE_LINK_TIMEOUT] outcome unknown'));+ await expect(state.mounts.get(local.viewId)!.frame({ op: 'message',+ message: { jsonrpc: '2.0', id: 1, method: 'tools/call' } })).rejects.toThrow('outcome unknown');+ await vi.advanceTimersByTimeAsync(30_000);+ expect(f.invoke).toHaveBeenCalledOnce();+ });+ it('releases the caller pending-open quota immediately and discards each late View', async () => {+ const f = fixture();+ const finishes: Array<(result: unknown) => void> = [];+ f.invoke.mockImplementation(async (_device, _session, input, preSend) => {+ preSend();+ return input.op === 'open' ? new Promise((resolve) => finishes.push(resolve)) : {};+ });+ const pending = Array.from({ length: 16 }, () => expect(f.open()).rejects.toThrow('MCP_APP_OPEN_CANCELLED'));+ await expect(f.open()).rejects.toThrow('MCP_APP_VIEW_LIMIT');+ await f.views.releaseCaller('renderer:1');+ f.invoke.mockResolvedValueOnce(document);+ expect(await f.open()).toHaveProperty('transport', 'sandbox');+ finishes.forEach((finish) => finish(document));+ await Promise.all(pending);+ expect(state.mounts.size).toBe(1);+ });+ it('stops a failed read after its bounded retry window', async () => {+ const f = fixture();+ const local = await f.open();+ vi.useFakeTimers();+ f.invoke.mockRejectedValue(new Error('[DEVICE_LINK_TIMEOUT] transport stalled'));+ const failed = expect(state.mounts.get(local.viewId)!.frame({ op: 'poll' })).rejects.toThrow('transport stalled');+ await vi.advanceTimersByTimeAsync(35_000);+ await failed;+ const calls = f.invoke.mock.calls.length;+ await vi.advanceTimersByTimeAsync(30_000);+ expect(f.invoke.mock.calls).toHaveLength(calls);+ });+ it('does not send a sleeping read again after its caller is released', async () => {+ const f = fixture();+ const local = await f.open();+ vi.useFakeTimers();+ f.invoke.mockRejectedValueOnce(new Error('[DEVICE_LINK_TIMEOUT] transport stalled'));+ const failed = expect(state.mounts.get(local.viewId)!.frame({ op: 'poll' })).rejects.toThrow('MCP_APP_VIEW_UNAVAILABLE');+ await vi.advanceTimersByTimeAsync(0);+ await f.views.releaseCaller('renderer:1');+ const polls = f.invoke.mock.calls.filter((call) => call[2].op === 'poll').length;+ await vi.advanceTimersByTimeAsync(500);+ await failed;+ expect(f.invoke.mock.calls.filter((call) => call[2].op === 'poll')).toHaveLength(polls);+ expect(state.mounts.size).toBe(0);+ });+});diff --git a/apps/desktop/src/main/mcp-apps/__tests__/resultDelivery.test.ts b/apps/desktop/src/main/mcp-apps/__tests__/resultDelivery.test.tsnew file mode 100644index 0000000000..adfe36cfe9--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/__tests__/resultDelivery.test.ts@@ -0,0 +1,361 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { AppBridge } from '@modelcontextprotocol/ext-apps/app-bridge';+import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';+import type { McpAppRecord } from '../../../shared/mcpApps.js';+import type { AppConnection } from '../connection.js';+import { McpAppsHost, appServerRevision, type McpAppsHostDeps } from '../host.js';+import { handleMcpAppOperation } from '../operations.js';++const hosts: McpAppsHost[] = [];+afterEach(async () => {+ await Promise.all(hosts.splice(0).map((host) => host.reset()));+ vi.restoreAllMocks();+ vi.useRealTimers();+});++const result: CallToolResult = {+ content: [{ type: 'text', text: 'Completed draft' }],+ structuredContent: { completed: true },+ _meta: { viewOnly: 'private result' },+};+const completion = (kind: 'result' | 'cancelled') =>+ kind === 'result' ? { result } : { cancelled: 'Tool execution cancelled' };++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => { resolve = done; });+ return { promise, resolve };+}++function fixture() {+ const owner = {};+ const config = { id: 'example', url: 'https://mcp.example.invalid', transport: 'http' as const };+ const uri = 'ui://form';+ const tool = {+ name: 'form',+ inputSchema: { type: 'object' as const },+ _meta: { ui: { resourceUri: uri } },+ };+ const card: McpAppRecord = {+ version: 1,+ serverId: config.id,+ serverRevision: appServerRevision(config),+ resourceUri: uri,+ tool,+ arguments: { title: 'Draft' },+ };+ const cards = new Map([+ ['card', card],+ ['other', { ...card }],+ ]);+ const readCard = vi.fn<McpAppsHostDeps['readCard']>(async (_sessionId, clientId) => {+ const current = cards.get(clientId);+ if (!current) throw new Error('MCP_APP_CARD_UNAVAILABLE');+ return current;+ });+ const writeCard = vi.fn<McpAppsHostDeps['writeCard']>(async (_sessionId, clientId, record) => {+ if (!cards.has(clientId)) throw new Error('MCP_APP_CARD_UNAVAILABLE');+ cards.set(clientId, record);+ });+ const dispose = vi.fn();+ const callTool = vi.fn(async () => result);+ const connection = {+ getClient: async () => ({ getServerCapabilities: () => ({ tools: {} }), callTool }),+ tools: async () => [tool],+ resource: async () => ({+ result: { contents: [{ uri, mimeType: 'text/html;profile=mcp-app', text: '<p>Form</p>' }] },+ }),+ listen: () => () => {},+ close: vi.fn(async () => {}),+ } as unknown as AppConnection;+ const host = new McpAppsHost({+ owner: () => owner,+ config: () => config,+ readCard,+ writeCard,+ authorizeTool: async () => {},+ sendMessage: async () => {},+ disposeDocument: dispose,+ connection: () => connection,+ });+ const connectionId = host.registerConnection(connection);+ for (const record of cards.values()) record.connectionId = connectionId;+ hosts.push(host);+ const sendResult = vi.spyOn(AppBridge.prototype, 'sendToolResult');+ const sendCancelled = vi.spyOn(AppBridge.prototype, 'sendToolCancelled');+ const sendInput = vi.spyOn(AppBridge.prototype, 'sendToolInput');+ return { host, card, cards, readCard, writeCard, dispose, sendResult, sendCancelled, sendInput, callTool };+}++async function open(host: McpAppsHost, caller: string, clientId = 'card') {+ const document = await host.open(caller, 'task', clientId, {});+ const viewId = document.viewId;+ await host.dispatch(caller, 'task', viewId, {+ jsonrpc: '2.0',+ id: 1,+ method: 'ui/initialize',+ params: {+ protocolVersion: '2026-01-26',+ appInfo: { name: 'Result delivery fixture', version: '1' },+ appCapabilities: {},+ },+ });+ const events = await host.poll(caller, 'task', viewId, 0);+ expect(events.some((event) => event.message && 'result' in event.message)).toBe(true);+ return { caller, viewId, after: events.at(-1)!.seq };+}++async function initialize(host: McpAppsHost, view: Awaited<ReturnType<typeof open>>) {+ await host.dispatch(view.caller, 'task', view.viewId, {+ jsonrpc: '2.0',+ method: 'ui/notifications/initialized',+ });+ let input = false;+ while (!input) {+ const events = await host.poll(view.caller, 'task', view.viewId, view.after);+ view.after = events.at(-1)!.seq;+ input = events.some(+ (event) =>+ event.message &&+ 'method' in event.message &&+ event.message.method === 'ui/notifications/tool-input',+ );+ }+}++describe('MCP App result delivery authorization', () => {+ it.each(['device:phone', 'device:desktop'])(+ 'acknowledges a slow tools/call before completion and polls its result once for %s',+ async (caller) => {+ const f = fixture();+ const view = await open(f.host, caller);+ await initialize(f.host, view);+ const healthy = await open(f.host, 'device:healthy');+ await initialize(f.host, healthy);+ vi.useFakeTimers();+ const upstream = deferred<CallToolResult>();+ f.callTool.mockReturnValueOnce(upstream.promise);+ let acknowledged = false;+ const ack = handleMcpAppOperation(f.host, caller, 'task', {+ op: 'message', viewId: view.viewId,+ message: { jsonrpc: '2.0', id: 100, method: 'tools/call', params: { name: 'form', arguments: {} } },+ }).then((value) => { acknowledged = true; return value; });+ await vi.advanceTimersByTimeAsync(0);+ expect(acknowledged).toBe(true);+ await expect(ack).resolves.toEqual({});+ expect(f.callTool).toHaveBeenCalledOnce();+ // Beyond both controllers' ordinary invoke windows, the View and original+ // tool request remain live. No retry, replay, or link reset is needed.+ await vi.advanceTimersByTimeAsync(35_000);+ expect(f.callTool).toHaveBeenCalledOnce();+ await expect(f.host.assertViewAuthorized(caller, 'task', view.viewId)).resolves.toBeUndefined();+ await handleMcpAppOperation(f.host, healthy.caller, 'task', {+ op: 'message', viewId: healthy.viewId,+ message: { jsonrpc: '2.0', id: 101, method: 'ping' },+ });+ await vi.advanceTimersByTimeAsync(0);+ const peerEvents = await f.host.poll(healthy.caller, 'task', healthy.viewId, healthy.after);+ expect(peerEvents.some((event) => event.message && 'id' in event.message && event.message.id === 101 && 'result' in event.message)).toBe(true);+ upstream.resolve(result);+ await vi.advanceTimersByTimeAsync(0);+ const events = await f.host.poll(caller, 'task', view.viewId, view.after);+ const replies = events.filter((event) => event.message && 'id' in event.message && event.message.id === 100);+ expect(replies).toHaveLength(1);+ expect(replies[0].message).toMatchObject({ id: 100, result });+ expect(f.callTool).toHaveBeenCalledOnce();+ vi.useRealTimers();+ },+ );++ it.each(['pending', 'result', 'cancelled'] as const)(+ 'restores an orphaned %s card without replaying its original tool',+ async (kind) => {+ const f = fixture();+ const saved = { ...f.card, connectionId: 'previous-host-connection',+ ...(kind === 'pending' ? {} : completion(kind)) };+ f.cards.set('card', saved);+ const local = await open(f.host, 'renderer:restored');+ await initialize(f.host, local);+ if (kind === 'result') {+ await vi.waitFor(() => expect(f.sendResult).toHaveBeenCalledExactlyOnceWith(result));+ expect(f.sendCancelled).not.toHaveBeenCalled();+ } else {+ await vi.waitFor(() => expect(f.sendCancelled).toHaveBeenCalledOnce());+ expect(f.cards.get('card')?.cancelled).toBe(kind === 'pending'+ ? 'Tool execution interrupted before completion' : saved.cancelled);+ }+ expect(f.writeCard).toHaveBeenCalledTimes(kind === 'pending' ? 1 : 0);+ const phone = await open(f.host, 'device:phone');+ await initialize(f.host, phone);+ await vi.waitFor(() => expect(kind === 'result' ? f.sendResult : f.sendCancelled).toHaveBeenCalledTimes(2));+ expect(f.writeCard).toHaveBeenCalledTimes(kind === 'pending' ? 1 : 0);+ },+ );++ it('does not publish a restored pending View if its terminal state cannot be saved', async () => {+ const f = fixture();+ f.cards.set('card', { ...f.card, connectionId: 'previous-host-connection' });+ f.writeCard.mockRejectedValueOnce(new Error('Persistence unavailable'));+ await expect(open(f.host, 'renderer:restored')).rejects.toThrow('Persistence unavailable');+ expect(f.sendInput).not.toHaveBeenCalled();+ expect(f.sendCancelled).not.toHaveBeenCalled();+ });++ it.each([+ ['result', true], ['result', false], ['cancelled', true], ['cancelled', false],+ ] as const)('preserves %s for an initialized=%s peer when another caller closes during authorization', async (kind, initialized) => {+ const f = fixture();+ const closing = await open(f.host, 'renderer:closing');+ await initialize(f.host, closing);+ const peer = await open(f.host, 'device:phone');+ if (initialized) await initialize(f.host, peer);+ const reading = deferred<void>();+ const pending = deferred<McpAppRecord>();+ f.readCard.mockImplementationOnce(() => { reading.resolve(); return pending.promise; });+ const record = { ...f.card, ...completion(kind) };+ const update = f.host.updateResult('task', 'card', record);+ await reading.promise;+ await f.host.releaseCaller(closing.caller);+ pending.resolve(record);+ await expect(update).resolves.toBeUndefined();+ expect(f.cards.get('card')).toEqual(record);+ if (!initialized) await initialize(f.host, peer);+ await vi.waitFor(() => expect(kind === 'result' ? f.sendResult : f.sendCancelled).toHaveBeenCalledOnce());+ expect(f.dispose).toHaveBeenCalledExactlyOnceWith(closing.viewId);+ await expect(f.host.assertViewAuthorized(peer.caller, 'task', peer.viewId)).resolves.toBeUndefined();+ // Reopened callers also receive the successfully persisted completion.+ const reopened = await open(f.host, 'renderer:reopened');+ await initialize(f.host, reopened);+ await vi.waitFor(() => expect(kind === 'result' ? f.sendResult : f.sendCancelled).toHaveBeenCalledTimes(2));+ });++ it.each(['result', 'cancelled'] as const)('isolates a %s transport failure to the affected View', async (kind) => {+ const f = fixture();+ const broken = await open(f.host, 'renderer:broken');+ await initialize(f.host, broken);+ const peer = await open(f.host, 'device:phone');+ await initialize(f.host, peer);+ const delivery = kind === 'result' ? f.sendResult : f.sendCancelled;+ delivery.mockRejectedValueOnce(new Error('MCP_APP_TRANSPORT_CLOSED'));+ await expect(f.host.updateResult('task', 'card', { ...f.card, ...completion(kind) })).resolves.toBeUndefined();+ expect(delivery).toHaveBeenCalledTimes(2);+ expect(f.dispose).toHaveBeenCalledExactlyOnceWith(broken.viewId);+ await expect(f.host.assertViewAuthorized(peer.caller, 'task', peer.viewId)).resolves.toBeUndefined();+ });++ it('rejects a poll immediately if disposal wins between authorization and installing its wake', async () => {+ const f = fixture();+ const view = await open(f.host, 'renderer:local');+ vi.useFakeTimers();+ let rejected = false;+ const poll = expect(f.host.poll(view.caller, 'task', view.viewId, view.after))+ .rejects.toThrow('MCP_APP_VIEW_UNAVAILABLE').then(() => { rejected = true; });+ // assertCurrentView resumes first, then removal wins before transport.poll.+ await Promise.resolve().then(() => f.host.releaseCaller(view.caller));+ await vi.advanceTimersByTimeAsync(0);+ expect(rejected).toBe(true);+ await poll;+ });+ it.each(['result', 'cancelled'] as const)(+ 'disposes initialized and waiting Views without delivering %s when persistence rejects a revoked card',+ async (kind) => {+ const f = fixture();+ const local = await open(f.host, 'renderer:local');+ await initialize(f.host, local);+ const waiting = await open(f.host, 'device:phone');+ const other = await open(f.host, 'renderer:other', 'other');+ await initialize(f.host, other);+ const rejectedPoll = expect(+ f.host.poll(local.caller, 'task', local.viewId, local.after),+ ).rejects.toThrow('MCP_APP_VIEW_UNAVAILABLE');++ // readCard/writeCard reject cleared, rewound or deleted cards through the same contract.+ f.cards.delete('card');+ await expect(+ f.host.updateResult('task', 'card', { ...f.card, ...completion(kind) }),+ ).rejects.toThrow('MCP_APP_CARD_UNAVAILABLE');+ await rejectedPoll;+ expect(f.sendResult).not.toHaveBeenCalled();+ expect(f.sendCancelled).not.toHaveBeenCalled();+ expect(f.dispose.mock.calls).toEqual([[local.viewId], [waiting.viewId]]);+ await expect(initialize(f.host, waiting)).rejects.toThrow('MCP_APP_VIEW_UNAVAILABLE');++ await f.host.updateResult('task', 'other', { ...f.card, result });+ const events = await f.host.poll(other.caller, 'task', other.viewId, other.after);+ expect(events).toContainEqual(+ expect.objectContaining({+ message: { jsonrpc: '2.0', method: 'ui/notifications/tool-result', params: result },+ }),+ );+ expect(f.sendResult).toHaveBeenCalledOnce();+ expect(f.dispose).not.toHaveBeenCalledWith(other.viewId);+ },+ );++ it('preserves a storage failure and fails closed even if the old card can still be read', async () => {+ const f = fixture();+ const view = await open(f.host, 'renderer:local');+ await initialize(f.host, view);+ const failure = new Error('STORAGE_FAILURE');+ f.writeCard.mockRejectedValueOnce(failure);+ await expect(f.host.updateResult('task', 'card', { ...f.card, result })).rejects.toBe(failure);+ expect(f.sendResult).not.toHaveBeenCalled();+ expect(f.dispose).toHaveBeenCalledWith(view.viewId);+ });++ it.each(['result', 'cancelled'] as const)(+ 'revalidates the live card before sending %s after a successful write',+ async (kind) => {+ const f = fixture();+ const view = await open(f.host, 'renderer:local');+ await initialize(f.host, view);+ f.writeCard.mockImplementationOnce(async (_sessionId, clientId, record) => {+ f.cards.set(clientId, record);+ // Revocation can race with the persistence completion.+ f.cards.delete(clientId);+ });+ await expect(+ f.host.updateResult('task', 'card', { ...f.card, ...completion(kind) }),+ ).rejects.toThrow('MCP_APP_CARD_UNAVAILABLE');+ expect(f.sendResult).not.toHaveBeenCalled();+ expect(f.sendCancelled).not.toHaveBeenCalled();+ expect(f.dispose).toHaveBeenCalledWith(view.viewId);+ },+ );++ it.each(['result', 'cancelled'] as const)(+ 'does not deliver saved %s or input when the card is revoked before initialization',+ async (kind) => {+ const f = fixture();+ const view = await open(f.host, 'renderer:local');+ await f.host.updateResult('task', 'card', { ...f.card, ...completion(kind) });+ f.cards.delete('card');+ await f.host.dispatch(view.caller, 'task', view.viewId, {+ jsonrpc: '2.0',+ method: 'ui/notifications/initialized',+ });+ await vi.waitFor(() => expect(f.dispose).toHaveBeenCalledWith(view.viewId));+ expect(f.sendInput).not.toHaveBeenCalled();+ expect(f.sendResult).not.toHaveBeenCalled();+ expect(f.sendCancelled).not.toHaveBeenCalled();+ },+ );++ it.each(['result', 'cancelled'] as const)(+ 'delivers %s once to active and later initialized Views while their card remains current',+ async (kind) => {+ const f = fixture();+ const active = await open(f.host, 'renderer:local');+ await initialize(f.host, active);+ const waiting = await open(f.host, 'device:phone');+ const record = { ...f.card, ...completion(kind) };+ await f.host.updateResult('task', 'card', record);+ await initialize(f.host, waiting);+ await f.host.updateResult('task', 'card', record);+ await vi.waitFor(() => {+ expect(kind === 'result' ? f.sendResult : f.sendCancelled).toHaveBeenCalledTimes(2);+ });+ expect(f.dispose).not.toHaveBeenCalled();+ },+ );+});diff --git a/apps/desktop/src/main/mcp-apps/__tests__/sandboxBridge.test.ts b/apps/desktop/src/main/mcp-apps/__tests__/sandboxBridge.test.tsnew file mode 100644index 0000000000..7cb63c3c52--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/__tests__/sandboxBridge.test.ts@@ -0,0 +1,73 @@+import { Script } from 'node:vm';+import { expect, it, vi } from 'vitest';+import { mcpAppDirectSandboxDocument } from '../sandboxBridge.js';++function fixture() {+ const handlers = new Map<string, (event: unknown) => void>();+ const frame = {+ setAttribute: vi.fn(), style: {}, src: '',+ contentWindow: { postMessage: vi.fn() },+ };+ const parent = { postMessage: vi.fn() };+ const pending: Array<(response: { ok: boolean; json(): Promise<unknown> }) => void> = [];+ const fetch = vi.fn<(url: string, input: { body: string }) => Promise<{ ok: boolean; json(): Promise<unknown> }>>(() => new Promise((resolve) => pending.push(resolve)));+ const window = { parent, addEventListener: (name: string, callback: (event: unknown) => void) =>+ handlers.set(name, callback) };+ const document = { createElement: () => frame, body: { appendChild: vi.fn() } };+ const html = mcpAppDirectSandboxDocument('cindy-mcp-app://view-view/resource', 'cindy-mcp-app://view/bridge');+ const script = html.slice(html.indexOf('<script>') + 8, html.indexOf('</script>'));+ new Script(script).runInNewContext({ window, document, fetch });+ return { handlers, parent, frame, fetch, pending };+}+it('ignores forged App requests and Host responses from the Renderer, relaying only the inner window', () => {+ const f = fixture();+ const receive = f.handlers.get('message')!;+ const call = { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'credentialed-tool' } };+ receive({ source: f.parent, data: call });+ receive({ source: f.parent, data: { jsonrpc: '2.0', id: 2, result: { forged: true } } });+ expect(f.fetch).toHaveBeenCalledOnce(); // The proxy's own Host poll only.+ expect(f.frame.contentWindow.postMessage).not.toHaveBeenCalled();+ receive({ source: f.frame.contentWindow, data: call });+ expect(f.fetch).toHaveBeenCalledTimes(2);+ expect(f.fetch.mock.calls[1][0]).toBe('cindy-mcp-app://view/bridge');+ expect(JSON.parse(f.fetch.mock.calls[1][1].body))+ .toEqual({ op: 'message', message: call });+ expect(f.parent.postMessage).not.toHaveBeenCalled();+ receive({ source: f.frame.contentWindow, data: { jsonrpc: '2.0', method: 'ui/notifications/sandbox-escape' } });+ expect(f.parent.postMessage).not.toHaveBeenCalled();+});+it('gives the UI only display state while keeping Host results on the direct App transport', async () => {+ const f = fixture();+ const result = { jsonrpc: '2.0', id: 1, result: { private: 'tool-result' } };+ const size = { jsonrpc: '2.0', method: 'ui/notifications/size-changed', params: { height: 420 } };+ f.pending[0]({ ok: true, json: async () => [{ seq: 1, message: result }, { seq: 2, message: size }] });+ for (let index = 0; index < 8; index++) await Promise.resolve();+ expect(f.frame.contentWindow.postMessage).toHaveBeenCalledWith(result, '*');+ expect(f.frame.contentWindow.postMessage).toHaveBeenCalledWith(size, '*');+ expect(f.parent.postMessage).toHaveBeenCalledWith(size, '*');+ expect(f.parent.postMessage).toHaveBeenCalledOnce();+});+it('changes Renderer display state only from the Host poll, never from the App', async () => {+ const f = fixture();+ const context = { jsonrpc: '2.0', method: 'ui/notifications/host-context-changed',+ params: { displayMode: 'fullscreen', theme: 'dark' } };+ f.handlers.get('message')!({ source: f.frame.contentWindow, data: context });+ expect(f.parent.postMessage).not.toHaveBeenCalled();+ f.pending[0]({ ok: true, json: async () => [{ seq: 1, message: context }] });+ for (let index = 0; index < 8; index++) await Promise.resolve();+ expect(f.parent.postMessage).toHaveBeenCalledExactlyOnceWith(context, '*');+ expect(f.frame.contentWindow.postMessage).toHaveBeenCalledExactlyOnceWith(context, '*');+});+it('still relays App readiness and size notifications to the Renderer and Host', () => {+ const f = fixture();+ const messages = [+ { jsonrpc: '2.0', method: 'ui/notifications/initialized' },+ { jsonrpc: '2.0', method: 'ui/notifications/size-changed', params: { height: 420 } },+ ];+ for (const message of messages) {+ f.handlers.get('message')!({ source: f.frame.contentWindow, data: message });+ expect(f.parent.postMessage).toHaveBeenCalledWith(message, '*');+ expect(JSON.parse(f.fetch.mock.calls.at(-1)![1].body)).toEqual({ op: 'message', message });+ }+ expect(f.parent.postMessage).toHaveBeenCalledTimes(2);+});diff --git a/apps/desktop/src/main/mcp-apps/__tests__/sandboxProtocol.test.ts b/apps/desktop/src/main/mcp-apps/__tests__/sandboxProtocol.test.tsnew file mode 100644index 0000000000..fffbd22035--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/__tests__/sandboxProtocol.test.ts@@ -0,0 +1,307 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { app, protocol, session, type WebContents } from 'electron';+import { EventEmitter } from 'node:events';+import type { McpAppsHost } from '../host.js';+import { setMcpAppsHost } from '../runtime.js';+vi.mock('electron', async (original) => {+ const electron = await original<typeof import('electron')>();+ return {+ ...electron,+ session: {+ ...electron.session,+ defaultSession: {+ ...electron.session.defaultSession,+ setPermissionRequestHandler: vi.fn(),+ setPermissionCheckHandler: vi.fn(),+ webRequest: { onBeforeSendHeaders: vi.fn((_filter: unknown, listener: typeof state.beforeHeaders) => {+ state.beforeHeaders = listener;+ }) },+ },+ },+ };+});+const state = vi.hoisted(() => ({ owner: {} as object | null,+ beforeHeaders: undefined as ((details: Electron.OnBeforeSendHeadersListenerDetails,+ callback: (response: Electron.BeforeSendResponse) => void) => void) | undefined,+}));+vi.mock('../../localDb/client/current.js', () => ({+ getCurrentDbClientSnapshot: () => state.owner,+}));+import {+ assertMcpAppDocumentCaller,+ clearMcpAppDocuments,+ mountRemoteAppDocument,+ registerMcpAppProtocol,+ isMcpAppFrameNavigationAllowed,+ isMcpAppPermissionRequest,+ supplyMcpAppDocument,+ setMcpAppCallerCleanup,+ unmountRemoteAppDocument,+} from '../sandboxProtocol.js';+afterEach(() => {+ clearMcpAppDocuments();+ setMcpAppCallerCleanup();+ app.removeAllListeners('web-contents-created');+ vi.restoreAllMocks();+ state.owner = {};+});+const document = {+ viewId: 'untrusted-id',+ html: '<!doctype html><body>App',+ csp: 'default-src *',+ prefersBorder: true,+};+describe('MCP App local protocol isolation', () => {+ it('gives remotely mounted documents the same authenticated bridge and releases their Main binding', async () => {+ let handler!: (request: Request) => Promise<Response> | Response;+ vi.spyOn(protocol, 'handle').mockImplementation((_scheme, callback) => { handler = callback; });+ registerMcpAppProtocol();+ const invoke = vi.fn(async () => ({}));+ const dispose = vi.fn();+ const id = mountRemoteAppDocument(document, 'renderer:1', invoke, dispose);+ const response = await handler(new Request(`cindy-mcp-app://${id}/sandbox`));+ expect(response.headers.get('Content-Security-Policy')).toContain("connect-src 'self'");+ expect(await response.text()).toContain(`cindy-mcp-app://${id}/bridge`);+ expect((await handler(new Request(`cindy-mcp-app://${id}/bridge`, { method: 'POST', body: '{}' }))).status).toBe(403);+ expect(invoke).not.toHaveBeenCalled();+ unmountRemoteAppDocument(id, 'renderer:1');+ clearMcpAppDocuments();+ expect(dispose).toHaveBeenCalledOnce();+ });+ it('authenticates the real sandbox frame, never the top Renderer or a forged channel key', async () => {+ let handler!: (request: Request) => Promise<Response> | Response;+ vi.spyOn(protocol, 'handle').mockImplementation((_scheme, callback) => { handler = callback; });+ registerMcpAppProtocol();+ const beforeHeaders = state.beforeHeaders!;+ const invoke = vi.fn(async () => ({ ok: true }));+ supplyMcpAppDocument(document, 'renderer:1', invoke);+ const frame = { url: 'cindy-mcp-app://untrusted-id/sandbox' };+ const details = { url: 'cindy-mcp-app://untrusted-id/bridge', method: 'POST',+ webContentsId: 1, frame, requestHeaders: { 'x-cindy-mcp-app-frame': 'forged' } };+ for (const invalid of [null, { url: 'file:///host.html' },+ { url: 'cindy-mcp-app://untrusted-id-view/resource' }]) {+ const callback = vi.fn();+ beforeHeaders({ ...details, frame: invalid } as never, callback);+ expect(callback).toHaveBeenCalledWith({ cancel: true });+ }+ const otherWindow = vi.fn();+ beforeHeaders({ ...details, webContentsId: 2 } as never, otherWindow);+ expect(otherWindow).toHaveBeenCalledWith({ cancel: true });+ const callback = vi.fn();+ beforeHeaders(details as never, callback);+ const headers = callback.mock.calls[0][0].requestHeaders;+ expect(headers['X-Cindy-Mcp-App-Frame']).not.toBe('forged');+ expect(headers['x-cindy-mcp-app-frame']).toBeUndefined();+ const request = (key: string) => new Request(details.url, { method: 'POST',+ headers: { 'X-Cindy-Mcp-App-Frame': key }, body: JSON.stringify({ op: 'message', message: {} }) });+ expect((await handler(request('forged'))).status).toBe(403);+ expect(invoke).not.toHaveBeenCalled();+ const html = await (await handler(new Request('cindy-mcp-app://untrusted-id/sandbox'))).text();+ expect(html).not.toContain(headers['X-Cindy-Mcp-App-Frame']);+ const response = await handler(request(headers['X-Cindy-Mcp-App-Frame']));+ expect(await response.json()).toEqual({ ok: true });+ expect(invoke).toHaveBeenCalledOnce();+ frame.url = 'https://navigated.example.org';+ expect((await handler(request(headers['X-Cindy-Mcp-App-Frame']))).status).toBe(403);+ expect(invoke).toHaveBeenCalledOnce();+ frame.url = 'cindy-mcp-app://untrusted-id/sandbox';+ const oversized = new Request(details.url, { method: 'POST',+ headers: { 'X-Cindy-Mcp-App-Frame': headers['X-Cindy-Mcp-App-Frame'] },+ body: 'x'.repeat(4 * 1024 * 1024 + 1) });+ expect((await handler(oversized)).status).toBe(400);+ expect(invoke).toHaveBeenCalledOnce();+ state.owner = {};+ expect((await handler(request(headers['X-Cindy-Mcp-App-Frame']))).status).toBe(404);+ expect(invoke).toHaveBeenCalledOnce();+ });+ it('installs both permission handlers and denies App and opaque subframe requests', () => {+ registerMcpAppProtocol();+ const request = vi+ .mocked(session.defaultSession.setPermissionRequestHandler)+ .mock.calls.at(-1)![0]!;+ const check = vi+ .mocked(session.defaultSession.setPermissionCheckHandler)+ .mock.calls.at(-1)![0]!;+ const callback = vi.fn();+ const details = { isMainFrame: false, requestingUrl: 'cindy-mcp-app://view-view/resource' };+ request(null as unknown as WebContents, 'notifications', callback, details);+ expect(callback).toHaveBeenCalledWith(false);+ expect(check(null, 'midi', 'cindy-mcp-app://view-view', details)).toBe(false);+ expect(check(null, 'serial', 'null', { isMainFrame: false })).toBe(false);+ expect(+ check(null, 'media', 'file://', { isMainFrame: true, requestingUrl: 'file:///host.html' }),+ ).toBe(true);+ });+ it('preserves Electron host permission defaults without enabling synchronous clipboard reads', () => {+ registerMcpAppProtocol();+ const request = vi.mocked(session.defaultSession.setPermissionRequestHandler).mock.calls.at(-1)![0]!;+ const check = vi.mocked(session.defaultSession.setPermissionCheckHandler).mock.calls.at(-1)![0]!;+ const details = { isMainFrame: true, requestingUrl: 'file:///host.html' };+ const callback = vi.fn();+ request(null as unknown as WebContents, 'notifications', callback, details);+ expect(callback).toHaveBeenCalledExactlyOnceWith(true);+ for (const permission of ['media', 'notifications', 'geolocation'] as const) {+ expect(check(null, permission, 'file://', details)).toBe(true);+ }+ expect(check(null, 'deprecated-sync-clipboard-read', 'file://', details)).toBe(false);+ });+ it('denies permissions for external descendants by their real ancestry', () => {+ const resource = { url: 'cindy-mcp-app://view-view/resource', parent: null };+ const nested = { url: 'https://embed.example.org', parent: resource };+ const unrelated = { url: 'https://other.example.org', parent: null };+ const contents = {+ mainFrame: { framesInSubtree: [resource, nested, unrelated] },+ } as unknown as WebContents;+ expect(+ isMcpAppPermissionRequest(contents, { isMainFrame: false, requestingUrl: nested.url }),+ ).toBe(true);+ expect(isMcpAppPermissionRequest(contents, { isMainFrame: false })).toBe(true);+ expect(+ isMcpAppPermissionRequest(contents, { isMainFrame: false, requestingUrl: unrelated.url }),+ ).toBe(false);+ });+ it('forwards unmodified Escape from the focused App into its trusted sandbox only', () => {+ registerMcpAppProtocol();+ const id = mountRemoteAppDocument(document, 'renderer:1');+ const sandbox = {+ url: `cindy-mcp-app://${id}/sandbox`,+ parent: null,+ executeJavaScript: vi.fn(async () => {}),+ };+ const contents = Object.assign(new EventEmitter(), {+ focusedFrame: { url: `cindy-mcp-app://${id}-view/resource`, parent: sandbox },+ });+ app.emit('web-contents-created', {}, contents);+ const event = { preventDefault: vi.fn() };+ contents.emit('before-input-event', event, {+ type: 'keyDown',+ key: 'Escape',+ isComposing: true,+ });+ expect(sandbox.executeJavaScript).not.toHaveBeenCalled();+ contents.emit('before-input-event', event, { type: 'keyDown', key: 'Escape' });+ expect(sandbox.executeJavaScript).toHaveBeenCalledOnce();+ expect(event.preventDefault).toHaveBeenCalledOnce();+ state.owner = {};+ contents.emit('before-input-event', event, { type: 'keyDown', key: 'Escape' });+ expect(sandbox.executeJavaScript).toHaveBeenCalledOnce();+ });+ it('rebuilds remote CSP and serves only the current owner through distinct origins', async () => {+ let handler!: (request: Request) => Promise<Response> | Response;+ vi.spyOn(protocol, 'handle').mockImplementation((_scheme, callback) => {+ handler = callback;+ });+ registerMcpAppProtocol();+ const id = mountRemoteAppDocument(document, 'renderer:1');+ const resource = await handler(new Request('cindy-mcp-app://' + id + '-view/resource'));+ expect(resource.status).toBe(200);+ expect(resource.headers.get('Content-Security-Policy')).toContain("connect-src 'none'");+ expect(await resource.text()).toBe(document.html);+ const sandbox = await handler(new Request('cindy-mcp-app://' + id + '/sandbox'));+ expect(sandbox.headers.get('Content-Security-Policy')).toContain(+ 'frame-src cindy-mcp-app://' + id + '-view',+ );+ for (const path of [+ 'cindy-mcp-app://' + id + '/resource',+ 'cindy-mcp-app://' + id + '-view/sandbox',+ 'cindy-mcp-app://' + id + '/secret',+ ])+ expect((await handler(new Request(path))).status).toBe(404);+ state.owner = {};+ expect((await handler(new Request('cindy-mcp-app://' + id + '-view/resource'))).status).toBe(+ 404,+ );+ });+ it('binds local mounts and privileged links to the mounting renderer and owner', () => {+ const id = mountRemoteAppDocument(document, 'renderer:1');+ expect(() => assertMcpAppDocumentCaller(id, 'renderer:1')).not.toThrow();+ expect(() => unmountRemoteAppDocument(id, 'renderer:2')).toThrow('MCP_APP_VIEW_UNAVAILABLE');+ state.owner = {};+ expect(() => assertMcpAppDocumentCaller(id, 'renderer:1')).toThrow('MCP_APP_VIEW_UNAVAILABLE');+ });+ it.each(['destroyed', 'render-process-gone', 'reload'] as const)(+ 'reclaims only the affected renderer documents and Host Views on %s',+ async (cause) => {+ const releaseCaller = vi.fn(async () => {});+ setMcpAppsHost({ releaseCaller } as unknown as McpAppsHost);+ let handler!: (request: Request) => Promise<Response> | Response;+ vi.spyOn(protocol, 'handle').mockImplementation((_scheme, callback) => {+ handler = callback;+ });+ registerMcpAppProtocol();+ const contents = Object.assign(new EventEmitter(), { id: 1 });+ app.emit('web-contents-created', {}, contents);+ const oldIds = Array.from({ length: 16 }, () =>+ mountRemoteAppDocument(document, 'renderer:1'),+ );+ const otherId = mountRemoteAppDocument(document, 'renderer:2');+ supplyMcpAppDocument({ ...document, viewId: 'host-document' });+ expect(() => mountRemoteAppDocument(document, 'renderer:1')).toThrow('MCP_APP_VIEW_LIMIT');++ // Same-document navigation and subframe reloads must leave cards alive.+ contents.emit('did-start-navigation', {}, 'cindy://app#task', true, true);+ contents.emit('did-start-navigation', {}, 'cindy-mcp-app://view/resource', false, false);+ expect(() => assertMcpAppDocumentCaller(oldIds[0], 'renderer:1')).not.toThrow();+ expect(releaseCaller).not.toHaveBeenCalled();+ if (cause === 'reload') contents.emit('did-start-navigation', {}, 'cindy://app', false, true);+ else contents.emit(cause);+ expect(releaseCaller).toHaveBeenCalledExactlyOnceWith('renderer:1');++ for (const id of oldIds) {+ expect(() => assertMcpAppDocumentCaller(id, 'renderer:1')).toThrow(+ 'MCP_APP_VIEW_UNAVAILABLE',+ );+ expect((await handler(new Request(`cindy-mcp-app://${id}-view/resource`))).status).toBe(+ 404,+ );+ }+ expect((await handler(new Request(`cindy-mcp-app://${otherId}-view/resource`))).status).toBe(+ 200,+ );+ expect(+ (await handler(new Request('cindy-mcp-app://host-document-view/resource'))).status,+ ).toBe(200);+ const replacement = mountRemoteAppDocument(document, 'renderer:1');+ expect(() => assertMcpAppDocumentCaller(replacement, 'renderer:1')).not.toThrow();+ },+ );+ it('does not allow a policy-bearing App to navigate itself into a privileged or external page', () => {+ const source = 'cindy-mcp-app://example-view/resource';+ expect(isMcpAppFrameNavigationAllowed(source, source + '#section')).toBe(true);+ expect(isMcpAppFrameNavigationAllowed('cindy-mcp-app://example/sandbox', source)).toBe(true);+ for (const target of [+ 'https://example.org',+ 'file:///private',+ 'cindy-mcp-app://other-view/resource',+ 'cindy-mcp-app://example/sandbox',+ ])+ expect(isMcpAppFrameNavigationAllowed(source, target)).toBe(false);+ expect(+ isMcpAppFrameNavigationAllowed('https://existing-cindy-view', 'https://existing-link'),+ ).toBe(true);+ });+ it('allows nested navigation only to the owning App approved frame domains', () => {+ const source = 'cindy-mcp-app://example-view/resource';+ const domains = ['https://frames.example.org', 'https://*.embed.example.org:*'];+ expect(isMcpAppFrameNavigationAllowed(source, 'https://frames.example.org/view', domains)).toBe(+ true,+ );+ expect(+ isMcpAppFrameNavigationAllowed(+ 'https://frames.example.org',+ 'https://sub.embed.example.org:8443/view',+ domains,+ ),+ ).toBe(true);+ for (const target of [+ 'https://other.example.org',+ 'http://frames.example.org',+ 'file:///private',+ 'cindy-mcp-app://other-view/resource',+ ])+ expect(isMcpAppFrameNavigationAllowed(source, target, domains)).toBe(false);+ expect(isMcpAppFrameNavigationAllowed(source, 'https://frames.example.org', [])).toBe(false);+ // Declaring a domain does not allow the App document itself to leave its origin.+ expect(isMcpAppFrameNavigationAllowed(source, 'https://frames.example.org')).toBe(false);+ });+});diff --git a/apps/desktop/src/main/mcp-apps/__tests__/serverProxy.test.ts b/apps/desktop/src/main/mcp-apps/__tests__/serverProxy.test.tsnew file mode 100644index 0000000000..babce2da5d--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/__tests__/serverProxy.test.ts@@ -0,0 +1,792 @@+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';+import type { RequestOptions } from '@modelcontextprotocol/sdk/shared/protocol.js';+import {+ CallToolRequestSchema,+ ListToolsRequestSchema,+ CompleteRequestSchema,+ SubscribeRequestSchema,+ UnsubscribeRequestSchema,+ SetLevelRequestSchema,+ ResourceUpdatedNotificationSchema,+ LoggingMessageNotificationSchema,+ TaskStatusNotificationSchema,+ GetTaskRequestSchema,+ GetTaskPayloadRequestSchema,+ ListTasksRequestSchema,+ CancelTaskRequestSchema,+ CreateTaskResultSchema,+ GetTaskResultSchema,+ ListTasksResultSchema,+ CallToolResultSchema,+ ResultSchema,+ ListRootsRequestSchema,+ RootsListChangedNotificationSchema,+ CreateMessageRequestSchema,+ ElicitRequestSchema,+ isJSONRPCNotification,+ type CallToolRequest,+ type CallToolResult,+ type ListToolsResult,+ type ClientRequest,+ type CompleteRequest,+ type CompleteResult,+ type ServerCapabilities,+ type ClientCapabilities,+ type ServerRequest,+} from '@modelcontextprotocol/sdk/types.js';+import { startMockAppServer } from '../../../../scripts/mcp-apps-mock.mjs';+import { McpAppsHost } from '../host.js';+import { AppConnection } from '../connection.js';+import { createAppServerProxy } from '../serverProxy.js';+import { setMcpAppsHost, registerAppServer, clearAppServerConfigs } from '../runtime.js';++const capabilities: ServerCapabilities = {+ tools: { listChanged: true },+ resources: { listChanged: true, subscribe: true },+ prompts: { listChanged: true },+ completions: {},+ logging: {},+ tasks: { list: {}, cancel: {}, requests: { tools: { call: {} } } },+ experimental: { 'example/custom': {} },+ extensions: { 'example/custom': {} },+};+const task = {+ taskId: 'ordinary-task',+ status: 'completed' as const,+ ttl: 60_000,+ createdAt: '2026-10-15T00:00:00Z',+ lastUpdatedAt: '2026-10-15T00:00:00Z',+};+const completionParams: CompleteRequest['params'] = {+ ref: { type: 'ref/prompt', name: 'plain' },+ argument: { name: 'value', value: 'draft' },+};+const complete =+ vi.fn<(params: CompleteRequest['params'], signal: AbortSignal) => Promise<CompleteResult>>();+const callTool =+ vi.fn<(params: CallToolRequest['params'], signal: AbortSignal) => Promise<CallToolResult>>();+const subscribed = vi.fn(),+ unsubscribed = vi.fn(),+ setLevel = vi.fn();+const upstreams: McpServer[] = [];+const callbackOutcomes = vi.fn();+const cleanup: Array<() => Promise<unknown>> = [];+let endpoint: Awaited<ReturnType<typeof startMockAppServer>>;+let emptyEndpoint: typeof endpoint;++function createPlainServer() {+ const server = new McpServer({ name: 'ordinary-mcp', version: '1' }, { capabilities });+ upstreams.push(server);+ server.server.setRequestHandler(ListToolsRequestSchema, async () => ({+ tools: [+ {+ name: 'plain',+ inputSchema: { type: 'object' as const },+ execution: { taskSupport: 'optional' as const },+ },+ {+ name: 'app_only',+ inputSchema: { type: 'object' as const },+ _meta: { ui: { visibility: ['app'] } },+ },+ ],+ }));+ server.server.setRequestHandler(CallToolRequestSchema, async (request, extra) =>+ request.params.task ? { task } : callTool(request.params, extra.signal),+ );+ server.server.setRequestHandler(CompleteRequestSchema, async (request, extra) => {+ if (extra._meta?.progressToken !== undefined)+ await extra.sendNotification({+ method: 'notifications/progress',+ params: { progressToken: extra._meta.progressToken, progress: 1, total: 1 },+ });+ return complete(request.params, extra.signal);+ });+ server.server.setRequestHandler(SubscribeRequestSchema, async (request) => {+ subscribed(request.params);+ return {};+ });+ server.server.setRequestHandler(UnsubscribeRequestSchema, async (request) => {+ unsubscribed(request.params);+ return {};+ });+ server.server.setRequestHandler(SetLevelRequestSchema, async (request) => {+ setLevel(request.params);+ return {};+ });+ server.server.setRequestHandler(GetTaskRequestSchema, async () => task);+ server.server.setRequestHandler(GetTaskPayloadRequestSchema, async () => ({+ content: [{ type: 'text' as const, text: 'task result' }],+ }));+ server.server.setRequestHandler(ListTasksRequestSchema, async () => ({ tasks: [task] }));+ server.server.setRequestHandler(CancelTaskRequestSchema, async () => ({+ ...task,+ status: 'cancelled' as const,+ }));+ server.server.fallbackRequestHandler = async (request, extra) => {+ if (request.method !== 'example/client-callback') return { echo: request.params?.value };+ try {+ const result = await extra.sendRequest(request.params?.request as ServerRequest, ResultSchema, {+ signal: extra.signal,+ });+ callbackOutcomes(server, { result });+ return result;+ } catch (error) {+ callbackOutcomes(server, { error });+ throw error;+ }+ };+ return server;+}++beforeAll(async () => {+ endpoint = await startMockAppServer({ createServer: createPlainServer });+ emptyEndpoint = await startMockAppServer({+ createServer: () => new McpServer({ name: 'empty', version: '1' }),+ });+});+beforeEach(() => {+ callTool.mockReset().mockResolvedValue({ content: [{ type: 'text', text: 'plain result' }] });+ complete+ .mockReset()+ .mockImplementation(async (params) => ({+ completion: { values: [params.argument.value + '-completed'] },+ }));+ subscribed.mockClear();+ unsubscribed.mockClear();+ setLevel.mockClear();+ callbackOutcomes.mockClear();+});+afterEach(async () => {+ vi.restoreAllMocks();+ for (const close of cleanup.splice(0).reverse()) await close();+ clearAppServerConfigs();+});+afterAll(async () => {+ await endpoint.close();+ await emptyEndpoint.close();+});++async function fixture(+ transport: 'http' | 'sse' = 'http',+ empty = false,+ peer?: { capabilities: ClientCapabilities; configure(client: Client): void },+) {+ const source = empty ? emptyEndpoint : endpoint;+ const config = { id: 'plain', url: transport === 'http' ? source.url : source.sseUrl, transport };+ let owner: object = {};+ const writeCard = vi.fn();+ const host = new McpAppsHost({+ owner: () => owner,+ config: () => config,+ readCard: async () => {+ throw new Error('No App');+ },+ writeCard,+ authorizeTool: async () => {},+ sendMessage: async () => {},+ });+ setMcpAppsHost(host);+ registerAppServer(config.id, () => config);+ const facade = createAppServerProxy(() => config, {+ agentKind: 'codex',+ sessionId: 'task',+ workingDir: '',+ });+ const client = new Client({ name: 'model', version: '1' }, { capabilities: peer?.capabilities ?? {} });+ peer?.configure(client);+ cleanup.push(async () => {+ await client.close();+ await facade.close();+ await host.reset();+ });+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ await facade.connect(serverTransport);+ await client.connect(clientTransport);+ return {+ client,+ clientTransport,+ writeCard,+ upstream: upstreams.at(-1)!,+ changeOwner: () => {+ owner = {};+ },+ changeConfig: () => {+ registerAppServer(config.id, () => ({+ ...config,+ headers: { 'x-test-revision': 'changed' },+ }));+ },+ };+}++const revocations = ['owner', 'server', 'config'] as const;+function revoke(f: Awaited<ReturnType<typeof fixture>>, kind: (typeof revocations)[number]) {+ if (kind === 'owner') f.changeOwner();+ else if (kind === 'config') f.changeConfig();+ else clearAppServerConfigs();+}++// Sampling/elicitation belong to a client-originating request. Using the SDK's+// related-request stream also avoids racing HTTP's optional standalone SSE GET.+function requestClient(+ f: Awaited<ReturnType<typeof fixture>>,+ request: ServerRequest,+ options?: RequestOptions,+) {+ return f.client.request(+ { method: 'example/client-callback', params: { request } } as unknown as ClientRequest,+ ResultSchema,+ options,+ );+}++describe('ordinary MCP downstream client callbacks', () => {+ const peerCapabilities: ClientCapabilities = {+ roots: { listChanged: true }, sampling: {}, elicitation: { form: {} },+ extensions: { 'example/client': {} },+ };++ it.each(['http', 'sse'] as const)('preserves declared capabilities and callbacks over %s', async (transport) => {+ const roots = vi.fn(async () => ({ roots: [{ uri: 'file:///fixture/project' }] }));+ const sampling = vi.fn(async () => ({+ role: 'assistant' as const, model: 'fixture',+ content: { type: 'text' as const, text: 'sample result' }, stopReason: 'endTurn',+ }));+ const elicit = vi.fn(async () => ({ action: 'accept' as const, content: { confirmed: true } }));+ const f = await fixture(transport, false, {+ capabilities: peerCapabilities,+ configure(client) {+ client.setRequestHandler(ListRootsRequestSchema, roots);+ client.setRequestHandler(CreateMessageRequestSchema, sampling);+ client.setRequestHandler(ElicitRequestSchema, elicit);+ },+ });+ expect(f.upstream.server.getClientCapabilities()).toMatchObject(peerCapabilities);+ expect(f.upstream.server.getClientCapabilities()?.extensions).toHaveProperty('io.modelcontextprotocol/ui');+ await expect(requestClient(f, { method: 'roots/list' })).resolves.toEqual(+ { roots: [{ uri: 'file:///fixture/project' }] },+ );+ await expect(requestClient(f, { method: 'sampling/createMessage', params: {+ messages: [{ role: 'user', content: { type: 'text', text: 'sample request' } }], maxTokens: 10,+ } })).resolves.toMatchObject({ model: 'fixture', content: { text: 'sample result' } });+ await expect(requestClient(f, { method: 'elicitation/create', params: {+ mode: 'form',+ message: 'Confirm fixture', requestedSchema: {+ type: 'object', properties: { confirmed: { type: 'boolean' } }, required: ['confirmed'],+ },+ } })).resolves.toEqual({ action: 'accept', content: { confirmed: true } });+ const changed = vi.fn(async () => {});+ f.upstream.server.setNotificationHandler(RootsListChangedNotificationSchema, changed);+ await f.client.sendRootsListChanged();+ await vi.waitFor(() => expect(changed).toHaveBeenCalledOnce());+ expect(roots).toHaveBeenCalledOnce();+ expect(sampling).toHaveBeenCalledOnce();+ expect(elicit).toHaveBeenCalledOnce();+ });++ it('does not advertise callbacks absent from the downstream client', async () => {+ const f = await fixture();+ const declared = f.upstream.server.getClientCapabilities()!;+ expect(declared.roots).toBeUndefined();+ expect(declared.sampling).toBeUndefined();+ expect(declared.elicitation).toBeUndefined();+ await expect(requestClient(f, { method: 'roots/list' })).rejects.toThrow('Method not found');+ });++ it('routes callbacks only to the facade that negotiated that connection', async () => {+ const firstRoots = vi.fn(async () => ({ roots: [{ uri: 'file:///fixture/first' }] }));+ const secondRoots = vi.fn(async () => ({ roots: [{ uri: 'file:///fixture/second' }] }));+ const first = await fixture('http', false, {+ capabilities: { roots: {} }, configure: client => client.setRequestHandler(ListRootsRequestSchema, firstRoots),+ });+ const second = await fixture('http', false, {+ capabilities: { roots: {} }, configure: client => client.setRequestHandler(ListRootsRequestSchema, secondRoots),+ });+ await expect(requestClient(first, { method: 'roots/list' })).resolves.toEqual(+ { roots: [{ uri: 'file:///fixture/first' }] },+ );+ await expect(requestClient(second, { method: 'roots/list' })).resolves.toEqual(+ { roots: [{ uri: 'file:///fixture/second' }] },+ );+ expect(firstRoots).toHaveBeenCalledOnce();+ expect(secondRoots).toHaveBeenCalledOnce();+ });++ it.each(revocations)('rejects a callback result after %s revocation', async (kind) => {+ let finish!: () => void;+ const roots = vi.fn(() => new Promise<{ roots: [] }>((resolve) => { finish = () => resolve({ roots: [] }); }));+ const f = await fixture('http', false, {+ capabilities: { roots: {} }, configure: client => client.setRequestHandler(ListRootsRequestSchema, roots),+ });+ const pending = requestClient(f, { method: 'roots/list' }).catch(error => error);+ await vi.waitFor(() => expect(finish).toBeDefined());+ revoke(f, kind);+ finish();+ expect(await pending).toHaveProperty('message', expect.stringContaining('MCP_APP_'));+ // The callback result itself must be withheld from the upstream server,+ // not only rejected later at the outer model response boundary.+ expect(callbackOutcomes).toHaveBeenLastCalledWith(f.upstream, {+ error: expect.objectContaining({ message: expect.stringContaining('MCP_APP_') }),+ });+ expect(roots).toHaveBeenCalledOnce();+ await expect(requestClient(f, { method: 'roots/list' })).rejects.toThrow('MCP_APP_');+ expect(roots).toHaveBeenCalledOnce();+ });++ it.each([0, 1])('forwards callback cancellation for request ID %s without replaying it', async (prior) => {+ const cancelled = vi.fn();+ let finish!: () => void;+ const roots = vi.fn((_request: unknown, extra: { signal: AbortSignal }) => new Promise<{ roots: [] }>((resolve) => {+ finish = () => resolve({ roots: [] });+ extra.signal.addEventListener('abort', () => { cancelled(); resolve({ roots: [] }); }, { once: true });+ }));+ const f = await fixture('http', false, {+ capabilities: { roots: {} }, configure: client => client.setRequestHandler(ListRootsRequestSchema, roots),+ });+ for (let index = 0; index < prior; index++) {+ roots.mockResolvedValueOnce({ roots: [] });+ await requestClient(f, { method: 'roots/list' });+ }+ const cancellation = vi.fn();+ const onmessage = f.clientTransport.onmessage!;+ f.clientTransport.onmessage = (message, extra) => {+ if (isJSONRPCNotification(message) && message.method === 'notifications/cancelled')+ cancellation(message.params);+ onmessage(message, extra);+ };+ const abort = new AbortController();+ const pending = requestClient(f, { method: 'roots/list' }, { signal: abort.signal }).catch(error => error);+ await vi.waitFor(() => expect(roots).toHaveBeenCalledTimes(prior + 1));+ abort.abort();+ expect(await pending).toBeInstanceOf(Error);+ await vi.waitFor(() => expect(cancellation).toHaveBeenCalledWith(+ expect.objectContaining({ requestId: prior }),+ ));+ // The test peer is SDK 1.29, whose default cancellation handler ignores ID+ // 0. Check the actual wire notification for both IDs and its signal for 1.+ if (prior !== 0) await vi.waitFor(() => expect(cancelled).toHaveBeenCalledOnce());+ finish();+ expect(roots).toHaveBeenCalledTimes(prior + 1);+ });+});++describe('ordinary MCP compatibility through the App facade', () => {+ it.each(['http', 'sse'] as const)(+ 'preserves upstream capabilities, completion/progress, subscriptions and logging over %s',+ async (transport) => {+ const f = await fixture(transport);+ expect(f.client.getServerCapabilities()).toEqual(capabilities);+ const progress = vi.fn();+ let finish!: () => void;+ // SSE may deliver progress and the final response in one socket chunk. The+ // SDK handles notifications asynchronously, so keep this request in flight+ // until the model has observed progress instead of relying on socket timing.+ complete.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finish = () => resolve({ completion: { values: ['draft-completed'] } });+ }),+ );+ const completion = f.client.complete(completionParams, { onprogress: progress });+ await vi.waitFor(() => expect(progress).toHaveBeenCalledWith({ progress: 1, total: 1 }));+ finish();+ expect(await completion).toEqual({ completion: { values: ['draft-completed'] } });+ const updates = vi.fn(),+ logs = vi.fn();+ f.client.setNotificationHandler(ResourceUpdatedNotificationSchema, updates);+ f.client.setNotificationHandler(LoggingMessageNotificationSchema, logs);+ await f.client.subscribeResource({ uri: 'resource://plain' });+ expect(subscribed).toHaveBeenCalledWith({ uri: 'resource://plain' });+ await f.upstream.server.sendResourceUpdated({ uri: 'resource://plain' });+ await vi.waitFor(() =>+ expect(updates).toHaveBeenCalledWith(+ expect.objectContaining({ params: { uri: 'resource://plain' } }),+ ),+ );+ await f.client.unsubscribeResource({ uri: 'resource://plain' });+ expect(unsubscribed).toHaveBeenCalledWith({ uri: 'resource://plain' });+ await f.client.setLoggingLevel('info');+ expect(setLevel).toHaveBeenCalledWith({ level: 'info' });+ await f.upstream.server.notification({+ method: 'notifications/message',+ params: { level: 'info', data: 'ordinary notification' },+ });+ await vi.waitFor(() =>+ expect(logs).toHaveBeenCalledWith(+ expect.objectContaining({ params: { level: 'info', data: 'ordinary notification' } }),+ ),+ );+ expect(+ await f.client.request(+ // SDK ClientRequest enumerates standard methods; this advertised extension is custom.+ { method: 'example/echo', params: { value: 'custom' } } as unknown as ClientRequest,+ ResultSchema,+ ),+ ).toEqual({ echo: 'custom' });+ expect(f.writeCard).not.toHaveBeenCalled();+ },+ );++ it('advertises only capabilities actually supplied by the upstream server', async () => {+ const f = await fixture('http', true);+ expect(f.client.getServerCapabilities()).toEqual({});+ });++ it('preserves task-augmented tools and task methods while enforcing model visibility', async () => {+ const f = await fixture();+ const status = vi.fn();+ f.client.setNotificationHandler(TaskStatusNotificationSchema, status);+ expect((await f.client.listTools()).tools.map((tool) => tool.name)).toEqual(['plain']);+ expect(+ await f.client.request(+ { method: 'tools/call', params: { name: 'plain', task: { ttl: 60_000 } } },+ CreateTaskResultSchema,+ ),+ ).toEqual({ task });+ expect(+ await f.client.request(+ { method: 'tasks/get', params: { taskId: task.taskId } },+ GetTaskResultSchema,+ ),+ ).toEqual(task);+ expect(+ await f.client.request(+ { method: 'tasks/result', params: { taskId: task.taskId } },+ CallToolResultSchema,+ ),+ ).toEqual({ content: [{ type: 'text', text: 'task result' }] });+ expect(await f.client.request({ method: 'tasks/list' }, ListTasksResultSchema)).toEqual({+ tasks: [task],+ });+ expect(+ await f.client.request(+ { method: 'tasks/cancel', params: { taskId: task.taskId } },+ GetTaskResultSchema,+ ),+ ).toMatchObject({ status: 'cancelled' });+ await f.upstream.server.notification({ method: 'notifications/tasks/status', params: task });+ await vi.waitFor(() =>+ expect(status).toHaveBeenCalledWith(expect.objectContaining({ params: task })),+ );+ await expect(+ f.client.request(+ { method: 'tools/call', params: { name: 'app_only', task: { ttl: 60_000 } } },+ CreateTaskResultSchema,+ ),+ ).rejects.toThrow('MCP_APP_TOOL_NOT_VISIBLE');+ expect(f.writeCard).not.toHaveBeenCalled();+ });++ it.each(['http', 'sse'] as const)(+ 'withholds View-only metadata from synchronous and task tool results over %s',+ async (transport) => {+ const f = await fixture(transport);+ const publicResult = {+ content: [{ type: 'text' as const, text: 'Public result', _meta: { publicBlock: true } }],+ structuredContent: { completed: false, _meta: { publicStructured: true } },+ isError: true,+ extension: 'public extension',+ };+ const result = { ...publicResult, _meta: { viewOnly: 'private task result' } };+ callTool.mockResolvedValueOnce(result);+ f.upstream.server.setRequestHandler(GetTaskPayloadRequestSchema, async () => result);++ await expect(f.client.callTool({ name: 'plain' })).resolves.toEqual(publicResult);+ await expect(+ f.client.request(+ { method: 'tools/call', params: { name: 'plain', task: { ttl: 60_000 } } },+ CreateTaskResultSchema,+ ),+ ).resolves.toEqual({ task });+ await expect(+ f.client.request(+ { method: 'tasks/result', params: { taskId: task.taskId } },+ CallToolResultSchema,+ ),+ ).resolves.toEqual(publicResult);+ expect(result._meta).toEqual({ viewOnly: 'private task result' });+ expect(f.writeCard).not.toHaveBeenCalled();+ },+ );++ it('preserves protocol metadata on ordinary forwarded task status results', async () => {+ const f = await fixture();+ const status = { ...task, _meta: { 'example/status': 'public protocol metadata' } };+ f.upstream.server.setRequestHandler(GetTaskRequestSchema, async () => status);+ await expect(+ f.client.request(+ { method: 'tasks/get', params: { taskId: task.taskId } },+ GetTaskResultSchema,+ ),+ ).resolves.toEqual(status);+ });++ it.each(revocations)(+ 'rejects a late task tool result after %s revocation without replay',+ async (kind) => {+ const f = await fixture();+ let finish!: () => void;+ const retrieve = vi.fn(+ () =>+ new Promise<CallToolResult>((resolve) => {+ finish = () =>+ resolve({+ content: [{ type: 'text', text: 'Late task result' }],+ _meta: { viewOnly: 'private task result' },+ });+ }),+ );+ f.upstream.server.setRequestHandler(GetTaskPayloadRequestSchema, retrieve);+ const readResult = () =>+ f.client.request(+ { method: 'tasks/result', params: { taskId: task.taskId } },+ CallToolResultSchema,+ );+ const error = kind === 'owner' ? 'MCP_APP_OWNER_CHANGED' : 'MCP_APP_SERVER_CHANGED';+ const rejected = expect(readResult()).rejects.toThrow(error);+ await vi.waitFor(() => expect(finish).toBeDefined());+ revoke(f, kind);+ finish();+ await rejected;+ await expect(readResult()).rejects.toThrow(error);+ expect(retrieve).toHaveBeenCalledOnce();+ expect(f.writeCard).not.toHaveBeenCalled();+ },+ );++ it.each(['owner', 'server'] as const)(+ 'rejects late completion results and new calls after %s revocation',+ async (kind) => {+ const f = await fixture();+ let finish!: () => void;+ complete.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finish = () => resolve({ completion: { values: ['late'] } });+ }),+ );+ const pending = f.client.complete(completionParams);+ const rejected = expect(pending).rejects.toThrow(+ kind === 'owner' ? 'MCP_APP_OWNER_CHANGED' : 'MCP_APP_SERVER_CHANGED',+ );+ await vi.waitFor(() => expect(finish).toBeDefined());+ if (kind === 'owner') f.changeOwner();+ else clearAppServerConfigs();+ finish();+ await rejected;+ await expect(f.client.subscribeResource({ uri: 'resource://plain' })).rejects.toThrow(+ kind === 'owner' ? 'MCP_APP_OWNER_CHANGED' : 'MCP_APP_SERVER_CHANGED',+ );+ expect(subscribed).not.toHaveBeenCalled();+ },+ );++ it.each(revocations)(+ 'does not execute a tool after %s revocation while acquiring its client',+ async (kind) => {+ const f = await fixture();+ const original = AppConnection.prototype.getClient;+ let finish!: () => void;+ vi.spyOn(AppConnection.prototype, 'getClient')+ // Tool discovery still uses the live client. Hold the separate acquisition+ // for execution to simulate a reconnect completing after revocation.+ .mockImplementationOnce(original)+ .mockImplementationOnce(function (this: AppConnection) {+ return new Promise<Client>((resolve, reject) => {+ finish = () => {+ void original.call(this).then(resolve, reject);+ };+ });+ });+ const rejected = expect(f.client.callTool({ name: 'plain' })).rejects.toThrow(+ kind === 'owner' ? 'MCP_APP_OWNER_CHANGED' : 'MCP_APP_SERVER_CHANGED',+ );+ await vi.waitFor(() => expect(finish).toBeDefined());+ revoke(f, kind);+ finish();+ await rejected;+ expect(callTool).not.toHaveBeenCalled();+ expect(f.writeCard).not.toHaveBeenCalled();+ },+ );++ it.each(revocations)(+ 'rejects a late ordinary tool result after %s revocation without replay',+ async (kind) => {+ const f = await fixture();+ let finish!: () => void;+ callTool.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finish = () => resolve({ content: [{ type: 'text', text: 'late result' }] });+ }),+ );+ const rejected = expect(f.client.callTool({ name: 'plain' })).rejects.toThrow(+ kind === 'owner' ? 'MCP_APP_OWNER_CHANGED' : 'MCP_APP_SERVER_CHANGED',+ );+ await vi.waitFor(() => expect(finish).toBeDefined());+ revoke(f, kind);+ finish();+ await rejected;+ await expect(f.client.callTool({ name: 'plain' })).rejects.toThrow(+ kind === 'owner' ? 'MCP_APP_OWNER_CHANGED' : 'MCP_APP_SERVER_CHANGED',+ );+ expect(callTool).toHaveBeenCalledOnce();+ expect(f.writeCard).not.toHaveBeenCalled();+ },+ );++ it.each(revocations)(+ 'rejects the model result after %s revocation during App result persistence',+ async (kind) => {+ const f = await fixture();+ f.upstream.server.setRequestHandler(ListToolsRequestSchema, async () => ({+ tools: [+ {+ name: 'plain',+ inputSchema: { type: 'object' as const },+ _meta: { ui: { resourceUri: 'ui://plain' } },+ },+ ],+ }));+ let finish!: () => void;+ f.writeCard+ .mockResolvedValueOnce(undefined)+ .mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ }),+ );+ const rejected = expect(f.client.callTool({ name: 'plain' })).rejects.toThrow(+ kind === 'owner' ? 'MCP_APP_OWNER_CHANGED' : 'MCP_APP_SERVER_CHANGED',+ );+ await vi.waitFor(() => expect(f.writeCard).toHaveBeenCalledTimes(2));+ revoke(f, kind);+ finish();+ await rejected;+ expect(callTool).toHaveBeenCalledOnce();+ expect(f.writeCard).toHaveBeenCalledTimes(2);+ },+ );++ it.each(+ (['http', 'sse'] as const).flatMap((transport) =>+ (['tools/list', 'tools/call'] as const).flatMap((method) =>+ [0, 1].map((page) => ({ transport, method, page })),+ ),+ ),+ )('cancels $transport $method discovery on page $page without executing or replaying a tool', async ({ transport, method, page }) => {+ const f = await fixture(transport);+ const tool = { name: 'plain', inputSchema: { type: 'object' as const } };+ const discovered = vi.fn();+ const cancelled = vi.fn();+ let release: (() => void) | undefined;+ cleanup.push(async () => release?.());+ f.upstream.server.setRequestHandler(ListToolsRequestSchema, (request, extra) => {+ discovered(request.params?.cursor);+ if (page === 1 && !request.params?.cursor)+ return { tools: [tool], nextCursor: 'next' };+ return new Promise<ListToolsResult>((resolve, reject) => {+ release = () => resolve({ tools: [] });+ extra.signal.addEventListener('abort', () => {+ cancelled();+ reject(new Error('discovery cancelled'));+ }, { once: true });+ });+ });+ const abort = new AbortController();+ const pending = method === 'tools/list'+ ? f.client.listTools(undefined, { signal: abort.signal })+ : f.client.callTool({ name: 'plain' }, CallToolResultSchema, { signal: abort.signal });+ const rejected = expect(pending).rejects.toThrow();+ await vi.waitFor(() => expect(release).toBeDefined());+ expect(discovered).toHaveBeenCalledTimes(page + 1);+ if (page === 1) expect(discovered).toHaveBeenLastCalledWith('next');+ abort.abort();+ await rejected;+ await vi.waitFor(() => expect(cancelled).toHaveBeenCalledOnce());+ expect(discovered).toHaveBeenCalledTimes(page + 1);+ expect(callTool).not.toHaveBeenCalled();+ expect(f.writeCard).not.toHaveBeenCalled();++ // Cancelling discovery must leave the connection usable for a new request.+ f.upstream.server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [tool] }));+ await expect(f.client.listTools()).resolves.toMatchObject({ tools: [tool] });+ await expect(f.client.callTool({ name: 'plain' })).resolves.toMatchObject({+ content: [{ type: 'text', text: 'plain result' }],+ });+ expect(callTool).toHaveBeenCalledOnce();+ });++ it.each(['http', 'sse'] as const)('cancels an ordinary %s request waiting for reconnect without disturbing another waiter', async (transport) => {+ const acquiring = vi.spyOn(AppConnection.prototype, 'getClient');+ const f = await fixture(transport);+ const initialClient = await acquiring.mock.results[0]!.value as Client;+ await initialClient.close();+ const before = acquiring.mock.calls.length;+ const connect = Client.prototype.connect;+ let release: (() => void) | undefined;+ cleanup.push(async () => release?.());+ // Hold the next real connection attempt before its handshake; the+ // AppConnection's shared-attempt and per-waiter cancellation remain real.+ vi.spyOn(Client.prototype, 'connect').mockImplementationOnce(function (this: Client, ...args: Parameters<Client['connect']>) {+ return new Promise<void>((resolve, reject) => {+ release = () => {+ release = undefined;+ void connect.call(this, ...args).then(resolve, reject);+ };+ });+ });+ const abort = new AbortController();+ const pending = f.client.complete(completionParams, { signal: abort.signal });+ const rejected = expect(pending).rejects.toThrow();+ await vi.waitFor(() => expect(release).toBeDefined());+ const cancelled = vi.fn();+ const waiter = acquiring.mock.results.at(-1)!.value as Promise<Client>;+ void waiter.catch(cancelled);+ abort.abort();+ await rejected;+ await vi.waitFor(() => expect(cancelled).toHaveBeenCalledOnce());+ expect(complete).not.toHaveBeenCalled();++ const healthy = f.client.complete(completionParams);+ const completed = expect(healthy).resolves.toMatchObject({+ completion: { values: ['draft-completed'] },+ });+ await vi.waitFor(() => expect(acquiring).toHaveBeenCalledTimes(before + 2));+ release!();+ await completed;+ expect(complete).toHaveBeenCalledOnce();+ });++ it('forwards cancellation to the single upstream request without replaying it', async () => {+ const f = await fixture();+ const cancelled = vi.fn();+ complete.mockImplementationOnce(+ (_params, signal) =>+ new Promise((_resolve, reject) => {+ signal.addEventListener(+ 'abort',+ () => {+ cancelled();+ reject(new Error('cancelled'));+ },+ { once: true },+ );+ }),+ );+ const abort = new AbortController();+ const pending = f.client.complete(completionParams, { signal: abort.signal });+ const rejected = expect(pending).rejects.toThrow();+ await vi.waitFor(() => expect(complete).toHaveBeenCalledOnce());+ abort.abort();+ await rejected;+ await vi.waitFor(() => expect(cancelled).toHaveBeenCalledOnce());+ expect(complete).toHaveBeenCalledOnce();+ });+});diff --git a/apps/desktop/src/main/mcp-apps/__tests__/serverRevision.test.ts b/apps/desktop/src/main/mcp-apps/__tests__/serverRevision.test.tsnew file mode 100644index 0000000000..1d2480e573--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/__tests__/serverRevision.test.ts@@ -0,0 +1,49 @@+import { createHash, createHmac } from 'node:crypto';+import { describe, expect, it } from 'vitest';+import { appServerRevision, McpAppsHost } from '../host.js';+import type { AppServerConfig } from '../connection.js';++const key = 'a'.repeat(64); // Deliberately invalid test-only vault material.+const config: AppServerConfig = {+ id: 'example', url: 'https://mcp.example.invalid', transport: 'http',+ headers: { Authorization: 'Basic invalid-test-only', 'x-api-key': 'fake-test-secret' },+};++function host(readKey: () => string) {+ return new McpAppsHost({+ owner: () => ({}), config: () => config, revisionKey: readKey,+ readCard: async () => { throw new Error('unused'); },+ writeCard: async () => {}, authorizeTool: async () => {}, sendMessage: async () => {},+ });+}++describe('private MCP App server revisions', () => {+ it('requires a host secret instead of persisting an offline credential verifier', () => {+ const input = JSON.stringify([config.id, config.url, config.transport, config.headers]);+ const revision = appServerRevision(config, key);+ expect(revision).toBe(createHmac('sha256', key)+ .update('cindy:mcp-app-server-revision:v1\0').update(input).digest('hex'));+ expect(revision).not.toBe(createHash('sha256').update(input).digest('hex'));+ expect(revision).not.toBe(appServerRevision(config, 'b'.repeat(64)));+ });++ it('retains the revision across Host recreation with the same vault key', () => {+ const first = host(() => key).serverRevision(config);+ expect(host(() => key).serverRevision({ ...config, headers: { ...config.headers } })).toBe(first);+ expect(first).not.toBe(host(() => 'b'.repeat(64)).serverRevision(config));+ });++ it.each([+ { ...config, url: config.url + '/changed' },+ { ...config, headers: { ...config.headers, Authorization: 'Bearer invalid-test-only-rotated' } },+ { ...config, headers: { ...config.headers, 'x-api-key': 'fake-test-secret-rotated' } },+ ])('still revokes a changed endpoint or credential configuration', (changed) => {+ const current = host(() => key);+ expect(current.serverRevision(changed)).not.toBe(current.serverRevision(config));+ });++ it('fails closed when the injected persistent key cannot be read', () => {+ const current = host(() => { throw new Error('MCP_APP_REVISION_KEY_UNAVAILABLE'); });+ expect(() => current.serverRevision(config)).toThrow('MCP_APP_REVISION_KEY_UNAVAILABLE');+ });+});diff --git a/apps/desktop/src/main/mcp-apps/__tests__/viewAuthorization.test.ts b/apps/desktop/src/main/mcp-apps/__tests__/viewAuthorization.test.tsnew file mode 100644index 0000000000..e87f577127--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/__tests__/viewAuthorization.test.ts@@ -0,0 +1,495 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { AppBridge } from '@modelcontextprotocol/ext-apps/app-bridge';+import type { JSONRPCMessage, Notification } from '@modelcontextprotocol/sdk/types.js';+import type { McpAppRecord } from '../../../shared/mcpApps.js';+import type { AppConnection } from '../connection.js';+import { McpAppsHost, appServerRevision } from '../host.js';+import { handleMcpAppFrameOperation, handleMcpAppOperation } from '../operations.js';++const hosts: McpAppsHost[] = [];+afterEach(async () => {+ vi.useRealTimers();+ await Promise.all(hosts.splice(0).map((host) => host.reset()));+ vi.restoreAllMocks();+});++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => {+ resolve = done;+ });+ return { promise, resolve };+}++const marker = 'private-upstream-result';+const tool = {+ name: 'form',+ description: marker,+ inputSchema: { type: 'object' as const },+ _meta: { ui: { resourceUri: 'ui://form' } },+};+const requests = [+ [+ 'tools/call',+ { name: tool.name, arguments: {} },+ 'callTool',+ { content: [{ type: 'text', text: marker }] },+ ],+ ['tools/list', {}, 'tools', [tool]],+ [+ 'resources/read',+ { uri: 'data://private' },+ 'readResource',+ { contents: [{ uri: 'data://private', text: marker }] },+ ],+ ['resources/list', {}, 'listResources', { resources: [{ name: marker, uri: 'data://private' }] }],+ [+ 'resources/templates/list',+ {},+ 'listResourceTemplates',+ { resourceTemplates: [{ name: marker, uriTemplate: 'data://{id}' }] },+ ],+ ['prompts/list', {}, 'listPrompts', { prompts: [{ name: marker }] }],+] as const;++async function fixture(caller = 'renderer:1') {+ let owner = {};+ let enabled = true;+ let visible = true;+ const config = { id: 'example', url: 'https://mcp.example.invalid', transport: 'http' as const };+ const card: McpAppRecord = {+ version: 1,+ serverId: config.id,+ serverRevision: appServerRevision(config),+ resourceUri: 'ui://form',+ tool,+ arguments: {},+ };+ const methods = {+ callTool: vi.fn(),+ tools: vi.fn(async () => [tool]),+ readResource: vi.fn(),+ listResources: vi.fn(),+ listResourceTemplates: vi.fn(),+ listPrompts: vi.fn(),+ };+ let notify!: (message: Notification) => void;+ const connection = {+ getClient: async () => ({+ ...methods,+ getServerCapabilities: () => ({ tools: {}, resources: {}, prompts: {} }),+ }),+ tools: methods.tools,+ resource: async () => ({+ result: {+ contents: [+ { uri: card.resourceUri, mimeType: 'text/html;profile=mcp-app', text: '<p>Form</p>' },+ ],+ },+ }),+ listen: (listener: typeof notify) => {+ notify = listener;+ return () => {};+ },+ close: vi.fn(async () => {}),+ } as unknown as AppConnection;+ const outgoing: JSONRPCMessage[] = [];+ const connect = AppBridge.prototype.connect;+ vi.spyOn(AppBridge.prototype, 'connect').mockImplementation(function (+ this: AppBridge,+ transport,+ ) {+ const send = transport.send.bind(transport);+ transport.send = async (message, options) => {+ outgoing.push(message);+ await send(message, options);+ };+ return connect.call(this, transport);+ });+ // These cases exercise request completion, not the separate bounded teardown handshake.+ vi.spyOn(AppBridge.prototype, 'teardownResource').mockResolvedValue({});+ const authorizeTool = vi.fn(async () => {});+ const readCard = vi.fn(async () => {+ if (!visible) throw new Error('MCP_APP_CARD_UNAVAILABLE');+ return card;+ });+ const host = new McpAppsHost({+ owner: () => owner,+ config: () => (enabled ? config : undefined),+ readCard,+ writeCard: async () => {},+ authorizeTool,+ sendMessage: async () => {},+ connection: () => connection,+ });+ hosts.push(host);+ const document = await host.open(caller, 'task', 'card', {});+ const dispatch = (message: JSONRPCMessage) =>+ host.dispatch(caller, 'task', document.viewId, message);+ await dispatch({+ jsonrpc: '2.0',+ id: 1,+ method: 'ui/initialize',+ params: {+ protocolVersion: '2026-01-26',+ appInfo: { name: 'Authorization fixture', version: '1' },+ appCapabilities: {},+ },+ });+ await vi.waitFor(() =>+ expect(outgoing).toContainEqual(expect.objectContaining({ id: 1, result: expect.anything() })),+ );+ await dispatch({ jsonrpc: '2.0', method: 'ui/notifications/initialized' });+ await vi.waitFor(() =>+ expect(outgoing).toContainEqual(+ expect.objectContaining({ method: 'ui/notifications/tool-input' }),+ ),+ );+ outgoing.length = 0;+ return {+ host,+ viewId: document.viewId,+ readCard,+ poll: (after: number) => host.poll(caller, 'task', document.viewId, after),+ notify: () => notify({ method: 'notifications/tools/list_changed' }),+ methods,+ outgoing,+ dispatch,+ config,+ authorizeTool,+ revoke(kind: 'card' | 'owner' | 'server' | 'config') {+ if (kind === 'card') visible = false;+ if (kind === 'owner') owner = {};+ if (kind === 'server') enabled = false;+ if (kind === 'config') config.url = 'https://changed.example.invalid';+ },+ };+}++describe('MCP App upstream result authorization', () => {+ async function returnedLink(f: Awaited<ReturnType<typeof fixture>>) {+ const initial = await f.poll(0);+ await f.dispatch({+ jsonrpc: '2.0',+ id: 2,+ method: 'ui/open-link',+ params: { url: 'https://example.invalid/' },+ });+ const events = await f.poll(initial.at(-1)!.seq);+ const link = events.find((event) => event.openLink)?.openLink;+ expect(link).toEqual({ id: expect.any(String), url: 'https://example.invalid/' });+ return { op: 'open-link', url: link!.url, linkId: link!.id };+ }++ it.each(['card', 'owner', 'server', 'config'] as const)(+ 'rejects remote link authorization after %s revocation following a returned poll',+ async (revocation) => {+ const f = await fixture('device:phone');+ const link = await returnedLink(f);+ f.revoke(revocation);+ await expect(+ handleMcpAppOperation(f.host, 'device:phone', 'task', {+ op: 'authorize-link',+ viewId: f.viewId,+ linkId: link.linkId,+ }),+ ).rejects.toThrow(/MCP_APP_(CARD_UNAVAILABLE|VIEW_UNAVAILABLE|SERVER_CHANGED)/);+ },+ );++ it('authorizes only the active link bound to the exact remote caller and task', async () => {+ const f = await fixture('device:phone');+ const link = await returnedLink(f);+ const input = { op: 'authorize-link', viewId: f.viewId, linkId: link.linkId };+ for (const [caller, task] of [+ ['device:other', 'task'],+ ['device:phone', 'other-task'],+ ])+ await expect(handleMcpAppOperation(f.host, caller, task, input)).rejects.toThrow(+ 'MCP_APP_VIEW_UNAVAILABLE',+ );+ await expect(+ handleMcpAppOperation(f.host, 'device:phone', 'task', {+ ...input,+ linkId: 'unknown-link',+ }),+ ).rejects.toThrow('MCP_APP_LINK_UNAVAILABLE');+ await expect(handleMcpAppOperation(f.host, 'device:phone', 'task', input)).resolves.toEqual({+ authorized: true,+ validForMs: 30_000,+ });+ f.host.linkResult('device:phone', 'task', f.viewId, link.linkId, false);+ await expect(handleMcpAppOperation(f.host, 'device:phone', 'task', input)).rejects.toThrow(+ 'MCP_APP_LINK_UNAVAILABLE',+ );+ });++ it('rechecks the remote View when its owner changes during final link authorization', async () => {+ const f = await fixture('device:phone');+ const link = await returnedLink(f);+ const current = await f.readCard();+ const pending = deferred<McpAppRecord>();+ f.readCard.mockClear().mockReturnValueOnce(pending.promise);+ const rejected = expect(+ handleMcpAppOperation(f.host, 'device:phone', 'task', {+ op: 'authorize-link',+ viewId: f.viewId,+ linkId: link.linkId,+ }),+ ).rejects.toThrow('MCP_APP_VIEW_UNAVAILABLE');+ await vi.waitFor(() => expect(f.readCard).toHaveBeenCalledOnce());+ f.revoke('owner');+ pending.resolve(current);+ await rejected;+ });++ it('opens a returned link when its bound View and card remain current', async () => {+ const f = await fixture();+ const input = await returnedLink(f);+ const openLink = vi.fn(async () => {});+ await expect(+ handleMcpAppFrameOperation(+ f.host,+ 'renderer:1',+ 'task',+ f.viewId,+ { ...input, viewId: 'forged-view', sessionId: 'forged-task' },+ openLink,+ ),+ ).resolves.toEqual({});+ expect(openLink).toHaveBeenCalledExactlyOnceWith(input.url);+ });++ it.each([+ { linkId: undefined },+ { linkId: 'unknown-link' },+ { url: 'https://another.example.invalid/' },+ ])('does not open a link with a missing or mismatched pending request: %j', async (patch) => {+ const f = await fixture();+ const input = await returnedLink(f);+ const openLink = vi.fn(async () => {});+ await expect(+ handleMcpAppFrameOperation(f.host, 'renderer:1', 'task', f.viewId, { ...input, ...patch }, openLink),+ ).rejects.toThrow(/MCP_APP_(INVALID_LINK|LINK_UNAVAILABLE)/);+ expect(openLink).not.toHaveBeenCalled();+ });++ it('does not replay a completed link request', async () => {+ const f = await fixture();+ const input = await returnedLink(f);+ f.host.linkResult('renderer:1', 'task', f.viewId, input.linkId, false);+ const openLink = vi.fn(async () => {});+ await expect(+ handleMcpAppFrameOperation(f.host, 'renderer:1', 'task', f.viewId, input, openLink),+ ).rejects.toThrow('MCP_APP_LINK_UNAVAILABLE');+ expect(openLink).not.toHaveBeenCalled();+ });++ it.each(['before', 'during'] as const)('does not open a link that expires %s final authorization', async (when) => {+ const f = await fixture();+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ const input = await returnedLink(f);+ const current = await f.readCard();+ const pending = deferred<McpAppRecord>();+ const openLink = vi.fn(async () => {});+ if (when === 'before') await vi.advanceTimersByTimeAsync(10_001);+ else f.readCard.mockClear().mockReturnValueOnce(pending.promise);+ const rejected = expect(+ handleMcpAppFrameOperation(f.host, 'renderer:1', 'task', f.viewId, input, openLink),+ ).rejects.toThrow('MCP_APP_LINK_UNAVAILABLE');+ if (when === 'during') {+ expect(f.readCard).toHaveBeenCalledOnce();+ await vi.advanceTimersByTimeAsync(10_001);+ pending.resolve(current);+ }+ await rejected;+ expect(openLink).not.toHaveBeenCalled();+ });++ it.each(['card', 'owner', 'server', 'config'] as const)(+ 'does not open a returned link after %s revocation',+ async (revocation) => {+ const f = await fixture();+ const input = await returnedLink(f);+ f.revoke(revocation);+ const openLink = vi.fn(async () => {});+ await expect(+ handleMcpAppFrameOperation(f.host, 'renderer:1', 'task', f.viewId, input, openLink),+ ).rejects.toThrow(/MCP_APP_(CARD_UNAVAILABLE|VIEW_UNAVAILABLE|SERVER_CHANGED)/);+ expect(openLink).not.toHaveBeenCalled();+ },+ );++ it('does not open a returned link after its View is released', async () => {+ const f = await fixture();+ const input = await returnedLink(f);+ await f.host.releaseCaller('renderer:1');+ const openLink = vi.fn(async () => {});+ await expect(+ handleMcpAppFrameOperation(f.host, 'renderer:1', 'task', f.viewId, input, openLink),+ ).rejects.toThrow('MCP_APP_VIEW_UNAVAILABLE');+ expect(openLink).not.toHaveBeenCalled();+ });++ it.each(['owner', 'server', 'config'] as const)(+ 'does not open a returned link after %s revocation during the card check',+ async (revocation) => {+ const f = await fixture();+ const input = await returnedLink(f);+ const current = await f.readCard();+ const pending = deferred<McpAppRecord>();+ f.readCard.mockClear().mockReturnValueOnce(pending.promise);+ const openLink = vi.fn(async () => {});+ const rejected = expect(+ handleMcpAppFrameOperation(f.host, 'renderer:1', 'task', f.viewId, input, openLink),+ ).rejects.toThrow(/MCP_APP_(VIEW_UNAVAILABLE|SERVER_CHANGED)/);+ await vi.waitFor(() => expect(f.readCard).toHaveBeenCalledOnce());+ f.revoke(revocation);+ pending.resolve(current);+ await rejected;+ expect(openLink).not.toHaveBeenCalled();+ },+ );++ it('discards a queued open-link event after its card is revoked', async () => {+ const f = await fixture();+ const initial = await f.poll(0);+ const after = initial.at(-1)!.seq;+ await f.dispatch({+ jsonrpc: '2.0',+ id: 2,+ method: 'ui/open-link',+ params: { url: 'https://example.invalid/' },+ });+ const queued = await f.poll(after);+ expect(queued).toContainEqual(+ expect.objectContaining({+ openLink: { id: expect.any(String), url: 'https://example.invalid/' },+ }),+ );+ f.revoke('card');+ await expect(f.poll(after)).rejects.toThrow('MCP_APP_CARD_UNAVAILABLE');+ });++ it('discards a notification arriving during a poll after its card is revoked', async () => {+ const f = await fixture();+ const initial = await f.poll(0);+ const after = initial.at(-1)!.seq;+ const rejected = expect(f.poll(after)).rejects.toThrow('MCP_APP_CARD_UNAVAILABLE');+ await new Promise<void>((resolve) => setImmediate(resolve));+ f.revoke('card');+ f.notify();+ await rejected;+ });++ it('delivers a notification arriving during a poll while its card remains current', async () => {+ const f = await fixture();+ const initial = await f.poll(0);+ const pending = f.poll(initial.at(-1)!.seq);+ f.notify();+ await expect(pending).resolves.toContainEqual(+ expect.objectContaining({+ message: expect.objectContaining({ method: 'notifications/tools/list_changed' }),+ }),+ );+ });++ it.each(['card', 'owner', 'server', 'config'] as const)(+ 'does not request tool approval after %s revocation during tool discovery',+ async (revocation) => {+ const f = await fixture();+ const pending = deferred<Array<typeof tool>>();+ f.methods.tools.mockClear().mockReturnValueOnce(pending.promise);+ await f.dispatch({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: requests[0][1] });+ await vi.waitFor(() => expect(f.methods.tools).toHaveBeenCalledOnce());+ f.revoke(revocation);+ pending.resolve([tool]);+ await vi.waitFor(() => expect(f.outgoing).toContainEqual(expect.objectContaining({ id: 2 })));+ expect(f.outgoing).toContainEqual(+ expect.objectContaining({ id: 2, error: expect.anything() }),+ );+ expect(f.authorizeTool).not.toHaveBeenCalled();+ expect(f.methods.callTool).not.toHaveBeenCalled();+ expect(f.methods.tools).toHaveBeenCalledOnce();+ },+ );++ it('requests approval once after slow tool discovery when the View remains current', async () => {+ const f = await fixture();+ const pending = deferred<Array<typeof tool>>();+ f.methods.tools.mockClear().mockReturnValueOnce(pending.promise);+ f.methods.callTool.mockResolvedValueOnce(requests[0][3]);+ await f.dispatch({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: requests[0][1] });+ await vi.waitFor(() => expect(f.methods.tools).toHaveBeenCalledOnce());+ expect(f.authorizeTool).not.toHaveBeenCalled();+ pending.resolve([tool]);+ await vi.waitFor(() => expect(f.outgoing).toContainEqual(expect.objectContaining({ id: 2 })));+ expect(f.outgoing).toContainEqual({ jsonrpc: '2.0', id: 2, result: requests[0][3] });+ expect(f.authorizeTool).toHaveBeenCalledExactlyOnceWith(+ 'task',+ tool,+ {},+ expect.any(AbortSignal),+ );+ expect(f.methods.callTool).toHaveBeenCalledOnce();+ expect(f.methods.tools).toHaveBeenCalledOnce();+ });++ it.each(['card', 'owner', 'server', 'config'] as const)(+ 'discards a completed App tool result after %s revocation without replaying it',+ async (revocation) => {+ const f = await fixture();+ const pending = deferred<unknown>();+ f.methods.callTool.mockReturnValueOnce(pending.promise);+ await f.dispatch({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: requests[0][1] });+ await vi.waitFor(() => expect(f.methods.callTool).toHaveBeenCalledOnce());+ f.revoke(revocation);+ pending.resolve(requests[0][3]);+ await vi.waitFor(() => expect(f.outgoing).toContainEqual(expect.objectContaining({ id: 2 })));+ expect(f.outgoing).toContainEqual(+ expect.objectContaining({ id: 2, error: expect.anything() }),+ );+ expect(JSON.stringify(f.outgoing)).not.toContain(marker);+ expect(f.methods.callTool).toHaveBeenCalledOnce();+ },+ );++ it.each(requests.slice(1))(+ 'discards %s results if the card is revoked while awaiting the server',+ async (method, params, upstream, result) => {+ const f = await fixture();+ const pending = deferred<unknown>();+ const operation = f.methods[upstream];+ operation.mockReturnValueOnce(pending.promise as never);+ operation.mockClear();+ await f.dispatch({ jsonrpc: '2.0', id: 2, method, params });+ await vi.waitFor(() => expect(operation).toHaveBeenCalledOnce());+ f.revoke('card');+ pending.resolve(result);+ await vi.waitFor(() => expect(f.outgoing).toContainEqual(expect.objectContaining({ id: 2 })));+ expect(f.outgoing).toContainEqual(+ expect.objectContaining({ id: 2, error: expect.anything() }),+ );+ expect(JSON.stringify(f.outgoing)).not.toContain(marker);+ expect(operation).toHaveBeenCalledOnce();+ },+ );++ it.each(requests)(+ 'delivers %s results once when the View remains authorized',+ async (method, params, upstream, result) => {+ const f = await fixture();+ const operation = f.methods[upstream];+ operation.mockResolvedValueOnce(result as never);+ operation.mockClear();+ await f.dispatch({ jsonrpc: '2.0', id: 2, method, params });+ await vi.waitFor(() => expect(f.outgoing).toContainEqual(expect.objectContaining({ id: 2 })));+ expect(f.outgoing).toContainEqual({+ jsonrpc: '2.0',+ id: 2,+ result: upstream === 'tools' ? { tools: result } : result,+ });+ expect(operation).toHaveBeenCalledOnce();+ },+ );+});diff --git a/apps/desktop/src/main/mcp-apps/__tests__/wireBudget.test.ts b/apps/desktop/src/main/mcp-apps/__tests__/wireBudget.test.tsnew file mode 100644index 0000000000..6857286b74--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/__tests__/wireBudget.test.ts@@ -0,0 +1,205 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';+import { encodeReliableFrames } from '../../../../../../packages/device-link/src/transport.js';+import { McpAppsHost, appServerRevision } from '../host.js';+import type { AppConnection } from '../connection.js';+import type { McpAppRecord } from '../../../shared/mcpApps.js';+import { MCP_APPS_MAX_BYTES, MCP_APPS_MAX_REMOTE_BYTES } from '../protocol.js';++const hosts: McpAppsHost[] = [];+afterEach(async () => {+ await Promise.all(hosts.splice(0).map((host) => host.reset()));+});++function wire(result: unknown) {+ return {+ v: 1 as const,+ kind: 'invoke-result' as const,+ id: 'request',+ src: 'host',+ dst: 'controller',+ payload: { ok: true as const, result },+ };+}++function fixture() {+ const owner = {};+ const config = { id: 'example', url: 'https://mcp.example.invalid', transport: 'http' as const };+ const uri = 'ui://form';+ const tool = {+ name: 'form',+ inputSchema: { type: 'object' as const },+ _meta: { ui: { resourceUri: uri } },+ };+ const record: McpAppRecord = {+ version: 1 as const,+ serverId: config.id,+ serverRevision: appServerRevision(config),+ resourceUri: uri,+ tool,+ arguments: {},+ };+ const contents = (text: string) => ({+ contents: [{ uri, mimeType: 'text/html;profile=mcp-app', text }],+ });+ const resource = vi.fn<AppConnection['resource']>(async () => ({ result: contents('') }));+ const readResource = vi.fn(async () => contents(''));+ const connection = {+ getClient: async () => ({ getServerCapabilities: () => ({ resources: {} }), readResource }),+ tools: async () => [tool],+ resource,+ listen: () => () => {},+ close: vi.fn(async () => {}),+ } as unknown as AppConnection;+ const host = new McpAppsHost({+ owner: () => owner,+ config: () => config,+ readCard: async () => record,+ writeCard: async () => {},+ authorizeTool: async () => {},+ sendMessage: async () => {},+ connection: () => connection,+ });+ // These budget cases model an active tool, not an orphan from a previous Host.+ record.connectionId = host.registerConnection(connection);+ hosts.push(host);+ return { host, resource, readResource, connection, contents };+}++async function initialized(host: McpAppsHost, caller: string) {+ const document = await host.open(caller, 'task', 'card', {});+ const viewId = document.viewId;+ await host.dispatch(caller, 'task', viewId, {+ jsonrpc: '2.0',+ id: 1,+ method: 'ui/initialize',+ params: {+ protocolVersion: '2026-01-26',+ appInfo: { name: 'Budget fixture', version: '1' },+ appCapabilities: {},+ },+ });+ const init = await host.poll(caller, 'task', viewId, 0);+ expect(init.some((event) => event.message && 'result' in event.message)).toBe(true);+ let after = init.at(-1)!.seq;+ await host.dispatch(caller, 'task', viewId, {+ jsonrpc: '2.0',+ method: 'ui/notifications/initialized',+ });+ let input = false;+ while (!input) {+ const events = await host.poll(caller, 'task', viewId, after);+ after = events.at(-1)!.seq;+ input = events.some(+ (event) =>+ event.message &&+ 'method' in event.message &&+ event.message.method === 'ui/notifications/tool-input',+ );+ }+ return { viewId, after };+}++describe('MCP Apps serialized remote result budgets', () => {+ it('accepts the complete remote document at its limit, including CSP and JSON escaping', async () => {+ const f = fixture();+ const empty = await f.host.open('renderer:local', 'task', 'card', {});+ const overhead = Buffer.byteLength(JSON.stringify(empty));+ const html = 'x'.repeat(MCP_APPS_MAX_REMOTE_BYTES - overhead);+ f.resource.mockResolvedValue({ result: f.contents(html) });+ const document = await f.host.open('device:phone', 'task', 'card', {});+ expect(Buffer.byteLength(JSON.stringify(document))).toBe(MCP_APPS_MAX_REMOTE_BYTES);+ expect(() => encodeReliableFrames(wire(document), 'stream', 1)).not.toThrow();+ f.resource.mockResolvedValue({ result: f.contents(html + 'x') });+ await expect(f.host.open('device:phone', 'task', 'card', {})).rejects.toThrow(+ 'MCP_APP_RESOURCE_TOO_LARGE',+ );+ });++ it.each(['multibyte', 'quotes', 'control characters'] as const)(+ 'rejects remote %s before retaining a View, while preserving the local resource budget',+ async (kind) => {+ const f = fixture();+ const html =+ kind === 'multibyte'+ ? '汉'.repeat(Math.floor(MCP_APPS_MAX_REMOTE_BYTES / 3))+ : kind === 'quotes'+ ? '"'.repeat(MCP_APPS_MAX_BYTES / 2)+ : String.fromCharCode(1).repeat(Math.ceil(MCP_APPS_MAX_REMOTE_BYTES / 6));+ expect(Buffer.byteLength(html)).toBeLessThanOrEqual(MCP_APPS_MAX_BYTES);+ f.resource.mockResolvedValue({ result: f.contents(html) });+ for (let attempt = 0; attempt < 5; attempt++)+ await expect(f.host.open('device:phone', 'task', 'card', {})).rejects.toThrow(+ 'MCP_APP_RESOURCE_TOO_LARGE',+ );+ expect((await f.host.open('renderer:local', 'task', 'card', {})).html).toBe(html);+ f.resource.mockResolvedValue({ result: f.contents('small') });+ expect(await f.host.open('device:phone', 'task', 'card', {})).toHaveProperty('viewId');+ },+ );++ it.each(['device:phone', 'renderer:local'])(+ 'applies UTF-8 event backpressure to %s without interrupting another controller',+ async (caller) => {+ const f = fixture();+ const healthy = await initialized(f.host, 'device:healthy');+ const target = await initialized(f.host, caller);+ const limit = caller.startsWith('device:') ? MCP_APPS_MAX_REMOTE_BYTES : MCP_APPS_MAX_BYTES;+ const text = '汉'.repeat(Math.floor(limit / 3) + 1);+ expect(JSON.stringify(f.contents(text)).length).toBeLessThan(limit);+ f.readResource.mockResolvedValueOnce(f.contents(text));+ const poll = f.host.poll(caller, 'task', target.viewId, target.after);+ const rejected = expect(poll).rejects.toThrow('MCP_APP_BACKPRESSURE');+ await f.host.dispatch(caller, 'task', target.viewId, {+ jsonrpc: '2.0',+ id: 2,+ method: 'resources/read',+ params: { uri: 'ui://form' },+ });+ await rejected;+ await f.host.dispatch('device:healthy', 'task', healthy.viewId, {+ jsonrpc: '2.0',+ id: 3,+ method: 'ping',+ });+ const events = await f.host.poll('device:healthy', 'task', healthy.viewId, healthy.after);+ expect(+ events.some(+ (event) =>+ event.message &&+ 'id' in event.message &&+ event.message.id === 3 &&+ 'result' in event.message,+ ),+ ).toBe(true);+ expect(f.connection.close).not.toHaveBeenCalled();+ },+ );++ it('reclaims the same UTF-8 bytes after acknowledgement and transports near-limit poll results', async () => {+ const f = fixture();+ const caller = 'device:phone';+ const view = await initialized(f.host, caller);+ const text = '汉'.repeat(Math.floor((MCP_APPS_MAX_REMOTE_BYTES - 1024) / 3));+ f.readResource.mockResolvedValue(f.contents(text));+ for (let id = 2; id < 5; id++) {+ const poll = f.host.poll(caller, 'task', view.viewId, view.after);+ await f.host.dispatch(caller, 'task', view.viewId, {+ jsonrpc: '2.0',+ id,+ method: 'resources/read',+ params: { uri: 'ui://form' },+ });+ const events = await poll;+ expect(Buffer.byteLength(JSON.stringify(events))).toBeLessThanOrEqual(+ MCP_APPS_MAX_REMOTE_BYTES,+ );+ expect(() => encodeReliableFrames(wire(events), 'stream', id)).not.toThrow();+ const response = events.find(+ (event) => event.message && 'id' in event.message && event.message.id === id,+ )?.message as JSONRPCMessage;+ expect(response).toHaveProperty('result.contents.0.text', text);+ view.after = events.at(-1)!.seq;+ }+ });+});diff --git a/apps/desktop/src/main/mcp-apps/connection.ts b/apps/desktop/src/main/mcp-apps/connection.tsnew file mode 100644index 0000000000..b0722599a4--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/connection.ts@@ -0,0 +1,209 @@+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';+import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';+import {+ ToolListChangedNotificationSchema,+ ResourceListChangedNotificationSchema,+ PromptListChangedNotificationSchema,+ ResourceUpdatedNotificationSchema,+ LoggingMessageNotificationSchema,+ TaskStatusNotificationSchema,+ CancelledNotificationSchema,+ type Notification,+ type ClientCapabilities,+ type RequestId,+ type Tool,+} from '@modelcontextprotocol/sdk/types.js';++type AppServerNotification = Notification;+import { RESOURCE_MIME_TYPE } from '@modelcontextprotocol/ext-apps/server';+import { MCP_APPS_EXTENSION } from './protocol.js';++export interface AppServerConfig {+ id: string;+ url: string;+ transport: 'http' | 'sse';+ headers?: Record<string, string>;+}++/** Credentials and the MCP client always stay in Main, never in a View. */+export class AppConnection {+ private createClient(): Client {+ const capabilities = this.peer?.capabilities() ?? {};+ const client = new Client(+ { name: 'Cindy', version: '1.0.0' },+ {+ capabilities: {+ ...capabilities,+ extensions: {+ ...capabilities.extensions,+ [MCP_APPS_EXTENSION]: { mimeTypes: [RESOURCE_MIME_TYPE] },+ },+ },+ },+ );+ if (this.peer) {+ const peer = this.peer;+ const pending = new Map<RequestId, AbortController>();+ client.fallbackRequestHandler = async (request, extra) => {+ const cancelled = new AbortController();+ pending.set(extra.requestId, cancelled);+ try {+ return await peer.request(request, {+ ...extra,+ signal: AbortSignal.any([extra.signal, cancelled.signal]),+ });+ } finally {+ pending.delete(extra.requestId);+ }+ };+ // SDK 1.29 ignores cancellation of numeric request ID 0. Main owns these+ // forwarded handlers, so cancel by exact ID without changing SDK internals.+ client.setNotificationHandler(CancelledNotificationSchema, (message) => {+ const requestId = message.params.requestId;+ if (requestId !== undefined) pending.get(requestId)?.abort(message.params.reason);+ });+ }+ return client;+ }+ private client?: Client;+ private connecting?: Promise<Client>;+ private closed = false;+ private readonly listeners = new Set<(message: AppServerNotification) => void>();+ get isClosed(): boolean {+ return this.closed;+ }++ constructor(+ readonly config: AppServerConfig,+ private readonly peer?: {+ capabilities(): ClientCapabilities;+ request: NonNullable<Client['fallbackRequestHandler']>;+ },+ ) {}++ async getClient(signal?: AbortSignal): Promise<Client> {+ signal?.throwIfAborted();+ if (this.closed) throw new Error('MCP_APP_CONNECTION_CLOSED');+ if (!this.connecting) {+ const client = this.createClient();+ this.client = client;+ const requestInit = { headers: this.config.headers };+ const url = new URL(this.config.url);+ const transport =+ this.config.transport === 'sse'+ ? new SSEClientTransport(url, {+ requestInit,+ eventSourceInit: {+ fetch: (input, init) =>+ fetch(input, { ...init, headers: { ...this.config.headers, ...init?.headers } }),+ },+ })+ : new StreamableHTTPClientTransport(url, { requestInit });+ // A transport loss retires only this attempt. A later independent request+ // may connect again; requests already sent are never replayed here.+ const retire = () => {+ if (this.client !== client) return;+ this.client = undefined;+ this.connecting = undefined;+ };+ client.onclose = retire;+ this.connecting = client.connect(transport, { timeout: 30_000 }).then(() => {+ if (this.closed || this.client !== client) throw new Error('MCP_APP_CONNECTION_CLOSED');+ for (const schema of [+ ToolListChangedNotificationSchema,+ ResourceListChangedNotificationSchema,+ PromptListChangedNotificationSchema,+ ResourceUpdatedNotificationSchema,+ LoggingMessageNotificationSchema,+ TaskStatusNotificationSchema,+ ]) {+ client.setNotificationHandler(schema, (message) => {+ this.listeners.forEach((listener) => listener(message));+ });+ }+ client.fallbackNotificationHandler = async (message) => {+ this.listeners.forEach((listener) => listener(message));+ };+ return client;+ }).catch(async (error) => {+ retire();+ await client.close().catch(() => {});+ throw error;+ });+ }+ if (!signal) return this.connecting;+ const connecting = this.connecting;+ // Initialization is shared. Cancel only this waiter, leaving peers and the+ // bounded connection attempt intact; observe late failures after cancellation.+ return new Promise<Client>((resolve, reject) => {+ const abort = () => {+ signal.removeEventListener('abort', abort);+ reject(signal.reason);+ };+ signal.addEventListener('abort', abort, { once: true });+ connecting.then(+ (client) => {+ signal.removeEventListener('abort', abort);+ resolve(client);+ },+ (error: unknown) => {+ signal.removeEventListener('abort', abort);+ reject(error);+ },+ );+ if (signal.aborted) abort();+ });+ }++ async tools(signal?: AbortSignal): Promise<Tool[]> {+ const client = await this.getClient(signal);+ const tools: Tool[] = [];+ let cursor: string | undefined;+ const seen = new Set<string>();+ do {+ const page = await client.listTools(cursor ? { cursor } : undefined, { signal });+ tools.push(...page.tools);+ cursor = page.nextCursor;+ if (cursor && seen.has(cursor)) throw new Error('MCP_APP_INVALID_PAGINATION');+ if (cursor) seen.add(cursor);+ if (seen.size > 100 || tools.length > 10_000) throw new Error('MCP_APP_TOOL_LIST_TOO_LARGE');+ } while (cursor);+ return tools;+ }++ async close(): Promise<void> {+ this.closed = true;+ this.listeners.clear();+ await this.client?.close();+ }++ listen(listener: (message: AppServerNotification) => void): () => void {+ this.listeners.add(listener);+ return () => this.listeners.delete(listener);+ }++ async resource(uri: string, signal?: AbortSignal) {+ const client = await this.getClient(signal);+ const result = await client.readResource({ uri }, { signal });+ if (result.contents.some((item) => item.uri === uri && item._meta?.ui !== undefined))+ return { result };+ let cursor: string | undefined;+ const seen = new Set<string>();+ // Metadata may live on resources/list. servers without listing still support read.+ try {+ do {+ const page = await client.listResources(cursor ? { cursor } : undefined, { signal });+ const resource = page.resources.find((item) => item.uri === uri);+ if (resource) return { result, meta: resource._meta?.ui };+ cursor = page.nextCursor;+ if (cursor && (seen.has(cursor) || seen.size >= 100))+ throw new Error('MCP_APP_INVALID_PAGINATION');+ if (cursor) seen.add(cursor);+ } while (cursor);+ } catch {+ /* Resource reads do not require list support. */+ }+ return { result };+ }+}diff --git a/apps/desktop/src/main/mcp-apps/host.ts b/apps/desktop/src/main/mcp-apps/host.tsnew file mode 100644index 0000000000..a7a9a2bf9e--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/host.ts@@ -0,0 +1,984 @@+import { randomUUID, randomBytes, createHmac } from 'node:crypto';+import { Buffer } from 'node:buffer';+import { AppBridge, type McpUiHostContext } from '@modelcontextprotocol/ext-apps/app-bridge';+import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';+import {+ JSONRPCMessageSchema,+ CallToolResultSchema,+ ListToolsRequestSchema,+ type JSONRPCMessage,+ type Tool,+ type CallToolResult,+} from '@modelcontextprotocol/sdk/types.js';+import type { McpAppRecord, McpAppDocument } from '../../shared/mcpApps.js';+import { MCP_APP_LINK_GRANT_MS, type McpAppLinkAuthorization } from '../../shared/mcpApps.js';+import type { McpAppMessageGuard } from './message.js';+import { AppConnection, type AppServerConfig } from './connection.js';+import {+ appCsp,+ boundedAppRecord,+ readAppResource,+ safeAppLink,+ toolVisibleTo,+ uiToolUri,+ MCP_APPS_MAX_BYTES,+ MCP_APPS_MAX_REMOTE_BYTES,+} from './protocol.js';++export interface McpAppsHostDeps {+ owner(): object | undefined;+ config(id: string): AppServerConfig | undefined;+ /** Desktop injects an owner-scoped vault key so revisions survive restarts. */+ revisionKey?(): string;+ readCard(sessionId: string, clientId: string): Promise<McpAppRecord>;+ writeCard(sessionId: string, clientId: string, record: McpAppRecord): Promise<void>;+ authorizeTool(+ sessionId: string,+ tool: Tool,+ args: Record<string, unknown>,+ signal: AbortSignal,+ ): Promise<void>;+ sendMessage(+ sessionId: string,+ record: McpAppRecord,+ content: unknown[],+ assertCurrent: McpAppMessageGuard,+ ): Promise<void>;+ disposeDocument?(viewId: string): void;+ connection?(config: AppServerConfig): AppConnection;+ audit?(method: string): void;+}++/** A send consumes only the captured updates, after the Agent accepts its input. */+export interface McpAppModelContext {+ text: string;+ assertCurrent(): Promise<void>;+ consume(): void;+}++class ViewTransport implements Transport {+ onmessage?: Transport['onmessage'];+ onerror?: Transport['onerror'];+ onclose?: Transport['onclose'];+ seq = 0;+ readonly events: import('../../shared/mcpApps.js').McpAppHostEvent<JSONRPCMessage>[] = [];+ private bytes = 2; // The serialized array's brackets also count toward the budget.+ private wake?: () => void;+ private failed = false;+ private closed = false;+ constructor(private readonly maxBytes: number) {}+ async start(): Promise<void> {}+ async send(message: JSONRPCMessage): Promise<void> {+ this.enqueue({ seq: ++this.seq, message });+ }+ openLink(id: string, url: string): void {+ this.enqueue({ seq: ++this.seq, openLink: { id, url } });+ }+ private enqueue(event: (typeof this.events)[number]): void {+ const bytes =+ this.bytes + Buffer.byteLength(JSON.stringify(event)) + (this.events.length ? 1 : 0);+ if (this.failed || bytes > this.maxBytes || this.events.length >= 256) {+ this.failed = true;+ this.wake?.();+ return;+ }+ this.bytes = bytes;+ this.events.push(event);+ this.wake?.();+ }+ async poll(after: number): Promise<(typeof this.events)[number][]> {+ if (this.closed) throw new Error('MCP_APP_VIEW_UNAVAILABLE');+ if (this.failed) throw new Error('MCP_APP_BACKPRESSURE');+ while (this.events[0]?.seq <= after) {+ const event = this.events.shift()!;+ this.bytes -= Buffer.byteLength(JSON.stringify(event)) + (this.events.length ? 1 : 0);+ }+ if (!this.events.length) {+ if (this.wake) throw new Error('MCP_APP_POLL_ALREADY_PENDING');+ await new Promise<void>((resolve) => {+ const timer = setTimeout(() => {+ this.wake = undefined;+ resolve();+ }, 10_000);+ this.wake = () => {+ clearTimeout(timer);+ this.wake = undefined;+ resolve();+ };+ });+ }+ if (this.closed) throw new Error('MCP_APP_VIEW_UNAVAILABLE');+ if (this.failed) throw new Error('MCP_APP_BACKPRESSURE');+ return this.events.filter((event) => event.seq > after);+ }+ async close(): Promise<void> {+ // Revocation can win after Host authorization but before poll installs its wake.+ this.closed = true;+ this.wake?.();+ this.onclose?.();+ }+}++interface View {+ openId?: string;+ owner: object;+ caller: string;+ sessionId: string;+ clientId: string;+ record: McpAppRecord;+ connection: AppConnection;+ bridge: AppBridge;+ transport: ViewTransport;+ initialized: boolean;+ inputSent: boolean;+ resultSent: boolean;+ context: McpUiHostContext;+ lastUsed: number;+ unlisten: (() => void)[];+ links: Map<string, { url: string; claim: () => void; resolve: (success: boolean) => void }>;+}++// Standalone, non-persistent Hosts still need a private key. Desktop supplies+// its persistent vault key through revisionKey; this default never leaves Main.+const transientRevisionKey = randomBytes(32).toString('hex');+export function appServerRevision(config: AppServerConfig, key = transientRevisionKey): string {+ return createHmac('sha256', key)+ .update('cindy:mcp-app-server-revision:v1\0')+ .update(JSON.stringify([config.id, config.url, config.transport, config.headers]))+ .digest('hex');+}++/** One official AppBridge per View; all requests are bound to a host-verified card. */+export class McpAppsHost {+ private readonly views = new Map<string, View>();+ private readonly opening = new Map<+ string,+ { owner: object; caller: string; abort: AbortController }+ >();+ private readonly cancelledOpens = new Map<string, { owner: object; until: number }>();+ private readonly connections = new Map<+ string,+ { owner: object; connection: AppConnection; retired?: boolean }+ >();+ private readonly contexts = new Map<+ string,+ {+ owner: object;+ sessionId: string;+ clientId: string;+ serverId: string;+ revision: string;+ value: unknown;+ }+ >();+ private readonly connectionIds = new WeakMap<AppConnection, string>();+ private sweepTimer?: ReturnType<typeof setInterval>;+ constructor(private readonly deps: McpAppsHostDeps) {}++ serverRevision(config: AppServerConfig): string {+ return appServerRevision(config, this.deps.revisionKey?.());+ }++ captureOwner(): object {+ const owner = this.deps.owner();+ if (!owner) throw new Error('MCP_APP_OWNER_UNAVAILABLE');+ return owner;+ }++ assertOwner(owner: object): void {+ if (owner !== this.deps.owner()) throw new Error('MCP_APP_OWNER_CHANGED');+ }++ registerConnection(connection: AppConnection, owner = this.captureOwner()): string {+ this.assertOwner(owner);+ const existing = this.connectionIds.get(connection);+ if (existing && this.connections.has(existing)) return existing;+ if (this.connections.size >= 256) throw new Error('MCP_APP_CONNECTION_LIMIT');+ const id = randomUUID();+ this.connections.set(id, { owner, connection });+ this.connectionIds.set(connection, id);+ return id;+ }++ async releaseConnection(connection: AppConnection): Promise<void> {+ const id = this.connectionIds.get(connection);+ const entry = id ? this.connections.get(id) : undefined;+ if (entry) entry.retired = true;+ if ([...this.views.values()].some((view) => view.connection === connection)) return;+ if (id) this.connections.delete(id);+ await connection.close();+ }++ async open(+ caller: string,+ sessionId: string,+ clientId: string,+ hostContext: McpUiHostContext,+ openId?: string,+ ): Promise<McpAppDocument> {+ const owner = this.captureOwner();+ const key = JSON.stringify([caller, sessionId, openId ?? randomUUID()]);+ this.pruneCancelledOpens();+ if (this.cancelledOpens.get(key)?.owner === owner) throw new Error('MCP_APP_OPEN_CANCELLED');+ if (this.opening.has(key) || this.opening.size >= 256) throw new Error('MCP_APP_VIEW_LIMIT');+ const pending = { owner, caller, abort: new AbortController() };+ this.opening.set(key, pending);+ const timer = setTimeout(() => pending.abort.abort(new Error('MCP_APP_OPEN_TIMEOUT')), 90_000);+ let onAbort!: () => void;+ const cancelled = new Promise<never>((_resolve, reject) => {+ onAbort = () => reject(pending.abort.signal.reason);+ pending.abort.signal.addEventListener('abort', onAbort, { once: true });+ });+ try {+ return await Promise.race([+ this.openView(caller, sessionId, clientId, hostContext, pending.abort.signal, openId),+ cancelled,+ ]);+ } finally {+ clearTimeout(timer);+ pending.abort.signal.removeEventListener('abort', onAbort);+ if (this.opening.get(key) === pending) this.opening.delete(key);+ }+ }++ async cancelOpen(caller: string, sessionId: string, openId: string): Promise<void> {+ const key = JSON.stringify([caller, sessionId, openId]);+ this.pruneCancelledOpens();+ // Cancellation may win the IPC authorization race before open reaches Host.+ // Keep a bounded tombstone longer than the complete control-side budget.+ if (this.cancelledOpens.size >= 512)+ this.cancelledOpens.delete(this.cancelledOpens.keys().next().value!);+ this.cancelledOpens.set(key, { owner: this.captureOwner(), until: Date.now() + 180_000 });+ const pending = this.opening.get(key);+ if (pending && pending.owner === this.deps.owner())+ pending.abort.abort(new Error('MCP_APP_OPEN_CANCELLED'));+ for (const [id, view] of this.views) {+ if (+ view.owner === this.deps.owner() &&+ view.caller === caller &&+ view.sessionId === sessionId &&+ view.openId === openId+ )+ await this.disposeView(id, view);+ }+ }++ async releaseCaller(caller: string): Promise<void> {+ for (const pending of this.opening.values())+ if (pending.caller === caller) pending.abort.abort(new Error('MCP_APP_OPEN_CANCELLED'));+ // The renderer and its iframes are already gone. Revoke Views synchronously,+ // without waiting for teardown or the idle sweep, before its replacement opens.+ await Promise.allSettled(+ [...this.views]+ .filter(([, view]) => view.caller === caller)+ .map(([id, view]) => this.disposeView(id, view)),+ );+ }++ private pruneCancelledOpens(): void {+ for (const [key, entry] of this.cancelledOpens)+ if (entry.owner !== this.deps.owner() || entry.until <= Date.now())+ this.cancelledOpens.delete(key);+ }++ private async openView(+ caller: string,+ sessionId: string,+ clientId: string,+ hostContext: McpUiHostContext,+ signal: AbortSignal,+ openId?: string,+ ): Promise<McpAppDocument> {+ await this.sweep();+ signal.throwIfAborted();+ const owner = this.deps.owner();+ if (!owner) throw new Error('MCP_APP_OWNER_UNAVAILABLE');+ if (+ [...this.views.values()].filter((view) => view.caller === caller).length >=+ (caller.startsWith('device:') ? 4 : 16)+ )+ throw new Error('MCP_APP_VIEW_LIMIT');+ let record = await this.deps.readCard(sessionId, clientId);+ signal.throwIfAborted();+ const config = this.deps.config(record.serverId);+ if (!config || this.serverRevision(config) !== record.serverRevision)+ throw new Error('MCP_APP_SERVER_CHANGED');+ const connectionId = (record as McpAppRecord & { connectionId?: string }).connectionId;+ const registered = connectionId ? this.connections.get(connectionId) : undefined;+ const detached = !registered || registered.owner !== owner || registered.connection.isClosed;+ // An unknown connection belongs to a previous Host lifetime. Its original+ // call cannot finish here, and replaying it could repeat a side effect.+ // Persist the terminal state before reconnecting, even if loading later fails.+ if (!registered && !record.result && !record.cancelled) {+ record = { ...record, cancelled: 'Tool execution interrupted before completion' };+ await this.updateResult(sessionId, clientId, record, owner);+ signal.throwIfAborted();+ }+ const connection =+ registered?.owner === owner && !registered.connection.isClosed+ ? registered.connection+ : (this.deps.connection?.(config) ?? new AppConnection(config));+ const registeredId = this.registerConnection(connection, owner);+ if (detached) this.connections.get(registeredId)!.retired = true;+ try {+ const client = await connection.getClient();+ signal.throwIfAborted();+ const tool = (await connection.tools(signal)).find((item) => item.name === record.tool.name);+ if (!tool || uiToolUri(tool) !== record.resourceUri)+ throw new Error('MCP_APP_TOOL_UNAVAILABLE');+ const loaded = await connection.resource(record.resourceUri, signal);+ signal.throwIfAborted();+ const resource = readAppResource(loaded.result, record.resourceUri, loaded.meta);+ const policy = appCsp(resource.meta);+ if (owner !== this.deps.owner()) throw new Error('MCP_APP_OWNER_CHANGED');+ // Recheck after async resource loading so simultaneous opens share the limit.+ if (+ [...this.views.values()].filter((view) => view.caller === caller).length >=+ (caller.startsWith('device:') ? 4 : 16)+ )+ throw new Error('MCP_APP_VIEW_LIMIT');+ const viewId = randomUUID();+ const document: McpAppDocument = {+ viewId,+ html: resource.html,+ csp: policy.header,+ policy: policy.csp,+ prefersBorder: resource.meta.prefersBorder !== false,+ };+ const remote = caller.startsWith('device:');+ if (remote && Buffer.byteLength(JSON.stringify(document)) > MCP_APPS_MAX_REMOTE_BYTES)+ throw new Error('MCP_APP_RESOURCE_TOO_LARGE');+ const transport = new ViewTransport(remote ? MCP_APPS_MAX_REMOTE_BYTES : MCP_APPS_MAX_BYTES);+ const context: McpUiHostContext = {+ ...hostContext,+ toolInfo: { tool, id: clientId },+ displayMode: 'inline',+ availableDisplayModes:+ hostContext.platform === 'mobile' ? ['inline'] : ['inline', 'fullscreen'],+ };+ const capabilities = client.getServerCapabilities();+ const bridge = new AppBridge(+ null,+ { name: 'Cindy', version: '1.0.0' },+ {+ openLinks: {},+ ...(capabilities?.tools+ ? { serverTools: { listChanged: capabilities.tools.listChanged } }+ : {}),+ ...(capabilities?.resources+ ? { serverResources: { listChanged: capabilities.resources.listChanged } }+ : {}),+ logging: {},+ message: { text: {}, resourceLink: {} },+ updateModelContext: { text: {}, structuredContent: {} },+ sandbox: { permissions: {}, csp: policy.csp },+ },+ { hostContext: context },+ );+ const view: View = {+ openId,+ owner,+ caller,+ sessionId,+ clientId,+ record,+ connection,+ bridge,+ transport,+ context,+ initialized: false,+ inputSent: false,+ resultSent: false,+ lastUsed: Date.now(),+ unlisten: [],+ links: new Map(),+ };+ this.views.set(viewId, view);+ if (!this.sweepTimer) {+ this.sweepTimer = setInterval(() => {+ void this.sweep().catch(() => {});+ }, 30_000);+ this.sweepTimer.unref();+ }+ const assertCurrent = () => this.assertCurrentView(viewId, view);+ const currentClient = async (signal: AbortSignal) => {+ await assertCurrent();+ signal.throwIfAborted();+ const current = await connection.getClient(signal);+ // Reconnecting can outlive a cancellation, card clear or owner change.+ await assertCurrent();+ signal.throwIfAborted();+ return current;+ };+ const currentResult = async <T>(pending: Promise<T>, signal: AbortSignal): Promise<T> => {+ const result = await pending;+ // Authorization can change while the server is working. Discard the late+ // result before AppBridge can send it; never replay the upstream request.+ await assertCurrent();+ signal.throwIfAborted();+ return result;+ };+ bridge.oninitialized = () => {+ if (view.initialized || !bridge.getAppCapabilities()) return;+ view.initialized = true;+ bridge.setHostContext(view.context);+ void assertCurrent()+ .then(() => bridge.sendToolInput({ arguments: record.arguments }))+ .then(() => {+ view.inputSent = true;+ return this.sendResult(viewId, view);+ })+ .catch(() => {+ void this.disposeView(viewId, view);+ });+ };+ bridge.oncalltool = async (params, extra) => {+ await assertCurrent();+ const tools = await currentResult(connection.tools(extra.signal), extra.signal);+ const target = tools.find((item) => item.name === params.name);+ if (!target || !toolVisibleTo(target, 'app')) throw new Error('MCP_APP_TOOL_NOT_VISIBLE');+ await this.deps.authorizeTool(sessionId, target, params.arguments ?? {}, extra.signal);+ const client = await currentClient(extra.signal);+ return (await currentResult(+ client.callTool(params, CallToolResultSchema, { signal: extra.signal }),+ extra.signal,+ )) as CallToolResult;+ };+ bridge.setRequestHandler(ListToolsRequestSchema, async (_params, extra) => {+ await assertCurrent();+ const tools = await currentResult(connection.tools(extra.signal), extra.signal);+ return { tools: tools.filter((item) => toolVisibleTo(item, 'app')) };+ });+ bridge.onreadresource = async (params, extra) => {+ const client = await currentClient(extra.signal);+ return currentResult(client.readResource(params, { signal: extra.signal }), extra.signal);+ };+ bridge.onlistresources = async (params, extra) => {+ const client = await currentClient(extra.signal);+ return currentResult(client.listResources(params, { signal: extra.signal }), extra.signal);+ };+ bridge.onlistresourcetemplates = async (params, extra) => {+ const client = await currentClient(extra.signal);+ return currentResult(+ client.listResourceTemplates(params, { signal: extra.signal }),+ extra.signal,+ );+ };+ bridge.onlistprompts = async (params, extra) => {+ const client = await currentClient(extra.signal);+ return currentResult(client.listPrompts(params, { signal: extra.signal }), extra.signal);+ };+ bridge.onmessage = async (params) => {+ await assertCurrent();+ const content = Array.isArray(params.content) ? params.content : [params.content];+ if (content.some((block) => block.type !== 'text' && block.type !== 'resource_link'))+ throw new Error('MCP_APP_MESSAGE_CONTENT_UNSUPPORTED');+ await this.deps.sendMessage(sessionId, record, content, assertCurrent);+ return {};+ };+ bridge.onupdatemodelcontext = async (params) => {+ await assertCurrent();+ if (Buffer.byteLength(JSON.stringify(params), 'utf8') > 128_000)+ throw new Error('MCP_APP_CONTEXT_TOO_LARGE');+ const { content, structuredContent } = params;+ if (content?.some((block) => block.type !== 'text'))+ throw new Error('MCP_APP_CONTEXT_CONTENT_UNSUPPORTED');+ const key = `${sessionId}:${clientId}`;+ if (this.contexts.size >= 256 && !this.contexts.has(key)) {+ await this.pruneModelContexts();+ // Pruning reads other cards and can outlive this View's authorization.+ await assertCurrent();+ }+ const next = {+ app: record.serverId,+ resourceUri: record.resourceUri,+ content,+ structuredContent,+ };+ const aggregateBytes = () => {+ const values = [...this.contexts.entries()]+ .filter(+ ([id, item]) => id !== key && item.owner === owner && item.sessionId === sessionId,+ )+ .map(([, item]) => item.value);+ values.push(next);+ return Buffer.byteLength(JSON.stringify(values), 'utf8');+ };+ let bytes = aggregateBytes();+ if (bytes > 512_000) {+ await this.pruneModelContexts();+ await assertCurrent();+ bytes = aggregateBytes();+ }+ // Recompute from the live map after cleanup; no await may separate the+ // final budget checks from publishing, or a concurrent update can overfill it.+ if (bytes > 512_000) throw new Error('MCP_APP_CONTEXT_TOO_LARGE');+ if (this.contexts.size >= 256 && !this.contexts.has(key))+ throw new Error('MCP_APP_CONTEXT_LIMIT');+ this.contexts.set(key, {+ owner,+ sessionId,+ clientId,+ serverId: record.serverId,+ revision: record.serverRevision,+ value: next,+ });+ return {};+ };+ bridge.onopenlink = async (params) => {+ await assertCurrent();+ const url = safeAppLink(params.url);+ if (view.links.size >= 4) throw new Error('MCP_APP_LINK_LIMIT');+ const id = randomUUID();+ const success = await new Promise<boolean>((resolve) => {+ const finish = (success: boolean) => {+ clearTimeout(timer);+ view.links.delete(id);+ resolve(success);+ };+ let timer = setTimeout(() => finish(false), 10_000);+ let claimed = false;+ view.links.set(id, {+ url,+ claim: () => {+ if (claimed) throw new Error('MCP_APP_LINK_ALREADY_AUTHORIZED');+ claimed = true;+ clearTimeout(timer);+ // The pending request cannot fail at its old deadline while the grant travels.+ timer = setTimeout(() => finish(false), MCP_APP_LINK_GRANT_MS);+ },+ resolve: finish,+ });+ transport.openLink(id, url);+ });+ if (!success) throw new Error('MCP_APP_LINK_OPEN_FAILED');+ return {};+ };+ bridge.onrequestdisplaymode = async (params) => {+ await assertCurrent();+ const modes = bridge.getAppCapabilities()?.availableDisplayModes ??+ context.availableDisplayModes ?? ['inline'];+ const mode =+ modes.includes(params.mode) && view.context.availableDisplayModes?.includes(params.mode)+ ? params.mode+ : (view.context.displayMode ?? 'inline');+ view.context = { ...view.context, displayMode: mode };+ bridge.setHostContext(view.context);+ return { mode };+ };+ // Accept application logging without persisting user data to the host diagnostic log.+ bridge.onloggingmessage = () => {};+ view.unlisten.push(+ connection.listen((message) => {+ if (!view.initialized || owner !== this.deps.owner()) return;+ if (message.method === 'notifications/tools/list_changed')+ void bridge.sendToolListChanged(message.params).catch(() => {});+ if (message.method === 'notifications/resources/list_changed')+ void bridge.sendResourceListChanged(message.params).catch(() => {});+ if (message.method === 'notifications/prompts/list_changed')+ void bridge.sendPromptListChanged(message.params).catch(() => {});+ }),+ );+ try {+ await bridge.connect(transport);+ // Register before rereading: tool completion during loading must reach this+ // View, and a clear or configuration change must prevent publishing it.+ const latest = await this.deps.readCard(sessionId, clientId);+ signal.throwIfAborted();+ this.view(caller, sessionId, viewId);+ if (+ latest.serverId !== record.serverId ||+ latest.serverRevision !== record.serverRevision ||+ latest.resourceUri !== record.resourceUri ||+ latest.tool.name !== record.tool.name+ )+ throw new Error('MCP_APP_CARD_UNAVAILABLE');+ // A completion delivered while the database read was pending is newer+ // than that read's snapshot; never replace it with an unfinished record.+ if (!view.record.result && !view.record.cancelled) view.record = latest;+ } catch (error) {+ await this.disposeView(viewId, view);+ throw error;+ }+ return document;+ } catch (error) {+ if (detached) await this.releaseConnection(connection).catch(() => {});+ throw error;+ }+ }++ async updateResult(+ sessionId: string,+ clientId: string,+ record: McpAppRecord,+ owner = this.captureOwner(),+ ): Promise<void> {+ this.assertOwner(owner);+ record = boundedAppRecord(record);+ try {+ await this.deps.writeCard(sessionId, clientId, record);+ this.assertOwner(owner);+ for (const [id, view] of this.views)+ if (view.owner === owner && view.sessionId === sessionId && view.clientId === clientId) {+ view.record = record;+ if (view.inputSent) await this.sendResult(id, view);+ }+ } catch (error) {+ // Persistence and card-wide authorization failures revoke every matching View.+ // Caller-local closure and transport failures are isolated inside sendResult.+ await Promise.allSettled(+ [...this.views]+ .filter(+ ([, view]) =>+ view.owner === owner && view.sessionId === sessionId && view.clientId === clientId,+ )+ .map(([id, view]) => this.disposeView(id, view)),+ );+ throw error;+ }+ }++ async assertViewAuthorized(caller: string, sessionId: string, id: string): Promise<void> {+ await this.assertCurrentView(id, this.view(caller, sessionId, id));+ }++ private async assertCurrentView(id: string, view: View): Promise<void> {+ this.view(view.caller, view.sessionId, id);+ const latest = await this.deps.readCard(view.sessionId, view.clientId);+ this.view(view.caller, view.sessionId, id);+ if (+ latest.serverId !== view.record.serverId ||+ latest.serverRevision !== view.record.serverRevision ||+ latest.resourceUri !== view.record.resourceUri ||+ latest.tool.name !== view.record.tool.name+ )+ throw new Error('MCP_APP_CARD_UNAVAILABLE');+ }++ private async sendResult(id: string, view: View): Promise<void> {+ if (view.resultSent || (!view.record.result && !view.record.cancelled)) return;+ try {+ await this.assertCurrentView(id, view);+ } catch (error) {+ // A caller can close while its card read is pending. The saved result+ // still belongs to active peers; only shared authorization failures escape.+ if (this.views.get(id) !== view) return;+ throw error;+ }+ // Initialization and completion can both wait on the same authorization read.+ if (view.resultSent) return;+ try {+ if (view.record.result) {+ view.resultSent = true;+ await view.bridge.sendToolResult(view.record.result as CallToolResult);+ } else if (view.record.cancelled) {+ view.resultSent = true;+ await view.bridge.sendToolCancelled({ reason: view.record.cancelled });+ }+ } catch {+ // A broken transport cannot invalidate a successfully persisted card.+ await this.disposeView(id, view).catch(() => {});+ }+ }++ private view(caller: string, sessionId: string, id: string): View {+ const view = this.views.get(id);+ if (+ !view ||+ view.caller !== caller ||+ view.sessionId !== sessionId ||+ view.owner !== this.deps.owner()+ )+ throw new Error('MCP_APP_VIEW_UNAVAILABLE');+ const config = this.deps.config(view.record.serverId);+ if (!config || this.serverRevision(config) !== view.record.serverRevision)+ throw new Error('MCP_APP_SERVER_CHANGED');+ view.lastUsed = Date.now();+ return view;+ }++ async dispatch(caller: string, sessionId: string, id: string, input: unknown): Promise<void> {+ if (JSON.stringify(input).length > MCP_APPS_MAX_BYTES)+ throw new Error('MCP_APP_MESSAGE_TOO_LARGE');+ const view = this.view(caller, sessionId, id);+ let message = JSONRPCMessageSchema.parse(input);+ // The stable spec used one content block; newer official SDKs use an array.+ if (+ 'method' in message &&+ message.method === 'ui/message' &&+ message.params?.content &&+ !Array.isArray(message.params.content)+ ) {+ message = { ...message, params: { ...message.params, content: [message.params.content] } };+ }+ if ('method' in message && message.method === 'ui/initialize' && view.initialized) {+ if ('id' in message)+ await view.transport.send({+ jsonrpc: '2.0',+ id: message.id,+ error: { code: -32600, message: 'MCP_APP_ALREADY_INITIALIZED' },+ });+ return;+ }+ if (+ 'method' in message &&+ !view.initialized &&+ !['ui/initialize', 'ui/notifications/initialized', 'ping'].includes(message.method)+ ) {+ if ('id' in message)+ await view.transport.send({+ jsonrpc: '2.0',+ id: message.id,+ error: { code: -32000, message: 'MCP_APP_NOT_INITIALIZED' },+ });+ return;+ }+ // Sandbox messages are reserved for the trusted outer proxy, never for an App.+ if ('method' in message && message.method.startsWith('ui/notifications/sandbox-')) return;+ if ('method' in message && 'id' in message) {+ const known =+ /^(ui\/(initialize|message|update-model-context|open-link|request-display-mode)|tools\/(list|call)|resources\/(read|list|templates\/list)|prompts\/list|ping)$/.test(+ message.method,+ );+ this.deps.audit?.(known ? message.method : 'unknown');+ }+ view.transport.onmessage?.(message);+ }++ async poll(caller: string, sessionId: string, id: string, after: number) {+ if (!Number.isSafeInteger(after) || after < 0) throw new Error('MCP_APP_INVALID_CURSOR');+ const view = this.view(caller, sessionId, id);+ if (after > view.transport.seq) throw new Error('MCP_APP_INVALID_CURSOR');+ await this.assertCurrentView(id, view);+ const events = await view.transport.poll(after);+ await this.assertCurrentView(id, view);+ return events;+ }++ context(caller: string, sessionId: string, id: string, patch: McpUiHostContext): void {+ const view = this.view(caller, sessionId, id);+ const old = view.context;+ // Tool identity and granted capabilities are host-owned, never renderer overrides.+ const allowed = [+ 'theme',+ 'styles',+ 'locale',+ 'timeZone',+ 'containerDimensions',+ 'safeAreaInsets',+ 'deviceCapabilities',+ ] as const;+ const update = Object.fromEntries(+ allowed.filter((key) => Object.hasOwn(patch, key)).map((key) => [key, patch[key]]),+ );+ view.context = { ...old, ...update };+ if (view.initialized) view.bridge.setHostContext(view.context);+ }++ async authorizeLink(+ caller: string,+ sessionId: string,+ id: string,+ linkId: string,+ url?: string,+ ): Promise<McpAppLinkAuthorization> {+ const view = this.view(caller, sessionId, id);+ await this.assertCurrentView(id, view);+ const link = view.links.get(linkId);+ if (!link) throw new Error('MCP_APP_LINK_UNAVAILABLE');+ if (url !== undefined && link.url !== url) throw new Error('MCP_APP_INVALID_LINK');+ link.claim();+ return { authorized: true, validForMs: MCP_APP_LINK_GRANT_MS };+ }++ linkResult(+ caller: string,+ sessionId: string,+ id: string,+ linkId: string,+ success: boolean,+ ): void {+ this.view(caller, sessionId, id).links.get(linkId)?.resolve(success);+ }++ displayMode(+ caller: string,+ sessionId: string,+ id: string,+ mode: 'inline' | 'fullscreen' | 'pip',+ ): void {+ const view = this.view(caller, sessionId, id);+ const appModes = view.bridge.getAppCapabilities()?.availableDisplayModes;+ if (+ !view.context.availableDisplayModes?.includes(mode) ||+ (appModes && !appModes.includes(mode))+ )+ return;+ view.context = { ...view.context, displayMode: mode };+ if (view.initialized) view.bridge.setHostContext(view.context);+ }++ async teardown(+ caller: string,+ sessionId: string,+ id: string,+ alreadyNotified = false,+ ): Promise<void> {+ const view = this.view(caller, sessionId, id);+ // The controller keeps its iframe mounted until this bounded handshake finishes.+ try {+ if (view.initialized && !alreadyNotified)+ await view.bridge.teardownResource({}, { timeout: 1_000 });+ } catch {+ /* An unresponsive App must not block leaving a task. */+ }+ await this.disposeView(id, view);+ }++ private async disposeView(id: string, view: View, notify = false): Promise<void> {+ if (this.views.get(id) !== view) return;+ if (notify && view.initialized) {+ try {+ await view.bridge.teardownResource({}, { timeout: 1_000 });+ } catch {+ /* Reclaim the View even when its teardown handshake times out. */+ }+ }+ this.views.delete(id);+ if (!this.views.size) {+ clearInterval(this.sweepTimer);+ this.sweepTimer = undefined;+ }+ view.links.forEach((link) => link.resolve(false));+ this.deps.disposeDocument?.(id);+ view.unlisten.forEach((remove) => remove());+ await view.bridge.close();+ const entry = this.connections.get(this.connectionIds.get(view.connection) ?? '');+ if (entry?.retired) await this.releaseConnection(view.connection);+ }++ private async pruneModelContexts(): Promise<void> {+ // Context survives a closed View until the next model turn. Reclaim revoked+ // cards, archived tasks and obsolete configurations before refusing a new one.+ for (const [key, item] of [...this.contexts]) {+ let current = false;+ if (item.owner === this.deps.owner()) {+ try {+ const card = await this.deps.readCard(item.sessionId, item.clientId);+ const config = this.deps.config(item.serverId);+ current =+ item.owner === this.deps.owner() &&+ !!config &&+ this.serverRevision(config) === item.revision &&+ card.serverId === item.serverId &&+ card.serverRevision === item.revision;+ } catch {+ // Unavailable cards cannot contribute model context.+ }+ }+ // A concurrent update may have replaced the value while readCard waited.+ if (!current && this.contexts.get(key) === item) this.contexts.delete(key);+ }+ }++ async modelContext(sessionId: string): Promise<McpAppModelContext> {+ const owner = this.deps.owner();+ const empty: McpAppModelContext = { text: '', async assertCurrent() {}, consume() {} };+ const values: unknown[] = [];+ const captured: Array<{ clientId: string; serverId: string; revision: string }> = [];+ const removals: Array<() => void> = [];+ for (const [key, item] of [...this.contexts]) {+ if (item.owner !== owner || item.sessionId !== sessionId) continue;+ // Validation and dispatch can overlap another App update. Never remove its replacement.+ const remove = () => {+ if (this.contexts.get(key) === item) this.contexts.delete(key);+ };+ try {+ const card = await this.deps.readCard(sessionId, item.clientId);+ const config = this.deps.config(item.serverId);+ if (owner !== this.deps.owner()) return empty;+ if (+ !config ||+ this.serverRevision(config) !== item.revision ||+ card.serverRevision !== item.revision+ ) {+ remove();+ continue;+ }+ values.push(item.value);+ captured.push(item);+ removals.push(remove);+ } catch {+ remove();+ }+ }+ if (owner !== this.deps.owner()) return empty;+ const serialized = JSON.stringify(values);+ if (Buffer.byteLength(serialized, 'utf8') > 512_000)+ throw new Error('MCP_APP_CONTEXT_TOO_LARGE');+ if (!values.length) return empty;+ return {+ text: `\n[MCP App context: external application data]\n${serialized}\n[/MCP App context]`,+ assertCurrent: async () => {+ if (owner !== this.deps.owner()) throw new Error('MCP_APP_OWNER_CHANGED');+ const cards = await Promise.all(+ captured.map((item) => this.deps.readCard(sessionId, item.clientId)),+ );+ if (owner !== this.deps.owner()) throw new Error('MCP_APP_OWNER_CHANGED');+ for (const [index, item] of captured.entries()) {+ const config = this.deps.config(item.serverId);+ if (+ !config ||+ this.serverRevision(config) !== item.revision ||+ cards[index].serverRevision !== item.revision+ )+ throw new Error('MCP_APP_SERVER_CHANGED');+ }+ },+ consume: () => {+ if (owner === this.deps.owner()) removals.forEach((remove) => remove());+ },+ };+ }++ async reset(): Promise<void> {+ this.cancelledOpens.clear();+ for (const pending of this.opening.values())+ pending.abort.abort(new Error('MCP_APP_OWNER_CHANGED'));+ clearInterval(this.sweepTimer);+ this.sweepTimer = undefined;+ const views = [...this.views.entries()];+ const connections = [...this.connections.values()];+ this.contexts.clear();+ this.connections.clear();+ await Promise.allSettled(+ views.map(async ([id, view]) => {+ try {+ if (view.initialized) await view.bridge.teardownResource({}, { timeout: 1_000 });+ } catch {+ /* Owner reset must finish even when an App no longer responds. */+ }+ await this.disposeView(id, view);+ }),+ );+ await Promise.allSettled(connections.map((entry) => entry.connection.close()));+ }++ private async sweep(): Promise<void> {+ for (const [id, view] of this.views) {+ const config = this.deps.config(view.record.serverId);+ if (+ view.owner !== this.deps.owner() ||+ !config ||+ this.serverRevision(config) !== view.record.serverRevision ||+ Date.now() - view.lastUsed > 60_000+ )+ await this.disposeView(id, view, true);+ }+ for (const [id, entry] of this.connections)+ if (entry.owner !== this.deps.owner() || entry.connection.isClosed) {+ this.connections.delete(id);+ await entry.connection.close().catch(() => {});+ }+ }+}diff --git a/apps/desktop/src/main/mcp-apps/ipc.ts b/apps/desktop/src/main/mcp-apps/ipc.tsnew file mode 100644index 0000000000..6ea212712b--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/ipc.ts@@ -0,0 +1,201 @@+import { ipcMain, shell } from 'electron';+import { randomUUID } from 'node:crypto';+import { and, eq, isNull, sql } from 'drizzle-orm';+import type { InteractionRequest, InteractionDecision } from '@cindy/maker-core';+import { getCurrentDbClientSnapshot } from '../localDb/client/current.js';+import { messages, sessions } from '../localDb/schema.js';+import { createMessage, broadcastMessageRow } from '../localDb/ipc/messages.js';+import { messageToCamel } from '../localDb/mapper.js';+import { captureDataOwnerBroadcastScope } from '../device-link/broadcast-tap.js';+import { throwIpcError } from '../utils/ipcValidate.js';+import { createLogger } from '../logger.js';+import { getMcpAppRevisionKey } from '../secrets/providerSecretStore.js';+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';+import { getDeviceLinkInvokeContext } from '../device-link/invoke-context.js';+import { getRemoteLinkCloseEpoch, remoteInvoke } from '../device-link/index.js';+import { getAppCapabilities } from '../appCapabilities.js';+import { McpAppsHost, type McpAppsHostDeps } from './host.js';+import { readAppServer, setMcpAppsHost } from './runtime.js';+import { MCP_APPS_INVOKE, parseMcpAppRecord } from '../../shared/mcpApps.js';+import { handleMcpAppOperation, handleMcpAppFrameOperation } from './operations.js';+import { RemoteMcpAppViews } from './remoteViews.js';+import {+ supplyMcpAppDocument,+ removeMcpAppDocument,+ assertMcpAppDocumentCaller,+ setMcpAppCallerCleanup,+} from './sandboxProtocol.js';++export function registerMcpAppsIpc(+ send: McpAppsHostDeps['sendMessage'],+ request: (+ sessionId: string,+ input: InteractionRequest,+ signal: AbortSignal,+ ) => Promise<InteractionDecision>,+): void {+ const currentOwner = () => getCurrentDbClientSnapshot() ?? undefined;+ const assertSession = async (sessionId: string) => {+ const owner = currentOwner();+ if (!owner) throw new Error('MCP_APP_OWNER_UNAVAILABLE');+ const [session] = await owner.client.drizzle+ .select()+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ if (currentOwner() !== owner || !session || session.status !== 'active')+ throw new Error('MCP_APP_SESSION_UNAVAILABLE');+ return { owner, session };+ };+ const host = new McpAppsHost({+ owner: currentOwner,+ config: readAppServer,+ revisionKey: getMcpAppRevisionKey,+ readCard: async (sessionId, clientId) => {+ const { owner } = await assertSession(sessionId);+ const [row] = await owner.client.drizzle+ .select({ content: messages.content, meta: messages.agentMeta })+ .from(messages)+ .where(+ and(+ eq(messages.sessionId, sessionId),+ eq(messages.clientId, clientId),+ eq(messages.role, 'assistant'),+ isNull(messages.rewindAt),+ sql`EXISTS (SELECT 1 FROM sessions WHERE sessions.id = ${sessionId} AND sessions.status = 'active' AND (sessions.cleared_at IS NULL OR ${messages.createdAt} > sessions.cleared_at))`,+ ),+ )+ .limit(1);+ if (currentOwner() !== owner || !row) throw new Error('MCP_APP_CARD_UNAVAILABLE');+ const meta = row.meta ? JSON.parse(row.meta) : null;+ const record = parseMcpAppRecord(row.content ? JSON.parse(row.content) : null);+ if (!record || meta?.mcpApp !== true) throw new Error('MCP_APP_CARD_UNAVAILABLE');+ return record;+ },+ writeCard: async (sessionId, clientId, record) => {+ const { owner, session } = await assertSession(sessionId);+ const scope = captureDataOwnerBroadcastScope();+ const [row] = await owner.client.drizzle+ .select()+ .from(messages)+ .where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, clientId)))+ .limit(1);+ if (currentOwner() !== owner) throw new Error('MCP_APP_OWNER_CHANGED');+ if (row) {+ if (row.rewindAt || (session.clearedAt && row.createdAt <= session.clearedAt))+ throw new Error('MCP_APP_CARD_UNAVAILABLE');+ const existing = parseMcpAppRecord(row.content ? JSON.parse(row.content) : null);+ const meta = row.agentMeta ? JSON.parse(row.agentMeta) : null;+ if (+ row.role !== 'assistant' ||+ meta?.mcpApp !== true ||+ !existing ||+ existing.serverRevision !== record.serverRevision+ )+ throw new Error('MCP_APP_CARD_UNAVAILABLE');+ const updated = await owner.client.drizzle+ .update(messages)+ .set({ content: JSON.stringify({ mcpApp: record }) })+ .where(+ and(+ eq(messages.id, row.id),+ isNull(messages.rewindAt),+ sql`EXISTS (SELECT 1 FROM sessions WHERE sessions.id = ${sessionId} AND sessions.status = 'active' AND (sessions.cleared_at IS NULL OR ${messages.createdAt} > sessions.cleared_at))`,+ ),+ )+ .returning();+ if (currentOwner() !== owner || !updated[0]) throw new Error('MCP_APP_CARD_UNAVAILABLE');+ broadcastMessageRow(sessionId, messageToCamel(updated[0]), scope);+ } else {+ // Only the pending card may be inserted. Completion cannot resurrect a deleted grant.+ if (record.result !== undefined || record.cancelled !== undefined)+ throw new Error('MCP_APP_CARD_UNAVAILABLE');+ await createMessage(+ sessionId,+ { clientId, role: 'assistant', content: { mcpApp: record }, agentMeta: { mcpApp: true } },+ {+ broadcastOwnerScope: scope,+ beforePublish: async () => {+ const latest = await assertSession(sessionId);+ if (latest.owner !== owner || latest.session.clearedAt !== session.clearedAt)+ throw new Error('MCP_APP_CARD_UNAVAILABLE');+ },+ },+ );+ }+ },+ authorizeTool: async (sessionId, tool, args, signal) => {+ const { session } = await assertSession(sessionId);+ if (session.permissionMode === 'bypassPermissions') return;+ const decision = await request(+ sessionId,+ {+ kind: 'permission',+ requestId: randomUUID(),+ toolName: `MCP App: ${tool.name}`,+ title: tool.title ?? tool.name,+ description: tool.description,+ input: args,+ },+ signal,+ );+ if (decision.kind !== 'permission' || decision.behavior !== 'allow')+ throw new Error('MCP_APP_TOOL_DENIED');+ },+ sendMessage: send,+ disposeDocument: removeMcpAppDocument,+ audit: (method) => createLogger('mcp-apps').debug('App request', { method }),+ });+ setMcpAppsHost(host);+ const remoteViews = new RemoteMcpAppViews({+ owner: currentOwner,+ closeEpoch: getRemoteLinkCloseEpoch,+ invoke: async (deviceId, sessionId, input, preSend) => {+ if (!getAppCapabilities().canUseDeviceLink) throw new Error('MCP_APP_OWNER_ONLY');+ const result = await remoteInvoke(deviceId, MCP_APPS_INVOKE, [sessionId, input], { preSend });+ if (result.ok) return result.result;+ if (result.error.code === 'CHANNEL_NOT_ALLOWED') throw new Error('MCP_APP_CHANNEL_NOT_ALLOWED');+ throw new Error(result.error.message);+ },+ openLink: (url) => shell.openExternal(url),+ });+ setMcpAppCallerCleanup(async (caller) => {+ await Promise.allSettled([host.releaseCaller(caller), remoteViews.releaseCaller(caller)]);+ });+ ipcMain.removeHandler(MCP_APPS_INVOKE);+ ipcMain.handle(MCP_APPS_INVOKE, async (event, sessionId: unknown, raw: unknown) => {+ const remote = getDeviceLinkInvokeContext();+ if (remote?.sharedTask) throwIpcError('PRECONDITION_FAILED', 'MCP_APP_OWNER_ONLY');+ if (!remote) assertTrustedAppRendererEvent(event);+ if (typeof sessionId !== 'string') throwIpcError('INVALID_PARAMS', 'MCP_APP_INVALID_REQUEST');+ const caller = remote ? `device:${remote.controllerDeviceId}` : `renderer:${event.sender.id}`;+ try {+ if (raw && typeof raw === 'object' && 'deviceId' in raw) {+ // Incoming device-link calls cannot use this local-only route to pivot to another computer.+ if (remote) throw new Error('MCP_APP_INVALID_REQUEST');+ return await remoteViews.control(caller, raw.deviceId, sessionId, raw);+ }+ return await handleMcpAppOperation(+ host,+ caller,+ sessionId,+ raw,+ remote+ ? undefined+ : {+ supply: (document, boundCaller) => supplyMcpAppDocument(document, boundCaller, (input) =>+ handleMcpAppFrameOperation(host, boundCaller, sessionId, document.viewId, input, async (url) => {+ assertMcpAppDocumentCaller(document.viewId, boundCaller);+ await shell.openExternal(url);+ })),+ },+ );+ } catch (error) {+ const code =+ error instanceof Error && /^MCP_APP_[A-Z_]+$/.test(error.message)+ ? error.message+ : 'MCP_APP_REQUEST_FAILED';+ throwIpcError('PRECONDITION_FAILED', code);+ }+ });+}diff --git a/apps/desktop/src/main/mcp-apps/message.ts b/apps/desktop/src/main/mcp-apps/message.tsnew file mode 100644index 0000000000..f815f2a500--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/message.ts@@ -0,0 +1,58 @@+import type { ContentBlock } from '@modelcontextprotocol/sdk/types.js';++/** Main-only card authorization; neither the View nor persisted queue can mint it. */+export const MCP_APP_MESSAGE_GUARD = Symbol('MCP_APP_MESSAGE_GUARD');+export type McpAppMessageGuard = () => Promise<void>;+export const MCP_APP_MESSAGE_CLIENT_PREFIX = 'mcp-app-message:';++type McpAppQueuedMessage = {+ clientId: string;+ sourcePlugin?: { pluginId: string };+ readonly [MCP_APP_MESSAGE_GUARD]?: McpAppMessageGuard;+};++/** A crash-restored App row has no live View grant and cannot be retried. */+export function isUnrestorableMcpAppMessage(item: McpAppQueuedMessage): boolean {+ // Pre-prefix App rows can exist after upgrading. Provenance can deny a stale+ // row, but only the Main-owned Symbol above can supply a live authorization.+ return !item[MCP_APP_MESSAGE_GUARD] &&+ (item.clientId.startsWith(MCP_APP_MESSAGE_CLIENT_PREFIX) ||+ item.sourcePlugin?.pluginId.startsWith('mcp-app:') === true);+}++/** JSON/restored queue rows cannot recreate a live View grant. Fail closed. */+export function queuedAppMessageGuard(item: McpAppQueuedMessage): McpAppMessageGuard | undefined {+ if (item[MCP_APP_MESSAGE_GUARD]) return item[MCP_APP_MESSAGE_GUARD];+ if (!isUnrestorableMcpAppMessage(item)) return undefined;+ return async () => { throw new Error('MCP_APP_CARD_UNAVAILABLE'); };+}++/** Convert protocol content into the existing, attachment-aware Cindy user input. */+export function appMessageBlocks(+ content: unknown[],+): Array<{ type: string; [key: string]: unknown }> {+ return (content as ContentBlock[]).map((block) => {+ switch (block.type) {+ case 'text':+ return { type: 'text', text: block.text };+ case 'resource_link':+ return { type: 'text', text: `${block.name}: ${block.uri}` };+ case 'resource':+ if ('text' in block.resource) return { type: 'text', text: block.resource.text };+ throw new Error('MCP_APP_MESSAGE_CONTENT_UNSUPPORTED');+ default:+ throw new Error('MCP_APP_MESSAGE_CONTENT_UNSUPPORTED');+ }+ });+}++/** Keep the authored body for history, but escape native commands in model input. */+export function appMessageInput(content: unknown[]) {+ const authored = appMessageBlocks(content);+ const persistedContent = authored.map((block) => String(block.text)).join('\n');+ const blocks = authored.map((block) => ({+ ...block,+ text: String(block.text).replace(/^(\s*)\//, '$1\\/'),+ }));+ return { blocks, text: blocks.map((block) => block.text).join('\n'), persistedContent };+}diff --git a/apps/desktop/src/main/mcp-apps/messageSender.ts b/apps/desktop/src/main/mcp-apps/messageSender.tsnew file mode 100644index 0000000000..f79b624917--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/messageSender.ts@@ -0,0 +1,73 @@+import type { AgentInputQueuedMessage } from '../../shared/agentInputQueue.js';+import type { McpAppRecord } from '../../shared/mcpApps.js';+import type { MakerSendTransaction } from '../maker-ipc/makerSendTransaction.js';+import { AUTO_REVIEW_DELEGATED_CONTINUATION } from '../maker-ipc/autoReviewUserIntent.js';+import { appMessageInput, MCP_APP_MESSAGE_CLIENT_PREFIX, MCP_APP_MESSAGE_GUARD, type McpAppMessageGuard } from './message.js';++interface AppMessageSenderDeps<Meta> {+ owner(): object | null | undefined;+ readClearBoundary(sessionId: string): Promise<number | null | undefined>;+ restoreQueue(sessionId: string): Promise<void>;+ clearBoundary(sessionId: string): number | null;+ shouldQueue(sessionId: string): boolean;+ getSessionMeta(sessionId: string): Promise<Meta | null | undefined>;+ createClientId(): string;+ buildQueueItem(params: {+ targetSessionId: string;+ message: string;+ persistedContent: string;+ clientId: string;+ meta: NonNullable<Meta>;+ sourcePlugin: { pluginId: string; name: string };+ autoReviewUserText: { kind: 'delegated-continuation' };+ }): Promise<AgentInputQueuedMessage>;+ enqueue(sessionId: string, item: AgentInputQueuedMessage): void;+ sendToAgentAccepted: MakerSendTransaction['sendToAgentAccepted'];+}++/** The App's card grant is checked after preparation and at the final send fence. */+export function createAppMessageSender<Meta>(deps: AppMessageSenderDeps<Meta>) {+ return async (+ sessionId: string,+ record: McpAppRecord,+ content: unknown[],+ assertViewCurrent: McpAppMessageGuard,+ ): Promise<void> => {+ const owner = deps.owner();+ const expectedClearBoundaryMs = await deps.readClearBoundary(sessionId);+ await deps.restoreQueue(sessionId);+ const assertInputCurrent = () => {+ if (!owner || owner !== deps.owner() || deps.clearBoundary(sessionId) !== expectedClearBoundaryMs)+ throw new Error('MCP_APP_CARD_UNAVAILABLE');+ };+ const assertDispatchCurrent = async () => {+ assertInputCurrent();+ await assertViewCurrent();+ assertInputCurrent();+ };+ await assertDispatchCurrent();+ const { blocks, text, persistedContent } = appMessageInput(content);+ const sourcePlugin = { pluginId: `mcp-app:${record.serverId}`, name: record.serverId };+ const clientId = `${MCP_APP_MESSAGE_CLIENT_PREFIX}${deps.createClientId()}`;+ if (deps.shouldQueue(sessionId)) {+ const meta = await deps.getSessionMeta(sessionId);+ if (!meta) throw new Error('MCP_APP_SESSION_UNAVAILABLE');+ const item = await deps.buildQueueItem({+ targetSessionId: sessionId, message: text, persistedContent, clientId, meta, sourcePlugin,+ autoReviewUserText: { kind: 'delegated-continuation' },+ });+ await assertDispatchCurrent();+ // The symbol survives Main queue copies but never enters JSON/IPC.+ const guardedItem = { ...item, [MCP_APP_MESSAGE_GUARD]: assertDispatchCurrent };+ deps.enqueue(sessionId, guardedItem);+ return;+ }+ const result = await deps.sendToAgentAccepted(sessionId, { type: 'user', content: blocks }, undefined, {+ sourcePlugin, [AUTO_REVIEW_DELEGATED_CONTINUATION]: true,+ [MCP_APP_MESSAGE_GUARD]: assertDispatchCurrent,+ expectedClearBoundaryMs,+ persistUserMessage: { clientId, content: persistedContent, sourcePlugin, expectedClearBoundaryMs },+ });+ if (result.accepted === false) throw new Error('MCP_APP_MESSAGE_NOT_ACCEPTED');+ };+}diff --git a/apps/desktop/src/main/mcp-apps/operations.ts b/apps/desktop/src/main/mcp-apps/operations.tsnew file mode 100644index 0000000000..e76b237d2e--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/operations.ts@@ -0,0 +1,113 @@+import { z } from 'zod';+import { McpUiHostContextSchema } from '@modelcontextprotocol/ext-apps/app-bridge';+import type { McpAppsHost } from './host.js';+import type { McpAppDocument, McpAppSandboxView } from '../../shared/mcpApps.js';+import { isMcpAppLinkAuthorizationCurrent } from '../../shared/mcpApps.js';+import { MCP_APPS_MAX_BYTES, safeAppLink } from './protocol.js';++const id = z.string().min(1).max(256);+export const mcpAppOperationSchema = z.discriminatedUnion('op', [+ z.object({ op: z.literal('open'), clientId: id, openId: id.optional(), context: McpUiHostContextSchema.default({}) }),+ z.object({ op: z.literal('cancel-open'), openId: id }),+ z.object({ op: z.literal('message'), viewId: id, message: z.unknown() }),+ z.object({ op: z.literal('poll'), viewId: id, after: z.number().int().nonnegative().default(0) }),+ z.object({ op: z.literal('context'), viewId: id, context: McpUiHostContextSchema }),+ z.object({ op: z.literal('teardown'), viewId: id, alreadyNotified: z.boolean().default(false) }),+ z.object({+ op: z.literal('display-mode'),+ viewId: id,+ mode: z.enum(['inline', 'fullscreen', 'pip']),+ }),+ z.object({ op: z.literal('link-result'), viewId: id, linkId: id, success: z.boolean() }),+ z.object({ op: z.literal('authorize-link'), viewId: id, linkId: id }),+ z.object({ op: z.literal('mount-remote'), document: z.unknown() }),+ z.object({ op: z.literal('unmount-remote'), viewId: id }),+ z.object({ op: z.literal('open-link'), viewId: id, url: z.string().max(8192) }),+]);+interface LocalViewDeps {+ supply(document: McpAppDocument, caller: string): void;+}+/** Called only by the protocol's frame-verified channel, with Host-bound task and View IDs. */+export async function handleMcpAppFrameOperation(+ host: McpAppsHost, caller: string, sessionId: string, viewId: string, raw: unknown,+ openLink: (url: string) => Promise<void>,+): Promise<unknown> {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('MCP_APP_INVALID_REQUEST');+ const input = raw as Record<string, unknown>;+ if (input.op === 'open-link') {+ const linkId = id.safeParse(input.linkId);+ if (typeof input.url !== 'string' || input.url.length > 8192 || !linkId.success)+ throw new Error('MCP_APP_INVALID_LINK');+ const url = safeAppLink(input.url);+ // A queued event is not a grant: its card or pending link may have expired.+ const requestedAt = performance.now();+ const authorization = await host.authorizeLink(caller, sessionId, viewId, linkId.data, url);+ if (!isMcpAppLinkAuthorizationCurrent(authorization, performance.now() - requestedAt))+ throw new Error('MCP_APP_LINK_NOT_AUTHORIZED');+ await openLink(url);+ return {};+ }+ if (!['message', 'poll', 'link-result'].includes(String(input.op))) throw new Error('MCP_APP_INVALID_REQUEST');+ return handleMcpAppOperation(host, caller, sessionId, { ...input, viewId });+}+export async function handleMcpAppOperation(+ host: McpAppsHost,+ caller: string,+ sessionId: string,+ raw: unknown,+ local?: LocalViewDeps,+): Promise<unknown> {+ if (+ !id.safeParse(sessionId).success ||+ !raw ||+ typeof raw !== 'object' ||+ Array.isArray(raw) ||+ Buffer.byteLength(JSON.stringify(raw)) > MCP_APPS_MAX_BYTES+ )+ throw new Error('MCP_APP_INVALID_REQUEST');+ const parsed = mcpAppOperationSchema.safeParse(raw);+ if (!parsed.success) throw new Error('MCP_APP_INVALID_REQUEST');+ const input = parsed.data;+ switch (input.op) {+ case 'open': {+ const document = await host.open(caller, sessionId, input.clientId, input.context, input.openId);+ if (!local) return document;+ local.supply(document, caller);+ // Main supplies the private document directly to the isolated frame.+ return { viewId: document.viewId, transport: 'sandbox',+ prefersBorder: document.prefersBorder } satisfies McpAppSandboxView;+ }+ case 'cancel-open':+ await host.cancelOpen(caller, sessionId, input.openId);+ return {};+ case 'message':+ if (local) throw new Error('MCP_APP_FRAME_REQUIRED');+ await host.dispatch(caller, sessionId, input.viewId, input.message);+ return {};+ case 'poll':+ if (local) throw new Error('MCP_APP_FRAME_REQUIRED');+ return await host.poll(caller, sessionId, input.viewId, input.after);+ case 'context':+ host.context(caller, sessionId, input.viewId, input.context);+ return {};+ case 'teardown':+ await host.teardown(caller, sessionId, input.viewId, input.alreadyNotified);+ return {};+ case 'display-mode':+ host.displayMode(caller, sessionId, input.viewId, input.mode);+ return {};+ case 'authorize-link':+ if (local) throw new Error('MCP_APP_FRAME_REQUIRED');+ return await host.authorizeLink(caller, sessionId, input.viewId, input.linkId);+ case 'link-result':+ if (local) throw new Error('MCP_APP_FRAME_REQUIRED');+ host.linkResult(caller, sessionId, input.viewId, input.linkId, input.success);+ return {};+ case 'mount-remote':+ case 'unmount-remote':+ case 'open-link':+ if (local) throw new Error('MCP_APP_FRAME_REQUIRED');+ break;+ }+ throw new Error('MCP_APP_INVALID_REQUEST');+}diff --git a/apps/desktop/src/main/mcp-apps/protocol.ts b/apps/desktop/src/main/mcp-apps/protocol.tsnew file mode 100644index 0000000000..9800b43e43--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/protocol.ts@@ -0,0 +1,139 @@+import { Buffer } from 'node:buffer';+import type { ReadResourceResult, Tool } from '@modelcontextprotocol/sdk/types.js';+import { RESOURCE_MIME_TYPE } from '@modelcontextprotocol/ext-apps/server';+import { McpUiResourceMetaSchema } from '@modelcontextprotocol/ext-apps/app-bridge';+import type { McpUiResourceMeta } from '@modelcontextprotocol/ext-apps';+import type { McpAppRecord } from '../../shared/mcpApps.js';++export const MCP_APPS_EXTENSION = 'io.modelcontextprotocol/ui';+export const MCP_APPS_MAX_BYTES = 4 * 1024 * 1024;+// Bound serialized remote results, reserving space for invoke and routing metadata.+export const MCP_APPS_MAX_REMOTE_BYTES = MCP_APPS_MAX_BYTES - 64 * 1024;+// Leave room for JSON-escaped history rows, initialization and input/result envelopes.+export const MCP_APPS_MAX_CARD_BYTES = MCP_APPS_MAX_BYTES / 4;++/** Bound the complete persisted card; never change the result returned to the model. */+export function boundedAppRecord(record: McpAppRecord): McpAppRecord {+ const fits = (value: McpAppRecord) =>+ Buffer.byteLength(JSON.stringify({ mcpApp: value })) <= MCP_APPS_MAX_CARD_BYTES;+ if (fits(record)) return record;+ if (!record.result) throw new Error('MCP_APP_CARD_TOO_LARGE');+ const bounded: McpAppRecord = {+ ...record,+ result: {+ isError: true,+ content: [{ type: 'text', text: 'MCP_APP_RESULT_TOO_LARGE' }],+ },+ };+ // Input or tool metadata can exceed the budget even after removing the result.+ if (!fits(bounded)) throw new Error('MCP_APP_CARD_TOO_LARGE');+ return bounded;+}++export function uiToolUri(tool: Tool): string | undefined {+ const ui = tool._meta?.ui as { resourceUri?: unknown } | undefined;+ const uri = ui?.resourceUri ?? tool._meta?.['ui/resourceUri'];+ return typeof uri === 'string' &&+ uri.startsWith('ui://') &&+ uri.length <= 8192 &&+ !/\s/.test(uri) &&+ Array.from(uri).every((character) => character.charCodeAt(0) >= 32)+ ? uri+ : undefined;+}++export function toolVisibleTo(tool: Tool, audience: 'model' | 'app'): boolean {+ const ui = tool._meta?.ui as { visibility?: unknown } | undefined;+ return (+ ui?.visibility === undefined ||+ (Array.isArray(ui.visibility) && ui.visibility.includes(audience))+ );+}++/** No schemes, directives, quotes, whitespace, credentials or paths from a CSP source. */+export function validateCspDomains(domains: string[] | undefined): string[] {+ if (domains && (!Array.isArray(domains) || domains.length > 100))+ throw new Error('MCP_APP_INVALID_CSP_DOMAIN');+ return (domains ?? []).map((source) => {+ if (+ !/^(https?|wss?):\/\/(?:\*\.)?(?:[a-zA-Z0-9.-]+|\[[a-fA-F0-9:]+\])(?::(?:[0-9]{1,5}|\*))?\/?$/.test(+ source,+ )+ ) {+ throw new Error('MCP_APP_INVALID_CSP_DOMAIN');+ }+ const url = new URL(source.replace('://*.', '://wildcard.').replace(/:\*(\/?)$/, ':443$1'));+ if (!url.hostname || (url.port && Number(url.port) > 65535))+ throw new Error('MCP_APP_INVALID_CSP_DOMAIN');+ return source;+ });+}++export function appCsp(meta: McpUiResourceMeta = {}): {+ header: string;+ csp: NonNullable<McpUiResourceMeta['csp']>;+} {+ const csp = {+ connectDomains: validateCspDomains(meta.csp?.connectDomains),+ resourceDomains: validateCspDomains(meta.csp?.resourceDomains),+ frameDomains: validateCspDomains(meta.csp?.frameDomains),+ baseUriDomains: validateCspDomains(meta.csp?.baseUriDomains),+ };+ const resources = csp.resourceDomains.join(' ');+ const header = [+ "default-src 'none'",+ `script-src 'self' 'unsafe-inline' ${resources}`,+ `style-src 'self' 'unsafe-inline' ${resources}`,+ `img-src 'self' data: ${resources}`,+ `media-src 'self' data: ${resources}`,+ `font-src 'self' ${resources}`,+ `connect-src ${csp.connectDomains.join(' ') || "'none'"}`,+ `frame-src ${csp.frameDomains.join(' ') || "'none'"}`,+ `base-uri ${csp.baseUriDomains.join(' ') || "'self'"}`,+ "object-src 'none'",+ "form-action 'none'",+ "worker-src 'none'",+ ].join('; ');+ return { header, csp };+}++export function readAppResource(+ result: ReadResourceResult,+ uri: string,+ fallbackMeta?: unknown,+): { html: string; meta: McpUiResourceMeta } {+ const item = result.contents.find(+ (content) => content.uri === uri && content.mimeType === RESOURCE_MIME_TYPE,+ );+ if (!item) throw new Error('MCP_APP_RESOURCE_MISSING');+ if (+ 'blob' in item &&+ (item.blob.length > Math.ceil(MCP_APPS_MAX_BYTES / 3) * 4 ||+ !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(item.blob))+ )+ throw new Error('MCP_APP_INVALID_RESOURCE');+ const html = 'text' in item ? item.text : Buffer.from(item.blob, 'base64').toString('utf8');+ if (Buffer.byteLength(html) > MCP_APPS_MAX_BYTES) throw new Error('MCP_APP_RESOURCE_TOO_LARGE');+ const meta = McpUiResourceMetaSchema.parse(item._meta?.ui ?? fallbackMeta ?? {});+ // Validate before any document is supplied to a renderer.+ appCsp(meta);+ return { html, meta };+}++export function safeAppLink(value: string): string {+ let url: URL;+ try {+ url = new URL(value);+ } catch {+ throw new Error('MCP_APP_INVALID_LINK');+ }+ if (+ !['https:', 'http:'].includes(url.protocol) ||+ url.username ||+ url.password ||+ value.length > 8192+ ) {+ throw new Error('MCP_APP_INVALID_LINK');+ }+ return url.href;+}diff --git a/apps/desktop/src/main/mcp-apps/remoteViews.ts b/apps/desktop/src/main/mcp-apps/remoteViews.tsnew file mode 100644index 0000000000..7a684a5cf6--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/remoteViews.ts@@ -0,0 +1,207 @@+import { randomUUID } from 'node:crypto';+import { z } from 'zod';+import { isSharedTaskPeer } from '@cindy/device-link';+import type { McpAppSandboxView } from '../../shared/mcpApps.js';+import { isMcpAppLinkAuthorizationCurrent } from '../../shared/mcpApps.js';+import { MCP_APPS_MAX_BYTES, MCP_APPS_MAX_REMOTE_BYTES, safeAppLink } from './protocol.js';+import { mcpAppOperationSchema } from './operations.js';+import { assertMcpAppDocumentCaller, mountRemoteAppDocument, unmountRemoteAppDocument } from './sandboxProtocol.js';++const id = z.string().min(1).max(256);+const documentSchema = z.object({+ viewId: id, html: z.string(), csp: z.string(), prefersBorder: z.boolean(),+ policy: z.object({+ connectDomains: z.array(z.string()).optional(), resourceDomains: z.array(z.string()).optional(),+ frameDomains: z.array(z.string()).optional(), baseUriDomains: z.array(z.string()).optional(),+ }).optional(),+});+interface RemoteViewDeps {+ owner(): object | null | undefined;+ closeEpoch(deviceId: string): number;+ invoke(deviceId: string, sessionId: string, input: Record<string, unknown>, preSend: () => void): Promise<unknown>;+ openLink(url: string): Promise<void>;+}+interface Opening {+ owner: object; caller: string; deviceId: string; sessionId: string; openId?: string;+ remoteOpenId: string; cancelled: boolean; closeEpoch: number;+}+interface RemoteView extends Opening {+ localId: string; remoteId: string; links: Map<string, string>; closing?: Promise<void>;+}++/** Main binds a remote View to its local owner/window/frame; Renderer IDs never grant App RPC access. */+export class RemoteMcpAppViews {+ private readonly opening = new Set<Opening>();+ private readonly views = new Map<string, RemoteView>();+ constructor(private readonly deps: RemoteViewDeps) {}++ private assertLink(entry: Opening): void {+ if (this.deps.closeEpoch(entry.deviceId) !== entry.closeEpoch) throw new Error('MCP_APP_LINK_CLOSED');+ }++ private async call(entry: Opening, input: Record<string, unknown>, assertCurrent = () => {}): Promise<unknown> {+ const preSend = () => {+ if (this.deps.owner() !== entry.owner) throw new Error('MCP_APP_OWNER_CHANGED');+ this.assertLink(entry);+ assertCurrent();+ };+ preSend();+ return this.deps.invoke(entry.deviceId, entry.sessionId, input, preSend);+ }+ private assertView(view: RemoteView): void {+ this.assertLink(view);+ if (this.views.get(view.localId) !== view || this.deps.owner() !== view.owner)+ throw new Error('MCP_APP_VIEW_UNAVAILABLE');+ assertMcpAppDocumentCaller(view.localId, view.caller);+ }+ private forward(view: RemoteView, input: Record<string, unknown>): Promise<unknown> {+ this.assertView(view);+ return this.call(view, { ...input, viewId: view.remoteId }, () => this.assertView(view));+ }+ private async poll(view: RemoteView, input: Record<string, unknown>): Promise<unknown> {+ let failedAt: number | undefined;+ let delay = 500;+ while (true) {+ try { return await this.forward(view, input); }+ catch (error) {+ this.assertView(view);+ failedAt ??= Date.now();+ if (view.closing || /MCP_APP_|CHANNEL_NOT_ALLOWED|NOT_FOUND|ACCESS_REVOKED|PERMISSION_DENIED/.test(String(error)) ||+ Date.now() - failedAt >= 30_000) throw error;+ // Only this View's read is retried. Never reset a peer/relay or replay App writes.+ await new Promise((resolve) => setTimeout(resolve, delay));+ delay = Math.min(5_000, delay * 2);+ }+ }+ }++ async control(caller: string, deviceId: unknown, sessionId: string, raw: unknown): Promise<unknown> {+ if (!id.safeParse(deviceId).success || !id.safeParse(sessionId).success ||+ !raw || Buffer.byteLength(JSON.stringify(raw)) > MCP_APPS_MAX_BYTES)+ throw new Error('MCP_APP_INVALID_REQUEST');+ const device = deviceId as string;+ if (isSharedTaskPeer(device)) throw new Error('MCP_APP_OWNER_ONLY');+ const parsed = mcpAppOperationSchema.safeParse(raw);+ if (!parsed.success) throw new Error('MCP_APP_INVALID_REQUEST');+ const input = parsed.data;+ if (input.op === 'open') return this.open(caller, device, sessionId, input);+ if (input.op === 'cancel-open') {+ await Promise.all([...this.opening].filter((entry) => entry.caller === caller &&+ entry.deviceId === device && entry.sessionId === sessionId && entry.openId === input.openId &&+ entry.owner === this.deps.owner()).map((entry) => this.cancel(entry)));+ return {};+ }+ if (!['context', 'display-mode', 'teardown'].includes(input.op))+ throw new Error('MCP_APP_FRAME_REQUIRED');+ const view = 'viewId' in input ? this.views.get(input.viewId) : undefined;+ if (!view || view.caller !== caller || view.deviceId !== device || view.sessionId !== sessionId)+ throw new Error('MCP_APP_VIEW_UNAVAILABLE');+ this.assertView(view);+ if (input.op === 'teardown') {+ await this.close(view);+ return {};+ }+ if (view.closing) throw new Error('MCP_APP_VIEW_UNAVAILABLE');+ const result = await this.forward(view, input);+ this.assertView(view);+ return result;+ }++ private async open(+ caller: string, deviceId: string, sessionId: string,+ input: Extract<z.infer<typeof mcpAppOperationSchema>, { op: 'open' }>,+ ): Promise<McpAppSandboxView> {+ const owner = this.deps.owner();+ if (!owner) throw new Error('MCP_APP_OWNER_UNAVAILABLE');+ const count = [...this.opening, ...this.views.values()].filter((entry) => entry.caller === caller && entry.owner === owner).length;+ if (count >= 16) throw new Error('MCP_APP_VIEW_LIMIT');+ const entry: Opening = { owner, caller, deviceId, sessionId, openId: input.openId,+ remoteOpenId: randomUUID(), cancelled: false, closeEpoch: this.deps.closeEpoch(deviceId) };+ this.opening.add(entry);+ let remoteId: string | undefined;+ try {+ const raw = await this.call(entry, { ...input, openId: entry.remoteOpenId }, () => {+ if (entry.cancelled) throw new Error('MCP_APP_OPEN_CANCELLED');+ });+ this.assertLink(entry);+ const document = documentSchema.parse(raw);+ remoteId = document.viewId;+ if (Buffer.byteLength(JSON.stringify(document)) > MCP_APPS_MAX_REMOTE_BYTES)+ throw new Error('MCP_APP_DOCUMENT_TOO_LARGE');+ if (entry.cancelled || this.deps.owner() !== owner) throw new Error('MCP_APP_OPEN_CANCELLED');+ // Only Main's remote result is supplied. There is no Renderer-controlled HTML/RPC rebinding.+ const view: RemoteView = { ...entry, localId: '', remoteId, links: new Map() };+ view.localId = mountRemoteAppDocument(document, caller, (raw) => this.frame(view, raw), () => this.dispose(view));+ this.views.set(view.localId, view);+ return { viewId: view.localId, transport: 'sandbox', prefersBorder: document.prefersBorder };+ } catch (error) {+ // No writes are replayed. An old Host may reject cancel-open; its idle lease remains the fallback.+ await this.call(entry, remoteId ? { op: 'teardown', viewId: remoteId } :+ { op: 'cancel-open', openId: entry.remoteOpenId }).catch(() => {});+ throw error;+ } finally { this.opening.delete(entry); }+ }++ /** Called exclusively by the protocol after verifying Chromium's actual sandbox frame. */+ private async frame(view: RemoteView, raw: unknown): Promise<unknown> {+ this.assertView(view);+ if (!raw || typeof raw !== 'object' || Array.isArray(raw) ||+ Buffer.byteLength(JSON.stringify(raw)) > MCP_APPS_MAX_BYTES) throw new Error('MCP_APP_INVALID_REQUEST');+ const value = raw as Record<string, unknown>;+ if (value.op === 'open-link') {+ if (view.closing) throw new Error('MCP_APP_VIEW_UNAVAILABLE');+ if (typeof value.linkId !== 'string' || typeof value.url !== 'string' ||+ view.links.get(value.linkId) !== safeAppLink(value.url)) throw new Error('MCP_APP_INVALID_LINK');+ view.links.delete(value.linkId);+ const requestedAt = performance.now();+ const authorization = await this.forward(view, { op: 'authorize-link', linkId: value.linkId });+ this.assertView(view);+ if (view.closing) throw new Error('MCP_APP_VIEW_UNAVAILABLE');+ if (!isMcpAppLinkAuthorizationCurrent(authorization, performance.now() - requestedAt))+ throw new Error('MCP_APP_LINK_NOT_AUTHORIZED');+ await this.deps.openLink(safeAppLink(value.url));+ return {};+ }+ const parsed = mcpAppOperationSchema.safeParse({ ...value, viewId: view.localId });+ if (!parsed.success || !['message', 'poll', 'link-result'].includes(parsed.data.op))+ throw new Error('MCP_APP_INVALID_REQUEST');+ const input = parsed.data;+ const result = await (input.op === 'poll' ? this.poll(view, input) : this.forward(view, input));+ this.assertView(view);+ if (input.op === 'poll') {+ if (!Array.isArray(result) || result.length > 256 || Buffer.byteLength(JSON.stringify(result)) > MCP_APPS_MAX_REMOTE_BYTES)+ throw new Error('MCP_APP_INVALID_POLL');+ for (const event of result) {+ if (event?.openLink && typeof event.openLink.id === 'string' && typeof event.openLink.url === 'string') {+ if (view.links.size >= 256 && !view.links.has(event.openLink.id)) throw new Error('MCP_APP_BACKPRESSURE');+ view.links.set(event.openLink.id, safeAppLink(event.openLink.url));+ }+ }+ }+ if (input.op === 'link-result') view.links.delete(input.linkId);+ return result;+ }++ private cancel(entry: Opening): Promise<unknown> {+ entry.cancelled = true;+ this.opening.delete(entry);+ return this.call(entry, { op: 'cancel-open', openId: entry.remoteOpenId });+ }+ private close(view: RemoteView): Promise<void> {+ view.closing ??= (async () => {+ try { await this.call(view, { op: 'teardown', viewId: view.remoteId }); }+ finally { if (this.views.get(view.localId) === view) unmountRemoteAppDocument(view.localId, view.caller); }+ })();+ return view.closing;+ }+ private dispose(view: RemoteView): void {+ this.views.delete(view.localId);+ view.links.clear();+ if (!view.closing) void this.call(view, { op: 'teardown', viewId: view.remoteId }).catch(() => {});+ }+ async releaseCaller(caller: string): Promise<void> {+ const pending = [...this.opening].filter((entry) => entry.caller === caller).map((entry) => this.cancel(entry));+ for (const view of this.views.values()) if (view.caller === caller) unmountRemoteAppDocument(view.localId, caller);+ await Promise.allSettled(pending);+ }+}diff --git a/apps/desktop/src/main/mcp-apps/runtime.ts b/apps/desktop/src/main/mcp-apps/runtime.tsnew file mode 100644index 0000000000..1404f992fd--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/runtime.ts@@ -0,0 +1,38 @@+import type { AppServerConfig } from './connection.js';+import type { McpAppsHost, McpAppModelContext } from './host.js';+import { clearMcpAppDocuments, setMcpAppCallerCleanup } from './sandboxProtocol.js';++let host: McpAppsHost | undefined;+const configs = new Map<string, () => AppServerConfig>();+export function setMcpAppsHost(value: McpAppsHost): void {+ host = value;+ setMcpAppCallerCleanup((caller) => value.releaseCaller(caller));+}+export function getMcpAppsHost(): McpAppsHost {+ if (!host) throw new Error('MCP_APPS_NOT_READY');+ return host;+}+export function registerAppServer(id: string, read: () => AppServerConfig): void {+ configs.set(id, read);+}+export function clearAppServerConfigs(): void {+ configs.clear();+}+export function readAppServer(id: string): AppServerConfig | undefined {+ return configs.get(id)?.();+}+export function appServerIds(): string[] {+ return [...configs.keys()];+}+export function resetAppServers(): void {+ configs.clear();+ clearMcpAppDocuments();+ void host?.reset();+}++/** Keep the snapshot pending until the send or steer carrying it is accepted. */+export async function mcpAppModelContext(sessionId: string): Promise<McpAppModelContext> {+ return (+ (await host?.modelContext(sessionId)) ?? { text: '', async assertCurrent() {}, consume() {} }+ );+}diff --git a/apps/desktop/src/main/mcp-apps/sandboxBridge.ts b/apps/desktop/src/main/mcp-apps/sandboxBridge.tsnew file mode 100644index 0000000000..f3e9804718--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/sandboxBridge.ts@@ -0,0 +1,51 @@+/** This document owns the App transport. The top Renderer only observes UI state. */+export function mcpAppDirectSandboxDocument(resourceUrl: string, bridgeUrl: string): string {+ const encode = (value: string) => JSON.stringify(value).replace(/</g, '\\u003c');+ return `<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;width:100%;height:100%;overflow:hidden}</style></head><body><script>+const frame=document.createElement('iframe');+frame.setAttribute('sandbox','allow-scripts allow-same-origin');+frame.setAttribute('allow',"camera 'none'; microphone 'none'; geolocation 'none'; clipboard-write 'none'");+frame.style.cssText='border:0;width:100%;height:100%;display:block';+let after=0,stopped=false;+const state=(message,fromHost=false)=>{+ // App notifications cannot assert Host-owned context such as display mode.+ if(['ui/notifications/initialized','ui/notifications/size-changed','ui/notifications/sandbox-escape'].includes(message.method)||(fromHost&&message.method==='ui/notifications/host-context-changed'))+ window.parent.postMessage(message,'*');+};+const fail=()=>{if(stopped)return;stopped=true;window.parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/sandbox-failed'},'*');};+async function invoke(input){+ const response=await fetch(${encode(bridgeUrl)},{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(input)});+ if(!response.ok)throw new Error('MCP_APP_VIEW_UNAVAILABLE');+ return response.json();+}+window.addEventListener('message',event=>{+ if(stopped||event.source!==frame.contentWindow)return;+ const message=event.data;+ if(!message||message.jsonrpc!=='2.0'||typeof message.method==='string'&&message.method.startsWith('ui/notifications/sandbox-'))return;+ state(message);+ void invoke({op:'message',message}).catch(fail);+});+window.addEventListener('keydown',event=>{+ if(event.key==='Escape'&&!event.isComposing&&!event.repeat&&!event.ctrlKey&&!event.altKey&&!event.metaKey&&!event.shiftKey)+ state({jsonrpc:'2.0',method:'ui/notifications/sandbox-escape',params:{}});+});+async function poll(){+ try{while(!stopped){+ const events=await invoke({op:'poll',after});+ for(const event of events){+ if(!Number.isSafeInteger(event.seq)||event.seq<=after)continue;+ after=event.seq;+ if(event.openLink){+ let success=false;+ try{await invoke({op:'open-link',linkId:event.openLink.id,url:event.openLink.url});success=true;}catch{}+ await invoke({op:'link-result',linkId:event.openLink.id,success});+ }else{state(event.message,true);frame.contentWindow.postMessage(event.message,'*');}+ }+ if(!events.length&&!stopped)await new Promise(resolve=>setTimeout(resolve,250));+ }}catch{fail();}+}+frame.src=${encode(resourceUrl)};+document.body.appendChild(frame);+void poll();+</script></body></html>`;+}diff --git a/apps/desktop/src/main/mcp-apps/sandboxProtocol.ts b/apps/desktop/src/main/mcp-apps/sandboxProtocol.tsnew file mode 100644index 0000000000..f74be7d8ba--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/sandboxProtocol.ts@@ -0,0 +1,279 @@+import { app, protocol, session, type WebContents, type WebFrameMain } from 'electron';+import { randomUUID } from 'node:crypto';+import { getCurrentDbClientSnapshot } from '../localDb/client/current.js';+import { appCsp, MCP_APPS_MAX_BYTES } from './protocol.js';+import {+ mcpAppSandboxDocument,+ mcpAppFrameUrlAllowed,+ type McpAppDocument,+} from '../../shared/mcpApps.js';+import { mcpAppDirectSandboxDocument } from './sandboxBridge.js';++export const mcpAppSchemePrivilege = {+ scheme: 'cindy-mcp-app',+ privileges: { standard: true, secure: true, supportFetchAPI: true, corsEnabled: true },+};+const frameHeader = 'X-Cindy-Mcp-App-Frame';+let callerCleanup: ((caller: string) => Promise<void>) | undefined;+export function setMcpAppCallerCleanup(cleanup?: (caller: string) => Promise<void>): void {+ callerCleanup = cleanup;+}+const documents = new Map<+ string,+ {+ document: McpAppDocument; owner: object | null; caller?: string;+ dispose?: () => void;+ bridge?: { key: string; frame?: WebFrameMain; invoke(input: unknown): Promise<unknown> };+ }+>();+async function readBridgeBody(request: Request): Promise<string> {+ const reader = request.body?.getReader();+ if (!reader) throw new Error('MCP_APP_INVALID_REQUEST');+ const chunks: Uint8Array[] = [];+ let size = 0;+ try {+ while (true) {+ const { value, done } = await reader.read();+ if (done) break;+ size += value.byteLength;+ if (size > MCP_APPS_MAX_BYTES) {+ await reader.cancel();+ throw new Error('MCP_APP_MESSAGE_TOO_LARGE');+ }+ chunks.push(value);+ }+ return new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks));+ } finally { reader.releaseLock(); }+}+export function supplyMcpAppDocument(+ document: McpAppDocument, caller?: string, invoke?: (input: unknown) => Promise<unknown>,+ dispose?: () => void,+): void {+ documents.set(document.viewId, {+ document, owner: getCurrentDbClientSnapshot(), caller, dispose,+ bridge: invoke ? { key: randomUUID(), invoke } : undefined,+ });+}+export function removeMcpAppDocument(id: string): void {+ const entry = documents.get(id);+ documents.delete(id);+ entry?.dispose?.();+}+export function clearMcpAppDocuments(): void {+ for (const id of documents.keys()) removeMcpAppDocument(id);+}+export function mountRemoteAppDocument(+ input: unknown, caller: string, invoke?: (input: unknown) => Promise<unknown>, dispose?: () => void,+): string {+ const document = input as McpAppDocument;+ if (!getCurrentDbClientSnapshot()) throw new Error('MCP_APP_OWNER_UNAVAILABLE');+ if (+ !document ||+ typeof document.html !== 'string' ||+ Buffer.byteLength(document.html) > MCP_APPS_MAX_BYTES+ )+ throw new Error('MCP_APP_INVALID_DOCUMENT');+ if ([...documents.values()].filter((item) => item.caller === caller).length >= 16)+ throw new Error('MCP_APP_VIEW_LIMIT');+ const policy = appCsp({ csp: document.policy });+ const id = randomUUID();+ supplyMcpAppDocument({ ...document, viewId: id, csp: policy.header, policy: policy.csp }, caller, invoke, dispose);+ return id;+}+export function unmountRemoteAppDocument(id: string, caller: string): void {+ if (documents.get(id)?.caller !== caller) throw new Error('MCP_APP_VIEW_UNAVAILABLE');+ removeMcpAppDocument(id);+}+export function assertMcpAppDocumentCaller(id: string, caller: string): void {+ const entry = documents.get(id);+ if (!entry || entry.owner !== getCurrentDbClientSnapshot() || entry.caller !== caller)+ throw new Error('MCP_APP_VIEW_UNAVAILABLE');+}+export function registerMcpAppProtocol(): void {+ // Only Chromium's actual requesting frame can acquire this Main-only channel key.+ // It never appears in HTML, a renderer IPC response, or a JavaScript Request object.+ session.defaultSession.webRequest.onBeforeSendHeaders(+ { urls: ['cindy-mcp-app://*/*'] },+ (details, callback) => {+ const url = new URL(details.url);+ if (url.pathname !== '/bridge') { callback({ requestHeaders: details.requestHeaders }); return; }+ const entry = documents.get(url.hostname);+ const frame = details.frame;+ if (details.method !== 'POST' || !entry?.bridge || !frame ||+ entry.owner !== getCurrentDbClientSnapshot() ||+ entry.caller !== `renderer:${details.webContentsId}` ||+ frame.url !== `cindy-mcp-app://${url.hostname}/sandbox` ||+ (entry.bridge.frame && entry.bridge.frame !== frame)) {+ callback({ cancel: true }); return;+ }+ entry.bridge.frame = frame;+ const headers = Object.fromEntries(Object.entries(details.requestHeaders)+ .filter(([key]) => key.toLowerCase() !== frameHeader.toLowerCase()));+ callback({ requestHeaders: { ...headers, [frameHeader]: entry.bridge.key } });+ },+ );+ // The main window shares the default session. Preserve its existing permission+ // behavior, but never grant undeclared capabilities to an App or its descendants.+ session.defaultSession.setPermissionRequestHandler((contents, _permission, callback, details) => {+ callback(!isMcpAppPermissionRequest(contents, details));+ });+ session.defaultSession.setPermissionCheckHandler(+ (contents, permission, origin, details) =>+ // Electron 42 grants ordinary host checks by default, but explicitly denies+ // this legacy clipboard read. Installing a handler must retain that denial.+ permission !== 'deprecated-sync-clipboard-read' &&+ !isMcpAppPermissionRequest(contents, details, origin),+ );+ // CSP does not restrict a frame's own location navigation. Keep the policy-bearing+ // document in place; external navigation goes through standard ui/open-link.+ app.on('web-contents-created', (_event, contents) => {+ // A crashed/reloaded renderer cannot unmount its old documents; reload reuses its caller ID.+ const caller = `renderer:${contents.id}`;+ const releaseCaller = () => {+ for (const [id, entry] of documents) if (entry.caller === caller) removeMcpAppDocument(id);+ void callerCleanup?.(caller).catch(() => {});+ };+ contents.on('destroyed', releaseCaller);+ contents.on('render-process-gone', releaseCaller);+ contents.on('did-start-navigation', (_event, _url, isInPlace, isMainFrame) => {+ if (isMainFrame && !isInPlace) releaseCaller();+ });+ // DOM keyboard events do not bubble out of a cross-origin App frame. Deliver+ // Escape to the trusted sandbox, which relays the exit to its own controller.+ contents.on('before-input-event', (event, input) => {+ if (+ input.type !== 'keyDown' ||+ input.key !== 'Escape' ||+ input.isAutoRepeat ||+ input.isComposing ||+ input.control ||+ input.alt ||+ input.meta ||+ input.shift+ )+ return;+ for (let frame = contents.focusedFrame; frame; frame = frame.parent) {+ if (!frame.url.startsWith('cindy-mcp-app:')) continue;+ const url = new URL(frame.url);+ if (url.pathname !== '/sandbox' || url.hostname.endsWith('-view')) continue;+ const entry = documents.get(url.hostname);+ if (!entry || entry.owner !== getCurrentDbClientSnapshot()) return;+ event.preventDefault();+ void frame+ .executeJavaScript("window.dispatchEvent(new KeyboardEvent('keydown', {key: 'Escape'}))")+ .catch(() => {});+ return;+ }+ });+ contents.on('will-frame-navigate', (event) => {+ const source = event.frame?.url || event.initiator?.url || '';+ // A declared nested iframe is allowed to load its approved origin. Only+ // descendants of the actual App resource get this grant, never the App+ // itself or its trusted sandbox proxy.+ let nestedDomains: readonly string[] | undefined;+ for (let ancestor = event.frame?.parent; ancestor; ancestor = ancestor.parent) {+ if (!ancestor.url.startsWith('cindy-mcp-app:')) continue;+ const url = new URL(ancestor.url);+ if (!url.hostname.endsWith('-view') || url.pathname !== '/resource') continue;+ const entry = documents.get(url.hostname.slice(0, -5));+ nestedDomains =+ entry?.owner === getCurrentDbClientSnapshot()+ ? (entry.document.policy?.frameDomains ?? [])+ : [];+ break;+ }+ if (!isMcpAppFrameNavigationAllowed(source, event.url, nestedDomains)) event.preventDefault();+ });+ });+ protocol.handle('cindy-mcp-app', async (request) => {+ const url = new URL(request.url);+ const id = url.hostname.replace(/-view$/, '');+ const entry = documents.get(id);+ const doc = entry?.document;+ if (!doc || entry?.owner !== getCurrentDbClientSnapshot())+ return new Response(null, { status: 404 });+ if (url.pathname === '/bridge' && url.hostname === id) {+ const bridge = entry.bridge;+ if (request.method !== 'POST' || !bridge ||+ request.headers.get(frameHeader) !== bridge.key ||+ bridge.frame?.url !== `cindy-mcp-app://${id}/sandbox`)+ return new Response(null, { status: 403 });+ try {+ const text = await readBridgeBody(request);+ // The document can be revoked while its body is arriving.+ if (documents.get(id) !== entry || entry.owner !== getCurrentDbClientSnapshot())+ return new Response(null, { status: 403 });+ return Response.json(await bridge.invoke(JSON.parse(text)), { headers: { 'Cache-Control': 'no-store' } });+ } catch {+ return new Response(null, { status: 400 });+ }+ }+ if (request.method !== 'GET') return new Response(null, { status: 404 });+ const isSandbox = url.pathname === '/sandbox';+ if (+ isSandbox+ ? url.hostname !== id+ : url.pathname !== '/resource' || url.hostname !== `${id}-view`+ )+ return new Response(null, { status: 404 });+ const resourceUrl = `cindy-mcp-app://${id}-view/resource`;+ return new Response(isSandbox+ ? entry.bridge+ ? mcpAppDirectSandboxDocument(resourceUrl, `cindy-mcp-app://${id}/bridge`)+ : mcpAppSandboxDocument('', resourceUrl)+ : doc.html, {+ headers: {+ 'Content-Type': 'text/html; charset=utf-8',+ 'Cache-Control': 'no-store',+ 'Content-Security-Policy': isSandbox+ ? `default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; frame-src cindy-mcp-app://${id}-view; connect-src ${entry.bridge ? "'self'" : "'none'"}; object-src 'none'; base-uri 'none'; form-action 'none'`+ : doc.csp,+ 'Permissions-Policy': 'camera=(), microphone=(), geolocation=(), clipboard-write=()',+ 'X-Content-Type-Options': 'nosniff',+ },+ });+ });+}+export function isMcpAppPermissionRequest(+ contents: Pick<WebContents, 'mainFrame'> | null,+ details: {+ requestingUrl?: string;+ embeddingOrigin?: string;+ securityOrigin?: string;+ isMainFrame: boolean;+ },+ origin?: string,+): boolean {+ const sources = [origin, details.requestingUrl, details.embeddingOrigin, details.securityOrigin];+ if (sources.some((value) => value?.startsWith('cindy-mcp-app:'))) return true;+ if (!contents && !details.isMainFrame) return true;+ const frames = contents?.mainFrame.framesInSubtree ?? [];+ // Match real frame ancestry as well: a nested frame can itself have an HTTPS+ // origin. Missing subframe identity must not become a permission bypass.+ return frames.some((frame) => {+ if (details.isMainFrame || (details.requestingUrl && frame.url !== details.requestingUrl))+ return false;+ for (let current: typeof frame | null = frame; current; current = current.parent) {+ if (current.url.startsWith('cindy-mcp-app:')) return true;+ }+ return false;+ });+}+export function isMcpAppFrameNavigationAllowed(+ source: string,+ target: string,+ nestedDomains?: readonly string[],+): boolean {+ if (nestedDomains !== undefined) return mcpAppFrameUrlAllowed(target, nestedDomains);+ if (!source.startsWith('cindy-mcp-app:')) return true;+ try {+ const from = new URL(source),+ to = new URL(target);+ if (to.protocol !== 'cindy-mcp-app:') return false;+ if (from.hostname.endsWith('-view'))+ return to.hostname === from.hostname && to.pathname === '/resource';+ return to.hostname === from.hostname + '-view' && to.pathname === '/resource';+ } catch {+ return false;+ }+}diff --git a/apps/desktop/src/main/mcp-apps/serverProxy.ts b/apps/desktop/src/main/mcp-apps/serverProxy.tsnew file mode 100644index 0000000000..66ae8b28fd--- /dev/null+++ b/apps/desktop/src/main/mcp-apps/serverProxy.ts@@ -0,0 +1,338 @@+import { randomUUID } from 'node:crypto';+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import type {+ Transport,+ TransportSendOptions,+} from '@modelcontextprotocol/sdk/shared/transport.js';+import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';+import {+ ListToolsRequestSchema,+ CallToolRequestSchema,+ CallToolResultSchema,+ CreateTaskResultSchema,+ ResultSchema,+ SetLevelRequestSchema,+ ErrorCode,+ isJSONRPCErrorResponse,+ isJSONRPCRequest,+ isJSONRPCResultResponse,+ type CallToolResult,+ type ClientRequest,+ type ClientNotification,+ type Progress,+ type Request,+ type RequestId,+ type ServerCapabilities,+ type ServerNotification,+ type ServerRequest,+} from '@modelcontextprotocol/sdk/types.js';+import type { McpProviderContext } from '@cindy/maker-core';+import type { McpAppRecord } from '../../shared/mcpApps.js';+import { AppConnection, type AppServerConfig } from './connection.js';+import { appServerRevision } from './host.js';+import { getMcpAppsHost, readAppServer } from './runtime.js';+import { toolVisibleTo, uiToolUri } from './protocol.js';+import { createLogger } from '../logger.js';++const log = createLogger('mcp-apps');++/** Tool-result root metadata belongs to Views, including results retrieved from tasks. */+function modelToolResult<T extends { _meta?: unknown }>(result: T) {+ const modelResult = { ...result };+ delete modelResult._meta;+ return modelResult;+}++/** Preserve the SDK handshake while attaching authenticated upstream metadata. */+class AppProxyServer extends McpServer {+ constructor(+ name: string,+ private readonly readInitialize: () => Promise<{+ instructions?: string;+ capabilities: ServerCapabilities;+ }>,+ ) {+ super(+ { name, version: '1.0.0' },+ {+ capabilities: {+ tools: { listChanged: true },+ resources: { listChanged: true, subscribe: true },+ prompts: { listChanged: true },+ completions: {},+ logging: {},+ tasks: { requests: { tools: { call: {} } } },+ },+ },+ );+ }++ override connect(transport: Transport): Promise<void> {+ const initializing = new Set<RequestId>();+ const wrapped: Transport = {+ get sessionId() {+ return transport.sessionId;+ },+ setProtocolVersion: (version) => transport.setProtocolVersion?.(version),+ start: async () => {+ const onmessage = transport.onmessage;+ const onerror = transport.onerror;+ const onclose = transport.onclose;+ transport.onmessage = (message, extra) => {+ if (isJSONRPCRequest(message) && message.method === 'initialize')+ initializing.add(message.id);+ onmessage?.(message, extra);+ wrapped.onmessage?.(message, extra);+ };+ transport.onerror = (error) => {+ onerror?.(error);+ wrapped.onerror?.(error);+ };+ transport.onclose = () => {+ initializing.clear();+ onclose?.();+ wrapped.onclose?.();+ };+ await transport.start();+ },+ send: async (message, options?: TransportSendOptions) => {+ if (isJSONRPCResultResponse(message) && initializing.delete(message.id)) {+ try {+ // The SDK's internal superset permits forwarding. Only the actual+ // upstream capabilities are advertised to the model client.+ const upstream = await this.readInitialize();+ message = { ...message, result: { ...message.result, ...upstream } };+ } catch {+ // A failed response send is only reported out of band by the SDK.+ // Return an initialize error instead of leaving the client waiting.+ message = {+ jsonrpc: '2.0',+ id: message.id,+ error: { code: ErrorCode.InternalError, message: 'MCP_APP_INITIALIZE_FAILED' },+ };+ }+ } else if (isJSONRPCErrorResponse(message) && message.id !== undefined) {+ initializing.delete(message.id);+ }+ await transport.send(message, options);+ },+ close: () => transport.close(),+ };+ return super.connect(wrapped);+ }+}++/** Generic MCP facade: the harness keeps its own tool approval, while Main negotiates Apps. */+export function createAppServerProxy(+ readConfig: () => AppServerConfig,+ context: McpProviderContext,+): McpServer {+ const config = readConfig();+ // Main-only live checks use a process-private key, independent of the vault.+ // Never persist this fingerprint or expose it as an App-card revision.+ const liveRevision = appServerRevision(config);+ const host = getMcpAppsHost();+ const owner = host.captureOwner();+ const connection = new AppConnection(config, {+ capabilities: () => server.server.getClientCapabilities() ?? {},+ request: async (request, extra) => {+ assertCurrent();+ const token = request.params?._meta?.progressToken;+ const result = await server.server.request(request as ServerRequest, ResultSchema, {+ signal: extra.signal,+ onprogress: token === undefined ? undefined : (progress) => {+ try { assertCurrent(); } catch { return; }+ void extra.sendNotification({+ method: 'notifications/progress',+ params: { ...progress, progressToken: token },+ }).catch(() => {});+ },+ });+ assertCurrent();+ return result;+ },+ });+ const assertCurrent = () => {+ host.assertOwner(owner);+ const current = readAppServer(config.id);+ if (!current || appServerRevision(current) !== liveRevision)+ throw new Error('MCP_APP_SERVER_CHANGED');+ };+ // Bridge factories are created eagerly, but unused proxies must not retain a Host slot.+ const registerOnUse = () => {+ assertCurrent();+ return host.registerConnection(connection, owner);+ };+ const currentClient = async (signal?: AbortSignal) => {+ registerOnUse();+ const client = await connection.getClient(signal);+ assertCurrent();+ signal?.throwIfAborted();+ return client;+ };+ const requestOptions = (+ request: Request,+ extra: RequestHandlerExtra<ServerRequest, ServerNotification>,+ ) => {+ const token = request.params?._meta?.progressToken;+ return {+ signal: extra.signal,+ onprogress:+ token === undefined+ ? undefined+ : (progress: Progress) => {+ try {+ assertCurrent();+ } catch {+ return;+ }+ // Upstream owns any task queue; this facade only relays the notification.+ void server.server+ .notification(+ {+ method: 'notifications/progress',+ params: { ...progress, progressToken: token },+ },+ { relatedRequestId: extra.requestId },+ )+ .catch(() => {});+ },+ };+ };+ const server: AppProxyServer = new AppProxyServer(config.id, async () => {+ const client = await currentClient();+ return {+ capabilities: client.getServerCapabilities() ?? {},+ instructions: client.getInstructions(),+ };+ });+ // Ordinary MCP methods (completion, subscriptions, logging, tasks and+ // extensions) retain their upstream behavior. tools/call stays below the+ // explicit visibility and App-card handling boundary.+ const forwardRequest = async (+ request: Request,+ extra: RequestHandlerExtra<ServerRequest, ServerNotification>,+ ) => {+ const client = await currentClient(extra.signal);+ const result = await client.request(+ request as ClientRequest,+ ResultSchema,+ requestOptions(request, extra),+ );+ assertCurrent();+ if (request.method === 'tasks/result') return modelToolResult(result);+ return result;+ };+ server.server.fallbackRequestHandler = forwardRequest;+ server.server.fallbackNotificationHandler = async (message) => {+ const client = await currentClient();+ await client.notification(message as ClientNotification);+ assertCurrent();+ };+ // Override the SDK's local log-level handler; the upstream owns its logging state.+ server.server.setRequestHandler(SetLevelRequestSchema, forwardRequest);+ server.server.setRequestHandler(ListToolsRequestSchema, async (_request, extra) => {+ registerOnUse();+ const tools = await connection.tools(extra.signal);+ assertCurrent();+ return { tools: tools.filter((tool) => toolVisibleTo(tool, 'model')) };+ });+ server.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {+ const connectionId = registerOnUse();+ const tool = (await connection.tools(extra.signal)).find(+ (candidate) => candidate.name === request.params.name,+ );+ extra.signal.throwIfAborted();+ assertCurrent();+ if (!tool || !toolVisibleTo(tool, 'model')) throw new Error('MCP_APP_TOOL_NOT_VISIBLE');+ if (request.params.task) {+ const client = await currentClient(extra.signal);+ const result = await client.request(+ { method: 'tools/call', params: request.params },+ CreateTaskResultSchema,+ requestOptions(request, extra),+ );+ assertCurrent();+ return result;+ }+ const active = context.getSessionContext?.() ?? context;+ const uri = uiToolUri(tool);+ const sessionId = active.sessionId;+ const clientId = `mcp-app:${randomUUID()}`;+ let record: McpAppRecord | undefined;+ if (uri && sessionId) {+ // Vault and UI persistence failure must not change a tool's actual outcome.+ try {+ record = {+ version: 1,+ serverId: config.id,+ serverRevision: host.serverRevision(config),+ resourceUri: uri,+ tool,+ arguments: request.params.arguments ?? {},+ connectionId,+ } as McpAppRecord;+ await host.updateResult(sessionId, clientId, record, owner);+ } catch {+ log.warn('MCP App card could not be stored');+ record = undefined;+ }+ }+ let result: CallToolResult;+ try {+ assertCurrent();+ const client = await currentClient(extra.signal);+ result = (await client.callTool(+ request.params,+ CallToolResultSchema,+ requestOptions(request, extra),+ )) as CallToolResult;+ assertCurrent();+ } catch (error) {+ if (record && sessionId) {+ try {+ await host.updateResult(+ sessionId,+ clientId,+ extra.signal.aborted+ ? { ...record, cancelled: 'Tool execution cancelled' }+ : {+ ...record,+ result: {+ isError: true,+ content: [{ type: 'text', text: 'MCP App tool execution failed' }],+ },+ },+ owner,+ );+ } catch {+ log.warn('MCP App failure card could not be stored');+ }+ }+ throw error;+ }+ if (record && sessionId) {+ try {+ await host.updateResult(sessionId, clientId, { ...record, result }, owner);+ } catch {+ log.warn('MCP App result card could not be stored');+ }+ }+ // Card persistence may yield while the owner or server configuration changes.+ assertCurrent();+ return modelToolResult(result);+ });+ const unlisten = connection.listen((message) => {+ try {+ assertCurrent();+ } catch {+ return;+ }+ void server.server.notification(message).catch(() => {});+ });+ server.server.onclose = () => {+ unlisten();+ void host.releaseConnection(connection).catch(() => {});+ };+ return server;+}diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/codexEnvironment.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/codexEnvironment.test.tsindex 18cfd0dc7a..faefe5acaa 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/codexEnvironment.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/codexEnvironment.test.ts@@ -1,7 +1,8 @@import { afterEach, describe, expect, it, vi } from 'vitest';import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';-import type { Logger, McpProvider } from '@cindy/maker-core';+import type { Logger, McpProvider, McpProviderContext } from '@cindy/maker-core';+import type { AppServerConfig } from '../../mcp-apps/connection.js';import {getActiveCodexBridgeServerNames,getCodexExtraSpawnConfig,@@ -10,8 +11,10 @@ import {shutdownCodexEnvironment,unregisterCodexMcpThreadContext,} from '../codexEnvironment.js';-import { CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY } from '../codexBuiltinToolPolicy.js';+import { CODEX_ALLOWED_BUILTIN_PLUGIN_IDS_KEY, CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY } from '../codexBuiltinToolPolicy.js';+import { registerAppServer, clearAppServerConfigs } from '../../mcp-apps/runtime.js';import { CINDY_MAKE_VENDOR_OPTION_KEY } from '../../../shared/cindyMakeSession.js';+import { CustomMcpProvider } from '../custom-mcp-provider.js';function noopLogger(): Logger {const logger: Logger = {@@ -83,6 +86,7 @@ describe('codexEnvironment', () => {afterEach(async () => {setCodexEnvironmentShutdownHook(null);await shutdownCodexEnvironment();+ clearAppServerConfigs();});it('reuses one bridge and exposes unbound MCP server URLs', async () => {@@ -123,6 +127,65 @@ describe('codexEnvironment', () => {expect(replacementUrl.toString()).not.toBe(boundUrl.toString());});+ it.each(['http', 'sse'] as const)('keeps a %s custom MCP facade available across Codex clients', async (transport) => {+ const instances: McpServer[] = [];+ const appProxy = vi.fn((read: () => AppServerConfig, context: McpProviderContext) => {+ expect(read()).toEqual({+ id: 'custom_test',+ url: 'https://example.test/mcp',+ transport,+ headers: { Authorization: 'Bearer test-only-token' },+ });+ expect(context.agentKind).toBe('codex');+ const server = new McpServer({ name: 'custom_test', version: '1.0.0' });+ instances.push(server);+ return server;+ });+ const provider = new CustomMcpProvider({+ id: 'custom_test', name: 'Custom Test', transport, url: 'https://example.test/mcp', headers: {},+ }, () => 'test-only-token', appProxy);+ registerAppServer(provider.name, () => provider.appServerConfig());+ const config = await getCodexExtraSpawnConfig({+ mcpProviders: [provider], logger: noopLogger(),+ });+ expect(config.bridgeServerNames).toContain('custom_test');+ expect(config.extraArgs.join('\n')).not.toContain('test-only-token');+ expect(Object.values(config.extraEnv)).not.toContain('test-only-token');+ expect(config.extraArgs).toContain('mcp_servers.custom_test.enabled=false');+ const vendorOptions = { [CODEX_ALLOWED_BUILTIN_PLUGIN_IDS_KEY]: [], cindyRuntimeMcpServerNames: [] as string[] };+ expect(config.buildSessionMcpConfig!('local-instance', { vendorOptions }))+ .toHaveProperty('mcp_servers.custom_test.enabled', false);+ vendorOptions.cindyRuntimeMcpServerNames = ['custom_test'];+ const bound = config.buildSessionMcpConfig!('local-instance', { vendorOptions });+ expect(bound).toHaveProperty('mcp_servers.custom_test.enabled', true);+ const url = bound['mcp_servers.custom_test.url'] as string;++ // Each MCP client needs its own facade; rebuilding must keep the provider receiver too.+ for (const id of [1, 2]) {+ const response = await config.bridge!.withDiscoveryContext({+ agentKind: 'codex', sessionId: 'local-task', sessionInstanceId: 'local-instance',+ workingDir: '/test', vendorOptions,+ }, () => fetch(url, {+ method: 'POST',+ headers: {+ authorization: `Bearer ${config.bridge!.token}`,+ accept: 'application/json, text/event-stream',+ 'content-type': 'application/json',+ },+ body: JSON.stringify({+ jsonrpc: '2.0', id, method: 'initialize',+ params: { protocolVersion: '2024-11-05', capabilities: {},+ clientInfo: { name: 'test-client', version: '1.0.0' } },+ }),+ }));+ const body = await response.text();+ expect(response.status).toBe(200);+ expect(body).toContain('"name":"custom_test"');+ }+ expect(appProxy).toHaveBeenCalledTimes(2);+ expect(instances[0]).not.toBe(instances[1]);+ });+it('disables cindy_make per thread unless the Session carries the Cindy Make marker', async () => {const cindyMake: McpProvider = {name: 'cindy_make',diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/piEnvironment.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/piEnvironment.test.tsindex ec142e8fa3..52563289be 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/piEnvironment.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/piEnvironment.test.ts@@ -782,6 +782,100 @@ describe('piEnvironment per-session identity', () => {config?.disposeSessionCtx?.();});+ it.each([false, true])('enforces frozen Pi custom-App mounts at the bridge request boundary (remote=%s)', async (remote) => {+ const credentials = vi.fn((id: string) => `test-main-only-credential-${id}`);+ const providers = ['allowed_app', 'excluded_app'].map((id) => new CustomMcpProvider(+ { id, name: id, url: 'https://mcp.example.invalid', transport: 'http', headers: {} },+ credentials,+ (read) => {+ const server = new McpServer({ name: id, version: '1' });+ server.tool('credentialed', {}, async () => {+ read(); // Main would attach the stored credentials to the upstream here.+ return { content: [{ type: 'text' as const, text: 'done' }] };+ });+ server.server.fallbackNotificationHandler = async () => { read(); };+ return server;+ },+ ));+ const ordinary = await getPiExtraSpawnConfig(providers, noopLogger(), {+ sessionId: 'pi-ordinary-apps', sessionInstanceId: 'ordinary-instance', workingDir: '/repo',+ ...(remote ? { remoteHostId: 'remote-host' } : {}), vendorOptions: {},+ });+ const vendorOptions: Record<string, unknown> = { [CODEX_ALLOWED_BUILTIN_PLUGIN_IDS_KEY]: [] };+ const frozen = await getPiExtraSpawnConfig(providers, noopLogger(), {+ sessionId: 'pi-frozen-apps', sessionInstanceId: 'frozen-instance', workingDir: '/repo',+ ...(remote ? { remoteHostId: 'remote-host' } : {}), vendorOptions,+ botMcpPolicy: {+ mode: 'allowlist', configured: ['allowed_app'],+ catalog: providers.map(({ name }) => ({ name, source: 'custom' as const, available: true })),+ },+ });+ try {+ expect(frozen!.mcpBridge!.servers.map((server) => server.name)).toEqual(['allowed_app']);+ expect(vendorOptions[RUNTIME_MCP_NAMES_KEY]).toEqual(['allowed_app']);+ expect(credentials).not.toHaveBeenCalled();+ const headers = (token: string) => ({+ authorization: `Bearer ${token}`, accept: 'application/json, text/event-stream',+ 'content-type': 'application/json',+ });+ const allowed = frozen!.mcpBridge!.servers[0]!;+ const init = await fetch(allowed.url, {+ method: 'POST', headers: headers(frozen!.mcpBridge!.token), body: INIT_BODY(1),+ });+ expect(init.status).toBe(200);+ const allowedSession = init.headers.get('mcp-session-id')!;+ await init.text();+ const called = await fetch(allowed.url, {+ method: 'POST', headers: { ...headers(frozen!.mcpBridge!.token), 'mcp-session-id': allowedSession },+ body: JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'credentialed', arguments: {} } }),+ });+ expect(called.status).toBe(200);+ expect(await readRpcText(called)).toMatchObject({ result: { content: [{ text: 'done' }] } });+ expect(credentials).toHaveBeenCalledWith('allowed_app');+ credentials.mockClear();++ // A bridge transport can already exist for another Session. Neither its+ // MCP session id nor a rewritten mounted URL may widen this Bot's mount.+ const ordinaryExcluded = ordinary!.mcpBridge!.servers.find((server) => server.name === 'excluded_app')!;+ const existing = await fetch(ordinaryExcluded.url, {+ method: 'POST', headers: headers(ordinary!.mcpBridge!.token), body: INIT_BODY(3),+ });+ expect(existing.status).toBe(200);+ const borrowedSession = existing.headers.get('mcp-session-id')!;+ await existing.text();+ const excluded = new URL(allowed.url);+ excluded.pathname = '/mcp/excluded_app';+ const statuses: number[] = [];+ const deniedInit = await fetch(excluded, {+ method: 'POST', headers: headers(frozen!.mcpBridge!.token), body: INIT_BODY(4),+ });+ statuses.push(deniedInit.status);+ await deniedInit.text();+ for (const body of [+ { jsonrpc: '2.0', id: 5, method: 'tools/list' },+ { jsonrpc: '2.0', id: 6, method: 'tools/call', params: { name: 'credentialed', arguments: {} } },+ { jsonrpc: '2.0', method: 'example/side-effect' },+ ]) {+ const response = await fetch(excluded, {+ method: 'POST', headers: { ...headers(frozen!.mcpBridge!.token), 'mcp-session-id': borrowedSession },+ body: JSON.stringify(body),+ });+ statuses.push(response.status);+ await response.text();+ }+ const deleted = await fetch(excluded, {+ method: 'DELETE', headers: { ...headers(frozen!.mcpBridge!.token), 'mcp-session-id': borrowedSession },+ });+ statuses.push(deleted.status);+ await deleted.text();+ expect(statuses).toEqual([403, 403, 403, 403, 403]);+ expect(credentials).not.toHaveBeenCalled();+ } finally {+ frozen?.disposeSessionCtx?.();+ ordinary?.disposeSessionCtx?.();+ }+ });+it('derives a stable per-session bridge token across rebuilds (round 41 — envHash stability)', async () => {// 回归(轮 41 CRITICAL):token 曾每次 randomBytes 新生成 → 断链重连重建// spawn env 时 CINDY_PI_MCP_BRIDGE 必变 → envHash 必变 → daemon ensurediff --git a/apps/desktop/src/main/mcp-integrations/codexBuiltinToolPolicy.ts b/apps/desktop/src/main/mcp-integrations/codexBuiltinToolPolicy.tsindex 77a94e0c6a..d5c2492e3a 100644--- a/apps/desktop/src/main/mcp-integrations/codexBuiltinToolPolicy.ts+++ b/apps/desktop/src/main/mcp-integrations/codexBuiltinToolPolicy.ts@@ -27,6 +27,16 @@ export function readAllowedBuiltinPluginIds(return readStringArray(vendorOptions, CODEX_ALLOWED_BUILTIN_PLUGIN_IDS_KEY);}+/** Custom App transports follow the same frozen mounts at configuration and use time. */+export function isFrozenMcpServerAllowed(+ vendorOptions: Readonly<Record<string, unknown>> | undefined,+ serverName: string,+): boolean {+ if (readAllowedBuiltinPluginIds(vendorOptions) === null) return true;+ const mounted = vendorOptions?.cindyRuntimeMcpServerNames;+ return Array.isArray(mounted) && mounted.includes(serverName);+}+/** Frozen per-runtime policy always wins over live/stable provider exceptions. */export function isFrozenBuiltinPluginAllowed(vendorOptions: Readonly<Record<string, unknown>> | undefined,diff --git a/apps/desktop/src/main/mcp-integrations/codexEnvironment.ts b/apps/desktop/src/main/mcp-integrations/codexEnvironment.tsindex fed952db7d..f85ef44768 100644--- a/apps/desktop/src/main/mcp-integrations/codexEnvironment.ts+++ b/apps/desktop/src/main/mcp-integrations/codexEnvironment.ts@@ -13,6 +13,7 @@ import { pluginIdForKnownProviderName } from '../maker-host/plugins/builtin-plugimport {CODEX_ALLOWED_BUILTIN_PLUGIN_IDS_KEY,CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY,+ isFrozenMcpServerAllowed,} from './codexBuiltinToolPolicy.js';import {CINDY_MAKE_MCP_SERVER_NAME,@@ -25,6 +26,7 @@ import {withMcpRouteIdentity,} from './codexHttpBridge.js';import { getRemoteMcpBridgeToken } from './remoteMcpBridgeToken.js';+import { appServerIds } from '../mcp-apps/runtime.js';const TOKEN_ENV = 'LIZI_MCP_TOKEN';const MCP_TIMEOUT_SEC = 10 * 60;@@ -322,7 +324,8 @@ async function doStart(if (!toClaudeSdkConfig) continue;const createServer = (): McpServer => {- const cfg = toClaudeSdkConfig(ctx) as+ // Class providers read instance state, including when creating later client facades.+ const cfg = toClaudeSdkConfig.call(provider, ctx) as| { type?: string; name?: string; instance?: unknown }| null;if (cfg?.type !== 'sdk' || !cfg.instance) {@@ -365,6 +368,7 @@ async function doStart(const bridge = Object.keys(serverFactories).length > 0? await startCodexHttpBridge({serverFactories,+ appServerNames: Object.keys(serverFactories).filter(name => appServerIds().includes(name)),pluginIdByServerName,// 远端常驻 daemon 经 SSH remote-forward 直连本 bridge:接受 persistent// token (safeStorage, 跨 app 重启稳定)。函数形式读取,token 首用时惰性@@ -404,6 +408,7 @@ async function doStart(// bearer_token_env_var 让 codex 从 env 读 token,不暴露在 process args。extraArgs.push('-c', `mcp_servers.${name}.url="${url}"`);extraArgs.push('-c', `mcp_servers.${name}.bearer_token_env_var="${TOKEN_ENV}"`);+ if (appServerIds().includes(name)) extraArgs.push('-c', `mcp_servers.${name}.enabled=false`);extraArgs.push('-c', `mcp_servers.${name}.startup_timeout_sec=${MCP_TIMEOUT_SEC}`);extraArgs.push('-c', `mcp_servers.${name}.tool_timeout_sec=${MCP_TIMEOUT_SEC}`);}@@ -435,6 +440,8 @@ async function doStart(withMcpRouteIdentity(bridge.url(name), { sessionInstanceId }),]),),+ ...Object.fromEntries(bridgeServerNames.filter((name) => appServerIds().includes(name))+ .map((name) => [`mcp_servers.${name}.enabled`, isFrozenMcpServerAllowed(session?.vendorOptions, name)])),// Cindy Make 个人版工具:app-server 共享一份 spawn 级 transport,只能按// 线程关。transport 与本 config 同源(上面刚写了 url),所以 enabled=false// 不会落成"只有 enabled 没有 transport"的非法条目(codex 先解析 transport)。diff --git a/apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts b/apps/desktop/src/main/mcp-integrations/codexHttpBridge.tsindex 3b9a4043db..a221facafe 100644--- a/apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts+++ b/apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts@@ -28,7 +28,8 @@ import {createCodexMcpThreadContextStore,isSameCodexMcpSessionContext,} from './codexMcpThreadContextStore.js';-import { isFrozenBuiltinPluginAllowed } from './codexBuiltinToolPolicy.js';+import { isFrozenBuiltinPluginAllowed, isFrozenMcpServerAllowed } from './codexBuiltinToolPolicy.js';+import { appServerIds } from '../mcp-apps/runtime.js';const SERVER_HEADER = 'Lizi_MCPS/1.0';const MCP_PATH_PREFIX = '/mcp/';@@ -74,9 +75,10 @@ export const REMOTE_ALLOWED_SERVER_NAMES: ReadonlySet<string> = new Set([*/export function selectRemoteInjectableServerNames(available: readonly string[],- gates: { collabEnabled: boolean; memoryEnabled: boolean; botHelperEnabled?: boolean },+ gates: { collabEnabled: boolean; memoryEnabled: boolean; botHelperEnabled?: boolean; appServerNames?: readonly string[] },): string[] {return [+ ...available.filter(name => appServerIds().includes(name) && (gates.appServerNames === undefined || gates.appServerNames.includes(name))),...(gates.collabEnabled ? available.filter((n) => REMOTE_COLLAB_SERVER_NAMES.has(n)) : []),...(gates.botHelperEnabled && available.includes(REMOTE_BOT_HELPER_SERVER_NAME)? [REMOTE_BOT_HELPER_SERVER_NAME]@@ -144,7 +146,7 @@ export interface CodexHttpBridge {instanceId: string;/** 拼出 codex 端 config 用的 URL,例如 http://127.0.0.1:54321/mcp/lizi_feishu */url(serverName: string): string;- /** Temporary startup identity, usable only by tools/list before thread registration. */+ /** Startup identity for App initialization and tools/list, never tool execution. */withDiscoveryContext<T>(ctx: LiziMcpSessionContext, run: () => Promise<T>): Promise<T>;registerThreadContext(threadId: string, ctx: LiziMcpSessionContext): void;unregisterThreadContext(threadId: string, expectedSessionInstanceId?: string): void;@@ -165,7 +167,7 @@ export interface CodexHttpBridge {*/unregisterSessionCtx(sessionId: string, expectedCtx?: LiziMcpSessionContext): void;/**- * per-session bearer token (pi 会话用)。与主 token 同权但按会话隔离:+ * per-session bearer token (pi 会话用)。按会话隔离,冻结伙伴仅能访问实际挂载的 server:* pi 每个会话在 spawn 前生成独立 token,经 env-file 交给远端进程 —— 单个* 会话的 env-file 泄漏只暴露该会话的 bridge 权限,不殃及其它会话与本地* codex 主 token(R5 安全审计 C-2)。必须与 registerSessionCtx 成对注册,@@ -199,6 +201,8 @@ export interface StartCodexHttpBridgeOptions {* 函数形式读取:token 允许晚于 bridge 启动才生成/落盘。*/additionalBearerTokens?: () => readonly string[];+ /** Explicit configured user MCP facades in this bridge generation; never arbitrary built-ins. */+ appServerNames?: readonly string[];logger: Logger;}@@ -249,8 +253,8 @@ export async function startCodexHttpBridge(// bearer token 鉴权:主 token (per-run, 本地 codex 子进程) / 额外 token// (persistent, 远端常驻 codex daemon 与远端 cc 共用) / per-session token- // (pi 会话, 按 ?session= 隔离, 见 interface 注释)。主 token 与 pi- // per-session token 全通;额外 token 只允许访问 REMOTE_ALLOWED_SERVER_NAMES+ // (pi 会话, 按 ?session= 隔离, 见 interface 注释)。Pi token 核对冻结伙伴的实际挂载;+ // 主 token 沿用 Codex 线程策略;额外 token 只允许访问 REMOTE_ALLOWED_SERVER_NAMES// 白名单 (协同、记忆、伙伴 helper;helper 另有 Session 实例与能力面校验)。// URL 解析提前:per-session token 匹配需要 session query,纯解析无副作用。const url = new URL(req.url ?? '/', 'http://127.0.0.1');@@ -348,12 +352,35 @@ export async function startCodexHttpBridge(// scoped (persistent) token 仅限远端白名单 server:// 同一 remote-forward 能摸到完整 /mcp/<name> 路由, 不得经它初始化// cindy_ssh 等其余本机 server — codex-connector P1。- if (isScopedRemoteToken && !REMOTE_ALLOWED_SERVER_NAMES.has(serverName)) {+ const appServer = opts.appServerNames?.includes(serverName) === true;+ const remoteAppServer = isScopedRemoteToken && appServer && appServerIds().includes(serverName);+ if (isScopedRemoteToken && !REMOTE_ALLOWED_SERVER_NAMES.has(serverName) && !remoteAppServer) {res.statusCode = 403;res.end();log.warn('rejected scoped remote token for non-collab server', { serverName });return;}+ // A process-wide daemon has no frozen mount policy. App facades+ // may attach upstream credentials only for an explicitly bound Session,+ // including Codex's short-lived discovery lease before thread/start returns.+ const appContext = appServer+ ? sessionTokenCtx ?? (instanceQuery === null ? undefined+ : threadContextStore.getContextForSessionInstanceId(instanceQuery) ?? discoveryContexts.get(instanceQuery))+ : undefined;+ if (appServer && (!appContext?.sessionId || (isScopedRemoteToken && !appContext.remoteHostId))) {+ res.statusCode = 401;+ res.end('MCP App server requires a bound Session');+ return;+ }+ // Bind frozen mounts for every token before initialization or transport lookup: an+ // excluded facade could otherwise attach Main-held upstream credentials,+ // or borrow a transport initialized by another Session.+ if ((appServer && !appServerIds().includes(serverName)) ||+ ((isPiSessionToken || appServer) && !isFrozenMcpServerAllowed((appContext ?? sessionTokenCtx)?.vendorOptions, serverName))) {+ res.statusCode = 403;+ res.end('MCP server is not mounted for this Session');+ return;+ }const createMcpServer = opts.serverFactories[serverName];const transports = transportsByServer.get(serverName);if (!createMcpServer || !transports) {@@ -372,6 +399,8 @@ export async function startCodexHttpBridge(log,threadContextStore,discoveryContexts,+ remoteAppServer,+ appServer,pluginId: opts.pluginIdByServerName?.[serverName],sessionTokenCtx,threadInstanceQuery: sessionQuery === null ? instanceQuery : null,@@ -574,6 +603,8 @@ interface DispatchOpts {threadContextStore: ReturnType<typeof createCodexMcpThreadContextStore>;discoveryContexts: ReadonlyMap<string, LiziMcpSessionContext>;remoteBotHelper?: boolean;+ remoteAppServer?: boolean;+ appServer?: boolean;pluginId?: string;/** per-session token 命中时解析出的 ctx;存在即优先于 _meta.threadId 路由。 */sessionTokenCtx?: LiziMcpSessionContext;@@ -609,6 +640,8 @@ async function dispatchToTransport(opts: DispatchOpts): Promise<void> {sessionTokenCtx,threadInstanceQuery,remoteBotHelper,+ remoteAppServer,+ appServer,} = opts;const sessionIdHeader = req.headers['mcp-session-id'];@@ -673,7 +706,22 @@ async function dispatchToTransport(opts: DispatchOpts): Promise<void> {});}}- // The remote token must never open the ordinary local helper surface.+ // Discovery and execution share the App's frozen mount policy on every route.+ if (appServer && parsedBody && typeof parsedBody === 'object') {+ const requests = Array.isArray(parsedBody) ? parsedBody : [parsedBody];+ const needsSession = requests.some((item) => {+ if (!item || typeof item !== 'object') return true;+ if ('id' in item) return !['ping', 'tools/list'].includes(String(item.method));+ // Only the transport handshake may precede Session binding. Standard+ // and extension notifications can mutate the credentialed upstream too.+ return item.method !== 'notifications/initialized';+ });+ if (!isFrozenMcpServerAllowed(activeContext?.vendorOptions, serverName) ||+ (needsSession && (!activeContext?.sessionId || !activeContext.sessionInstanceId ||+ (remoteAppServer && !activeContext.remoteHostId)))) {+ res.statusCode = 401;res.end('MCP App server requires a bound Session instance');return;+ }+ }// Startup discovery may list tools, but calls still need the registered thread.if (remoteBotHelper && (hasToolCall(parsedBody) ||(parsedBody as { method?: unknown } | undefined)?.method === 'tools/list') &&diff --git a/apps/desktop/src/main/mcp-integrations/custom-mcp-provider.ts b/apps/desktop/src/main/mcp-integrations/custom-mcp-provider.tsindex 36ad370776..cf317bd34d 100644--- a/apps/desktop/src/main/mcp-integrations/custom-mcp-provider.ts+++ b/apps/desktop/src/main/mcp-integrations/custom-mcp-provider.ts@@ -3,6 +3,9 @@* 适配成 maker-core 的 `McpProvider`,让同一份配置同时被 Claude Code 与 Codex 调用。** 仅支持远程 transport(http/sse):+ * - Desktop 注入 appProxy 时,两种 transport 都由 Main 的标准 MCP Apps Host 连接,+ * Claude/Codex/Pi 通过同一 SDK facade 访问;认证头不交给 View 或子进程。+ * - 以下原生配置与 env 注入仅用于未提供 appProxy 的兼容路径。* - Claude:`toClaudeSdkConfig` 返回原生 { type:'http'|'sse', url, headers }* (本地 cc 直用;纯 JSON 也能存活 remote cc 的可序列化过滤)。* - Codex:`toCodexMcpConfig` 返回 { type:'http', url, bearerTokenEnvVar? }@@ -26,6 +29,8 @@ import type {} from '@cindy/maker-core';import type { CustomMcpConfig } from '../maker-host/custom-mcp-store.js';+import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import type { AppServerConfig } from '../mcp-apps/connection.js';/*** 把 MCP id 规整成合法且**对不同 id 单射**的 env var 名。@@ -80,11 +85,19 @@ export class CustomMcpProvider implements McpProvider {readonly name: string;private readonly config: CustomMcpConfig;private readonly tokenReader: (id: string) => string | null;+ readonly supportsApps: boolean;+ private readonly appProxy?: (read: () => AppServerConfig, context: McpProviderContext) => McpServer;- constructor(config: CustomMcpConfig, tokenReader: (id: string) => string | null) {+ constructor(config: CustomMcpConfig, tokenReader: (id: string) => string | null, appProxy?: CustomMcpProvider['appProxy']) {this.config = config;this.name = config.id;this.tokenReader = tokenReader;+ this.appProxy = appProxy;+ this.supportsApps = Boolean(appProxy);+ }++ appServerConfig(): AppServerConfig {+ return { id: this.config.id, url: this.config.url, transport: this.config.transport, headers: this.buildHeaders() };}/** 合成 Claude 端使用的 headers(用户 headers + 可选 Bearer)。 */@@ -98,6 +111,7 @@ export class CustomMcpProvider implements McpProvider {}toClaudeSdkConfig(_context: McpProviderContext): unknown {+ if (this.appProxy) return { type: 'sdk', name: this.name, instance: this.appProxy(() => this.appServerConfig(), _context) };const headers = this.buildHeaders();return {type: this.config.transport, // 'http' | 'sse'@@ -107,6 +121,7 @@ export class CustomMcpProvider implements McpProvider {}toCodexMcpConfig(_context: McpProviderContext): CodexHttpMcpServerConfig | null {+ if (this.appProxy) return null; // Existing authenticated host bridge carries the facade.// Codex 只支持 Streamable HTTP transport;SSE 协议不兼容,跳过(null = 不注入 Codex)。// Claude 侧走 toClaudeSdkConfig,支持 sse,不受此限制。if (this.config.transport === 'sse') return null;@@ -133,6 +148,7 @@ export class CustomMcpProvider implements McpProvider {}getExtraEnv(_context: McpProviderContext): Record<string, string> | null {+ if (this.appProxy) return null; // Upstream secrets stay in Main.// SSE MCPs are not registered in Codex (toCodexMcpConfig returns null), so// neither their token nor their custom headers should be injected into the// Codex app-server environment.diff --git a/apps/desktop/src/main/mcp-integrations/custom-mcp-registry.ts b/apps/desktop/src/main/mcp-integrations/custom-mcp-registry.tsindex 56d0fa78d3..f5d36430bc 100644--- a/apps/desktop/src/main/mcp-integrations/custom-mcp-registry.ts+++ b/apps/desktop/src/main/mcp-integrations/custom-mcp-registry.ts@@ -23,6 +23,8 @@ import {} from '../maker-host/custom-mcp-store.js';import { readCustomMcpToken } from '../secrets/providerSecretStore.js';import { CustomMcpProvider } from './custom-mcp-provider.js';+import { createAppServerProxy } from '../mcp-apps/serverProxy.js';+import { registerAppServer, resetAppServers, clearAppServerConfigs } from '../mcp-apps/runtime.js';const log = createLogger('custom-mcp-registry');@@ -42,6 +44,7 @@ export function registerCustomMcpArrays(...arrays: McpProvider[][]): void {/** 清空注册表(切账号 / resetMaker 时调用,防止旧数组引用残留)。 */export function resetCustomMcpRegistry(): void {registeredArrays.length = 0;+ resetAppServers();}/**@@ -88,7 +91,8 @@ export async function refreshCustomMcpProviders(): Promise<void> {skippedNames.add(serverName);return [];}- return [new CustomMcpProvider(config, readCustomMcpToken)];+ const provider = new CustomMcpProvider(config, readCustomMcpToken, createAppServerProxy);+ return [provider];});} catch (err) {log.warn('list custom mcp servers failed; leaving providers unchanged', {@@ -96,6 +100,9 @@ export async function refreshCustomMcpProviders(): Promise<void> {});return;}+ // Saved endpoint changes revoke open Views, while existing Agent calls retain their snapshot.+ clearAppServerConfigs();+ for (const provider of providers) registerAppServer(provider.name, () => provider.appServerConfig());for (const arr of registeredArrays) {// 原地移除旧的 custom provider,再追加新的一批(不换数组引用)。for (let i = arr.length - 1; i >= 0; i--) {diff --git a/apps/desktop/src/main/mcp-integrations/piEnvironment.ts b/apps/desktop/src/main/mcp-integrations/piEnvironment.tsindex 79493826e3..03b03edef6 100644--- a/apps/desktop/src/main/mcp-integrations/piEnvironment.ts+++ b/apps/desktop/src/main/mcp-integrations/piEnvironment.ts@@ -644,7 +644,7 @@ async function doStart(if (!toClaudeSdkConfig) continue;const createServer = (): McpServer => {- const cfg = toClaudeSdkConfig(ctx) as { type?: string; instance?: unknown } | null;+ const cfg = toClaudeSdkConfig.call(provider, ctx) as { type?: string; instance?: unknown } | null;if (cfg?.type !== 'sdk' || !cfg.instance) {throw new Error(`provider ${provider.name} did not return an SDK McpServer instance`);}diff --git a/apps/desktop/src/main/mcp-integrations/piMcpTransport.ts b/apps/desktop/src/main/mcp-integrations/piMcpTransport.tsindex 66eb8c17bf..cf67f866f0 100644--- a/apps/desktop/src/main/mcp-integrations/piMcpTransport.ts+++ b/apps/desktop/src/main/mcp-integrations/piMcpTransport.ts@@ -1,4 +1,5 @@import type { McpProvider } from '@cindy/maker-core';+import { CustomMcpProvider } from './custom-mcp-provider.js';/** Desktop-owned loopback hosts. Remote Pi's loopback is a different machine. */export function isDesktopLoopbackMcpUrl(url: URL): boolean {@@ -25,6 +26,7 @@ export function isPiCustomMcpProviderAvailable(provider: McpProvider,opts?: { remoteHostId?: string | null },): boolean {+ if (provider instanceof CustomMcpProvider && provider.supportsApps) return true;try {const config = provider.toCodexMcpConfig?.({ agentKind: 'pi', workingDir: '', vendorOptions: {} });if (config?.type !== 'http') return false;diff --git a/apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.tsindex f4d6eba28f..63c12c5ca3 100644--- a/apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.ts+++ b/apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.ts@@ -29,6 +29,8 @@ vi.mock('../../mcp-integrations/remoteMcpBridgeToken.js', () => ({}));import { getRemoteMcpBridgeToken } from '../../mcp-integrations/remoteMcpBridgeToken.js';+import { registerAppServer, clearAppServerConfigs } from '../../mcp-apps/runtime.js';+import { CODEX_ALLOWED_BUILTIN_PLUGIN_IDS_KEY } from '../../mcp-integrations/codexBuiltinToolPolicy.js';const SERVERS = ['cindy_orca', 'orca_worker_bridge'];@@ -1623,3 +1625,39 @@ describe('remote Bot helper transport', () => {},);});++describe('remote App transports', () => {+ it('renders custom App transports disabled without depending on the current registry', () => {+ const block = parseToml(renderManagedMcpBlock({+ remotePort: 47921, serverNames: ['example'], tokenFingerprint: 'test-fingerprint',+ })) as { mcp_servers: Record<string, { enabled?: boolean }> };+ expect(block.mcp_servers.example.enabled).toBe(false);+ });+ it.each([false, true])('disables process-wide discovery and binds ordinary/Bot threads with helper=%s', async (helper) => {+ registerAppServer('example', () => ({ id: 'example', url: 'https://example.invalid/mcp', transport: 'http' }));+ try {+ const { host, inputs } = fakeHost(`host-app-${helper}`, '');+ const serverNames = ['example', ...(helper ? ['cindy_helper'] : [])];+ expect(await ensureRemoteCodexMcpBridge(host, {+ ensureBridgeStarted: async () => ({ port: 38991, serverNames, bridgeInstanceId: 'app-bridge' }),+ isCollabEnabled: () => false, isMakerMemoryEnabled: () => false,+ })).toMatchObject({ ok: true });+ const written = parseToml(decodeWrittenConfig(inputs)!) as { mcp_servers: Record<string, { enabled?: boolean }> };+ expect(written.mcp_servers.example.enabled).toBe(false);+ const opts = { bridgeInstanceId: 'app-bridge', serverNames, collabEnabled: false, makerMemoryEnabled: false };+ const ordinary = buildRemoteCodexSessionMcpConfig(host.id, 'app-instance', opts);+ expect(ordinary).toMatchObject({+ 'mcp_servers.example.url': 'http://127.0.0.1:47921/mcp/example?instance=app-instance',+ 'mcp_servers.example.enabled': true,+ 'mcp_servers.example.bearer_token_env_var': 'LIZI_MCP_TOKEN',+ });+ const vendorOptions = { [CODEX_ALLOWED_BUILTIN_PLUGIN_IDS_KEY]: [], cindyRuntimeMcpServerNames: [] as string[] };+ expect(buildRemoteCodexSessionMcpConfig(host.id, 'bot-instance', { ...opts, vendorOptions }))+ .toHaveProperty('mcp_servers.example.enabled', false);+ vendorOptions.cindyRuntimeMcpServerNames = ['example'];+ expect(buildRemoteCodexSessionMcpConfig(host.id, 'bot-instance', { ...opts, vendorOptions }))+ .toHaveProperty('mcp_servers.example.enabled', true);+ if (helper) expect(ordinary['mcp_servers.cindy_helper.enabled']).toBe(false);+ } finally { clearAppServerConfigs(); }+ });+});diff --git a/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts b/apps/desktop/src/main/remote-ssh/codex-remote-mcp.tsindex 018f850b69..eb85476013 100644--- a/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts+++ b/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts@@ -42,6 +42,8 @@ import {selectRemoteInjectableServerNames,} from '../mcp-integrations/codexHttpBridge.js';import { getRemoteMcpBridgeToken } from '../mcp-integrations/remoteMcpBridgeToken.js';+import { appServerIds } from '../mcp-apps/runtime.js';+import { isFrozenMcpServerAllowed } from '../mcp-integrations/codexBuiltinToolPolicy.js';const log = createLogger('codex-remote-mcp');@@ -201,9 +203,9 @@ export function invalidateRemoteCodexMcpEndpointState(hostId: string): void {});}-/** Bind the remote daemon's disabled helper transport to one concrete Session.+/** Bind the remote daemon's disabled helper and App transports to one concrete Session.* Read the port at use time: SSH forwarding is established after host construction.- * Only Bot MCP policy enables this transport; ordinary remote threads keep it disabled.+ * Only Bot MCP policy enables the helper; Apps follow the thread's frozen mounts.*/export function buildRemoteCodexSessionMcpConfig(hostId: string,@@ -213,6 +215,7 @@ export function buildRemoteCodexSessionMcpConfig(serverNames: string[];collabEnabled: boolean;makerMemoryEnabled: boolean;+ vendorOptions?: Record<string, unknown>;},): Record<string, unknown> {const prefs = readPortPrefs()[hostId];@@ -224,21 +227,24 @@ export function buildRemoteCodexSessionMcpConfig(botHelperEnabled: true,});// A written config is not proof that a busy daemon has loaded this generation.- // Never combine a new route with its old token or pre-helper server config.- if (!serverNames.includes(REMOTE_BOT_HELPER_SERVER_NAME) || prefs.appliedFingerprint !== computeRemoteMcpFingerprint({+ // Never combine a new route with its old token or unloaded server config.+ if (!serverNames.length || prefs.appliedFingerprint !== computeRemoteMcpFingerprint({token,bridgeInstanceId: opts.bridgeInstanceId,remotePort: prefs.remotePort,serverNames,})) return {};- return {- [`mcp_servers.${REMOTE_BOT_HELPER_SERVER_NAME}.url`]: withMcpRouteIdentity(- `http://127.0.0.1:${prefs.remotePort}/mcp/${REMOTE_BOT_HELPER_SERVER_NAME}`,- { sessionInstanceId },- ),- [`mcp_servers.${REMOTE_BOT_HELPER_SERVER_NAME}.bearer_token_env_var`]: TOKEN_ENV,- [`mcp_servers.${REMOTE_BOT_HELPER_SERVER_NAME}.enabled`]: false,- };+ const apps = new Set(appServerIds());+ return Object.fromEntries(serverNames+ .filter((name) => name === REMOTE_BOT_HELPER_SERVER_NAME || apps.has(name))+ .flatMap((name) => [+ [`mcp_servers.${name}.url`, withMcpRouteIdentity(+ `http://127.0.0.1:${prefs.remotePort}/mcp/${name}`, { sessionInstanceId },+ )],+ [`mcp_servers.${name}.bearer_token_env_var`, TOKEN_ENV],+ [`mcp_servers.${name}.enabled`, name !== REMOTE_BOT_HELPER_SERVER_NAME &&+ isFrozenMcpServerAllowed(opts.vendorOptions, name)],+ ]));}// ── 远端 config.toml 管理段 (纯函数, 便于单测) ──────────────────────────────@@ -260,7 +266,9 @@ export function renderManagedMcpBlock(opts: {`[mcp_servers.${name}]`,`url = "http://127.0.0.1:${opts.remotePort}/mcp/${name}"`,`bearer_token_env_var = "${TOKEN_ENV}"`,- ...(name === REMOTE_BOT_HELPER_SERVER_NAME ? ['enabled = false'] : []),+ // Only process-wide built-ins can initialize without a Session. Every+ // other managed name is a custom App facade, bound by the thread config.+ ...(name === REMOTE_BOT_HELPER_SERVER_NAME || !REMOTE_ALLOWED_SERVER_NAMES.has(name) ? ['enabled = false'] : []),'startup_timeout_sec = 600','tool_timeout_sec = 600','',@@ -312,7 +320,7 @@ function isManagedResidueLine(line: string): boolean {}/**- * 受管 table 内我们自己写的标量行 (trim 后)。`enabled` 是 cindy_helper 的禁用标记,+ * 受管 table 内我们自己写的标量行 (trim 后)。`enabled` 是 helper / App 的禁用标记,* 与两个 timeout 同属受管段; 旧版本没把它当受管内容, 刷新时它连同其后的 timeout* 会留在 end 标记之外, 累积两份就是 TOML duplicate-key, codex 起不来 (#4776)。*/@@ -778,7 +786,7 @@ export function hasPendingRemoteMcpDrift(},): boolean {const applied = readPortPrefs()[hostId]?.appliedFingerprint ?? null;- if ((!opts.collabEnabled && !opts.makerMemoryEnabled && !opts.botHelperAvailable) || !opts.token) {+ if ((!opts.collabEnabled && !opts.makerMemoryEnabled && !opts.botHelperAvailable && appServerIds().length === 0) || !opts.token) {// 清理语义:applied 存在 = 待清理 (strip / 清理路径未跑过)。return applied !== null;}@@ -793,7 +801,7 @@ export function hasPendingRemoteMcpDrift(token: opts.token,bridgeInstanceId: opts.bridgeInstanceId,remotePort,- serverNames: selectRemoteInjectableServerNames([...REMOTE_ALLOWED_SERVER_NAMES], {+ serverNames: selectRemoteInjectableServerNames([...REMOTE_ALLOWED_SERVER_NAMES, ...appServerIds()], {collabEnabled: opts.collabEnabled,memoryEnabled: opts.makerMemoryEnabled,botHelperEnabled: opts.botHelperAvailable,diff --git a/apps/desktop/src/main/secrets/__tests__/mcpAppRevisionKey.test.ts b/apps/desktop/src/main/secrets/__tests__/mcpAppRevisionKey.test.tsnew file mode 100644index 0000000000..e7a615aa6f--- /dev/null+++ b/apps/desktop/src/main/secrets/__tests__/mcpAppRevisionKey.test.ts@@ -0,0 +1,100 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const state = vi.hoisted(() => ({ root: '', owner: 'fixture-a', available: true, pending: false }));+vi.mock('electron', () => ({+ app: { getPath: () => state.root },+ safeStorage: {+ isEncryptionAvailable: () => state.available,+ encryptString: (value: string) => Buffer.from(`sealed-test-only:${value}`),+ decryptString: (value: Buffer) => {+ if (!value.toString().startsWith('sealed-test-only:')) throw new Error('invalid ciphertext');+ return value.toString().slice('sealed-test-only:'.length);+ },+ },+}));+vi.mock('../../logger.js', () => ({ createLogger: () => ({ warn: vi.fn(), info: vi.fn() }) }));+vi.mock('../../appSessionState.js', () => ({+ getActiveAppSession: () => ({ dataOwnerId: state.owner }),+ isAppSessionBoundaryPending: () => state.pending,+ dataOwnerStorageKey: (owner: string) => owner, LOCAL_DATA_OWNER_ID: 'local-v1',+}));++import { getMcpAppRevisionKey, getProviderSecretStore, resolveOwnerScopedSecretStorageKey } from '../providerSecretStore.js';+import { MCP_APP_REVISION_KEY_STORAGE_KEY } from '../../../shared/providerSecrets.js';++function keyPath() {+ return path.join(state.root, 'safe-storage', `${resolveOwnerScopedSecretStorageKey(MCP_APP_REVISION_KEY_STORAGE_KEY)}.enc`);+}+beforeEach(() => {+ state.root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-mcp-app-revision-key-'));+ state.owner = 'fixture-a'; state.available = true; state.pending = false;+ getProviderSecretStore().invalidateCaches();+});+afterEach(() => {+ vi.restoreAllMocks();+ getProviderSecretStore().invalidateCaches();+ fs.rmSync(state.root, { recursive: true, force: true });+});++describe('MCP App revision key vault', () => {+ it('persists only encrypted key material and reuses it after process-cache invalidation', () => {+ const key = getMcpAppRevisionKey();+ expect(key).toMatch(/^[a-f0-9]{64}$/);+ const bytes = fs.readFileSync(keyPath());+ expect(bytes.toString()).not.toContain(key);+ getProviderSecretStore().invalidateCaches();+ expect(getMcpAppRevisionKey()).toBe(key);+ expect(fs.readFileSync(keyPath())).toEqual(bytes);+ });++ it('isolates owners even before cache invalidation and refuses pending owner boundaries', () => {+ const first = getMcpAppRevisionKey();+ state.owner = 'fixture-b';+ expect(getMcpAppRevisionKey()).not.toBe(first);+ state.owner = 'fixture-a';+ expect(getMcpAppRevisionKey()).toBe(first);+ state.pending = true;+ expect(getMcpAppRevisionKey).toThrow('MCP_APP_REVISION_KEY_UNAVAILABLE');+ state.pending = false; state.owner = '';+ expect(getMcpAppRevisionKey).toThrow('MCP_APP_REVISION_KEY_UNAVAILABLE');+ });++ it('retries unavailable secure storage without writing a plaintext or ephemeral substitute', () => {+ state.available = false;+ expect(getMcpAppRevisionKey).toThrow('MCP_APP_REVISION_KEY_UNAVAILABLE');+ expect(fs.readdirSync(state.root)).toEqual([]);+ state.available = true;+ expect(getMcpAppRevisionKey()).toMatch(/^[a-f0-9]{64}$/);+ });++ it.each(['invalid-ciphertext', Buffer.from('sealed-test-only:invalid-key').toString('base64')])(+ 'preserves unreadable vault data instead of silently replacing it', (bytes) => {+ fs.mkdirSync(path.dirname(keyPath()));+ fs.writeFileSync(keyPath(), bytes);+ expect(getMcpAppRevisionKey).toThrow('MCP_APP_REVISION_KEY_UNAVAILABLE');+ expect(fs.readFileSync(keyPath(), 'utf8')).toBe(bytes);+ },+ );++ it('adopts a concurrent creator instead of replacing the already persisted key', () => {+ const winner = 'b'.repeat(64);+ const bytes = Buffer.from(`sealed-test-only:${winner}`).toString('base64');+ const write = fs.writeFileSync;+ vi.spyOn(fs, 'writeFileSync').mockImplementationOnce((file, data, options) => {+ write(file, bytes, options);+ write(file, data, options); // Same exclusive-create flags now produce EEXIST.+ });+ expect(getMcpAppRevisionKey()).toBe(winner);+ expect(fs.readFileSync(keyPath(), 'utf8')).toBe(bytes);+ });++ it('clears the key and its cache with the existing explicit secret-clearing boundary', () => {+ const before = getMcpAppRevisionKey();+ getProviderSecretStore().clearAll();+ expect(fs.existsSync(keyPath())).toBe(false);+ expect(getMcpAppRevisionKey()).not.toBe(before);+ });+});diff --git a/apps/desktop/src/main/secrets/providerSecretStore.ts b/apps/desktop/src/main/secrets/providerSecretStore.tsindex 8f0a3901c6..1827d49cea 100644--- a/apps/desktop/src/main/secrets/providerSecretStore.ts+++ b/apps/desktop/src/main/secrets/providerSecretStore.ts@@ -5,6 +5,7 @@ import {import { app, safeStorage } from 'electron';import fs from 'node:fs';import path from 'node:path';+import { randomBytes } from 'node:crypto';import { readChunkedSecret, writeChunkedSecret } from './chunkedSecretFile.js';import { storedCustomProviderId } from '@cindy/model-providers';@@ -25,6 +26,7 @@ import {GHOST_SECRET_HINT_PREFIX,PROVIDER_SECRET_IDS,PI_PROXY_DERIVATION_KEY_STORAGE_KEY,+ MCP_APP_REVISION_KEY_STORAGE_KEY,REMOTE_MCP_BRIDGE_TOKEN_STORAGE_KEY,type ProviderSecretId,} from '../../shared/providerSecrets.js';@@ -37,6 +39,7 @@ import {import { hasLegacyOwnerNamespaceClaim } from '../ownerNamespaceMigration.js';const log = createLogger('providerSecretStore');+let mcpAppRevisionKeyCache: { path: string; key: string } | undefined;let canUseMivoAlias: ((instanceKey: string) => boolean) | null = null;@@ -301,6 +304,7 @@ export function createProviderSecretStore(): ProviderSecretStore {let lastReconciledOwnerId: string | null = null;const notifySecretsCleared = (): void => {+ mcpAppRevisionKeyCache = undefined;for (const listener of secretsClearedListeners) {try {listener();@@ -317,6 +321,7 @@ export function createProviderSecretStore(// 旧账号远端 host 上仍在跑的 daemon env 里的 token 必须失效,防串号。io.remove(REMOTE_MCP_BRIDGE_TOKEN_STORAGE_KEY);io.remove(PI_PROXY_DERIVATION_KEY_STORAGE_KEY);+ io.remove(MCP_APP_REVISION_KEY_STORAGE_KEY);// 动态键名密钥同清(按前缀扫 io.list()):自定义 MCP bearer token(mcp_token_<id>)、// 自定义供应商 per-runtime key(provider_key_*)、通用 OAuth 凭证 blob(provider_oauth_*)、// 意识 network 槽凭证(ghost_secret_*)。这些不在 PROVIDER_SECRET_IDS 静态集合里,@@ -652,6 +657,37 @@ export function writePiProxyDerivationKey(value: string): boolean {}}+/** Owner-scoped revision key: private, encrypted and stable across Host restarts. */+export function getMcpAppRevisionKey(): string {+ try {+ const storageKey = resolveOwnerScopedSecretStorageKey(MCP_APP_REVISION_KEY_STORAGE_KEY);+ if (!storageKey || isAppSessionBoundaryPending()) throw new Error('owner unavailable');+ const filepath = path.join(secretDir(), `${storageKey}.enc`);+ if (mcpAppRevisionKeyCache?.path === filepath) return mcpAppRevisionKeyCache.key;+ if (!safeStorage.isEncryptionAvailable()) throw new Error('vault unavailable');+ let key = readPhysical(storageKey);+ if (key === null) {+ const created = randomBytes(32).toString('hex');+ const encrypted = safeStorage.encryptString(created).toString('base64');+ fs.mkdirSync(secretDir(), { recursive: true });+ try {+ // Concurrent instances must adopt the winner, never overwrite its key.+ fs.writeFileSync(filepath, encrypted, { encoding: 'utf8', flag: 'wx', mode: 0o600 });+ key = created;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;+ key = readPhysical(storageKey);+ }+ }+ if (!key || !/^[a-f0-9]{64}$/.test(key)) throw new Error('invalid revision key');+ mcpAppRevisionKeyCache = { path: filepath, key };+ return key;+ } catch {+ // Never fall back to a public hash, replace unreadable vault data or expose it.+ throw new Error('MCP_APP_REVISION_KEY_UNAVAILABLE');+ }+}+/** 删除某自定义供应商 runtime 的 API key;不存在视为成功。 */export function removeCustomProviderKey(providerId: string,diff --git a/apps/desktop/src/main/security/__tests__/csp.test.ts b/apps/desktop/src/main/security/__tests__/csp.test.tsindex fa7659afd8..8dd3b19f0d 100644--- a/apps/desktop/src/main/security/__tests__/csp.test.ts+++ b/apps/desktop/src/main/security/__tests__/csp.test.ts@@ -62,7 +62,9 @@ describe('buildContentSecurityPolicy — shared invariants', () => {const d = parsePolicy(buildContentSecurityPolicy(ctx));expect(d['default-src']).toEqual(["'self'"]);expect(d['object-src']).toEqual(["'none'"]);- expect(d['frame-src']).toEqual(["'none'"]);+ // Only host-supplied, separately sandboxed MCP App documents may be framed.+ expect(d['frame-src']).toEqual(['cindy-mcp-app:']);+ expect(d['frame-src']).not.toEqual(expect.arrayContaining(['https:', 'http:', 'data:', "'self'"]));expect(d['frame-ancestors']).toEqual(["'none'"]);expect(d['base-uri']).toEqual(["'self'"]);expect(d['form-action']).toEqual(["'self'"]);diff --git a/apps/desktop/src/main/security/csp.ts b/apps/desktop/src/main/security/csp.tsindex 9cf2240bae..96e0c2b324 100644--- a/apps/desktop/src/main/security/csp.ts+++ b/apps/desktop/src/main/security/csp.ts@@ -92,7 +92,7 @@ export function parseOrigin(url: string | null | undefined): string | null {* media (avatars, markdown / web-search images) and cannot execute code — a* blocked image is a worse UX regression than the marginal risk. The real* hardening lives in `script-src` (no inline in prod; unsafe-eval kept for- * vendored drawio) plus `object-src 'none'` and `frame-src 'none'`.+ * vendored drawio) plus `object-src 'none'` and the isolated MCP Apps frame scheme.*/export function buildContentSecurityPolicy(ctx: CspContext): string {const { isDev, devServerOrigin } = ctx;@@ -169,9 +169,9 @@ export function buildContentSecurityPolicy(ctx: CspContext): string {// covers bundler-emitted blob workers.'worker-src': ["'self'", 'blob:'],'object-src': ["'none'"],- // No <iframe> in the app renderer; the RSB <webview> is not governed by- // frame-src. 'none' blocks an XSS-injected iframe.- 'frame-src': ["'none'"],+ // MCP Apps frames use only the isolated custom scheme; other frame sources+ // remain blocked. The RSB <webview> is not governed by frame-src.+ 'frame-src': ['cindy-mcp-app:'],'frame-ancestors': ["'none'"],'base-uri': ["'self'"],'form-action': ["'self'"],diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 4badb2d1ab..b9b31e7340 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -6328,6 +6328,7 @@ contextBridge.exposeInMainWorld('electronAPI', {onLocalModelPullProgress: fanOutMakerLocalModelPullProgress,onLocalModelInstallProgress: fanOutMakerLocalModelInstallProgress,+ mcpApps: (sessionId: string, input: unknown): Promise<unknown> => ipcRenderer.invoke('maker:mcp-apps:v1', sessionId, input),// 自定义 MCP 服务器配置 CRUD(可选 bearer token 另走通用 safeStorage IPC,不经这里)。listCustomMcpServers: (context?: import('../shared/customMcp').CustomMcpListContext,diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreLearnCard.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreLearnCard.test.tsindex 59572ccd1c..20070c07d5 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreLearnCard.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreLearnCard.test.ts@@ -214,6 +214,52 @@ describe('teammate result attachment history', () => {});// Both initial history and live message insertion use the same stored-row projection.+describe('MCP App read-only history', () => {+ it.each(['owner', 'guest', 'pending'])(+ 'keeps public text and titles for %s card history',+ async (audience) => {+ const id = sid('mcp-app-history');+ const text = audience === 'pending' ? '' : 'Saved form result';+ transportMocks.listMessages.mockResolvedValueOnce([+ {+ id: 'app-row',+ clientId: 'app-card',+ sessionId: id,+ role: 'assistant',+ createdAt: Date.now(),+ content:+ audience !== 'owner'+ ? { mcpAppHistory: { version: 1, title: 'Saved form', text } }+ : {+ mcpApp: {+ version: 1,+ serverId: 'example',+ serverRevision: 'revision',+ resourceUri: 'ui://example/app',+ tool: { name: 'draft', title: 'Saved form', inputSchema: { type: 'object' } },+ arguments: {},+ result: {+ content: [{ type: 'text', text: 'Saved form result' }],+ _meta: { private: 'view-only' },+ },+ },+ },+ agentMeta: { mcpApp: true },+ },+ ] as never);+ makerChatStore.ensureInitialMessages(id);+ await vi.waitFor(() => expect(makerChatStore.getSnapshot(id).historyLoaded).toBe(true));+ expect(makerChatStore.getSnapshot(id).messages[0]).toMatchObject({+ systemCardType: 'mcp-app',+ systemCardData: { title: 'Saved form', fallbackText: text },+ });+ expect(+ JSON.stringify(makerChatStore.getSnapshot(id).messages[0].systemCardData),+ ).not.toContain('view-only');+ },+ );+});+describe('private group reply source', () => {it('keeps group provenance on assistant rows without relabeling normal private replies', async () => {const id = sid('group-private-source');diff --git a/apps/desktop/src/renderer/components/chat/McpAppCard.tsx b/apps/desktop/src/renderer/components/chat/McpAppCard.tsxnew file mode 100644index 0000000000..80ea6df0fe--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/McpAppCard.tsx@@ -0,0 +1,303 @@+import { useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore } from 'react';+import { useTranslation } from 'react-i18next';+import { isSharedTaskPeer } from '@cindy/device-link';+import {+ McpAppController,+ mcpAppFailureKey,+ type AppRpc,+ type AppInvoker,+} from '@cindy/maker-shared/mcp-app-controller';+import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOrigin';+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';+import { Button } from '@/components/ui/button';+import { Spinner } from '@/components/ui/spinner';++function hostContext(locale: string, element: HTMLElement): Record<string, unknown> {+ const style = getComputedStyle(document.documentElement);+ const variable = (name: string) => style.getPropertyValue(name).trim();+ return {+ theme: document.documentElement.classList.contains('dark') ? 'dark' : 'light',+ locale,+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,+ platform: 'desktop',+ userAgent: 'Cindy',+ deviceCapabilities: {+ touch: navigator.maxTouchPoints > 0,+ hover: matchMedia('(hover: hover)').matches,+ },+ containerDimensions: { width: Math.round(element.clientWidth), maxHeight: 1_200 },+ styles: {+ variables: {+ '--color-background-primary': variable('--surface'),+ '--color-background-secondary': variable('--surface-elevated'),+ '--color-background-tertiary': variable('--surface-hover'),+ '--color-text-primary': variable('--text-primary'),+ '--color-text-secondary': variable('--text-secondary'),+ '--color-text-tertiary': variable('--text-tertiary'),+ '--color-border-primary': variable('--border-default'),+ '--color-border-secondary': variable('--border-subtle'),+ '--color-text-danger': variable('--error-fg'),+ '--color-text-warning': variable('--warning-fg'),+ '--font-sans': variable('--font-sans') || style.fontFamily,+ '--font-mono': variable('--font-mono'),+ '--border-radius-md': '8px',+ },+ },+ };+}++interface McpAppCardProps {+ sessionId: string;+ clientId: string;+ title: string;+ fallbackText?: string;+}++export function McpAppCard(props: McpAppCardProps) {+ const { t } = useTranslation();+ const deviceId = useSyncExternalStore(+ remoteProjectsStore.subscribe,+ () => getStickySessionDeviceId(props.sessionId),+ () => undefined,+ );+ // Shared-task peers can read history, but must not create an interactive View.+ if (isSharedTaskPeer(deviceId)) {+ const title = props.title ? t('mcpApps.cardTitle', { title: props.title }) : t('mcpApps.appName');+ return (+ <section className="my-3 rounded-xl border border-border p-3" aria-label={title}>+ <div className="text-13 text-[var(--text-secondary)]">{title}</div>+ {props.fallbackText && (+ <p className="mt-3 whitespace-pre-wrap break-words text-14 text-[var(--text-primary)]">+ {props.fallbackText}+ </p>+ )}+ <p className="mt-3 text-13 text-[var(--text-secondary)]">{t('mcpApps.sharedTaskReadOnly')}</p>+ </section>+ );+ }+ return <InteractiveMcpAppCard {...props} deviceId={deviceId} />;+}++/** Untrusted HTML always sits across an origin boundary, without Cindy's preload. */+function InteractiveMcpAppCard({ sessionId, clientId, title, fallbackText, deviceId }: McpAppCardProps & { deviceId?: string }) {+ const { t, i18n } = useTranslation();+ const appTitle = title || t('mcpApps.appName');+ const card = useRef<HTMLDialogElement>(null);+ const root = useRef<HTMLDivElement>(null);+ const controllerRef = useRef<McpAppController | undefined>(undefined);+ const [attempt, setAttempt] = useState(0);+ const [error, setError] = useState<ReturnType<typeof mcpAppFailureKey>>();+ const [loading, setLoading] = useState(true);+ const [height, setHeight] = useState(320);+ const [mode, setMode] = useState('inline');+ const [border, setBorder] = useState(true);+ const [visible, setVisible] = useState(false);+ const locale = i18n.resolvedLanguage ?? i18n.language;+ const localeRef = useRef(locale);+ localeRef.current = locale;++ useEffect(() => {+ // A failed View collapses; observe the card so its retry stays visible.+ const element = card.current;+ if (!element) return;+ let intersecting = false;+ const update = () => setVisible(intersecting && document.visibilityState !== 'hidden');+ const observer = new IntersectionObserver(([entry]) => {+ intersecting = entry.isIntersecting;+ update();+ });+ observer.observe(element);+ document.addEventListener('visibilitychange', update);+ return () => {+ observer.disconnect();+ document.removeEventListener('visibilitychange', update);+ };+ }, []);++ useEffect(() => {+ const element = root.current;+ if (!element || !visible) return;+ let disposed = false;+ let frame: HTMLIFrameElement | undefined;+ let localViewId: string | undefined;+ const invoke: AppInvoker = (id, input) =>+ window.electronAPI.maker.mcpApps(id, deviceId ? { ...input, deviceId } : input);+ const post = (message: AppRpc) => frame?.contentWindow?.postMessage(message, '*');+ const fail = (error: unknown) => {+ if (!disposed) {+ setLoading(false);+ setError(mcpAppFailureKey(error));+ frame?.remove();+ setMode('inline');+ }+ };+ const controller = new McpAppController(+ invoke,+ sessionId,+ clientId,+ post,+ (message) => {+ if (disposed) return;+ if (message.method === 'ui/notifications/initialized') setLoading(false);+ if (message.method === 'ui/notifications/size-changed') {+ const value = message.params?.height;+ if (typeof value === 'number' && Number.isFinite(value))+ setHeight(Math.max(80, Math.min(1_200, Math.ceil(value))));+ }+ if (message.method === 'ui/notifications/host-context-changed') {+ const mode = message.params?.displayMode;+ if (mode === 'inline' || mode === 'fullscreen') setMode(mode);+ }+ },+ fail,+ );+ controllerRef.current = controller;+ setLoading(true);+ setError(undefined);+ setMode('inline');+ const receive = (event: MessageEvent) => {+ if (!frame || event.source !== frame.contentWindow) return;+ const message = event.data as AppRpc;+ if (message?.method === 'ui/notifications/sandbox-proxy-ready') {+ controller.sandboxReady(`cindy-mcp-app://${localViewId}-view/resource`);+ } else controller.receive(message);+ };+ window.addEventListener('message', receive);+ void controller+ .open(hostContext(localeRef.current, element))+ .then(async (document) => {+ if (!document || disposed) return;+ localViewId = document.viewId;+ setBorder(document.prefersBorder);+ frame = window.document.createElement('iframe');+ frame.title = appTitle;+ frame.setAttribute('sandbox', 'allow-scripts allow-same-origin');+ frame.setAttribute(+ 'allow',+ "camera 'none'; microphone 'none'; geolocation 'none'; clipboard-write 'none'",+ );+ frame.style.cssText = 'width:100%;height:100%;display:block;border:0';+ frame.src = `cindy-mcp-app://${localViewId}/sandbox`;+ element.appendChild(frame);+ })+ .catch((error) => {+ fail(error);+ void controller.close().catch(() => {});+ });+ const update = () => {+ void controller.context(hostContext(localeRef.current, element)).catch(() => {});+ };+ const themeObserver = new MutationObserver(update);+ themeObserver.observe(document.documentElement, {+ attributes: true,+ attributeFilter: ['class', 'style'],+ });+ const sizeObserver = new ResizeObserver(update);+ sizeObserver.observe(element);+ return () => {+ disposed = true;+ controllerRef.current = undefined;+ // Notify before hiding the frame; close() retains the View until the+ // teardown response arrives or the bounded wait expires.+ controller.prepareNativeClose();+ themeObserver.disconnect();+ sizeObserver.disconnect();+ // Atomic move preserves the Chromium frame during its bounded teardown handshake.+ if (frame) {+ frame.style.cssText =+ 'position:fixed;width:1px;height:1px;visibility:hidden;pointer-events:none';+ const body = document.body as HTMLElement & {+ moveBefore?: (node: Node, child: Node | null) => void;+ };+ if (body.moveBefore) body.moveBefore(frame, null);+ else controller.prepareNativeClose();+ }+ void controller+ .close()+ .catch(() => {})+ .finally(() => {+ frame?.remove();+ window.removeEventListener('message', receive);+ });+ };+ }, [sessionId, clientId, attempt, appTitle, visible, deviceId]);++ useEffect(() => {+ if (root.current)+ void controllerRef.current?.context(hostContext(locale, root.current)).catch(() => {});+ }, [locale]);+ useLayoutEffect(() => {+ if (mode !== 'fullscreen') return;+ const dialog = card.current;+ if (!dialog) return;+ const previousFocus = document.activeElement as HTMLElement | null;+ // The same native dialog stays mounted inline and fullscreen. Its modal+ // top layer supplies inert background and cross-frame Tab containment+ // without moving or remounting the live, cross-origin App document.+ dialog.close();+ dialog.showModal();+ dialog.querySelector<HTMLButtonElement>('button[data-exit-fullscreen]')?.focus();+ return () => {+ dialog.close();+ dialog.setAttribute('open', '');+ if (previousFocus?.isConnected) previousFocus.focus();+ };+ }, [mode]);+ return (+ <dialog+ ref={card}+ open+ className={+ mode === 'fullscreen'+ ? 'fixed inset-4 z-50 m-0 flex h-auto max-h-none w-auto max-w-none flex-col rounded-xl border border-border bg-[var(--surface-elevated)] p-3 text-inherit backdrop:bg-transparent'+ : `static mx-0 my-3 w-full max-w-none overflow-hidden rounded-xl bg-transparent p-0 text-inherit ${border ? 'border border-border' : 'border-0'}`+ }+ role={mode === 'fullscreen' ? 'dialog' : 'region'}+ aria-modal={mode === 'fullscreen' ? true : undefined}+ aria-label={appTitle}+ onCancel={(event) => {+ event.preventDefault();+ void controllerRef.current?.displayMode('inline').catch(() => {});+ }}+ >+ <div className="flex min-h-9 items-center justify-between gap-3 px-3 text-13 text-[var(--text-secondary)]">+ <span>{title ? t('mcpApps.cardTitle', { title }) : appTitle}</span>+ {loading && visible && <Spinner size="sm" />}+ {mode === 'fullscreen' && (+ <Button+ data-exit-fullscreen+ variant="secondary"+ size="sm"+ onClick={() => {+ void controllerRef.current?.displayMode('inline').catch(() => {});+ }}+ >+ {t('mcpApps.exitFullscreen')}+ </Button>+ )}+ {error && (+ <Button variant="secondary" size="sm" onClick={() => setAttempt((value) => value + 1)}>+ {t('mcpApps.retry')}+ </Button>+ )}+ </div>+ {error && (+ <p role="alert" className="px-3 pb-3 text-13 text-[var(--text-secondary)]">+ {t(error)}+ </p>+ )}+ {error && fallbackText && (+ <p className="whitespace-pre-wrap break-words px-3 pb-3 text-14 text-[var(--text-primary)]">+ {fallbackText}+ </p>+ )}+ <div+ ref={root}+ style={{+ height: error ? 0 : mode === 'fullscreen' ? undefined : height,+ flex: mode === 'fullscreen' ? 1 : undefined,+ }}+ />+ </dialog>+ );+}diff --git a/apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx b/apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsxindex 108de4fce0..edee9c2fde 100644--- a/apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx@@ -27,7 +27,12 @@ import {import { SHARE_SOURCE_ATTR } from '@/lib/shareConversationImage';import { toast } from '@/lib/toast';import { cn } from '@/lib/utils';-import type { MessageSourceDevice, MessageSourcePlugin, MessageSourceGroup } from '@cindy/maker-shared/message-source';+import {+ messageSourceIdEntries,+ type MessageSourceDevice,+ type MessageSourcePlugin,+ type MessageSourceGroup,+} from '@cindy/maker-shared/message-source';import { AutomationOriginBadge, MessageSourceLabelShell } from './AutomationOriginBadge';@@ -126,19 +131,24 @@ export function MessageSourcePluginBadge({const navigate = useNavigate();const navigationMode = useSessionNavigationMode();const remote = Boolean(getStickySessionDeviceId(hostSessionId));- const interactive = navigationMode !== 'sidebar-embedded' && !remote;+ const isApp = plugin.pluginId.startsWith('mcp-app:');+ const interactive = navigationMode !== 'sidebar-embedded' && !remote && !isApp;return (<MessageSourceLabelShellkind="plugin"icon={<Puzzle size={11} strokeWidth={1.75} aria-hidden className="shrink-0" />}label={- plugin.name- ? t('chat.userMessage.pluginSentNamed', { name: plugin.name })- : t('chat.userMessage.pluginSent')+ isApp+ ? t('mcpApps.messageSource', { name: plugin.name ?? plugin.pluginId.slice(8) })+ : plugin.name+ ? t('chat.userMessage.pluginSentNamed', { name: plugin.name })+ : t('chat.userMessage.pluginSent')}tooltip={joinSourceTooltip([interactive && t('chat.userMessage.pluginViewDetail'),- t('chat.userMessage.sourceIds.plugin', { id: plugin.pluginId }),+ ...messageSourceIdEntries({ sourcePlugin: plugin }).map(({ kind, id }) =>+ t(`chat.userMessage.sourceIds.${kind}`, { id }),+ ),])}onOpen={interactive ? () => navigate(`/plugins?ghost=${encodeURIComponent(plugin.pluginId)}`) : nulldiff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex 34233249b7..a326c6c392 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -326,6 +326,7 @@ import { ErrorMessageCard } from './ErrorMessageCard';import { APP_EXIT_INTERRUPTED_REASON } from '../../../shared/interruptedTurn';import { PlanReviewBubble } from './PlanReviewBubble';import { ToolCallCard, getToolSummary } from './ToolCallCard';+import { McpAppCard } from './McpAppCard';import { InlinePlanCard } from './TodoListCard';import { SystemCard } from './SystemCard';import { NewMessageIndicator } from './NewMessageIndicator';@@ -6868,6 +6869,13 @@ const MessageItem = memo(function MessageItem({/>);case 'assistant':+ if (message.systemCardType === 'mcp-app') {+ return sessionId ? (+ <McpAppCard sessionId={sessionId} clientId={message.clientId}+ title={String(message.systemCardData?.title ?? '')}+ fallbackText={String(message.systemCardData?.fallbackText ?? '')} />+ ) : null;+ }if (message.systemCardType) {const card = (<SystemCarddiff --git a/apps/desktop/src/renderer/components/chat/SystemCard.tsx b/apps/desktop/src/renderer/components/chat/SystemCard.tsxindex 0071b479f5..d789b86c30 100644--- a/apps/desktop/src/renderer/components/chat/SystemCard.tsx+++ b/apps/desktop/src/renderer/components/chat/SystemCard.tsx@@ -57,6 +57,7 @@ import { getSessionDeviceId } from '@/features/device-link/remoteProjectsStore';interface SystemCardProps {cardType:+ | 'mcp-app'| 'input-handoff'| 'cindy-make-doctor'| 'cindy-make'diff --git a/apps/desktop/src/renderer/components/chat/__tests__/McpAppCard.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/McpAppCard.test.tsxnew file mode 100644index 0000000000..7ad9f7c596--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/__tests__/McpAppCard.test.tsx@@ -0,0 +1,278 @@+// @vitest-environment jsdom+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, expect, it, vi } from 'vitest';+import { sharedTaskHostPeer } from '@cindy/device-link';+const state = vi.hoisted(() => ({+ deviceId: undefined as string | undefined,+ openError: undefined as Error | undefined,+ originListeners: new Set<() => void>(),+ controllers: [] as Array<{+ open: ReturnType<typeof vi.fn>;+ close: ReturnType<typeof vi.fn>;+ displayMode: ReturnType<typeof vi.fn>;+ message: (message: { method: string; params?: Record<string, unknown> }) => void;+ fail: (error: unknown) => void;+ invoke: (session: string, input: Record<string, unknown>) => Promise<unknown>;+ }>,+ intersections: new Map<Element, (entries: Array<{ isIntersecting: boolean }>) => void>(),+}));+vi.mock('react-i18next', () => ({ useTranslation: () => ({+ t: (key: string, values?: { title: string }) => key === 'mcpApps.cardTitle' ? values?.title : key,+ i18n: { language: 'en' },+}) }));+vi.mock('@/features/device-link/stickySessionOrigin', () => ({ getStickySessionDeviceId: () => state.deviceId }));+vi.mock('@/features/device-link/remoteProjectsStore', () => ({ remoteProjectsStore: {+ subscribe: (listener: () => void) => {+ state.originListeners.add(listener);+ return () => { state.originListeners.delete(listener); };+ },+} }));+vi.mock('@/components/ui/button', () => ({+ Button: ({ children, ...props }: React.ComponentProps<'button'>) => (+ <button {...props}>{children}</button>+ ),+}));+vi.mock('@/components/ui/spinner', () => ({ Spinner: () => null }));+vi.mock('@cindy/maker-shared/mcp-app-controller', () => ({+ mcpAppFailureKey: () => 'mcpApps.loadFailed',+ McpAppController: class {+ open = vi.fn(async () => {+ if (state.openError) throw state.openError;+ return { viewId: `view-${state.controllers.length}`, prefersBorder: true };+ });+ close = vi.fn(async () => {});+ context = vi.fn(async () => {});+ prepareNativeClose = vi.fn();+ displayMode = vi.fn(async (displayMode: string) => {+ this.message({ method: 'ui/notifications/host-context-changed', params: { displayMode } });+ });+ constructor(+ readonly invoke: (session: string, input: Record<string, unknown>) => Promise<unknown>,+ _session: string,+ _client: string,+ _post: unknown,+ readonly message: (message: { method: string; params?: Record<string, unknown> }) => void,+ readonly fail: (error: unknown) => void,+ ) { state.controllers.push(this); }+ },+}));+import { McpAppCard } from '../McpAppCard';+afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ state.controllers = [];+ state.intersections.clear();+ state.deviceId = undefined;+ state.openError = undefined;+ state.originListeners.clear();+});+it('reopens when device ownership is restored but ignores unchanged ownership', async () => {+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);+ vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible');+ vi.stubGlobal('matchMedia', () => ({ matches: false }));+ vi.stubGlobal('IntersectionObserver', class {+ constructor(private callback: (entries: Array<{ isIntersecting: boolean }>) => void) {}+ observe(element: Element) { state.intersections.set(element, this.callback); }+ disconnect() {}+ });+ vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });+ const invoke = vi.fn(async () => ({}));+ vi.stubGlobal('electronAPI', { maker: { mcpApps: invoke } });+ const container = document.createElement('div');+ document.body.appendChild(container);+ const root = createRoot(container);+ try {+ await act(async () => root.render(<McpAppCard sessionId="task" clientId="card" title="App" />));+ await act(async () => [...state.intersections.values()][0]([{ isIntersecting: true }]));+ const original = state.controllers[0];+ await act(async () => original.fail(new Error('MCP_APP_CARD_UNAVAILABLE')));+ await act(async () => {+ state.deviceId = 'restored-device';+ state.originListeners.forEach((listener) => listener());+ });+ expect(original.close).toHaveBeenCalledOnce();+ expect(state.controllers).toHaveLength(2);+ expect(container.querySelector('[role="alert"]')).toBeNull();+ await state.controllers[1].invoke('task', { op: 'open', clientId: 'card' });+ expect(invoke).toHaveBeenLastCalledWith('task', { op: 'open', clientId: 'card', deviceId: 'restored-device' });+ await act(async () => state.originListeners.forEach((listener) => listener()));+ expect(state.controllers).toHaveLength(2);+ } finally {+ await act(async () => root.unmount());+ container.remove();+ }+});+it.each([undefined, 'owner-device'])('releases offscreen history and opens visible owner cards on %s', async (deviceId) => {+ state.deviceId = deviceId;+ const invoke = vi.fn(async () => ({}));+ const generalInvoke = vi.fn();+ vi.stubGlobal('electronAPI', { maker: { mcpApps: invoke }, deviceLink: { invoke: generalInvoke } });+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);+ vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible');+ vi.stubGlobal('matchMedia', () => ({ matches: false }));+ vi.stubGlobal('IntersectionObserver', class {+ constructor(private callback: (entries: Array<{ isIntersecting: boolean }>) => void) {}+ observe(element: Element) { state.intersections.set(element, this.callback); }+ disconnect() {}+ });+ vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });+ const container = document.createElement('div');+ document.body.appendChild(container);+ const root = createRoot(container);+ try {+ await act(async () => root.render(<>{Array.from({ length: 17 }, (_, i) =>+ <McpAppCard key={i} sessionId="task" clientId={`card-${i}`} title={`App ${i}`} />)}</>));+ expect(state.controllers).toHaveLength(0);+ const callbacks = [...state.intersections.values()];+ for (let i = 0; i < callbacks.length; i++) {+ await act(async () => {+ if (i) callbacks[i - 1]([{ isIntersecting: false }]);+ callbacks[i]([{ isIntersecting: true }]);+ });+ expect(state.controllers).toHaveLength(i + 1);+ expect(state.controllers.filter((controller) => controller.close.mock.calls.length === 0)).toHaveLength(1);+ expect(container.querySelectorAll('iframe')).toHaveLength(1);+ await state.controllers[i].invoke('task', { op: 'open', clientId: `card-${i}` });+ expect(invoke).toHaveBeenLastCalledWith('task', deviceId+ ? { op: 'open', clientId: `card-${i}`, deviceId } : { op: 'open', clientId: `card-${i}` });+ expect(generalInvoke).not.toHaveBeenCalled();+ }+ } finally {+ await act(async () => root.unmount());+ container.remove();+ }+ expect(state.controllers.every((controller) => controller.close.mock.calls.length === 1)).toBe(true);+});++it.each(['light', 'dark'])('shows saved text without mounting an interactive guest View in %s mode', async (mode) => {+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);+ document.documentElement.classList.toggle('dark', mode === 'dark');+ state.deviceId = sharedTaskHostPeer('shared-task', 'host-device');+ const invoke = vi.fn();+ vi.stubGlobal('electronAPI', { maker: { mcpApps: invoke }, deviceLink: { invoke } });+ const container = document.createElement('div');+ const root = createRoot(container);+ try {+ await act(async () => root.render(<McpAppCard sessionId="task" clientId="card" title="Saved form"+ fallbackText="Saved result <script>window.attack=true</script>" />));+ expect(container.textContent).toContain('Saved form');+ expect(container.textContent).toContain('Saved result <script>window.attack=true</script>');+ expect(container.textContent).toContain('mcpApps.sharedTaskReadOnly');+ expect(container.textContent).not.toContain('mcpApps.loadFailed');+ expect(container.querySelector('iframe, button, script')).toBeNull();+ expect(state.controllers).toHaveLength(0);+ expect(state.intersections.size).toBe(0);+ expect(invoke).not.toHaveBeenCalled();+ await act(async () => root.render(<McpAppCard sessionId="task" clientId="pending" title="Pending form" />));+ expect(container.textContent).toContain('Pending form');+ expect(container.textContent).toContain('mcpApps.sharedTaskReadOnly');+ } finally {+ await act(async () => root.unmount());+ document.documentElement.classList.remove('dark');+ }+});++it.each(['light', 'dark'])('keeps saved text readable after App failures and retry in %s mode', async (mode) => {+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);+ document.documentElement.classList.toggle('dark', mode === 'dark');+ vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible');+ vi.stubGlobal('matchMedia', () => ({ matches: false }));+ vi.stubGlobal('IntersectionObserver', class {+ constructor(private callback: (entries: Array<{ isIntersecting: boolean }>) => void) {}+ observe(element: Element) { state.intersections.set(element, this.callback); }+ disconnect() {}+ });+ vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });+ state.openError = new Error('MCP_APP_SERVER_CHANGED');+ const saved = 'Saved result\n<script>window.attack=true</script>';+ const container = document.createElement('div');+ document.body.appendChild(container);+ const root = createRoot(container);+ try {+ await act(async () => root.render(+ <McpAppCard sessionId="task" clientId="card" title="Saved form" fallbackText={saved} />,+ ));+ const [observed, intersect] = [...state.intersections.entries()][0];+ await act(async () => intersect([{ isIntersecting: true }]));+ expect(container.textContent).toContain(saved);+ expect(container.querySelector('[role="alert"]')?.textContent).toBe('mcpApps.loadFailed');+ expect(container.querySelector('iframe, script')).toBeNull();+ // Retry must remain observable even after the empty iframe area collapses.+ expect(observed).toBe(container.querySelector('dialog'));+ state.openError = undefined;+ await act(async () => container.querySelector('button')!.click());+ expect(container.textContent).not.toContain(saved);+ expect(container.querySelector('iframe')).not.toBeNull();+ expect(state.controllers).toHaveLength(2);+ await act(async () => state.controllers[1].fail(new Error('offline')));+ expect(container.textContent).toContain(saved);+ expect(container.querySelector('iframe, script')).toBeNull();+ } finally {+ await act(async () => root.unmount());+ container.remove();+ document.documentElement.classList.remove('dark');+ }+});++it.each(['light', 'dark'])('keeps the live App mounted while entering and leaving the native fullscreen modal in %s mode', async (mode) => {+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);+ document.documentElement.classList.toggle('dark', mode === 'dark');+ vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible');+ vi.stubGlobal('matchMedia', () => ({ matches: false }));+ vi.stubGlobal('IntersectionObserver', class {+ constructor(private callback: (entries: Array<{ isIntersecting: boolean }>) => void) {}+ observe(element: Element) { state.intersections.set(element, this.callback); }+ disconnect() {}+ });+ vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });+ const container = document.createElement('div');+ document.body.appendChild(container);+ const root = createRoot(container);+ try {+ await act(async () => root.render(<><button>Opener</button>+ <McpAppCard sessionId="task" clientId="card" title="Live form" /></>));+ await act(async () => [...state.intersections.values()][0]([{ isIntersecting: true }]));+ const opener = container.querySelector('button')!;+ opener.focus();+ const dialog = container.querySelector('dialog')!;+ const frame = dialog.querySelector('iframe')!;+ const appWindow = frame.contentWindow;+ // JSDOM has no native modal/top-layer implementation; this suite covers+ // the retained document and controller lifecycle, not browser Tab traversal.+ const close = vi.fn(() => dialog.removeAttribute('open'));+ const showModal = vi.fn(() => dialog.setAttribute('open', ''));+ Object.defineProperties(dialog, { close: { value: close }, showModal: { value: showModal } });+ await act(async () => state.controllers[0].message({+ method: 'ui/notifications/host-context-changed', params: { displayMode: 'fullscreen' },+ }));+ expect(dialog.getAttribute('role')).toBe('dialog');+ expect(dialog.getAttribute('aria-modal')).toBe('true');+ expect(dialog.getAttribute('aria-label')).toBe('Live form');+ expect(showModal).toHaveBeenCalledOnce();+ expect(document.activeElement).toBe(dialog.querySelector('[data-exit-fullscreen]'));+ const cancel = new Event('cancel', { cancelable: true });+ await act(async () => { dialog.dispatchEvent(cancel); });+ expect(cancel.defaultPrevented).toBe(true);+ expect(state.controllers[0].displayMode).toHaveBeenCalledWith('inline');+ expect(dialog.getAttribute('role')).toBe('region');+ expect(dialog.hasAttribute('aria-modal')).toBe(false);+ expect(document.activeElement).toBe(opener);+ expect(dialog.querySelector('iframe')).toBe(frame);+ expect(frame.contentWindow).toBe(appWindow);+ expect(state.controllers).toHaveLength(1);+ expect(state.controllers[0].close).not.toHaveBeenCalled();+ await act(async () => state.controllers[0].message({+ method: 'ui/notifications/host-context-changed', params: { displayMode: 'fullscreen' },+ }));+ await act(async () => state.controllers[0].fail(new Error('offline')));+ expect(document.activeElement).toBe(opener);+ expect(dialog.getAttribute('aria-modal')).toBeNull();+ expect(dialog.querySelector('iframe')).toBeNull();+ expect(close).toHaveBeenCalled();+ } finally {+ await act(async () => root.unmount());+ container.remove();+ document.documentElement.classList.remove('dark');+ }+});diff --git a/apps/desktop/src/renderer/components/chat/__tests__/MessageSourceLabels.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/MessageSourceLabels.test.tsxindex e3d589a496..36a2988ffa 100644--- a/apps/desktop/src/renderer/components/chat/__tests__/MessageSourceLabels.test.tsx+++ b/apps/desktop/src/renderer/components/chat/__tests__/MessageSourceLabels.test.tsx@@ -122,6 +122,20 @@ describe('MessageSourceLabels device label', () => {});describe('MessageSourceLabels plugin and row', () => {+ it.each([['Reports', 'Reports'], [undefined, 'reports']])(+ 'identifies MCP Apps by server name or ID without opening plugin details (%s)',+ (name, expectedLabel) => {+ render(<MessageSourceLabels sourcePlugin={{ pluginId: 'mcp-app:reports', name }} />);+ const label = screen.getByText(`mcpApps.messageSource:${expectedLabel}`);+ expect(label.closest('[title]')?.getAttribute('title')).toBe(+ 'chat.userMessage.sourceIds.mcpApp:reports',+ );+ expect(screen.queryByRole('button')).toBeNull();+ fireEvent.click(label);+ expect(mocks.navigate).not.toHaveBeenCalled();+ },+ );+it('labels plugin messages and opens the plugin detail', () => {render(<MessageSourceLabels sourcePlugin={{ pluginId: 'ghost.notes', name: 'Notes' }} />);const button = screen.getByRole('button');diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex a36d9a112f..089fc21918 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -11445,6 +11445,7 @@"pluginSent": "Sent by plugin","pluginViewDetail": "View plugin","sourceIds": {+ "mcpApp": "$t(mcpApps.serverId)","session": "Session ID: {{id}}","teammate": "Teammate ID: {{id}}","automation": "Automation ID: {{id}}",@@ -16271,5 +16272,16 @@"offerExpired": "The account or reset offer changed. Refresh usage before resetting.","resetFailed": "Could not confirm the reset result. Refresh usage to check whether limits were restored.","limitAction": "Use Reset · {{count}} Available"+ },+ "mcpApps": {+ "sharedTaskReadOnly": "Only the session owner can interact with this card.",+ "retry": "Reload",+ "loadFailed": "The app could not load. Check the connection and reload.",+ "updateRequired": "This computer does not support MCP Apps yet. Update Cindy on that computer and try again.",+ "appName": "MCP App",+ "cardTitle": "{{title}} · $t(mcpApps.appName)",+ "messageSource": "Sent by $t(mcpApps.appName) “{{name}}”",+ "serverId": "MCP Server ID: {{id}}",+ "exitFullscreen": "Exit Fullscreen"}}diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 69b8627cf8..161e267cdb 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -11400,6 +11400,7 @@"pluginSent": "プラグインから送信","pluginViewDetail": "プラグインを表示","sourceIds": {+ "mcpApp": "$t(mcpApps.serverId)","session": "セッション ID:{{id}}","teammate": "仲間 ID:{{id}}","automation": "自動化 ID:{{id}}",@@ -16211,5 +16212,16 @@"offerExpired": "アカウントまたはリセットの状態が変わりました。使用量を更新してからリセットを使用してください。","resetFailed": "リセットの結果を確認できませんでした。使用量を更新して、利用枠が回復したか確認してください。","limitAction": "リセットを使用 · 残り {{count}} 回"+ },+ "mcpApps": {+ "sharedTaskReadOnly": "このカードを操作できるのはセッションのオーナーだけです。",+ "retry": "再読み込み",+ "loadFailed": "アプリを読み込めませんでした。接続を確認して再読み込みしてください。",+ "updateRequired": "このコンピューターはまだ MCP Apps に対応していません。このコンピューターの Cindy を更新してから、もう一度お試しください。",+ "appName": "MCP App",+ "cardTitle": "{{title}} · $t(mcpApps.appName)",+ "messageSource": "$t(mcpApps.appName)「{{name}}」から送信",+ "serverId": "MCP サーバー ID:{{id}}",+ "exitFullscreen": "全画面表示を終了"}}diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 8c983540f4..2d95708ed3 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -11400,6 +11400,7 @@"pluginSent": "플러그인에서 보냄","pluginViewDetail": "플러그인 보기","sourceIds": {+ "mcpApp": "$t(mcpApps.serverId)","session": "세션 ID: {{id}}","teammate": "동료 ID: {{id}}","automation": "자동화 ID: {{id}}",@@ -16211,5 +16212,16 @@"offerExpired": "계정 또는 초기화 상태가 변경되었습니다. 사용량을 새로고침한 후 초기화를 사용하세요.","resetFailed": "초기화 결과를 확인할 수 없습니다. 사용량을 새로고침하여 한도가 복구되었는지 확인하세요.","limitAction": "초기화 사용 · {{count}}회 남음"+ },+ "mcpApps": {+ "sharedTaskReadOnly": "이 카드는 세션 소유자만 조작할 수 있습니다.",+ "retry": "다시 불러오기",+ "loadFailed": "앱을 불러오지 못했습니다. 연결을 확인한 후 다시 불러오세요.",+ "updateRequired": "이 컴퓨터는 아직 MCP Apps를 지원하지 않습니다. 해당 컴퓨터의 Cindy를 업데이트한 후 다시 시도하세요.",+ "appName": "MCP App",+ "cardTitle": "{{title}} · $t(mcpApps.appName)",+ "messageSource": "$t(mcpApps.appName) “{{name}}”에서 전송",+ "serverId": "MCP 서버 ID: {{id}}",+ "exitFullscreen": "전체 화면 종료"}}diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 0cca62f208..85aa41eeed 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -11400,6 +11400,7 @@"pluginSent": "由插件发送","pluginViewDetail": "查看插件","sourceIds": {+ "mcpApp": "$t(mcpApps.serverId)","session": "任务 ID:{{id}}","teammate": "伙伴 ID:{{id}}","automation": "自动化 ID:{{id}}",@@ -16211,5 +16212,16 @@"offerExpired": "账号或重置状态已变化,请刷新用量后再使用重置","resetFailed": "无法确认重置结果,请刷新用量查看额度是否已恢复","limitAction": "使用重置 · 剩余 {{count}} 次"+ },+ "mcpApps": {+ "sharedTaskReadOnly": "此卡片仅任务主人可操作。",+ "retry": "重新加载",+ "loadFailed": "应用加载失败。请检查连接后重新加载。",+ "updateRequired": "这台电脑暂不支持 MCP Apps,请更新电脑上的 Cindy 后再试。",+ "appName": "MCP App",+ "cardTitle": "{{title}} · $t(mcpApps.appName)",+ "messageSource": "由 $t(mcpApps.appName)「{{name}}」发送",+ "serverId": "MCP 服务器 ID:{{id}}",+ "exitFullscreen": "退出全屏"}}diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 14a4f07747..35cdc53f4f 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -11399,6 +11399,7 @@"pluginSent": "由插件傳送","pluginViewDetail": "檢視插件","sourceIds": {+ "mcpApp": "$t(mcpApps.serverId)","session": "任務 ID:{{id}}","teammate": "夥伴 ID:{{id}}","automation": "自動化 ID:{{id}}",@@ -16211,5 +16212,16 @@"offerExpired": "帳號或重置狀態已變更,請重新整理用量後再使用重置","resetFailed": "無法確認重置結果,請重新整理用量查看額度是否已恢復","limitAction": "使用重置 · 剩餘 {{count}} 次"+ },+ "mcpApps": {+ "sharedTaskReadOnly": "此卡片僅任務擁有者可操作。",+ "retry": "重新載入",+ "loadFailed": "應用程式載入失敗。請檢查連線後重新載入。",+ "updateRequired": "這台電腦尚不支援 MCP Apps,請更新電腦上的 Cindy 後再試。",+ "appName": "MCP App",+ "cardTitle": "{{title}} · $t(mcpApps.appName)",+ "messageSource": "由 $t(mcpApps.appName)「{{name}}」傳送",+ "serverId": "MCP 伺服器 ID:{{id}}",+ "exitFullscreen": "離開全螢幕"}}diff --git a/apps/desktop/src/renderer/lib/ccAgent.types.ts b/apps/desktop/src/renderer/lib/ccAgent.types.tsindex f4e2b9c208..1cd3672f65 100644--- a/apps/desktop/src/renderer/lib/ccAgent.types.ts+++ b/apps/desktop/src/renderer/lib/ccAgent.types.ts@@ -100,6 +100,8 @@ export type StoredMessageOrigin =* 只接受 SDK 自己分配的 uuid,所以这是 fork 的唯一主键。*/export interface CcMeta {+ /** Host-authored official MCP App snapshot; not an assistant prose reply. */+ mcpApp?: boolean;botLearning?: import('@cindy/maker-shared/bot-learning').BotLearningReceipt[];/** Provider text phase, retained to exclude commentary from notification previews. */assistantPhase?: string;diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 604b9b493a..c7888c3530 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -129,6 +129,7 @@ import type {GhostSetupStepPhase,} from '../../shared/ghost';import * as messageService from '@/lib/messageService';+import { parseMcpAppHistory } from '@cindy/maker-shared/mcp-apps';import * as sessionService from '@/lib/sessionService';// device-link 透明传输:远程(被控设备)会话的操作/读取走隧道,本地会话零变化。import {@@ -574,7 +575,9 @@ export interface ChatMessage {| 'bot-authorization'/** 代输入结束留痕:由隐藏续接行派生,只有步数、设备与域名,没有任何输入值。 */| 'input-handoff'- | 'context-rebuild';+ | 'context-rebuild'+ | 'mcp-app';+ mcpAppClientId?: string;systemCardData?: Record<string, unknown>;/** FP-3: plan_review message fields */planReviewStatus?: 'pending' | 'approved' | 'revised' | 'expired' | 'cancelled';@@ -18514,6 +18517,13 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {const ordered = filtered.sort(compareMessageTimeline);const legacyUserTurnCosts = projectLegacyUserTurnCosts(ordered);const mapped = ordered.map((m) => {+ const mcpApp = m.role === 'assistant' && m.agentMeta?.mcpApp === true ? parseMcpAppHistory(m.content) : undefined;+ if (mcpApp) return {+ clientId: m.clientId, role: 'assistant' as const, content: '', isStreaming: false,+ systemCardType: 'mcp-app' as const,+ systemCardData: { title: mcpApp.title, fallbackText: mcpApp.text },+ mcpAppClientId: m.clientId,+ };const persistedCindyCard =m.role === 'assistant' && m.content && typeof m.content === 'object'? (m.content as Record<string, unknown>)[CINDY_MAKE_CARD_MARKER]diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 5c868d37a7..3ba6590014 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -5619,6 +5619,7 @@ interface ElectronAPI {/** 自定义供应商变更广播订阅(返回 off)。 */onProvidersChanged: (cb: () => void) => () => void;+ mcpApps: (sessionId: string, input: unknown) => Promise<unknown>;// 自定义 MCP 服务器配置 CRUD(可选 bearer token 另走通用 safeStorage IPC,不经这里)。listCustomMcpServers: (context?: import('../shared/customMcp').CustomMcpListContext,diff --git a/apps/desktop/src/shared/mcpApps.ts b/apps/desktop/src/shared/mcpApps.tsnew file mode 100644index 0000000000..8574b0f1fc--- /dev/null+++ b/apps/desktop/src/shared/mcpApps.ts@@ -0,0 +1 @@+export * from '@cindy/maker-shared/mcp-apps';diff --git a/apps/desktop/src/shared/providerSecrets.ts b/apps/desktop/src/shared/providerSecrets.tsindex 9d97b0541d..557066a2a9 100644--- a/apps/desktop/src/shared/providerSecrets.ts+++ b/apps/desktop/src/shared/providerSecrets.ts@@ -85,12 +85,16 @@ export const REMOTE_MCP_BRIDGE_TOKEN_STORAGE_KEY = 'remote_mcp_bridge_token';*/export const PI_PROXY_DERIVATION_KEY_STORAGE_KEY = 'pi_proxy_derivation_key';+/** Host-only key for persisted MCP App configuration revisions, never synced. */+export const MCP_APP_REVISION_KEY_STORAGE_KEY = 'mcp_app_revision_key';+const MAIN_ONLY_PROVIDER_SECRET_STORAGE_KEYS = new Set<string>([STORAGE_KEYS['voice-asr'].toLowerCase(),STORAGE_KEYS['gemini'].toLowerCase(),STORAGE_KEYS['openai-images'].toLowerCase(),REMOTE_MCP_BRIDGE_TOKEN_STORAGE_KEY.toLowerCase(),PI_PROXY_DERIVATION_KEY_STORAGE_KEY.toLowerCase(),+ MCP_APP_REVISION_KEY_STORAGE_KEY.toLowerCase(),]);/** Custom-provider runtime header blobs are main-only credential material. */diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsxindex 2c66401a79..59d62738e7 100644--- a/apps/mobile/app/_layout.tsx+++ b/apps/mobile/app/_layout.tsx@@ -2,6 +2,7 @@ import { completePrecreatedWorktreeRecovery } from '@/session/completePrecreatedimport { recentTaskKey } from '@/session/recentTasks';import { readComposerEntry } from '@/session/composerMorph';import { RecentMessageHistoriesProvider } from '@/session/RecentMessageHistories';+import { McpAppViewsProvider } from '@/session/McpAppViews';import { ResidentHomeListProvider } from '@/session/ResidentHomeList';import { AndroidUpdateSheet } from '@/update/AndroidUpdateSheet';import { PeerFileTransport } from '@/device-link/peerFileTransport';@@ -170,6 +171,7 @@ function NavigationGate() {/>) : null}<RemoteDesktopHost>+ <McpAppViewsProvider><RecentMessageHistoriesProvider key={auth.accountGeneration}><ResidentHomeListProvider><Stack@@ -208,6 +210,7 @@ function NavigationGate() {</Stack></ResidentHomeListProvider></RecentMessageHistoriesProvider>+ </McpAppViewsProvider></RemoteDesktopHost></NavigationThemeProvider>);diff --git a/apps/mobile/modules/cindy-html-preview/android/src/main/java/expo/modules/cindyhtmlpreview/CindyHtmlPreviewModule.kt b/apps/mobile/modules/cindy-html-preview/android/src/main/java/expo/modules/cindyhtmlpreview/CindyHtmlPreviewModule.ktindex 63450d4e35..0b75474b59 100644--- a/apps/mobile/modules/cindy-html-preview/android/src/main/java/expo/modules/cindyhtmlpreview/CindyHtmlPreviewModule.kt+++ b/apps/mobile/modules/cindy-html-preview/android/src/main/java/expo/modules/cindyhtmlpreview/CindyHtmlPreviewModule.kt@@ -3,13 +3,73 @@ package expo.modules.cindyhtmlpreviewimport expo.modules.kotlin.modules.Moduleimport expo.modules.kotlin.modules.ModuleDefinitionimport java.io.File+import android.os.Handler+import android.os.Looper+import android.view.View+import android.webkit.CookieManager+import expo.modules.kotlin.Promiseclass CindyHtmlPreviewModule : Module() {private val servers = mutableMapOf<String, HtmlSnapshotServer>()+ private val appServers = mutableMapOf<String, HtmlSnapshotServer>()+ // A retiring WebView can still be detaching after JS stops its HTTP server.+ // Never assign its origin to another App in this process. Across process+ // restarts the trusted storage bootstrap clears that origin before App HTML.+ private companion object {+ val issuedAppOrigins = mutableSetOf<String>()+ }+ private val handler = Handler(Looper.getMainLooper())private var foreground = trueoverride fun definition() = ModuleDefinition {Name("CindyHtmlPreview")Events("resourceRequest", "resourceClosed")+ Constant("appHostAvailable") { true }+ View(HtmlAppHost::class) {+ Name("AppHost")+ Prop("surfaceId") { view: HtmlAppHost, id: String -> view.surfaceId = id }+ GroupView<HtmlAppHost> {+ AddChildView { parent: HtmlAppHost, child: View, index: Int ->+ parent.content.addView(child, index, android.widget.FrameLayout.LayoutParams(-1, -1))+ HtmlAppSurfaces.attach(parent.surfaceId)+ }+ GetChildCount { parent: HtmlAppHost -> parent.content.childCount }+ GetChildViewAt { parent: HtmlAppHost, index: Int -> parent.content.getChildAt(index) }+ RemoveChildViewAt { parent: HtmlAppHost, index: Int -> parent.content.removeViewAt(index) }+ RemoveChildView { parent: HtmlAppHost, child: View -> parent.content.removeView(child) }+ }+ }+ View(HtmlAppSlot::class) {+ Name("AppSlot")+ Prop("surfaceId") { view: HtmlAppSlot, id: String -> view.surfaceId = id }+ }+ AsyncFunction("startApp") { root: String, entry: String, token: String, csp: String, files: List<List<String>>, promise: Promise ->+ var created: HtmlSnapshotServer? = null+ fun reject(error: Exception) {+ synchronized(servers) {+ if (created != null && appServers[token] === created) stopApp(token)+ }+ promise.reject("HTML_PREVIEW_START_FAILED", "Unable to start App resource", error)+ }+ try {+ val url = synchronized(servers) {+ val cache = File(requireNotNull(appContext.reactContext).cacheDir, "mcp-apps").canonicalPath+ require(File(root).canonicalPath.startsWith(cache + File.separator))+ require(foreground && appServers.size < 16 && !appServers.containsKey(token))+ val server = allocateAppServer(root, entry, token, csp, files)+ created = server+ appServers[token] = server+ server.start()+ }+ handler.post {+ try {+ synchronized(servers) { require(appServers[token] === created) }+ // Storage is cleared by the trusted bootstrap, which can await+ // completion. WebStorage.deleteOrigin has no completion callback.+ promise.resolve(url)+ } catch (error: Exception) { reject(error) }+ }+ } catch (error: Exception) { reject(error) }+ }AsyncFunction("start") { root: String, entry: String, token: String, csp: String, files: List<List<String>> ->synchronized(servers) {val cache = requireNotNull(appContext.reactContext).cacheDir.canonicalPath@@ -35,13 +95,42 @@ class CindyHtmlPreviewModule : Module() {AsyncFunction("resolveRequest") { token: String, id: String, filename: String, mime: String, status: Int ->synchronized(servers) { servers[token]?.resolve(id, filename, mime, status) ?: false }}- AsyncFunction("stop") { token: String -> synchronized(servers) { servers.remove(token)?.stop(); Unit } }- OnActivityEntersBackground { synchronized(servers) { foreground = false; stopAll() } }+ AsyncFunction("stop") { token: String -> synchronized(servers) {+ servers.remove(token)?.stop(); stopApp(token); Unit+ } }+ OnActivityEntersBackground { synchronized(servers) {+ foreground = false+ stopPreviews()+ val tokens = appServers.keys.toList()+ handler.postDelayed({ synchronized(servers) { tokens.forEach { stopApp(it) } } }, 1000)+ } }OnActivityEntersForeground { synchronized(servers) { foreground = true } }OnDestroy { stopAll() }}private fun stopAll() = synchronized(servers) {+ stopPreviews()+ appServers.keys.toList().forEach { stopApp(it) }+ }+ private fun stopPreviews() {servers.values.forEach { it.stop() }servers.clear()}+ private fun stopApp(token: String) {+ val server = appServers.remove(token) ?: return+ val origin = server.origin+ server.stop()+ handler.post {+ try {+ CookieManager.getInstance().setCookie(origin, "cindy_$token=; Max-Age=0; Path=/")+ } catch (_: Exception) {}+ }+ }+ private fun allocateAppServer(root: String, entry: String, token: String, csp: String, files: List<List<String>>): HtmlSnapshotServer {+ repeat(128) {+ val candidate = HtmlSnapshotServer(root, entry, token, csp, files)+ if (synchronized(issuedAppOrigins) { issuedAppOrigins.add(candidate.origin) }) return candidate+ candidate.stop()+ }+ throw IllegalStateException("MCP_APP_ORIGIN_CAPACITY")+ }}diff --git a/apps/mobile/modules/cindy-html-preview/android/src/main/java/expo/modules/cindyhtmlpreview/HtmlAppSurface.kt b/apps/mobile/modules/cindy-html-preview/android/src/main/java/expo/modules/cindyhtmlpreview/HtmlAppSurface.ktnew file mode 100644index 0000000000..0e0690cd06--- /dev/null+++ b/apps/mobile/modules/cindy-html-preview/android/src/main/java/expo/modules/cindyhtmlpreview/HtmlAppSurface.kt@@ -0,0 +1,76 @@+package expo.modules.cindyhtmlpreview++import android.content.Context+import android.view.ViewGroup+import android.view.View.MeasureSpec+import android.widget.FrameLayout+import expo.modules.kotlin.AppContext+import expo.modules.kotlin.views.ExpoView+import java.lang.ref.WeakReference++// Fabric's parent remains AppHost. Moving only a plain native container keeps+// the WebView instance alive when its route-owned slot is removed.+internal object HtmlAppSurfaces {+ val hosts = mutableMapOf<String, WeakReference<HtmlAppHost>>()+ private val slots = mutableListOf<WeakReference<HtmlAppSlot>>()+ fun register(slot: HtmlAppSlot) { slots.add(WeakReference(slot)) }+ fun attach(key: String) {+ slots.removeAll { it.get() == null }+ val host = hosts[key]?.get() ?: return+ val target: ViewGroup = slots.mapNotNull { it.get() }+ .lastOrNull { it.surfaceId == key && it.attached } ?: host+ if (host.content.parent !== target) {+ (host.content.parent as? ViewGroup)?.removeView(host.content)+ target.addView(host.content, ViewGroup.LayoutParams(-1, -1))+ }+ layoutContent(host.content, target.width, target.height)+ }+ fun layoutContent(content: FrameLayout, width: Int, height: Int) {+ content.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),+ MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY))+ content.layout(0, 0, width, height)+ }+}++class HtmlAppHost(context: Context, appContext: AppContext) : ExpoView(context, appContext) {+ val content = FrameLayout(context)+ var surfaceId: String = ""+ set(value) {+ if (field == value) return+ if (HtmlAppSurfaces.hosts[field]?.get() === this) HtmlAppSurfaces.hosts.remove(field)+ field = value+ HtmlAppSurfaces.hosts[value] = WeakReference(this)+ HtmlAppSurfaces.attach(value)+ }+ override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {+ if (content.parent === this) HtmlAppSurfaces.layoutContent(content, width, height)+ }+ override fun onAttachedToWindow() {+ super.onAttachedToWindow()+ HtmlAppSurfaces.hosts[surfaceId] = WeakReference(this)+ HtmlAppSurfaces.attach(surfaceId)+ }+ override fun onDetachedFromWindow() {+ super.onDetachedFromWindow()+ if (HtmlAppSurfaces.hosts[surfaceId]?.get() === this) HtmlAppSurfaces.hosts.remove(surfaceId)+ (content.parent as? ViewGroup)?.removeView(content)+ }+}++class HtmlAppSlot(context: Context, appContext: AppContext) : ExpoView(context, appContext) {+ internal var attached = false+ var surfaceId: String = ""+ set(value) { val previous = field; field = value; HtmlAppSurfaces.attach(previous); HtmlAppSurfaces.attach(value) }+ init { clipChildren = true; HtmlAppSurfaces.register(this) }+ override fun onAttachedToWindow() { super.onAttachedToWindow(); attached = true; HtmlAppSurfaces.attach(surfaceId) }+ override fun onDetachedFromWindow() {+ attached = false+ super.onDetachedFromWindow()+ HtmlAppSurfaces.attach(surfaceId)+ }+ override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {+ for (index in 0 until childCount) {+ (getChildAt(index) as? FrameLayout)?.let { HtmlAppSurfaces.layoutContent(it, width, height) }+ }+ }+}diff --git a/apps/mobile/modules/cindy-html-preview/android/src/main/java/expo/modules/cindyhtmlpreview/HtmlSnapshotServer.kt b/apps/mobile/modules/cindy-html-preview/android/src/main/java/expo/modules/cindyhtmlpreview/HtmlSnapshotServer.ktindex 28f8f60404..66cef50b21 100644--- a/apps/mobile/modules/cindy-html-preview/android/src/main/java/expo/modules/cindyhtmlpreview/HtmlSnapshotServer.kt+++ b/apps/mobile/modules/cindy-html-preview/android/src/main/java/expo/modules/cindyhtmlpreview/HtmlSnapshotServer.kt@@ -30,7 +30,7 @@ internal class HtmlSnapshotServer(root: String, private val entry: String, privaprivate val disconnectWatchers = Executors.newCachedThreadPool()private val listener: ServerSocket@Volatile private var stopped = false- private val origin get() = "http://127.0.0.1:${listener.localPort}"+ val origin get() = "http://127.0.0.1:${listener.localPort}"init {require(Regex("^[a-f0-9]{48}$").matches(token) && !csp.contains('\r') && !csp.contains('\n'))diff --git a/apps/mobile/modules/cindy-html-preview/ios/CindyHtmlPreviewModule.swift b/apps/mobile/modules/cindy-html-preview/ios/CindyHtmlPreviewModule.swiftindex edc2c8847f..439583e928 100644--- a/apps/mobile/modules/cindy-html-preview/ios/CindyHtmlPreviewModule.swift+++ b/apps/mobile/modules/cindy-html-preview/ios/CindyHtmlPreviewModule.swift@@ -2,12 +2,42 @@ import ExpoModulesCorepublic class CindyHtmlPreviewModule: Module {private var servers: [String: HtmlSnapshotServer] = [:]+ private var appServers: [String: HtmlSnapshotServer] = [:]private let queue = DispatchQueue(label: "cindy.html-preview")private var foreground = truepublic func definition() -> ModuleDefinition {Name("CindyHtmlPreview")Events("resourceRequest", "resourceClosed")+ Constant("appHostAvailable") { true }+ View(HtmlAppHost.self) {+ ViewName("AppHost")+ Prop("surfaceId") { (view, id: String) in view.surfaceId = id }+ }+ View(HtmlAppSlot.self) {+ ViewName("AppSlot")+ Prop("surfaceId") { (view, id: String) in view.surfaceId = id }+ }+ // Separate from the four ordinary HTML previews: four live Apps can each+ // use two origins, with a bounded allowance for their retiring Views.+ AsyncFunction("startApp") { (root: String, entry: String, token: String, csp: String, files: [[String]], promise: Promise) in+ do {+ guard self.foreground, self.appServers.count < 16, self.appServers[token] == nil,+ let cache = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first,+ URL(fileURLWithPath: root).resolvingSymlinksInPath().path.hasPrefix(cache.appendingPathComponent("mcp-apps").resolvingSymlinksInPath().path + "/")+ else { throw HtmlSnapshotServer.Failure.invalid }+ let server = try HtmlSnapshotServer(root: root, entry: entry, token: token, csp: csp, files: files, queue: self.queue)+ self.appServers[token] = server+ server.start { result in+ switch result {+ case .success(let url): promise.resolve(url)+ case .failure:+ self.appServers.removeValue(forKey: token)?.stop()+ promise.reject("HTML_PREVIEW_START_FAILED", "Unable to start App resource")+ }+ }+ } catch { promise.reject("HTML_PREVIEW_START_FAILED", "Unable to start App resource") }+ }.runOnQueue(queue)AsyncFunction("start") { (root: String, entry: String, token: String, csp: String, files: [[String]], promise: Promise) indo {guard self.foreground, self.servers.count < 4, self.servers[token] == nil,@@ -49,13 +79,32 @@ public class CindyHtmlPreviewModule: Module {AsyncFunction("resolveRequest") { (token: String, id: String, filename: String, mime: String, status: Int) -> Bool inself.servers[token]?.resolve(id, filename: filename, mime: mime, status: status) ?? false}.runOnQueue(queue)- AsyncFunction("stop") { (token: String) in self.servers.removeValue(forKey: token)?.stop() }.runOnQueue(queue)- OnAppEntersBackground { self.queue.async { self.foreground = false; self.stopAll() } }+ AsyncFunction("stop") { (token: String) in+ self.servers.removeValue(forKey: token)?.stop()+ self.appServers.removeValue(forKey: token)?.stop()+ }.runOnQueue(queue)+ OnAppEntersBackground { self.queue.async {+ self.foreground = false+ self.stopPreviews()+ // Keep only this background generation available for bounded teardown.+ // A quick foreground/reopen must not be stopped by an old timer.+ let tokens = Array(self.appServers.keys)+ self.queue.asyncAfter(deadline: .now() + 1) {+ for token in tokens { self.appServers.removeValue(forKey: token)?.stop() }+ }+ } }OnAppEntersForeground { self.queue.async { self.foreground = true } }OnDestroy { self.queue.async { self.stopAll() } }}private func stopAll() {+ stopPreviews()+ let active = Array(appServers.values)+ appServers.removeAll()+ active.forEach { $0.stop() }+ }++ private func stopPreviews() {let active = Array(servers.values)servers.removeAll()active.forEach { $0.stop() }diff --git a/apps/mobile/modules/cindy-html-preview/ios/HtmlAppSurface.swift b/apps/mobile/modules/cindy-html-preview/ios/HtmlAppSurface.swiftnew file mode 100644index 0000000000..9400ab24d5--- /dev/null+++ b/apps/mobile/modules/cindy-html-preview/ios/HtmlAppSurface.swift@@ -0,0 +1,67 @@+import ExpoModulesCore+import UIKit++// Like ResidentHistoryHost, Fabric owns the React children at a persistent+// host. Only this plain native container moves into the route's inline slot.+private enum HtmlAppSurfaces {+ static let hosts = NSMapTable<NSString, HtmlAppHost>(keyOptions: .strongMemory, valueOptions: .weakMemory)+ static let slots = NSHashTable<HtmlAppSlot>.weakObjects()++ static func attach(_ key: String) {+ guard !key.isEmpty, let host = hosts.object(forKey: key as NSString) else { return }+ let target: UIView = slots.allObjects.last(where: { $0.surfaceId == key && $0.window != nil }) ?? host+ if host.content.superview !== target {+ host.content.removeFromSuperview()+ target.addSubview(host.content)+ }+ host.content.frame = target.bounds+ }+}++final class HtmlAppHost: ExpoView {+ let content = UIView()+ var surfaceId = "" {+ didSet {+ if HtmlAppSurfaces.hosts.object(forKey: oldValue as NSString) === self {+ HtmlAppSurfaces.hosts.removeObject(forKey: oldValue as NSString)+ }+ HtmlAppSurfaces.hosts.setObject(self, forKey: surfaceId as NSString)+ HtmlAppSurfaces.attach(surfaceId)+ }+ }+ override func mountChildComponentView(_ childComponentView: UIView, index: Int) {+ content.insertSubview(childComponentView, at: index)+ }+ override func unmountChildComponentView(_ childComponentView: UIView, index: Int) {+ childComponentView.removeFromSuperview()+ }+ override func layoutSubviews() {+ super.layoutSubviews()+ if let target = content.superview { content.frame = target.bounds }+ }+ deinit {+ content.removeFromSuperview()+ if HtmlAppSurfaces.hosts.object(forKey: surfaceId as NSString) === self {+ HtmlAppSurfaces.hosts.removeObject(forKey: surfaceId as NSString)+ }+ }+}++final class HtmlAppSlot: ExpoView {+ var surfaceId = "" { didSet { HtmlAppSurfaces.attach(oldValue); HtmlAppSurfaces.attach(surfaceId) } }+ required init(appContext: AppContext? = nil) {+ super.init(appContext: appContext)+ clipsToBounds = true+ HtmlAppSurfaces.slots.add(self)+ }+ override func didMoveToWindow() {+ super.didMoveToWindow()+ // A removed card parks the very same WebView at its offscreen root host.+ // React does not destroy it until the owner's bounded teardown completes.+ HtmlAppSurfaces.attach(surfaceId)+ }+ override func layoutSubviews() {+ super.layoutSubviews()+ for child in subviews { child.frame = bounds }+ }+}diff --git a/apps/mobile/modules/cindy-html-preview/src/CindyHtmlPreviewModule.ts b/apps/mobile/modules/cindy-html-preview/src/CindyHtmlPreviewModule.tsindex 58097e7258..769e3018cb 100644--- a/apps/mobile/modules/cindy-html-preview/src/CindyHtmlPreviewModule.ts+++ b/apps/mobile/modules/cindy-html-preview/src/CindyHtmlPreviewModule.ts@@ -1,6 +1,8 @@import { requireOptionalNativeModule } from 'expo-modules-core';interface CindyHtmlPreviewModule {+ appHostAvailable?: boolean;+ startApp?(root: string, entry: string, token: string, csp: string, files: string[][]): Promise<string>;start(root: string, entry: string, token: string, csp: string, files: string[][]): Promise<string>;startOnDemand?(root: string, entry: string, token: string, csp: string): Promise<string>;resolveRequest?(token: string, id: string, filename: string, mime: string, status: number): Promise<boolean>;diff --git a/apps/mobile/src/__tests__/BotGroupMessageAttachments.test.tsx b/apps/mobile/src/__tests__/BotGroupMessageAttachments.test.tsxindex a927916ec3..6862e2064e 100644--- a/apps/mobile/src/__tests__/BotGroupMessageAttachments.test.tsx+++ b/apps/mobile/src/__tests__/BotGroupMessageAttachments.test.tsx@@ -64,6 +64,7 @@ vi.mock('@/session/ImageLightbox', async () => {const { createElement } = await import('react');return { ImageLightbox: ({ initialUrl }: { initialUrl: string }) => createElement('div', { 'data-testid': 'lightbox', 'data-url': initialUrl }) };});+vi.mock('@/session/McpAppCard', () => ({ McpAppCard: () => null }));vi.mock('@/session/mermaidWebView', () => ({ MermaidDiagram: () => null }));vi.mock('@/session/mathWebView', () => ({ MathFormulaWebView: () => null }));vi.mock('@/session/mediaPlayerWebView', () => ({ RemoteMediaPlayerWebView: () => null }));diff --git a/apps/mobile/src/__tests__/botGroupAttachmentLightbox.test.tsx b/apps/mobile/src/__tests__/botGroupAttachmentLightbox.test.tsxindex 5e87e6af1a..8d9dbda88e 100644--- a/apps/mobile/src/__tests__/botGroupAttachmentLightbox.test.tsx+++ b/apps/mobile/src/__tests__/botGroupAttachmentLightbox.test.tsx@@ -5,6 +5,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { BotGroupAttachment } from '@cindy/maker-shared/botGroupChat';import type { ResolveRemoteMediaFn } from '@/session/remoteMedia';+// This suite exercises attachments; MCP App's native WebView is covered by mcpAppCard.test.tsx.+vi.mock('@/session/McpAppCard', () => ({ McpAppCard: () => null }));+// Group attachments open the real shared ImageLightbox here (#5875): the timeline strip, the payload// conversion and the viewer are production code; only native surfaces and unrelated views are replaced.const runtime = vi.hoisted(() => ({diff --git a/apps/mobile/src/__tests__/fileChipNameWidth.test.tsx b/apps/mobile/src/__tests__/fileChipNameWidth.test.tsxindex bdad157500..8031f530c2 100644--- a/apps/mobile/src/__tests__/fileChipNameWidth.test.tsx+++ b/apps/mobile/src/__tests__/fileChipNameWidth.test.tsx@@ -5,6 +5,9 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import type { BotGroupAttachment } from '@cindy/maker-shared/botGroupChat';import type { ResolveRemoteMediaFn } from '@/session/remoteMedia';+// This suite exercises attachment layout; keep the unrelated native App surface out of Node.+vi.mock('@/session/McpAppCard', () => ({ McpAppCard: () => null }));+// Keeps the rendered React Native styles of the real file chip (#5875). Node has no Yoga, so the// content-sized width below applies Yoga's own flex-basis rule to those styles instead of a layout pass.vi.mock('react-native', async () => {diff --git a/apps/mobile/src/__tests__/mcpAppCard.test.tsx b/apps/mobile/src/__tests__/mcpAppCard.test.tsxnew file mode 100644index 0000000000..5429d3fcf2--- /dev/null+++ b/apps/mobile/src/__tests__/mcpAppCard.test.tsx@@ -0,0 +1,437 @@+// @vitest-environment jsdom+import { act, createElement, useEffect, useImperativeHandle } from 'react';+import { createRoot } from 'react-dom/client';+import { Script } from 'node:vm';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { sharedTaskHostPeer } from '@cindy/device-link';+import { mcpAppSandboxDocument } from '@cindy/maker-shared/mcp-apps';+const state = vi.hoisted(() => ({+ props: {} as Record<string, any>,+ inject: vi.fn(),+ invoke: vi.fn(),+ mode: 'light',+ prepare: vi.fn(),+ random: 0,+ foreground: 'active',+ appStateListeners: new Set<(state: string) => void>(),+ surfaceAvailable: true,+ mounts: 0,+}));+vi.mock('../session/NativeMcpAppSurface', () => ({+ get mcpAppSurfaceAvailable() { return state.surfaceAvailable; },+ NativeMcpAppHost: ({ children, surfaceId }: any) => createElement('div', { 'data-host': surfaceId }, children),+ NativeMcpAppSlot: ({ surfaceId }: any) => createElement('div', { 'data-slot': surfaceId }),+}));+vi.mock('../session/mcpAppNativeDocument', () => ({ prepareMcpAppNativeDocument: state.prepare }));+vi.mock('react-native', () => ({+ View: ({ children }: { children: React.ReactNode }) => createElement('div', null, children),+ ActivityIndicator: () => null,+ Pressable: ({ children, onPress }: { children?: React.ReactNode; onPress?: () => void }) =>+ createElement('button', { onClick: onPress }, children),+ Linking: { openURL: vi.fn() },+ StyleSheet: { create: (value: unknown) => value, hairlineWidth: 1 },+ Platform: { OS: 'android' },+ AppState: {+ currentState: 'active',+ addEventListener: (_name: string, listener: (state: string) => void) => {+ state.appStateListeners.add(listener);+ return { remove: () => state.appStateListeners.delete(listener) };+ },+ },+}));+vi.mock('react-native-webview', () => ({+ WebView: ({ ref, ...props }: any) => {+ state.props = props;+ useEffect(() => { ++state.mounts; }, []);+ useImperativeHandle(ref, () => ({ injectJavaScript: state.inject }));+ return createElement('div', { 'data-testid': 'mcp-webview' });+ },+}));+vi.mock('expo-crypto', () => ({+ getRandomBytes: (length: number) => new Uint8Array(length).fill(++state.random),+}));+vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, values?: { title: string }) => key === 'mcpApps.cardTitle' ? values?.title : key,+ i18n: { language: 'en' },+ }),+}));+vi.mock('@/components/AppText', () => ({+ Text: ({ children }: { children: React.ReactNode }) => createElement('span', null, children),+}));+vi.mock('@/device-link/DeviceLinkContext', () => ({+ useDeviceLink: () => ({ invoke: state.invoke }),+}));+vi.mock('@/theme', () => {+ const colors = {+ surface: 'white',+ surfaceElevated: 'white',+ textPrimary: 'black',+ textSecondary: 'gray',+ textTertiary: 'gray',+ border: 'gray',+ };+ return {+ useTheme: () => ({ colors, mode: state.mode }),+ textStyles: {},+ fontWeight: {},+ radius: {},+ spacing: {},+ };+});+import { McpAppCard } from '../session/McpAppCard';+import { McpAppViewsProvider } from '../session/McpAppViews';+const doc = {+ viewId: 'view',+ html: '<script>window.app=true</script>',+ csp: "default-src 'none'",+ prefersBorder: true,+ policy: { frameDomains: ['https://frame.example.org'] },+};+const nativeDocument = {+ source: { uri: 'http://127.0.0.1:5002/proxy.html' },+ resourceUrl: 'http://127.0.0.1:5001/resource.html',+ documentUrls: ['http://127.0.0.1:5002/proxy.html', 'http://127.0.0.1:5002/bootstrap',+ 'http://127.0.0.1:5001/resource.html', 'http://127.0.0.1:5001/bootstrap'],+ close: async () => {},+};+let container: HTMLDivElement;+let root: ReturnType<typeof createRoot>;+const render = (children: React.ReactNode) => root.render(<McpAppViewsProvider>{children}</McpAppViewsProvider>);+beforeEach(() => {+ vi.useFakeTimers();+ state.random = 0;+ state.mounts = 0;+ state.surfaceAvailable = true;+ state.appStateListeners.clear();+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);+ state.invoke.mockReset();+ state.inject.mockReset();+ state.props = {};+ state.mode = 'light';+ state.prepare.mockReset().mockResolvedValue(nativeDocument);+ state.invoke.mockImplementation(async (_device, _channel, [, input]) =>+ input.op === 'open' ? { ...doc } : input.op === 'poll' ? new Promise(() => {}) : {},+ );+ container = document.createElement('div');+ root = createRoot(container);+});+afterEach(async () => {+ await act(async () => root.unmount());+ await act(async () => { await vi.advanceTimersByTimeAsync(1000); });+ vi.useRealTimers();+ vi.unstubAllGlobals();+});+it('binds a served resource origin and gates declared frame navigation', async () => {+ await act(async () =>+ render(<McpAppCard deviceId="device" sessionId="task" clientId="card" title="App" />),+ );+ expect(state.props.originWhitelist).toEqual(['*']);+ const allow = state.props.onShouldStartLoadWithRequest;+ expect(allow({ isTopFrame: false, url: 'https://frame.example.org/embed' })).toBe(true);+ expect(allow({ isTopFrame: false, url: 'https://other.example.org/embed' })).toBe(false);+ expect(allow({ isTopFrame: true, url: 'https://frame.example.org/embed' })).toBe(false);+ expect(allow({ isTopFrame: true, url: 'http://127.0.0.1:5002/proxy.html' })).toBe(true);+ expect(allow({ isTopFrame: true, url: 'http://127.0.0.1:5001/resource.html' })).toBe(false);+ expect(allow({ isTopFrame: false, url: 'javascript:alert(1)' })).toBe(false);+ // Android supplies no frame identity, including for about:srcdoc and nested frames.+ expect(allow({ url: 'about:srcdoc' })).toBe(true);+ expect(allow({ url: 'http://127.0.0.1:5001/resource.html' })).toBe(true);+ expect(allow({ url: 'https://frame.example.org/embed' })).toBe(true);+ expect(allow({ url: 'https://other.example.org/embed' })).toBe(false);+ expect(allow({ url: 'https://frame.example.org.evil.test/embed' })).toBe(false);+ expect(allow({ url: 'file:///private' })).toBe(false);+ expect(allow({ url: 'javascript:alert(1)' })).toBe(false);+ expect(+ allow({+ isTopFrame: true,+ url: 'https://view.cindy-app.invalid/elsewhere',+ }),+ ).toBe(false);+ state.props.onMessage({+ nativeEvent: {+ data: JSON.stringify({+ key: state.prepare.mock.calls[0][1],+ message: {+ jsonrpc: '2.0',+ method: 'ui/notifications/sandbox-proxy-ready',+ },+ }),+ },+ });+ const script = state.inject.mock.calls[0][0];+ expect(script).not.toContain('<');+ const dispatchEvent = vi.fn();+ new Script(script).runInNewContext({+ window: { dispatchEvent },+ MessageEvent: class {+ data: unknown;+ constructor(_type: string, init: { data: unknown }) {+ this.data = init.data;+ }+ },+ });+ expect(dispatchEvent.mock.calls[0][0].data.params.html).toContain(doc.html);++ // Exercise the actual native proxy: its sandbox must prevent every App and+ // descendant from navigating the trusted top document, even with user activation.+ const shell = document.implementation.createHTMLDocument();+ const listeners = new Map<string, (event: unknown) => void>();+ const nativePost = vi.fn();+ const proxy = {+ location: { href: state.props.source.uri },+ ReactNativeWebView: { postMessage: nativePost },+ addEventListener: (name: string, listener: (event: unknown) => void) =>+ listeners.set(name, listener),+ };+ const proxyDocument = new DOMParser().parseFromString(mcpAppSandboxDocument(state.prepare.mock.calls[0][1],+ 'http://127.0.0.1:5001/resource.html'), 'text/html');+ const proxyScript = proxyDocument.querySelector('script')!.textContent!;+ new Script(proxyScript).runInNewContext({ document: shell, window: proxy, URL });+ listeners.get('message')!({+ source: proxy,+ data: dispatchEvent.mock.calls[0][0].data,+ });+ const appFrame = shell.querySelector('iframe')!;+ expect(appFrame.getAttribute('sandbox')).toBe('allow-scripts allow-same-origin');+ expect(appFrame.srcdoc).toBe('');+ expect(appFrame.src).toBe('http://127.0.0.1:5001/resource.html');+ // The same WindowProxy can now name a frame-domain replacement document.+ // Its real event.origin, rather than Android's missing isTopFrame, is decisive.+ nativePost.mockClear();+ const message = { jsonrpc: '2.0', id: 9, method: 'tools/call', params: { name: 'write' } };+ listeners.get('message')!({ source: appFrame.contentWindow, origin: 'https://frame.example.org', data: message });+ expect(nativePost).not.toHaveBeenCalled();+ listeners.get('message')!({ source: {}, origin: 'http://127.0.0.1:5001', data: message });+ expect(nativePost).not.toHaveBeenCalled();+ listeners.get('message')!({ source: appFrame.contentWindow, origin: 'http://127.0.0.1:5001', data: message });+ expect(JSON.parse(nativePost.mock.calls[0][0]).message).toEqual(message);+});++it('rejects a Desktop-only descriptor without starting a native document or leaving a View open', async () => {+ state.invoke.mockResolvedValueOnce({ viewId: 'view', transport: 'sandbox', prefersBorder: true });+ await act(async () => render(<McpAppCard deviceId="device" sessionId="task" clientId="card" title="App" />));+ expect(state.prepare).not.toHaveBeenCalled();+ expect(container.querySelector('[data-testid="mcp-webview"]')).toBeNull();+ expect(container.textContent).toContain('mcpApps.loadFailed');+ expect(state.invoke).toHaveBeenCalledWith('device', 'maker:mcp-apps:v1', [+ 'task', { op: 'teardown', viewId: 'view', alreadyNotified: false },+ ]);+});++it('closes late native servers without mounting them after the card has left the screen', async () => {+ let prepared!: (value: typeof nativeDocument) => void;+ const close = vi.fn(async () => {});+ state.prepare.mockImplementation(() => new Promise((resolve) => { prepared = resolve; }));+ await act(async () => render(<McpAppCard deviceId="device" sessionId="task" clientId="card" title="App" />));+ expect(state.prepare).toHaveBeenCalledOnce();+ await act(async () => render(<McpAppCard deviceId="device" sessionId="task" clientId="card" title="App" active={false} />));+ await act(async () => prepared({ ...nativeDocument, close }));+ expect(close).toHaveBeenCalledOnce();+ expect(container.querySelector('[data-testid="mcp-webview"]')).toBeNull();+});++it.each(['inactive', 'parent-unmount'])('keeps the same live WebView until teardown responds after %s', async (reason) => {+ const close = vi.fn(async () => {});+ state.prepare.mockResolvedValue({ ...nativeDocument, close });+ const card = (active = true) => <McpAppCard deviceId="device" sessionId="task" clientId="card" title="App" active={active} />;+ await act(async () => render(card()));+ const original = container.querySelector('[data-testid="mcp-webview"]');+ const props = state.props;+ const key = state.prepare.mock.calls[0][1];+ await act(async () => props.onMessage({ nativeEvent: { data: JSON.stringify({ key,+ message: { jsonrpc: '2.0', method: 'ui/notifications/sandbox-proxy-ready' } }) } }));+ state.inject.mockClear();+ await act(async () => render(reason === 'inactive' ? card(false) : null));+ expect(container.querySelector('[data-slot]')).toBeNull();+ expect(container.querySelector('[data-testid="mcp-webview"]')).toBe(original);+ expect(state.mounts).toBe(1);+ expect(close).not.toHaveBeenCalled();+ const dispatchEvent = vi.fn();+ new Script(state.inject.mock.calls[0][0]).runInNewContext({+ window: { dispatchEvent },+ MessageEvent: class { data: unknown; constructor(_type: string, init: any) { this.data = init.data; } },+ });+ const teardown = dispatchEvent.mock.calls[0][0].data;+ expect(teardown.method).toBe('ui/resource-teardown');+ await act(async () => { await vi.advanceTimersByTimeAsync(300); });+ expect(container.querySelector('[data-testid="mcp-webview"]')).toBe(original);+ await act(async () => props.onMessage({ nativeEvent: { data: JSON.stringify({ key,+ message: { jsonrpc: '2.0', id: teardown.id, result: {} } }) } }));+ expect(container.querySelector('[data-testid="mcp-webview"]')).toBeNull();+ expect(close).toHaveBeenCalledOnce();+ expect(state.invoke.mock.calls.map(([, , [, input]]) => input).filter((i) => i.op === 'teardown'))+ .toEqual([expect.objectContaining({ alreadyNotified: true })]);+});++it('disposes at one second even when App teardown and remote teardown never return', async () => {+ const close = vi.fn(async () => {});+ state.prepare.mockResolvedValue({ ...nativeDocument, close });+ state.invoke.mockImplementation(async (_device, _channel, [, input]) => {+ if (input.op === 'open') return { ...doc };+ if (input.op === 'poll' || input.op === 'teardown') return new Promise(() => {});+ return {};+ });+ await act(async () => render(<McpAppCard deviceId="device" sessionId="task" clientId="card" title="App" />));+ await act(async () => state.props.onMessage({ nativeEvent: { data: JSON.stringify({+ key: state.prepare.mock.calls[0][1], message: { jsonrpc: '2.0', method: 'ui/notifications/sandbox-proxy-ready' },+ }) } }));+ await act(async () => render(null));+ await act(async () => { await vi.advanceTimersByTimeAsync(999); });+ expect(container.querySelector('[data-testid="mcp-webview"]')).not.toBeNull();+ expect(close).not.toHaveBeenCalled();+ await act(async () => { await vi.advanceTimersByTimeAsync(1); });+ expect(container.querySelector('[data-testid="mcp-webview"]')).toBeNull();+ expect(close).toHaveBeenCalledOnce();+});++it('reopens a fresh View after background shutdown without replaying App tools', async () => {+ const close = vi.fn(async () => {});+ state.prepare.mockResolvedValue({ ...nativeDocument, close });+ await act(async () => render(<McpAppCard deviceId="device" sessionId="task" clientId="card" title="App" />));+ const background = (value: string) => { for (const listener of state.appStateListeners) listener(value); };+ const original = container.querySelector('[data-host]')?.getAttribute('data-host');+ await act(async () => background('background'));+ expect(container.querySelector('[data-slot]')).toBeNull();+ expect(close).toHaveBeenCalledOnce();+ await act(async () => background('active'));+ expect(container.querySelector('[data-host]')?.getAttribute('data-host')).not.toBe(original);+ const ops = state.invoke.mock.calls.map(([, , [, input]]) => input.op);+ expect(ops.filter((op) => op === 'open')).toHaveLength(2);+ expect(ops).not.toContain('message');+});++it.each(['light', 'dark'])('keeps saved text and requests a phone update on old binaries in %s mode', async (mode) => {+ state.mode = mode;+ state.surfaceAvailable = false;+ await act(async () => render(<McpAppCard deviceId="device" sessionId="task" clientId="card" title="App" fallbackText="Saved text" />));+ expect(container.textContent).toContain('mcpApps.mobileUpdateRequired');+ expect(container.textContent).toContain('Saved text');+ expect(state.invoke).not.toHaveBeenCalled();+ expect(container.querySelector('[data-testid="mcp-webview"]')).toBeNull();+});++it('hosts four independently bound visible cards without sharing bridge keys', async () => {+ await act(async () => render(<>{Array.from({ length: 4 }, (_, index) =>+ <McpAppCard key={index} deviceId="device" sessionId="task" clientId={String(index)} title="App" />)}</>));+ expect(container.querySelectorAll('[data-host]')).toHaveLength(4);+ expect(container.querySelectorAll('[data-slot]')).toHaveLength(4);+ expect(state.prepare).toHaveBeenCalledTimes(4);+ expect(new Set(state.prepare.mock.calls.map(([, key]) => key)).size).toBe(4);+});++it('releases offscreen Views, stops polling and reopens only the newly visible card', async () => {+ const polls = new Map<string, (events: unknown[]) => void>();+ state.invoke.mockImplementation(async (_device, _channel, [, input]) => {+ if (input.op === 'open') return { ...doc, viewId: input.clientId };+ if (input.op === 'poll') return new Promise((resolve) => polls.set(input.viewId, resolve));+ return {};+ });+ const renderCards = (visible: number) =>+ render(+ <>+ {Array.from({ length: 6 }, (_, index) => (+ <McpAppCard+ key={index}+ deviceId="device"+ sessionId="task"+ clientId={`card-${index}`}+ title="App"+ active={index === visible}+ />+ ))}+ </>,+ );+ const inputs = (op: string) =>+ state.invoke.mock.calls.map(([, , [, input]]) => input).filter((input) => input.op === op);+ await act(async () => renderCards(-1));+ expect(state.invoke).not.toHaveBeenCalled();+ expect(container.querySelectorAll('[data-testid="mcp-webview"]')).toHaveLength(0);++ await act(async () => renderCards(0));+ expect(inputs('open').map((input) => input.clientId)).toEqual(['card-0']);+ expect(container.querySelectorAll('[data-testid="mcp-webview"]')).toHaveLength(1);+ await act(async () => renderCards(5));+ expect(inputs('teardown')).toEqual([expect.objectContaining({ viewId: 'card-0' })]);+ expect(inputs('open').map((input) => input.clientId)).toEqual(['card-0', 'card-5']);+ expect(container.querySelectorAll('[data-testid="mcp-webview"]')).toHaveLength(1);++ // A poll from the old View cannot inject into the replacement or schedule another poll.+ state.inject.mockClear();+ await act(async () =>+ polls.get('card-0')!([{ seq: 1, message: { jsonrpc: '2.0', method: 'old' } }]),+ );+ expect(state.inject).not.toHaveBeenCalled();+ expect(inputs('poll').filter((input) => input.viewId === 'card-0')).toHaveLength(1);+ await act(async () => renderCards(0));+ expect(inputs('teardown').map((input) => input.viewId)).toEqual(['card-0', 'card-5']);+ expect(inputs('open').map((input) => input.clientId)).toEqual(['card-0', 'card-5', 'card-0']);+});++it('cancels an offscreen pending open and disposes its late View without mounting it', async () => {+ let finishOpen!: (document: typeof doc) => void;+ state.invoke.mockImplementation(async (_device, _channel, [, input]) =>+ input.op === 'open'+ ? new Promise((resolve) => {+ finishOpen = resolve;+ })+ : {},+ );+ const renderCard = (active: boolean) =>+ render(+ <McpAppCard deviceId="device" sessionId="task" clientId="card" title="App" active={active} />,+ );+ await act(async () => renderCard(true));+ const opening = state.invoke.mock.calls[0][2][1];+ await act(async () => renderCard(false));+ expect(state.invoke).toHaveBeenCalledWith('device', 'maker:mcp-apps:v1', [+ 'task',+ { op: 'cancel-open', openId: opening.openId },+ ]);+ await act(async () => finishOpen({ ...doc }));+ expect(state.invoke).toHaveBeenCalledWith('device', 'maker:mcp-apps:v1', [+ 'task',+ { op: 'teardown', viewId: 'view' },+ ]);+ expect(container.querySelectorAll('[data-testid="mcp-webview"]')).toHaveLength(0);+ expect(state.invoke.mock.calls.map(([, , [, input]]) => input.op)).toEqual([+ 'open',+ 'cancel-open',+ 'teardown',+ ]);+});++it.each(['light', 'dark'])('renders read-only guest history without invoking the Host in %s mode', async (mode) => {+ state.mode = mode;+ const deviceId = sharedTaskHostPeer('shared-task', 'host-device');+ await act(async () => render(<McpAppCard deviceId={deviceId} sessionId="task" clientId="card"+ title="Saved form" fallbackText="Saved result <script>window.attack=true</script>" />));+ expect(container.textContent).toContain('Saved form');+ expect(container.textContent).toContain('Saved result <script>window.attack=true</script>');+ expect(container.textContent).toContain('mcpApps.sharedTaskReadOnly');+ expect(container.textContent).not.toContain('mcpApps.loadFailed');+ expect(container.querySelector('[data-testid="mcp-webview"], button, script')).toBeNull();+ expect(state.invoke).not.toHaveBeenCalled();+ expect(state.inject).not.toHaveBeenCalled();+ await act(async () => render(<McpAppCard deviceId={deviceId} sessionId="task" clientId="pending" title="Pending form" />));+ expect(container.textContent).toContain('Pending form');+ expect(container.textContent).toContain('mcpApps.sharedTaskReadOnly');+});++it.each(['light', 'dark'])('keeps saved text readable after App failures and retry in %s mode', async (mode) => {+ state.mode = mode;+ state.invoke.mockRejectedValueOnce(new Error('MCP_APP_SERVER_CHANGED'));+ const saved = 'Saved result\n<script>window.attack=true</script>';+ await act(async () => render(+ <McpAppCard deviceId="device" sessionId="task" clientId="card" title="Saved form" fallbackText={saved} />,+ ));+ expect(container.textContent).toContain(saved);+ expect(container.textContent).toContain('mcpApps.loadFailed');+ expect(container.querySelector('[data-testid="mcp-webview"], script')).toBeNull();+ await act(async () => container.querySelector('button')!.click());+ expect(container.textContent).not.toContain(saved);+ expect(container.querySelector('[data-testid="mcp-webview"]')).not.toBeNull();+ await act(async () => state.props.onError());+ expect(container.textContent).toContain(saved);+ expect(container.querySelector('[data-testid="mcp-webview"], script')).toBeNull();+});diff --git a/apps/mobile/src/__tests__/mcpAppNativeDocument.test.ts b/apps/mobile/src/__tests__/mcpAppNativeDocument.test.tsnew file mode 100644index 0000000000..660d5ec291--- /dev/null+++ b/apps/mobile/src/__tests__/mcpAppNativeDocument.test.ts@@ -0,0 +1,185 @@+import { beforeEach, expect, it, vi } from "vitest";+import { Script } from 'node:vm';++const state = vi.hoisted(() => ({+ files: new Map<string, string>(),+ removed: [] as string[],+ start: vi.fn(),+ stop: vi.fn(),+ random: 0,+ hostAvailable: true,+ startAvailable: true,+}));+vi.mock("expo-crypto", () => ({+ getRandomBytes: (size: number) => new Uint8Array(size).fill(++state.random),+}));+vi.mock("../../modules/cindy-html-preview/src/CindyHtmlPreviewModule", () => ({+ default: {+ get appHostAvailable() { return state.hostAvailable; },+ get startApp() { return state.startAvailable ? state.start : undefined; },+ stop: state.stop,+ },+}));+vi.mock("expo-file-system", () => {+ class Directory {+ uri: string;+ constructor(...parts: Array<string | { uri: string }>) {+ this.uri = parts+ .map((part) => (typeof part === "string" ? part : part.uri))+ .join("/");+ }+ get exists() {+ return this.uri.endsWith("/mcp-apps") ? false : true;+ }+ create() {}+ delete() {+ state.removed.push(this.uri);+ }+ }+ class File extends Directory {+ write(value: string) {+ state.files.set(this.uri, value);+ }+ }+ return { Directory, File, Paths: { cache: "file:///cache" } };+});+import { MCP_APP_STORAGE_BOOTSTRAP, prepareMcpAppNativeDocument } from "../session/mcpAppNativeDocument";++const document = {+ viewId: "view",+ html: "<script>window.app=true</script>",+ csp: "default-src 'none'; script-src 'unsafe-inline'",+ prefersBorder: true,+};+beforeEach(() => {+ state.files.clear();+ state.removed = [];+ state.random = 0;+ state.hostAvailable = true;+ state.startAvailable = true;+ state.start+ .mockReset()+ .mockImplementation(+ async (_root, _entry, token) =>+ `http://127.0.0.1:${5000 + state.start.mock.calls.length}/__cindy/${token}`,+ );+ state.stop.mockReset().mockResolvedValue(undefined);+});+it.each(['host', 'server'])('requires a compatible native %s before writing private files', async (missing) => {+ if (missing === 'host') state.hostAvailable = false;+ else state.startAvailable = false;+ await expect(prepareMcpAppNativeDocument(document, 'native-key'))+ .rejects.toThrow('MCP_APP_NATIVE_UPDATE_REQUIRED');+ expect(state.files.size).toBe(0);+ expect(state.start).not.toHaveBeenCalled();+ expect(state.stop).not.toHaveBeenCalled();+});+it("serves complete App HTML and its exact CSP on a different origin from the trusted proxy", async () => {+ const view = await prepareMcpAppNativeDocument(document, "native-key");+ expect(new URL(view.source.uri).origin).not.toBe(+ new URL(view.resourceUrl).origin,+ );+ const [resource, proxy] = state.start.mock.calls;+ expect(resource[3]).toBe(document.csp);+ expect(resource[1]).toBe('initialize.html');+ expect(resource[4]).toEqual([["initialize.html", "2", "text/html"], ["resource.html", "0", "text/html"]]);+ expect(+ state.files.get("file:///cache/mcp-apps/" + "01".repeat(24) + "/0"),+ ).toBe(document.html);+ expect(proxy[4]).toEqual([["proxy.html", "1", "text/html"]]);+ expect(proxy[3]).toContain("frame-src " + new URL(view.resourceUrl).origin);+ expect(proxy[3]).toContain("connect-src 'none'");+ const html = state.files.get(+ "file:///cache/mcp-apps/" + "01".repeat(24) + "/1",+ )!;+ expect(html).toContain(+ "const expectedResourceUrl=" + JSON.stringify(view.resourceUrl),+ );+ expect(view.documentUrls).toEqual([+ view.source.uri,+ "http://127.0.0.1:5002/proxy.html",+ view.resourceUrl,+ "http://127.0.0.1:5001/initialize.html",+ "http://127.0.0.1:5001/resource.html",+ ]);+ await Promise.all([view.close(), view.close()]);+ expect(state.stop.mock.calls.map(([token]) => token)).toEqual([+ "01".repeat(24),+ "02".repeat(24),+ ]);+ expect(state.removed).toHaveLength(1);+});+it('clears DOM storage and waits for IndexedDB deletion before loading untrusted HTML', async () => {+ const localStorage = { clear: vi.fn() };+ const sessionStorage = { clear: vi.fn() };+ const pending: Array<{ onsuccess?: () => void; onerror?: () => void; onblocked?: () => void }> = [];+ const replace = vi.fn();+ const indexedDB = { databases: async () => [{ name: 'old-app' }, { name: 'other-db' }],+ deleteDatabase: vi.fn(() => { const request = {}; pending.push(request); return request; }) };+ const script = MCP_APP_STORAGE_BOOTSTRAP.split('<script>')[1].split('</script>')[0];+ const result = new Script(script).runInNewContext({ localStorage, sessionStorage, indexedDB, location: { replace } });+ await vi.waitFor(() => expect(pending).toHaveLength(2));+ expect(localStorage.clear).toHaveBeenCalledOnce();+ expect(sessionStorage.clear).toHaveBeenCalledOnce();+ expect(indexedDB.deleteDatabase.mock.calls).toEqual([['old-app'], ['other-db']]);+ expect(replace).not.toHaveBeenCalled();+ pending[0].onsuccess!();+ await Promise.resolve();+ expect(replace).not.toHaveBeenCalled();+ pending[1].onsuccess!();+ await result;+ expect(replace).toHaveBeenCalledWith('/resource.html');+});+it.each(['onerror', 'onblocked'])('does not load an App when storage deletion signals %s', async (event) => {+ const request: Record<string, () => void> = {};+ const replace = vi.fn();+ const script = MCP_APP_STORAGE_BOOTSTRAP.split('<script>')[1].split('</script>')[0];+ const result = new Script(script).runInNewContext({ localStorage: { clear() {} }, sessionStorage: { clear() {} },+ indexedDB: { databases: async () => [{ name: 'old-app' }], deleteDatabase: () => request }, location: { replace } });+ await vi.waitFor(() => expect(request[event]).toBeTypeOf('function'));+ request[event]();+ await result;+ expect(replace).not.toHaveBeenCalled();+});+it.each([1, 2])(+ "reclaims every attempted server and the private cache when start %s fails",+ async (failed) => {+ state.start.mockImplementation(async (_root, _entry, token) => {+ if (state.start.mock.calls.length === failed)+ throw new Error("START_FAILED");+ return `http://127.0.0.1:5001/__cindy/${token}`;+ });+ await expect(+ prepareMcpAppNativeDocument(document, "native-key"),+ ).rejects.toThrow("START_FAILED");+ expect(state.stop).toHaveBeenCalledTimes(failed);+ expect(state.removed).toHaveLength(1);+ },+);+it("rejects a native response that would place App and proxy on one origin", async () => {+ state.start.mockResolvedValue("http://127.0.0.1:5001/document");+ await expect(+ prepareMcpAppNativeDocument(document, "native-key"),+ ).rejects.toThrow("MCP_APP_INVALID_ORIGIN");+ expect(state.stop).toHaveBeenCalledTimes(2);+ expect(state.removed).toHaveLength(1);+});+it("waits for every server to stop before removing its files, even when one stop fails", async () => {+ const view = await prepareMcpAppNativeDocument(document, "native-key");+ let finish!: () => void;+ state.stop+ .mockRejectedValueOnce(new Error("STOP_FAILED"))+ .mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ }),+ );+ const closing = view.close();+ const result = expect(closing).rejects.toThrow("STOP_FAILED");+ await Promise.resolve();+ expect(state.removed).toHaveLength(0);+ finish();+ await result;+ expect(state.removed).toHaveLength(1);+});diff --git a/apps/mobile/src/__tests__/messageNormalize.test.ts b/apps/mobile/src/__tests__/messageNormalize.test.tsindex 3f91d32116..9609e2b82e 100644--- a/apps/mobile/src/__tests__/messageNormalize.test.ts+++ b/apps/mobile/src/__tests__/messageNormalize.test.ts@@ -31,6 +31,39 @@ describe('normalizeRemoteMessages', () => {await i18n.changeLanguage('zh-CN');});+ it('recognizes host-marked MCP App cards and leaves ordinary assistant content unchanged', () => {+ const content = { mcpApp: { version: 1, serverId: 'example', serverRevision: 'revision', resourceUri: 'ui://example/app', tool: { name: 'draft', title: '申请表', inputSchema: { type: 'object' } }, arguments: {},+ result: { content: [{ type: 'text', text: 'Saved form result' }], _meta: { private: 'view-only' } } } };+ const output = normalizeRemoteMessages([+ message({ id: 'app', role: 'assistant', content, agentMeta: { mcpApp: true } }),+ message({ id: 'plain', role: 'assistant', content: '工具返回的文本' }),+ ]);+ expect(output[0]).toMatchObject({ systemCardType: 'mcp-app', systemCardData: { title: '申请表', fallbackText: 'Saved form result' } });+ expect(output[1]).toMatchObject({ body: '工具返回的文本' });+ });++ it("renders public guest MCP App summaries, including pending cards with no text", () => {+ const rows = ["", "Saved result"].map((text, index) =>+ message({+ id: `guest-app-${index}`,+ role: "assistant",+ agentMeta: { mcpApp: true },+ content: { mcpAppHistory: { version: 1, title: "Draft form", text } },+ }),+ );+ expect(+ normalizeRemoteMessages(rows).map((row) => [+ row.systemCardType,+ row.systemCardData,+ ]),+ ).toEqual(+ ["", "Saved result"].map((fallbackText) => [+ "mcp-app",+ { title: "Draft form", fallbackText },+ ]),+ );+ });+it('renders a projected large tool input from its bounded summary and keeps its result', () => {const projected = projectLargeSettledToolInputs([message({diff --git a/apps/mobile/src/__tests__/messageSourceLabels.test.ts b/apps/mobile/src/__tests__/messageSourceLabels.test.tsindex 3333c48359..ff31bad352 100644--- a/apps/mobile/src/__tests__/messageSourceLabels.test.ts+++ b/apps/mobile/src/__tests__/messageSourceLabels.test.ts@@ -9,6 +9,7 @@ import {shortDeviceId,sourceDeviceDisplayName,sourceDeviceLabel,+ sourceIdText,sourcePluginLabel,} from "@/session/messageSourceLabels";@@ -90,6 +91,27 @@ describe("device source label", () => {});describe("sender labels", () => {+ it.each(['en', 'zh-CN', 'zh-TW', 'ja', 'ko'])(+ 'keeps the MCP server name and ID visible in %s',+ async (language) => {+ await i18n.changeLanguage(language);+ try {+ const sourcePlugin = { pluginId: 'mcp-app:reports', name: 'Reports' };+ expect(sourcePluginLabel(sourcePlugin)).toContain('Reports');+ expect(sourcePluginLabel({ pluginId: sourcePlugin.pluginId })).toContain('reports');+ const idText = sourceIdText({ sourcePlugin });+ expect(idText).toBe(i18n.t('mcpApps.serverId', { id: 'reports' }));+ expect(idText).toContain('reports');+ expect(idText).not.toContain('mcp-app:');+ expect(i18n.t('mcpApps.cardTitle', { title: 'Dashboard' })).toBe(+ `Dashboard · ${i18n.t('mcpApps.appName')}`,+ );+ } finally {+ await i18n.changeLanguage('zh-CN');+ }+ },+ );+it("formats plugin, automation (incl. redacted) and Orca titles with the shared wording", () => {expect(sourcePluginLabel({ pluginId: "p", name: "日报" })).toBe("由插件「日报」发送",diff --git a/apps/mobile/src/__tests__/messageSourceLabelsRender.test.tsx b/apps/mobile/src/__tests__/messageSourceLabelsRender.test.tsxindex e9929a303d..508f903185 100644--- a/apps/mobile/src/__tests__/messageSourceLabelsRender.test.tsx+++ b/apps/mobile/src/__tests__/messageSourceLabelsRender.test.tsx@@ -207,6 +207,7 @@ vi.mock("@/session/MobileComposerInputRow", () => ({MOBILE_COMPOSER_CONTROL_SIZE: 44,}));vi.mock("@/session/ImageLightbox", () => ({ ImageLightbox: () => null }));+vi.mock("@/session/McpAppCard", () => ({ McpAppCard: () => null }));vi.mock("@/session/mermaidWebView", () => ({ MermaidDiagram: () => null }));vi.mock("@/session/mathWebView", () => ({ MathFormulaWebView: () => null }));vi.mock("@/session/mediaPlayerWebView", () => ({@@ -479,6 +480,13 @@ describe("source labels reveal their ids on long press", () => {}it("shows plugin, session and automation ids, like the device label", () => {+ const appSource = longPress(+ [msg("app", "run", { sourcePlugin: { pluginId: "mcp-app:reports", name: "Reports" } })],+ "message.sourcePlugin",+ );+ expect(appSource).toContain("由 MCP App「Reports」发送");+ expect(appSource).toContain("MCP 服务器 ID:reports");+ expect(appSource).not.toContain("mcp-app:reports");expect(longPress([msg("p1", "run", { sourcePlugin: { pluginId: "ghost-github", name: "GitHub" } })], "message.sourcePlugin"),).toContain("插件 ID:ghost-github");diff --git a/apps/mobile/src/__tests__/pluginAttachmentBubble.test.tsx b/apps/mobile/src/__tests__/pluginAttachmentBubble.test.tsxindex 73fc2ab18b..28dd525dca 100644--- a/apps/mobile/src/__tests__/pluginAttachmentBubble.test.tsx+++ b/apps/mobile/src/__tests__/pluginAttachmentBubble.test.tsx@@ -61,6 +61,7 @@ vi.mock('@/session/expandedBlockMemory', () => ({ useFoldableExpandedState: () =vi.mock('@/platform/chrome', () => ({ NativePullDownMenu: () => null, showActionMenu: vi.fn(), usesNativePullDownMenu: () => false, usesSystemActionMenu: () => false }));vi.mock('@/session/MobileComposerInputRow', () => ({ MobileComposerInputRow: () => null, MOBILE_COMPOSER_VOICE_ANCHOR_RIGHT: 0, MOBILE_COMPOSER_CONTROL_SIZE: 44 }));vi.mock('@/session/ImageLightbox', () => ({ ImageLightbox: () => null }));+vi.mock('@/session/McpAppCard', () => ({ McpAppCard: () => null }));vi.mock('@/session/mermaidWebView', () => ({ MermaidDiagram: () => null }));vi.mock('@/session/mathWebView', () => ({ MathFormulaWebView: () => null }));vi.mock('@/session/mediaPlayerWebView', () => ({ RemoteMediaPlayerWebView: () => null }));diff --git a/apps/mobile/src/i18n/locales/en/index.ts b/apps/mobile/src/i18n/locales/en/index.tsindex 0a55403977..0c94c70f8f 100644--- a/apps/mobile/src/i18n/locales/en/index.ts+++ b/apps/mobile/src/i18n/locales/en/index.ts@@ -1,3 +1,4 @@+import mcpApps from './mcpApps.json';import plugins from './plugins.json';import taskTags from './taskTags.json';/**@@ -28,6 +29,7 @@ import startup from './startup.json';import update from './update.json';export default {+ mcpApps,plugins,taskTags,remoteDesktop,diff --git a/apps/mobile/src/i18n/locales/en/mcpApps.json b/apps/mobile/src/i18n/locales/en/mcpApps.jsonnew file mode 100644index 0000000000..38ff8af432--- /dev/null+++ b/apps/mobile/src/i18n/locales/en/mcpApps.json@@ -0,0 +1,12 @@+{+ "sharedTaskReadOnly": "Only the session owner can interact with this card.",+ "retry": "Reload",+ "loadFailed": "The app could not load. Check the connection and reload.",+ "updateRequired": "This computer does not support MCP Apps yet. Update Cindy on that computer and try again.",+ "appName": "MCP App",+ "cardTitle": "{{title}} · $t(mcpApps.appName)",+ "messageSource": "Sent by $t(mcpApps.appName) “{{name}}”",+ "serverId": "MCP Server ID: {{id}}",+ "exitFullscreen": "Exit Fullscreen",+ "mobileUpdateRequired": "Update Cindy on this phone to open this card."+}diff --git a/apps/mobile/src/i18n/locales/ja/index.ts b/apps/mobile/src/i18n/locales/ja/index.tsindex 0a55403977..0c94c70f8f 100644--- a/apps/mobile/src/i18n/locales/ja/index.ts+++ b/apps/mobile/src/i18n/locales/ja/index.ts@@ -1,3 +1,4 @@+import mcpApps from './mcpApps.json';import plugins from './plugins.json';import taskTags from './taskTags.json';/**@@ -28,6 +29,7 @@ import startup from './startup.json';import update from './update.json';export default {+ mcpApps,plugins,taskTags,remoteDesktop,diff --git a/apps/mobile/src/i18n/locales/ja/mcpApps.json b/apps/mobile/src/i18n/locales/ja/mcpApps.jsonnew file mode 100644index 0000000000..a7175ae7b7--- /dev/null+++ b/apps/mobile/src/i18n/locales/ja/mcpApps.json@@ -0,0 +1,12 @@+{+ "sharedTaskReadOnly": "このカードを操作できるのはセッションのオーナーだけです。",+ "retry": "再読み込み",+ "loadFailed": "アプリを読み込めませんでした。接続を確認して再読み込みしてください。",+ "updateRequired": "このコンピューターはまだ MCP Apps に対応していません。このコンピューターの Cindy を更新してから、もう一度お試しください。",+ "appName": "MCP App",+ "cardTitle": "{{title}} · $t(mcpApps.appName)",+ "messageSource": "$t(mcpApps.appName)「{{name}}」から送信",+ "serverId": "MCP サーバー ID:{{id}}",+ "exitFullscreen": "全画面表示を終了",+ "mobileUpdateRequired": "このカードを開くには、スマートフォンの Cindy を更新してください。"+}diff --git a/apps/mobile/src/i18n/locales/ko/index.ts b/apps/mobile/src/i18n/locales/ko/index.tsindex 0a55403977..0c94c70f8f 100644--- a/apps/mobile/src/i18n/locales/ko/index.ts+++ b/apps/mobile/src/i18n/locales/ko/index.ts@@ -1,3 +1,4 @@+import mcpApps from './mcpApps.json';import plugins from './plugins.json';import taskTags from './taskTags.json';/**@@ -28,6 +29,7 @@ import startup from './startup.json';import update from './update.json';export default {+ mcpApps,plugins,taskTags,remoteDesktop,diff --git a/apps/mobile/src/i18n/locales/ko/mcpApps.json b/apps/mobile/src/i18n/locales/ko/mcpApps.jsonnew file mode 100644index 0000000000..6920a0ac96--- /dev/null+++ b/apps/mobile/src/i18n/locales/ko/mcpApps.json@@ -0,0 +1,12 @@+{+ "sharedTaskReadOnly": "이 카드는 세션 소유자만 조작할 수 있습니다.",+ "retry": "다시 불러오기",+ "loadFailed": "앱을 불러오지 못했습니다. 연결을 확인한 후 다시 불러오세요.",+ "updateRequired": "이 컴퓨터는 아직 MCP Apps를 지원하지 않습니다. 해당 컴퓨터의 Cindy를 업데이트한 후 다시 시도하세요.",+ "appName": "MCP App",+ "cardTitle": "{{title}} · $t(mcpApps.appName)",+ "messageSource": "$t(mcpApps.appName) “{{name}}”에서 전송",+ "serverId": "MCP 서버 ID: {{id}}",+ "exitFullscreen": "전체 화면 종료",+ "mobileUpdateRequired": "이 카드를 열려면 휴대폰의 Cindy를 업데이트하세요."+}diff --git a/apps/mobile/src/i18n/locales/zh-CN/index.ts b/apps/mobile/src/i18n/locales/zh-CN/index.tsindex 0a55403977..0c94c70f8f 100644--- a/apps/mobile/src/i18n/locales/zh-CN/index.ts+++ b/apps/mobile/src/i18n/locales/zh-CN/index.ts@@ -1,3 +1,4 @@+import mcpApps from './mcpApps.json';import plugins from './plugins.json';import taskTags from './taskTags.json';/**@@ -28,6 +29,7 @@ import startup from './startup.json';import update from './update.json';export default {+ mcpApps,plugins,taskTags,remoteDesktop,diff --git a/apps/mobile/src/i18n/locales/zh-CN/mcpApps.json b/apps/mobile/src/i18n/locales/zh-CN/mcpApps.jsonnew file mode 100644index 0000000000..8cc9acaede--- /dev/null+++ b/apps/mobile/src/i18n/locales/zh-CN/mcpApps.json@@ -0,0 +1,12 @@+{+ "sharedTaskReadOnly": "此卡片仅任务主人可操作。",+ "retry": "重新加载",+ "loadFailed": "应用加载失败。请检查连接后重新加载。",+ "updateRequired": "这台电脑暂不支持 MCP Apps,请更新电脑上的 Cindy 后再试。",+ "appName": "MCP App",+ "cardTitle": "{{title}} · $t(mcpApps.appName)",+ "messageSource": "由 $t(mcpApps.appName)「{{name}}」发送",+ "serverId": "MCP 服务器 ID:{{id}}",+ "exitFullscreen": "退出全屏",+ "mobileUpdateRequired": "请更新手机上的 Cindy 后再打开此卡片。"+}diff --git a/apps/mobile/src/i18n/locales/zh-TW/index.ts b/apps/mobile/src/i18n/locales/zh-TW/index.tsindex 0a55403977..0c94c70f8f 100644--- a/apps/mobile/src/i18n/locales/zh-TW/index.ts+++ b/apps/mobile/src/i18n/locales/zh-TW/index.ts@@ -1,3 +1,4 @@+import mcpApps from './mcpApps.json';import plugins from './plugins.json';import taskTags from './taskTags.json';/**@@ -28,6 +29,7 @@ import startup from './startup.json';import update from './update.json';export default {+ mcpApps,plugins,taskTags,remoteDesktop,diff --git a/apps/mobile/src/i18n/locales/zh-TW/mcpApps.json b/apps/mobile/src/i18n/locales/zh-TW/mcpApps.jsonnew file mode 100644index 0000000000..d0a94e2839--- /dev/null+++ b/apps/mobile/src/i18n/locales/zh-TW/mcpApps.json@@ -0,0 +1,12 @@+{+ "sharedTaskReadOnly": "此卡片僅任務擁有者可操作。",+ "retry": "重新載入",+ "loadFailed": "應用程式載入失敗。請檢查連線後重新載入。",+ "updateRequired": "這台電腦尚不支援 MCP Apps,請更新電腦上的 Cindy 後再試。",+ "appName": "MCP App",+ "cardTitle": "{{title}} · $t(mcpApps.appName)",+ "messageSource": "由 $t(mcpApps.appName)「{{name}}」傳送",+ "serverId": "MCP 伺服器 ID:{{id}}",+ "exitFullscreen": "離開全螢幕",+ "mobileUpdateRequired": "請更新手機上的 Cindy 後再開啟此卡片。"+}diff --git a/apps/mobile/src/session/McpAppCard.tsx b/apps/mobile/src/session/McpAppCard.tsxnew file mode 100644index 0000000000..b119001840--- /dev/null+++ b/apps/mobile/src/session/McpAppCard.tsx@@ -0,0 +1,107 @@+import { useEffect, useMemo, useRef, useState } from 'react';+import { ActivityIndicator, Pressable, StyleSheet, View } from 'react-native';+import { useTranslation } from 'react-i18next';+import { isSharedTaskPeer } from '@cindy/device-link';+import { Text } from '@/components/AppText';+import { useTheme, textStyles, fontWeight, radius, spacing } from '@/theme';+import { useMcpAppViews, NativeMcpAppSlot, mcpAppSurfaceAvailable } from './McpAppViews';+import type { McpAppView, McpAppViewState } from './mcpAppView';++interface McpAppCardProps {+ deviceId?: string; sessionId: string; clientId: string; title: string; active?: boolean; fallbackText?: string;+}+export function McpAppCard(props: McpAppCardProps) {+ const { colors } = useTheme();+ const { t } = useTranslation();+ if (isSharedTaskPeer(props.deviceId)) return (+ <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}>+ <View style={styles.header}>+ <Text style={[styles.title, { color: colors.textPrimary }]}>+ {props.title ? t('mcpApps.cardTitle', { title: props.title }) : t('mcpApps.appName')}+ </Text>+ </View>+ {props.fallbackText ? <Text selectable style={[styles.historyText, { color: colors.textPrimary }]}>{props.fallbackText}</Text> : null}+ <Text style={[styles.error, { color: colors.textSecondary }]}>{t('mcpApps.sharedTaskReadOnly')}</Text>+ </View>+ );+ return <InteractiveMcpAppCard {...props} />;+}++function InteractiveMcpAppCard({ deviceId, sessionId, clientId, title, active = true, fallbackText }: McpAppCardProps) {+ const host = useMcpAppViews();+ const { colors, mode } = useTheme();+ const { t, i18n } = useTranslation();+ const [attempt, setAttempt] = useState(0);+ const [view, setView] = useState<McpAppView>();+ const [state, setState] = useState<McpAppViewState>({ loading: true, height: 320 });+ const width = useRef(1);+ const context = useMemo(() => ({+ platform: 'mobile', theme: mode, locale: i18n.resolvedLanguage ?? i18n.language,+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,+ deviceCapabilities: { touch: true, hover: false }, containerDimensions: { maxHeight: 1_200 },+ styles: { variables: {+ '--color-background-primary': colors.surface, '--color-background-secondary': colors.surfaceElevated,+ '--color-text-primary': colors.textPrimary, '--color-text-secondary': colors.textSecondary,+ '--color-text-tertiary': colors.textTertiary, '--color-border-primary': colors.border, '--font-sans': 'system-ui, sans-serif',+ } },+ }), [mode, colors, i18n.resolvedLanguage, i18n.language]);+ const contextRef = useRef(context);+ contextRef.current = context;+ const foreground = host?.foreground ?? false;+ const open = host?.open;+ const hasHost = !!host;+ useEffect(() => {+ setView(undefined);+ if (!active || (hasHost && !foreground)) {+ setState((previous) => ({ height: previous.height, loading: false }));+ return;+ }+ if (!mcpAppSurfaceAvailable || !open) {+ setState((previous) => ({ ...previous, loading: false, error: 'mcpApps.mobileUpdateRequired' }));+ return;+ }+ if (!deviceId) {+ setState((previous) => ({ ...previous, loading: false, error: 'mcpApps.loadFailed' }));+ return;+ }+ const current = open(deviceId, sessionId, clientId, contextRef.current);+ current.setWidth(width.current);+ setView(current);+ const unsubscribe = current.subscribe(setState);+ return () => {+ unsubscribe();+ // The persistent host owns the live WebView, including after this actual+ // card/route unmount. Its close() removes that same View only at the bound.+ void current.close();+ };+ }, [open, hasHost, foreground, deviceId, sessionId, clientId, attempt, active]);+ useEffect(() => { if (!view?.closing) void view?.controller.context(context).catch(() => {}); }, [view, context]);+ const { error, loading, height } = state;+ return (+ <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}>+ <View style={styles.header}>+ <Text style={[styles.title, { color: colors.textPrimary }]}>{title ? t('mcpApps.cardTitle', { title }) : t('mcpApps.appName')}</Text>+ {active && loading && <ActivityIndicator size="small" color={colors.textSecondary} />}+ {error && <Pressable accessibilityRole="button" onPress={() => setAttempt((value) => value + 1)} style={styles.retry}>+ <Text style={[styles.action, { color: colors.textPrimary }]}>{t('mcpApps.retry')}</Text>+ </Pressable>}+ </View>+ {error && <Text style={[styles.error, { color: colors.textSecondary }]}>{t(error)}</Text>}+ {error && fallbackText ? <Text selectable style={[styles.historyText, { color: colors.textPrimary }]}>{fallbackText}</Text> : null}+ {!error && <View style={{ height }} onLayout={(event) => {+ width.current = event.nativeEvent.layout.width; view?.setWidth(width.current);+ }}>+ {active && foreground && view && NativeMcpAppSlot ? <NativeMcpAppSlot surfaceId={view.id} style={{ flex: 1 }} /> : null}+ </View>}+ </View>+ );+}+const styles = StyleSheet.create({+ card: { borderWidth: StyleSheet.hairlineWidth, borderRadius: radius.container, overflow: 'hidden', marginVertical: spacing.sm },+ header: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: spacing.md, paddingVertical: spacing.sm },+ title: { ...textStyles.subtitle, fontWeight: fontWeight.medium, flex: 1 },+ action: { ...textStyles.body, fontWeight: fontWeight.medium },+ error: { ...textStyles.footnote, paddingHorizontal: spacing.md, paddingBottom: spacing.md },+ historyText: { ...textStyles.bodyLarge, paddingHorizontal: spacing.md, paddingBottom: spacing.md },+ retry: { minHeight: 44, minWidth: 44, alignItems: 'center', justifyContent: 'center' },+});diff --git a/apps/mobile/src/session/McpAppViews.tsx b/apps/mobile/src/session/McpAppViews.tsxnew file mode 100644index 0000000000..4ba1264e7f--- /dev/null+++ b/apps/mobile/src/session/McpAppViews.tsx@@ -0,0 +1,94 @@+import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';+import { AppState, Linking, Platform, StyleSheet, View } from 'react-native';+import { WebView } from 'react-native-webview';+import { mcpAppFrameUrlAllowed } from '@cindy/maker-shared/mcp-apps';+import { useDeviceLink } from '@/device-link/DeviceLinkContext';+import { useTheme } from '@/theme';+import { NativeMcpAppHost, NativeMcpAppSlot, mcpAppSurfaceAvailable } from './NativeMcpAppSurface';+import { McpAppView } from './mcpAppView';++const Context = createContext<{+ foreground: boolean;+ open(deviceId: string, sessionId: string, clientId: string, context: Record<string, unknown>): McpAppView;+} | null>(null);+export const useMcpAppViews = () => useContext(Context);+export { NativeMcpAppSlot, mcpAppSurfaceAvailable };++/** Hosts stay at the app root; native slots place their content inline inside+ * the real navigation screen. No root overlay, coordinates or touch interception. */+export function McpAppViewsProvider({ children }: { children: ReactNode }) {+ const { invoke } = useDeviceLink();+ const views = useRef(new Set<McpAppView>());+ const mounted = useRef(true);+ const [, refresh] = useState(0);+ const [foreground, setForeground] = useState(AppState.currentState !== 'background' && AppState.currentState !== 'inactive');+ const changed = useCallback(() => { if (mounted.current) refresh((n) => n + 1); }, []);+ const open = useCallback((deviceId: string, sessionId: string, clientId: string, context: Record<string, unknown>) => {+ const view = new McpAppView(invoke, deviceId, sessionId, clientId, changed,+ () => { views.current.delete(view); changed(); }, async (url) => {+ const parsed = new URL(url);+ if (!['https:', 'http:'].includes(parsed.protocol) || parsed.username || parsed.password)+ throw new Error('MCP_APP_INVALID_LINK');+ await Linking.openURL(parsed.href);+ });+ views.current.add(view);+ changed();+ void view.open(context);+ return view;+ }, [invoke, changed]);+ useEffect(() => {+ mounted.current = true;+ const subscription = AppState.addEventListener('change', (state) => {+ const active = state === 'active';+ if (!active) for (const view of views.current) void view.close();+ setForeground(active);+ });+ return () => {+ mounted.current = false;+ subscription.remove();+ for (const view of views.current) void view.close();+ };+ }, []);+ const value = useMemo(() => ({ foreground, open }), [foreground, open]);+ const Host = NativeMcpAppHost;+ const hosted = Host ? [...views.current].map((view) => <Host key={view.id} surfaceId={view.id}+ pointerEvents="none" accessibilityElementsHidden importantForAccessibility="no-hide-descendants"+ style={{ position: 'absolute', left: -100_000, top: 0, width: view.width, height: view.state.height }}>+ <McpAppWebView view={view} />+ </Host>) : null;+ return <Context.Provider value={value}>+ <View style={styles.root}>+ {children}+ {hosted}+ </View>+ </Context.Provider>;+}++function McpAppWebView({ view }: { view: McpAppView }) {+ const { colors } = useTheme();+ const { document, nativeDocument } = view;+ const bind = useCallback((webview: WebView | null) => {+ view.inject = webview ? (script) => webview.injectJavaScript(script) : undefined;+ }, [view]);+ if (!document || !nativeDocument) return null;+ return <WebView ref={bind} source={nativeDocument.source}+ style={{ height: view.state.height, backgroundColor: colors.surface }}+ originWhitelist={['*']} allowFileAccess={false} allowUniversalAccessFromFileURLs={false}+ sharedCookiesEnabled={false} thirdPartyCookiesEnabled={false}+ incognito={Platform.OS === 'ios'} cacheEnabled={false} domStorageEnabled+ // A different loopback origin per View isolates web storage. Android's+ // incognito prop clears the process-wide cookie jar, breaking other Apps.+ javaScriptCanOpenWindowsAutomatically={false} setSupportMultipleWindows+ allowsInlineMediaPlayback={false} mediaPlaybackRequiresUserAction+ onShouldStartLoadWithRequest={(request) => {+ if (nativeDocument.documentUrls.slice(0, 2).includes(request.url)) return true;+ return request.isTopFrame !== true && (nativeDocument.documentUrls.includes(request.url) ||+ mcpAppFrameUrlAllowed(request.url, document.policy?.frameDomains));+ }}+ onMessage={(event) => view.receive(event.nativeEvent.data)}+ onError={() => view.fail(new Error('MCP_APP_LOAD_FAILED'))}+ onContentProcessDidTerminate={() => view.fail(new Error('MCP_APP_PROCESS_TERMINATED'))}+ onRenderProcessGone={() => view.fail(new Error('MCP_APP_PROCESS_TERMINATED'))}+ />;+}+const styles = StyleSheet.create({ root: { flex: 1 } });diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex 3086c64561..b4118ef1b3 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -1,4 +1,5 @@import { PluginCardActions } from '@/plugins/PluginCardActions';+import { McpAppCard } from './McpAppCard';import { RichContentContext } from './richContentContext';import { RichContentRuntime } from './richContentRuntime';import { MessageListVisibility, MessageListVisibilityContext, useMessageListItemVisible } from './messageListVisibility';@@ -3272,13 +3273,13 @@ function SourceDeviceLabel({/** 插件任务派发的消息:气泡外的来源标签;与气泡内的本轮插件调用头(PluginInvocationHeader)是两回事。 */function SourcePluginLabel({ align, plugin }: { align: 'user' | 'agent'; plugin: MessageSourcePlugin }) {const { colors } = useTheme();- const { t, i18n: i18nInstance } = useTranslation();+ const { i18n: i18nInstance } = useTranslation();const label = useMemo(() => sourcePluginLabel(plugin), [plugin, i18nInstance.language]);return (<SourceLabelWithIdalign={align}icon={<Ghost color={colors.textTertiary} size={iconSize.xs} strokeWidth={iconStroke.thin} />}- idText={t('message.renderer.sourcePluginId', { id: plugin.pluginId })}+ idText={sourceIdText({ sourcePlugin: plugin })}label={label}testID="message.sourcePlugin"/>@@ -3817,7 +3818,11 @@ function MessageBubble({) : null}</View>) : null}- {item.message.systemCardType ? (+ {item.message.systemCardType === 'mcp-app' ? (+ <ViewabilityGatedMcpAppCard deviceId={actions.remoteDeviceId} sessionId={item.message.source.sessionId}+ clientId={item.message.source.clientId} title={String(item.message.systemCardData?.title ?? '')}+ fallbackText={String(item.message.systemCardData?.fallbackText ?? '')} />+ ) : item.message.systemCardType ? (<MobileSystemCardautoResumeInFlight={isMobileAutoResumeRowInFlight({isContinuationTurnOwner: clientId === actions.continuationTurnClientId,@@ -5614,6 +5619,13 @@ function OrcaCollabCard({ card, screenWidth, blockKey }: {);}+const ViewabilityGatedMcpAppCard = memo(function ViewabilityGatedMcpAppCard(+ props: Omit<ComponentProps<typeof McpAppCard>, 'active'>,+) {+ const heavyContentVisible = useContext(MessageHeavyContentVisibilityContext);+ return <McpAppCard {...props} active={heavyContentVisible} />;+});+const ViewabilityGatedMermaidDiagram = memo(function ViewabilityGatedMermaidDiagram({source,testID,diff --git a/apps/mobile/src/session/NativeMcpAppSurface.tsx b/apps/mobile/src/session/NativeMcpAppSurface.tsxnew file mode 100644index 0000000000..4aba02fedc--- /dev/null+++ b/apps/mobile/src/session/NativeMcpAppSurface.tsx@@ -0,0 +1,12 @@+import type { ViewProps } from 'react-native';+import { requireNativeViewManager } from 'expo-modules-core';+import native from '../../modules/cindy-html-preview/src/CindyHtmlPreviewModule';++// Old binaries can still show the saved text; never load a half-compatible+// interactive View or fall back to same-origin/opaque srcdoc.+export const mcpAppSurfaceAvailable = !!native?.appHostAvailable && !!native.startApp;+type Props = ViewProps & { surfaceId: string };+export const NativeMcpAppHost = mcpAppSurfaceAvailable+ ? requireNativeViewManager<Props>('CindyHtmlPreview', 'AppHost') : null;+export const NativeMcpAppSlot = mcpAppSurfaceAvailable+ ? requireNativeViewManager<Props>('CindyHtmlPreview', 'AppSlot') : null;diff --git a/apps/mobile/src/session/mcpAppNativeDocument.ts b/apps/mobile/src/session/mcpAppNativeDocument.tsnew file mode 100644index 0000000000..edbc59d829--- /dev/null+++ b/apps/mobile/src/session/mcpAppNativeDocument.ts@@ -0,0 +1,124 @@+import { Directory, File, Paths } from "expo-file-system";+import { getRandomBytes } from "expo-crypto";+import {+ mcpAppSandboxDocument,+ type McpAppDocument,+} from "@cindy/maker-shared/mcp-apps";+import native from "../../modules/cindy-html-preview/src/CindyHtmlPreviewModule";++export interface McpAppNativeDocument {+ source: { uri: string };+ resourceUrl: string;+ documentUrls: readonly string[];+ close(): Promise<void>;+}+let swept = false;++// Android's WebStorage.deleteOrigin does not clear localStorage and has no+// completion callback. Run in the new App origin, before any untrusted HTML,+// and do not navigate to that HTML until IndexedDB deletion has completed.+export const MCP_APP_STORAGE_BOOTSTRAP = `<!doctype html><meta charset="utf-8"><script>+(async()=>{+ localStorage.clear();+ sessionStorage.clear();+ const databases=await indexedDB.databases();+ await Promise.all(databases.map(({name})=>new Promise((resolve,reject)=>{+ if(typeof name!=='string'){resolve();return;}+ const request=indexedDB.deleteDatabase(name);+ request.onsuccess=()=>resolve();+ request.onerror=request.onblocked=()=>reject(new Error('MCP_APP_STORAGE_RESET_FAILED'));+ })));+ location.replace('/resource.html');+})().catch(()=>{});+</script>`;++/** Reuse the installed loopback server; different ports give proxy and App distinct origins. */+export async function prepareMcpAppNativeDocument(+ document: McpAppDocument,+ bridgeKey: string,+): Promise<McpAppNativeDocument> {+ if (!native?.appHostAvailable || !native.startApp) throw new Error("MCP_APP_NATIVE_UPDATE_REQUIRED");+ const server = native;+ const start = native.startApp.bind(native);+ if (!swept) {+ swept = true;+ const parent = new Directory(Paths.cache, "mcp-apps");+ if (parent.exists) {+ for (const child of parent.list()) {+ if (child instanceof Directory && /^[a-f0-9]{48}$/.test(child.name)) {+ try {+ child.delete();+ } catch {+ /* OS cache eviction remains the fallback. */+ }+ }+ }+ }+ }+ const token = () =>+ Array.from(getRandomBytes(24), (byte) =>+ byte.toString(16).padStart(2, "0"),+ ).join("");+ const resourceToken = token();+ const proxyToken = token();+ const directory = new Directory(Paths.cache, "mcp-apps", resourceToken);+ directory.create({ intermediates: true });+ const root = decodeURIComponent(directory.uri.slice("file://".length));+ const started: string[] = [];+ let closing: Promise<void> | undefined;+ const close = () =>+ (closing ??= (async () => {+ try {+ const stopped = await Promise.allSettled(+ started.map((value) => server.stop(value)),+ );+ const failed = stopped.find((result) => result.status === "rejected");+ if (failed?.status === "rejected") throw failed.reason;+ } finally {+ if (directory.exists) directory.delete();+ }+ })());+ try {+ const resource = new File(directory, "0");+ resource.create();+ resource.write(document.html);+ const bootstrap = new File(directory, "2");+ bootstrap.create();+ bootstrap.write(MCP_APP_STORAGE_BOOTSTRAP);+ started.push(resourceToken);+ const resourceUrl = await start(+ root,+ "initialize.html",+ resourceToken,+ document.csp,+ [["initialize.html", "2", "text/html"], ["resource.html", "0", "text/html"]],+ );+ const resourceOrigin = new URL(resourceUrl).origin;+ const proxy = new File(directory, "1");+ proxy.create();+ proxy.write(mcpAppSandboxDocument(bridgeKey, resourceUrl));+ const csp = `default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; frame-src ${resourceOrigin}; connect-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'`;+ started.push(proxyToken);+ const proxyUrl = await start(root, "proxy.html", proxyToken, csp, [+ ["proxy.html", "1", "text/html"],+ ]);+ if (new URL(proxyUrl).origin === resourceOrigin)+ throw new Error("MCP_APP_INVALID_ORIGIN");+ return {+ source: { uri: proxyUrl },+ resourceUrl,+ // Each server bootstraps its HttpOnly cookie then redirects to its one manifest entry.+ documentUrls: [+ proxyUrl,+ new URL("/proxy.html", proxyUrl).href,+ resourceUrl,+ new URL("/initialize.html", resourceUrl).href,+ new URL("/resource.html", resourceUrl).href,+ ],+ close,+ };+ } catch (error) {+ await close().catch(() => {});+ throw error;+ }+}diff --git a/apps/mobile/src/session/mcpAppView.ts b/apps/mobile/src/session/mcpAppView.tsnew file mode 100644index 0000000000..83e40a7637--- /dev/null+++ b/apps/mobile/src/session/mcpAppView.ts@@ -0,0 +1,119 @@+import { getRandomBytes } from 'expo-crypto';+import { McpAppController, mcpAppFailureKey, type AppRpc } from '@cindy/maker-shared/mcp-app-controller';+import { MCP_APPS_INVOKE, type McpAppDocument } from '@cindy/maker-shared/mcp-apps';+import { prepareMcpAppNativeDocument, type McpAppNativeDocument } from './mcpAppNativeDocument';++export interface McpAppViewState {+ loading: boolean;+ height: number;+ error?: ReturnType<typeof mcpAppFailureKey> | 'mcpApps.mobileUpdateRequired';+}+type Invoke = (device: string, channel: string, args: unknown[]) => Promise<unknown>;++/** Owned by the persistent native host, not by a virtualized message/route. */+export class McpAppView {+ readonly id = Array.from(getRandomBytes(24), (byte) => byte.toString(16).padStart(2, '0')).join('');+ readonly bridgeKey = Array.from(getRandomBytes(24), (byte) => byte.toString(16).padStart(2, '0')).join('');+ readonly controller: McpAppController;+ document?: McpAppDocument;+ nativeDocument?: McpAppNativeDocument;+ width = 1;+ state: McpAppViewState = { loading: true, height: 320 };+ closing = false;+ disposed = false;+ inject?: (script: string) => void;+ private listeners = new Set<(state: McpAppViewState) => void>();+ private closePromise?: Promise<void>;++ constructor(+ invoke: Invoke, deviceId: string, sessionId: string, clientId: string,+ private readonly changed: () => void,+ private readonly removed: () => void,+ openLink: (url: string) => Promise<void>,+ ) {+ this.controller = new McpAppController(+ (id, input) => invoke(deviceId, MCP_APPS_INVOKE, [id, input]), sessionId, clientId,+ (message) => {+ if (this.disposed) return;+ const serialized = JSON.stringify(JSON.stringify(message)).replace(/</g, '\\u003c');+ this.inject?.(`window.dispatchEvent(new MessageEvent('message',{data:JSON.parse(${serialized}),source:window}));true;`);+ },+ (message) => {+ if (this.closing) return;+ if (message.method === 'ui/notifications/initialized') this.update({ loading: false });+ if (message.method === 'ui/notifications/size-changed' &&+ typeof message.params?.height === 'number' && Number.isFinite(message.params.height))+ this.update({ height: Math.max(80, Math.min(1_200, Math.ceil(message.params.height))) });+ },+ (error) => this.fail(error), openLink,+ );+ }++ subscribe(listener: (state: McpAppViewState) => void): () => void {+ this.listeners.add(listener);+ listener(this.state);+ return () => { this.listeners.delete(listener); };+ }+ setWidth(width: number): void {+ if (Number.isFinite(width) && width > 0 && width !== this.width && !this.disposed) {+ this.width = width;+ this.changed();+ }+ }+ private update(value: Partial<McpAppViewState>): void {+ if (this.disposed) return;+ this.state = { ...this.state, ...value };+ this.listeners.forEach((listener) => listener(this.state));+ this.changed();+ }+ async open(context: Record<string, unknown>): Promise<void> {+ try {+ const document = await this.controller.open(context);+ if (!document || this.closing) return;+ if (document.transport === 'sandbox') throw new Error('MCP_APP_INVALID_DOCUMENT');+ const nativeDocument = await prepareMcpAppNativeDocument(document, this.bridgeKey);+ if (this.closing) { await nativeDocument.close(); return; }+ this.document = document;+ this.nativeDocument = nativeDocument;+ this.changed();+ } catch (error) { if (!this.closing) this.fail(error); }+ }+ receive(data: string): void {+ if (this.disposed) return;+ try {+ const envelope = JSON.parse(data) as { key?: string; message: AppRpc };+ if (envelope.key !== this.bridgeKey) return;+ if (envelope.message.method === 'ui/notifications/sandbox-proxy-ready')+ this.controller.sandboxReady(this.nativeDocument?.resourceUrl);+ else this.controller.receive(envelope.message);+ } catch { this.fail(new Error('MCP_APP_INVALID_MESSAGE')); }+ }+ fail(error: unknown): void {+ if (this.closing) return;+ this.update({ loading: false, error: /MCP_APP_NATIVE_UPDATE_REQUIRED/.test(String(error))+ ? 'mcpApps.mobileUpdateRequired' : mcpAppFailureKey(error) });+ void this.close();+ }+ close(): Promise<void> {+ return this.closePromise ??= this.closeView();+ }+ private async closeView(): Promise<void> {+ this.closing = true;+ // Keep the same root-owned WebView and its callback alive. No RPC/HTTP+ // teardown completion can extend the native disposal deadline indefinitely.+ let timer: ReturnType<typeof setTimeout> | undefined;+ const deadline = new Promise<void>((resolve) => { timer = setTimeout(resolve, 1_000); });+ this.controller.prepareNativeClose();+ this.changed();+ try {+ await Promise.race([this.controller.close().catch(() => {}), deadline]);+ } finally {+ clearTimeout(timer);+ this.disposed = true;+ this.inject = undefined;+ this.listeners.clear();+ this.removed();+ await this.nativeDocument?.close().catch(() => {});+ }+ }+}diff --git a/apps/mobile/src/session/messageNormalize.ts b/apps/mobile/src/session/messageNormalize.tsindex bd3dec8b64..b22e6f463a 100644--- a/apps/mobile/src/session/messageNormalize.ts+++ b/apps/mobile/src/session/messageNormalize.ts@@ -1,4 +1,5 @@import { formatDuration } from '@cindy/maker-shared/message-render';+import { parseMcpAppHistory } from '@cindy/maker-shared/mcp-apps';import { collectPluginInvocations, type PluginInvocation } from './pluginInvocations';import { extractPayloadToolResultFiles, extractPayloadToolCardIds, type PayloadToolFile } from '@cindy/maker-shared/payload-summary';import { placeBotTaskCardsAfterIntroduction, readBotCollaborationMeta, type BotCollaborationMeta } from '@cindy/maker-shared/botCollaboration';@@ -290,6 +291,13 @@ export function normalizeRemoteMessages(for (const message of sorted) {if (message.role === 'tool_result') continue;if (message.role === 'assistant') {+ const app = message.agentMeta?.mcpApp === true ? parseMcpAppHistory(message.content) : undefined;+ if (app) {+ result.push({ key: messageNormalizeKey(message), source: message, kind: 'system', role: message.role,+ label: 'system:mcp-app', body: '', systemCardType: 'mcp-app',+ systemCardData: { title: app.title, fallbackText: app.text }, align: 'agent', createdAt: message.createdAt });+ continue;+ }const authorization = readRecord(message.agentMeta?.botAuthorization);const snapshot = readRecord(authorization?.snapshot);if (authorization?.v === 1 && authorization.sessionId === message.sessionId && snapshot?.kind === 'plugin_setup') {diff --git a/apps/mobile/src/session/messageSourceLabels.ts b/apps/mobile/src/session/messageSourceLabels.tsindex 84f8c06bd3..258b14feeb 100644--- a/apps/mobile/src/session/messageSourceLabels.ts+++ b/apps/mobile/src/session/messageSourceLabels.ts@@ -111,6 +111,11 @@ export function isSourceDeviceRemoved(}export function sourcePluginLabel(plugin: MessageSourcePlugin): string {+ if (plugin.pluginId.startsWith('mcp-app:')) {+ return i18n.t('mcpApps.messageSource', {+ name: plugin.name ?? plugin.pluginId.slice(8),+ });+ }return plugin.name? i18n.t("message.renderer.sourcePluginNamed", { name: plugin.name }): i18n.t("message.renderer.sourcePlugin");@@ -157,6 +162,7 @@ export function orcaMessageTitle(const SOURCE_ID_I18N_KEYS: Record<MessageSourceIdKind, string> = {plugin: "message.renderer.sourcePluginId",+ mcpApp: "mcpApps.serverId",teammate: "message.renderer.sourceTeammateId",session: "message.renderer.sourceSessionId",automation: "message.renderer.sourceAutomationId",diff --git a/apps/mobile/src/session/systemCard.ts b/apps/mobile/src/session/systemCard.tsindex 199039f8bd..f7f499e176 100644--- a/apps/mobile/src/session/systemCard.ts+++ b/apps/mobile/src/session/systemCard.ts@@ -36,7 +36,8 @@ export type MobileSystemCardType =// session-agent-switch 边界卡(desktop 落库 role='agent_switch',读侧派生)。| 'agent-switch'// 代输入结束留痕(隐藏续接行派生)。- | 'input-handoff';+ | 'input-handoff'+ | 'mcp-app';export type MobileSystemCardPresentation = SystemCardPresentation;/** goal 达成记录文案(对齐桌面 GoalCompleteCard 的 goal.complete.record)。 */@@ -104,7 +105,7 @@ export function buildMobileSystemCardData(): Record<string, unknown> {// goal / auto-resume / agent-switch 卡的数据由桌面落库行派生,learn 卡的数据由// 发送侧 buildLearnCardData 直接组装,都不走本地 slash 命令的数据组装。- if (type === 'goal-complete' || type === 'goal-resumed' || type === 'context-rebuild' || type === 'auto-resume' || type === 'learn' || type === 'agent-switch' || type === 'input-handoff') return {};+ if (type === 'goal-complete' || type === 'goal-resumed' || type === 'context-rebuild' || type === 'auto-resume' || type === 'learn' || type === 'agent-switch' || type === 'input-handoff' || type === 'mcp-app') return {};return buildSystemCardData(type, {...options,localCommands: MOBILE_LOCAL_SYSTEM_COMMANDS,@@ -135,7 +136,7 @@ export function formatMobileSystemCard(if (type === 'agent-switch') return formatAgentSwitchCard(data);if (type === 'learn') return formatLearnCard(data);// 代输入留痕由 InputHandoffRecordRow 渲染,不走通用卡片。- if (type === 'input-handoff') return { title: '', rows: [] };+ if (type === 'input-handoff' || type === 'mcp-app') return { title: '', rows: [] };return formatSystemCard(type, data);}diff --git a/apps/mobile/src/session/types.ts b/apps/mobile/src/session/types.tsindex 0325fc2f93..8b1d733927 100644--- a/apps/mobile/src/session/types.ts+++ b/apps/mobile/src/session/types.ts@@ -148,7 +148,8 @@ export interface RemoteMessage {systemCardType?:| 'help' | 'context' | 'cost' | 'pwd' | 'status' | 'compact' | 'cmd' | 'goal-complete' | 'goal-resumed' | 'context-rebuild' | 'auto-resume' | 'learn' | 'agent-switch'/** 代输入结束留痕(由隐藏续接行派生,无输入值)。 */- | 'input-handoff';+ | 'input-handoff'+ | 'mcp-app';}export type RemoteAttachmentCategory = 'image' | 'pdf' | 'text' | 'office' | 'file';diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.mdindex 3bd150bfde..293ac8caea 100644--- a/docs/design-rules/design-inventory.md+++ b/docs/design-rules/design-inventory.md@@ -18,12 +18,12 @@| `desktop.auth.add-account` | desktop | 添加账号 | hash `/add-account`(ProtectedRoute → AddAccountLoginPage) | AddAccountLoginPage | apps/desktop/src/renderer/components/login/AddAccountLoginPage.tsx, apps/desktop/src/renderer/components/login/LoginBrandStage.tsx, apps/desktop/src/renderer/components/login/LoginCaptchaOverlay.tsx, apps/desktop/src/renderer/components/login/LoginControls.tsx, apps/desktop/src/renderer/components/login/LoginPage.tsx, apps/desktop/src/renderer/components/login/loginDesignTokens.ts | 59 | 0 | 20 || `desktop.auth.legacy-migration` | desktop | 首登数据迁移弹窗 | App 顶层挂载 LegacyMigrationDialog(仅主窗;main 检测到旧版 userData 经 `legacy-migration:state` 驱动) | LegacyMigrationDialog | apps/desktop/src/renderer/components/auth/LegacyMigrationDialog.tsx | 8 | 0 | 2 || `desktop.auth.login` | desktop | 登录页 | hash `/login`(GuestRoute → LoginPage) | LoginBrandStage, LoginCaptchaOverlay, LoginControls, LoginPage | apps/desktop/src/renderer/components/login/LoginBrandStage.tsx, apps/desktop/src/renderer/components/login/LoginCaptchaOverlay.tsx, apps/desktop/src/renderer/components/login/LoginControls.tsx, apps/desktop/src/renderer/components/login/LoginPage.tsx, apps/desktop/src/renderer/components/login/loginDesignTokens.ts | 59 | 0 | 20 |-| `desktop.bots` | desktop | 伙伴(列表 / 对话 / 设置 / 历史 / 伙伴私聊 / 群聊) | hash `/bots`、`/bots/list`、`/bots/:botId`、`/bots/roster` 及伙伴当前/历史任务、伙伴私聊、伙伴群聊路由(BotsFeatureLayout) | BotBasicProfileFields, BotCollaborationCard, BotDirectMessageView, BotGroupChatView, BotGroupCreateDialog, BotGroupSettingsDrawer, BotHistorySessionView, BotLifecycleSettings, BotModelChainEditor, BotRosterView, BotSessionView, BotSettingsDrawer, BotsHomeView, BotsListView, RemoteBotSessionView | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentOnOtherDeviceContext.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AgentTaskLiveDetails.tsx, apps/desktop/src/renderer/components/chat/AnnotationStrokesSvg.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatLoadingImage.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/MessageViewport.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/animateFocusScroll.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/markdownMedia.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageNavigationProjection.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageViewportGeometry.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/observeProgrammaticScroll.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeHighlightShared.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useImageClipboard.ts, apps/desktop/src/renderer/components/chat/useImageLoadFailure.ts, apps/desktop/src/renderer/components/chat/useMessageViewport.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerAttachments.tsx, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/LocalModelCatalogNotice.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupRemoteDesktopButton.tsx, apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/bots/BotAddToGroupMenu.tsx, apps/desktop/src/renderer/features/bots/BotAuthorizationCard.tsx, apps/desktop/src/renderer/features/bots/BotAvatar.tsx, apps/desktop/src/renderer/features/bots/BotBasicProfileFields.tsx, apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx, apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx, apps/desktop/src/renderer/features/bots/BotConnectionStatus.tsx, apps/desktop/src/renderer/features/bots/BotCreateMenu.tsx, apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx, apps/desktop/src/renderer/features/bots/BotFollowMark.tsx, apps/desktop/src/renderer/features/bots/BotGenerationLabel.tsx, apps/desktop/src/renderer/features/bots/BotGroupAvatars.tsx, apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx, apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx, apps/desktop/src/renderer/features/bots/BotGroupCreateDialog.tsx, apps/desktop/src/renderer/features/bots/BotGroupMessageAttachments.tsx, apps/desktop/src/renderer/features/bots/BotGroupPendingInteraction.tsx, apps/desktop/src/renderer/features/bots/BotGroupPlan.tsx, apps/desktop/src/renderer/features/bots/BotGroupQuote.tsx, apps/desktop/src/renderer/features/bots/BotGroupRuntimeFailureNotice.tsx, apps/desktop/src/renderer/features/bots/BotGroupSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx, apps/desktop/src/renderer/features/bots/BotGroupTaskCard.tsx, apps/desktop/src/renderer/features/bots/BotGroupThreadViews.tsx, apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx, apps/desktop/src/renderer/features/bots/BotHomeComputerSetting.tsx, apps/desktop/src/renderer/features/bots/BotImportForm.tsx, apps/desktop/src/renderer/features/bots/BotInvitationWelcome.tsx, apps/desktop/src/renderer/features/bots/BotLearningFooter.tsx, apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx, apps/desktop/src/renderer/features/bots/BotMemorySettings.tsx, apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx, apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsx, apps/desktop/src/renderer/features/bots/BotRosterView.tsx, apps/desktop/src/renderer/features/bots/BotRoutines.tsx, apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx, apps/desktop/src/renderer/features/bots/BotSessionTaskLink.tsx, apps/desktop/src/renderer/features/bots/BotSessionTaskResultCard.tsx, apps/desktop/src/renderer/features/bots/BotSessionView.tsx, apps/desktop/src/renderer/features/bots/BotSettingsBlock.tsx, apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotTaskCardHeader.tsx, apps/desktop/src/renderer/features/bots/BotTaskModelEditor.tsx, apps/desktop/src/renderer/features/bots/BotTodoList.tsx, apps/desktop/src/renderer/features/bots/BotWorkbench.tsx, apps/desktop/src/renderer/features/bots/BotWorkingStatus.tsx, apps/desktop/src/renderer/features/bots/BotsFeatureLayout.tsx, apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx, apps/desktop/src/renderer/features/bots/BotsHomeView.tsx, apps/desktop/src/renderer/features/bots/BotsListView.tsx, apps/desktop/src/renderer/features/bots/ChatBotAccessField.tsx, apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx, apps/desktop/src/renderer/features/bots/ChatInviteDialog.tsx, apps/desktop/src/renderer/features/bots/ChatInviteHost.tsx, apps/desktop/src/renderer/features/bots/ChatReactionButton.tsx, apps/desktop/src/renderer/features/bots/ChatServerControls.tsx, apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx, apps/desktop/src/renderer/features/bots/CindyDevicePicker.tsx, apps/desktop/src/renderer/features/bots/CindyDeviceRow.tsx, apps/desktop/src/renderer/features/bots/CloudCompanionOfflineView.tsx, apps/desktop/src/renderer/features/bots/CompanionShadowBanner.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSettings.tsx, apps/desktop/src/renderer/features/bots/RemoveChatFromListButton.tsx, apps/desktop/src/renderer/features/bots/TeammateSearchResults.tsx, apps/desktop/src/renderer/features/bots/TeammatesSection.tsx, apps/desktop/src/renderer/features/bots/WorkbenchSessionList.tsx, apps/desktop/src/renderer/features/bots/botAvatarIdentity.ts, apps/desktop/src/renderer/features/bots/botCapabilityDefaults.ts, apps/desktop/src/renderer/features/bots/botChatPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationTimeline.ts, apps/desktop/src/renderer/features/bots/botDelegationLive.ts, apps/desktop/src/renderer/features/bots/botFollowScopes.ts, apps/desktop/src/renderer/features/bots/botGeneratedArtifacts.ts, apps/desktop/src/renderer/features/bots/botGroupAttachments.ts, apps/desktop/src/renderer/features/bots/botGroupComposerChrome.ts, apps/desktop/src/renderer/features/bots/botGroupLane.ts, apps/desktop/src/renderer/features/bots/botGroupMentions.ts, apps/desktop/src/renderer/features/bots/botGroupOutbox.ts, apps/desktop/src/renderer/features/bots/botGroupPresentation.ts, apps/desktop/src/renderer/features/bots/botGroupStore.ts, apps/desktop/src/renderer/features/bots/botListDisplay.ts, apps/desktop/src/renderer/features/bots/botNavigation.ts, apps/desktop/src/renderer/features/bots/botPronounContext.tsx, apps/desktop/src/renderer/features/bots/botReadState.ts, apps/desktop/src/renderer/features/bots/botRosterDisplay.ts, apps/desktop/src/renderer/features/bots/botSessionOwners.ts, apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/botStore.ts, apps/desktop/src/renderer/features/bots/botTodo.css, apps/desktop/src/renderer/features/bots/botWelcomeContext.ts, apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts, apps/desktop/src/renderer/features/bots/chatError.ts, apps/desktop/src/renderer/features/bots/cindyDeviceRoster.ts, apps/desktop/src/renderer/features/bots/companionCloudPresentation.ts, apps/desktop/src/renderer/features/bots/companionCloudStore.ts, apps/desktop/src/renderer/features/bots/islandEntryAlert.ts, apps/desktop/src/renderer/features/bots/remoteBotRoster.ts, apps/desktop/src/renderer/features/bots/remoteBotSettingsData.ts, apps/desktop/src/renderer/features/bots/teammatesSectionPrefs.ts, apps/desktop/src/renderer/features/bots/useBotGeneratedFileDeliveries.ts, apps/desktop/src/renderer/features/bots/useBotGroupMentionPicker.tsx, apps/desktop/src/renderer/features/bots/useBotIslandVisibleSession.ts, apps/desktop/src/renderer/features/bots/useBotSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/useBotUnreadSync.ts, apps/desktop/src/renderer/features/bots/useRemoteBots.ts, apps/desktop/src/renderer/features/bots/useSessionEntryLocationCommits.ts, apps/desktop/src/renderer/features/bots/useViewedBotSessionId.ts, apps/desktop/src/renderer/features/bots/useWorkbenchSessionPages.ts, apps/desktop/src/renderer/features/bots/useWorkingStatusCopy.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 275 | 38 | 502 |+| `desktop.bots` | desktop | 伙伴(列表 / 对话 / 设置 / 历史 / 伙伴私聊 / 群聊) | hash `/bots`、`/bots/list`、`/bots/:botId`、`/bots/roster` 及伙伴当前/历史任务、伙伴私聊、伙伴群聊路由(BotsFeatureLayout) | BotBasicProfileFields, BotCollaborationCard, BotDirectMessageView, BotGroupChatView, BotGroupCreateDialog, BotGroupSettingsDrawer, BotHistorySessionView, BotLifecycleSettings, BotModelChainEditor, BotRosterView, BotSessionView, BotSettingsDrawer, BotsHomeView, BotsListView, RemoteBotSessionView | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentOnOtherDeviceContext.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AgentTaskLiveDetails.tsx, apps/desktop/src/renderer/components/chat/AnnotationStrokesSvg.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatLoadingImage.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/McpAppCard.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/MessageViewport.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/animateFocusScroll.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/markdownMedia.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageNavigationProjection.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageViewportGeometry.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/observeProgrammaticScroll.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeHighlightShared.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useImageClipboard.ts, apps/desktop/src/renderer/components/chat/useImageLoadFailure.ts, apps/desktop/src/renderer/components/chat/useMessageViewport.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerAttachments.tsx, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/LocalModelCatalogNotice.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupRemoteDesktopButton.tsx, apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/bots/BotAddToGroupMenu.tsx, apps/desktop/src/renderer/features/bots/BotAuthorizationCard.tsx, apps/desktop/src/renderer/features/bots/BotAvatar.tsx, apps/desktop/src/renderer/features/bots/BotBasicProfileFields.tsx, apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx, apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx, apps/desktop/src/renderer/features/bots/BotConnectionStatus.tsx, apps/desktop/src/renderer/features/bots/BotCreateMenu.tsx, apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx, apps/desktop/src/renderer/features/bots/BotFollowMark.tsx, apps/desktop/src/renderer/features/bots/BotGenerationLabel.tsx, apps/desktop/src/renderer/features/bots/BotGroupAvatars.tsx, apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx, apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx, apps/desktop/src/renderer/features/bots/BotGroupCreateDialog.tsx, apps/desktop/src/renderer/features/bots/BotGroupMessageAttachments.tsx, apps/desktop/src/renderer/features/bots/BotGroupPendingInteraction.tsx, apps/desktop/src/renderer/features/bots/BotGroupPlan.tsx, apps/desktop/src/renderer/features/bots/BotGroupQuote.tsx, apps/desktop/src/renderer/features/bots/BotGroupRuntimeFailureNotice.tsx, apps/desktop/src/renderer/features/bots/BotGroupSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx, apps/desktop/src/renderer/features/bots/BotGroupTaskCard.tsx, apps/desktop/src/renderer/features/bots/BotGroupThreadViews.tsx, apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx, apps/desktop/src/renderer/features/bots/BotHomeComputerSetting.tsx, apps/desktop/src/renderer/features/bots/BotImportForm.tsx, apps/desktop/src/renderer/features/bots/BotInvitationWelcome.tsx, apps/desktop/src/renderer/features/bots/BotLearningFooter.tsx, apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx, apps/desktop/src/renderer/features/bots/BotMemorySettings.tsx, apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx, apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsx, apps/desktop/src/renderer/features/bots/BotRosterView.tsx, apps/desktop/src/renderer/features/bots/BotRoutines.tsx, apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx, apps/desktop/src/renderer/features/bots/BotSessionTaskLink.tsx, apps/desktop/src/renderer/features/bots/BotSessionTaskResultCard.tsx, apps/desktop/src/renderer/features/bots/BotSessionView.tsx, apps/desktop/src/renderer/features/bots/BotSettingsBlock.tsx, apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotTaskCardHeader.tsx, apps/desktop/src/renderer/features/bots/BotTaskModelEditor.tsx, apps/desktop/src/renderer/features/bots/BotTodoList.tsx, apps/desktop/src/renderer/features/bots/BotWorkbench.tsx, apps/desktop/src/renderer/features/bots/BotWorkingStatus.tsx, apps/desktop/src/renderer/features/bots/BotsFeatureLayout.tsx, apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx, apps/desktop/src/renderer/features/bots/BotsHomeView.tsx, apps/desktop/src/renderer/features/bots/BotsListView.tsx, apps/desktop/src/renderer/features/bots/ChatBotAccessField.tsx, apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx, apps/desktop/src/renderer/features/bots/ChatInviteDialog.tsx, apps/desktop/src/renderer/features/bots/ChatInviteHost.tsx, apps/desktop/src/renderer/features/bots/ChatReactionButton.tsx, apps/desktop/src/renderer/features/bots/ChatServerControls.tsx, apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx, apps/desktop/src/renderer/features/bots/CindyDevicePicker.tsx, apps/desktop/src/renderer/features/bots/CindyDeviceRow.tsx, apps/desktop/src/renderer/features/bots/CloudCompanionOfflineView.tsx, apps/desktop/src/renderer/features/bots/CompanionShadowBanner.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSettings.tsx, apps/desktop/src/renderer/features/bots/RemoveChatFromListButton.tsx, apps/desktop/src/renderer/features/bots/TeammateSearchResults.tsx, apps/desktop/src/renderer/features/bots/TeammatesSection.tsx, apps/desktop/src/renderer/features/bots/WorkbenchSessionList.tsx, apps/desktop/src/renderer/features/bots/botAvatarIdentity.ts, apps/desktop/src/renderer/features/bots/botCapabilityDefaults.ts, apps/desktop/src/renderer/features/bots/botChatPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationTimeline.ts, apps/desktop/src/renderer/features/bots/botDelegationLive.ts, apps/desktop/src/renderer/features/bots/botFollowScopes.ts, apps/desktop/src/renderer/features/bots/botGeneratedArtifacts.ts, apps/desktop/src/renderer/features/bots/botGroupAttachments.ts, apps/desktop/src/renderer/features/bots/botGroupComposerChrome.ts, apps/desktop/src/renderer/features/bots/botGroupLane.ts, apps/desktop/src/renderer/features/bots/botGroupMentions.ts, apps/desktop/src/renderer/features/bots/botGroupOutbox.ts, apps/desktop/src/renderer/features/bots/botGroupPresentation.ts, apps/desktop/src/renderer/features/bots/botGroupStore.ts, apps/desktop/src/renderer/features/bots/botListDisplay.ts, apps/desktop/src/renderer/features/bots/botNavigation.ts, apps/desktop/src/renderer/features/bots/botPronounContext.tsx, apps/desktop/src/renderer/features/bots/botReadState.ts, apps/desktop/src/renderer/features/bots/botRosterDisplay.ts, apps/desktop/src/renderer/features/bots/botSessionOwners.ts, apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/botStore.ts, apps/desktop/src/renderer/features/bots/botTodo.css, apps/desktop/src/renderer/features/bots/botWelcomeContext.ts, apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts, apps/desktop/src/renderer/features/bots/chatError.ts, apps/desktop/src/renderer/features/bots/cindyDeviceRoster.ts, apps/desktop/src/renderer/features/bots/companionCloudPresentation.ts, apps/desktop/src/renderer/features/bots/companionCloudStore.ts, apps/desktop/src/renderer/features/bots/islandEntryAlert.ts, apps/desktop/src/renderer/features/bots/remoteBotRoster.ts, apps/desktop/src/renderer/features/bots/remoteBotSettingsData.ts, apps/desktop/src/renderer/features/bots/teammatesSectionPrefs.ts, apps/desktop/src/renderer/features/bots/useBotGeneratedFileDeliveries.ts, apps/desktop/src/renderer/features/bots/useBotGroupMentionPicker.tsx, apps/desktop/src/renderer/features/bots/useBotIslandVisibleSession.ts, apps/desktop/src/renderer/features/bots/useBotSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/useBotUnreadSync.ts, apps/desktop/src/renderer/features/bots/useRemoteBots.ts, apps/desktop/src/renderer/features/bots/useSessionEntryLocationCommits.ts, apps/desktop/src/renderer/features/bots/useViewedBotSessionId.ts, apps/desktop/src/renderer/features/bots/useWorkbenchSessionPages.ts, apps/desktop/src/renderer/features/bots/useWorkingStatusCopy.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 275 | 38 | 505 || `desktop.chat.files` | desktop | 工作目录文件浏览 | hash `/cc-agent/files/:sessionId`(WorkdirBrowseRoute) | FileBodyView, FileTreeView, WorkdirBrowseRoute | apps/desktop/src/renderer/features/cc-agent/workdir-browse/DocSearchBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/DrawioPreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileBodyView.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileFilterInput.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileTabsBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileTreeView.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FilterResultList.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/ImagePreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/OpenInSystemActions.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/PdfPreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/SessionTabsBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/UnrenderablePlaceholder.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseRoute.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseSidebar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useChatRailCollapsed.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useChatRailResize.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useConfirmSwitchAwayIfDirty.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useDelayedFlag.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileContent.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileTree.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useOpenTabs.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useProjectFileList.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useRevealFileInTree.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/activeFileBodyHandle.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/docModeSwitchProjects.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/drawioExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/expandedStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileContentCache.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileIcon.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileMeta.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileScrollStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileSelectionParams.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/filterFiles.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/imageExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/markdownAutosave.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/openTabsStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/pdfExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/selectedFileStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchInput.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchPanel.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchResults.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/hooks/useProjectSearch.ts | 17 | 7 | 45 || `desktop.chat.new-draft` | desktop | 新建任务草稿页 | hash `/cc-agent/new`(NewMakerDraftRoute) | NewMakerDraftRoute | apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx | 15 | 0 | 3 |-| `desktop.chat.orca-workflow` | desktop | Orca 协同工作台 | hash `/cc-agent/orca/:sessionId`(OrcaWorkflowRoute) | CCAgentSessionView, OrcaSplitView, OrcaWorkerPanel, OrcaWorkflowRoute | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentOnOtherDeviceContext.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AgentTaskLiveDetails.tsx, apps/desktop/src/renderer/components/chat/AnnotationStrokesSvg.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatLoadingImage.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/MessageViewport.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/animateFocusScroll.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/markdownMedia.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageNavigationProjection.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageViewportGeometry.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/observeProgrammaticScroll.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeHighlightShared.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useImageClipboard.ts, apps/desktop/src/renderer/components/chat/useImageLoadFailure.ts, apps/desktop/src/renderer/components/chat/useMessageViewport.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerAttachments.tsx, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/LocalModelCatalogNotice.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupRemoteDesktopButton.tsx, apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaSplitView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkerPanel.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkflowRoute.tsx | 249 | 38 | 337 |+| `desktop.chat.orca-workflow` | desktop | Orca 协同工作台 | hash `/cc-agent/orca/:sessionId`(OrcaWorkflowRoute) | CCAgentSessionView, OrcaSplitView, OrcaWorkerPanel, OrcaWorkflowRoute | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentOnOtherDeviceContext.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AgentTaskLiveDetails.tsx, apps/desktop/src/renderer/components/chat/AnnotationStrokesSvg.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatLoadingImage.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/McpAppCard.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/MessageViewport.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/animateFocusScroll.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/markdownMedia.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageNavigationProjection.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageViewportGeometry.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/observeProgrammaticScroll.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeHighlightShared.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useImageClipboard.ts, apps/desktop/src/renderer/components/chat/useImageLoadFailure.ts, apps/desktop/src/renderer/components/chat/useMessageViewport.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerAttachments.tsx, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/LocalModelCatalogNotice.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupRemoteDesktopButton.tsx, apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaSplitView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkerPanel.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkflowRoute.tsx | 249 | 38 | 340 || `desktop.chat.scheduled` | desktop | 调度任务列表 | hash `/cc-agent/scheduled`(SchedulerPage) | SchedulerPage | apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsx, apps/desktop/src/renderer/features/scheduler/components/AgentMark.tsx, apps/desktop/src/renderer/features/scheduler/components/BoundSessionCard.tsx, apps/desktop/src/renderer/features/scheduler/components/ProjectAutomationNotifyBridge.tsx, apps/desktop/src/renderer/features/scheduler/components/RunHistoryCard.tsx, apps/desktop/src/renderer/features/scheduler/components/RunHistoryPane.tsx, apps/desktop/src/renderer/features/scheduler/components/ScheduleChips.tsx, apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx, apps/desktop/src/renderer/features/scheduler/components/ScheduleSessionIndexOwner.tsx, apps/desktop/src/renderer/features/scheduler/components/ScheduleStatusChip.tsx, apps/desktop/src/renderer/features/scheduler/components/ScriptCapabilityMultiSelect.tsx, apps/desktop/src/renderer/features/scheduler/components/TaskListCell.tsx, apps/desktop/src/renderer/features/scheduler/components/TaskListFilterPopover.tsx, apps/desktop/src/renderer/features/scheduler/components/TaskListPane.tsx, apps/desktop/src/renderer/features/scheduler/components/TemplateCard.tsx, apps/desktop/src/renderer/features/scheduler/components/TemplateGallery.tsx, apps/desktop/src/renderer/features/scheduler/components/TemplateParamForm.tsx, apps/desktop/src/renderer/features/scheduler/hooks/useDeleteScheduleWithSessions.tsx, apps/desktop/src/renderer/features/scheduler/hooks/useReadFailedScheduleRuns.ts, apps/desktop/src/renderer/features/scheduler/hooks/useRunNowBusyGuard.ts, apps/desktop/src/renderer/features/scheduler/hooks/useRuns.ts, apps/desktop/src/renderer/features/scheduler/hooks/useScheduleForm.ts, apps/desktop/src/renderer/features/scheduler/hooks/useScheduleUnreadRunCounts.ts, apps/desktop/src/renderer/features/scheduler/hooks/useSchedules.ts, apps/desktop/src/renderer/features/scheduler/hooks/useSessionReferences.ts, apps/desktop/src/renderer/features/scheduler/hooks/useTemplates.ts, apps/desktop/src/renderer/features/scheduler/index.ts, apps/desktop/src/renderer/features/scheduler/lib/cronCodexPreset.ts, apps/desktop/src/renderer/features/scheduler/lib/cronToHuman.ts, apps/desktop/src/renderer/features/scheduler/lib/failedScheduleDismissal.ts, apps/desktop/src/renderer/features/scheduler/lib/formatters.ts, apps/desktop/src/renderer/features/scheduler/lib/pluginScheduleCreateIntent.ts, apps/desktop/src/renderer/features/scheduler/lib/projectAutomationConfig.ts, apps/desktop/src/renderer/features/scheduler/lib/projectScheduleSidebarIndex.ts, apps/desktop/src/renderer/features/scheduler/lib/runHistoryGrouping.ts, apps/desktop/src/renderer/features/scheduler/lib/runUnread.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleBindingIndex.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleFormLogic.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleRunReadSync.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleSessionBinding.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleSidebarIndexRuns.ts, apps/desktop/src/renderer/features/scheduler/lib/schedulesStore.ts, apps/desktop/src/renderer/features/scheduler/lib/statusFilter.ts, apps/desktop/src/renderer/features/scheduler/lib/statusFilterStorage.ts, apps/desktop/src/renderer/features/scheduler/lib/templateLocalization.ts | 34 | 0 | 90 |-| `desktop.chat.session` | desktop | 会话工作台 | hash `/cc-agent/:sessionId`;副窗经 `/cc-agent/boot` 解析后落到同一会话视图 | AssistantMessage, CCAgentFeatureLayout, CCAgentSessionView, ChatInput, PermissionPrompt | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentOnOtherDeviceContext.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AgentTaskLiveDetails.tsx, apps/desktop/src/renderer/components/chat/AnnotationStrokesSvg.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatLoadingImage.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/MessageViewport.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/animateFocusScroll.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/markdownMedia.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageNavigationProjection.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageViewportGeometry.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/observeProgrammaticScroll.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeHighlightShared.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useImageClipboard.ts, apps/desktop/src/renderer/components/chat/useImageLoadFailure.ts, apps/desktop/src/renderer/components/chat/useMessageViewport.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerAttachments.tsx, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/LocalModelCatalogNotice.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupRemoteDesktopButton.tsx, apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 249 | 38 | 336 |+| `desktop.chat.session` | desktop | 会话工作台 | hash `/cc-agent/:sessionId`;副窗经 `/cc-agent/boot` 解析后落到同一会话视图 | AssistantMessage, CCAgentFeatureLayout, CCAgentSessionView, ChatInput, PermissionPrompt | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentOnOtherDeviceContext.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AgentTaskLiveDetails.tsx, apps/desktop/src/renderer/components/chat/AnnotationStrokesSvg.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatLoadingImage.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/McpAppCard.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/MessageViewport.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/animateFocusScroll.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/markdownMedia.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageNavigationProjection.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageViewportGeometry.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/observeProgrammaticScroll.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeHighlightShared.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useImageClipboard.ts, apps/desktop/src/renderer/components/chat/useImageLoadFailure.ts, apps/desktop/src/renderer/components/chat/useMessageViewport.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerAttachments.tsx, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/LocalModelCatalogNotice.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupRemoteDesktopButton.tsx, apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 249 | 38 | 339 || `desktop.dev.maker-experimental` | desktop | Maker 实验诊断页 | hash `/maker-experimental`(MakerExperimentalView;EXPERIMENTAL_FEATURES 现为空,仍是生产路由) | MakerExperimentalView | apps/desktop/src/renderer/features/maker-experimental/MakerExperimentalView.tsx | 9 | 0 | 7 || `desktop.issues.guide` | desktop | Issue 引导页 | hash `/issues`(IssueTrackerFeatureLayout,已迁 GitHub 后的引导页) | IssueTrackerFeatureLayout | apps/desktop/src/renderer/features/issue-tracker/IssueTrackerFeatureLayout.tsx, apps/desktop/src/renderer/features/issue-tracker/MyIssueList.tsx, apps/desktop/src/renderer/features/issue-tracker/hooks/useMyIssues.ts, apps/desktop/src/renderer/features/issue-tracker/lib/myIssuesNotices.ts, apps/desktop/src/renderer/features/issue-tracker/lib/startIssueChat.ts | 0 | 0 | 7 || `desktop.native.app-menu` | desktop | 应用菜单 | Menu.setApplicationMenu(用户可见出口,不展开业务逻辑) | applicationMenuLabels | apps/desktop/src/main/applicationMenuLabels.ts | 0 | 0 | 0 |@@ -51,23 +51,23 @@| `desktop.window.sidebar` | desktop | 右侧栏独立窗口 | `?sidebarWindow=1` → renderer/sidebar-window-entry.tsx;hash `/sidebar-window` | RightSidebar, RightSidebarShell, SidebarWindowLayout | apps/desktop/src/main/right-sidebar-window/controller.ts, apps/desktop/src/main/right-sidebar-window/ipc.ts, apps/desktop/src/main/right-sidebar-window/registry.ts, apps/desktop/src/main/right-sidebar-window/resolveHostContext.ts, apps/desktop/src/main/right-sidebar-window/settings-store.ts, apps/desktop/src/main/right-sidebar-window/window.ts, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBotWorkbenchTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openRoutinesTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/bot-workbench/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/CindyMakeTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/retired-feature/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/routines/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/tabAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/sidebar-window-entry.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 113 | 45 | 119 || `desktop.window.voice-dictionary-toast` | desktop | 语音词典 Toast 窗 | `?view=voice-input-dictionary-toast` → main-entry.tsx → VoiceInputDictionaryToast | VoiceInputDictionaryToast | apps/desktop/src/renderer/voice-input/VoiceInputDictionaryToast.tsx | 6 | 0 | 2 || `desktop.window.voice-overlay` | desktop | 语音输入浮窗 | `?view=voice-input-overlay` → main-entry.tsx → VoiceInputOverlay | VoiceInputOverlay, VoiceInputStatusNotice | apps/desktop/src/main/voice-input/global.ts, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css, apps/desktop/src/renderer/voice-input/VoiceInputOverlay.tsx, apps/desktop/src/renderer/voice-input/VoiceInputStatusNotice.tsx | 82 | 38 | 20 |-| `mobile.account-deletion` | mobile | 账号注销 | app/account-deletion.tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, CompanionNativeContent.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, HomeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, 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, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, account-deletion, gestureHandler, nativeToolbarMenuItems, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/account-deletion.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/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/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/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.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/session/SheetSurface.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 | 60 |-| `mobile.auth` | mobile | 登录与添加账号 | app/(auth)/login.tsx / app/add-account.tsx | AccountSwitcherSheet, AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, CompanionNativeContent.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, IncomingShareBridge, LoginCaptchaWebView, LoginNativeButton, LoginNativeButton.ios, LoginSkinControls, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, MobileUserAvatar, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, 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, SheetSurface, StartupSplashOverlay, SystemNavigationBack, ThemeProvider, _layout, add-account, gestureHandler, login, peerFileTransport, useLocale | apps/mobile/app/(auth)/login.tsx, apps/mobile/app/_layout.tsx, apps/mobile/app/add-account.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/LoginCaptchaWebView.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/LoginNativeButton.ios.tsx, apps/mobile/src/components/LoginNativeButton.tsx, apps/mobile/src/components/LoginSkinControls.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/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/SystemNavigationBack.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/AccountSwitcherSheet.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/CompanionNativeContent.ios.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/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.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/session/SheetSurface.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 | 221 | 82 |-| `mobile.chat.new` | mobile | 新建任务 | app/sessions/new.tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AnnotationBurnInWebView, AppText, AuthContext, BlurBackdrop, CenteredScreen, CompanionNativeContent.ios, ComposerActivityPill, ComposerAttachmentTray, ComposerDockKeyboardFollow, ComposerFrame, ComposerFrame.ios, ComposerKeyboardAvoidingView, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ContextSheetCollabView, ContextSheetGoalView, ContextSheetGoalView.ios, ContextSheetMediaViews, ContextSheetPlugins, DeviceLinkContext, FileTypeIcon, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, HomeStackHeader, ImageLightbox, IncomingShareBridge, MobileAgentMark, MobileAgentSwitcher, MobileChoicePickerList, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobileModelPickerList.ios, MobileOutboxBridge, MobilePermissionPickerList, MobilePermissionPickerList.ios, MobilePrimitives, MobileProviderMark, MobileVendorIcon, ModelOptionsSheetView, ModelOptionsSheetView.ios, ModelPickerNativeHeader, ModelPickerNativeHeader.ios, ModelPickerSheet, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePermissionSheet, NativePermissionSheet.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, NativeVideoPlayer, NewTaskSelectionRow, NewTaskSelectionSheet, NewTaskSelectionSheet.android, NewTaskSelectionSheet.ios, OrcaWorkerDirectoryPicker, OutsideTap, PaperPlaneIcon, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PlanModeChip, 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, SlowSendNotice, StartupSplashOverlay, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, VoiceRecordingPill, _layout, composerPullThrough, gestureHandler, mediaPlayerWebView, nativeToolbarMenuItems, new, peerFileTransport, useLocale, voicePillWidthMotion | apps/mobile/app/_layout.tsx, apps/mobile/app/sessions/new.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/FileTypeIcon.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/PaperPlaneIcon.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/AnnotationBurnInWebView.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/CompanionNativeContent.ios.tsx, apps/mobile/src/session/ComposerActivityPill.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerDockKeyboardFollow.tsx, apps/mobile/src/session/ComposerFrame.ios.tsx, apps/mobile/src/session/ComposerFrame.tsx, apps/mobile/src/session/ComposerKeyboardAvoidingView.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/ContextSheetCollabView.tsx, apps/mobile/src/session/ContextSheetGoalView.ios.tsx, apps/mobile/src/session/ContextSheetGoalView.tsx, apps/mobile/src/session/ContextSheetMediaViews.tsx, apps/mobile/src/session/ContextSheetPlugins.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileChoicePickerList.tsx, apps/mobile/src/session/MobileComposerInputRow.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/NativePermissionSheet.ios.tsx, apps/mobile/src/session/NativePermissionSheet.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/NativeVideoPlayer.tsx, apps/mobile/src/session/NewTaskSelectionRow.tsx, apps/mobile/src/session/NewTaskSelectionSheet.android.tsx, apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx, apps/mobile/src/session/NewTaskSelectionSheet.tsx, apps/mobile/src/session/OrcaWorkerDirectoryPicker.tsx, apps/mobile/src/session/PlanModeChip.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/SlowSendNotice.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/VoiceRecordingPill.tsx, apps/mobile/src/session/composerPullThrough.tsx, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/voicePillWidthMotion.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 | 251 | 112 |-| `mobile.chat.session` | mobile | 任务内容与输入 | app/sessions/[sessionId].tsx | AccountSwitcherSheet, AdaptiveWindow, AgentErrorDetails, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AnnotationBurnInWebView, AppText, AuthContext, AuthorizationMessageCard, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ChatFileChipMenuSheet, ChatIdentityHeader, CindyMakeSessionGate, CompanionChoice, CompanionCreateNativeView, CompanionCreateNativeView.ios, CompanionEntering, CompanionHeader, CompanionImportSheet, CompanionLearningFooter, CompanionMemoryPage, CompanionMemoryPage.ios, CompanionMessageActions, CompanionMessageCard, CompanionModelChain, CompanionNativeContent.ios, CompanionPortraitPicker, CompanionPresenceRing, CompanionProfileArtifacts, CompanionProfileNativeView, CompanionProfileNativeView.ios, CompanionProfileSheet, CompanionSettingsRow, CompanionSettingsRow.ios, CompanionSheet, CompanionSheet.ios, CompanionTaskResultCard, CompanionTodoRow, CompanionTodos, CompanionWorkingStatus, ComposerActivityPill, ComposerAttachmentTray, ComposerDockKeyboardFollow, ComposerExpandButton, ComposerExpandButton.ios, ComposerFrame, ComposerFrame.ios, ComposerKeyboardAvoidingView, ComposerMorphSource, ComposerMorphSource.ios, ComposerNativeInput, ComposerNativeInput.ios, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerRichInput, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ContextSheetCollabView, ContextSheetGoalView, ContextSheetGoalView.ios, ContextSheetMediaViews, ContextSheetPlugins, ConversationSearchFilterSheet, ConversationShareSvg, ConversationShareWebView, DeviceLinkContext, FailedScheduleNotice, FileTypeIcon, FoldTouchpad, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeListVisuals, HomeModeSwitch, HomeNativeStackHeader, HomeNewTaskButton, HomeProjectMachineLabel, HomeSearchBar, HomeSessionInfoMeta, HomeStackHeader, HomeSurface, HomeUnreadContext, ImageLightbox, IncomingShareBridge, InlineQueueSection, InlineQuoteChip, InlineReferenceChip, InputHandoffCard, InputHandoffDeviceCode, InputHandoffPictureStep, InputHandoffQrCode, InputHandoffRecordRow, InputHandoffSheet, InputHandoffSheet.ios, InputHandoffStepFields, InteractionPanel, MarkdownBlockContent, MessageActionSheet, MessageLoadingImage, MessageRenderer, MobileAgentMark, MobileAgentSwitcher, MobileBoundaryNotice, MobileComposerInputRow, 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, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePermissionSheet, NativePermissionSheet.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, NativeVideoPlayer, NewTaskSelectionRow, NewTaskSelectionSheet, NewTaskSelectionSheet.android, NewTaskSelectionSheet.ios, OrcaWorkerDirectoryPicker, OutsideTap, PaperPlaneIcon, PendingSendBubble, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PlanModeChip, PluginCardActions, PluginInvocationHeader, PluginMenuUnreadDot, PluginSetupNativeActions, PluginSetupNativeForm, PromptRecommendation, PushNotificationsBridge, QuietSyncIndicator, QuoteCapsule, ReadableHistoryRecovery, 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, RewindPreviewPanel, RunningTokenRatePopover, SentInlineAtomBody, SessionActionSheet, SessionActionSheetFrame, SessionActionSheetFrame.android, SessionDetailsNative, SessionDetailsNative.ios, SessionEntryRecovery, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionListDrawer, SessionMenuSheet, SessionOptionsExpoSheet, SessionResourceCards, SessionRightSpinner, SessionSearchNative, SessionSearchNative.ios, SessionTailBanner, SessionTransientNotice, SessionUsageSummary, ShareImageNativeButton, ShareImageNativeButton.ios, ShareMessageCheckbox, ShareSelectAllButton, ShareSelectionBar, SharedTaskEndedState, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, SystemNavigationBack, TaskTags, TaskTagsSheet, ThemeProvider, ThinkingDots, TodoDateInput, TodoDateInput.android, TodoDateInput.ios, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, VoiceRecordingPill, WorkingStatusText, [sessionId], _layout, composerPullThrough, gestureHandler, listDisclosureTransition, mathWebView, mediaPlayerWebView, mermaidWebView, nativeToolbarMenuItems, peerFileTransport, useLocale, useSharedTaskConfirmation, voicePillWidthMotion | apps/mobile/app/_layout.tsx, apps/mobile/app/sessions/[sessionId].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/FileTypeIcon.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/PaperPlaneIcon.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/inputHandoff/InputHandoffCard.tsx, apps/mobile/src/inputHandoff/InputHandoffDeviceCode.tsx, apps/mobile/src/inputHandoff/InputHandoffPictureStep.tsx, apps/mobile/src/inputHandoff/InputHandoffQrCode.tsx, apps/mobile/src/inputHandoff/InputHandoffRecordRow.tsx, apps/mobile/src/inputHandoff/InputHandoffSheet.ios.tsx, apps/mobile/src/inputHandoff/InputHandoffSheet.tsx, apps/mobile/src/inputHandoff/InputHandoffStepFields.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/NativeChromeBackButton.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/PluginCardActions.tsx, apps/mobile/src/plugins/PluginMenuUnreadDot.tsx, apps/mobile/src/plugins/PluginSetupNativeActions.tsx, apps/mobile/src/plugins/PluginSetupNativeForm.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/AgentErrorDetails.tsx, apps/mobile/src/session/AnnotationBurnInWebView.tsx, apps/mobile/src/session/AuthorizationMessageCard.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ChatFileChipMenuSheet.tsx, apps/mobile/src/session/ChatIdentityHeader.tsx, apps/mobile/src/session/CindyMakeSessionGate.tsx, apps/mobile/src/session/CompanionChoice.tsx, apps/mobile/src/session/CompanionCreateNativeView.ios.tsx, apps/mobile/src/session/CompanionCreateNativeView.tsx, apps/mobile/src/session/CompanionEntering.tsx, apps/mobile/src/session/CompanionHeader.tsx, apps/mobile/src/session/CompanionImportSheet.tsx, apps/mobile/src/session/CompanionLearningFooter.tsx, apps/mobile/src/session/CompanionMemoryPage.ios.tsx, apps/mobile/src/session/CompanionMemoryPage.tsx, apps/mobile/src/session/CompanionMessageActions.tsx, apps/mobile/src/session/CompanionMessageCard.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/CompanionTaskResultCard.tsx, apps/mobile/src/session/CompanionTodoRow.tsx, apps/mobile/src/session/CompanionTodos.tsx, apps/mobile/src/session/CompanionWorkingStatus.tsx, apps/mobile/src/session/ComposerActivityPill.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerDockKeyboardFollow.tsx, apps/mobile/src/session/ComposerExpandButton.ios.tsx, apps/mobile/src/session/ComposerExpandButton.tsx, apps/mobile/src/session/ComposerFrame.ios.tsx, apps/mobile/src/session/ComposerFrame.tsx, apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx, apps/mobile/src/session/ComposerMorphSource.ios.tsx, apps/mobile/src/session/ComposerMorphSource.tsx, apps/mobile/src/session/ComposerNativeInput.ios.tsx, apps/mobile/src/session/ComposerNativeInput.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/ComposerRichInput.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/ContextSheetCollabView.tsx, apps/mobile/src/session/ContextSheetGoalView.ios.tsx, apps/mobile/src/session/ContextSheetGoalView.tsx, apps/mobile/src/session/ContextSheetMediaViews.tsx, apps/mobile/src/session/ContextSheetPlugins.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/ConversationShareSvg.tsx, apps/mobile/src/session/ConversationShareWebView.tsx, apps/mobile/src/session/FailedScheduleNotice.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/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/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/InlineQueueSection.tsx, apps/mobile/src/session/InlineQuoteChip.tsx, apps/mobile/src/session/InlineReferenceChip.tsx, apps/mobile/src/session/InteractionPanel.tsx, apps/mobile/src/session/MarkdownBlockContent.tsx, apps/mobile/src/session/MessageActionSheet.tsx, apps/mobile/src/session/MessageLoadingImage.tsx, apps/mobile/src/session/MessageRenderer.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileBoundaryNotice.tsx, apps/mobile/src/session/MobileComposerInputRow.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/NativePermissionSheet.ios.tsx, apps/mobile/src/session/NativePermissionSheet.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/NativeVideoPlayer.tsx, apps/mobile/src/session/NewTaskSelectionRow.tsx, apps/mobile/src/session/NewTaskSelectionSheet.android.tsx, apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx, apps/mobile/src/session/NewTaskSelectionSheet.tsx, apps/mobile/src/session/OrcaWorkerDirectoryPicker.tsx, apps/mobile/src/session/PendingSendBubble.tsx, apps/mobile/src/session/PlanModeChip.tsx, apps/mobile/src/session/PluginInvocationHeader.tsx, apps/mobile/src/session/PromptRecommendation.tsx, apps/mobile/src/session/QuoteCapsule.tsx, apps/mobile/src/session/ReadableHistoryRecovery.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/RewindPreviewPanel.tsx, apps/mobile/src/session/RunningTokenRatePopover.tsx, apps/mobile/src/session/SentInlineAtomBody.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/SessionEntryRecovery.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionListDrawer.tsx, apps/mobile/src/session/SessionMenuSheet.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SessionResourceCards.tsx, apps/mobile/src/session/SessionRightSpinner.tsx, apps/mobile/src/session/SessionSearchNative.ios.tsx, apps/mobile/src/session/SessionSearchNative.tsx, apps/mobile/src/session/SessionTailBanner.tsx, apps/mobile/src/session/SessionTransientNotice.tsx, apps/mobile/src/session/SessionUsageSummary.tsx, apps/mobile/src/session/ShareImageNativeButton.ios.tsx, apps/mobile/src/session/ShareImageNativeButton.tsx, apps/mobile/src/session/ShareMessageCheckbox.tsx, apps/mobile/src/session/ShareSelectAllButton.tsx, apps/mobile/src/session/ShareSelectionBar.tsx, apps/mobile/src/session/SharedTaskEndedState.tsx, apps/mobile/src/session/SharedTaskScreen.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SlowSendNotice.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/session/TaskTags.tsx, apps/mobile/src/session/TaskTagsSheet.tsx, apps/mobile/src/session/ThinkingDots.tsx, apps/mobile/src/session/TodoDateInput.android.tsx, apps/mobile/src/session/TodoDateInput.ios.tsx, apps/mobile/src/session/TodoDateInput.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/VoiceRecordingPill.tsx, apps/mobile/src/session/WorkingStatusText.tsx, apps/mobile/src/session/composerPullThrough.tsx, apps/mobile/src/session/composerRichInputHtml.ts, apps/mobile/src/session/conversationShareWebViewHtml.ts, apps/mobile/src/session/listDisclosureTransition.tsx, apps/mobile/src/session/mathWebView.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/mermaidWebView.tsx, apps/mobile/src/session/mermaidWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.ts, apps/mobile/src/session/useSharedTaskConfirmation.tsx, apps/mobile/src/session/voicePillWidthMotion.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 | 7 | 252 | 315 |-| `mobile.chat.sharing` | mobile | 共享任务邀请与成员;供应商分享链接提示 | app/shared-session.tsx / app/provider-share.tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, CompanionNativeContent.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, 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, SharedTaskAdmissionDialog, SharedTaskEndedState, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, peerFileTransport, provider-share, shared-session, useLocale, useSharedTaskConfirmation | apps/mobile/app/_layout.tsx, apps/mobile/app/provider-share.tsx, apps/mobile/app/shared-session.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/chrome/SimpleStackHeader.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/CompanionNativeContent.ios.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/IncomingShareBridge.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.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/SharedTaskAdmissionDialog.tsx, apps/mobile/src/session/SharedTaskEndedState.tsx, apps/mobile/src/session/SharedTaskScreen.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/useSharedTaskConfirmation.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 | 69 |-| `mobile.companions.cloud` | mobile | 云端伙伴:主力电脑离线时的对话与换电脑 | app/companions/cloud/[actorId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, BotGroupAvatars, BotGroupMessageText, CenteredScreen, ChatIdentityHeader, CloudCompanionScreen, CompanionCardButton, CompanionNativeContent.ios, CompanionPresenceRing, CompanionSettingsRow, CompanionSettingsRow.ios, CompanionSheet, CompanionSheet.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton, NativeChromeBackButton.ios, NativeChromeButton.ios, 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, ResidentHomeList, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, [actorId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/companions/cloud/[actorId].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/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/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.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/BotGroupAvatars.tsx, apps/mobile/src/session/BotGroupMessageText.tsx, apps/mobile/src/session/ChatIdentityHeader.tsx, apps/mobile/src/session/CloudCompanionScreen.tsx, apps/mobile/src/session/CompanionCardButton.tsx, apps/mobile/src/session/CompanionNativeContent.ios.tsx, apps/mobile/src/session/CompanionPresenceRing.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/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/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.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/session/SheetSurface.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 | 66 |-| `mobile.companions.direct` | mobile | 伙伴私聊回看 | app/companions/direct/[threadId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, CompanionNativeContent.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, HomeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, 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, ResidentHomeList, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [threadId], _layout, gestureHandler, nativeToolbarMenuItems, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/companions/direct/[threadId].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/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/CompanionNativeContent.ios.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/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.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/session/SheetSurface.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 | 58 |-| `mobile.companions.groups` | mobile | 伙伴群聊与分工 | app/companions/groups/[groupId].tsx | AdaptiveWindow, AgentErrorDetails, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, AuthorizationMessageCard, BlurBackdrop, BotGroupAvatars, BotGroupChatScreen, BotGroupComposer, BotGroupMenu, BotGroupMessageAttachments, BotGroupMessageText, BotGroupPlan, BotGroupQuote, BotGroupSettingsSheet, BotGroupSpeakerRow, BotGroupTaskCard, CenteredScreen, ChatIdentityHeader, CompanionCardButton, CompanionEntering, CompanionLearningFooter, CompanionMessageActions, CompanionMessageCard, CompanionNativeContent.ios, CompanionPresenceRing, CompanionSheet, CompanionSheet.ios, CompanionTaskResultCard, ComposerAttachmentTray, ComposerFrame, ComposerFrame.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ContextSheetMediaViews, DeviceLinkContext, FileTypeIcon, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, HomeStackHeader, ImageLightbox, IncomingShareBridge, InlineQuoteChip, InlineReferenceChip, InputHandoffCard, InputHandoffDeviceCode, InputHandoffPictureStep, InputHandoffQrCode, InputHandoffRecordRow, InputHandoffSheet, InputHandoffSheet.ios, InputHandoffStepFields, InteractionPanel, MarkdownBlockContent, MessageActionSheet, MessageLoadingImage, MessageRenderer, MobileBoundaryNotice, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, NativeVideoPlayer, OutsideTap, PaperPlaneIcon, PendingSendBubble, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PluginCardActions, PluginInvocationHeader, PluginSetupNativeActions, PluginSetupNativeForm, PushNotificationsBridge, QuietSyncIndicator, QuoteCapsule, 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, ResidentHomeList, SentInlineAtomBody, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, ShareMessageCheckbox, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, TaskTags, ThemeProvider, ThinkingDots, WorkingStatusText, [groupId], _layout, gestureHandler, mathWebView, mediaPlayerWebView, mermaidWebView, nativeToolbarMenuItems, peerFileTransport, useLocale, voicePillWidthMotion | apps/mobile/app/_layout.tsx, apps/mobile/app/companions/groups/[groupId].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/FileTypeIcon.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/PaperPlaneIcon.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/inputHandoff/InputHandoffCard.tsx, apps/mobile/src/inputHandoff/InputHandoffDeviceCode.tsx, apps/mobile/src/inputHandoff/InputHandoffPictureStep.tsx, apps/mobile/src/inputHandoff/InputHandoffQrCode.tsx, apps/mobile/src/inputHandoff/InputHandoffRecordRow.tsx, apps/mobile/src/inputHandoff/InputHandoffSheet.ios.tsx, apps/mobile/src/inputHandoff/InputHandoffSheet.tsx, apps/mobile/src/inputHandoff/InputHandoffStepFields.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/NativeChromeBackButton.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/PluginCardActions.tsx, apps/mobile/src/plugins/PluginSetupNativeActions.tsx, apps/mobile/src/plugins/PluginSetupNativeForm.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/AgentErrorDetails.tsx, apps/mobile/src/session/AuthorizationMessageCard.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/BotGroupAvatars.tsx, apps/mobile/src/session/BotGroupChatScreen.tsx, apps/mobile/src/session/BotGroupComposer.tsx, apps/mobile/src/session/BotGroupMenu.tsx, apps/mobile/src/session/BotGroupMessageAttachments.tsx, apps/mobile/src/session/BotGroupMessageText.tsx, apps/mobile/src/session/BotGroupPlan.tsx, apps/mobile/src/session/BotGroupQuote.tsx, apps/mobile/src/session/BotGroupSettingsSheet.tsx, apps/mobile/src/session/BotGroupSpeakerRow.tsx, apps/mobile/src/session/BotGroupTaskCard.tsx, apps/mobile/src/session/ChatIdentityHeader.tsx, apps/mobile/src/session/CompanionCardButton.tsx, apps/mobile/src/session/CompanionEntering.tsx, apps/mobile/src/session/CompanionLearningFooter.tsx, apps/mobile/src/session/CompanionMessageActions.tsx, apps/mobile/src/session/CompanionMessageCard.tsx, apps/mobile/src/session/CompanionNativeContent.ios.tsx, apps/mobile/src/session/CompanionPresenceRing.tsx, apps/mobile/src/session/CompanionSheet.ios.tsx, apps/mobile/src/session/CompanionSheet.tsx, apps/mobile/src/session/CompanionTaskResultCard.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerFrame.ios.tsx, apps/mobile/src/session/ComposerFrame.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/ContextSheetMediaViews.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/InlineQuoteChip.tsx, apps/mobile/src/session/InlineReferenceChip.tsx, apps/mobile/src/session/InteractionPanel.tsx, apps/mobile/src/session/MarkdownBlockContent.tsx, apps/mobile/src/session/MessageActionSheet.tsx, apps/mobile/src/session/MessageLoadingImage.tsx, apps/mobile/src/session/MessageRenderer.tsx, apps/mobile/src/session/MobileBoundaryNotice.tsx, apps/mobile/src/session/MobileComposerInputRow.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/NativeVideoPlayer.tsx, apps/mobile/src/session/PendingSendBubble.tsx, apps/mobile/src/session/PluginInvocationHeader.tsx, apps/mobile/src/session/QuoteCapsule.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SentInlineAtomBody.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/ShareMessageCheckbox.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/TaskTags.tsx, apps/mobile/src/session/ThinkingDots.tsx, apps/mobile/src/session/WorkingStatusText.tsx, apps/mobile/src/session/mathWebView.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/mermaidWebView.tsx, apps/mobile/src/session/mermaidWebViewHtml.ts, apps/mobile/src/session/voicePillWidthMotion.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 | 251 | 208 |-| `mobile.device-management` | mobile | 设备管理 | app/devices/manage.tsx / app/devices/manage/[deviceId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, CompanionNativeContent.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceInformationFields, DeviceInformationFields.ios, DeviceLinkContext, DeviceManagementDialogs, DeviceManagementList, DeviceManagementList.ios, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, HomeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, ModalContentArea, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, 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, RenameDeviceModal, ResidentHomeList, SettingsGroupRows, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, listDisclosureTransition, manage, nativeToolbarMenuItems, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/manage.tsx, apps/mobile/app/devices/manage/[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/DeviceInformationFields.ios.tsx, apps/mobile/src/device-link/DeviceInformationFields.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/DeviceManagementDialogs.tsx, apps/mobile/src/device-link/DeviceManagementList.ios.tsx, apps/mobile/src/device-link/DeviceManagementList.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/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/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/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx, apps/mobile/src/session/RenameDeviceModal.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/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 214 | 58 |-| `mobile.devices` | mobile | 主机详情 | app/devices/[deviceId].tsx | AccountSwitcherSheet, AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, CenteredScreen, CompanionNativeContent.ios, ComposerMorphSource, ComposerMorphSource.ios, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ConversationSearchFilterSheet, DeviceLinkContext, FoldTouchpad, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeListVisuals, HomeModeSwitch, HomeNativeStackHeader, HomeNewTaskButton, HomeProjectMachineLabel, HomeSearchBar, HomeSessionInfoMeta, HomeStackHeader, HomeSurface, HomeUnreadContext, IncomingShareBridge, MobileAgentMark, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, MobileUserAvatar, MobileVendorIcon, ModalContentArea, MountOnFirstOpen, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PluginMenuUnreadDot, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteAccessGuide, 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, SessionOptionsExpoSheet, SessionRightSpinner, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, TaskTags, ThemeProvider, [deviceId], _layout, gestureHandler, listDisclosureTransition, nativeToolbarMenuItems, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/[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/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/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.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/CompanionNativeContent.ios.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/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/MobileOutboxBridge.tsx, apps/mobile/src/session/MountOnFirstOpen.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.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/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SessionRightSpinner.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/session/TaskTags.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 | 111 |-| `mobile.files` | mobile | 任务文件与预览 | app/files/[sessionId].tsx / app/files/preview/[sessionId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, CindyMakeSessionGate, CompanionNativeContent.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FileBrowserSegmentedControl, FileTransferBusyNotice, FileTypeIcon, FileTypeTile, FoldTouchpad, HomeEntryProvider, HtmlBrowserChrome, HtmlBrowserChrome.ios, HtmlFileReader, HtmlWebsiteBrowser, ImageLightbox, IncomingShareBridge, MarkdownFileReader, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, ModalContentArea, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, NativeVideoPlayer, 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, SessionEntryRecovery, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SystemNavigationBack, ThemeProvider, [sessionId], _layout, gestureHandler, mediaPlayerWebView, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/files/[sessionId].tsx, apps/mobile/app/files/preview/[sessionId].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/FileTypeIcon.tsx, apps/mobile/src/components/FileTypeTile.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/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/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/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/CindyMakeSessionGate.tsx, apps/mobile/src/session/CompanionNativeContent.ios.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/FileBrowserSegmentedControl.tsx, apps/mobile/src/session/FileTransferBusyNotice.tsx, apps/mobile/src/session/HomeEntryProvider.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/MarkdownFileReader.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.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/ResidentHomeList.tsx, apps/mobile/src/session/SessionEntryRecovery.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.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 | 82 |-| `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, FoldTouchpad, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeListVisuals, HomeModePanes, HomeModeSwitch, HomeNativeStackHeader, HomeNewTaskButton, HomeProjectMachineLabel, HomeSearchBar, HomeSessionInfoMeta, HomeStackHeader, HomeSurface, HomeUnreadContext, IncomingShareBridge, 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, 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, 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/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/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/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/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/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 | 143 |-| `mobile.overlay.connection-startup` | mobile | 根布局挂载的启动与连接反馈 | app/_layout.tsx → StartupSplashOverlay / ConnectionNoticeProvider;各页面 ConnectionBanner | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, CompanionNativeContent.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ConnectionNoticeProvider, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, 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, SheetSurface, 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/CompanionNativeContent.ios.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/IncomingShareBridge.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.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/session/SheetSurface.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 | 53 |-| `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, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, HomeStackHeader, HtmlBrowserChrome, HtmlBrowserChrome.ios, HtmlFileReader, HtmlWebsiteBrowser, ImageLightbox, IncomingShareBridge, 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, 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, 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/MobileAgentMark.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/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/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/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/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/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 | 86 |-| `mobile.remote-desktop` | mobile | 远程桌面 | app/devices/desktop/[deviceId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, CompanionNativeContent.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, 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, SheetSurface, 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/CompanionNativeContent.ios.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/IncomingShareBridge.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.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/session/SheetSurface.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 | 53 |-| `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, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, HomeStackHeader, IncomingShareBridge, 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, 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/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.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/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/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 | 80 |-| `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, CompanionNativeContent.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, HomeStackHeader, IncomingShareBridge, MobileChoicePickerList, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, MobileUserAvatar, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, 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/CompanionNativeContent.ios.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/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/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 | 69 |+| `mobile.account-deletion` | mobile | 账号注销 | app/account-deletion.tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, CompanionNativeContent.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, HomeStackHeader, 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, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, account-deletion, gestureHandler, nativeToolbarMenuItems, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/account-deletion.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/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/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/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/session/SheetSurface.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 | 60 |+| `mobile.auth` | mobile | 登录与添加账号 | app/(auth)/login.tsx / app/add-account.tsx | AccountSwitcherSheet, AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, CompanionNativeContent.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, IncomingShareBridge, LoginCaptchaWebView, LoginNativeButton, LoginNativeButton.ios, LoginSkinControls, McpAppViews, 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, SheetModal, SheetSurface, StartupSplashOverlay, SystemNavigationBack, ThemeProvider, _layout, add-account, gestureHandler, login, peerFileTransport, useLocale | apps/mobile/app/(auth)/login.tsx, apps/mobile/app/_layout.tsx, apps/mobile/app/add-account.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/LoginCaptchaWebView.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/LoginNativeButton.ios.tsx, apps/mobile/src/components/LoginNativeButton.tsx, apps/mobile/src/components/LoginSkinControls.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/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/SystemNavigationBack.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/AccountSwitcherSheet.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/CompanionNativeContent.ios.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/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/session/SheetSurface.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 | 221 | 82 |+| `mobile.chat.new` | mobile | 新建任务 | app/sessions/new.tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AnnotationBurnInWebView, AppText, AuthContext, BlurBackdrop, CenteredScreen, CompanionNativeContent.ios, ComposerActivityPill, ComposerAttachmentTray, ComposerDockKeyboardFollow, ComposerFrame, ComposerFrame.ios, ComposerKeyboardAvoidingView, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ContextSheetCollabView, ContextSheetGoalView, ContextSheetGoalView.ios, ContextSheetMediaViews, ContextSheetPlugins, DeviceLinkContext, FileTypeIcon, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, HomeStackHeader, ImageLightbox, IncomingShareBridge, McpAppViews, MobileAgentMark, MobileAgentSwitcher, MobileChoicePickerList, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobileModelPickerList.ios, MobileOutboxBridge, MobilePermissionPickerList, MobilePermissionPickerList.ios, MobilePrimitives, MobileProviderMark, MobileVendorIcon, ModelOptionsSheetView, ModelOptionsSheetView.ios, ModelPickerNativeHeader, ModelPickerNativeHeader.ios, ModelPickerSheet, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, NativeMcpAppSurface, NativePermissionSheet, NativePermissionSheet.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, NativeVideoPlayer, NewTaskSelectionRow, NewTaskSelectionSheet, NewTaskSelectionSheet.android, NewTaskSelectionSheet.ios, OrcaWorkerDirectoryPicker, OutsideTap, PaperPlaneIcon, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PlanModeChip, 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, SlowSendNotice, StartupSplashOverlay, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, VoiceRecordingPill, _layout, composerPullThrough, gestureHandler, mediaPlayerWebView, nativeToolbarMenuItems, new, peerFileTransport, useLocale, voicePillWidthMotion | apps/mobile/app/_layout.tsx, apps/mobile/app/sessions/new.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/FileTypeIcon.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/PaperPlaneIcon.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/AnnotationBurnInWebView.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/CompanionNativeContent.ios.tsx, apps/mobile/src/session/ComposerActivityPill.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerDockKeyboardFollow.tsx, apps/mobile/src/session/ComposerFrame.ios.tsx, apps/mobile/src/session/ComposerFrame.tsx, apps/mobile/src/session/ComposerKeyboardAvoidingView.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/ContextSheetCollabView.tsx, apps/mobile/src/session/ContextSheetGoalView.ios.tsx, apps/mobile/src/session/ContextSheetGoalView.tsx, apps/mobile/src/session/ContextSheetMediaViews.tsx, apps/mobile/src/session/ContextSheetPlugins.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.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/MobileChoicePickerList.tsx, apps/mobile/src/session/MobileComposerInputRow.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/NativePermissionSheet.ios.tsx, apps/mobile/src/session/NativePermissionSheet.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/NativeVideoPlayer.tsx, apps/mobile/src/session/NewTaskSelectionRow.tsx, apps/mobile/src/session/NewTaskSelectionSheet.android.tsx, apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx, apps/mobile/src/session/NewTaskSelectionSheet.tsx, apps/mobile/src/session/OrcaWorkerDirectoryPicker.tsx, apps/mobile/src/session/PlanModeChip.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/SlowSendNotice.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/VoiceRecordingPill.tsx, apps/mobile/src/session/composerPullThrough.tsx, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/voicePillWidthMotion.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 | 251 | 112 |+| `mobile.chat.session` | mobile | 任务内容与输入 | app/sessions/[sessionId].tsx | AccountSwitcherSheet, AdaptiveWindow, AgentErrorDetails, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AnnotationBurnInWebView, AppText, AuthContext, AuthorizationMessageCard, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ChatFileChipMenuSheet, ChatIdentityHeader, CindyMakeSessionGate, CompanionChoice, CompanionCreateNativeView, CompanionCreateNativeView.ios, CompanionEntering, CompanionHeader, CompanionImportSheet, CompanionLearningFooter, CompanionMemoryPage, CompanionMemoryPage.ios, CompanionMessageActions, CompanionMessageCard, CompanionModelChain, CompanionNativeContent.ios, CompanionPortraitPicker, CompanionPresenceRing, CompanionProfileArtifacts, CompanionProfileNativeView, CompanionProfileNativeView.ios, CompanionProfileSheet, CompanionSettingsRow, CompanionSettingsRow.ios, CompanionSheet, CompanionSheet.ios, CompanionTaskResultCard, CompanionTodoRow, CompanionTodos, CompanionWorkingStatus, ComposerActivityPill, ComposerAttachmentTray, ComposerDockKeyboardFollow, ComposerExpandButton, ComposerExpandButton.ios, ComposerFrame, ComposerFrame.ios, ComposerKeyboardAvoidingView, ComposerMorphSource, ComposerMorphSource.ios, ComposerNativeInput, ComposerNativeInput.ios, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerRichInput, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ContextSheetCollabView, ContextSheetGoalView, ContextSheetGoalView.ios, ContextSheetMediaViews, ContextSheetPlugins, ConversationSearchFilterSheet, ConversationShareSvg, ConversationShareWebView, DeviceLinkContext, FailedScheduleNotice, FileTypeIcon, FoldTouchpad, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeListVisuals, HomeModeSwitch, HomeNativeStackHeader, HomeNewTaskButton, HomeProjectMachineLabel, HomeSearchBar, HomeSessionInfoMeta, HomeStackHeader, HomeSurface, HomeUnreadContext, ImageLightbox, IncomingShareBridge, InlineQueueSection, InlineQuoteChip, InlineReferenceChip, InputHandoffCard, InputHandoffDeviceCode, InputHandoffPictureStep, InputHandoffQrCode, InputHandoffRecordRow, InputHandoffSheet, InputHandoffSheet.ios, InputHandoffStepFields, InteractionPanel, MarkdownBlockContent, McpAppCard, McpAppViews, MessageActionSheet, MessageLoadingImage, MessageRenderer, MobileAgentMark, MobileAgentSwitcher, MobileBoundaryNotice, MobileComposerInputRow, 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, NativeChromeBackButton.ios, NativeChromeButton.ios, NativeMcpAppSurface, NativePermissionSheet, NativePermissionSheet.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, NativeVideoPlayer, NewTaskSelectionRow, NewTaskSelectionSheet, NewTaskSelectionSheet.android, NewTaskSelectionSheet.ios, OrcaWorkerDirectoryPicker, OutsideTap, PaperPlaneIcon, PendingSendBubble, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PlanModeChip, PluginCardActions, PluginInvocationHeader, PluginMenuUnreadDot, PluginSetupNativeActions, PluginSetupNativeForm, PromptRecommendation, PushNotificationsBridge, QuietSyncIndicator, QuoteCapsule, ReadableHistoryRecovery, 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, RewindPreviewPanel, RunningTokenRatePopover, SentInlineAtomBody, SessionActionSheet, SessionActionSheetFrame, SessionActionSheetFrame.android, SessionDetailsNative, SessionDetailsNative.ios, SessionEntryRecovery, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionListDrawer, SessionMenuSheet, SessionOptionsExpoSheet, SessionResourceCards, SessionRightSpinner, SessionSearchNative, SessionSearchNative.ios, SessionTailBanner, SessionTransientNotice, SessionUsageSummary, ShareImageNativeButton, ShareImageNativeButton.ios, ShareMessageCheckbox, ShareSelectAllButton, ShareSelectionBar, SharedTaskEndedState, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, SystemNavigationBack, TaskTags, TaskTagsSheet, ThemeProvider, ThinkingDots, TodoDateInput, TodoDateInput.android, TodoDateInput.ios, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, VoiceRecordingPill, WorkingStatusText, [sessionId], _layout, composerPullThrough, gestureHandler, listDisclosureTransition, mathWebView, mediaPlayerWebView, mermaidWebView, nativeToolbarMenuItems, peerFileTransport, useLocale, useSharedTaskConfirmation, voicePillWidthMotion | apps/mobile/app/_layout.tsx, apps/mobile/app/sessions/[sessionId].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/FileTypeIcon.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/PaperPlaneIcon.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/inputHandoff/InputHandoffCard.tsx, apps/mobile/src/inputHandoff/InputHandoffDeviceCode.tsx, apps/mobile/src/inputHandoff/InputHandoffPictureStep.tsx, apps/mobile/src/inputHandoff/InputHandoffQrCode.tsx, apps/mobile/src/inputHandoff/InputHandoffRecordRow.tsx, apps/mobile/src/inputHandoff/InputHandoffSheet.ios.tsx, apps/mobile/src/inputHandoff/InputHandoffSheet.tsx, apps/mobile/src/inputHandoff/InputHandoffStepFields.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/NativeChromeBackButton.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/PluginCardActions.tsx, apps/mobile/src/plugins/PluginMenuUnreadDot.tsx, apps/mobile/src/plugins/PluginSetupNativeActions.tsx, apps/mobile/src/plugins/PluginSetupNativeForm.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/AgentErrorDetails.tsx, apps/mobile/src/session/AnnotationBurnInWebView.tsx, apps/mobile/src/session/AuthorizationMessageCard.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ChatFileChipMenuSheet.tsx, apps/mobile/src/session/ChatIdentityHeader.tsx, apps/mobile/src/session/CindyMakeSessionGate.tsx, apps/mobile/src/session/CompanionChoice.tsx, apps/mobile/src/session/CompanionCreateNativeView.ios.tsx, apps/mobile/src/session/CompanionCreateNativeView.tsx, apps/mobile/src/session/CompanionEntering.tsx, apps/mobile/src/session/CompanionHeader.tsx, apps/mobile/src/session/CompanionImportSheet.tsx, apps/mobile/src/session/CompanionLearningFooter.tsx, apps/mobile/src/session/CompanionMemoryPage.ios.tsx, apps/mobile/src/session/CompanionMemoryPage.tsx, apps/mobile/src/session/CompanionMessageActions.tsx, apps/mobile/src/session/CompanionMessageCard.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/CompanionTaskResultCard.tsx, apps/mobile/src/session/CompanionTodoRow.tsx, apps/mobile/src/session/CompanionTodos.tsx, apps/mobile/src/session/CompanionWorkingStatus.tsx, apps/mobile/src/session/ComposerActivityPill.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerDockKeyboardFollow.tsx, apps/mobile/src/session/ComposerExpandButton.ios.tsx, apps/mobile/src/session/ComposerExpandButton.tsx, apps/mobile/src/session/ComposerFrame.ios.tsx, apps/mobile/src/session/ComposerFrame.tsx, apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx, apps/mobile/src/session/ComposerMorphSource.ios.tsx, apps/mobile/src/session/ComposerMorphSource.tsx, apps/mobile/src/session/ComposerNativeInput.ios.tsx, apps/mobile/src/session/ComposerNativeInput.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/ComposerRichInput.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/ContextSheetCollabView.tsx, apps/mobile/src/session/ContextSheetGoalView.ios.tsx, apps/mobile/src/session/ContextSheetGoalView.tsx, apps/mobile/src/session/ContextSheetMediaViews.tsx, apps/mobile/src/session/ContextSheetPlugins.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/ConversationShareSvg.tsx, apps/mobile/src/session/ConversationShareWebView.tsx, apps/mobile/src/session/FailedScheduleNotice.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/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/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/InlineQueueSection.tsx, apps/mobile/src/session/InlineQuoteChip.tsx, apps/mobile/src/session/InlineReferenceChip.tsx, apps/mobile/src/session/InteractionPanel.tsx, apps/mobile/src/session/MarkdownBlockContent.tsx, apps/mobile/src/session/McpAppCard.tsx, apps/mobile/src/session/McpAppViews.tsx, apps/mobile/src/session/MessageActionSheet.tsx, apps/mobile/src/session/MessageLoadingImage.tsx, apps/mobile/src/session/MessageRenderer.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileBoundaryNotice.tsx, apps/mobile/src/session/MobileComposerInputRow.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/NativePermissionSheet.ios.tsx, apps/mobile/src/session/NativePermissionSheet.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/NativeVideoPlayer.tsx, apps/mobile/src/session/NewTaskSelectionRow.tsx, apps/mobile/src/session/NewTaskSelectionSheet.android.tsx, apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx, apps/mobile/src/session/NewTaskSelectionSheet.tsx, apps/mobile/src/session/OrcaWorkerDirectoryPicker.tsx, apps/mobile/src/session/PendingSendBubble.tsx, apps/mobile/src/session/PlanModeChip.tsx, apps/mobile/src/session/PluginInvocationHeader.tsx, apps/mobile/src/session/PromptRecommendation.tsx, apps/mobile/src/session/QuoteCapsule.tsx, apps/mobile/src/session/ReadableHistoryRecovery.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/RewindPreviewPanel.tsx, apps/mobile/src/session/RunningTokenRatePopover.tsx, apps/mobile/src/session/SentInlineAtomBody.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/SessionEntryRecovery.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionListDrawer.tsx, apps/mobile/src/session/SessionMenuSheet.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SessionResourceCards.tsx, apps/mobile/src/session/SessionRightSpinner.tsx, apps/mobile/src/session/SessionSearchNative.ios.tsx, apps/mobile/src/session/SessionSearchNative.tsx, apps/mobile/src/session/SessionTailBanner.tsx, apps/mobile/src/session/SessionTransientNotice.tsx, apps/mobile/src/session/SessionUsageSummary.tsx, apps/mobile/src/session/ShareImageNativeButton.ios.tsx, apps/mobile/src/session/ShareImageNativeButton.tsx, apps/mobile/src/session/ShareMessageCheckbox.tsx, apps/mobile/src/session/ShareSelectAllButton.tsx, apps/mobile/src/session/ShareSelectionBar.tsx, apps/mobile/src/session/SharedTaskEndedState.tsx, apps/mobile/src/session/SharedTaskScreen.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SlowSendNotice.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/session/TaskTags.tsx, apps/mobile/src/session/TaskTagsSheet.tsx, apps/mobile/src/session/ThinkingDots.tsx, apps/mobile/src/session/TodoDateInput.android.tsx, apps/mobile/src/session/TodoDateInput.ios.tsx, apps/mobile/src/session/TodoDateInput.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/VoiceRecordingPill.tsx, apps/mobile/src/session/WorkingStatusText.tsx, apps/mobile/src/session/composerPullThrough.tsx, apps/mobile/src/session/composerRichInputHtml.ts, apps/mobile/src/session/conversationShareWebViewHtml.ts, apps/mobile/src/session/listDisclosureTransition.tsx, apps/mobile/src/session/mathWebView.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/mermaidWebView.tsx, apps/mobile/src/session/mermaidWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.ts, apps/mobile/src/session/useSharedTaskConfirmation.tsx, apps/mobile/src/session/voicePillWidthMotion.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 | 7 | 252 | 316 |+| `mobile.chat.sharing` | mobile | 共享任务邀请与成员;供应商分享链接提示 | app/shared-session.tsx / app/provider-share.tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, CompanionNativeContent.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, 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, SharedTaskAdmissionDialog, SharedTaskEndedState, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, peerFileTransport, provider-share, shared-session, useLocale, useSharedTaskConfirmation | apps/mobile/app/_layout.tsx, apps/mobile/app/provider-share.tsx, apps/mobile/app/shared-session.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/chrome/SimpleStackHeader.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/CompanionNativeContent.ios.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/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/SharedTaskAdmissionDialog.tsx, apps/mobile/src/session/SharedTaskEndedState.tsx, apps/mobile/src/session/SharedTaskScreen.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/useSharedTaskConfirmation.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 | 69 |+| `mobile.companions.cloud` | mobile | 云端伙伴:主力电脑离线时的对话与换电脑 | app/companions/cloud/[actorId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, BotGroupAvatars, BotGroupMessageText, CenteredScreen, ChatIdentityHeader, CloudCompanionScreen, CompanionCardButton, CompanionNativeContent.ios, CompanionPresenceRing, CompanionSettingsRow, CompanionSettingsRow.ios, CompanionSheet, CompanionSheet.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, IncomingShareBridge, McpAppViews, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton, NativeChromeBackButton.ios, NativeChromeButton.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, ResidentHomeList, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, [actorId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/companions/cloud/[actorId].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/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/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.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/BotGroupAvatars.tsx, apps/mobile/src/session/BotGroupMessageText.tsx, apps/mobile/src/session/ChatIdentityHeader.tsx, apps/mobile/src/session/CloudCompanionScreen.tsx, apps/mobile/src/session/CompanionCardButton.tsx, apps/mobile/src/session/CompanionNativeContent.ios.tsx, apps/mobile/src/session/CompanionPresenceRing.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/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/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/session/SheetSurface.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 | 66 |+| `mobile.companions.direct` | mobile | 伙伴私聊回看 | app/companions/direct/[threadId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, CompanionNativeContent.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, HomeStackHeader, 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, 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, ResidentHomeList, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [threadId], _layout, gestureHandler, nativeToolbarMenuItems, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/companions/direct/[threadId].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/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/CompanionNativeContent.ios.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/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/session/SheetSurface.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 | 58 |+| `mobile.companions.groups` | mobile | 伙伴群聊与分工 | app/companions/groups/[groupId].tsx | AdaptiveWindow, AgentErrorDetails, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, AuthorizationMessageCard, BlurBackdrop, BotGroupAvatars, BotGroupChatScreen, BotGroupComposer, BotGroupMenu, BotGroupMessageAttachments, BotGroupMessageText, BotGroupPlan, BotGroupQuote, BotGroupSettingsSheet, BotGroupSpeakerRow, BotGroupTaskCard, CenteredScreen, ChatIdentityHeader, CompanionCardButton, CompanionEntering, CompanionLearningFooter, CompanionMessageActions, CompanionMessageCard, CompanionNativeContent.ios, CompanionPresenceRing, CompanionSheet, CompanionSheet.ios, CompanionTaskResultCard, ComposerAttachmentTray, ComposerFrame, ComposerFrame.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ContextSheetMediaViews, DeviceLinkContext, FileTypeIcon, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, HomeStackHeader, ImageLightbox, IncomingShareBridge, InlineQuoteChip, InlineReferenceChip, InputHandoffCard, InputHandoffDeviceCode, InputHandoffPictureStep, InputHandoffQrCode, InputHandoffRecordRow, InputHandoffSheet, InputHandoffSheet.ios, InputHandoffStepFields, InteractionPanel, MarkdownBlockContent, McpAppCard, McpAppViews, MessageActionSheet, MessageLoadingImage, MessageRenderer, MobileBoundaryNotice, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton, NativeChromeBackButton.ios, NativeChromeButton.ios, NativeMcpAppSurface, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, NativeVideoPlayer, OutsideTap, PaperPlaneIcon, PendingSendBubble, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PluginCardActions, PluginInvocationHeader, PluginSetupNativeActions, PluginSetupNativeForm, PushNotificationsBridge, QuietSyncIndicator, QuoteCapsule, 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, ResidentHomeList, SentInlineAtomBody, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, ShareMessageCheckbox, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, TaskTags, ThemeProvider, ThinkingDots, WorkingStatusText, [groupId], _layout, gestureHandler, mathWebView, mediaPlayerWebView, mermaidWebView, nativeToolbarMenuItems, peerFileTransport, useLocale, voicePillWidthMotion | apps/mobile/app/_layout.tsx, apps/mobile/app/companions/groups/[groupId].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/FileTypeIcon.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/PaperPlaneIcon.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/inputHandoff/InputHandoffCard.tsx, apps/mobile/src/inputHandoff/InputHandoffDeviceCode.tsx, apps/mobile/src/inputHandoff/InputHandoffPictureStep.tsx, apps/mobile/src/inputHandoff/InputHandoffQrCode.tsx, apps/mobile/src/inputHandoff/InputHandoffRecordRow.tsx, apps/mobile/src/inputHandoff/InputHandoffSheet.ios.tsx, apps/mobile/src/inputHandoff/InputHandoffSheet.tsx, apps/mobile/src/inputHandoff/InputHandoffStepFields.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/NativeChromeBackButton.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/PluginCardActions.tsx, apps/mobile/src/plugins/PluginSetupNativeActions.tsx, apps/mobile/src/plugins/PluginSetupNativeForm.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/AgentErrorDetails.tsx, apps/mobile/src/session/AuthorizationMessageCard.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/BotGroupAvatars.tsx, apps/mobile/src/session/BotGroupChatScreen.tsx, apps/mobile/src/session/BotGroupComposer.tsx, apps/mobile/src/session/BotGroupMenu.tsx, apps/mobile/src/session/BotGroupMessageAttachments.tsx, apps/mobile/src/session/BotGroupMessageText.tsx, apps/mobile/src/session/BotGroupPlan.tsx, apps/mobile/src/session/BotGroupQuote.tsx, apps/mobile/src/session/BotGroupSettingsSheet.tsx, apps/mobile/src/session/BotGroupSpeakerRow.tsx, apps/mobile/src/session/BotGroupTaskCard.tsx, apps/mobile/src/session/ChatIdentityHeader.tsx, apps/mobile/src/session/CompanionCardButton.tsx, apps/mobile/src/session/CompanionEntering.tsx, apps/mobile/src/session/CompanionLearningFooter.tsx, apps/mobile/src/session/CompanionMessageActions.tsx, apps/mobile/src/session/CompanionMessageCard.tsx, apps/mobile/src/session/CompanionNativeContent.ios.tsx, apps/mobile/src/session/CompanionPresenceRing.tsx, apps/mobile/src/session/CompanionSheet.ios.tsx, apps/mobile/src/session/CompanionSheet.tsx, apps/mobile/src/session/CompanionTaskResultCard.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerFrame.ios.tsx, apps/mobile/src/session/ComposerFrame.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/ContextSheetMediaViews.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/InlineQuoteChip.tsx, apps/mobile/src/session/InlineReferenceChip.tsx, apps/mobile/src/session/InteractionPanel.tsx, apps/mobile/src/session/MarkdownBlockContent.tsx, apps/mobile/src/session/McpAppCard.tsx, apps/mobile/src/session/McpAppViews.tsx, apps/mobile/src/session/MessageActionSheet.tsx, apps/mobile/src/session/MessageLoadingImage.tsx, apps/mobile/src/session/MessageRenderer.tsx, apps/mobile/src/session/MobileBoundaryNotice.tsx, apps/mobile/src/session/MobileComposerInputRow.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/NativeVideoPlayer.tsx, apps/mobile/src/session/PendingSendBubble.tsx, apps/mobile/src/session/PluginInvocationHeader.tsx, apps/mobile/src/session/QuoteCapsule.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SentInlineAtomBody.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/ShareMessageCheckbox.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/TaskTags.tsx, apps/mobile/src/session/ThinkingDots.tsx, apps/mobile/src/session/WorkingStatusText.tsx, apps/mobile/src/session/mathWebView.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/mermaidWebView.tsx, apps/mobile/src/session/mermaidWebViewHtml.ts, apps/mobile/src/session/voicePillWidthMotion.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 | 251 | 209 |+| `mobile.device-management` | mobile | 设备管理 | app/devices/manage.tsx / app/devices/manage/[deviceId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, CompanionNativeContent.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceInformationFields, DeviceInformationFields.ios, DeviceLinkContext, DeviceManagementDialogs, DeviceManagementList, DeviceManagementList.ios, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, HomeStackHeader, IncomingShareBridge, McpAppViews, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, ModalContentArea, 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, RenameDeviceModal, ResidentHomeList, SettingsGroupRows, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, listDisclosureTransition, manage, nativeToolbarMenuItems, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/manage.tsx, apps/mobile/app/devices/manage/[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/DeviceInformationFields.ios.tsx, apps/mobile/src/device-link/DeviceInformationFields.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/DeviceManagementDialogs.tsx, apps/mobile/src/device-link/DeviceManagementList.ios.tsx, apps/mobile/src/device-link/DeviceManagementList.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/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/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/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/RenameDeviceModal.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/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 214 | 58 |+| `mobile.devices` | mobile | 主机详情 | app/devices/[deviceId].tsx | AccountSwitcherSheet, AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, CenteredScreen, CompanionNativeContent.ios, ComposerMorphSource, ComposerMorphSource.ios, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ConversationSearchFilterSheet, DeviceLinkContext, FoldTouchpad, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeListVisuals, HomeModeSwitch, HomeNativeStackHeader, HomeNewTaskButton, HomeProjectMachineLabel, HomeSearchBar, HomeSessionInfoMeta, HomeStackHeader, HomeSurface, HomeUnreadContext, IncomingShareBridge, McpAppViews, MobileAgentMark, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, MobileUserAvatar, MobileVendorIcon, ModalContentArea, MountOnFirstOpen, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, NativeMcpAppSurface, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PluginMenuUnreadDot, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteAccessGuide, 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, SessionOptionsExpoSheet, SessionRightSpinner, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, TaskTags, ThemeProvider, [deviceId], _layout, gestureHandler, listDisclosureTransition, nativeToolbarMenuItems, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/[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/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/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.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/CompanionNativeContent.ios.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/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/MobileOutboxBridge.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/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SessionRightSpinner.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/session/TaskTags.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 | 111 |+| `mobile.files` | mobile | 任务文件与预览 | app/files/[sessionId].tsx / app/files/preview/[sessionId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, CindyMakeSessionGate, CompanionNativeContent.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FileBrowserSegmentedControl, FileTransferBusyNotice, FileTypeIcon, FileTypeTile, FoldTouchpad, HomeEntryProvider, HtmlBrowserChrome, HtmlBrowserChrome.ios, HtmlFileReader, HtmlWebsiteBrowser, ImageLightbox, IncomingShareBridge, MarkdownFileReader, McpAppViews, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, ModalContentArea, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, NativeMcpAppSurface, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, NativeVideoPlayer, 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, SessionEntryRecovery, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SystemNavigationBack, ThemeProvider, [sessionId], _layout, gestureHandler, mediaPlayerWebView, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/files/[sessionId].tsx, apps/mobile/app/files/preview/[sessionId].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/FileTypeIcon.tsx, apps/mobile/src/components/FileTypeTile.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/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/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/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/CindyMakeSessionGate.tsx, apps/mobile/src/session/CompanionNativeContent.ios.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/FileBrowserSegmentedControl.tsx, apps/mobile/src/session/FileTransferBusyNotice.tsx, apps/mobile/src/session/HomeEntryProvider.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/MarkdownFileReader.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/NativeVideoPlayer.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SessionEntryRecovery.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.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 | 82 |+| `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, 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, 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, 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/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/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/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 | 143 |+| `mobile.overlay.connection-startup` | mobile | 根布局挂载的启动与连接反馈 | app/_layout.tsx → StartupSplashOverlay / ConnectionNoticeProvider;各页面 ConnectionBanner | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, CompanionNativeContent.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ConnectionNoticeProvider, ContextSheet, ContextSheet.ios, 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, SheetSurface, 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/CompanionNativeContent.ios.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/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/session/SheetSurface.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 | 53 |+| `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, ContextSheet, ContextSheet.ios, DeviceLinkContext, 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, 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, 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/MobileAgentMark.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/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/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/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 | 86 |+| `mobile.remote-desktop` | mobile | 远程桌面 | app/devices/desktop/[deviceId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, CompanionNativeContent.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, 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, SheetSurface, 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/CompanionNativeContent.ios.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/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/session/SheetSurface.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 | 53 |+| `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, 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, 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/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.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 | 80 |+| `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, CompanionNativeContent.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, 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/CompanionNativeContent.ios.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/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 | 69 |### 生产路由覆盖diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex e151f55e9e..f5a984a9f7 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -1,5 +1,48 @@# 跨端协议兼容+## MCP Apps++标准 MCP Apps 使用 `io.modelcontextprotocol/ui` 扩展及官方 `2026-01-26` 协议。+客户端新增独立 `maker:mcp-apps:v1` channel,复用 device-link 的同账号调用与错误协议,+不改变已有 channel、relay 帧或服务端 schema;Mobile 原生承载与指纹影响见本节末尾。+App 卡片是既有 assistant 消息 content 的可选 `mcpApp` 字段,且必须有 Main 写入的+`agentMeta.mcpApp` 标记;旧客户端不解析该字段,仍可阅读原工具返回的文本。+新控制端连接旧 Host 时拒绝该 channel 并提示更新执行电脑,不回退到执行任意 HTML。+完整交互需要执行电脑和查看端都支持 MCP Apps;共享任务访客不开放该入口。+共享访客的消息历史与推送只携带 `content.mcpAppHistory: { version: 1, title, text }`,+不发送完整 `mcpApp`、调用参数、服务器身份、schema、structuredContent 或 View-only `_meta`;+`text` 仅来自结果的 text 块。同账号与本机继续读取完整记录,持久化数据不变。+新查看端将摘要呈现为原有只读卡片;旧查看端不支持该摘要时不提供交互,完整只读显示需更新查看端。++查看端只传标准 JSON-RPC 和界面环境;执行 Host 持有 MCP 连接、账号归属、工具可见性与+审批决定。View 绑定 owner、task、card、caller 与配置版本,清空、回退、账号切换或配置+撤销后旧操作失效。轮询可有界重试,工具调用、消息发送与创建申请不自动重放。+远程外链动作单独传给控制端,在当前查看设备打开,不在执行电脑打开。+新远程查看端打开前通过同一 channel 的一次性 `authorize-link`(`viewId` / `linkId`)+向执行 Host 复核当前卡片、账号、配置与未结束的外链请求,且只接受显式+`{ authorized: true, validForMs: 30000 }` 回执。Host 原子认领请求并把原 10 秒待授权+计时替换为 30 秒结果等待,拒绝重复认领;控制端用单调时钟把整个授权往返计入+有效期,在打开浏览器前拒绝过期回包。期限内仍由 `link-result` 返回实际打开结果,+结果丢失或 View 销毁会失败收尾。旧 Host 拒绝该增量操作、回执缺失或没有有效期时不打开外链,+该次请求按失败收尾,完整外链交互需更新执行电脑;不降级为跳过授权,也不自动重放。+旧查看端可继续连接新 Host 并忽略新增回执字段,完整打开前复核需查看端更新;+没有修改既有请求字段、channel、权限范围或原生指纹。+兼容矩阵、可选能力声明与验证入口见 [MCP Apps 接入](../mcp-apps.md)。+Desktop 远程卡片复用查看端 Main 验证真实 frame 的通道;本机 IPC 的 `deviceId` 只选择+目标,不跨 device-link 传递。Main 保存远端 View 绑定,顶层 Renderer 只提交界面控制,+不能通过通用 `deviceLink.invoke` 发送 MCP Apps RPC,也不能提供 HTML 或指定 frame 的+目标 View。新查看端 Main 可连接既有 v1 Host,外链仍要求 `authorize-link` 明确回执;+Mobile 和旧查看端的 wire 保持原样,完整 frame 边界需更新 Desktop 查看端。+没有新增 channel、allowlist、relay 或原生配置。回归见 `remoteViews.test.ts`。+本机与远控 Desktop 的 open IPC 只返回 `viewId`、`transport: "sandbox"` 与 `prefersBorder`,+用于同版本 Main/Renderer 切换到 Main 验证真实 frame 的直连通道。凭证读取的 HTML、CSP 与+资源策略只由 Main 供给隔离 frame,不进入顶层 Renderer。该描述符不向远程设备返回;+Mobile 和 Desktop Main 之间的远程 v1 仍传完整文档,原有 channel 不变。Mobile 在原生+HTML 资源模块增加独立 App 资源额度和内联承载视图,+以不同来源隔离 proxy/App,并保留卸载后的有界 teardown;这改变 iOS/Android runtime+fingerprint,须遵守 [冷更边界](mobile-development.md#原生配置与-runtime-fingerprint冷更边界)。+旧 Mobile binary 保留卡片文本并提示更新手机,不回退到同源或 opaque-origin srcdoc。+> **状态**:权威开发规则(authoritative)> **读取时机**:修改插件分发来源边界、device-link 协议/relay/隧道 payload/IPC> allowlist,或任何改动客户端与服务端之间 wire protocol 的地方之前diff --git a/docs/mcp-apps-validation.md b/docs/mcp-apps-validation.mdnew file mode 100644index 0000000000..24716c4b71--- /dev/null+++ b/docs/mcp-apps-validation.md@@ -0,0 +1,319 @@+# MCP Apps 本地协议验证记录++验证日期:2026-10-15(Asia/Shanghai,日期由系统时钟取得)。++结论:官方 SDK 申请表与独立 JSON-RPC 数据看板通过同一个生产 Host 接入,+无需按业务调整 Cindy。官方 `2026-01-26` 稳定协议及 Cindy 已声明能力的本地回归通过。+本记录是本仓的互操作与沙箱验证结果,不是上游颁发的兼容认证,也不代表实现全部可选能力。++## 环境与复跑++| 项目 | 实际环境 |+| ------------ | -------------------------------------------------------------------------------------------------------------------- |+| 系统 | Windows,PowerShell |+| Node.js | 22.22.2 |+| Electron | 42.11.12 |+| MCP Apps SDK | `@modelcontextprotocol/[email protected]` |+| MCP SDK | `@modelcontextprotocol/[email protected]` |+| 协议基准 | [官方 2026-01-26 规范](https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx) |++从仓库根目录运行:++```powershell+pnpm.cmd --filter desktop test:mcp-apps:conformance+```++前序单测阶段结果为 12 个测试文件、158 项测试通过,退出码为 0。+前序两个真实 Electron 集成检查均以退出码 0 结束,分别输出+`MCP_APPS_SANDBOX_VERDICT=passed` 和 `MCP_APPS_RAW_SANDBOX_VERDICT=passed`。+`pnpm.cmd --filter desktop typecheck` 本轮通过。定向 ESLint 与当前 HEAD 基准逐项比对,+本轮代码和测试没有新增错误;`register.ts` 与 `makerSendTransaction.test.ts` 分别保留+13 项和 10 项既有错误。当前触及文件另有 coordinator 测试 3 项、Session 与视觉桥+测试各 1 项既有错误,与当前 HEAD 基准一致;没有新增错误,其余本轮文件为 0。+前序模拟/验证脚本的 ESLint 已通过。+前序自定义 MCP provider、Codex HTTP bridge 与 Pi 环境接入的 66 项回归通过;+前序作者侧修复重跑自定义 provider/registry、Codex 与 Pi 环境的 62 项回归通过。+已有卡片大小回归:完整卡片按 UTF-8 JSON 字节限制为 1 MiB,超大结果在写入前+变成标准有界错误;官方 View SDK 的实时/远程重开均能读取,模型仍收到原结果。+恰好达到上限、超出一字节、多字节文本、View-only metadata 和输入/结果合计均纳入验证。+前序新增 14 项回归:远程完整文档和事件数组使用 4 MiB 减 64 KiB 的 UTF-8 JSON+预算,覆盖多字节、引号/控制字符转义、真实 device-link invoke-result 分片编码、+超限 View 不占额度、消费后字节回收及另一控制端继续工作;普通 MCP 的 HTTP/SSE+补全、进行中的进度、订阅/退订、日志级别/通知、task 方法/状态通知和扩展请求均透传。+无上游能力时不虚报,撤权拦住迟到结果和新请求,取消只传给原请求、不重放。+普通工具调用另新增 9 项撤权竞态回归:在连接获取、工具执行、App 结果保存的等待期间,+分别切换账号、删除服务器和修改配置;等待后重新核验 owner/config,拒绝执行或向模型+返回迟到结果,已经执行的调用不重放。9 项均在修复前复现失败,修复后通过;+见 `serverProxy.test.ts`。该轮撤权修复重跑完整 MCP Apps 单测、Desktop 类型检查与+定向 ESLint,未重跑前序沙箱与真机验证。++前序 App 消息修复新增 23 项回归:所有文本块开头的斜线均转义,覆盖 Claude Code、+Pi 和 Codex 的 App 输入与来源说明,历史仍保留原文;读取任务、恢复队列、加载 metadata、+构建排队项及直发准备期间撤销卡片会阻止入队或派发,账号、清空与配置边界继续生效。+直发复用 Session 既有钩子,在 accepted 持久化前和异步准备后的最终 vendor 派发前核验;+保留主人授权意图,私有 guard 不进入队列持久快照、公开投影、历史或 provider options。+官方 App SDK 另验证发送准备期间撤销卡片、账号和服务器后没有派发。++前序另新增 26 项回归:排队后撤销卡片会阻止 drain 和排队插话;活 guard 留在 Main,+公开投影和 JSON/IPC 丢弃它。恢复快照时丢弃无活授权的 App 队列行(含旧版+来源标记),走正常 discard 结算并清理持久快照;不重造授权、不阻塞后续用户消息。+消息创建返回、历史回读和本机/同账号控制端广播均只下发公开标题与文本摘要,+完整参数、schema、structuredContent 和结果 metadata 仍留在 Main,只有授权后的+sandboxed App View 可读取;共享访客复用同一摘要白名单。回归见 `ipc.test.ts`、+`messagesWriteReadback.test.ts`、`agent-input-coordinator.test.ts` 与 `mcpApps.test.ts`。+Session 插话复用发送前的私有钩子,在异步准备后再核验;钩子不传给 provider,+钩子等待期间结束、替换或关闭的 turn 都不能接收迟到消息。+普通 MCP facade 继承下游实际 client capabilities,HTTP/SSE 的 roots、sampling、+form elicitation、roots 变更通知均到达原 harness;不同 facade 不串线,撤权后不向+上游返回迟到回调结果,无能力时不虚报。取消不重放,Main 对请求 ID 0 同样转发取消。+测试 peer 使用的 SDK 1.29 默认取消 handler 忽略数字 ID 0,因此该项直接检查 wire+通知;ID 1 同时检查实际 signal,不能把 wire 证据说成测试 peer 的 ID 0 handler 已取消。++该轮执行:++```powershell+pnpm.cmd --filter desktop exec vitest run src/main/mcp-apps/__tests__ src/main/maker-ipc/__tests__/makerSendTransaction.test.ts src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts src/main/maker-ipc/__tests__/messageSourceNote.test.ts src/main/__tests__/mobileClientPromptNote.test.ts --maxWorkers=2 --reporter=dot+pnpm.cmd --filter @cindy/maker-core exec vitest run src/session.vision-bridge.test.ts src/session.origin.test.ts src/session-control.test.ts src/session-send-outcome.test.ts src/session.close.test.ts src/session.async-user-questions.test.ts --maxWorkers=2 --reporter=dot+pnpm.cmd --filter @cindy/maker-core build+```++结果:Desktop 16 个测试文件、925 项测试通过,退出码为 0;其中 MCP Apps 为 158 项,+`makerSendTransaction.test.ts` 为 172 项,来源说明和客户端说明分别为 12 项与 68 项。+coordinator 为 515 项。maker-core 的 6 个测试文件、200 项测试及无输出构建类型检查通过;+该包没有独立 typecheck script,build 实际执行 tsc --noEmit。+该轮未重跑前序 Electron 沙箱;真实模型账号、完整卡片双主题目检和 Mobile 真机仍未验证。++| 测试文件 | 通过数量 | 主要覆盖 |+| ----------------------------- | -------: | ----------------------------------------------------------------------------------------- |+| `interop.test.ts` | 28 | 官方 App SDK、HTTP/SSE、上游 instructions、初始化失败回复、加载期间完成/撤销、模型 facade、App 消息撤权 |+| `conformance.test.ts` | 18 | 独立 JSON-RPC App、编码/metadata 组合、分页、通知、取消、能力协商 |+| `operations.test.ts` | 11 | 任务与调用者绑定、输入校验、远程操作边界 |+| `ipc.test.ts` | 9 | 卡片持久化、清空与账号竞态、删除后禁止重建、权限路由、公开错误 |+| `protocol.test.ts` | 22 | 标准 metadata、可见性、资源格式/大小、CSP 域声明与同源 base URI 默认值 |+| `sandboxProtocol.test.ts` | 10 | 不同 origin、账号隔离、权限拒绝、Renderer 生命周期回收、嵌套导航与 Escape |+| `remoteAuthorization.test.ts` | 5 | 真实 Session instance 路由、冻结装配名单、远程发现与执行授权 |+| `connection.test.ts` | 3 | 首次失败及断线后独立重连、关闭竞态、不重放已发送工具 |+| `openLifecycle.test.ts` | 4 | 加载超时、打开前取消、晚到 View 回收、调用者与任务隔离 |+| `wireBudget.test.ts` | 7 | 完整文档/事件 UTF-8 JSON 大小、转义、device-link 编码、额度回收与控制端隔离 |+| `serverProxy.test.ts` | 25 | 普通 MCP 能力、补全/进度、订阅/日志、task/扩展;客户端能力及 roots/sampling/elicitation 回调、隔离/撤权/取消 |+| `messageSender.test.ts` | 19 | App 命令转义、来源与历史保留、发送/入队准备与入队后撤权、序列化丢授权与旧行拒绝 |+| `resultDelivery.test.ts` | 9 | 晚到结果/取消撤权、保存失败、延迟初始化、正常交付与其他卡片隔离 |++作者侧修复另经 Desktop 卡片可见性、MCP 目录与 SSH bridge、安全守卫定向测试验证;+Mobile 的卡片导航/HTML 注入与三个受影响消息展示测试共 39 项通过。共享 controller/+文档测试 13 项、device-link 超时与重试策略测试 31 项通过;Desktop、Mobile 与两个+共享包的类型检查、定向 ESLint、i18n 及设计台账检查通过。未用本地定向结果替代完整 CI。++前序跟进开始时旧 head `8cd728d` 的 [Linux unit tests (1/2)](https://github.com/makecindy/cindy/actions/runs/38636206425/job/116099904816) 失败:+`linuxInstallation.test.ts` 在 beforeAll 制作 `.deb` 夹具时,`ar rc … package.deb debian-binary data.tar.gz` 返回失败。+日志没有给出具体 stderr/退出原因,不能认定为瞬态;该安装器测试不在 PR 改动范围,+该轮未修改或跳过它。完整 CI 仍由新 head 正常触发并决定通过与否。++## 关闭握手补充验证(2026-10-15)++关闭控制器现在会等待其主动发送的 teardown 回执,收到 result/error 或达到发送后的+1 秒上限才通知 Host 释放 View。重复关闭共用同一等待,不把本地回执交给未发起该请求的+Host bridge;未主动通知时仍转发 Host 的标准 teardown 握手。++新增 4 项控制器回归,其中成功回执、错误回执和超时的 3 项在修复前复现提前关闭;+修复后控制器 14 项、共享文档 3 项、Desktop Host 协议与卡片 19 项、Mobile 卡片 3 项通过。+覆盖异步回执前不释放、错误回执完成、相同 ID 请求或无关响应不能完成清理、重复关闭、+从通知时刻计算的上限、晚到回执丢弃,以及关闭期间保留 Host 请求/响应路由。++head `298ad2a` 的 [Linux unit tests (2/2)](https://github.com/makecindy/cindy/actions/runs/38643078077/job/116123167873)+另有 3 项委派发送、1 项目标模式测试失败,原因均为源码片段的 Function 夹具没有注入+新增 Symbol,错误为 `MCP_APP_MESSAGE_GUARD is not defined`;本机均复现。+补入真实模块导出的 Symbol 后,`pluginTaskAuthorshipWiring.test.ts` 的 17 项与+`goal-host/__tests__/controller.test.ts` 的 228 项通过,原授权与目标模式断言保留。+本次定向测试合计 7 个文件、284 项通过,完整 CI 需在新 head 正常重跑后判定。++```powershell+pnpm.cmd --filter @cindy/maker-shared exec vitest run src/__tests__/mcpAppController.test.ts src/__tests__/mcpApps.test.ts --reporter=dot+pnpm.cmd --filter desktop exec vitest run src/main/mcp-apps/__tests__/conformance.test.ts src/renderer/components/chat/__tests__/McpAppCard.test.tsx --maxWorkers=2 --reporter=dot+pnpm.cmd --filter mobile exec vitest run src/__tests__/mcpAppCard.test.tsx --maxWorkers=2 --reporter=dot+pnpm.cmd --filter desktop exec vitest run src/main/maker-ipc/__tests__/pluginTaskAuthorshipWiring.test.ts src/main/goal-host/__tests__/controller.test.ts --maxWorkers=2 --reporter=dot+pnpm.cmd --filter @cindy/maker-shared run --if-present typecheck+pnpm.cmd --filter @cindy/maker-shared build+pnpm.cmd --filter desktop run --if-present typecheck+pnpm.cmd --filter mobile run --if-present typecheck+pnpm.cmd --filter @cindy/maker-shared exec eslint src/mcpAppController.ts src/__tests__/mcpAppController.test.ts+pnpm.cmd --filter desktop exec eslint src/main/maker-ipc/__tests__/pluginTaskAuthorshipWiring.test.ts src/main/goal-host/__tests__/controller.test.ts+```++maker-shared 没有独立 typecheck script,build 实际执行 `tsc --noEmit`,已通过;+Mobile 与 Desktop 类型检查均通过。+上述定向 ESLint 和文档合同检查(10 项)通过。+本次未重跑 Electron 沙箱,也未完成 macOS、Mobile 真机或完整卡片双主题目检。+当时 Mobile 原生卸载不能保留 WebView,属于尽力通知;未将单测结果当作原生异步清理完成的证据。+2026-10-16 的修复改为根级持有 WebView、原生 slot 内联承载,等待回执或 1 秒后再销毁,+实现与当前验收边界见 [MCP Apps 接入说明](mcp-apps.md)。原生实际运行仍须单独验收。++## 共享任务访客历史卡片补充验证(2026-10-15)++Desktop 和 Mobile 在挂载交互卡片前识别共享任务 peer,只展示名称、保存结果中的+text 块和主人专属操作说明。无结果时仍显示名称与说明;React / 原生 Text 将文字作为+正文显示,不执行其中的 HTML,不展示 View-only `_meta`、structuredContent 或嵌入资源。+Host 仍拒绝访客 MCP Apps 请求,房主本机和同账号远控仍使用原交互卡片。++- 定向回归 9 文件 / 136 项通过:Desktop 卡片、历史投影及 IPC 17 项;Mobile 卡片、+ 历史投影、文字规范、五语 catalog 与来源文案 115 项;共享记录投影 4 项。覆盖访客+ 零 Host 调用、无 iframe/WebView/重试按钮、保存文字与空结果、主人本机/远控打开和离屏回收。+- Desktop、Mobile typecheck 通过;maker-shared 无单独 typecheck,`build` 的+ `tsc --noEmit` 通过。i18n key、术语检查及文档合同 10 项通过。+- Desktop / 共享包改动文件 ESLint 除 `makerChatStore.ts` 外通过。该文件 3832、4159、+ 11184 行的 3 项错误及 11182 行的 1 项警告,在原 head 与工作区逐项相同;均在本轮+ 改动外。Mobile ESLint 未执行成功:包内没有 `eslint.config.*`,退出码 2,未添加临时配置+ 或放宽规则。+- 两端新增说明已逐语核对简中、繁中、英、日、韩的含义及编码,未做母语者复核。+ 测试覆盖 Light/Dark 状态分支,不计作真实 UI 目检;本轮未启动 Electron 沙箱或 Metro,+ 未完成卡片双主题实机、macOS、Mobile 真机或真实双账号联调。++## 晚到工具结果撤权补充验证(2026-10-15)++结果保存失败时,Host 不再替换或投递晚到数据,而是释放同一账号、任务和卡片的全部 View,+并保留原错误。初始化输入和结果/取消通知发送前复用当前卡片校验;校验失败也回收 View。+持久化只允许新建待执行卡片,已删除行的结果/取消更新会明确失败,不重新创建卡片。++- 新增 Host 回归 9 项,其中 7 项在修复前复现越权投递或未回收;补充 IPC 回归 3 项,+ 其中 2 项在修复前复现删除后重建。覆盖本机与远程 View、已初始化与等待初始化、+ 保存失败及保存后撤权、完整结果和取消、正常交付一次、其他卡片不受影响及新卡片创建。+- MCP Apps、WebView 安全与 CSP 定向回归共 15 文件 / 258 项通过,退出码 0;+ Desktop typecheck、所改 Host/IPC 及测试 ESLint、文档合同 10 项均通过。测试使用+ 内存依赖与现有 loopback fixture,没有读取用户数据库或连接生产服务。+- head `1053f64` 的 [client-ci](https://github.com/makecindy/cindy/actions/runs/38650071286)+ 中 verify-checks、Desktop Git integration、Windows unit tests (1/2) 的根级 runner+ 均因设计台账过期失败:上轮只读卡片新增的圆角未重新生成计数。本轮运行+ `pnpm.cmd design:inventory`,仅更新三个 surface 各增加 1 的圆角计数,人工区不变。+ `check:design-inventory` 与设计台账合同 52 项通过,未跳过或放宽门禁。++```powershell+pnpm.cmd --filter desktop exec vitest run src/main/mcp-apps/__tests__ src/main/__tests__/webview-security.test.ts src/main/security/__tests__/csp.test.ts --maxWorkers=2 --reporter=dot+pnpm.cmd --filter desktop run --if-present typecheck+pnpm.cmd --filter desktop exec eslint src/main/mcp-apps/host.ts src/main/mcp-apps/ipc.ts src/main/mcp-apps/__tests__/resultDelivery.test.ts src/main/mcp-apps/__tests__/ipc.test.ts+pnpm.cmd check:design-inventory+node --test scripts/__tests__/design-inventory.test.mjs+pnpm.cmd check:dev-docs+```++本轮未重跑真实 Electron 沙箱、Mobile 真机或 macOS;本地定向结果不替代新 head 的完整 CI。++## 两个独立 App++1. **申请表**:服务器使用官方 `registerAppTool`/`registerAppResource`,View 使用官方 App SDK。+ AI 预填后,用户修改并创建内存申请;更新模型上下文不启动模型轮次,明确发送消息才触发测试回调。+2. **数据看板**:View 只使用标准 JSON-RPC/postMessage;服务器使用普通 MCP SDK 低层 handler,+ 不依赖 ext-apps 注册 helper。使用不同工具名和 `ui://` 资源,默认 blob HTML、list-level metadata,+ 另测 text HTML、read-level metadata 与旧 `ui/resourceUri`。刷新、消息、上下文、模式和尺寸均走同一 Host。++两种服务器都提供随机 loopback Streamable HTTP 与 SSE,互操作测试覆盖两种传输;+真实 Electron 检查分别通过 Streamable HTTP 加载两种 App。+工具数据全在内存中,不连接 GM 生产接口、不创建真实申请、不发送消息给其他人。++## 协议覆盖与证据++卡片中的完整工具结果均指 1 MiB 序列化预算内的数据;超限只交付标准有界错误。++| 协议项 | 本次验证 |+| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| 扩展与 MIME | Client 声明 `io.modelcontextprotocol/ui`;读取 `text/html;profile=mcp-app`;两种服务器与传输均可发现 UI |+| 工具发现与可见性 | 支持 `_meta.ui.resourceUri` 和旧键;默认 model+app;模型看不到 App-only 工具,View 不能调用 model-only 工具;工具分页不会漏项 |+| HTML 资源 | text/blob 两种编码;read/list metadata;拒绝错误 URI/MIME、非法 base64 和超过 4 MiB 的资源;远程完整文档按 UTF-8 JSON 计量,超限在保留 View 前拒绝 |+| 远程响应大小与背压 | 完整文档及 poll 事件数组最多 4 MiB 减 64 KiB,预留 invoke-result 封装;UTF-8、JSON 转义、数组括号/分隔符计入;已消费事件按相同字节回收,另一控制端继续工作;见 `wireBudget.test.ts` |+| 初始化、版本与 ping | `ui/initialize` 协商 `2026-01-26`;未知请求版本返回实际支持版本;initialized 前不发输入/结果、拒绝工具调用;拒绝重复初始化;ping 正常 |+| 模型 MCP 初始化 | HTTP/SSE 上游 `instructions` 和实际 capabilities 在标准 initialize 中保留;SDK 的 serverInfo 和版本协商保留;owner 变化时明确回复错误;见 `interop.test.ts` 与 `serverProxy.test.ts` |+| 模型 MCP 标准能力 | HTTP/SSE 补全、资源订阅/退订、日志级别/通知、task 方法/状态通知及扩展请求透传;任务式工具调用仍检查 model 可见性;取消不重放,迟到结果重新检查 owner/config;见 `serverProxy.test.ts` |+| 输入、结果与模型隔离 | initialized 后按输入、结果顺序交付;text/image/audio、嵌入文本/二进制资源、resource_link、structuredContent 与 `_meta` 完整保留给 View;模型 facade 去掉结果根 `_meta`;加载期间完成或取消仍正确交付 |+| App 工具调用 | 只连接产生卡片的 server;按任务授权;拒绝授权时服务器不执行;保留工具 `isError` 与 View metadata;不重放写操作 |+| 资源与列表变更 | resources/read/list/templates、prompts/list;resources/list 游标可继续分页;tools/resources/prompts 的 list_changed 到达 App,刷新后工具定义更新 |+| 连接生命周期 | 超过 Host 额度的闲置 facade 不登记连接;首次请求(包括 initialize)登记,后续请求复用连接 ID,代理关闭后释放;回归见 `interop.test.ts` |+| 远程文档生命周期 | Renderer 重载、崩溃或销毁后,旧供片返回 404 并可重新挂载;同文档/子 frame 导航、其他 Renderer 与本地 Host 供片保留;回归见 `sandboxProtocol.test.ts` |+| 消息与模型上下文 | `ui/message` 支持稳定单块与数组形状、text/resource_link;App 原生命令转为普通文字并保留来源和历史原文,入队及最终派发前核验卡片/View;上下文支持 text/structuredContent,后一次替换旧值;发送接受后仅消费本次快照,失败或主人原生命令保留,更新与发送重叠时不丢新值;单独更新不启动轮次;未声明模态明确失败 |+| 打开链接 | `ui/open-link` 转交查看端 controller;成功/失败均有 RPC 结果;拒绝 javascript 与含凭证的 URL;不让 App 自身导航离开资源 |+| 显示与尺寸 | inline/fullscreen 协商;App 限制仅 inline 时返回 inline;pip 请求返回实际支持模式;host-context-changed 同步模式;真实浏览器按 size-changed 改变 iframe 高度 |+| 环境与主题 | locale、时区、容器尺寸、安全区域和工具信息可读;Host context 可增量更新;真实 Electron 内两种 App 的 Light/Dark 背景随 CSS variables 切换 |+| sandbox 隔离 | 标准 sandbox-ready 与生产 proxy 供片;App 无 preload、require、process;不能读取不同 origin 的父文档;供片绑定当前账号 |+| CSP 域声明 | 真实浏览器中 connect/resource/frame/baseUri 声明域可用;未声明 fetch 和嵌套导航均被阻断,禁止域 HTTP 请求计数为 0 |+| 系统权限 | Host permissions 为空;真实 Permissions Policy 拒绝 camera、microphone、geolocation、clipboard-write;Electron request/check 两道守卫拒绝 App 及其外部后代 frame 的系统权限,真实 App 的通知权限请求返回 denied |+| 取消与销毁 | `notifications/cancelled` 传到正在执行的 server 工具,且执行次数为 1;`ui/resource-teardown` 完成握手后释放;供片变为 404;清空、删 server 或账号切换后旧 View 不可用 |+| 未支持能力 | 不声明 sampling、downloadFile;相应请求与未知方法返回 `-32601`;不声明的图像/音频消息或上下文明确拒绝,不静默丢内容 |++工具输入片段通知是可选项,当前发送零次 partial 通知并在初始化后发送完整 arguments。+工具结果的图像/音频块能完整到达 View,不代表 Host 支持图像/音频 `ui/message` 或模型上下文。+Desktop 声明 inline/fullscreen,Mobile 声明 inline;不声明 pip 或任何系统权限。++## 实测发现并修复的问题++生产导航守卫原先把 App 内声明过 `frameDomains` 的嵌套 iframe 也拦截了。+这会导致符合标准、使用外部嵌入内容的 App 无法加载该内容。++修复后沿真实 frame 的父链找到所属 App 资源,只按该资源重新校验的 `frameDomains`+授权后代 frame。App 自身和外层 sandbox 的导航限制保留;账号不匹配或供片撤销时没有授权。+真实 Electron 已确认声明域可加载、未声明域无网络请求;回归单测同时确认不同协议、+本地文件和其他 App 的供片地址仍受限。验证过程中主动访问禁止域产生的+`ERR_BLOCKED_BY_CSP` 是预期阻断证据,以最终退出码和 verdict 判断检查结果。++## 验证边界++这些结果说明:遵守上述稳定协议、使用 Cindy 已声明能力的不同 Apps 可以复用现有 Host 接入,+无需编写申请表或数据看板专用前端逻辑。它不保证未知的未来协议版本,或要求未声明可选能力的 App。+后续 SDK/协议升级需复跑同一套检查并补充新增能力覆盖。++真实浏览器检查加载生产 Host/controller/custom-scheme sandbox,但卡片存储、权限与消息使用测试回调。+尚未联调真实模型账号与完整 Cindy React 卡片,不等同于完整产品 UI 的 Light/Dark 实机目检。+大小检查只约束本版本的新卡片写入,不批量改写此前已经保存的历史记录。+上游 instructions 透传恢复模型既有的服务器说明,并在 facade 初始化时建立认证连接;+本地协议 fixture 验证字段与失败语义;修改边界的运行期测量见下节,+真实模型的缓存率、完整启动耗时、token 用量或调用决策准确率未测量。+Mobile 真机、真实 SSH 主机、真实 GM endpoint 仍待端到端验收。+本地模拟与自动验证不修改用户 MCP 设置,不连接生产业务接口。++## 外链授权有效期回归(2026-10-16)++Host 的 `authorize-link` 现在一次性认领待处理外链,把原 10 秒待授权计时替换为+30 秒结果等待,并返回 `validForMs`。Desktop Main 和 Mobile 共享控制器用单调时钟+把整个授权往返计入期限,在调用系统浏览器前拒绝过期回包。重复认领不延长期限,+结果丢失、撤权和 View 销毁按失败收尾;不重放浏览器动作,不重置 link 或 relay。++新增回归复现了旧代码在授权后原计时到期、过期授权回包仍打开浏览器的情况。+修复后 Desktop 4 文件 / 96 项、共享包 2 文件 / 61 项、Mobile 2 文件 / 26 项通过;+Desktop、Mobile 类型检查及 maker-shared 的 `tsc --noEmit` 通过,定向 ESLint 通过。+随后完整 MCP Apps 回归 19 文件 / 354 项通过,文档合同 10 项通过。+测试初始化夹具最初未完成握手,随后补齐;fake timer 清理顺序导致的 hook 超时也已修正,+未将这两类夹具错误作为产品问题或通过证据。++## 核心指标的运行期边界测量(2026-10-16)++影响评估:新增 MCP facade 可能影响稳定工具目录/instructions(缓存前缀输入)、+初始化与工具返回速度、发给模型的内容与额外轮次(用量),以及参数/结果/事件的准确性。+本 PR 未改 system 段、模型映射或 usage 计量;App 上下文只作为外部数据进入用户消息。++复跑命令:++```powershell+node apps/desktop/scripts/mcp-apps-sandbox.verify.mjs --metrics+node apps/desktop/scripts/mcp-apps-sandbox.verify.mjs --raw --remote --metrics+```++方法:真实隔离 Electron 加载生产 Host、facade、controller 与不同 App,+上游使用真实 loopback HTTP MCP server,下游使用 SDK InMemory transport,存储与消息发送+使用内存回调。每种 App 交替执行 30 次直接工具调用和 30 次 facade 调用,逐次比较结果+(只移除有意不交给模型的根 `_meta`),并比较工具目录与 instructions;App 编辑上下文后再比较。+没有真实模型请求、生产业务调用或用户数据库访问。++| 运行测量 | 官方 SDK 申请表 | 独立 raw 看板 |+| --- | ---: | ---: |+| facade 初始化 | 11.85 ms | 8.44 ms |+| 直接调用 mean / p95 | 12.99 / 16.40 ms | 13.63 / 17.72 ms |+| facade 调用 mean / p95 | 28.02 / 32.90 ms | 50.52 / 64.45 ms |+| 稳定工具目录 | 699 bytes,30 次及编辑后完全相同 | 310 bytes,30 次及编辑后完全相同 |+| 工具结果比较 | 30/30 相同(仅根 `_meta` 按边界剔除) | 30/30 相同(仅根 `_meta` 按边界剔除) |+| 直接/模型可见结果 | 225 / 127 bytes | 863 / 759 bytes |+| 最新 App 上下文 | 231 bytes,接受后消费一次 | 239 bytes,接受后消费一次 |+| 编辑上下文启动模型轮次 | 0 | 0 |+| 明确发送消息启动回调 | 0(此检查未点击发送) | 1 |++结论:修改边界未引入易变工具定义、未丢失模型可见结果,App 编辑不会启动多余轮次。+facade 比直接调用增加了约 15.03 / 36.89 ms 的本地平均耗时,包含调用前工具发现与校验;+raw 服务器使用三页目录,不能把这组本地测量外推为 SSH、真实网络或数据库性能。+两项完整沙箱检查均退出 0。真实供应商的 prompt cache 命中率、token 用量和模型决策准确率+仍未测量,输出对应值为 `null`;本记录只证明实际修改的 MCP/上下文边界,不宣称线上指标通过。diff --git a/docs/mcp-apps.md b/docs/mcp-apps.mdnew file mode 100644index 0000000000..6e7e1e6d00--- /dev/null+++ b/docs/mcp-apps.md@@ -0,0 +1,242 @@+# MCP Apps 接入与验证++Cindy 实现通用 MCP Apps Host。业务服务器按官方协议提供工具与 HTML 资源,+可以使用官方 MCP Apps SDK,也可以自行实现标准消息;无需修改 Cindy 前端,+也无需把页面做成 Cindy `.cindy` 插件。+基准为 [官方 `2026-01-26` 规范](https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx),+Host 与 View 互操作使用 `@modelcontextprotocol/[email protected]`,MCP SDK 保持现有 1.x。+模型 facade 在首次 MCP 请求(包括 `initialize`)时登记连接,未使用的桥接工厂不占 Host 连接额度。+代理关闭时释放连接;仍被打开的 View 使用的连接保留到该 View 关闭。+标准初始化回复逐字保留上游 MCP 的可选 `instructions`,由 Main 的认证连接读取;+协议版本与 capabilities 仍由官方 SDK 协商。初始化失败会返回明确的 RPC 错误。++## 协议兼容矩阵++卡片中的完整工具结果以 1 MiB 持久化预算为界;超限处理见下文「接入」。++| 官方协议项 | Cindy 行为 | 验证 |+| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |+| Client extension / MIME | 声明 `io.modelcontextprotocol/ui` 与 `text/html;profile=mcp-app` | HTTP、SSE 官方 SDK 互操作 |+| 工具发现 | 解析 `_meta.ui.resourceUri`,兼容 `ui/resourceUri`;读取 `ui://` 资源 | metadata / URI 单测 |+| 工具可见性 | 默认 model+app;App-only 不给模型,model-only 不给 View | 官方 SDK 互操作、远程授权回归 |+| 资源读取 | `resources/read` 支持 text、base64 blob;优先读取内容 metadata,缺失时查 resources/list | 资源 / MIME / 大小 / base64 单测 |+| 初始化 | 官方 AppBridge 协商版本、Host/App capabilities、Host context | 独立官方 App SDK |+| iframe proxy | Host、外层 proxy、View 相互隔离;保留标准 sandbox-ready 通知与完整 HTML;桌面通过不同 custom origins 提供同一 HTML 和 CSP headers | 真实 Electron 集成 |+| 工具输入 / 结果 | initialized 后先给完整 arguments,再给完整 ContentBlock、structuredContent 和 View-only `_meta`;模型结果去掉根 `_meta` | 初始化 / 顺序 / 结果互操作 |+| 工具输入片段 | 可选;当前在工具调用时发送完整输入,无 partial 通知 | 完整输入顺序测试 |+| 取消 / 销毁 | 标准 cancelled 与 resource-teardown;等待响应,有界退出,撤销本地供片 | 官方 SDK 与 Electron 集成 |+| App 调工具 | 只连接产生该卡片的 MCP server;复用任务权限卡;发起审批前、审批后与结果返回前再次核对归属、清空与配置 | 可见性 / owner / 撤销 / IPC 回归 |+| MCP 资源与通知 | 转发 resources/read/list/templates、工具列表、prompts/list 与 list_changed;不开放任意 server 或 endpoint | 官方 SDK、连接和操作测试 |+| `ui/open-link` | 仅 http/https,无内嵌凭证;在当前查看设备的系统浏览器打开,失败返回 RPC 错误 | controller / Host / URL 单测 |+| `ui/message` | 支持 text、resourceLink;原生命令转为普通文字,历史保留原文;保留 user role 和真实 App 来源,不作为主人授权;入队及最终派发前重新核验卡片和 View | 官方 SDK 互操作、来源与发送回归 |+| `ui/update-model-context` | 支持 text、structuredContent;按 View 替换最新值,不启动模型;下次发送或插话附加外部应用上下文,接受后消费这份快照,失败保留;不进入 system prompt | 官方 SDK、发送链回归 |+| 显示模式 / 尺寸 | Desktop inline+fullscreen,Mobile inline;返回实际模式;size-changed 调整高度;Host context 同步模式变化 | 互操作、controller 生命周期 |+| 主题 / 环境 | Light/Dark、CSS variables、locale、时区、尺寸和设备能力通过 Host context 传递 | Electron 中主题切换、类型检查 |+| CSP / 权限 | 按 connect/resource/frame/baseUri domains 构建 CSP;默认拒绝未声明网络;权限声明为空,拒绝摄像头、麦克风、定位和剪贴板 | 注入单测、真实 Electron 阻域 |++“符合标准”包含如实协商可选能力,并不表示 Host 宣称支持所有可选能力。View 对接的 AppBridge 当前不声明+sampling、downloadFile、pip、图像/音频 `ui/message` 或图像/音频模型上下文。App 必须先检查+Host capabilities;不支持的调用明确失败,不静默丢内容。工具结果本身仍完整交给 View。+后续标准新增版本需要升级并重新验证 SDK;使用上述稳定协议的新 App 不需要业务特例。++桌面允许 App 内的嵌套 iframe 加载该资源声明的 `frameDomains`,并核对所属 App 和当前账号。+这项授权只适用于资源的后代 frame;App 自身和外层 proxy 仍保持原导航边界。+未声明域、不同协议、其他 App 的供片地址和本地文件不会因此获得访问权限。++Desktop(本机和远程卡片)的 App RPC 双向传输由可信 proxy 直接发给 Main,不经过顶层 Renderer。+open IPC 只返回 `viewId`、`transport: "sandbox"` 与 `prefersBorder`;私有 HTML、CSP 和+资源策略只由 Main 供给隔离 frame。远程 v1 仍向 Mobile 与查看端 Main 发送完整文档。+Main 按 Chromium 的真实请求 frame、所属窗口、账号与供片记录验证通道,内部鉴别值不进入+HTML、preload 返回值或 JavaScript Request。顶层 Renderer 的 message/poll/link-result+操作被拒绝;它只观察初始化、尺寸、显示模式等界面状态,不能伪造 App 调用或 Host 结果。+回归见 `sandboxProtocol.test.ts`、`sandboxBridge.test.ts` 与真实 Electron 沙箱验证。+其中 `host-context-changed` 只接受 Host 轮询返回的事件;App 自报的同名通知不能改变+卡片显示模式,App 的初始化和尺寸通知仍正常转发。真实沙箱验证同时覆盖伪造通知被拒绝+与标准 `ui/request-display-mode` 成功后的模式同步。+远程 Desktop 的专用本机入口仅允许打开、取消、环境和显示状态及关闭;Main 取得远端文档后+绑定本机账号、窗口、任务、设备和远端 View,只将真实 frame 的请求转发到既有 device-link。+通用 `deviceLink.invoke` 不再转发 MCP Apps channel,Renderer 也不能提供远端 HTML、+重绑 View 或直接打开 App 外链。外链只能来自 Main 保存的轮询事件,在执行 Host 明确复核+该 `linkId` 后由查看端 Main 打开。关闭期间保留 frame;窗口重载/崩溃仅取消和回收本窗口的+加载及 View。短暂断连只重试该 View 的读取轮询,最多 30 秒,不重放工具/消息,不重置+其他控制端或 relay。回归见 `remoteViews.test.ts` 与 `deviceLinkIpc.test.ts`;双机实测待补。+App 发起的工具调用与工具、资源、模板、提示列表及资源读取在上游完成后,交付结果前再次核验+当前 View、卡片、账号、服务器配置和取消信号;撤权后的晚到结果被丢弃,不重放上游调用。+工具发现完成后、发起权限请求前也执行同一复核,避免已撤权的 View 弹出审批。+回归见 `viewAuthorization.test.ts`。++Mobile 扩展已有原生 HTML 资源模块,分别在两个 loopback 端口提供可信 proxy 与 App,+两者同站但不同源;App iframe 使用 `allow-scripts allow-same-origin`,保留 localStorage /+IndexedDB 的来源能力,同时不能访问 proxy 或跳转顶层页面、打开弹窗。原生 HTTP 响应提供+App 的完整 CSP,proxy 的资源地址由宿主固定,不能被普通桥消息替换为同源内容。+原生 App 资源与普通 HTML 预览分别计数:App 最多 16 个来源服务,容纳 4 个活跃 View 的+双来源与退出期间的余量,普通预览仍限制为 4 个。原生内联 slot 承载根级 React host 持有的+同一个 WebView;卡片离屏或实际页面卸载后,先将内容移回屏幕外 host,保留消息回调,+收到 teardown 响应或满 1 秒后移除 WebView、停止两项资源服务并清理专属缓存。退后台+关闭旧 View,原生资源最多保留本次后台代次 1 秒;回前台打开新 View,不重放工具调用。+这改变两端 runtime fingerprint,必须有针对冷更的明确确认并发布原生新包;不能仅 OTA 交付。+旧安装包缺少 App 承载能力时保留已保存文本并提示更新手机,不回退到同源或 opaque-origin+`srcdoc`。下次进程首次打开时清理中断遗留的本功能随机目录。iOS 使用非持久 WebView+数据存储;Android 不使用会清空其他 View cookie 的 incognito 开关,只删除本 View 的+cookie,并避免本进程重用已发放的 App 端口。资源来源先加载可信初始化页,同步清除+localStorage/sessionStorage、等待所有旧 IndexedDB 删除成功后才加载原始 App HTML;+删除失败或被阻塞时不运行 App,由初始化超时报错。实际存储清理与端口重用隔离仍须+Android 原生验收。Android 的 WebView 导航回调没有+`isTopFrame`,因此声明的 `frameDomains` 仍按域校验,不把缺失字段当成顶层导航;+iOS 另保留显式顶层请求拦截;可信 proxy 同时检查实际 `event.origin`,同一 WindowProxy+导航到声明的第三方 frame 域后也无法获得 App 桥。回归见+`apps/mobile/src/__tests__/mcpAppCard.test.tsx` 与 `mcpAppNativeDocument.test.ts`。这些测试+使用 JS mock/VM,不是原生存储、内联 slot、异步 teardown 或系统返回手势的真机证据。+手机卡片只在消息列表项可见或被定位时打开 View,离屏释放并保留高度占位,重新进入时+重新读取;打开期间离屏会取消加载并回收晚到的 View,不重放 App 工具调用。++## 接入++在 Cindy 设置中添加普通自定义 MCP,选择 Streamable HTTP 或 SSE 地址及所需认证。+凭证留在 Main 的现有密钥存储中,不进入 iframe。Claude Code、Codex、Pi 都通过同一+Host facade 调用自定义 MCP;支持 Apps 的工具执行时生成独立卡片,历史卡片可重新连接。+不支持 UI 扩展的普通 MCP 保持文本工具使用方式。+模型侧 facade 继承下游 harness 实际声明的 client capabilities(含其他 extensions),+再追加 Apps extension;roots、sampling、elicitation 与普通服务器回调只返回产生该+连接的 harness,客户端通知(如 roots/list_changed)沿同一连接转发。回调返回前+再次核验账号与服务器配置;取消按请求 ID 转发,不重放。View 的 AppBridge 不因此+获得 sampling 等可选能力。+模型侧 facade 如实透传上游 capabilities;补全、资源订阅/退订、日志级别、普通扩展请求+与 MCP task 方法仍由同一认证连接处理,资源更新、日志和 task 状态通知返回原模型连接。+进度 token 映射及取消跟随单次请求;异步结果返回前再核对账号和服务器配置。+工具调用仍检查 model 可见性。MCP task 异步调用沿用上游结果,不额外生成 App 卡片;+这些模型侧能力不扩展 App 沙箱已声明的可选能力。++SSH 远端使用既有认证桥和 Session instance 路由;只暴露实际配置的自定义 server,+仍拒绝无关的本机 MCP。伙伴的自定义 server 还需出现在冻结的工具装配名单里。+设备互联和手机端只负责显示与转发,不下放凭证。远程调用授权已做 loopback 回归;+尚未验证真实 SSH 主机与真机 Mobile 的端到端行为。+共享任务访客在 Desktop 和 Mobile 只显示卡片名称、已保存结果中的 text 块和主人专属+操作说明,不挂载交互 View、不请求 MCP Apps channel;没有文字结果时仍保留名称与说明。+历史、增量推送和离线队列在 Host 的共享访客 wire 边界统一投影为仅含版本、名称和公开+文本的 `mcpAppHistory`;不下发调用参数、服务器身份、schema、structuredContent、+View-only `_meta`、嵌入资源或未知附加字段,持久化的房主完整记录不变。房主本机及同账号远控+继续使用交互卡片,Host 的访客拒绝规则保持不变。回归见两端 `McpAppCard` 测试与+`packages/maker-shared/src/__tests__/mcpApps.test.ts`。++资源上限为 4 MiB;每个远程查看端最多同时打开 4 个 View,本地查看端 16 个。+远程文档(含 HTML、CSP、policy 与 viewId)和 poll 的完整事件数组按 UTF-8 JSON 字节+计量,上限为 4 MiB 减 64 KiB,给 invoke-result 与路由封装留出余量;多字节文本、+JSON 转义、数组括号和分隔符均计入。超限文档在保留 View 前明确拒绝;事件背压+只作用于该 View,确认已消费事件时回收相同的 UTF-8 字节,不重建共享连接。+持久卡片按完整 `{mcpApp: record}` 的 UTF-8 JSON 字节计量,上限 1 MiB,+为 4 MiB View/device-link 传输中的历史行转义、初始化和输入/结果封装保留余量。+结果使卡片超限时,在写入前替换为标准 `isError` 与 `MCP_APP_RESULT_TOO_LARGE`,+实时及重开 View 使用同一有界结果;原工具返回给模型的内容保持不变。+输入或工具 metadata 本身超限时拒绝存卡,不写入超大历史,也不阻止原工具执行。+Desktop 卡片仅在可见时打开,离屏或窗口隐藏时释放 View,重新可见后重新加载。+主动关闭时,控制器先发送标准 `ui/resource-teardown`,从发送时起最多等待 1 秒,+收到对应 JSON-RPC result/error 或超时后再让 Host 释放 View;并发关闭等待同一次清理。+Desktop 在此期间保留隐藏 iframe 与回执监听。Mobile 由根级 host 保留同一个原生+WebView 与回执监听,消息卡片卸载时先移回屏幕外,再按同一上限回收;实际原生运行仍待验收。+回归见 `packages/maker-shared/src/__tests__/mcpAppController.test.ts`。+承载本地或远端卡片的 Renderer 重载、崩溃或销毁时,Main 同时回收该 Renderer 的 HTML+供片和 Host View,立即释放额度,并取消该查看端尚未完成的加载,拒绝晚到 View;同文档+导航、子 frame 导航、其他窗口和设备的 View 及仍被使用的连接不受影响。+回归见 `sandboxProtocol.test.ts` 与 `openLifecycle.test.ts`。+单次模型上下文按请求参数的 UTF-8 JSON 字节计量,上限 128,000 字节;每个任务的+完整上下文数组上限 512,000 字节,包含 JSON 转义、数组括号和分隔符。更新与发送+使用相同的计量方式,替换旧值释放预算;超限拒绝保留原值,不影响其他任务或账号。+Host 最多保留 256 份待发送上下文;达到条数上限或任务聚合字节将超限时,先回收卡片失效、任务归档、账号或配置+变化留下的旧值,再判断额度。关闭 View 不清除仍有效的上下文,并发更新不被旧清理覆盖。+回归见 `contextBudget.test.ts`。发送与插话在实际派发前重新核验快照对应的卡片、账号与+MCP 配置;普通发送在 metadata、附件及视觉准备后再次复核,插话也覆盖视觉准备后的+边界。复核不消费上下文,派发失败保留仍合法的更新,接受后只消费本次捕获值。+只复核 App 上下文时保留原有主人意图,不把外部 App 文本提升为授权;宿主明确返回的+空意图仍会清除旧授权。回归见 `makerSendTransaction.test.ts`、+`pluginTaskAuthorshipWiring.test.ts` 与 `packages/maker-core/src/session.origin.test.ts`。+Host 资源加载最多 90 秒,远程打开+请求等待 120 秒;文档到达后再给 App 45 秒初始化。控制端取消或丢失打开回执时,+使用可选 `openId` 和 `cancel-open` 回收该次加载或晚到 View,不影响其他查看端。+旧 v1 Host 不支持取消操作时仍由既有空闲租约回收,收到晚到回执时控制端主动销毁。+连接暂时中断只重试读取轮询,最多 30 秒;后续独立请求可重新建立 MCP 连接,+已发出的工具调用和消息不自动重放。+长轮询等待前后均复核当前卡片、账号与配置;撤权后不交付已排队或晚到的外链与通知。+本机 Desktop 在实际打开外链前再次复核 Host 的 View/card。远程 Desktop 由查看端 Main、+Mobile 由共享控制器,在调用当前查看设备的浏览器前通过 `authorize-link` 复核执行 Host 的+View/card 及仍在等待的 `linkId`。Host 一次性认领请求,将原 10 秒待授权计时替换为+30 秒结果等待;回执携带 `validForMs`,控制端用单调时钟计入整个往返时间,+打开前再检查有效期及查看端 View 未关闭。重复认领、过期回包、拒绝、超时、+未知操作或缺少有效期回执均不打开、不自动重试该动作,并向 Host 报告外链失败;+旧执行端需更新才能为新查看端完成复核,旧查看端需更新才会执行这一步。+回归见 `viewAuthorization.test.ts` 与 `mcpAppController.test.ts`。+App 消息排队期间只在 Main 保留当前卡片/View 的私有 guard;正常 drain 和排队插话+均在最终派发时重新核验,插话也在 Session 异步准备之后检查。guard 不进入公开队列+投影、历史或持久快照;恢复后的 App 队列行无法重建活授权,会明确失败,需要从当前+卡片重新触发。旧版 App 来源标记只用于拒绝无 guard 的旧行,不能授予发送权限。+模型工具发现完成后、返回工具清单或写入待执行卡片前复核账号与配置;配置在存卡期间失效时,+已写卡片收尾为标准错误,取消请求收尾为取消,不调用或重放工具。+回归见 `preCallValidation.test.ts`。+工具在页面加载期间完成或取消也会在初始化后正确交付;任务在加载期间被清空、+服务器被撤销时,Host 会拒绝展示并清理 View。+保存晚到结果失败时,Host 会释放该账号、任务和卡片的所有 View,并保留原错误;+初始化输入及结果/取消通知在发送前重新校验当前卡片。清空、回退或删除后的旧 View+不能收到晚到数据,其他卡片的 View 继续工作。++## 本地模拟申请表++```powershell+pnpm.cmd --filter desktop mcp-apps:mock+```++脚本输出随机 loopback 端口的 HTTP 与 SSE 地址。把其中一个地址手动添加为自定义 MCP,+让模型调用 `draft_form` 即可显示表单。模拟服务器使用官方 registerAppTool、registerAppResource+和独立 App SDK,页面无需联网下载代码。脚本不修改用户设置。++1. AI 给 title/body 初值。+2. 用户核对修改,`ui/update-model-context` 只更新下一次发送的上下文;发送或插话被接受后消费本次快照,失败时保留供重试。发送期间的新更新留给下一次发送,原生命令不消费上下文。+3. 点击创建后调用 App-only `create_application`,返回内存申请编号和 `sent:false`。+4. 点击“请 AI 继续修改”才发送消息并启动后续模型轮次。++这验证了于浩博讨论中的“AI 预填 → 用户核对 → 创建申请”流程。模拟创建不发送真实站内信,+不连接业务生产接口;真实 GM App 尚需业务服务器提供标准工具与资源。++## 独立实现的数据看板++```powershell+pnpm.cmd --filter desktop mcp-apps:mock --raw+```++同样输出随机 loopback HTTP/SSE 地址;添加为普通自定义 MCP 后调用 `open_metrics`。+看板的 View 只使用标准 JSON-RPC/postMessage,不依赖 Cindy API 或官方 View SDK;+服务器使用普通 MCP SDK 的低层 handler,不使用 MCP Apps 注册 helper。+它与申请表复用同一生产 Host,覆盖分页发现、blob HTML、resources/list metadata、+App-only 刷新、完整工具结果、模型上下文、消息、显示模式和尺寸通知。+测试还使用 text HTML、read-level metadata 和旧 `ui/resourceUri` 组合验证兼容读取。++## 一键协议验证++```powershell+pnpm.cmd --filter desktop test:mcp-apps:conformance+```++顺序运行协议、连接、授权与 IPC 回归,再分别启动真实 Electron 沙箱加载官方 SDK 申请表+和独立 JSON-RPC 看板。HTTP/SSE、text/blob、metadata 来源、分页与变更通知、取消、+销毁、显示、主题和 CSP 都纳入覆盖。前序两种 App 的沙箱检查通过,+逐项证据与边界见 [本地协议验证记录](./mcp-apps-validation.md)。++## 检查入口++```powershell+pnpm.cmd --filter desktop exec vitest run src/main/mcp-apps/__tests__ --maxWorkers=2+pnpm.cmd --filter @cindy/maker-shared exec vitest run+pnpm.cmd --filter desktop test:mcp-apps:sandbox+pnpm.cmd --filter desktop typecheck+pnpm.cmd --filter mobile typecheck+pnpm.cmd --filter @cindy/maker-shared build+pnpm.cmd --filter @cindy/device-link build+pnpm.cmd check:i18n+pnpm.cmd check:i18n-glossary+```++Electron 检查启动独立隐藏测试窗口与唯一临时 profile,加载生产 Host/proxy 和两个 App,+验证预填、修改、创建/刷新、Light/Dark、跨 origin、无 preload、声明的 connect/resource/frame/baseUri+域可用、未声明域无网络请求、导航阻断、销毁和 owner 切换。测试结束关闭自身进程并清理+唯一临时目录,不启动、重启或修改当前 Cindy。+这是独立页面沙箱集成证据,不等同于完整 Cindy 卡片的 Light/Dark 实机目检;Mobile 真机+与真实 SSH 主机仍需验收。diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.mdindex 5a45ff0680..793d491079 100644--- a/i18n/GLOSSARY.md+++ b/i18n/GLOSSARY.md@@ -383,6 +383,10 @@ Orca 协同角色名,与 Worker 成对。五语统一保留英文 Lead,不灵动岛角色皮肤名(设置页「图标皮肤」列表)。角色专名,四语统一保留拉丁原词,不做音译(避免「艾莉卡 / エリカ / 에리카」多套写法)。+### MCP App++标准 MCP Apps 协议提供的交互应用;卡片标题与消息来源沿用协议名称,各语言保留 MCP App,待术语评审后固化。+### Audio GenerationV4 模型类型 audio_generation,包含通用声音生成;与 audio_speech 语音合成分别展示。diff --git a/i18n/glossary.json b/i18n/glossary.jsonindex a0bc699a00..f1a88c600e 100644--- a/i18n/glossary.json+++ b/i18n/glossary.json@@ -5,6 +5,7 @@"sourceLocale": "en","punctuationExempt": ["desktop:settings.help.qnaFeedbackBodyTemplate"],"terms": [+ {"id": "mcp-app", "status": "proposed", "en": "MCP App", "translations": {"zh-CN": "MCP App", "zh-TW": "MCP App", "ja": "MCP App", "ko": "MCP App"}, "note": "标准 MCP Apps 协议提供的交互应用;卡片标题与消息来源沿用协议名称,各语言保留 MCP App,待术语评审后固化。"},{"id": "dissolve-group", "status": "proposed", "en": "Dissolve group", "translations": {"zh-CN": "解散群聊", "zh-TW": "解散群聊", "ja": "グループを解散", "ko": "그룹 해산"}, "checkCase": false, "note": "Irreversible group termination, distinct from archive, leave and personal list removal."},{"id": "input-handoff", "status": "proposed", "en": "Input Handoff", "translations": {"zh-CN": "代输入", "zh-TW": "代輸入", "ja": "代理入力", "ko": "대리 입력"}, "checkCase": false, "note": "Agent 遇到需要主人填写的界面(选择、文本、密码、验证码、授权)时,由宿主读出当前一步,主人在本机或远程设备上填写,值只交给宿主、不进模型与记录。不是远程控制。"},{"id": "wallpaper-blur", "status": "proposed", "en": "Wallpaper Blur", "translations": {"zh-CN": "壁纸模糊", "zh-TW": "桌布模糊", "ja": "壁紙のぼかし", "ko": "배경화면 흐림"}, "note": "仅使应用壁纸柔化,不模糊文字或控件;0 为关闭,按用户选择应用于静态图片和视频。"},diff --git a/packages/device-link/src/__tests__/invokePolicy.test.ts b/packages/device-link/src/__tests__/invokePolicy.test.tsindex b14795afd0..fba9e36389 100644--- a/packages/device-link/src/__tests__/invokePolicy.test.ts+++ b/packages/device-link/src/__tests__/invokePolicy.test.ts@@ -8,6 +8,15 @@ import {} from '../index.js';describe('remote invoke policy boundaries', () => {+ it.each(['desktop', 'mobile'] as const)('budgets MCP App loading on %s without replaying any operation', (platform) => {+ const channel = 'maker:mcp-apps:v1';+ expect(resolveRemoteInvokeTimeoutMs(channel, ['task', { op: 'open' }], platform)).toBe(120_000);+ for (const op of ['poll', 'message', 'cancel-open', 'teardown'])+ expect(resolveRemoteInvokeTimeoutMs(channel, ['task', { op }], platform)).toBeUndefined();+ expect(isPeerResetRetryableReadChannel(channel)).toBe(false);+ expect(isCompletedInvokeRetryableReadChannel(channel)).toBe(false);+ expect(canCoalesceRemoteListing({ channel, args: ['task', { op: 'open' }] })).toBe(false);+ });it('keeps mobile history recovery within the fork budget without retrying writes', () => {const channel = 'maker:fork-strip-encrypted';expect(resolveRemoteInvokeTimeoutMs(channel, ['source'], 'mobile')).toBe(30_000);diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.tsindex 0bae738545..af57c850df 100644--- a/packages/device-link/src/allowlist.ts+++ b/packages/device-link/src/allowlist.ts@@ -177,6 +177,8 @@ const CORE_INVOKE_CHANNELS: readonly string[] = ['maker:close-session','maker:abort-session','maker:send',+ // Task-bound official MCP App bridge. No credentials or arbitrary endpoint selection.+ 'maker:mcp-apps:v1',DL_SESSION_HANDOFF_CHANNEL,'maker:steer','maker:list-active',diff --git a/packages/device-link/src/invokePolicy.ts b/packages/device-link/src/invokePolicy.tsindex e044ea0a29..6e4eea8d6d 100644--- a/packages/device-link/src/invokePolicy.ts+++ b/packages/device-link/src/invokePolicy.ts@@ -115,6 +115,9 @@ export const MOBILE_INVOKE_TIMEOUT_OVERRIDES_MS: Record<string, number> = {export const MOBILE_SCHEDULE_CHANNEL_TIMEOUT_MS = 40_000;export const BOT_GROUP_SEND_TIMEOUT_MS = 180_000;+// MCP Apps Host bounds loading at 90s (connection + discovery + HTML). Leave+// room for response delivery without changing other MCP App operation budgets.+export const MCP_APP_OPEN_TIMEOUT_MS = 120_000;/*** Every action-specific desktop budget `resolveRemoteInvokeTimeoutMs` can return beyond@@ -123,6 +126,7 @@ export const BOT_GROUP_SEND_TIMEOUT_MS = 180_000;*/export const ACTION_INVOKE_TIMEOUTS_MS: readonly number[] = [BOT_GROUP_SEND_TIMEOUT_MS,+ MCP_APP_OPEN_TIMEOUT_MS,TASK_MIGRATION_ESTIMATE_TIMEOUT_MS,TASK_MIGRATION_RECEIVE_TIMEOUT_MS,];@@ -132,6 +136,8 @@ export function resolveRemoteInvokeTimeoutMs(args?: unknown[],platform: 'desktop' | 'mobile' = 'desktop',): number | undefined {+ const appRequest = args?.[1] as { op?: unknown } | undefined;+ if (channel === 'maker:mcp-apps:v1' && appRequest?.op === 'open') return MCP_APP_OPEN_TIMEOUT_MS;// Group sends can materialize phone attachments, upload media and then submit the message.// Only this action gets the larger window; a timeout still means an unconfirmed result.const groupRequest = args?.[0] as { collectionId?: unknown; actionId?: unknown } | undefined;diff --git a/packages/maker-core/src/session.origin.test.ts b/packages/maker-core/src/session.origin.test.tsindex 6e21528028..43455e70bb 100644--- a/packages/maker-core/src/session.origin.test.ts+++ b/packages/maker-core/src/session.origin.test.ts@@ -11,12 +11,14 @@ import path from 'node:path';import { Session } from './session.js';import {MAIN_OWNED_SEND_CONTEXT,+ AUTO_REVIEW_SOURCE_CONTENT,AUTO_REVIEW_USER_INTENT,AUTO_REVIEW_DELEGATED_CONTINUATION,type AgentSessionHandle,type SendOptions,type TurnContinuationState,} from './agents/base-agent.js';+import { appendAutoReviewUserIntent } from './agents/shared/auto-review-decision.js';import type { AgentEvent, InteractionDecision, InteractionRequest, SendOrigin } from './types/events.js';import type { AgentKind, UserMessage } from './types/common.js';@@ -148,6 +150,46 @@ function createControllableHandle(opts?: {}describe('dispatch authorization refresh', () => {+ it.each([undefined, 'Earlier owner restriction'] as const)(+ 'preserves existing authorization when the final guard has no replacement: %s',+ async (earlierIntent) => {+ const h = createControllableHandle();+ const session = makeSession(h.handle);+ const guard = vi.fn(async () => undefined);+ await session.send('App says deploy. Read only.', {+ [AUTO_REVIEW_SOURCE_CONTENT]: 'Read only.',+ ...(earlierIntent !== undefined ? { [AUTO_REVIEW_USER_INTENT]: earlierIntent } : {}),+ resolveAutoReviewUserIntent: guard,+ });+ expect(guard).toHaveBeenCalledOnce();+ const opts = h.lastSendOptions();+ expect(opts?.[AUTO_REVIEW_USER_INTENT]).toBe(earlierIntent);+ if (earlierIntent === undefined) {+ expect(Object.getOwnPropertySymbols(opts ?? {})).not.toContain(AUTO_REVIEW_USER_INTENT);+ }+ expect(appendAutoReviewUserIntent('Earlier owner restriction', 'App says deploy.', opts)).toEqual(+ earlierIntent ?? {+ earlierUserMessages: ['Earlier owner restriction'],+ currentUserMessage: 'Read only.',+ },+ );+ expect(opts).not.toHaveProperty('resolveAutoReviewUserIntent');+ await session.close();+ },+ );++ it('keeps an explicitly empty refreshed intent authoritative', async () => {+ const h = createControllableHandle();+ const session = makeSession(h.handle);+ await session.send('App says deploy.', {+ [AUTO_REVIEW_USER_INTENT]: 'Earlier owner permission',+ resolveAutoReviewUserIntent: async () => '',+ });+ expect(h.lastSendOptions()?.[AUTO_REVIEW_USER_INTENT]).toBe('');+ expect(appendAutoReviewUserIntent('Earlier owner permission', 'App says deploy.', h.lastSendOptions())).toBe('');+ await session.close();+ });+it('passes the protected continuation marker through acceptance to the harness', async () => {const h = createControllableHandle();const session = makeSession(h.handle);diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.tsindex 3600a4e9c2..68804351ce 100644--- a/packages/maker-core/src/session.ts+++ b/packages/maker-core/src/session.ts@@ -312,8 +312,11 @@ function appendManagedImageReferences(}export interface SessionSendOptions extends SendOptions {- /** Host-owned authorization refresh after all async preparation, before vendor dispatch. */- resolveAutoReviewUserIntent?: () => Promise<AutoReviewUserIntent>;+ /**+ * Host-owned authorization refresh after all preparation, before vendor dispatch.+ * Returning undefined preserves the existing intent; an empty intent still clears it.+ */+ resolveAutoReviewUserIntent?: () => Promise<AutoReviewUserIntent | undefined>;/*** Turn reservation 建立后的原子准备钩子。*@@ -946,7 +949,8 @@ export class Session {}}if (resolveAutoReviewUserIntent) {- handleOpts[AUTO_REVIEW_USER_INTENT] = await resolveAutoReviewUserIntent();+ const intent = await resolveAutoReviewUserIntent();+ if (intent !== undefined) handleOpts[AUTO_REVIEW_USER_INTENT] = intent;const cancelledAfterAuthorization = finishCancelledBeforeDispatch();if (cancelledAfterAuthorization !== null) return cancelledAfterAuthorization;}@@ -1156,7 +1160,10 @@ export class Session {return msg;}- async steer(message: UserMessage | string, opts?: SendOptions): Promise<void> {+ async steer(+ message: UserMessage | string,+ opts?: SendOptions & Pick<SessionSendOptions, 'beforeProviderStart'>,+ ): Promise<void> {let msg: UserMessage = typeof message === 'string'? { type: 'user', content: message }: message;@@ -1177,6 +1184,13 @@ export class Session {// 层 B:steer 追加图片同样走视觉桥(与 send 一致),否则纯文本模型收到的// 原始 image block 会被后端忽略或拒绝(Greptile P1)。msg = await this.bridgedVisionMessage(msg, opts?.signal);+ const { beforeProviderStart, ...handleOpts } = opts ?? {};+ // Host grants must survive all asynchronous preparation, including steer.+ // Keep the private authorization hook out of provider options.+ if (beforeProviderStart) {+ await beforeProviderStart();+ this.ensureActive();+ }// 异步视觉转换期间 turn 可能已完成/被中止(视觉后端慢、用户已切任务等):// 转换结果此时已无人接收,必须先复查原 turn 生命周期再调用 handle.steer,// 否则底层以「No active turn to steer」拒绝或 Pi 把迟到消息交给已结束的 turn。@@ -1188,7 +1202,7 @@ export class Session {const previousSteerGeneration = this.steerAcceptedGeneration;this.steerAcceptedGeneration = steerTurnGeneration;try {- await this.handle.steer(msg, { ...opts, [AUTO_REVIEW_SOURCE_CONTENT]: autoReviewSourceContent });+ await this.handle.steer(msg, { ...handleOpts, [AUTO_REVIEW_SOURCE_CONTENT]: autoReviewSourceContent });} catch (error) {if (this.steerAcceptedGeneration === steerTurnGeneration) {this.steerAcceptedGeneration = previousSteerGeneration;diff --git a/packages/maker-core/src/session.vision-bridge.test.ts b/packages/maker-core/src/session.vision-bridge.test.tsindex 6a9e8129df..610a9f26da 100644--- a/packages/maker-core/src/session.vision-bridge.test.ts+++ b/packages/maker-core/src/session.vision-bridge.test.ts@@ -305,6 +305,64 @@ describe('Session.send vision bridge hook', () => {});describe('Session.steer vision bridge hook', () => {+ function guardedSteerSession(visionBridge?: VisionBridgeHook) {+ const { handle } = makeRecordingHandle();+ handle.isTurnRunning = () => true;+ const steer = vi.fn(async (_message: UserMessage, _options?: SendOptions) => {});+ handle.steer = steer;+ const session = new Session({+ id: 'guarded-steer', agentKind: 'claude-code', workDir: path.join('workspace', 'repo'),+ handle, capabilities: { sameTurnSteer: { supported: true } } as never,+ logger: createLogger() as never, visionBridge,+ });+ return { session, handle, steer };+ }++ it('runs the Host grant at final steer dispatch without forwarding it to the provider', async () => {+ const { session, steer } = guardedSteerSession();+ const grant = vi.fn(async () => {});+ await session.steer('App-authored text', { beforeProviderStart: grant, messageUuid: 'app-input' });+ expect(grant).toHaveBeenCalledOnce();+ expect(steer).toHaveBeenCalledWith(+ { type: 'user', content: 'App-authored text' }, expect.objectContaining({ messageUuid: 'app-input' }),+ );+ expect(steer.mock.calls[0][1]).not.toHaveProperty('beforeProviderStart');+ await session.close();+ });++ it('rejects a Host grant revoked during asynchronous steer preparation', async () => {+ let visible = true;+ const bridge: VisionBridgeHook = async message => {+ await Promise.resolve();+ visible = false;+ return { applied: false, message };+ };+ const { session, steer } = guardedSteerSession(bridge);+ const grant = vi.fn(async () => { if (!visible) throw new Error('MCP_APP_CARD_UNAVAILABLE'); });+ await expect(session.steer({+ type: 'user', content: [{ type: 'image', path: path.join('fixture', 'app.png') }],+ }, { beforeProviderStart: grant })).rejects.toThrow('MCP_APP_CARD_UNAVAILABLE');+ expect(grant).toHaveBeenCalledOnce();+ expect(steer).not.toHaveBeenCalled();+ await session.close();+ });++ it.each(['ended', 'replaced', 'closed'] as const)('rechecks a turn %s while awaiting the Host steer grant', async (change) => {+ const { session, handle, steer } = guardedSteerSession();+ const generation = vi.spyOn(session, 'getTurnGeneration').mockReturnValue(1);+ await expect(session.steer('App-authored text', {+ beforeProviderStart: async () => {+ await Promise.resolve();+ if (change === 'ended') handle.isTurnRunning = () => false;+ else if (change === 'replaced') generation.mockReturnValue(2);+ else await session.close();+ },+ })).rejects.toThrow(change === 'closed' ? 'closed' : 'has no active turn to steer');+ expect(steer).not.toHaveBeenCalled();+ generation.mockRestore();+ await session.close();+ });+it('replaces the image message with the bridged text before steering', async () => {const steered: UserMessage[] = [];const handle = {diff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.jsonindex 00204857b2..6264836188 100644--- a/packages/maker-shared/package.json+++ b/packages/maker-shared/package.json@@ -43,6 +43,8 @@"./mermaid-autofix": "./src/mermaidAutofix.ts","./message-render": "./src/messageRender.ts","./message-normalize": "./src/messageNormalize.ts",+ "./mcp-apps": "./src/mcpApps.ts",+ "./mcp-app-controller": "./src/mcpAppController.ts","./message-presentation": "./src/messagePresentation.ts","./message-search": "./src/messageSearch.ts","./message-source": "./src/messageSource.ts",diff --git a/packages/maker-shared/src/__tests__/mcpAppController.test.ts b/packages/maker-shared/src/__tests__/mcpAppController.test.tsnew file mode 100644index 0000000000..a6ad239c52--- /dev/null+++ b/packages/maker-shared/src/__tests__/mcpAppController.test.ts@@ -0,0 +1,364 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { McpAppController, type AppRpc } from '../mcpAppController.js';+const document = {+ viewId: 'view',+ html: '<html></html>',+ csp: "default-src 'none'",+ prefersBorder: true,+};+const never = () => new Promise<unknown>(() => {});+const flush = async () => {+ for (let i = 0; i < 12; i++) await Promise.resolve();+};+afterEach(() => { vi.restoreAllMocks(); vi.useRealTimers(); });+function fixture(poll: () => Promise<unknown> = never) {+ const invoke = vi.fn(+ async (_session: string, input: Record<string, unknown>): Promise<unknown> =>+ input.op === 'open' ? document : input.op === 'poll' ? poll()+ : input.op === 'authorize-link' ? { authorized: true, validForMs: 30_000 } : {},+ );+ const post = vi.fn(),+ state = vi.fn(),+ error = vi.fn(),+ link = vi.fn(async () => {});+ const controller = new McpAppController(invoke, 'task', 'card', post, state, error, link);+ return { controller, invoke, post, state, error, link };+}+function linkFixture(authorize: () => Promise<unknown>) {+ const poll = vi.fn()+ .mockResolvedValueOnce([{ seq: 1, openLink: { id: 'link', url: 'https://example.org/' } }])+ .mockImplementation(never);+ const f = fixture(poll);+ const invoke = f.invoke.getMockImplementation()!;+ f.invoke.mockImplementation(async (session, input) =>+ input.op === 'authorize-link' ? authorize() : invoke(session, input));+ return f;+}+describe('MCP App transport lifecycle', () => {+ it('keeps local Desktop RPC out of the Renderer while retaining UI state and Host-owned teardown', async () => {+ const f = fixture();+ f.invoke.mockImplementation(async (_session, input) => input.op === 'open'+ ? { viewId: 'view', transport: 'sandbox', prefersBorder: true } : {});+ expect(await f.controller.open({})).toEqual({ viewId: 'view', transport: 'sandbox', prefersBorder: true });+ f.controller.sandboxReady('cindy-mcp-app://forged/resource');+ f.controller.receive({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: {} });+ f.controller.receive({ jsonrpc: '2.0', method: 'ui/notifications/initialized' });+ f.controller.receive({ jsonrpc: '2.0', method: 'ui/notifications/size-changed', params: { height: 420 } });+ expect(f.invoke.mock.calls.map(([, input]) => input.op)).toEqual(['open']);+ expect(f.post).not.toHaveBeenCalled();+ expect(f.state.mock.calls.map(([message]) => message.method)).toEqual([+ 'ui/notifications/initialized', 'ui/notifications/size-changed',+ ]);+ f.controller.prepareNativeClose();+ await f.controller.close();+ expect(f.invoke).toHaveBeenLastCalledWith('task', { op: 'teardown', viewId: 'view', alreadyNotified: false });+ });+ it('relays initialization and complete HTML only after sandbox ready', async () => {+ const f = fixture();+ await f.controller.open({});+ f.controller.sandboxReady('cindy-mcp-app://view-view/resource');+ expect(f.post).toHaveBeenCalledWith(+ expect.objectContaining({+ method: 'ui/notifications/sandbox-resource-ready',+ params: { html: document.html, resourceUrl: 'cindy-mcp-app://view-view/resource' },+ }),+ );+ f.controller.receive({ jsonrpc: '2.0', method: 'ui/notifications/initialized' });+ expect(f.invoke).toHaveBeenCalledWith(+ 'task',+ expect.objectContaining({+ op: 'message',+ message: expect.objectContaining({ method: 'ui/notifications/initialized' }),+ }),+ );+ await f.controller.close();+ });+ it.each([{ result: {} }, { error: { code: -32603, message: 'cleanup failed' } }])(+ 'waits for the locally requested teardown response before releasing the View: %j',+ async (response) => {+ vi.useFakeTimers();+ const f = fixture();+ await f.controller.open({});+ f.controller.sandboxReady();+ f.controller.prepareNativeClose();+ f.controller.prepareNativeClose();+ const requests = f.post.mock.calls+ .map(([message]) => message as AppRpc)+ .filter((message) => message.method === 'ui/resource-teardown');+ expect(requests).toHaveLength(1);+ const request = requests[0];+ const closed = vi.fn();+ const pending = f.controller.close().then(closed);+ const repeated = f.controller.close().then(closed);+ await flush();+ expect(closed).not.toHaveBeenCalled();+ expect(f.invoke.mock.calls.some(([, input]) => input.op === 'teardown')).toBe(false);++ f.controller.receive({ jsonrpc: '2.0', id: 'unrelated', result: {} });+ f.controller.receive(request);+ await vi.advanceTimersByTimeAsync(200);+ expect(closed).not.toHaveBeenCalled();+ expect(f.invoke.mock.calls.some(([, input]) => input.op === 'teardown')).toBe(false);++ f.controller.receive({ jsonrpc: '2.0', id: request.id, ...response });+ await Promise.all([pending, repeated]);+ expect(f.invoke).toHaveBeenLastCalledWith('task', {+ op: 'teardown', viewId: 'view', alreadyNotified: true,+ });+ expect(f.invoke.mock.calls.filter(([, input]) => input.op === 'teardown')).toHaveLength(1);+ expect(f.state).not.toHaveBeenCalledWith(expect.objectContaining({ id: request.id }));+ expect(f.invoke).not.toHaveBeenCalledWith('task', expect.objectContaining({+ op: 'message', message: expect.objectContaining({ id: request.id }),+ }));+ expect(vi.getTimerCount()).toBe(0);+ },+ );+ it('bounds an unresponsive local teardown from notification time and ignores late replies', async () => {+ vi.useFakeTimers();+ const f = fixture();+ await f.controller.open({});+ f.controller.sandboxReady();+ f.controller.prepareNativeClose();+ const request = f.post.mock.calls.at(-1)![0] as AppRpc;+ await vi.advanceTimersByTimeAsync(400);+ const pending = f.controller.close();+ await vi.advanceTimersByTimeAsync(599);+ expect(f.invoke.mock.calls.some(([, input]) => input.op === 'teardown')).toBe(false);+ await vi.advanceTimersByTimeAsync(1);+ await pending;+ expect(f.invoke).toHaveBeenLastCalledWith('task', {+ op: 'teardown', viewId: 'view', alreadyNotified: true,+ });+ const invocations = f.invoke.mock.calls.length;+ f.controller.receive({ jsonrpc: '2.0', id: request.id, result: {} });+ expect(f.invoke).toHaveBeenCalledTimes(invocations);+ expect(vi.getTimerCount()).toBe(0);+ });+ it('continues routing the Host teardown handshake while closing without a local notification', async () => {+ let deliver!: (events: unknown) => void;+ const f = fixture(() => new Promise((resolve) => { deliver = resolve; }));+ await f.controller.open({});+ f.controller.sandboxReady();+ let release!: () => void;+ f.invoke.mockImplementationOnce(() => new Promise<void>((resolve) => { release = resolve; }));+ const pending = f.controller.close();+ await flush();+ const request: AppRpc = { jsonrpc: '2.0', id: 'host-teardown', method: 'ui/resource-teardown' };+ deliver([{ seq: 1, message: request }]);+ await flush();+ expect(f.post).toHaveBeenCalledWith(request);+ const response: AppRpc = { jsonrpc: '2.0', id: request.id, result: {} };+ f.controller.receive(response);+ expect(f.invoke).toHaveBeenCalledWith('task', { op: 'message', viewId: 'view', message: response });+ expect(f.invoke).toHaveBeenCalledWith('task', {+ op: 'teardown', viewId: 'view', alreadyNotified: false,+ });+ release();+ await pending;+ });+ it('closes a View that finishes opening after its card unmounts', async () => {+ let resolve!: (value: unknown) => void;+ const invoke = vi.fn(+ async (_session: string, input: Record<string, unknown>) =>+ input.op === 'open' ? new Promise<unknown>((done) => {+ resolve = done;+ }) : {},+ );+ const controller = new McpAppController(invoke, 'task', 'card', vi.fn(), vi.fn(), vi.fn());+ const pending = controller.open({});+ await controller.close();+ invoke.mockResolvedValueOnce({});+ resolve(document);+ expect(await pending).toBeUndefined();+ expect(invoke).toHaveBeenLastCalledWith('task', { op: 'teardown', viewId: 'view' });+ });+ it('gives slow resource loading a separate initialization window', async () => {+ vi.useFakeTimers();+ const f = fixture();+ f.invoke.mockImplementationOnce(async () => {+ await new Promise((resolve) => setTimeout(resolve, 60_000));+ return document;+ });+ const pending = f.controller.open({});+ await vi.advanceTimersByTimeAsync(60_000);+ expect(await pending).toBe(document);+ expect(f.error).not.toHaveBeenCalled();+ f.controller.receive({ jsonrpc: '2.0', method: 'ui/notifications/initialized' });+ await vi.advanceTimersByTimeAsync(45_000);+ expect(f.error).not.toHaveBeenCalled();+ await f.controller.close();+ });+ it('cancels the correlated open after a lost response without replaying it', async () => {+ const f = fixture();+ f.invoke.mockRejectedValueOnce(new Error('INVOKE_TIMEOUT'));+ await expect(f.controller.open({})).rejects.toThrow('INVOKE_TIMEOUT');+ const open = f.invoke.mock.calls[0][1];+ await f.controller.close();+ expect(f.invoke).toHaveBeenLastCalledWith('task', { op: 'cancel-open', openId: open.openId });+ expect(f.invoke.mock.calls.filter(([, input]) => input.op === 'open')).toHaveLength(1);+ });+ it('handles trusted sandbox Escape through the display-mode operation', async () => {+ const f = fixture();+ await f.controller.open({});+ f.controller.receive({ jsonrpc: '2.0', method: 'ui/notifications/sandbox-escape' });+ expect(f.invoke).toHaveBeenLastCalledWith('task', { op: 'display-mode', viewId: 'view', mode: 'inline' });+ expect(f.state).not.toHaveBeenCalled();+ await f.controller.close();+ });+ it('times out initialization and releases the View without restarting a write', async () => {+ vi.useFakeTimers();+ const f = fixture();+ await f.controller.open({});+ await vi.advanceTimersByTimeAsync(45_000);+ expect(f.error).toHaveBeenCalledOnce();+ expect(String(f.error.mock.calls[0][0])).toContain('MCP_APP_INITIALIZATION_TIMEOUT');+ expect(f.invoke.mock.calls.filter(([, input]) => input.op === 'open')).toHaveLength(1);+ expect(f.invoke.mock.calls.filter(([, input]) => input.op === 'teardown')).toHaveLength(1);+ });+ it('retries only transient polling and never replays tools/call', async () => {+ vi.useFakeTimers();+ const poll = vi+ .fn()+ .mockRejectedValueOnce(new Error('connection lost'))+ .mockImplementation(never);+ const f = fixture(poll);+ await f.controller.open({});+ f.controller.sandboxReady();+ const request: AppRpc = {+ jsonrpc: '2.0',+ id: 1,+ method: 'tools/call',+ params: { name: 'submit' },+ };+ f.controller.receive(request);+ await flush();+ await vi.advanceTimersByTimeAsync(500);+ expect(poll).toHaveBeenCalledTimes(2);+ expect(f.invoke.mock.calls.filter(([, input]) => input.op === 'message')).toHaveLength(1);+ expect(f.error).not.toHaveBeenCalled();+ await f.controller.close();+ });+ it('fails closed immediately for a revoked Host and discards its polling loop', async () => {+ const f = fixture(async () => {+ throw new Error('MCP_APP_SERVER_CHANGED');+ });+ await f.controller.open({});+ await flush();+ expect(f.error).toHaveBeenCalledOnce();+ expect(f.invoke.mock.calls.filter(([, input]) => input.op === 'poll')).toHaveLength(1);+ expect(f.invoke.mock.calls.filter(([, input]) => input.op === 'teardown')).toHaveLength(1);+ });+ it('consumes controller links without exposing host actions to the App', async () => {+ const poll = vi+ .fn()+ .mockResolvedValueOnce([{ seq: 1, openLink: { id: 'link', url: 'https://example.org/' } }])+ .mockImplementation(never);+ const f = fixture(poll);+ await f.controller.open({});+ f.controller.sandboxReady();+ await flush();+ expect(f.link).toHaveBeenCalledWith('https://example.org/');+ expect(f.invoke).toHaveBeenCalledWith('task', {+ op: 'link-result',+ viewId: 'view',+ linkId: 'link',+ success: true,+ });+ expect(f.post.mock.calls.flat()).not.toContainEqual(+ expect.objectContaining({ openLink: expect.anything() }),+ );+ await f.controller.close();+ });+ it.each([+ 'MCP_APP_CARD_UNAVAILABLE',+ 'MCP_APP_VIEW_UNAVAILABLE',+ 'MCP_APP_SERVER_CHANGED',+ 'MCP_APP_INVALID_REQUEST',+ 'INVOKE_TIMEOUT',+ ])('does not open a returned link when final Host authorization fails: %s', async (reason) => {+ const f = linkFixture(async () => { throw new Error(reason); });+ await f.controller.open({});+ await flush();+ expect(f.link).not.toHaveBeenCalled();+ expect(f.invoke).toHaveBeenCalledWith('task', {+ op: 'authorize-link', viewId: 'view', linkId: 'link',+ });+ expect(f.invoke).toHaveBeenCalledWith('task', {+ op: 'link-result', viewId: 'view', linkId: 'link', success: false,+ });+ expect(f.invoke.mock.calls.filter(([, input]) => input.op === 'authorize-link')).toHaveLength(1);+ expect(f.error).not.toHaveBeenCalled();+ await f.controller.close();+ });+ it.each([{}, { authorized: false }, { authorized: true },+ { authorized: true, validForMs: 0 }, { authorized: true, validForMs: 30_001 }, null])(+ 'requires an explicit Host authorization receipt before opening a link: %j',+ async (authorization) => {+ const f = linkFixture(async () => authorization);+ await f.controller.open({});+ await flush();+ expect(f.link).not.toHaveBeenCalled();+ expect(f.invoke).toHaveBeenCalledWith('task', {+ op: 'link-result', viewId: 'view', linkId: 'link', success: false,+ });+ await f.controller.close();+ },+ );+ it('waits for final execution-Host authorization before opening the link once', async () => {+ let authorize!: (value: unknown) => void;+ const f = linkFixture(() => new Promise((resolve) => { authorize = resolve; }));+ await f.controller.open({});+ await flush();+ expect(f.invoke).toHaveBeenCalledWith('task', {+ op: 'authorize-link', viewId: 'view', linkId: 'link',+ });+ expect(f.link).not.toHaveBeenCalled();+ authorize({ authorized: true, validForMs: 30_000 });+ await flush();+ expect(f.link).toHaveBeenCalledExactlyOnceWith('https://example.org/');+ expect(f.invoke).toHaveBeenCalledWith('task', {+ op: 'link-result', viewId: 'view', linkId: 'link', success: true,+ });+ await f.controller.close();+ });+ it('discards a late link authorization when the controller has closed', async () => {+ let authorize!: (value: unknown) => void;+ const f = linkFixture(() => new Promise((resolve) => { authorize = resolve; }));+ await f.controller.open({});+ await flush();+ await f.controller.close();+ authorize({ authorized: true, validForMs: 30_000 });+ await flush();+ expect(f.link).not.toHaveBeenCalled();+ expect(f.invoke.mock.calls.some(([, input]) => input.op === 'link-result')).toBe(false);+ });+ it('rejects an authorization response whose lease elapsed in transit', async () => {+ let elapsed = 0;+ vi.spyOn(performance, 'now').mockImplementation(() => elapsed);+ let authorize!: (value: unknown) => void;+ const f = linkFixture(() => new Promise((resolve) => { authorize = resolve; }));+ await f.controller.open({});+ await flush();+ elapsed = 30_000;+ authorize({ authorized: true, validForMs: 30_000 });+ await flush();+ expect(f.link).not.toHaveBeenCalled();+ expect(f.invoke).toHaveBeenCalledWith('task', {+ op: 'link-result', viewId: 'view', linkId: 'link', success: false,+ });+ await f.controller.close();+ vi.restoreAllMocks();+ });+ it('host display changes never synthesize View request IDs', async () => {+ const f = fixture();+ await f.controller.open({});+ await f.controller.displayMode('inline');+ expect(f.invoke).toHaveBeenCalledWith('task', {+ op: 'display-mode',+ viewId: 'view',+ mode: 'inline',+ });+ expect(f.post).not.toHaveBeenCalled();+ await f.controller.close();+ });+});diff --git a/packages/maker-shared/src/__tests__/mcpApps.test.ts b/packages/maker-shared/src/__tests__/mcpApps.test.tsnew file mode 100644index 0000000000..99ee0bb8a7--- /dev/null+++ b/packages/maker-shared/src/__tests__/mcpApps.test.ts@@ -0,0 +1,188 @@+import { describe, expect, it, vi } from 'vitest';+import { Script } from 'node:vm';+import { mcpAppSandboxDocument, mcpAppFrameUrlAllowed, mcpAppHistoryText, parseMcpAppRecord, parseMcpAppHistory, projectMcpAppContent } from '../mcpApps.js';+describe('MCP Apps cross-platform document contract', () => {+ function proxy(resourceUrl?: string, requestedUrl = resourceUrl) {+ const attributes: Record<string, string> = {};+ const frame = {+ setAttribute: (name: string, value: string) => { attributes[name] = value; },+ style: {}, src: '', srcdoc: '', contentWindow: { postMessage: vi.fn() },+ };+ let receive!: (event: unknown) => void;+ let mounted = false;+ const window = {+ location: { href: 'http://127.0.0.1:5002/proxy.html' },+ parent: { postMessage: vi.fn() },+ addEventListener: (name: string, listener: (event: unknown) => void) => {+ if (name === 'message') receive = listener;+ },+ };+ const document = { createElement: () => frame, body: { appendChild: () => { mounted = true; } } };+ const html = mcpAppSandboxDocument('', resourceUrl);+ const script = html.slice(html.indexOf('<script>') + 8, html.indexOf('</script>'));+ new Script(script).runInNewContext({ window, document, URL });+ receive({ source: window.parent, data: { jsonrpc: '2.0',+ method: 'ui/notifications/sandbox-resource-ready',+ params: { resourceUrl: requestedUrl, html: '<script>untrusted</script>' } } });+ window.parent.postMessage.mockClear();+ return { frame, mounted, attributes, window, receive };+ }+ it('pins the proxy resource URL to its Host-generated cross-origin document', () => {+ const result = proxy('http://127.0.0.1:5001/resource.html', 'http://127.0.0.1:5002/attack.html');+ expect(result.mounted).toBe(true);+ expect(result.frame.src).toBe('http://127.0.0.1:5001/resource.html');+ expect(result.frame.srcdoc).toBe('');+ });+ it.each(['http://127.0.0.1:5002/app.html', 'javascript:alert(1)', 'file:///private'])(+ 'refuses a same-origin or privileged resource URL: %s', (url) => {+ expect(proxy(url).mounted).toBe(false);+ },+ );+ it('keeps an inline srcdoc App opaque rather than granting access to the proxy origin', () => {+ const result = proxy();+ expect(result.mounted).toBe(true);+ expect(result.frame.srcdoc).toBe('<script>untrusted</script>');+ expect(result.attributes.sandbox).toBe('allow-scripts');+ });+ it.each([+ ['http://127.0.0.1:5001/resource.html', 'http://127.0.0.1:5001'],+ ['cindy-mcp-app://example-view/resource', 'cindy-mcp-app://example-view'],+ ])('binds both RPC directions to the original resource origin: %s', (resourceUrl, origin) => {+ const result = proxy(resourceUrl);+ const message = { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'tool' } };+ result.receive({ source: result.frame.contentWindow, origin, data: message });+ expect(result.window.parent.postMessage).toHaveBeenCalledExactlyOnceWith(message, '*');+ result.receive({ source: result.window.parent, data: { jsonrpc: '2.0', id: 1, result: { private: 'result' } } });+ expect(result.frame.contentWindow.postMessage).toHaveBeenCalledExactlyOnceWith(+ { jsonrpc: '2.0', id: 1, result: { private: 'result' } }, origin,+ );+ });+ it.each(['https://frame.example.org', 'http://127.0.0.1:5002', 'null', undefined])(+ 'rejects the original WindowProxy after navigation to another origin: %s', (origin) => {+ const result = proxy('http://127.0.0.1:5001/resource.html');+ result.receive({ source: result.frame.contentWindow, origin,+ data: { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'tool' } } });+ expect(result.window.parent.postMessage).not.toHaveBeenCalled();+ },+ );+ it('does not mistake a descendant or sibling for the App even when its origin matches', () => {+ const result = proxy('http://127.0.0.1:5001/resource.html');+ result.receive({ source: {}, origin: 'http://127.0.0.1:5001',+ data: { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'tool' } } });+ expect(result.window.parent.postMessage).not.toHaveBeenCalled();+ expect(result.frame.contentWindow.postMessage).not.toHaveBeenCalled();+ });+ it('escapes native bridge keys without changing their JavaScript value', () => {+ const key = '</script><script>attack</script>';+ const html = mcpAppSandboxDocument(key);+ expect(html).not.toContain(key);+ expect(html.match(/<script>/gi)).toHaveLength(1);+ const encoded = html.match(/const bridgeKey=(.*?);/s)![1];+ expect(JSON.parse(encoded)).toBe(key);+ });+ it('denies undeclared native navigation and matches exact or wildcard domains', () => {+ expect(mcpAppFrameUrlAllowed('https://example.org')).toBe(false);+ expect(mcpAppFrameUrlAllowed('https://a.example.org', ['https://*.example.org'])).toBe(true);+ expect(mcpAppFrameUrlAllowed('https://example.org', ['https://*.example.org'])).toBe(false);+ expect(mcpAppFrameUrlAllowed('https://badexample.org', ['https://*.example.org'])).toBe(false);+ expect(mcpAppFrameUrlAllowed('https://a.example.org:9443', ['https://*.example.org:*'])).toBe(+ true,+ );+ expect(mcpAppFrameUrlAllowed('file:///private', ['https://example.org'])).toBe(false);+ });+ it('rejects malformed persisted cards while accepting additive fields', () => {+ const record = {+ version: 1,+ serverId: 'example',+ serverRevision: 'revision',+ resourceUri: 'ui://example/app',+ tool: { name: 'draft', inputSchema: { type: 'object' } },+ arguments: {},+ future: true,+ };+ expect(parseMcpAppRecord({ mcpApp: record })).toBe(record);+ expect(parseMcpAppRecord({ mcpApp: { ...record, arguments: [] } })).toBeUndefined();+ expect(+ parseMcpAppRecord({ mcpApp: { ...record, result: { content: 'invalid' } } }),+ ).toBeUndefined();+ });+ it('projects only saved public text blocks for read-only history', () => {+ const record = parseMcpAppRecord({ mcpApp: {+ version: 1, serverId: 'example', serverRevision: 'revision', resourceUri: 'ui://example/app',+ tool: { name: 'draft', inputSchema: { type: 'object' } }, arguments: { private: 'input' },+ } })!;+ expect(mcpAppHistoryText(record)).toBe('');+ record.result = {+ content: [+ { type: 'text', text: 'Saved result' },+ { type: 'image', data: 'private image' },+ { type: 'resource', resource: { text: 'embedded HTML' } },+ null, 'invalid', { type: 'text', text: 123 },+ { type: 'text', text: '<script>plain text</script>' },+ ],+ structuredContent: { private: 'structured' },+ _meta: { private: 'view-only' },+ };+ expect(mcpAppHistoryText(record)).toBe('Saved result\n\n<script>plain text</script>');+ });+ it('accepts public guest history for display without granting access to an App View', () => {+ const content = {+ mcpAppHistory: { version: 1, title: 'Draft form', text: 'Saved result' },+ };+ expect(parseMcpAppHistory(content)).toEqual({+ title: 'Draft form',+ text: 'Saved result',+ });+ expect(parseMcpAppRecord(content)).toBeUndefined();+ expect(+ parseMcpAppHistory({+ mcpAppHistory: { version: 1, title: 'Draft form', text: '' },+ }),+ ).toEqual({ title: 'Draft form', text: '' });+ });+ it.each([+ null,+ [],+ { version: 2, title: 'Draft', text: 'result' },+ { version: 1, title: {}, text: 'result' },+ { version: 1, title: 'Draft', text: {} },+ ])('rejects malformed public history %j', (mcpAppHistory) => {+ expect(parseMcpAppHistory({ mcpAppHistory })).toBeUndefined();+ });+ it('rebuilds public history without unknown private fields at any level', () => {+ const content = {+ mcpAppHistory: { version: 1, title: 'Draft', text: 'Saved', private: 'view-only' },+ private: { arguments: 'input' },+ };+ const expected = { mcpAppHistory: { version: 1, title: 'Draft', text: 'Saved' } };+ expect(projectMcpAppContent(content, true)).toEqual(expected);+ expect(projectMcpAppContent(JSON.stringify(content), true)).toEqual(expected);+ expect(content.mcpAppHistory.private).toBe('view-only');+ });+ it.each([+ { content: { mcpApp: { version: 2, private: 'view-only' } }, marked: true },+ { content: { mcpAppHistory: { version: 2, private: 'view-only' } }, marked: true },+ { content: { private: 'view-only' }, marked: true },+ { content: '{malformed private record', marked: true },+ ])('fails closed for malformed or unknown marked cards: %j', ({ content, marked }) => {+ expect(projectMcpAppContent(content, marked)).toEqual({ mcpAppHistory: { version: 1, title: '', text: '' } });+ });+ it('leaves ordinary message content untouched', () => {+ const content = { text: 'A user message', images: [{ url: 'example.png' }] };+ expect(projectMcpAppContent(content)).toBe(content);+ expect(projectMcpAppContent('ordinary text')).toBe('ordinary text');+ });+ it.each([+ { text: 'Ordinary structured result', mcpApp: null },+ { mcpApp: { version: 2, data: 'ordinary data' }, extra: 'preserve me' },+ { mcpAppHistory: { version: 1, title: 'User data', text: 'Saved', extra: 'preserve me' } },+ { mcpApp: {+ version: 1, serverId: 'example', serverRevision: 'revision', resourceUri: 'ui://example/app',+ tool: { name: 'draft', inputSchema: { type: 'object' } }, arguments: { ordinary: 'data' },+ } },+ ])('preserves App-shaped ordinary content without the Main-written marker: %j', (content) => {+ expect(projectMcpAppContent(content)).toBe(content);+ expect(projectMcpAppContent(content, false)).toBe(content);+ expect(projectMcpAppContent(JSON.stringify(content), false)).toBe(JSON.stringify(content));+ });+});diff --git a/packages/maker-shared/src/__tests__/messageSource.test.ts b/packages/maker-shared/src/__tests__/messageSource.test.tsindex 0c4f9408bf..eb0f8f67bc 100644--- a/packages/maker-shared/src/__tests__/messageSource.test.ts+++ b/packages/maker-shared/src/__tests__/messageSource.test.ts@@ -138,6 +138,14 @@ describe('messageSourceSenderFromMeta', () => {});describe('messageSourceIdEntries', () => {+ it('uses the same MCP server identity for UI hints and model source notes', () => {+ const meta = { sourcePlugin: { pluginId: 'mcp-app:reports', name: 'Reports' } };+ expect(messageSourceIdEntries(meta)).toEqual([{ kind: 'mcpApp', id: 'reports' }]);+ expect(describeMessageSourceSender(messageSourceSenderFromMeta(meta)!)).toBe(+ '由 MCP App「Reports」(mcp_server_id: reports) 发送',+ );+ });+it('lists the ids of the visible sender label, in the same priority as the label', () => {expect(messageSourceIdEntries({diff --git a/packages/maker-shared/src/mcpAppController.ts b/packages/maker-shared/src/mcpAppController.tsnew file mode 100644index 0000000000..d973cd03b4--- /dev/null+++ b/packages/maker-shared/src/mcpAppController.ts@@ -0,0 +1,259 @@+import { MCP_APPS_INVOKE, isMcpAppLinkAuthorizationCurrent, type McpAppOpenResult, type McpAppHostEvent } from './mcpApps.js';++export type AppRpc = {+ jsonrpc: '2.0';+ method?: string;+ id?: string | number;+ params?: Record<string, unknown>;+ [key: string]: unknown;+};+export type AppInvoker = (sessionId: string, input: Record<string, unknown>) => Promise<unknown>;+let nextOpenId = 0;++/** The UI is a transport only; official negotiation, schemas and permissions live on the Host. */+export class McpAppController {+ document?: McpAppOpenResult;+ private after = 0;+ private stopped = false;+ private closing = false;+ private teardownId?: string;+ private teardownDone?: Promise<void>;+ private finishTeardown?: () => void;+ private closePromise?: Promise<void>;+ private ready = false;+ private outbound: AppRpc[] = [];+ private initializeId?: string | number;+ private startupTimer?: ReturnType<typeof setTimeout>;+ private readonly openId = `${Date.now()}:${++nextOpenId}`;+ constructor(+ private readonly invoke: AppInvoker,+ readonly sessionId: string,+ readonly clientId: string,+ private readonly post: (message: AppRpc) => void,+ private readonly onState: (message: AppRpc) => void,+ private readonly onError: (error: unknown) => void,+ private readonly openLink?: (url: string) => Promise<void>,+ ) {}++ async open(context: Record<string, unknown>): Promise<McpAppOpenResult | undefined> {+ const document = (await this.invoke(this.sessionId, {+ op: 'open',+ openId: this.openId,+ clientId: this.clientId,+ context,+ })) as McpAppOpenResult;+ this.document = document;+ if (this.closing) {+ await this.invoke(this.sessionId, { op: 'teardown', viewId: document.viewId });+ return;+ }+ // Resource loading has its own Host/remote budget. Give the App a complete+ // initialization window after the document reaches this controller.+ this.startupTimer = setTimeout(+ () => this.fail(new Error('MCP_APP_INITIALIZATION_TIMEOUT')),+ 45_000,+ );+ if (document.transport !== 'sandbox') void this.poll();+ return document;+ }++ sandboxReady(resourceUrl?: string): void {+ if (!this.document || this.document.transport === 'sandbox' || this.ready || this.closing) return;+ this.ready = true;+ this.post({+ jsonrpc: '2.0',+ method: 'ui/notifications/sandbox-resource-ready',+ params: resourceUrl+ ? { html: this.document.html, resourceUrl }+ : { html: this.document.html },+ });+ this.outbound.splice(0).forEach((message) => this.post(message));+ }++ receive(message: AppRpc): void {+ if (this.stopped || !this.document || !message || message.jsonrpc !== '2.0') return;+ if (this.document.transport === 'sandbox') {+ if (message.method === 'ui/notifications/sandbox-failed')+ this.fail(new Error('MCP_APP_SANDBOX_FAILED'));+ if (this.closing) return;+ if (message.method === 'ui/notifications/sandbox-escape')+ void this.displayMode('inline').catch((error) => this.fail(error));+ if (message.method === 'ui/notifications/initialized') {+ clearTimeout(this.startupTimer);+ this.startupTimer = undefined;+ }+ if (['ui/notifications/initialized', 'ui/notifications/size-changed', 'ui/notifications/host-context-changed'].includes(message.method ?? ''))+ this.onState(message);+ return;+ }+ if (this.teardownId !== undefined && message.id === this.teardownId) {+ if (message.method === undefined && ('result' in message || 'error' in message))+ this.finishTeardown?.();+ return;+ }+ if (message.method === 'ui/notifications/sandbox-escape') {+ void this.displayMode('inline').catch((error) => this.fail(error));+ return;+ }+ if (message.method?.startsWith('ui/notifications/sandbox-')) return;+ if (this.closing && message.method) return;+ if (message.method === 'ui/initialize') this.initializeId = message.id;+ if (message.method === 'ui/notifications/initialized') {+ clearTimeout(this.startupTimer);+ this.startupTimer = undefined;+ }+ this.onState(message);+ void this.invoke(this.sessionId, {+ op: 'message',+ viewId: this.document.viewId,+ message,+ }).catch((error) => this.fail(error));+ }++ async context(context: Record<string, unknown>): Promise<void> {+ if (this.document && !this.closing)+ await this.invoke(this.sessionId, { op: 'context', viewId: this.document.viewId, context });+ }+ async displayMode(mode: 'inline' | 'fullscreen' | 'pip'): Promise<void> {+ if (this.document && !this.closing)+ await this.invoke(this.sessionId, { op: 'display-mode', viewId: this.document.viewId, mode });+ }+ private fail(error: unknown): void {+ if (this.closing) return;+ this.onError(error);+ this.prepareNativeClose();+ void this.close().catch(() => {});+ }++ private async poll(): Promise<void> {+ let failedAt = 0;+ let delay = 500;+ try {+ while (!this.stopped && this.document) {+ let events: Array<McpAppHostEvent<AppRpc>>;+ try {+ events = (await this.invoke(this.sessionId, {+ op: 'poll',+ viewId: this.document.viewId,+ after: this.after,+ })) as typeof events;+ if (!Array.isArray(events)) throw new Error('MCP_APP_INVALID_POLL');+ failedAt = 0;+ delay = 500;+ } catch (error) {+ if (this.closing) return;+ if (/MCP_APP_|CHANNEL_NOT_ALLOWED|NOT_FOUND/.test(String(error))) throw error;+ failedAt ||= Date.now();+ if (Date.now() - failedAt >= 30_000) throw error;+ await new Promise((resolve) => setTimeout(resolve, delay));+ delay = Math.min(5_000, delay * 2);+ continue;+ }+ if (this.stopped) return;+ for (const event of events) {+ if (!Number.isSafeInteger(event.seq) || event.seq <= this.after) continue;+ this.after = event.seq;+ if (event.openLink) {+ const viewId = this.document.viewId;+ void (async () => {+ let success = false;+ try {+ if (this.openLink && !this.closing) {+ const requestedAt = performance.now();+ const authorization = await this.invoke(this.sessionId, {+ op: 'authorize-link',+ viewId,+ linkId: event.openLink.id,+ });+ if (+ !isMcpAppLinkAuthorizationCurrent(authorization, performance.now() - requestedAt)+ )+ throw new Error('MCP_APP_LINK_NOT_AUTHORIZED');+ // Closing can win while the execution Host checks the current card.+ if (!this.closing && !this.stopped && this.document?.viewId === viewId) {+ await this.openLink(event.openLink.url);+ success = true;+ }+ }+ } catch {+ /* Report the failed link action to the Host so its RPC can finish. */+ }+ if (!this.stopped && this.document?.viewId === viewId)+ await this.invoke(this.sessionId, {+ op: 'link-result',+ viewId,+ linkId: event.openLink.id,+ success,+ });+ })().catch((error) => this.fail(error));+ continue;+ }+ if (+ this.initializeId !== undefined &&+ event.message.id === this.initializeId &&+ event.message.error+ )+ throw new Error('MCP_APP_INITIALIZATION_FAILED');+ this.onState(event.message);+ if (this.ready) this.post(event.message);+ else this.outbound.push(event.message);+ }+ // Broken/legacy hosts must not cause a hot empty-poll loop.+ if (!events.length && !this.stopped)+ await new Promise((resolve) => setTimeout(resolve, 250));+ }+ } catch (error) {+ this.fail(error);+ }+ }++ /** Notify before native disposal; close() waits at most one second for the response. */+ prepareNativeClose(): void {+ if (!this.ready || this.document?.transport === 'sandbox' || this.closing || this.teardownId) return;+ this.teardownId = `cindy-teardown:${Date.now()}:${this.clientId}`;+ this.teardownDone = new Promise<void>((resolve) => {+ const timer = setTimeout(() => this.finishTeardown?.(), 1_000);+ this.finishTeardown = () => {+ clearTimeout(timer);+ this.finishTeardown = undefined;+ resolve();+ };+ });+ this.post({ jsonrpc: '2.0', id: this.teardownId, method: 'ui/resource-teardown', params: {} });+ }++ close(): Promise<void> {+ this.closePromise ??= this.closeView();+ return this.closePromise;+ }++ private async closeView(): Promise<void> {+ this.closing = true;+ clearTimeout(this.startupTimer);+ this.startupTimer = undefined;+ if (!this.document) {+ // Correlate cancellation even if transport timeout lost the View response.+ // Older v1 hosts may reject this additive operation; their idle lease still+ // reclaims the orphan, and a late successful response is closed by open().+ await this.invoke(this.sessionId, { op: 'cancel-open', openId: this.openId }).catch(() => {});+ return;+ }+ try {+ if (this.teardownDone) await this.teardownDone;+ await this.invoke(this.sessionId, {+ op: 'teardown',+ viewId: this.document.viewId,+ alreadyNotified: !!this.teardownId,+ });+ } finally {+ this.stopped = true;+ this.outbound = [];+ }+ }+}+export function mcpAppFailureKey(error: unknown): 'mcpApps.updateRequired' | 'mcpApps.loadFailed' {+ return /CHANNEL_NOT_ALLOWED|UNKNOWN_CHANNEL|CHANNEL_NOT_FOUND/.test(String(error))+ ? 'mcpApps.updateRequired'+ : 'mcpApps.loadFailed';+}+export { MCP_APPS_INVOKE };diff --git a/packages/maker-shared/src/mcpApps.ts b/packages/maker-shared/src/mcpApps.tsnew file mode 100644index 0000000000..668f061698--- /dev/null+++ b/packages/maker-shared/src/mcpApps.ts@@ -0,0 +1,200 @@+/** Data-only, additive MCP Apps contract shared by Desktop and Mobile. */+export const MCP_APPS_INVOKE = 'maker:mcp-apps:v1';+export const MCP_APP_CARD = 'mcp-app';+export const MCP_APP_LINK_GRANT_MS = 30_000;+export interface McpAppLinkAuthorization {+ authorized: true;+ validForMs: number;+}+/** Count the whole round trip against the Host's reservation; no clock sync is required. */+export function isMcpAppLinkAuthorizationCurrent(value: unknown, elapsedMs: number): boolean {+ if (!value || typeof value !== 'object') return false;+ const grant = value as Partial<McpAppLinkAuthorization>;+ return grant.authorized === true && typeof grant.validForMs === 'number' &&+ Number.isFinite(grant.validForMs) && grant.validForMs > 0 &&+ grant.validForMs <= MCP_APP_LINK_GRANT_MS && elapsedMs >= 0 && elapsedMs < grant.validForMs;+}+/** Host-to-controller actions never enter the App's standard JSON-RPC transport. */+export type McpAppHostEvent<T> =+ | { seq: number; message: T; openLink?: never }+ | { seq: number; openLink: { id: string; url: string }; message?: never };+export interface McpAppRecord {+ version: 1;+ serverId: string;+ serverRevision: string;+ resourceUri: string;+ connectionId?: string;+ tool: {+ name: string;+ title?: string;+ inputSchema: { type: 'object'; [key: string]: unknown };+ [key: string]: unknown;+ };+ arguments: Record<string, unknown>;+ result?: {+ content: unknown[];+ structuredContent?: Record<string, unknown>;+ _meta?: Record<string, unknown>;+ isError?: boolean;+ [key: string]: unknown;+ };+ cancelled?: string;+}+export interface McpAppDocument {+ viewId: string;+ transport?: undefined;+ html: string;+ csp: string;+ prefersBorder: boolean;+ policy?: {+ connectDomains?: string[];+ resourceDomains?: string[];+ frameDomains?: string[];+ baseUriDomains?: string[];+ };+}+/** Desktop UI metadata only; credential-backed App content stays in Main. */+export interface McpAppSandboxView {+ viewId: string;+ transport: 'sandbox';+ prefersBorder: boolean;+}+export type McpAppOpenResult = McpAppDocument | McpAppSandboxView;+export function parseMcpAppRecord(content: unknown): McpAppRecord | undefined {+ if (!content || typeof content !== 'object') return;+ const value = (content as { mcpApp?: unknown }).mcpApp;+ if (!value || typeof value !== 'object') return;+ const record = value as McpAppRecord;+ return record.version === 1 &&+ typeof record.serverId === 'string' &&+ typeof record.serverRevision === 'string' &&+ typeof record.resourceUri === 'string' &&+ record.resourceUri.startsWith('ui://') &&+ typeof record.tool?.name === 'string' &&+ record.tool.inputSchema?.type === 'object' &&+ record.arguments &&+ typeof record.arguments === 'object' &&+ !Array.isArray(record.arguments) &&+ (!record.result || Array.isArray(record.result.content))+ ? record+ : undefined;+}++/** Read-only history uses public text blocks, never View-only metadata or embedded resources. */+export function mcpAppHistoryText(record: McpAppRecord): string {+ return (record.result?.content ?? [])+ .flatMap((block) => {+ if (!block || typeof block !== 'object') return [];+ const value = block as { type?: unknown; text?: unknown };+ return value.type === 'text' && typeof value.text === 'string' ? [value.text] : [];+ })+ .join('\n\n');+}++/** Public history has no server identity, tool inputs, schema or View-only result. */+export interface McpAppHistory {+ title: string;+ text: string;+}++/** Display persisted records and public summaries without minting a View grant. */+export function parseMcpAppHistory(content: unknown): McpAppHistory | undefined {+ const record = parseMcpAppRecord(content);+ if (record) return {+ title: typeof record.tool.title === 'string' ? record.tool.title : record.tool.name,+ text: mcpAppHistoryText(record),+ };+ if (!content || typeof content !== 'object' || Array.isArray(content)) return;+ const value = (content as { mcpAppHistory?: unknown }).mcpAppHistory;+ if (!value || typeof value !== 'object' || Array.isArray(value)) return;+ const summary = value as Record<string, unknown>;+ if (summary.version === 1 && typeof summary.title === 'string' && typeof summary.text === 'string')+ return { title: summary.title, text: summary.text };+}++/** Only public history may leave Main outside an authorized sandboxed View. */+export function projectMcpAppContent(content: unknown, marked = false): unknown {+ // Only Main's marker identifies App rows; ordinary structured data may use+ // these property names too and must retain its original content.+ if (!marked) return content;+ let value = content;+ if (typeof value === 'string') {+ try { value = JSON.parse(value); } catch { value = undefined; }+ }+ // Unknown/malformed cards must not fall back to sending the private original.+ const history = parseMcpAppHistory(value);+ return { mcpAppHistory: { version: 1, title: history?.title ?? '', text: history?.text ?? '' } };+}++/** Trusted proxy. No privileged host API; relay only the actual inner window. */+export const MCP_APP_SANDBOX_SCRIPT = `+const frame=document.createElement('iframe');+frame.setAttribute('sandbox','allow-scripts');+frame.setAttribute('allow',"camera 'none'; microphone 'none'; geolocation 'none'; clipboard-write 'none'");+frame.style.cssText='border:0;width:100%;height:100%;display:block';+let loaded=false;+let resourceOrigin='null';+const post=message=>window.ReactNativeWebView?window.ReactNativeWebView.postMessage(JSON.stringify({key:bridgeKey,message})):window.parent.postMessage(message,'*');+window.addEventListener('keydown',event=>{+ if(event.key==='Escape'&&!event.isComposing&&!event.repeat&&!event.ctrlKey&&!event.altKey&&!event.metaKey&&!event.shiftKey)+ post({jsonrpc:'2.0',method:'ui/notifications/sandbox-escape',params:{}});+});+window.addEventListener('message',event=>{+ const message=event.data;+ if(!message||message.jsonrpc!=='2.0')return;+ if(event.source===frame.contentWindow){+ // WindowProxy identity survives navigation; a replacement document gets no bridge.+ if(!loaded||event.origin!==resourceOrigin)return;+ if(typeof message.method==='string'&&message.method.startsWith('ui/notifications/sandbox-'))return;+ post(message);return;+ }+ if(event.source!==window.parent&&event.source!==window)return;+ if(message.method==='ui/notifications/sandbox-resource-ready'){+ if(loaded)return;+ const resourceUrl=typeof expectedResourceUrl==='string'?expectedResourceUrl:message.params.resourceUrl;+ if(resourceUrl){+ const resource=new URL(resourceUrl),proxy=new URL(window.location.href);+ if(!['http:','https:','cindy-mcp-app:'].includes(resource.protocol)||resource.username||resource.password||+ resource.protocol===proxy.protocol&&resource.host===proxy.host)return;+ // URL.origin can be null for Electron's registered custom scheme.+ resourceOrigin=resource.protocol+'//'+resource.host;+ frame.setAttribute('sandbox','allow-scripts allow-same-origin');frame.src=resource.href;+ }+ else{frame.srcdoc=message.params.html;}+ loaded=true;+ document.body.appendChild(frame);return;+ }+ if(loaded)frame.contentWindow?.postMessage(message,resourceOrigin==='null'?'*':resourceOrigin);+});+post({jsonrpc:'2.0',method:'ui/notifications/sandbox-proxy-ready',params:{}});+`;+export function mcpAppSandboxDocument(nativeBridgeKey = '', resourceUrl?: string): string {+ const key = JSON.stringify(nativeBridgeKey).replace(/</g, '\\u003c');+ const resource = JSON.stringify(resourceUrl ?? null).replace(/</g, '\\u003c');+ return `<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;width:100%;height:100%;overflow:hidden}</style></head><body><script>const bridgeKey=${key};const expectedResourceUrl=${resource};${MCP_APP_SANDBOX_SCRIPT}</script></body></html>`;+}+/** Legacy inline wrapper; served native Views receive CSP headers from their resource server. */+export function mcpAppNativeResource(html: string, csp: string): string {+ const escaped = csp.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<');+ return `<!doctype html><meta http-equiv="Content-Security-Policy" content="${escaped}">${html}`;+}+/** Native frame navigation needs its own gate; document CSP does not cover location. */+export function mcpAppFrameUrlAllowed(value: string, domains: readonly string[] = []): boolean {+ if (value === 'about:blank' || value === 'about:srcdoc') return true;+ try {+ const url = new URL(value);+ if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password) return false;+ return domains.some((domain) => {+ const wildcard = domain.includes('://*.');+ const anyPort = /:\*\/?$/.test(domain);+ const source = new URL(domain.replace('://*.', '://').replace(/:\*(\/?$)/, '$1'));+ return (+ source.protocol === url.protocol &&+ (anyPort || source.port === url.port) &&+ (wildcard ? url.hostname.endsWith('.' + source.hostname) : url.hostname === source.hostname)+ );+ });+ } catch {+ return false;+ }+}diff --git a/packages/maker-shared/src/messageSource.ts b/packages/maker-shared/src/messageSource.tsindex 70ce7ab3b6..fb78a7ab46 100644--- a/packages/maker-shared/src/messageSource.ts+++ b/packages/maker-shared/src/messageSource.ts@@ -217,7 +217,7 @@ export function isCrossDeviceSourceSessionId(sessionId: string | undefined): booreturn split > 0 && split < sessionId.length - 2;}-export type MessageSourceIdKind = 'plugin' | 'teammate' | 'session' | 'automation' | 'member';+export type MessageSourceIdKind = 'plugin' | 'mcpApp' | 'teammate' | 'session' | 'automation' | 'member';export interface MessageSourceIdEntry {kind: MessageSourceIdKind;@@ -231,7 +231,11 @@ export interface MessageSourceIdEntry {*/export function messageSourceIdEntries(meta: unknown): MessageSourceIdEntry[] {const sender = messageSourceSenderFromMeta(meta);- if (sender?.kind === 'plugin') return [{ kind: 'plugin', id: sender.pluginId }];+ if (sender?.kind === 'plugin') {+ return sender.pluginId.startsWith('mcp-app:')+ ? [{ kind: 'mcpApp', id: sender.pluginId.slice(8) }]+ : [{ kind: 'plugin', id: sender.pluginId }];+ }if (sender?.kind === 'shared-member') return [{ kind: 'member', id: sender.memberId }];if (sender?.kind === 'session') {return [@@ -269,6 +273,7 @@ export function describeMessageSourceSender(sender: MessageSourceSender): stringreturn ref ? `由任务${ref} 发送` : '由其他任务发送';}case 'plugin':+ if (sender.pluginId.startsWith('mcp-app:')) return `由 MCP App${formatSourceRef(sender.name, 'mcp_server_id', sender.pluginId.slice(8))} 发送`;return `由插件${formatSourceRef(sender.name, 'plugin_id', sender.pluginId)} 发送`;case 'shared-member':return `由共享任务成员${formatSourceRef(sender.name, 'member_id', sender.memberId)} 发送`;diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex bf9cc89566..b0810cf61b 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -260,6 +260,9 @@ importers:'@lezer/highlight':specifier: ^1.2.3version: 1.2.3+ '@modelcontextprotocol/ext-apps':+ specifier: 1.7.5+ version: 1.7.5(@modelcontextprotocol/[email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])'@modelcontextprotocol/sdk':specifier: ^1.29.0version: 1.29.0([email protected])@@ -3499,6 +3502,20 @@ packages:'@mermaid-js/[email protected]':resolution: {integrity: sha512-oYPyv8A4As1yH5Bx+04iQEQxXuIQDe0GKCNSRgao6z8AM9jixXIfP0vsppRLvGf+nKIOb9/LdpWA4YuJiVvESA==}+ '@modelcontextprotocol/[email protected]':+ resolution: {integrity: sha512-TjPH2S2y5UEGKhmI6+XGFuqfqOV4ppe1x6DA3txnUaEWkgtA4G5vo14jGKFZmegdkZ1H4QMLyujLvoU1BEdnAg==}+ engines: {node: '>=20'}+ peerDependencies:+ '@modelcontextprotocol/sdk': ^1.29.0+ react: ^17.0.0 || ^18.0.0 || ^19.0.0+ react-dom: ^17.0.0 || ^18.0.0 || ^19.0.0+ zod: 4.3.6+ peerDependenciesMeta:+ react:+ optional: true+ react-dom:+ optional: true+'@modelcontextprotocol/[email protected]':resolution: {integrity: sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==}engines: {node: '>=18'}@@ -4677,6 +4694,9 @@ packages:resolution: {integrity: sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==}engines: {node: '>=14.0.0'}+ '@standard-schema/[email protected]':+ resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}+'@szmarczak/[email protected]':resolution: {integrity: sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w==}engines: {node: '>=10'}@@ -13979,6 +13999,15 @@ snapshots:dependencies:'@chevrotain/types': 11.1.2+ '@modelcontextprotocol/[email protected](@modelcontextprotocol/[email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])':+ dependencies:+ '@modelcontextprotocol/sdk': 1.29.0([email protected])+ '@standard-schema/spec': 1.1.0+ zod: 4.3.6+ optionalDependencies:+ react: 19.2.3+ react-dom: 19.2.3([email protected])+'@modelcontextprotocol/[email protected]([email protected])':dependencies:'@hono/node-server': 1.19.14([email protected])@@ -15106,6 +15135,8 @@ snapshots:'@smithy/util-buffer-from': 2.2.0tslib: 2.8.1+ '@standard-schema/[email protected]': {}+'@szmarczak/[email protected]':dependencies:defer-to-connect: 2.0.1