Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(mobile): 接入插件页面与原生交互 (#5359)
Chris Zhang1bde0037e451
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cardRemoteResource.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cardRemoteResource.test.tsindex a907efab0b..bcbe6f5538 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/cardRemoteResource.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/cardRemoteResource.test.ts@@ -1,7 +1,7 @@import { describe, it, expect, vi } from 'vitest';vi.mock('../cardStoreDb.js', () => ({ getGhostCard: vi.fn(), upsertGhostCard: vi.fn() }));vi.mock('../../device-link/broadcast-tap.js', () => ({ captureDataOwnerBroadcastScope: vi.fn(), isDataOwnerBroadcastScopeCurrent: vi.fn(), tapWindowBroadcast: vi.fn(), getSafeDataOwnerPushStamp: vi.fn() }));-import { createPluginIdentityRemoteProvider, createGhostCardRemoteProvider, projectGhostCardBlocks, persistGhostCardWithRemoteChange } from '../cardRemoteResource.js';+import { createPluginIdentityRemoteProvider, createGhostCardRemoteProvider, projectGhostCardBlocks, projectGhostCardActions, persistGhostCardWithRemoteChange } from '../cardRemoteResource.js';import { upsertGhostCard } from '../cardStoreDb.js';import { isDataOwnerBroadcastScopeCurrent, tapWindowBroadcast } from '../../device-link/broadcast-tap.js';const image = `cindy-media://blobs/${'b'.repeat(64)}.png`;@@ -9,6 +9,37 @@ const audio = `cindy-media://blobs/${'c'.repeat(64)}.mp3`;const request = { ref: { collectionId: 'plugin-results', kind: 'card', id: JSON.stringify(['s', 'c']) }, client: { protocolVersion: 1, primitives: [] } };const context = { controllerDeviceId: 'phone' };+describe('native mobile card actions', () => {+ it('projects declared buttons and approved links, preserving required text input and disabled state', () => {+ const html = '<button data-ghost-action="edit" data-ghost-prompt="Describe & edit">Edit <b>image</b></button><button data-ghost-action="delete" disabled>Delete</button><a data-ghost-link="https://example.com/?a=1&b=2">Visit</a>';+ expect(projectGhostCardActions(html, false)).toEqual([+ { id: 'edit', label: 'Edit image', prompt: 'Describe & edit', disabled: false },+ { id: 'delete', label: 'Delete', disabled: true },+ ]);+ expect(projectGhostCardActions(html, true)[2]).toEqual({ id: 'link:2', label: 'Visit', url: 'https://example.com/?a=1&b=2', disabled: false });+ });+ it('checks the actual persisted card revision and declaration before dispatch, and keeps legacy clients inert', async () => {+ let html = '<button data-ghost-action="edit" data-ghost-prompt="Describe">Edit</button>';+ const dispatch = vi.fn(async () => true);+ const provider = createGhostCardRemoteProvider({+ readCard: async () => ({ sessionId: 's', callId: 'c', ghostId: 'art', html, v: 1, height: 100 }),+ authorize: async () => {}, captureScope: () => () => true,+ interactions: { externalLinks: () => true, dispatch },+ });+ const old = await provider.get!(context, request);+ expect(old.blocks?.some(b => b.primitive === 'plugin-card-actions')).toBe(false);+ const resource = await provider.get!(context, { ...request, client: { protocolVersion: 1, primitives: ['plugin-card-actions'] } });+ const base = { client: request.client, collectionId: 'plugin-results', resourceRef: request.ref, actionId: 'edit', input: { revision: resource.revision, pageId: 'page', prompt: 'Change it' } };+ await expect(provider.invoke!(context, { ...base, actionId: 'forged' })).rejects.toThrow();+ await expect(provider.invoke!(context, { ...base, input: { ...base.input, prompt: '' } })).rejects.toThrow();+ await provider.invoke!(context, base);+ expect(dispatch).toHaveBeenCalledWith('c', 'edit', 'Change it', 'page', 'art', 'phone');+ html = '<p>Changed</p>';+ await expect(provider.invoke!(context, base)).rejects.toThrow();+ expect(dispatch).toHaveBeenCalledTimes(1);+ });+});+describe('read-only plugin card projection', () => {it('preserves readable text and managed assets, never HTML, styles or executable actions', () => {const blocks = projectGhostCardBlocks(`<style>p{color:red}</style><h2>Result & title</h2><p>Done</p><img src="${image}"/><div data-ghost-audio="${audio}"></div><button data-ghost-action="delete">Delete</button><script>secret()</script><img src="file:///secret"/>`);diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.tsindex f206877f0c..faa4811960 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts@@ -24,7 +24,6 @@ import { describe, expect, it } from 'vitest';const MUTATING_GHOST_CHANNELS = ['ghosts:install','ghosts:update',- 'ghosts:set-enabled','ghosts:restore-builtin',] as const;@@ -53,6 +52,22 @@ describe('ghost 写路径 IPC 的 owner 租约(源码契约)', () => {});}+ it('ghosts:set-enabled 同步委托共用入口,入口先持 owner 租约再异步修改', () => {+ const block = handlerBlock(source, 'ghosts:set-enabled');+ expect(block).toContain('assertTrustedAppRendererEvent(event)');+ expect(block).toContain('return setGhostEnabledForUser(id, enabled)');+ expect(block).not.toMatch(/\bawait\b/);+ const start = source.indexOf('async function setGhostEnabledForUser(');+ expect(start).toBeGreaterThan(-1);+ // 注释会描述 await 窗口,只比较真正语句中的租约和异步边界。+ const fn = source.slice(start, source.indexOf('\n}', start)).replace(/\/\/[^\n]*/g, '');+ const lease = fn.indexOf('beginGhostMutation(captureGhostMutationOwner())');+ expect(lease).toBeGreaterThan(-1);+ expect(lease).toBeLessThan(fn.indexOf('await '));+ expect(fn).toContain('await manager.setEnabled(id, enabled)');+ expect(fn).toMatch(/finally\s*\{\s*releaseMutation\(\)/);+ });+it('ghosts:uninstall 经 uninstallGhostAndCleanup 持租约(入口同步取,无异步窗口故无需 capture)', () => {const block = handlerBlock(source, 'ghosts:uninstall');expect(block).toContain('uninstallGhostAndCleanup(');diff --git a/apps/desktop/src/main/cindy-brain/__tests__/mobilePageAssets.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/mobilePageAssets.test.tsnew file mode 100644index 0000000000..404d91feaf--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/mobilePageAssets.test.ts@@ -0,0 +1,36 @@+import { afterEach, describe, expect, it } from 'vitest';+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import type { InstalledGhost } from '../../../shared/ghost.js';+import { listMobilePageFiles, readMobilePageChunk } from '../mobilePageAssets.js';++const roots: string[] = [];+afterEach(async () => {+ await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true })));+});+async function fixture() {+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-mobile-plugin-assets-'));+ roots.push(dir);+ await fs.writeFile(path.join(dir, 'panel.html'), '<html>first</html>');+ return { dir } as InstalledGhost;+}+describe('mobile page package snapshot', () => {+ it('reads its original page and rejects a same-length edit between chunks', async () => {+ const ghost = await fixture();+ const [file] = await listMobilePageFiles(ghost, 'panel.html');+ const value = await readMobilePageChunk(ghost, file, 0);+ expect(Buffer.from(value.base64, 'base64').toString()).toBe('<html>first</html>');+ await fs.writeFile(path.join(ghost.dir, 'panel.html'), '<html>other</html>');+ await expect(readMobilePageChunk(ghost, file, 0)).rejects.toThrow('PLUGIN_ASSET_CHANGED');+ });+ it('does not follow a file replaced by an external link', async () => {+ const ghost = await fixture();+ const [file] = await listMobilePageFiles(ghost, 'panel.html');+ const outside = path.join(ghost.dir, 'outside.html');+ await fs.writeFile(outside, '<html>other</html>');+ await fs.unlink(path.join(ghost.dir, 'panel.html'));+ await fs.symlink(outside, path.join(ghost.dir, 'panel.html'));+ await expect(readMobilePageChunk(ghost, file, 0)).rejects.toThrow();+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/mobilePageRelay.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/mobilePageRelay.test.tsnew file mode 100644index 0000000000..ccfcb5f7c9--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/mobilePageRelay.test.ts@@ -0,0 +1,46 @@+import { runInNewContext } from 'node:vm';+import { describe, expect, it } from 'vitest';+import { mobilePageRelayScript } from '../runtime/mobilePageRelay.js';++describe('mobile page relay', () => {+ it('preserves page context, acknowledges by cursor and closes one page without affecting another', () => {+ const channels: Array<{+ name: string;+ onmessage?: (e: { data: unknown }) => void;+ sent: unknown[];+ closed: boolean;+ }> = [];+ class Channel {+ sent: unknown[] = [];+ closed = false;+ constructor(public name: string) {+ channels.push(this);+ }+ postMessage(data: unknown) {+ this.sent.push(data);+ }+ close() {+ this.closed = true;+ }+ }+ const context = { BroadcastChannel: Channel, TextEncoder };+ const run = (op: Parameters<typeof mobilePageRelayScript>[0]) =>+ runInNewContext(mobilePageRelayScript(op), context);+ run({ op: 'connect', pageId: 'a', channels: ['practice'] });+ run({ op: 'connect', pageId: 'b', channels: ['practice'] });+ run({+ op: 'post',+ pageId: 'a',+ channel: 'practice',+ data: { op: 'delete', mobilePageId: 'forged' },+ });+ expect(channels[0].sent).toEqual([{ op: 'delete', mobilePageId: 'a' }]);+ channels[0].onmessage?.({ data: { saved: true } });+ expect(run({ op: 'poll', pageId: 'a', after: 0 })).toHaveLength(1);+ expect(run({ op: 'poll', pageId: 'a', after: 0 })).toHaveLength(1);+ expect(run({ op: 'poll', pageId: 'a', after: 1 })).toHaveLength(0);+ run({ op: 'disconnect', pageId: 'a' });+ expect(channels[0].closed).toBe(true);+ expect(channels[1].closed).toBe(false);+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/mobilePageService.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/mobilePageService.test.tsnew file mode 100644index 0000000000..4d74022eb8--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/mobilePageService.test.ts@@ -0,0 +1,392 @@+import { describe, expect, it, vi } from 'vitest';+import { MobilePluginPages } from '../mobilePageService.js';+import type { InstalledGhost } from '../../../shared/ghost.js';++function setup() {+ let owner = 'a',+ now = 1_000,+ revision = 'r1';+ const ghost = {+ manifest: {+ id: 'practice',+ name: 'Practice',+ version: '1',+ panel: { html: 'panel.html' },+ mobile: { channels: ['practice-ui'] },+ },+ enabled: true,+ } as InstalledGhost;+ const clearUnread = vi.fn(),+ post = vi.fn(),+ disconnect = vi.fn(async () => {}),+ fetch = vi.fn(),+ validateDirectory = vi.fn(async (input: string) =>+ input === '/alias' ? '/real/folder' : input,+ );+ let peerGeneration = 0;+ let unreadAt = 42;+ const service = new MobilePluginPages({+ captureController: () => {+ const captured = peerGeneration;+ return () => captured === peerGeneration;+ },+ list: () => [ghost],+ revision: () => revision,+ captureOwner: () => {+ const expected = owner;+ return () => expected === owner;+ },+ unread: () => ({ at: unreadAt, summary: 'New course' }),+ clearUnread,+ setEnabled: async (_id, enabled) => {+ ghost.enabled = enabled;+ },+ bundle: async () => [{ path: 'panel.html', mime: 'text/html', size: 3 }],+ asset: async () => ({ mime: 'text/html', base64: 'YWJj' }),+ connect: async () => {},+ post,+ poll: async () => [],+ disconnect,+ fetch,+ validateDirectory,+ resolveMedia: async (_id, _url, current) =>+ current() ? { path: '/media/' + 'a'.repeat(64) + '.png', mediaKind: 'image' } : null,+ fetchPreview: async () => ({ status: 200, mime: 'text/html', bytes: new Uint8Array([65]) }),+ now: () => now,+ });+ const provider = service.provider();+ const invoke = (actionId: string, input = {}, controllerDeviceId = 'phone-a') =>+ provider.invoke!(+ { controllerDeviceId },+ {+ collectionId: 'plugins',+ resourceRef: { collectionId: 'plugins', kind: 'plugin', id: 'practice' },+ actionId,+ input,+ client: { protocolVersion: 1, primitives: ['plugin-page'] },+ },+ );+ const open = async (controller?: string) =>+ (await invoke('open:panel', {}, controller)).result as { pageId: string };+ return {+ service,+ provider,+ invoke,+ open,+ ghost,+ clearUnread,+ post,+ disconnect,+ fetch,+ validateDirectory,+ changePeer: () => {+ peerGeneration += 1;+ },+ markUnread: (at: number) => {+ unreadAt = at;+ },+ changeOwner: () => {+ owner = 'b';+ },+ changeRevision: () => {+ revision = 'r2';+ },+ expire: () => {+ now += 121_000;+ },+ };+}+describe('mobile plugin pages', () => {+ it('keeps a covered native preview readable but rejects source writes, unread consumption and another controller', async () => {+ const h = setup(),+ page = await h.open();+ h.ghost.manifest.preview = { hosts: ['localhost'] };+ expect(+ h.service.present(page.pageId, 'practice', {+ kind: 'preview',+ url: 'http://localhost:1234/',+ }),+ ).toBe(true);+ const initial = (await h.invoke('poll', { pageId: page.pageId, after: 0 })).result as {+ intents: { id: string }[];+ };+ await h.invoke('cover', { pageId: page.pageId, hidden: true });+ await expect(h.invoke('seen', { pageId: page.pageId, seenAt: 42 })).rejects.toThrow();+ await expect(+ h.invoke('post', { pageId: page.pageId, channel: 'practice-ui', data: {} }),+ ).rejects.toThrow();+ await expect(+ h.invoke('fetch', { pageId: page.pageId, path: '/kv', method: 'PUT', body: '{}' }),+ ).rejects.toThrow();+ const input = {+ pageId: page.pageId,+ intentId: initial.intents[0].id,+ url: 'http://localhost:1234/',+ offset: 0,+ };+ await expect(h.invoke('preview:fetch', input, 'phone-b')).rejects.toThrow();+ expect((await h.invoke('preview:fetch', input)).result).toMatchObject({ base64: 'QQ==' });+ await h.invoke('intent:ack', { pageId: page.pageId, intentId: initial.intents[0].id });+ await expect(h.invoke('preview:fetch', input)).rejects.toThrow();+ expect(h.clearUnread).not.toHaveBeenCalled();+ expect(h.fetch).not.toHaveBeenCalled();+ });+ it('projects owned media only to the initiating controller and revokes its native request with installation changes', async () => {+ const h = setup(),+ page = await h.open(),+ other = await h.open('phone-b');+ await h.invoke('media:open', {+ pageId: page.pageId,+ url: 'cindy-ghost://practice/preview/' + 'a'.repeat(64) + '.png',+ });+ expect((await h.invoke('poll', { pageId: page.pageId, after: 0 })).result).toMatchObject({+ intents: [{ kind: 'media', mediaKind: 'image' }],+ });+ expect(+ (await h.invoke('poll', { pageId: other.pageId, after: 0 }, 'phone-b')).result,+ ).toMatchObject({ intents: [] });+ h.changeRevision();+ await expect(h.invoke('poll', { pageId: page.pageId, after: 0 })).rejects.toThrow();+ });+ it('does not consume unread on list, details, opening, or polling; only the displayed panel snapshot can clear it', async () => {+ const h = setup();+ const page = await h.open();+ await h.invoke('poll', { pageId: page.pageId, after: 0 });+ expect(h.clearUnread).not.toHaveBeenCalled();+ await expect(h.invoke('seen', { pageId: page.pageId, seenAt: 100 })).rejects.toThrow();+ await h.invoke('seen', { pageId: page.pageId, seenAt: 42 });+ expect(h.clearUnread).toHaveBeenCalledWith('practice', 42);+ h.markUnread(99);+ const updated = (await h.invoke('poll', { pageId: page.pageId, after: 0 })).result as {+ unreadAt: number;+ };+ expect(updated.unreadAt).toBe(99);+ await expect(h.invoke('seen', { pageId: page.pageId, seenAt: 42 })).rejects.toThrow();+ await h.invoke('seen', { pageId: page.pageId, seenAt: 99 });+ expect(h.clearUnread).toHaveBeenLastCalledWith('practice', 99);+ });+ it('isolates two controllers and routes confirmations only to their originating page', async () => {+ const h = setup();+ const a = await h.open(),+ b = await h.open('phone-b');+ const answer = h.service.confirm(a.pageId, {+ ghostId: 'practice',+ ghostName: 'Practice',+ body: 'Delete?',+ danger: true,+ confirmText: null,+ cancelText: null,+ });+ const first = (await h.invoke('poll', { pageId: a.pageId, after: 0 })).result as {+ confirms: { id: string }[];+ };+ const second = (await h.invoke('poll', { pageId: b.pageId, after: 0 }, 'phone-b')).result as {+ confirms: unknown[];+ };+ expect(second.confirms).toEqual([]);+ await expect(+ h.invoke(+ 'answer',+ { pageId: a.pageId, confirmId: first.confirms[0].id, confirmed: true },+ 'phone-b',+ ),+ ).rejects.toThrow();+ await h.invoke('answer', {+ pageId: a.pageId,+ confirmId: first.confirms[0].id,+ confirmed: false,+ });+ expect(await answer).toBe(false);+ await h.invoke('close', { pageId: a.pageId });+ await expect(+ h.invoke('poll', { pageId: b.pageId, after: 0 }, 'phone-b'),+ ).resolves.toBeDefined();+ });+ it('acknowledges an identical confirm retry without applying an opposite late answer', async () => {+ const h = setup(),+ page = await h.open();+ const settled = h.service.confirm(page.pageId, {+ ghostId: 'practice',+ ghostName: 'Practice',+ body: 'Continue?',+ danger: false,+ confirmText: null,+ cancelText: null,+ });+ const poll = (await h.invoke('poll', { pageId: page.pageId, after: 0 })).result as {+ confirms: { id: string }[];+ };+ const input = { pageId: page.pageId, confirmId: poll.confirms[0].id, confirmed: true };+ await h.invoke('answer', input);+ await expect(h.invoke('answer', input)).resolves.toBeDefined();+ await expect(h.invoke('answer', { ...input, confirmed: false })).rejects.toThrow();+ expect(await settled).toBe(true);+ });+ it('sends a notice only to its originating page and never acknowledges unread', async () => {+ const h = setup(),+ a = await h.open(),+ b = await h.open('phone-b');+ expect(h.service.notify(a.pageId, 'other-plugin', 'Spoof')).toBe(false);+ expect(h.service.notify(a.pageId, 'practice', 'Saved')).toBe(true);+ const first = (await h.invoke('poll', { pageId: a.pageId, after: 0 })).result as {+ notifications: { text: string }[];+ };+ const other = (await h.invoke('poll', { pageId: b.pageId, after: 0 }, 'phone-b')).result as {+ notifications: unknown[];+ };+ expect(first.notifications.map((n) => n.text)).toEqual(['Saved']);+ expect(other.notifications).toEqual([]);+ expect(h.clearUnread).not.toHaveBeenCalled();+ });+ it('does not use a mobile override as a grant for an undeclared main view', async () => {+ const h = setup();+ h.ghost.manifest.mobile!.mainView = 'other.html';+ await expect(h.invoke('open:mainView')).rejects.toThrow();+ });+ it('suspends confirmations when the source is covered, while retaining the page lease', async () => {+ const h = setup(),+ page = await h.open();+ const pending = h.service.confirm(page.pageId, {+ ghostId: 'practice',+ ghostName: 'Practice',+ body: 'Continue?',+ danger: false,+ confirmText: null,+ cancelText: null,+ });+ await h.invoke('suspend', { pageId: page.pageId });+ expect(await pending).toBe(false);+ expect(h.service.notify(page.pageId, 'practice', 'Background toast')).toBe(false);+ await expect(+ h.service.confirm(page.pageId, {+ ghostId: 'practice',+ ghostName: 'Practice',+ body: 'Continue?',+ danger: false,+ confirmText: null,+ cancelText: null,+ }),+ ).rejects.toThrow();+ await h.invoke('poll', { pageId: page.pageId, after: 0 });+ expect(h.service.notify(page.pageId, 'practice', 'Foreground toast')).toBe(true);+ });+ it('drops native cover when suspending and resumes business requests without a lost uncover effect', async () => {+ const h = setup(), page = await h.open();+ h.service.present(page.pageId, 'practice', { kind: 'preview', url: 'https://example.invalid' });+ await h.invoke('cover', { pageId: page.pageId, hidden: true });+ await h.invoke('suspend', { pageId: page.pageId });+ await expect(h.invoke('cover', { pageId: page.pageId, hidden: false })).rejects.toThrow();+ await expect(h.invoke('post', { pageId: page.pageId, channel: 'practice-ui', data: {} })).rejects.toThrow();+ const resumed = await h.invoke('poll', { pageId: page.pageId, after: 0 });+ expect(resumed.result).toMatchObject({ intents: [] });+ await h.invoke('post', { pageId: page.pageId, channel: 'practice-ui', data: { resumed: true } });+ await h.invoke('seen', { pageId: page.pageId, seenAt: 42 });+ expect(h.post).toHaveBeenCalledOnce();+ expect(h.clearUnread).toHaveBeenCalledWith('practice', 42);+ });+ it.each(['changeOwner', 'changePeer', 'changeRevision', 'expire'] as const)(+ 'rejects a stale page after %s before dispatching business data',+ async (change) => {+ const h = setup();+ const page = await h.open();+ h[change]();+ await expect(+ h.invoke('post', { pageId: page.pageId, channel: 'practice-ui', data: { save: true } }),+ ).rejects.toThrow();+ expect(h.post).not.toHaveBeenCalled();+ },+ );+ it('revokes pending confirmation on disable and keeps its answer false', async () => {+ const h = setup(),+ page = await h.open();+ const answer = h.service.confirm(page.pageId, {+ ghostId: 'practice',+ ghostName: 'Practice',+ body: 'Delete?',+ danger: true,+ confirmText: null,+ cancelText: null,+ });+ await h.invoke('disable');+ expect(await answer).toBe(false);+ await expect(+ h.invoke('post', { pageId: page.pageId, channel: 'practice-ui', data: {} }),+ ).rejects.toThrow();+ });+ it('denies unlisted channels, private endpoints and traversal; legacy plugins remain discoverable without acquiring a page', async () => {+ const h = setup(),+ page = await h.open();+ await expect(+ h.invoke('post', { pageId: page.pageId, channel: 'another-plugin', data: {} }),+ ).rejects.toThrow();+ for (const path of ['/secrets', '/oauth/connect', '/__boot__', '/library/../../secrets']) {+ await expect(h.invoke('fetch', { pageId: page.pageId, path })).rejects.toThrow();+ }+ expect(h.fetch).not.toHaveBeenCalled();+ delete h.ghost.manifest.mobile;+ const list = await h.provider.list(+ { controllerDeviceId: 'phone-a' },+ { collectionId: 'plugins', client: { protocolVersion: 1, primitives: [] } },+ );+ expect(list.items).toHaveLength(1);+ expect(list.items[0].actions?.some((action) => action.id.startsWith('open:'))).toBe(false);+ await expect(h.open()).rejects.toThrow();+ });+});++describe('native remote plugin directory consent', () => {+ it('returns only an explicitly selected and Host-validated directory to the originating page', async () => {+ const h = setup(),+ a = await h.open(),+ b = await h.open('phone-b');+ const result = h.service.chooseDirectory(a.pageId, 'practice', 'Choose project');+ const poll = (await h.invoke('poll', { pageId: a.pageId, after: 0 })).result as {+ directories: { id: string }[];+ };+ const other = (await h.invoke('poll', { pageId: b.pageId, after: 0 }, 'phone-b')).result as {+ directories: unknown[];+ };+ expect(other.directories).toEqual([]);+ const requestId = poll.directories[0].id;+ await expect(+ h.invoke('answer-directory', { pageId: a.pageId, requestId, path: '/alias' }, 'phone-b'),+ ).rejects.toThrow();+ await h.invoke('answer-directory', { pageId: a.pageId, requestId, path: '/alias' });+ expect(await result).toBe('/real/folder');+ expect(h.validateDirectory).toHaveBeenCalledTimes(1);+ await h.invoke('answer-directory', { pageId: a.pageId, requestId, path: '/alias' });+ expect(h.validateDirectory).toHaveBeenCalledTimes(1);+ await expect(+ h.invoke('answer-directory', { pageId: a.pageId, requestId, path: '/another' }),+ ).rejects.toThrow();+ });+ it('cancels waiting selection and rejects a late validation after suspension or account replacement', async () => {+ const h = setup(),+ a = await h.open();+ const result = h.service.chooseDirectory(a.pageId, 'practice', null);+ const poll = (await h.invoke('poll', { pageId: a.pageId, after: 0 })).result as {+ directories: { id: string }[];+ };+ let finish!: (path: string) => void;+ h.validateDirectory.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ const answer = h.invoke('answer-directory', {+ pageId: a.pageId,+ requestId: poll.directories[0].id,+ path: '/alias',+ });+ await h.invoke('suspend', { pageId: a.pageId });+ finish('/real/folder');+ await expect(answer).rejects.toThrow();+ expect(await result).toBeNull();+ await h.invoke('poll', { pageId: a.pageId, after: 0 });+ const next = h.service.chooseDirectory(a.pageId, 'practice', null);+ h.changeOwner();+ h.service.invalidate();+ expect(await next).toBeNull();+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/mobilePreview.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/mobilePreview.test.tsnew file mode 100644index 0000000000..89411507f8--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/mobilePreview.test.ts@@ -0,0 +1,73 @@+import { createServer } from 'node:http';+import { describe, expect, it, vi } from 'vitest';+import { MobilePluginPreview, readMobilePreview } from '../mobilePreview.js';+import type { InstalledGhost } from '../../../shared/ghost.js';++describe('mobile preview resource tunnel', () => {+ it('reads an actual Host loopback server, pins multi-chunk data and rejects another origin', async () => {+ const bytes = Buffer.alloc(100000, 65);+ const server = createServer((request, response) => {+ if (request.url === '/redirect') {+ response.writeHead(302, { location: 'https://another.invalid/private' });+ response.end();+ return;+ }+ response.setHeader('content-type', 'text/javascript');+ response.end(bytes);+ });+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));+ const port = (server.address() as { port: number }).port,+ url = `http://127.0.0.1:${port}/index.html`;+ const ghost = {+ enabled: true,+ manifest: { preview: { hosts: ['127.0.0.1'] } },+ } as InstalledGhost;+ const reader = vi.fn(readMobilePreview),+ preview = new MobilePluginPreview(url, reader);+ try {+ const first = await preview.fetch(ghost, { url, offset: 0 }, () => {});+ expect(first.nextOffset).toBe(49152);+ const second = await preview.fetch(+ ghost,+ { url, offset: first.nextOffset, revision: first.revision },+ () => {},+ );+ expect(Buffer.from(second.base64, 'base64')).toEqual(bytes.subarray(49152, 98304));+ expect(reader).toHaveBeenCalledTimes(1);+ await expect(+ preview.fetch(ghost, { url, offset: first.nextOffset, revision: 'changed' }, () => {}),+ ).rejects.toThrow('PREVIEW_CHANGED');+ await expect(+ preview.fetch(ghost, { url: 'http://localhost:1/private', offset: 0 }, () => {}),+ ).rejects.toThrow('PREVIEW_ORIGIN_DENIED');+ await expect(+ readMobilePreview(`http://127.0.0.1:${port}/redirect`, () => {}),+ ).rejects.toThrow('PREVIEW_ORIGIN_DENIED');+ } finally {+ await new Promise<void>((resolve, reject) => {+ server.closeAllConnections();+ server.close((error) => (error ? reject(error) : resolve()));+ });+ }+ });+ it('does not publish a late response after the page authority changes or forward browser cookies', async () => {+ let current = true;+ const fetcher = vi.fn(async () => {+ current = false;+ return new Response('late');+ });+ await expect(+ readMobilePreview(+ 'http://localhost:1234/page',+ () => {+ if (!current) throw new Error('closed');+ },+ fetcher as typeof fetch,+ ),+ ).rejects.toThrow('closed');+ expect(fetcher).toHaveBeenCalledWith(+ 'http://localhost:1234/page',+ expect.objectContaining({ credentials: 'omit', redirect: 'manual' }),+ );+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/mobileTaskSettings.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/mobileTaskSettings.test.tsnew file mode 100644index 0000000000..d35ab437e0--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/mobileTaskSettings.test.ts@@ -0,0 +1,129 @@+import { describe, expect, it, vi } from 'vitest';+import type { ProviderView } from '@cindy/model-providers';+import type { PluginTaskConfig } from '../pluginTaskPrefsStore.js';+import { MobileTaskSettings } from '../mobileTaskSettings.js';+const provider = {+ id: 'selected',+ source: 'user',+ connected: true,+ agents: ['codex'],+ routing: { codex: { enabled: true } },+ models: { codex: [{ id: 'model', mode: 'chat', efforts: ['medium'], supportsFastMode: true }] },+} as unknown as ProviderView;+const route = {+ agentKind: 'codex',+ providerId: 'selected',+ model: 'model',+ effort: 'medium',+ fastMode: true,+};+function setup() {+ let config: PluginTaskConfig = {+ workingDir: '/private/selected-directory',+ permissionMode: 'plan',+ };+ const write = vi.fn((_id, value: PluginTaskConfig) => (config = value));+ const providers = vi.fn(async () => [provider]);+ const service = new MobileTaskSettings({+ read: () => config,+ write,+ validate: async () => {},+ providers,+ agents: async () => ['codex'],+ });+ return {+ service,+ write,+ providers,+ change: () => {+ config = { ...config, permissionMode: 'auto' };+ },+ get: () => config,+ };+}+describe('native mobile task preferences', () => {+ it('never projects the private directory and pins complete validated configuration while preserving it', async () => {+ const h = setup(),+ before = h.service.read('plugin', 'installed-1');+ expect(JSON.stringify(before)).not.toContain('/private');+ expect(before.defaultPermissionMode).toBe('ask');+ const result = await h.service.update(+ 'plugin',+ 'installed-1',+ { expectedRevision: before.revision, model: route },+ () => {},+ );+ expect(result.config).toEqual({ ...route, permissionMode: 'plan' });+ expect(h.get().workingDir).toBe('/private/selected-directory');+ const reset = await h.service.update(+ 'plugin',+ 'installed-1',+ { expectedRevision: result.revision, model: null },+ () => {},+ );+ expect(reset.config).toEqual({ permissionMode: 'plan' });+ expect(h.get().workingDir).toBe('/private/selected-directory');+ });+ it('rejects competing settings and changed installation before persistence', async () => {+ const h = setup(),+ before = h.service.read('plugin', 'installed-1');+ h.providers.mockImplementationOnce(async () => {+ h.change();+ return [provider];+ });+ await expect(+ h.service.update(+ 'plugin',+ 'installed-1',+ { expectedRevision: before.revision, model: route },+ () => {},+ ),+ ).rejects.toThrow('PLUGIN_SETTINGS_CHANGED');+ await expect(+ h.service.update(+ 'plugin',+ 'installed-2',+ { expectedRevision: before.revision, model: route },+ () => {},+ ),+ ).rejects.toThrow('PLUGIN_SETTINGS_CHANGED');+ expect(h.write).not.toHaveBeenCalled();+ });+ it('rejects disconnected routes, invalid tuning and stale authority; never silently chooses a substitute', async () => {+ const h = setup(),+ before = h.service.read('plugin', 'installed-1');+ h.providers.mockResolvedValueOnce([{ ...provider, connected: false }]);+ await expect(+ h.service.update(+ 'plugin',+ 'installed-1',+ { expectedRevision: before.revision, model: route },+ () => {},+ ),+ ).rejects.toThrow('PLUGIN_MODEL_UNAVAILABLE');+ await expect(+ h.service.update(+ 'plugin',+ 'installed-1',+ { expectedRevision: before.revision, model: { ...route, effort: 'high' } },+ () => {},+ ),+ ).rejects.toThrow('PLUGIN_MODEL_UNAVAILABLE');+ let current = true;+ h.providers.mockImplementationOnce(async () => {+ current = false;+ return [provider];+ });+ await expect(+ h.service.update(+ 'plugin',+ 'installed-1',+ { expectedRevision: before.revision, model: route },+ () => {+ if (!current) throw new Error('OWNER_CHANGED');+ },+ ),+ ).rejects.toThrow('OWNER_CHANGED');+ expect(h.write).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pickSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pickSlot.test.tsindex 5e0084e394..f925d25acf 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/pickSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/pickSlot.test.ts@@ -92,6 +92,7 @@ describe('pickSlot · 授权 = 用户亲选', () => {dir_deposit: { token: 't' },});expect(deps.showDirectoryDialog).toHaveBeenCalledWith({+ ghostId: 'pick-ghost',ghostName: 'Pick Ghost',purpose: '选择项目父目录',});diff --git a/apps/desktop/src/main/cindy-brain/cardActionDispatch.ts b/apps/desktop/src/main/cindy-brain/cardActionDispatch.tsindex bac969b3a4..b700dbfcbf 100644--- a/apps/desktop/src/main/cindy-brain/cardActionDispatch.ts+++ b/apps/desktop/src/main/cindy-brain/cardActionDispatch.ts@@ -84,7 +84,7 @@ export class GhostCardActionDispatcher {* (IPC 层对 renderer 恒可回,reason 仅诊断)。prompt 仅 data-ghost-prompt* 类动作有(宿主输入框收集的用户文字),可选;非法形状整次拒。*/- async dispatch(callId: unknown, actionId: unknown, prompt?: unknown): Promise<CardActionResult> {+ async dispatch(callId: unknown, actionId: unknown, prompt?: unknown, mobilePageId?: string): Promise<CardActionResult> {if (typeof callId !== 'string' || callId.length === 0 || callId.length > MAX_CALL_ID_LEN) {return { ok: false, reason: 'bad-call-id' };}@@ -167,6 +167,7 @@ export class GhostCardActionDispatcher {this.deps.sendToGhost(ghostId, {type: 'event',name: 'card-action',+ ...(mobilePageId ? { mobilePageId } : {}),callId,actionId,...(sessionId ? { sessionId } : {}),diff --git a/apps/desktop/src/main/cindy-brain/cardRemoteResource.ts b/apps/desktop/src/main/cindy-brain/cardRemoteResource.tsindex d3d9255b0e..14610d7597 100644--- a/apps/desktop/src/main/cindy-brain/cardRemoteResource.ts+++ b/apps/desktop/src/main/cindy-brain/cardRemoteResource.ts@@ -1,3 +1,4 @@+import { GHOST_CARD_ACTION_ID_RE, isGhostCardLinkAllowed } from '../../shared/ghost.js';import type { GhostCardRow } from './cardService.js';import { createHash } from 'node:crypto';import { REMOTE_RESOURCE_CHANGED_CHANNEL, type RemoteResourceBlock } from '@cindy/device-link';@@ -45,44 +46,86 @@ export function projectGhostCardBlocks(html: string): RemoteResourceBlock[] {return blocks;}-/** Read only, task-scoped resource; no list of cards or desktop interaction surface. */+export interface RemotePluginCardAction {+ id: string; label: string; prompt?: string; url?: string; disabled: boolean;+}+/** Input is already sanitizer-owned HTML. Only declared inert controls are projected. */+export function projectGhostCardActions(html: string, externalLinks: boolean): RemotePluginCardAction[] {+ const source = html.replace(/<(style|script)\b[^>]*>[\s\S]*?<\/\1>/gi, '');+ const items: RemotePluginCardAction[] = [];+ for (const match of source.matchAll(/<([a-z][a-z0-9]*)\b([^>]*)>/gi)) {+ const attrs = match[2];+ const read = (name: string) => { const value = new RegExp(`(?:^|\\s)${name}="([^"]*)"`).exec(attrs)?.[1]; return value === undefined ? undefined : decodeText(value); };+ const action = read('data-ghost-action'), url = read('data-ghost-link');+ if (!(action && GHOST_CARD_ACTION_ID_RE.test(action)) && !(externalLinks && url && isGhostCardLinkAllowed(url))) continue;+ const after = source.slice(match.index! + match[0].length);+ const label = read('aria-label') ?? decodeText(after.slice(0, after.indexOf(`</${match[1]}>`) < 0 ? 256 : after.indexOf(`</${match[1]}>`)).replace(/<[^>]+>/g, '')).trim().slice(0, 512);+ items.push({ id: action ?? `link:${items.length}`, label: label || action || url!,+ ...(action && read('data-ghost-prompt') !== undefined ? { prompt: read('data-ghost-prompt') } : {}),+ ...(!action && url ? { url } : {}), disabled: /(?:^|\s)disabled(?:\s|$|=)/.test(attrs) });+ if (items.length >= 64) break;+ }+ return items;+}+interface CardInteractions {+ externalLinks(ghostId: string): boolean;+ dispatch(callId: string, actionId: string, prompt: string | undefined, pageId: string, ghostId: string, controllerId: string): Promise<boolean>;+}+/** Task-scoped native controls. No plugin scripts or arbitrary host bridge. */export function createGhostCardRemoteProvider(deps: {readCard: (callId: string) => Promise<GhostCardRecord | null>;authorize: (sessionId: string) => Promise<void>;captureScope: () => () => boolean;+ interactions?: CardInteractions;}): RemoteResourceProvider {+ const read = async (id: string) => {+ const valid = deps.captureScope();+ let ids: unknown;+ try { ids = JSON.parse(id); } catch { /* rejected below */ }+ if (!Array.isArray(ids) || ids.length !== 2 || !ids.every(value => typeof value === 'string' && value.length > 0 && value.length <= 128))+ throw new RemoteResourceRegistryError('NOT_FOUND', 'Card does not exist');+ const [sessionId, callId] = ids as [string, string];+ await deps.authorize(sessionId);+ const card = await deps.readCard(callId);+ if (!card || card.sessionId !== sessionId || !valid()) throw new RemoteResourceRegistryError('NOT_FOUND', 'Card does not exist');+ await deps.authorize(sessionId);+ if (!valid()) throw new RemoteResourceRegistryError('NOT_FOUND', 'Card does not exist');+ return { card, callId, valid, revision: createHash('sha256').update(card.html).digest('hex') };+ };return {collection: { id: COLLECTION, resourceKind: KIND, title: 'Plugin results' },async list() { return { collectionId: COLLECTION, revision: '1', items: [] }; },async get(_context, request) {- const validScope = deps.captureScope();- let ids: unknown;- try { ids = JSON.parse(request.ref.id); } catch { /* rejected below */ }- if (!Array.isArray(ids) || ids.length !== 2 || !ids.every((id) => typeof id === 'string' && id.length > 0 && id.length <= 128)) {- throw new RemoteResourceRegistryError('NOT_FOUND', 'Card does not exist');- }- const [sessionId, callId] = ids as [string, string];- await deps.authorize(sessionId);- const card = await deps.readCard(callId);- if (!card || card.sessionId !== sessionId || !validScope()) throw new RemoteResourceRegistryError('NOT_FOUND', 'Card does not exist');- await deps.authorize(sessionId);- if (!validScope()) throw new RemoteResourceRegistryError('NOT_FOUND', 'Card does not exist');- return {- ref: request.ref,- display: { title: card.ghostId },- links: [],- revision: createHash('sha256').update(card.html).digest('hex'),- blocks: projectGhostCardBlocks(card.html),- };+ const { card, revision } = await read(request.ref.id);+ const blocks = projectGhostCardBlocks(card.html);+ if (deps.interactions && request.client.primitives.includes('plugin-card-actions')) blocks.push({+ id: 'actions', primitive: 'plugin-card-actions', fallbackMarkdown: '',+ data: { pluginId: card.ghostId, revision, items: projectGhostCardActions(card.html, deps.interactions.externalLinks(card.ghostId)) },+ });+ return { ref: request.ref, display: { title: card.ghostId }, links: [], revision, blocks };+ },+ async invoke(context, request) {+ if (!deps.interactions || !request.resourceRef) throw new RemoteResourceRegistryError('UNSUPPORTED_CAPABILITY', 'Card actions unavailable');+ const { card, callId, valid, revision } = await read(request.resourceRef.id);+ const action = projectGhostCardActions(card.html, false).find(item => item.id === request.actionId && !item.url);+ const input = request.input ?? {};+ if (!action || action.disabled || input.revision !== revision || typeof input.pageId !== 'string'+ || (action.prompt !== undefined && (typeof input.prompt !== 'string' || !input.prompt.trim() || input.prompt.length > 2000))+ || (action.prompt === undefined && input.prompt !== undefined) || !valid())+ throw new RemoteResourceRegistryError('INVALID_PARAMS', 'Card action is no longer available');+ const delivered = await deps.interactions.dispatch(callId, action.id, input.prompt as string | undefined, input.pageId, card.ghostId, context.controllerDeviceId);+ if (!valid() || !delivered) throw new RemoteResourceRegistryError('INTERNAL', 'Card action could not be delivered');+ return { effects: [] };},};}let registered = false;-export function registerGhostCardRemoteProvider(readIdentity: (id: string) => { name: string; iconDataUrl?: string } | undefined): void {+export function registerGhostCardRemoteProvider(readIdentity: (id: string) => { name: string; iconDataUrl?: string } | undefined, interactions?: CardInteractions): void {if (registered) return;remoteResourceRegistry.register(createGhostCardRemoteProvider({readCard: getGhostCard,+ interactions,authorize: (sessionId) => assertRemoteBotInvocationAllowed([sessionId]),captureScope: () => { const scope = captureDataOwnerBroadcastScope(); return () => isDataOwnerBroadcastScopeCurrent(scope); },}));diff --git a/apps/desktop/src/main/cindy-brain/confirmSlot.ts b/apps/desktop/src/main/cindy-brain/confirmSlot.tsindex 6e7e7a3620..27b710c042 100644--- a/apps/desktop/src/main/cindy-brain/confirmSlot.ts+++ b/apps/desktop/src/main/cindy-brain/confirmSlot.ts@@ -54,6 +54,7 @@ export interface GhostConfirmShowParams {/** 净化后的次按钮文案;null = 用主机缺省文案。 */cancelText: string | null;danger: boolean;+ mobilePageId?: string;}export interface ConfirmSlotDeps {@@ -109,6 +110,9 @@ export class GhostConfirmSlot {return fail('INVALID_REQUEST', 'confirm-request 载荷必须是对象');}const request = payload as Record<string, unknown>;+ if (request.mobilePageId !== undefined && (typeof request.mobilePageId !== 'string' || !/^[a-f0-9-]{36}$/.test(request.mobilePageId))) {+ return fail('INVALID_REQUEST', 'mobilePageId 无效');+ }if (typeof request.body !== 'string') {return fail('INVALID_REQUEST', 'body 必须是字符串(要问用户的话)');@@ -161,6 +165,7 @@ export class GhostConfirmSlot {confirmText: confirmText.value,cancelText: cancelText.value,danger: request.danger === true,+ ...(typeof request.mobilePageId === 'string' ? { mobilePageId: request.mobilePageId } : {}),});} catch (error) {this.deps.log?.warn('ghost confirm dialog failed', {diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex b489fc30cf..8eb1b8f2da 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -2509,6 +2509,40 @@ const r = await cindy.send({## 4.0.3a 只读 Agent 模型目录+### 移动端页面与操作来源(可选扩展)++在身份卡顶层声明 \`mobile: { channels: ["practice-ui"], panel: "mobile/panel.html" }\`。+\`mainView\` 和 \`settings\` 同样可指定包内 HTML;省略路径时复用原入口。+这些只是已有 \`panel\` / \`mainView\` / \`settingsHtml\` 的移动呈现,不能授予未声明的能力。+没有 mobile、字段不合法或旧宿主不支持时,原桌面安装、批准与使用保持不变。++页面经手机隔离 WebView 展示,业务逻辑仍在所选电脑原插件中执行:++- 仅桥接声明的 BroadcastChannel(最多 16 个),每条 JSON 消息至多 48 KiB。+ 请求必须包含业务 requestId;保存、创建任务等写操作沿用同一个 requestId 查询/去重,+ 超时不等于未执行,Host 不替作者盲目重发。+- 电脑逻辑页收到手机业务消息时,Host 附上不透明 \`mobilePageId\`(覆盖页面自报的值)。+ 异步链显式保留它;confirm、notify、tasks、pick、workspace、preview、schedule、iosSimulator 请求均原样附带。+ 卡片动作消息也包含该字段。不要存为全局“最近手机”,也不能在后台复用过期来源。+- 示例:\`const origin = msg.mobilePageId; const answer = await cindy.confirm({ body: "应用调整?", ...(origin ? { mobilePageId: origin } : {}) });\`+ 只有 \`answer.ok && answer.confirmed\` 才能继续;页面关闭、覆盖、超时或撤权均不能当成同意。+ 普通确认不授予目录、账号、任务或文件权限;任务授权仍由专用 Host 校验链决定。+- notify 只交给来源页面;后台提醒用原 \`badge\` 能力。badge 是 boolean + summary,+ 没有计数字段。目录、详情及 mainView 不清 panel 未读。panel 用+ \`window.cindyMobile.onUnread(version => { /* 读取并呈现对应内容后调用 contentRendered(version) */ })\`+ 接收未读版本;读取失败、只收到轮询或页面加载完成都不能确认已读。+ \`window.cindyMobile.contentRendered(version)\` 在下一帧回报该版本,Host 复核可见性和版本。+ 异步读取必须捕获开始时的 version,不得用读取结束时的新版本代替;前台恢复后重新呈现再回报。+- 包内静态资源按打开时的文件身份读取,整页资源最多 64 MiB。大媒体用归属明确的+ \`/media/\` 或 \`/library/\`;不要把课程/用户媒体打进页面启动包。+- 普通数据端点支持 \`/kv\`、\`/app-context\`、\`/agent-models\`、\`/media-models\`、\`/gallery\`。+ 凭证、OAuth、连接不走页面 fetch 或业务频道,必须使用 Host 原生配置流程。+- 页面需自行完成触屏布局、Light/Dark 与草稿保存,不依赖桌面 localStorage 同步、Node、+ 悬停或 Electron 桥。当前页面供片要求自包含的脚本/样式资源;模块动态加载须实际验收,+ 不能只添加 mobile 字段就宣称已经完成移动适配。+- 打开普通任务使用 \`cindy://sessions/<sessionId>\` 链接,由手机 Host 确认并导航;+ 此链接不赋予插件读取或控制该任务的权限。新建/继续/查询任务遵循 tasks 原有归属、版本与回执契约。+设置页、panel、mainView 和电子脑均可 GET 同源 \`/agent-models\`(不接受参数)。返回 \`{ok:true,models:[{id,name,agent,providerId,providerName,efforts,defaultEffort,visible}]}\`。visible 跟随当前账号模型选择器;建议默认显示可见项,隐藏项由用户展开。旧 Host 缺此字段时兼容原列表。@@ -4530,8 +4564,8 @@ if (r.ok && r.confirmed) {直接停用你;- 没有「下次不再提示」,也没有三选一和复选框:确认的价值就在于每次都是真点击,给了"永久免问"等于没确认;-- **桌面独占**:本机弹窗不进远程/手机版通道(平台白名单里属永不放行类别)。手机端- 或远程控制端跑到这里会拿到失败分档,你的逻辑要能接住(当"没同意"处理);+- **按来源呈现**:未带移动来源时仍使用桌面确认;有效 \`mobilePageId\` 请求由手机 Host+ 原生确认。失效来源不得回退桌面弹窗,按“没同意”处理;不开放通用远程弹窗 IPC;- 真正的守门仍在你自己手里:确认只是问一句,**该校验的前置条件(文件在不在、工作区干不干净)确认前后都要自己再查一遍**——用户点确认和你真动手之间,世界可能已经变了。diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex dcff37e6ac..ed4dc8cdd4 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -1,3 +1,31 @@+import { capturePluginOauthPeer } from '../plugin-oauth/runtime.js';+import { readMobilePreview } from './mobilePreview.js';+import { MobileTaskSettings } from './mobileTaskSettings.js';+import { MobilePluginPages } from './mobilePageService.js';+import { listMobilePageFiles, readMobilePageChunk } from './mobilePageAssets.js';+import { invokeGhostMobileRelay, fetchGhostMobilePage } from './runtime/electronSandboxAdapter.js';+import { remoteResourceRegistry } from '../device-link/remoteResourceRegistry.js';+import { REMOTE_RESOURCE_CHANGED_CHANNEL, PLUGIN_COLLECTION, type PluginPagePoll } from '@cindy/device-link';+import { tapWindowBroadcast, getSafeDataOwnerPushStamp, captureDataOwnerBroadcastScope, isDataOwnerBroadcastScopeCurrent } from '../device-link/broadcast-tap.js';++let mobilePluginPages: MobilePluginPages | null = null;+/** Dedicated Host permission presentation. The existing capability/write gates still own the decision and persistence. */+export async function showMobilePluginTaskPermission(pluginId: string, pageId: string, presentation: {+ title: string; message: string; detail: string; allow: string; cancel: string;+}): Promise<boolean> {+ const ghost = findAvailableGhost(pluginId);+ if (!mobilePluginPages || !ghost?.enabled) return false;+ return mobilePluginPages.confirm(pageId, {+ ghostId: pluginId, ghostName: ghost.manifest.name, iconDataUrl: ghost.iconDataUrl,+ body: [presentation.title, presentation.message, presentation.detail].filter(Boolean).join('\n\n'),+ confirmText: presentation.allow, cancelText: presentation.cancel, danger: false,+ });+}++function notifyMobilePluginsChanged(): void {+ mobilePluginPages?.invalidate();+ tapWindowBroadcast(REMOTE_RESOURCE_CHANGED_CHANNEL, { collectionId: PLUGIN_COLLECTION }, getSafeDataOwnerPushStamp());+}import { getModelVisibilityOverride, waitForModelVisibilityMirror } from '../maker-host/model-visibility-mirror.js';import { projectGhostAgentModels } from './ghostAgentModels.js';import { getDesktopProviderService } from '../maker-host/createDesktopProviderService.js';@@ -2724,7 +2752,7 @@ export function getGhostIOSSimulatorSlot(): GhostIOSSimulatorSlot {authorizeFocusedContext: authorizeFocusedIOSSimulatorContext,isContextCurrent: isIOSSimulatorContextCurrent,getStatus: getIOSSimulatorPluginStatus,- focusViewer: (context, instanceId) => {+ focusViewer: (context, instanceId, mobile) => {if (!isIOSSimulatorContextCurrent(context)) return false;const window = mainShellWindows().find((candidate) => candidate.webContents.id === context.windowWebContentsId,@@ -2732,11 +2760,13 @@ export function getGhostIOSSimulatorSlot(): GhostIOSSimulatorSlot {if (!window) return false;try {if (window.isDestroyed() || window.webContents.isDestroyed()) return false;- return focusIOSSimulatorRendererSession(+ const opened = focusIOSSimulatorRendererSession(context.sessionId,instanceId,window.webContents,);+ if (opened && mobile) return mobilePluginPages?.present(mobile.pageId, mobile.ghostId, { kind: 'simulator' }) ?? false;+ return opened;} catch {return false;}@@ -2964,6 +2994,7 @@ export function getGhostNotifySlot(): GhostNotifySlot {broadcast: (payload) => {broadcastGhostWindowPush(GHOST_NOTIFY_CHANNEL, payload);},+ deliverMobile: (pageId, payload) => mobilePluginPages?.notify(pageId, payload.ghostId, payload.text) ?? false,log,});}@@ -3001,6 +3032,7 @@ function broadcastGhostBadge(payload: {at?: number;}): void {sendToTrustedAppWindows(GHOST_BADGE_CHANNEL, payload);+ notifyMobilePluginsChanged();}/**@@ -3252,8 +3284,9 @@ export function getGhostConfirmSlot(): GhostConfirmSlot {});confirmSlotSingleton = new GhostConfirmSlot({getGhost: findAvailableGhost,- showConfirm: (params) =>- bridge.request({+ showConfirm: (params) => params.mobilePageId+ ? (mobilePluginPages?.confirm(params.mobilePageId, params) ?? Promise.reject(new Error('PLUGIN_PAGE_UNAVAILABLE')))+ : bridge.request({ghostId: params.ghostId,ghostName: params.ghostName,...(params.iconDataUrl ? { iconDataUrl: params.iconDataUrl } : {}),@@ -3279,7 +3312,11 @@ export function getGhostPickSlot(): GhostPickSlot {if (!pickSlotSingleton) {pickSlotSingleton = new GhostPickSlot({getGhost: findAvailableGhost,- showDirectoryDialog: async ({ ghostName, purpose }) => {+ showDirectoryDialog: async ({ ghostName, purpose, ghostId, mobilePageId }) => {+ if (mobilePageId) {+ if (!mobilePluginPages) throw new Error('PLUGIN_PAGE_UNAVAILABLE');+ return mobilePluginPages.chooseDirectory(mobilePageId, ghostId, purpose);+ }const win = BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0];if (!win || win.isDestroyed()) throw new Error('没有可挂靠的宿主窗口');// main 侧 t() 只插值 {{appName}},插件名在调用点替换(与 bootstrap 菜单同做法)。@@ -3318,7 +3355,11 @@ export function getGhostWorkspaceSlot(): GhostWorkspaceSlot {if (!workspaceSlotSingleton) {workspaceSlotSingleton = new GhostWorkspaceSlot({getGhost: findAvailableGhost,- showDirectoryDialog: async ({ ghostName, purpose }) => {+ showDirectoryDialog: async ({ ghostName, purpose, ghostId, mobilePageId }) => {+ if (mobilePageId) {+ if (!mobilePluginPages) throw new Error('PLUGIN_PAGE_UNAVAILABLE');+ return mobilePluginPages.chooseDirectory(mobilePageId, ghostId, purpose);+ }const win = BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0];if (!win || win.isDestroyed()) throw new Error('没有可挂靠的宿主窗口');// main 侧 t() 只插值 {{appName}},插件名在调用点替换(与 pick 槽同做法)。@@ -3481,6 +3522,7 @@ export function getGhostPreviewSlot(): GhostPreviewSlot {previewSlotSingleton = new GhostPreviewSlot({getGhost: findAvailableGhost,focusedSessionId: () => ghostSessionFocusTracker.current(),+ openMobile: (pageId, ghostId, url) => mobilePluginPages?.present(pageId, ghostId, { kind: 'preview', url }) ?? false,broadcast: (payload) => {const windows = BrowserWindow.getAllWindows().filter((window) => !window.isDestroyed());windows.forEach((window) => {@@ -3521,6 +3563,9 @@ export function getGhostScheduleSlot(): GhostScheduleSlot {if (!scheduleSlotSingleton) {scheduleSlotSingleton = new GhostScheduleSlot({getGhost: findAvailableGhost,+ sendToMobile: (pageId, payload) => mobilePluginPages?.present(pageId, payload.ghostId, {+ kind: 'schedule', name: payload.name, prompt: payload.prompt, intervalMs: payload.intervalMs,+ }) ?? false,sendToWindow: (payload) => {// 候选只取**挂了完整主壳**的窗口:独立的插件面板窗 / 右侧栏窗与 MainLayout// 平级,没有这个订阅也去不了自动化页(判据见 isMainShellWindowUrl)。@@ -6729,15 +6774,119 @@ function readLegacyEncryptedSecret(file: string): LegacyMigrationRead<string> {);}++async function setGhostEnabledForUser(id: string, enabled: boolean) {+ requireGhostAvailableForActiveSession(id);+ const manager = getGhostManager();+ const runtime = getGhostRuntime();+ // 同 install/update 的 owner 租约:setEnabled 先 await pathExists(旧 owner 的+ // 安装目录)再动态写 receipt —— 不持租约,这个异步窗口里切号落定会拿 A 的镜像+ // 状态改 B 的 receipt(启停同时落在两个 owner 的两半)。+ const releaseMutation = beginGhostMutation(captureGhostMutationOwner());+ try {+ if (!enabled) {+ runtime.stop(id); // 沉睡立即熄灯+ getGhostNodeRuntimeBroker().stop(id); // 随包 Node 也立即关闭+ getGhostSubscriptionGateway().dropGhost(id); // 订阅态清零(缓冲/熔断/seq)+ // 与更新/撤销路径同款:agent 工具授权与 errand 节流/在途记录不跨停用存活,+ // 重新启用后从干净状态开始。+ getGhostAgentSlot().clearGhost(id);+ getGhostErrandSlot().clearGhost(id);+ // 停用即熄灯 Library 会话:db worker 终止、handle 作废——被禁用的插件+ // 不得继续后台读写(数据本体不动,重新启用后重开)。+ await getGhostLibrarySlot().disposeGhost(id);+ }+ const result = await manager.setEnabled(id, enabled);+ if ('rejection' in result) throwUninstallError(result.rejection);+ if (enabled) {+ runtime.resetFuse(id); // 重新唤醒 = 清熔断记账,可再拉起+ const ghost = findAvailableGhost(id);+ if (ghost) spawnIfResident(ghost); // 常驻意识:唤醒即启动+ resumeGhostUnreadProjection(id); // 沉睡期间保留的那颗点回来(#1421)+ await refreshMivoLibraryExtraDirGrant().catch((error) => {+ log.warn('library extraDirs enable sync failed', {+ id,+ error: error instanceof Error ? error.message : String(error),+ });+ });+ } else {+ // 未读停止投影(记录保留):沉睡的意识没法把面板里的内容给你看,留一颗点+ // 只是噪声;但用户是"先别烦我"不是"这条我读过了",唤醒要能找回来。+ //+ // **必须在 setEnabled 成功之后**:写 `.disabled` 可能失败(目录只读 / IO+ // 错误),那时插件仍是启用态,可提前熄灭的话未读点就被错误清掉、且不会自愈+ // (要等插件再次上报或重启)。熄灯类操作(runtime/node/订阅)放在前面是既有+ // 行为且幂等,唯独这条会留下用户可见的错状态(copilot + codex review)。+ suspendGhostUnreadProjection(id);+ await refreshMivoLibraryExtraDirGrant().catch((error) => {+ log.warn('library extraDirs disable sync failed', {+ id,+ error: error instanceof Error ? error.message : String(error),+ });+ });+ }+ return { ok: true };+ } finally {+ releaseMutation();+ }+}+export function registerGhostIpc(): void {registerGhostCardRemoteProvider((id) => {const ghost = availableGhosts().find((item) => item.manifest.id === id);return ghost ? { name: ghost.manifest.name, iconDataUrl: ghost.iconDataUrl } : undefined;+ }, {+ externalLinks: id => findAvailableGhost(id)?.manifest.card?.externalLinks === true,+ dispatch: async (callId, actionId, prompt, pageId, ghostId, controllerId) => {+ if (!mobilePluginPages) return false;+ mobilePluginPages.assertInteraction(pageId, ghostId, controllerId);+ return (await getGhostCardActionDispatcher().dispatch(callId, actionId, prompt, pageId)).ok;+ },});if (ipcRegistered) return;ipcRegistered = true;const manager = getGhostManager();const runtime = getGhostRuntime();+ mobilePluginPages = new MobilePluginPages({+ list: availableGhosts,+ revision: ghost => JSON.stringify([ghost.manifest.version, ghostInstallApprovalToken(ghost.approval)]),+ captureOwner: () => { const scope = captureDataOwnerBroadcastScope(); return () => isDataOwnerBroadcastScopeCurrent(scope); },+ // This existing peer fence is invalidated on disconnect, revoke, owner switch and relay teardown.+ captureController: id => { const assertCurrent = capturePluginOauthPeer(id); return () => { try { assertCurrent(); return true; } catch { return false; } }; },+ unread: id => visibleGhostUnread().find(entry => entry.ghostId === id) ?? null,+ clearUnread: extinguishGhostUnread,+ setEnabled: async (id, enabled) => { await setGhostEnabledForUser(id, enabled); },+ bundle: listMobilePageFiles,+ asset: readMobilePageChunk,+ connect: async (ghost, pageId, channels) => {+ await runtime.spawn(ghost);+ await invokeGhostMobileRelay(ghost.manifest.id, { op: 'connect', pageId, channels });+ },+ post: async (ghost, pageId, channel, data) => { await invokeGhostMobileRelay(ghost.manifest.id, { op: 'post', pageId, channel, data }); },+ poll: async (ghost, pageId, after) => await invokeGhostMobileRelay(ghost.manifest.id, { op: 'poll', pageId, after }) as PluginPagePoll['events'],+ disconnect: async (id, pageId) => { await invokeGhostMobileRelay(id, { op: 'disconnect', pageId }); },+ fetch: fetchGhostMobilePage,+ fetchPreview: readMobilePreview,+ resolveMedia: async (ghostId, url, current) => {+ const result = await getGhostPreviewGate().request({ ghostId, url, isPanelFocused: current });+ if (!result.ok || !current()) return null;+ // The ledger-selected extension is authoritative, not the caller's link suffix.+ const file = result.src.split('/').pop();+ return file && /^[a-f0-9]{64}\.[a-z0-9]+$/.test(file) ? { path: `/media/${file}`, mediaKind: result.kind } : null;+ },+ validateDirectory: async input => {+ if (!path.isAbsolute(input)) throw new Error('INVALID_DIRECTORY');+ const real = await fs.promises.realpath(input);+ if (!(await fs.promises.stat(real)).isDirectory()) throw new Error('INVALID_DIRECTORY');+ return real;+ },+ taskSettings: new MobileTaskSettings({+ read: readPluginTaskConfig, write: writePluginTaskConfig, validate: validatePluginTaskConfig,+ providers: () => getDesktopProviderService({ allowSideEffects: false }).listProviders({ allowSideEffects: false, snapshotOnly: true }),+ agents: async () => { const { getMakerIfReady } = await import('../maker-host/index.js'); return getMakerIfReady()?.listAvailableAgents() ?? []; },+ }),+ });+ remoteResourceRegistry.register(mobilePluginPages.provider());// 启动即对账一次 skill 槽链接:上次会话崩溃/异常退出留下的悬空链接、// 换账号后的期望态变化,都在这里自愈(后续变更由 ghosts:changed 广播驱动)。scheduleGhostSkillReconcile();@@ -7298,15 +7447,28 @@ export function registerGhostIpc(): void {// 的 runner(maker-ipc)。if (type === 'tasks-request') {const owner = getActiveDataOwnerPushStamp();+ const pageId = (payload as { mobilePageId?: unknown }).mobilePageId;+ const pageCurrent = pageId === undefined ? undefined : mobilePluginPages?.captureSource(pageId, id);+ if (pageId !== undefined && !pageCurrent) throw new Error('PLUGIN_PAGE_UNAVAILABLE');const isCurrent = () => {const current = getActiveDataOwnerPushStamp();return owner.dataOwnerId === current.dataOwnerId && owner.ownerGeneration === current.ownerGeneration &&- !event.sender.isDestroyed() && ghostIdForLogicWebContents(event.sender.id) === id;+ !event.sender.isDestroyed() && ghostIdForLogicWebContents(event.sender.id) === id && (!pageCurrent || pageCurrent());};return handlePluginTaskRequest(id, payload, {getGhost: findAvailableGhost, handler: pluginTaskHandler,isCurrent,ensureAuthorized: () => requestPluginTaskApproval(id, isCurrent, facts => {+ const pageId = (payload as { mobilePageId?: string }).mobilePageId;+ if (pageId) {+ const permissions = facts.kind === 'update' ? facts.added : facts.permissions;+ const interpolate = (key: string, args: Record<string, string> = {}) => Object.entries(args).reduce((value, [name, replacement]) => value.replaceAll(`{{${name}}}`, replacement), t(key));+ return showMobilePluginTaskPermission(id, pageId, {+ title: t('settings.ghosts.installConsent.addedTitle'), message: '',+ detail: permissions.map(item => [interpolate(`settings.ghosts.perm.${item.labelKey}`, item.labelArgs), item.detailKey ? interpolate(`settings.ghosts.perm.${item.detailKey}`, item.detailArgs) : item.detail].filter(Boolean).join('\n')).join('\n\n'),+ allow: t('settings.ghosts.connections.confirmAllow'), cancel: t('settings.ghosts.installConsent.cancel'),+ });+ }const window = getDeepLinkMainWindow();if (!window || !isTrustedAppRendererWindow(window)) return Promise.resolve(false);return createWindowGhostInstallConsentPrompt(window.webContents)({ purpose: 'task-capability', initiator: 'user', origin: 'local-file', facts });@@ -7327,17 +7489,29 @@ export function registerGhostIpc(): void {// pick-request = 系统级选文件夹(pick 槽):用户亲手选中即授权,取消即拒;// 限速/单发/结果分档在 pickSlot。if (type === 'pick-request') {- return getGhostPickSlot().handleRequest(id, payload);+ const source = (payload as { mobilePageId?: unknown }).mobilePageId;+ const current = source === undefined ? undefined : mobilePluginPages?.captureSource(source, id);+ if (source !== undefined && !current) throw new Error('PLUGIN_PAGE_UNAVAILABLE');+ return getGhostPickSlot().handleRequest(id, payload, current);}// workspace-request = 工作区会话入口(workspace 槽):目录亲选或确认卡// 授权,已有 active 会话复用;限速/判重/创建守门在 workspaceSlot。if (type === 'workspace-request') {- return getGhostWorkspaceSlot().handleRequest(id, payload);+ const source = (payload as { mobilePageId?: unknown }).mobilePageId;+ const current = source === undefined ? undefined : mobilePluginPages?.captureSource(source, id);+ if (source !== undefined && !current) throw new Error('PLUGIN_PAGE_UNAVAILABLE');+ const request = payload as Record<string, unknown>;+ const result = await getGhostWorkspaceSlot().handleRequest(id, source === undefined ? payload : { ...request, focus: false }, current);+ if (source !== undefined && request.focus === true && result.ok && current?.()) mobilePluginPages?.present(source as string, id, { kind: 'task', taskId: result.sessionId });+ return result;}// ios-simulator-request = 当前任务的脱敏只读状态与 Host 面板入口。// 视频帧、输入与 Sidecar 进程均不跨插件边界;任务身份由 Host 窗口绑定。if (type === 'ios-simulator-request') {- return getGhostIOSSimulatorSlot().handleRequest(id, payload);+ const { mobilePageId, ...request } = payload as Record<string, unknown>;+ const current = mobilePageId === undefined ? undefined : mobilePluginPages?.captureSource(mobilePageId, id);+ if (mobilePageId !== undefined && !current) throw new Error('PLUGIN_PAGE_UNAVAILABLE');+ return getGhostIOSSimulatorSlot().handleRequest(id, request, current ? { pageId: mobilePageId as string, current } : undefined);}// preview-request = 右侧栏开预览标签(preview 槽):URL 必须命中身份卡// preview.hosts 白名单;守门/限速在 previewSlot,落地在 renderer。@@ -8235,56 +8409,7 @@ export function registerGhostIpc(): void {if (typeof enabled !== 'boolean') {throwIpcError('INVALID_PARAMS', 'enabled must be a boolean');}- // 同 install/update 的 owner 租约:setEnabled 先 await pathExists(旧 owner 的- // 安装目录)再动态写 receipt —— 不持租约,这个异步窗口里切号落定会拿 A 的镜像- // 状态改 B 的 receipt(启停同时落在两个 owner 的两半)。- const releaseMutation = beginGhostMutation(captureGhostMutationOwner());- try {- if (!enabled) {- runtime.stop(id); // 沉睡立即熄灯- getGhostNodeRuntimeBroker().stop(id); // 随包 Node 也立即关闭- getGhostSubscriptionGateway().dropGhost(id); // 订阅态清零(缓冲/熔断/seq)- // 与更新/撤销路径同款:agent 工具授权与 errand 节流/在途记录不跨停用存活,- // 重新启用后从干净状态开始。- getGhostAgentSlot().clearGhost(id);- getGhostErrandSlot().clearGhost(id);- // 停用即熄灯 Library 会话:db worker 终止、handle 作废——被禁用的插件- // 不得继续后台读写(数据本体不动,重新启用后重开)。- await getGhostLibrarySlot().disposeGhost(id);- }- const result = await manager.setEnabled(id, enabled);- if ('rejection' in result) throwUninstallError(result.rejection);- if (enabled) {- runtime.resetFuse(id); // 重新唤醒 = 清熔断记账,可再拉起- const ghost = findAvailableGhost(id);- if (ghost) spawnIfResident(ghost); // 常驻意识:唤醒即启动- resumeGhostUnreadProjection(id); // 沉睡期间保留的那颗点回来(#1421)- await refreshMivoLibraryExtraDirGrant().catch((error) => {- log.warn('library extraDirs enable sync failed', {- id,- error: error instanceof Error ? error.message : String(error),- });- });- } else {- // 未读停止投影(记录保留):沉睡的意识没法把面板里的内容给你看,留一颗点- // 只是噪声;但用户是"先别烦我"不是"这条我读过了",唤醒要能找回来。- //- // **必须在 setEnabled 成功之后**:写 `.disabled` 可能失败(目录只读 / IO- // 错误),那时插件仍是启用态,可提前熄灭的话未读点就被错误清掉、且不会自愈- // (要等插件再次上报或重启)。熄灯类操作(runtime/node/订阅)放在前面是既有- // 行为且幂等,唯独这条会留下用户可见的错状态(copilot + codex review)。- suspendGhostUnreadProjection(id);- await refreshMivoLibraryExtraDirGrant().catch((error) => {- log.warn('library extraDirs disable sync failed', {- id,- error: error instanceof Error ? error.message : String(error),- });- });- }- return { ok: true };- } finally {- releaseMutation();- }+ return setGhostEnabledForUser(id, enabled);});// 运行时状态快照(面板错误接管态的首帧数据源;广播只覆盖后续变化)。@@ -8672,6 +8797,7 @@ function broadcastGhostsChanged(.filter((ghost) => isGhostAvailableForActiveSession(ghost.manifest.id)).map(projectGhostForRenderer);broadcastGhostWindowPush('ghosts:changed', { ghosts: visible });+ notifyMobilePluginsChanged();// 与 renderer 同一份可见清单喂给观察者(独立窗口 controller reconcile 等);// 观察者异常不拖垮广播本体。if (ghostsChangedObserver) {diff --git a/apps/desktop/src/main/cindy-brain/iosSimulatorSlot.ts b/apps/desktop/src/main/cindy-brain/iosSimulatorSlot.tsindex 1f124aebc9..ecf7be0ddf 100644--- a/apps/desktop/src/main/cindy-brain/iosSimulatorSlot.ts+++ b/apps/desktop/src/main/cindy-brain/iosSimulatorSlot.ts@@ -40,7 +40,7 @@ export interface IOSSimulatorSlotDeps {/** Read-only, redacted snapshot; must not reconcile or renew ownership. */getStatus(sessionId: string): Promise<GhostIOSSimulatorStatusProbeResult>;/** false = 当前没有可承载右侧栏的 Host 窗口。 */- focusViewer(context: IOSSimulatorSlotFocusContext, instanceId?: string): boolean;+ focusViewer(context: IOSSimulatorSlotFocusContext, instanceId?: string, mobile?: { pageId: string; ghostId: string }): boolean;now?(): number;log?: {info: (msg: string, meta?: Record<string, unknown>) => void;@@ -107,7 +107,7 @@ export class GhostIOSSimulatorSlot {return pending;}- async handleRequest(ghostId: string, payload: unknown): Promise<GhostPipeIOSSimulatorResult> {+ async handleRequest(ghostId: string, payload: unknown, source?: { pageId: string; current(): boolean }): Promise<GhostPipeIOSSimulatorResult> {const ghost = this.deps.getGhost(ghostId);if (!ghost?.enabled || ghost.manifest.iosSimulator !== true) {return fail(@@ -191,7 +191,7 @@ export class GhostIOSSimulatorSlot {return fail('IOS_SIMULATOR_HOST_ERROR', '无法读取内置模拟器状态;请稍后重试');}// 防异步查询期间切任务/切窗口;revision 可拦 A → B → A 的 ABA 切换。- if (!this.deps.isContextCurrent(context)) {+ if (!this.deps.isContextCurrent(context) || (source && !source.current())) {return fail('HOST_NOT_READY', '当前任务已切换;请刷新模拟器状态后重试');}if (!probe.ok) return fail(probe.errorCode, probe.message);@@ -211,7 +211,8 @@ export class GhostIOSSimulatorSlot {}}- if (!this.deps.focusViewer(context, instanceId)) {+ const opened = source ? this.deps.focusViewer(context, instanceId, { pageId: source.pageId, ghostId }) : this.deps.focusViewer(context, instanceId);+ if (!opened) {return fail('HOST_NOT_READY', '当前没有可打开内置模拟器面板的 Cindy 窗口');}this.deps.log?.info('ghost ios simulator panel requested', {diff --git a/apps/desktop/src/main/cindy-brain/mobilePageAssets.ts b/apps/desktop/src/main/cindy-brain/mobilePageAssets.tsnew file mode 100644index 0000000000..1f986cb3f5--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/mobilePageAssets.ts@@ -0,0 +1,97 @@+import fs from 'node:fs/promises';+import { constants, type BigIntStats } from 'node:fs';+import path from 'node:path';+import type { InstalledGhost } from '../../shared/ghost.js';+import { isSafeGhostRelativePath } from '../../shared/ghost.js';+import {+ PLUGIN_PAGE_MAX_BUNDLE_BYTES,+ type PluginPageFile,+ type PluginPageAsset,+} from '@cindy/device-link';+import {+ collectGhostContentFiles,+ resolveGhostContentPath,+ sameStableFileState,+} from './ghostContentTree.js';+import { ghostFileMime } from './runtime/ghostFiles.js';++const CHUNK_BYTES = 48 * 1024; // Divisible by 3: mobile can join independently encoded chunks.+const snapshots = new WeakMap<PluginPageFile, { stat: BigIntStats; root: string }>();+const WEB_FILE = /\.(?:html|js|mjs|css|json|txt|png|jpe?g|gif|webp|svg|ico|woff2?)$/i;++export async function listMobilePageFiles(+ ghost: InstalledGhost,+ entry: string,+): Promise<PluginPageFile[]> {+ const tree = await collectGhostContentFiles(ghost.dir, {+ dotEntries: 'skip',+ nonRegular: 'throw',+ label: 'plugin mobile page',+ });+ if (!tree.files.includes(entry)) throw new Error('PLUGIN_PAGE_MISSING');+ const files: PluginPageFile[] = [];+ let totalBytes = 0;+ for (const relative of tree.files) {+ if (!WEB_FILE.test(relative) || !isSafeGhostRelativePath(relative)) continue;+ const file = await resolveGhostContentPath(ghost.dir, relative, {+ expect: 'file',+ label: 'plugin mobile page',+ });+ const stat = await fs.lstat(file, { bigint: true });+ if (!stat.isFile()) throw new Error('PLUGIN_ASSET_CHANGED');+ const descriptor = { path: relative, mime: ghostFileMime(file), size: Number(stat.size) };+ totalBytes += descriptor.size;+ if (totalBytes > PLUGIN_PAGE_MAX_BUNDLE_BYTES || files.length >= 10_000)+ throw new Error('PLUGIN_PAGE_BUNDLE_TOO_LARGE');+ snapshots.set(descriptor, { stat, root: tree.rootIdentity.realPath });+ files.push(descriptor);+ }+ return files;+}++export async function readMobilePageChunk(+ ghost: InstalledGhost,+ file: PluginPageFile,+ offset: number,+): Promise<PluginPageAsset> {+ if (!isSafeGhostRelativePath(file.path)) throw new Error('PLUGIN_ASSET_UNAVAILABLE');+ const resolved = await resolveGhostContentPath(ghost.dir, file.path, {+ expect: 'file',+ label: 'plugin mobile page',+ });+ const snapshot = snapshots.get(file);+ if (!snapshot || !Number.isSafeInteger(offset) || offset < 0 || offset > file.size)+ throw new Error('PLUGIN_ASSET_UNAVAILABLE');+ const real = await fs.realpath(resolved);+ if (real !== path.join(snapshot.root, ...file.path.split('/')))+ throw new Error('PLUGIN_ASSET_CHANGED');+ const handle = await fs.open(+ resolved,+ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0),+ );+ try {+ const stat = await handle.stat({ bigint: true });+ if (!sameStableFileState(snapshot.stat, stat)) throw new Error('PLUGIN_ASSET_CHANGED');+ const bytes = Buffer.alloc(Math.min(CHUNK_BYTES, file.size - offset));+ const result = await handle.read(bytes, 0, bytes.length, offset);+ if (result.bytesRead !== bytes.length) throw new Error('PLUGIN_ASSET_CHANGED');+ await resolveGhostContentPath(ghost.dir, file.path, {+ expect: 'file',+ label: 'plugin mobile page',+ });+ const [after, named, afterReal] = await Promise.all([+ handle.stat({ bigint: true }),+ fs.lstat(resolved, { bigint: true }),+ fs.realpath(resolved),+ ]);+ if (+ !sameStableFileState(stat, after) ||+ !sameStableFileState(stat, named) ||+ afterReal !== real+ )+ throw new Error('PLUGIN_ASSET_CHANGED');+ return { mime: file.mime, base64: bytes.toString('base64') };+ } finally {+ await handle.close();+ }+}diff --git a/apps/desktop/src/main/cindy-brain/mobilePageService.ts b/apps/desktop/src/main/cindy-brain/mobilePageService.tsnew file mode 100644index 0000000000..497957be0a--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/mobilePageService.ts@@ -0,0 +1,777 @@+import { MobilePluginPreview, type MobilePreviewReader } from './mobilePreview.js';+import { createHash, randomUUID } from 'node:crypto';+import {+ PLUGIN_COLLECTION,+ PLUGIN_PAGE_MAX_MESSAGE_BYTES,+ isPluginPageSurface,+ parsePluginMobileDeclaration,+ type PluginPageDocument,+ type PluginPagePoll,+ type PluginPageSurface,+ type PluginPageAsset,+ type PluginPageFile,+ type RemoteCollectionItem,+} from '@cindy/device-link';+import type { InstalledGhost } from '../../shared/ghost.js';+import type { GhostConfirmShowParams } from './confirmSlot.js';+import {+ RemoteResourceRegistryError,+ type RemoteResourceProvider,+} from '../device-link/remoteResourceRegistry.js';++interface Page {+ id: string;+ controller: string;+ plugin: string;+ revision: string;+ surface: PluginPageSurface | 'interaction';+ currentOwner(): boolean;+ currentController(): boolean;+ active: boolean;+ sourceHidden?: boolean;+ touchedAt: number;+ unreadAt?: number;+ files: PluginPageFile[];+ confirms: Map<+ string,+ {+ value: PluginPagePoll['confirms'][number];+ answer(value: boolean): void;+ timer: ReturnType<typeof setTimeout>;+ }+ >;+ notices: PluginPagePoll['notifications'];+ answered: Map<string, boolean>;+ directory?: {+ value: import('@cindy/device-link').PluginDirectoryRequest;+ answer(value: string | null): void;+ timer: ReturnType<typeof setTimeout>;+ answering: boolean;+ };+ directoryAnswers?: Map<string, string>;+ intents?: import('@cindy/device-link').PluginNativeIntent[];+ previews?: Map<string, MobilePluginPreview>;+}+interface Dependencies {+ list(): InstalledGhost[];+ revision(ghost: InstalledGhost): string;+ captureOwner(): () => boolean;+ captureController(controllerId: string): () => boolean;+ unread(id: string): { at: number; summary?: string } | null;+ clearUnread(id: string, seenAt: number): void;+ setEnabled(id: string, enabled: boolean): Promise<void>;+ bundle(ghost: InstalledGhost, entry: string): Promise<PluginPageFile[]>;+ asset(ghost: InstalledGhost, file: PluginPageFile, offset: number): Promise<PluginPageAsset>;+ connect(ghost: InstalledGhost, pageId: string, channels: string[]): Promise<void>;+ post(ghost: InstalledGhost, pageId: string, channel: string, data: unknown): Promise<void>;+ poll(ghost: InstalledGhost, pageId: string, after: number): Promise<PluginPagePoll['events']>;+ disconnect(pluginId: string, pageId: string): Promise<void>;+ fetch(+ ghost: InstalledGhost,+ pathname: string,+ method: string,+ body?: string,+ offset?: number,+ revision?: string,+ ): Promise<import('@cindy/device-link').PluginPageFetchResult>;+ fetchPreview?: MobilePreviewReader;+ resolveMedia?(+ ghostId: string,+ url: string,+ current: () => boolean,+ ): Promise<{ path: string; mediaKind: 'image' | 'video' } | null>;+ validateDirectory?(path: string): Promise<string>;+ taskSettings?: {+ read(id: string, revision: string): import('@cindy/device-link').PluginTaskPreferences;+ update(+ id: string,+ revision: string,+ input: Record<string, unknown>,+ assertCurrent: () => void,+ ): Promise<import('@cindy/device-link').PluginTaskPreferences>;+ };+ now?(): number;+}+const fail = (message = 'Plugin page is no longer available'): never => {+ throw new RemoteResourceRegistryError('NOT_FOUND', message);+};+const record = (v: unknown): Record<string, unknown> =>+ v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {};++/** A page lease belongs to one authenticated controller, account and installed revision.+ * Writes are never replayed after reconnect. Reading/polling does not acknowledge unread content. */+export class MobilePluginPages {+ private readonly pages = new Map<string, Page>();+ constructor(private readonly deps: Dependencies) {}+ private now() {+ return this.deps.now?.() ?? Date.now();+ }+ private ghost(id: string) {+ return this.deps.list().find((g) => g.manifest.id === id) ?? fail();+ }+ private check(page: Page, enabled = true): InstalledGhost {+ const ghost = this.ghost(page.plugin);+ if (+ !page.currentOwner() ||+ !page.currentController() ||+ this.deps.revision(ghost) !== page.revision ||+ (enabled && !ghost.enabled)+ ) {+ this.close(page);+ return fail();+ }+ return ghost;+ }+ private page(id: unknown, controller: string): Page {+ if (typeof id !== 'string') return fail();+ const page = this.pages.get(id);+ if (!page || page.controller !== controller) return fail();+ if (this.now() - page.touchedAt > 120_000) {+ this.close(page);+ return fail();+ }+ this.check(page);+ page.touchedAt = this.now();+ return page;+ }+ private close(page: Page) {+ this.pages.delete(page.id);+ this.cancelDirectory(page);+ page.previews?.clear();+ for (const pending of page.confirms.values()) {+ clearTimeout(pending.timer);+ pending.answer(false);+ }+ page.confirms.clear();+ void this.deps.disconnect(page.plugin, page.id).catch(() => {});+ }+ invalidate() {+ for (const page of this.pages.values()) {+ try {+ this.check(page);+ } catch {+ this.close(page);+ }+ }+ }+ private cancelDirectory(page: Page) {+ if (!page.directory) return;+ clearTimeout(page.directory.timer);+ page.directory.answer(null);+ page.directory = undefined;+ }+ captureSource(pageId: unknown, pluginId: string): () => boolean {+ if (typeof pageId !== 'string') return fail();+ const page = this.pages.get(pageId);+ if (!page || page.plugin !== pluginId || !page.active || page.sourceHidden) return fail();+ this.check(page);+ return () => {+ try {+ this.page(pageId, page.controller);+ return page.active && !page.sourceHidden;+ } catch {+ return false;+ }+ };+ }+ async chooseDirectory(+ pageId: string,+ pluginId: string,+ purpose: string | null,+ ): Promise<string | null> {+ const current = this.captureSource(pageId, pluginId),+ page = this.pages.get(pageId)!;+ if (!current() || page.directory || !this.deps.validateDirectory) return fail();+ const ghost = this.check(page),+ id = randomUUID();+ return new Promise((resolve) => {+ const timer = setTimeout(() => this.cancelDirectory(page), 90_000);+ page.directory = {+ timer,+ answer: resolve,+ answering: false,+ value: {+ id,+ pluginId,+ ghostName: ghost.manifest.name,+ purpose,+ expiresAt: this.now() + 90_000,+ },+ };+ });+ }+ present(+ pageId: string,+ pluginId: string,+ intent:+ | { kind: 'task'; taskId: string }+ | { kind: 'preview'; url: string }+ | { kind: 'schedule'; name: string; prompt: string; intervalMs?: number }+ | { kind: 'simulator' }+ | { kind: 'media'; path: string; mediaKind: 'image' | 'video' },+ ): boolean {+ try {+ if (!this.captureSource(pageId, pluginId)()) return false;+ const page = this.pages.get(pageId)!,+ ghost = this.check(page);+ if ((page.intents?.length ?? 0) >= 8) return false;+ (page.intents ??= []).push({+ ...intent,+ id: randomUUID(),+ pluginId,+ ghostName: ghost.manifest.name,+ });+ return true;+ } catch {+ return false;+ }+ }+ notify(pageId: string, pluginId: string, text: string): boolean {+ this.sweep();+ const page = this.pages.get(pageId);+ if (+ !page ||+ !page.active ||+ page.sourceHidden ||+ page.plugin !== pluginId ||+ !page.currentOwner()+ )+ return false;+ try {+ this.check(page);+ } catch {+ return false;+ }+ page.notices.push({ id: randomUUID(), text });+ if (page.notices.length > 16) page.notices.shift();+ return true;+ }+ assertInteraction(pageId: unknown, pluginId: string, controllerId: string) {+ const page = this.page(pageId, controllerId);+ if (+ page.plugin !== pluginId ||+ page.surface !== 'interaction' ||+ !page.active ||+ page.sourceHidden+ )+ return fail();+ }+ private sweep() {+ for (const page of this.pages.values()) {+ if (+ !page.currentOwner() ||+ !page.currentController() ||+ this.now() - page.touchedAt > 120_000+ )+ this.close(page);+ }+ }+ /** Explicit page context supplied by a plugin handling that page's business request.+ * A missing/invalid context never falls back to a different phone. */+ async confirm(pageId: string, params: GhostConfirmShowParams): Promise<boolean> {+ const page = this.pages.get(pageId);+ if (!page || !page.active || page.sourceHidden || page.plugin !== params.ghostId) return fail();+ this.check(page);+ if (this.now() - page.touchedAt > 120_000 || page.confirms.size) return fail();+ const id = randomUUID();+ return new Promise<boolean>((resolve) => {+ const timer = setTimeout(() => {+ page.confirms.delete(id);+ resolve(false);+ }, 90_000);+ page.confirms.set(id, {+ timer,+ answer: resolve,+ value: {+ id,+ pluginId: params.ghostId,+ title: params.ghostName,+ body: params.body,+ confirmText: params.confirmText,+ cancelText: params.cancelText,+ danger: params.danger,+ expiresAt: this.now() + 90_000,+ },+ });+ });+ }+ private item(ghost: InstalledGhost): RemoteCollectionItem {+ const m = ghost.manifest;+ const mobile = parsePluginMobileDeclaration(m.mobile);+ const unread = ghost.enabled ? this.deps.unread(m.id) : null;+ return {+ ref: { collectionId: PLUGIN_COLLECTION, kind: 'plugin', id: m.id },+ revision: this.deps.revision(ghost),+ display: {+ title: m.name,+ subtitle: m.description ?? '',+ preview: unread?.summary,+ ...(unread+ ? { timestamp: unread.at, badges: [{ accessibilityLabel: 'Unread', tone: 'positive' }] }+ : {}),+ ...(ghost.iconDataUrl+ ? {+ avatar: { kind: 'asset', value: ghost.iconDataUrl, fallbackText: m.name.slice(0, 1) },+ }+ : {}),+ status: { label: ghost.enabled ? 'enabled' : 'disabled', tone: 'neutral' },+ },+ links: [],+ actions: [+ ...(['panel', 'mainView', 'settings'] as const).flatMap((surface) => {+ const declared =+ surface === 'panel'+ ? m.panel?.html+ : surface === 'mainView'+ ? m.mainView?.html+ : m.settingsHtml;+ const entry = declared ? (mobile?.[surface] ?? declared) : undefined;+ return mobile && entry+ ? [{ id: `open:${surface}`, label: surface, disabled: !ghost.enabled }]+ : [];+ }),+ { id: ghost.enabled ? 'disable' : 'enable', label: ghost.enabled ? 'Disable' : 'Enable' },+ ],+ };+ }+ provider(): RemoteResourceProvider {+ return {+ collection: {+ id: PLUGIN_COLLECTION,+ resourceKind: 'plugin',+ title: { fallback: 'Plugins', translations: { 'zh-CN': '插件' } },+ icon: { name: 'puzzle', fallbackText: 'P' },+ },+ list: async (_ctx, request) => {+ this.sweep();+ const q = request.query?.toLocaleLowerCase();+ const items = this.deps+ .list()+ .filter(+ (g) =>+ !q ||+ `${g.manifest.name} ${g.manifest.description ?? ''}`.toLocaleLowerCase().includes(q),+ )+ .map((g) => this.item(g));+ return {+ collectionId: PLUGIN_COLLECTION,+ revision: createHash('sha256').update(JSON.stringify(items)).digest('hex'),+ items,+ };+ },+ get: async (_ctx, request) => {+ const ghost = this.ghost(request.ref.id);+ const item = this.item(ghost);+ return {+ ...item,+ blocks: [+ {+ id: 'about',+ primitive: 'markdown',+ fallbackMarkdown: ghost.manifest.description ?? '',+ },+ { id: 'version', primitive: 'status', fallbackMarkdown: ghost.manifest.version },+ {+ id: 'capabilities',+ primitive: 'plugin-capabilities',+ fallbackMarkdown: '',+ data: {+ tools:+ ghost.manifest.tools?.map((tool) => ({+ name: tool.name,+ description: tool.description,+ })) ?? [],+ tasks: Boolean(ghost.manifest.agent?.tasks || ghost.manifest.agent?.errand),+ mobile: parsePluginMobileDeclaration(ghost.manifest.mobile) !== null,+ },+ },+ ],+ };+ },+ invoke: async (context, request) => {+ this.sweep();+ const input = record(request.input);+ const id = request.resourceRef?.id;+ if (!id) return fail();+ if (request.actionId === 'task-settings:get' || request.actionId === 'task-settings:set') {+ const ghost = this.ghost(id),+ settings = this.deps.taskSettings;+ if (+ !settings ||+ !ghost.enabled ||+ !(ghost.manifest.agent?.tasks || ghost.manifest.agent?.errand)+ )+ return fail();+ const revision = this.deps.revision(ghost),+ owner = this.deps.captureOwner(),+ peer = this.deps.captureController(context.controllerDeviceId);+ const assertCurrent = () => {+ const current = this.ghost(id);+ if (!owner() || !peer() || !current.enabled || this.deps.revision(current) !== revision)+ return fail();+ };+ assertCurrent();+ const result =+ request.actionId === 'task-settings:get'+ ? settings.read(id, revision)+ : await settings.update(id, revision, input, assertCurrent);+ assertCurrent();+ return { effects: [], result };+ }+ if (request.actionId === 'open-interaction') {+ const ghost = this.ghost(id);+ if (!ghost.enabled || !ghost.manifest.card || this.pages.size >= 32) return fail();+ const page: Page = {+ id: randomUUID(),+ plugin: id,+ controller: context.controllerDeviceId,+ revision: this.deps.revision(ghost),+ currentOwner: this.deps.captureOwner(),+ currentController: this.deps.captureController(context.controllerDeviceId),+ surface: 'interaction',+ active: true,+ touchedAt: this.now(),+ files: [],+ confirms: new Map(),+ notices: [],+ answered: new Map(),+ };+ this.pages.set(page.id, page);+ return { effects: [], result: { pageId: page.id } };+ }+ if (request.actionId === 'enable' || request.actionId === 'disable') {+ const valid = this.deps.captureOwner();+ this.ghost(id);+ await this.deps.setEnabled(id, request.actionId === 'enable');+ if (!valid()) return fail();+ if (request.actionId === 'disable')+ for (const page of this.pages.values()) if (page.plugin === id) this.close(page);+ return { effects: [{ kind: 'refresh-collection', collectionId: PLUGIN_COLLECTION }] };+ }+ if (request.actionId.startsWith('open:')) {+ const surface = request.actionId.slice(5);+ if (!isPluginPageSurface(surface)) return fail();+ const ghost = this.ghost(id),+ mobile = parsePluginMobileDeclaration(ghost.manifest.mobile);+ const declared =+ surface === 'panel'+ ? ghost.manifest.panel?.html+ : surface === 'mainView'+ ? ghost.manifest.mainView?.html+ : ghost.manifest.settingsHtml;+ const entry = declared ? (mobile?.[surface] ?? declared) : undefined;+ if (!ghost.enabled || !mobile || !entry) return fail('Plugin has no mobile page');+ if (this.pages.size >= 32)+ throw new RemoteResourceRegistryError('INTERNAL', 'Too many open plugin pages');+ const page: Page = {+ id: randomUUID(),+ plugin: id,+ controller: context.controllerDeviceId,+ revision: this.deps.revision(ghost),+ currentOwner: this.deps.captureOwner(),+ currentController: this.deps.captureController(context.controllerDeviceId),+ surface,+ active: true,+ touchedAt: this.now(),+ unreadAt: this.deps.unread(id)?.at,+ files: [],+ confirms: new Map(),+ notices: [],+ answered: new Map(),+ };+ const files = await this.deps.bundle(ghost, entry);+ this.check(page);+ page.files = files;+ try {+ await this.deps.connect(ghost, page.id, mobile.channels);+ this.check(page);+ } catch (error) {+ this.close(page);+ throw error;+ }+ this.pages.set(page.id, page);+ const result: PluginPageDocument = {+ pageId: page.id,+ pluginId: id,+ title: ghost.manifest.name,+ surface,+ entry,+ channels: mobile.channels,+ files,+ unreadAt: page.unreadAt,+ };+ return { effects: [], result };+ }+ const page = this.page(input.pageId, context.controllerDeviceId);+ if (page.plugin !== id) return fail();+ const ghost = this.check(page);+ switch (request.actionId) {+ case 'asset': {+ const file = page.files.find((f) => f.path === input.path);+ if (+ !file ||+ !Number.isSafeInteger(input.offset) ||+ (input.offset as number) < 0 ||+ (input.offset as number) > file.size+ )+ return fail();+ const result = await this.deps.asset(ghost, file, input.offset as number);+ this.check(page);+ return { effects: [], result };+ }+ case 'suspend': {+ page.active = false;+ // Suspension removes native intents; their cover must not survive resume.+ page.sourceHidden = false;+ this.cancelDirectory(page);+ page.intents = [];+ page.previews?.clear();+ for (const pending of page.confirms.values()) {+ clearTimeout(pending.timer);+ pending.answer(false);+ }+ page.confirms.clear();+ page.notices.length = 0;+ return { effects: [] };+ }+ case 'close':+ this.close(page);+ return { effects: [] };+ case 'seen': {+ if (!page.active || page.sourceHidden) return fail();+ if (+ !page.active ||+ page.surface !== 'panel' ||+ typeof input.seenAt !== 'number' ||+ input.seenAt !== page.unreadAt+ )+ return fail();+ this.deps.clearUnread(id, input.seenAt);+ return { effects: [] };+ }+ case 'post': {+ if (!page.active || page.sourceHidden) return fail();+ if (page.surface === 'interaction') return fail();+ const mobile = parsePluginMobileDeclaration(ghost.manifest.mobile);+ if (+ typeof input.channel !== 'string' ||+ !mobile?.channels.includes(input.channel) ||+ Buffer.byteLength(JSON.stringify(input.data) ?? '') > PLUGIN_PAGE_MAX_MESSAGE_BYTES+ )+ return fail();+ await this.deps.post(ghost, page.id, input.channel, input.data);+ this.check(page);+ return { effects: [] };+ }+ case 'poll': {+ page.active = true;+ if (!Number.isSafeInteger(input.after) || (input.after as number) < 0) return fail();+ const events =+ page.surface === 'interaction'+ ? []+ : await this.deps.poll(ghost, page.id, input.after as number);+ this.check(page);+ page.unreadAt = this.deps.unread(id)?.at;+ const result: PluginPagePoll = {+ events,+ confirms: [...page.confirms.values()].map((p) => p.value),+ notifications: page.notices.splice(0),+ unreadAt: page.unreadAt,+ directories: page.directory ? [page.directory.value] : [],+ intents: page.intents ?? [],+ };+ return { effects: [], result };+ }+ case 'cover': {+ if (typeof input.hidden !== 'boolean' || !page.active) return fail();+ page.sourceHidden = input.hidden;+ if (input.hidden) {+ for (const pending of page.confirms.values()) {+ clearTimeout(pending.timer);+ pending.answer(false);+ }+ page.confirms.clear();+ }+ return { effects: [] };+ }+ case 'media:open': {+ if (+ !page.active ||+ page.sourceHidden ||+ !this.deps.resolveMedia ||+ typeof input.url !== 'string'+ )+ return fail();+ const current = this.captureSource(page.id, id);+ const media = await this.deps.resolveMedia(id, input.url, current);+ if (!current() || !media) return fail();+ this.present(page.id, id, { kind: 'media', ...media });+ return { effects: [] };+ }+ case 'preview:fetch': {+ if (!page.active || !this.deps.fetchPreview || typeof input.intentId !== 'string')+ return fail();+ const intent = page.intents?.find(+ (item) => item.id === input.intentId && item.kind === 'preview',+ );+ if (!intent || intent.kind !== 'preview') return fail();+ page.previews ??= new Map();+ let preview = page.previews.get(intent.id);+ if (!preview) {+ preview = new MobilePluginPreview(intent.url, this.deps.fetchPreview);+ page.previews.set(intent.id, preview);+ }+ const result = await preview.fetch(ghost, input, () => {+ this.check(page);+ if (!page.active || !page.intents?.some((item) => item.id === intent.id))+ return fail();+ });+ return { effects: [], result };+ }+ case 'intent:ack': {+ if (!page.active || typeof input.intentId !== 'string') return fail();+ // Receipt acknowledgement only; it never claims that a task or automation was created.+ page.intents = page.intents?.filter((intent) => intent.id !== input.intentId);+ page.previews?.delete(input.intentId);+ return { effects: [] };+ }+ case 'answer-directory': {+ if (+ !page.active ||+ typeof input.requestId !== 'string' ||+ !(+ input.path === null ||+ (typeof input.path === 'string' &&+ input.path.length > 0 &&+ input.path.length <= 4096)+ )+ )+ return fail();+ const receipt = createHash('sha256').update(JSON.stringify(input.path)).digest('hex');+ const previous = page.directoryAnswers?.get(input.requestId);+ if (previous) {+ if (previous !== receipt) return fail();+ return { effects: [] };+ }+ const pending = page.directory;+ if (+ !pending ||+ pending.value.id !== input.requestId ||+ pending.answering ||+ pending.value.expiresAt <= this.now()+ )+ return fail();+ pending.answering = true;+ try {+ const path =+ input.path === null+ ? null+ : await this.deps.validateDirectory!(input.path as string);+ this.check(page);+ if (+ !page.active ||+ page.directory !== pending ||+ pending.value.expiresAt <= this.now()+ )+ return fail();+ clearTimeout(pending.timer);+ page.directory = undefined;+ page.directoryAnswers ??= new Map();+ page.directoryAnswers.set(input.requestId, receipt);+ if (page.directoryAnswers.size > 32)+ page.directoryAnswers.delete(page.directoryAnswers.keys().next().value!);+ pending.answer(path);+ return { effects: [] };+ } finally {+ pending.answering = false;+ }+ }+ case 'answer': {+ const pending =+ typeof input.confirmId === 'string' ? page.confirms.get(input.confirmId) : null;+ if (+ !pending &&+ typeof input.confirmId === 'string' &&+ typeof input.confirmed === 'boolean' &&+ page.answered.get(input.confirmId) === input.confirmed+ )+ return { effects: [] };+ if (+ !pending ||+ typeof input.confirmed !== 'boolean' ||+ pending.value.expiresAt <= this.now()+ )+ return fail();+ page.confirms.delete(pending.value.id);+ clearTimeout(pending.timer);+ page.answered.set(pending.value.id, input.confirmed);+ if (page.answered.size > 32) page.answered.delete(page.answered.keys().next().value!);+ pending.answer(input.confirmed);+ return { effects: [] };+ }+ case 'fetch': {+ if (page.surface === 'interaction') return fail();+ if (+ typeof input.path !== 'string' ||+ !input.path.startsWith('/') ||+ input.path.startsWith('//') ||+ input.path.length > 2048+ )+ return fail();+ const url = new URL(input.path, 'https://plugin.invalid');+ // Credentials/configuration executors use their dedicated trusted UI, never this page transport.+ const method = input.method ?? 'GET';+ if (method !== 'GET' && (!page.active || page.sourceHidden)) return fail();+ if (+ method !== 'GET' &&+ !(url.pathname === '/kv' && (method === 'PUT' || method === 'POST'))+ )+ return fail();+ const file = /^\/(?:library|media)\/[^/]/.test(url.pathname);+ if (+ !file &&+ !/^\/(?:kv|app-context|agent-models|media-models|gallery)$/.test(url.pathname)+ )+ return fail();+ if (+ input.offset !== undefined &&+ (!file ||+ method !== 'GET' ||+ !Number.isSafeInteger(input.offset) ||+ (input.offset as number) < 0)+ )+ return fail();+ if (+ input.revision !== undefined &&+ (typeof input.revision !== 'string' || input.revision.length > 128)+ )+ return fail();+ if (+ url.pathname.startsWith('/library/') &&+ Number(input.offset) > 0 &&+ typeof input.revision !== 'string'+ )+ return fail();+ if (+ input.body !== undefined &&+ (typeof input.body !== 'string' || input.body.length > 32_000)+ )+ return fail();+ const result = await this.deps.fetch(+ ghost,+ url.pathname + url.search,+ method as string,+ input.body as string | undefined,+ input.offset as number | undefined,+ input.revision as string | undefined,+ );+ this.check(page);+ return { effects: [], result };+ }+ default:+ return fail();+ }+ },+ };+ }+}diff --git a/apps/desktop/src/main/cindy-brain/mobilePreview.ts b/apps/desktop/src/main/cindy-brain/mobilePreview.tsnew file mode 100644index 0000000000..07f64ae8f8--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/mobilePreview.ts@@ -0,0 +1,147 @@+import { Agent, fetch as undiciFetch } from 'undici';+import { randomUUID } from 'node:crypto';+import { ghostPreviewUrlAllowed, type InstalledGhost } from '../../shared/ghost.js';+import type { PluginPageFetchResult } from '@cindy/device-link';++export type MobilePreviewReader = (+ url: string,+ assertCurrent: () => void,+) => Promise<{ status: number; mime: string; bytes: Uint8Array }>;+/** One approved preview origin, bounded immutable response chunks, no cookies or arbitrary URL proxy. */+export class MobilePluginPreview {+ private readonly responses = new Map<+ string,+ { id: string; status: number; mime: string; bytes: Uint8Array }+ >();+ private readonly pending = new Map<string, Promise<void>>();+ private totalBytes = 0;+ constructor(+ private readonly entry: string,+ private readonly read: MobilePreviewReader,+ ) {}+ async fetch(+ ghost: InstalledGhost,+ input: Record<string, unknown>,+ assertCurrent: () => void,+ ): Promise<PluginPageFetchResult> {+ assertCurrent();+ if (+ typeof input.url !== 'string' ||+ input.url.length > 4096 ||+ !Number.isSafeInteger(input.offset) ||+ (input.offset as number) < 0+ )+ throw new Error('INVALID_PREVIEW_REQUEST');+ const url = new URL(input.url),+ entry = new URL(this.entry);+ if (+ url.origin !== entry.origin ||+ url.username ||+ url.password ||+ url.hash ||+ !ghostPreviewUrlAllowed(ghost.manifest, url.href)+ )+ throw new Error('PREVIEW_ORIGIN_DENIED');+ const offset = input.offset as number;+ if (offset === 0 && input.revision === undefined && !this.responses.has(url.href)) {+ let work = this.pending.get(url.href);+ if (!work) {+ if (this.pending.size >= 4 || this.responses.size + this.pending.size >= 128)+ throw new Error('PREVIEW_BUSY');+ work = (async () => {+ const response = await this.read(url.href, assertCurrent);+ assertCurrent();+ if (+ response.bytes.byteLength > 8 * 1024 * 1024 ||+ this.totalBytes + response.bytes.byteLength > 64 * 1024 * 1024+ )+ throw new Error('PREVIEW_TOO_LARGE');+ this.responses.set(url.href, { ...response, id: randomUUID() });+ this.totalBytes += response.bytes.byteLength;+ })();+ this.pending.set(url.href, work);+ }+ try {+ await work;+ } finally {+ if (this.pending.get(url.href) === work) this.pending.delete(url.href);+ }+ }+ assertCurrent();+ const response = this.responses.get(url.href);+ if (+ !response ||+ (offset > 0 && input.revision !== response.id) ||+ (input.revision !== undefined && input.revision !== response.id) ||+ offset > response.bytes.byteLength+ )+ throw new Error('PREVIEW_CHANGED');+ const end = Math.min(offset + 48 * 1024, response.bytes.byteLength);+ return {+ mime: response.mime,+ status: response.status,+ base64: Buffer.from(response.bytes.subarray(offset, end)).toString('base64'),+ revision: response.id,+ ...(end < response.bytes.byteLength ? { nextOffset: end } : {}),+ };+ }+}++const directAgent = new Agent();+const directFetch: typeof fetch = (url, init) =>+ undiciFetch(String(url), { ...init, dispatcher: directAgent } as Parameters<+ typeof undiciFetch+ >[1]) as unknown as Promise<Response>;++/** Fetch redirects only within the same approved origin, and never inherit computer browser credentials. */+export async function readMobilePreview(+ url: string,+ assertCurrent: () => void,+ fetcher: typeof fetch = directFetch,+) {+ const origin = new URL(url).origin;+ for (let hop = 0; hop < 5; hop++) {+ assertCurrent();+ const response = await fetcher(url, {+ redirect: 'manual',+ credentials: 'omit',+ signal: AbortSignal.timeout(30_000),+ });+ assertCurrent();+ if (response.status >= 300 && response.status < 400 && response.headers.get('location')) {+ await response.body?.cancel();+ const next = new URL(response.headers.get('location')!, url);+ if (next.origin !== origin || next.username || next.password)+ throw new Error('PREVIEW_ORIGIN_DENIED');+ url = next.href;+ continue;+ }+ const reader = response.body?.getReader(),+ parts: Uint8Array[] = [];+ let size = 0;+ try {+ while (reader) {+ const part = await reader.read();+ assertCurrent();+ if (part.done) break;+ size += part.value.byteLength;+ if (size > 8 * 1024 * 1024) throw new Error('PREVIEW_TOO_LARGE');+ parts.push(part.value);+ }+ } finally {+ await reader?.cancel().catch(() => {});+ }+ const bytes = new Uint8Array(size);+ let offset = 0;+ for (const part of parts) {+ bytes.set(part, offset);+ offset += part.length;+ }+ return {+ status: response.status,+ mime: response.headers.get('content-type')?.split(';')[0] ?? 'application/octet-stream',+ bytes,+ };+ }+ throw new Error('PREVIEW_REDIRECT_LIMIT');+}diff --git a/apps/desktop/src/main/cindy-brain/mobileTaskSettings.ts b/apps/desktop/src/main/cindy-brain/mobileTaskSettings.tsnew file mode 100644index 0000000000..50c66fb460--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/mobileTaskSettings.ts@@ -0,0 +1,109 @@+import { createHash } from 'node:crypto';+import {+ connectedProvidersForAgent,+ isModelSelectableForNewRoute,+ type ProviderView,+} from '@cindy/model-providers';+import { GHOST_ERRAND_PERMISSION_MODES } from '../../shared/ghost.js';+import { PLUGIN_TASK_EFFORTS, type PluginTaskConfig } from './pluginTaskPrefsStore.js';+import type { PluginTaskPreferences } from '@cindy/device-link';++/** Host-owned task overrides. Never called from a plugin page's generic fetch/relay. */+export class MobileTaskSettings {+ constructor(+ private readonly deps: {+ read(id: string): PluginTaskConfig;+ write(id: string, value: PluginTaskConfig): PluginTaskConfig;+ validate(config: PluginTaskConfig): Promise<void>;+ providers(): Promise<ProviderView[]>;+ agents(): Promise<readonly string[]>;+ },+ ) {}+ read(id: string, installRevision: string): PluginTaskPreferences {+ const { workingDir: _privatePath, ...config } = this.deps.read(id);+ return {+ revision: this.revision(id, installRevision),+ config,+ permissionModes: [...GHOST_ERRAND_PERMISSION_MODES],+ defaultPermissionMode: 'ask',+ };+ }+ private revision(id: string, installation: string) {+ return createHash('sha256')+ .update(JSON.stringify([installation, this.deps.read(id)]))+ .digest('hex');+ }+ async update(+ id: string,+ installation: string,+ input: Record<string, unknown>,+ assertCurrent: () => void,+ ) {+ assertCurrent();+ const checkRevision = () => {+ assertCurrent();+ if (input.expectedRevision !== this.revision(id, installation))+ throw new Error('PLUGIN_SETTINGS_CHANGED');+ };+ checkRevision();+ // A narrow patch preserves the desktop-selected directory and other independent settings.+ const current = this.deps.read(id),+ next = { ...current };+ if (input.model === null) {+ for (const key of ['agentKind', 'providerId', 'model', 'effort', 'fastMode'] as const)+ delete next[key];+ } else if (input.model !== undefined) {+ if (!input.model || typeof input.model !== 'object' || Array.isArray(input.model))+ throw new Error('PLUGIN_SETTINGS_INVALID');+ const v = input.model as Record<string, unknown>;+ if (+ Object.keys(v).some(+ (k) => !['agentKind', 'providerId', 'model', 'effort', 'fastMode'].includes(k),+ ) ||+ !['cc', 'codex', 'pi'].includes(v.agentKind as string) ||+ typeof v.providerId !== 'string' ||+ typeof v.model !== 'string' ||+ !v.model ||+ v.model.length > 128 ||+ !v.providerId ||+ v.providerId.length > 128 ||+ (v.effort !== undefined &&+ !(PLUGIN_TASK_EFFORTS as readonly unknown[]).includes(v.effort)) ||+ typeof v.fastMode !== 'boolean'+ )+ throw new Error('PLUGIN_SETTINGS_INVALID');+ const agent = v.agentKind === 'cc' ? 'claude-code' : (v.agentKind as 'codex' | 'pi');+ if (!(await this.deps.agents()).includes(agent)) throw new Error('PLUGIN_MODEL_UNAVAILABLE');+ const views = await this.deps.providers();+ checkRevision();+ const provider = connectedProvidersForAgent(views, agent).find((p) => p.id === v.providerId);+ const model = provider?.models[agent]?.find((m) => m.id === v.model);+ if (+ !provider ||+ !model ||+ !isModelSelectableForNewRoute(model, { userProvider: provider.source === 'user' }) ||+ (v.effort !== undefined && !model.efforts.includes(v.effort as never)) ||+ (v.fastMode && model.supportsFastMode !== true)+ )+ throw new Error('PLUGIN_MODEL_UNAVAILABLE');+ next.agentKind = v.agentKind as PluginTaskConfig['agentKind'];+ next.providerId = provider.id;+ next.model = model.id;+ // The store owns its supported effort vocabulary. Empty effort means no explicit override.+ if (v.effort === undefined) delete next.effort;+ else next.effort = v.effort as PluginTaskConfig['effort'];+ next.fastMode = v.fastMode;+ }+ if (input.permissionMode === null) delete next.permissionMode;+ else if (input.permissionMode !== undefined) {+ if (!(GHOST_ERRAND_PERMISSION_MODES as readonly unknown[]).includes(input.permissionMode))+ throw new Error('PLUGIN_SETTINGS_INVALID');+ next.permissionMode = input.permissionMode as PluginTaskConfig['permissionMode'];+ }+ checkRevision();+ await this.deps.validate(next);+ checkRevision();+ this.deps.write(id, next);+ return this.read(id, installation);+ }+}diff --git a/apps/desktop/src/main/cindy-brain/notifySlot.ts b/apps/desktop/src/main/cindy-brain/notifySlot.tsindex 8240711f40..170883f962 100644--- a/apps/desktop/src/main/cindy-brain/notifySlot.ts+++ b/apps/desktop/src/main/cindy-brain/notifySlot.ts@@ -40,6 +40,7 @@ export interface NotifySlotDeps {getGhost(id: string): InstalledGhost | null;/** 把提示推给全部宿主窗口(renderer 走统一 Toast 体系渲染)。 */broadcast(payload: GhostNotifyPush): void;+ deliverMobile?(pageId: string, payload: GhostNotifyPush): boolean;now?(): number;log?: {info: (msg: string, meta?: Record<string, unknown>) => void;@@ -69,7 +70,8 @@ export class GhostNotifySlot {/** 处理一条 notify(ghost-pipe:send 的 invoke 返回值即本结果)。 */handleNotify(ghostId: string, payload: unknown): GhostPipeNotifyResult {- const p = payload as { text?: unknown; tone?: unknown };+ const p = payload as { text?: unknown; tone?: unknown; mobilePageId?: unknown };+ if (p?.mobilePageId !== undefined && (typeof p.mobilePageId !== 'string' || !/^[a-f0-9-]{36}$/.test(p.mobilePageId))) return { ok: false, message: 'Invalid mobile page context' };const ghost = this.deps.getGhost(ghostId);if (!ghost || !ghost.enabled) {@@ -107,15 +109,17 @@ export class GhostNotifySlot {message: `提示过于频繁(同一意识最小间隔 ${GHOST_NOTIFY_MIN_INTERVAL_MS / 1000} 秒),本条已丢弃`,};}- this.lastSentAt.set(ghostId, now);-- this.deps.broadcast({+ const notice: GhostNotifyPush = {ghostId,name: ghost.manifest.name,...(ghost.iconDataUrl ? { iconDataUrl: ghost.iconDataUrl } : {}),text,tone,- });+ };+ if (typeof p.mobilePageId === 'string') {+ if (!this.deps.deliverMobile?.(p.mobilePageId, notice)) return { ok: false, message: 'Mobile page is no longer available' };+ } else this.deps.broadcast(notice);+ this.lastSentAt.set(ghostId, now);this.deps.log?.info('ghost notify shown', { ghostId, tone, chars: text.length });return { ok: true };}diff --git a/apps/desktop/src/main/cindy-brain/pickSlot.ts b/apps/desktop/src/main/cindy-brain/pickSlot.tsindex d57b37cecd..363a9ec4c5 100644--- a/apps/desktop/src/main/cindy-brain/pickSlot.ts+++ b/apps/desktop/src/main/cindy-brain/pickSlot.ts@@ -39,7 +39,7 @@ export interface PickSlotDeps {* 弹系统级选文件夹窗口;返回所选绝对路径,取消返回 null。* 找不到可挂靠的 Cindy 窗口时应 reject(失败关闭,不弹无主对话框)。*/- showDirectoryDialog(params: { ghostName: string; purpose: string | null }): Promise<string | null>;+ showDirectoryDialog(params: { ghostName: string; purpose: string | null; ghostId: string; mobilePageId?: string }): Promise<string | null>;/** 签发目录过户票据(dirDeposit.deposit,userGranted 语义 = 用户已亲手选中)。 */depositDir(ghostId: string,@@ -73,7 +73,7 @@ export class GhostPickSlot {constructor(private readonly deps: PickSlotDeps) {}- async handleRequest(ghostId: string, payload: unknown): Promise<GhostPipePickResult> {+ async handleRequest(ghostId: string, payload: unknown, shouldContinue: () => boolean = () => true): Promise<GhostPipePickResult> {const ghost = this.deps.getGhost(ghostId);if (!ghost?.enabled || ghost.manifest.pick !== true) {return fail('PERMISSION_DENIED', '插件未申请目录选择权限(pick),或当前未启用');@@ -82,6 +82,7 @@ export class GhostPickSlot {return fail('INVALID_REQUEST', 'pick-request 载荷必须是对象');}const request = payload as Record<string, unknown>;+ if (request.mobilePageId !== undefined && (typeof request.mobilePageId !== 'string' || request.mobilePageId.length > 128)) return fail('INVALID_REQUEST', 'Invalid mobile page context');if (request.mode !== 'directory') {return fail('INVALID_REQUEST', 'mode 目前只支持 "directory"');}@@ -121,6 +122,8 @@ export class GhostPickSlot {picked = await this.deps.showDirectoryDialog({ghostName: ghost.manifest.name,purpose,+ ghostId,+ ...(typeof request.mobilePageId === 'string' ? { mobilePageId: request.mobilePageId } : {}),});} catch (error) {this.deps.log?.warn('ghost pick dialog failed', {@@ -131,6 +134,7 @@ export class GhostPickSlot {} finally {this.dialogInFlight = false;}+ if (!shouldContinue()) return fail('CANCELLED', 'The originating page has closed.');if (picked === null) {return fail('CANCELLED', '用户取消了选择');}diff --git a/apps/desktop/src/main/cindy-brain/previewSlot.ts b/apps/desktop/src/main/cindy-brain/previewSlot.tsindex 334ba79796..d1d0fb4351 100644--- a/apps/desktop/src/main/cindy-brain/previewSlot.ts+++ b/apps/desktop/src/main/cindy-brain/previewSlot.ts@@ -43,6 +43,7 @@ export interface PreviewSlotDeps {getGhost(id: string): InstalledGhost | null;/** 把开页请求推给宿主窗口;false = 一个窗口都不在(HOST_NOT_READY)。 */broadcast(payload: GhostPreviewOpenPush): boolean;+ openMobile?(pageId: string, ghostId: string, url: string): boolean;/** 台前会话快照(请求缺省 sessionId 时的落点;非会话页为 null)。 */focusedSessionId(): string | null;now?(): number;@@ -78,6 +79,7 @@ export class GhostPreviewSlot {return fail('INVALID_REQUEST', 'preview-request 载荷必须是对象');}const request = payload as Record<string, unknown>;+ if (request.mobilePageId !== undefined && (typeof request.mobilePageId !== 'string' || request.mobilePageId.length > 128)) return fail('INVALID_REQUEST', 'Invalid mobile page context');if (typeof request.url !== 'string' || request.url.length === 0) {return fail('INVALID_REQUEST', 'url 必填且必须是字符串');}@@ -101,6 +103,10 @@ export class GhostPreviewSlot {return fail('RATE_LIMITED', '预览打开请求太频繁,稍后再试');}+ if (typeof request.mobilePageId === 'string') {+ return this.deps.openMobile?.(request.mobilePageId, ghostId, request.url)+ ? { ok: true } : fail('HOST_NOT_READY', 'The originating mobile page is unavailable');+ }// 落点会话:显式 sessionId 优先(通常来自 session-context 注入),缺省// 落台前会话;两者皆无(用户不在会话页)= 没有可开标签的家,如实拒。const sessionId =diff --git a/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts b/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.tsindex 9ddebc453a..a86ab8b6ea 100644--- a/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts+++ b/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts@@ -1,5 +1,6 @@import { BrowserWindow, session, webContents, type CustomScheme } from 'electron';import fs from 'node:fs/promises';+import { createHash } from 'node:crypto';import * as nodeFs from 'node:fs';import { Readable } from 'node:stream';import path from 'node:path';@@ -25,6 +26,7 @@ import {listGhostGallery as listGhostGalleryFromLedger,} from '../../cindy-media/ledger.js';import type { SandboxHandle, SandboxHostAdapter } from './GhostRuntime.js';+import { mobilePageRelayScript, type MobileRelayOperation } from './mobilePageRelay.js';/*** Electron 沙箱宿主(docs/dev-rules/plugin-security-and-authoring.md):@@ -108,6 +110,80 @@ export function sendToGhostLogic(ghostId: string, payload: unknown): boolean {return false;}+/** The remote page uses the same owner partition and running logic as desktop. */+export async function invokeGhostMobileRelay(ghostId: string, operation: MobileRelayOperation): Promise<unknown> {+ const partition = ownerScopedGhostPartition(ghostId, getActiveAppSession());+ if (!partition) throw new Error('PLUGIN_PAGE_UNAVAILABLE');+ const ownerSession = session.fromPartition(partition);+ for (const [id, plugin] of logicWebContentsToGhost) {+ if (plugin !== ghostId) continue;+ const wc = webContents.fromId(id);+ if (wc && !wc.isDestroyed() && wc.session === ownerSession) {+ return wc.executeJavaScript(mobilePageRelayScript(operation));+ }+ }+ throw new Error('PLUGIN_PAGE_UNAVAILABLE');+}++export async function fetchGhostMobilePage(ghost: InstalledGhost, pathname: string, method: string, body?: string, offset = 0, expectedRevision?: string) {+ const partition = ownerScopedGhostPartition(ghost.manifest.id, getActiveAppSession());+ if (!partition) throw new Error('PLUGIN_PAGE_UNAVAILABLE');+ // Read only the requested immutable blob chunk. The desktop protocol buffers+ // the whole file, which would repeat that work for every remote video chunk.+ if (pathname.startsWith('/media/')) {+ const match = /^\/media\/([a-f0-9]{64})(\.[a-z0-9]+)$/.exec(pathname);+ const missing = { status: 404, mime: 'application/octet-stream', base64: '' };+ if (!match || method !== 'GET' || !Number.isSafeInteger(offset) || offset < 0) return missing;+ if (!(await ghostCanReadMedia(match[1], ghost.manifest.id))) return missing;+ let resolved: { absPath: string; mimeType: string };+ try { resolved = resolveBlobHashRef(match[1], match[2]); } catch { return missing; }+ const handle = await fs.open(resolved.absPath, nodeFs.constants.O_RDONLY | nodeFs.constants.O_NOFOLLOW);+ try {+ const stat = await handle.stat();+ if (!stat.isFile() || offset > stat.size) return missing;+ const data = Buffer.alloc(Math.min(49_152, stat.size - offset));+ const { bytesRead } = await handle.read(data, 0, data.length, offset);+ if (bytesRead !== data.length) throw new Error('PLUGIN_MEDIA_CHANGED');+ return { status: 200, mime: resolved.mimeType, base64: data.toString('base64'), revision: match[1],+ ...(offset + bytesRead < stat.size ? { nextOffset: offset + bytesRead } : {}),+ };+ } finally { await handle.close(); }+ }+ ensureGhostProtocolRegistered(ghost);+ const file = /^\/(?:library|media)\//.test(pathname);+ const response = await session.fromPartition(partition).fetch(`${GHOST_SCHEME}://${ghost.manifest.id}${pathname}`, { method, body,+ ...(file && offset ? { headers: { Range: `bytes=${offset}-` } } : {}),+ });+ const revision = response.headers.get('etag') ?? undefined;+ if (pathname.startsWith('/library/') && offset > 0 && (!expectedRevision || revision !== expectedRevision)) {+ await response.body?.cancel(); throw new Error('PLUGIN_LIBRARY_CHANGED');+ }+ // These JSON endpoints have bounded existing contracts; never expose an unbounded file here.+ const reader = response.body?.getReader();+ const chunks: Uint8Array[] = [];+ let total = 0;+ if (reader) {+ try {+ for (;;) {+ const part = await reader.read();+ if (part.done) break;+ if (file) {+ const chunk = part.value.subarray(0, 49_152 - total); chunks.push(chunk); total += chunk.length;+ if (total >= 49_152) break;+ } else {+ total += part.value.length;+ if (total > 1_048_576) throw new Error('PLUGIN_RESPONSE_TOO_LARGE');+ chunks.push(part.value);+ }+ }+ } finally { await reader.cancel(); }+ }+ const remaining = Number(response.headers.get('content-length'));+ return { status: response.status === 206 ? 200 : response.status, mime: response.headers.get('content-type') ?? 'application/json', base64: Buffer.concat(chunks).toString('base64'), ...(revision ? { revision } : {}),+ ...(file && remaining > total ? { nextOffset: offset + total } : {}),+ };+}+// 管子桥 preload 的产物路径(与 main bundle 同目录,forge VitePlugin 出的// .vite/build/ghostPreload.js;__dirname 在 dev/prod 都指向 .vite/build)。const GHOST_PRELOAD_PATH = path.join(@@ -608,6 +684,7 @@ async function serveGhostLibraryFile(ghostId: string, relPath: string, rangeHeadconst st = await fs.stat(absPath);if (!st.isFile()) return new Response(null, { status: 404 });const total = st.size;+ headers.ETag = `"${createHash('sha256').update(JSON.stringify([st.dev, st.ino, st.size, st.mtimeMs, st.ctimeMs])).digest('hex')}"`;if (rangeHeader !== null && rangeHeader !== undefined && rangeHeader !== '') {const match = /^bytes=(\d*)-(\d*)$/.exec(rangeHeader.trim());// 非单段(多段/后缀拼接/非法)按不支持处理:满足 prefix 的回 416,diff --git a/apps/desktop/src/main/cindy-brain/runtime/mobilePageRelay.ts b/apps/desktop/src/main/cindy-brain/runtime/mobilePageRelay.tsnew file mode 100644index 0000000000..90e21d4bee--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/runtime/mobilePageRelay.ts@@ -0,0 +1,82 @@+import type { PluginPageEvent } from '@cindy/device-link';++export type MobileRelayOperation =+ | { op: 'connect'; pageId: string; channels: string[] }+ | { op: 'post'; pageId: string; channel: string; data: unknown }+ | { op: 'poll'; pageId: string; after: number }+ | { op: 'disconnect'; pageId: string };++/** Runs in the existing, owner-scoped logic sandbox. No new process or plugin API. */+function relay(operation: MobileRelayOperation) {+ type Page = {+ channels: Map<string, BroadcastChannel>;+ events: PluginPageEvent[];+ sequence: number;+ bytes: number;+ overflow: boolean;+ };+ const root = globalThis as typeof globalThis & { __cindyMobilePages?: Map<string, Page> };+ const pages: Map<string, Page> = (root.__cindyMobilePages ??= new Map<string, Page>());+ let page: Page | undefined = pages.get(operation.pageId);+ if (operation.op === 'connect') {+ if (page) return;+ page = { channels: new Map(), events: [], sequence: 0, bytes: 0, overflow: false };+ const target = page;+ for (const name of operation.channels) {+ const channel = new BroadcastChannel(name);+ channel.onmessage = (event) => {+ let data: unknown, bytes: number;+ try {+ const json = JSON.stringify(event.data);+ bytes = new TextEncoder().encode(json).length;+ data = JSON.parse(json);+ } catch {+ return;+ }+ // A slow controller must recover its page state; never silently skip an ACK.+ if (bytes > 49_152 || target.events.length >= 256 || target.bytes + bytes > 1_048_576) {+ target.overflow = true;+ return;+ }+ target.events.push({ sequence: ++target.sequence, channel: name, data });+ target.bytes += bytes;+ };+ target.channels.set(name, channel);+ }+ pages.set(operation.pageId, target);+ return;+ }+ if (!page) throw new Error('PLUGIN_PAGE_CLOSED');+ if (operation.op === 'disconnect') {+ for (const channel of page.channels.values()) channel.close();+ pages.delete(operation.pageId);+ return;+ }+ if (operation.op === 'poll') {+ if (page.overflow) throw new Error('PLUGIN_PAGE_RESYNC_REQUIRED');+ page.events = page.events.filter((event) => event.sequence > operation.after);+ page.bytes = new TextEncoder().encode(JSON.stringify(page.events)).length;+ const batch: PluginPageEvent[] = [];+ let bytes = 0;+ for (const event of page.events) {+ const size = new TextEncoder().encode(JSON.stringify(event)).length;+ if (batch.length && bytes + size > 64 * 1024) break;+ batch.push(event);+ bytes += size;+ }+ return batch;+ }+ const channel = page.channels.get(operation.channel);+ if (!channel) throw new Error('PLUGIN_CHANNEL_UNAVAILABLE');+ const data = operation.data;+ // Plugins forward this opaque origin when requesting a host confirmation.+ channel.postMessage(+ data && typeof data === 'object' && !Array.isArray(data)+ ? { ...data, mobilePageId: operation.pageId }+ : data,+ );+}++export function mobilePageRelayScript(operation: MobileRelayOperation): string {+ return `(${relay.toString()})(${JSON.stringify(operation)})`;+}diff --git a/apps/desktop/src/main/cindy-brain/scheduleSlot.ts b/apps/desktop/src/main/cindy-brain/scheduleSlot.tsindex 0d96e6399c..d3e2e70bfe 100644--- a/apps/desktop/src/main/cindy-brain/scheduleSlot.ts+++ b/apps/desktop/src/main/cindy-brain/scheduleSlot.ts@@ -55,6 +55,7 @@ export interface ScheduleSlotDeps {* 保存成多条自动化。装配处负责选窗(focused ?? 第一个),本槽只管投一次。*/sendToWindow(payload: GhostScheduleDraftPush): boolean;+ sendToMobile?(pageId: string, payload: GhostScheduleDraftPush): boolean;now?(): number;/** 仅测试注入;生产用 randomUUID。 */newRequestId?(): string;@@ -153,6 +154,7 @@ export class GhostScheduleSlot {return fail('INVALID_REQUEST', 'schedule-request 载荷必须是对象');}const request = payload as Record<string, unknown>;+ if (request.mobilePageId !== undefined && (typeof request.mobilePageId !== 'string' || request.mobilePageId.length > 128)) return fail('INVALID_REQUEST', 'Invalid mobile page context');if (typeof request.name !== 'string' || request.name.trim().length === 0) {return fail('INVALID_REQUEST', 'name 必填且必须是非空字符串(预填的任务名)');}@@ -198,7 +200,7 @@ export class GhostScheduleSlot {): undefined;- const delivered = this.deps.sendToWindow({+ const draft: GhostScheduleDraftPush = {requestId: this.deps.newRequestId?.() ?? randomUUID(),ghostId,ghostName: ghost.manifest.name,@@ -206,7 +208,9 @@ export class GhostScheduleSlot {name,prompt,...(intervalMs !== undefined ? { intervalMs } : {}),- });+ };+ const delivered = typeof request.mobilePageId === 'string'+ ? this.deps.sendToMobile?.(request.mobilePageId, draft) : this.deps.sendToWindow(draft);if (!delivered) {return fail('HOST_NOT_READY', '当前没有可用的宿主窗口');}diff --git a/apps/desktop/src/main/cindy-brain/taskSlot.ts b/apps/desktop/src/main/cindy-brain/taskSlot.tsindex 9c58d5d257..ac6afe98b9 100644--- a/apps/desktop/src/main/cindy-brain/taskSlot.ts+++ b/apps/desktop/src/main/cindy-brain/taskSlot.ts@@ -48,7 +48,8 @@ export function validPluginTaskRequest(value: unknown): value is PluginTaskReque};if (typeof value.kind !== 'string' || !Object.hasOwn(allowed, value.kind)) return false;const kind = value.kind;- if (Object.keys(value).some((key) => !['type', 'kind', ...allowed[kind]].includes(key)))+ if (value.mobilePageId !== undefined && (typeof value.mobilePageId !== 'string' || !/^[a-f0-9-]{36}$/.test(value.mobilePageId))) return false;+ if (Object.keys(value).some((key) => !['type', 'kind', 'mobilePageId', ...allowed[kind]].includes(key)))return false;if (kind === 'requestWriteAccess' && value.mode !== undefined && !['acceptEdits', 'auto'].includes(String(value.mode))) return false;const requires = (key: string) => text(value[key], 128);diff --git a/apps/desktop/src/main/cindy-brain/workspaceSlot.ts b/apps/desktop/src/main/cindy-brain/workspaceSlot.tsindex 7a85d214fc..755dea96f8 100644--- a/apps/desktop/src/main/cindy-brain/workspaceSlot.ts+++ b/apps/desktop/src/main/cindy-brain/workspaceSlot.ts@@ -65,7 +65,7 @@ export interface WorkspaceSlotDeps {* 弹系统级选文件夹窗口;返回所选绝对路径,取消返回 null。* 找不到可挂靠的 Cindy 窗口时应 reject(失败关闭,不弹无主对话框)。*/- showDirectoryDialog(params: { ghostName: string; purpose: string | null }): Promise<string | null>;+ showDirectoryDialog(params: { ghostName: string; purpose: string | null; ghostId: string; mobilePageId?: string }): Promise<string | null>;/** 在途 ghost_call 反查(cardService.inFlightCallInfoOf):查无/过期返回 null。 */resolveCallContext(callId: string): { ghostId: string; sessionId: string | null; sessionInstanceId?: string } | null;/** 会话目录快照(localDb);查无会话返回 null。 */@@ -118,7 +118,7 @@ export class GhostWorkspaceSlot {this.sessionService = service;}- async handleRequest(ghostId: string, payload: unknown): Promise<GhostPipeWorkspaceResult> {+ async handleRequest(ghostId: string, payload: unknown, shouldContinue?: () => boolean): Promise<GhostPipeWorkspaceResult> {const ghost = this.deps.getGhost(ghostId);if (!ghost?.enabled || ghost.manifest.workspace !== true) {return fail('PERMISSION_DENIED', '插件未申请工作区会话权限(workspace),或当前未启用');@@ -127,6 +127,7 @@ export class GhostWorkspaceSlot {return fail('INVALID_REQUEST', 'workspace-request 载荷必须是对象');}const request = payload as Record<string, unknown>;+ if (request.mobilePageId !== undefined && (typeof request.mobilePageId !== 'string' || request.mobilePageId.length > 128)) return fail('INVALID_REQUEST', 'Invalid mobile page context');if (request.kind !== 'ensure-session') {return fail('INVALID_REQUEST', 'kind 目前只支持 "ensure-session"');}@@ -161,7 +162,7 @@ export class GhostWorkspaceSlot {// ── 目录授权 ────────────────────────────────────────────────────────let dirAbs: string;let sourceSessionId: string | undefined;- let callIsCurrent: (() => boolean) | undefined;+ let callIsCurrent: (() => boolean) | undefined = shouldContinue;if (request.mode === 'pick') {this.consentInFlight = true;let picked: string | null;@@ -169,6 +170,8 @@ export class GhostWorkspaceSlot {picked = await this.deps.showDirectoryDialog({ghostName: ghost.manifest.name,purpose: title,+ ghostId,+ ...(typeof request.mobilePageId === 'string' ? { mobilePageId: request.mobilePageId } : {}),});} catch (error) {this.deps.log?.warn('ghost workspace pick dialog failed', {@@ -179,6 +182,7 @@ export class GhostWorkspaceSlot {} finally {this.consentInFlight = false;}+ if (shouldContinue && !shouldContinue()) return fail('CANCELLED', 'The originating page has closed.');if (picked === null) {return fail('CANCELLED', '用户取消了选择');}@@ -210,7 +214,7 @@ export class GhostWorkspaceSlot {return fail('PERMISSION_DENIED', 'The originating task cannot authorize this workspace operation.');}callIsCurrent = () => {- if (authorization && !authorization()) return false;+ if ((shouldContinue && !shouldContinue()) || (authorization && !authorization())) return false;const current = this.deps.resolveCallContext(request.callId as string);return current?.ghostId === ctx.ghostId && current?.sessionId === ctx.sessionId&& current?.sessionInstanceId === ctx.sessionInstanceId;diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex a2d3cf1bda..42a5150758 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -7,7 +7,7 @@ import { pluginWorkerCompletedAt } from './pluginWorkerCompletion.js';import { createPluginTaskStore } from './pluginTaskStore.js';import { hasAcceptedUserTaskInput } from './pluginTaskInput.js';import { controlOwnedSessionExecution, isSameSessionExecution, withdrawOwnedSessionInputs } from './sessionExecutionOwnership.js';-import { setPluginTaskHandler, getPluginTaskSourceSessionId, setPluginTaskUninstaller, isPluginTaskAuthorized, getPluginTaskInstallRevision, pluginTaskAuthorizationRevision } from '../cindy-brain/index.js';+import { showMobilePluginTaskPermission, setPluginTaskHandler, getPluginTaskSourceSessionId, setPluginTaskUninstaller, isPluginTaskAuthorized, getPluginTaskInstallRevision, pluginTaskAuthorizationRevision } from '../cindy-brain/index.js';import type { PluginTaskRoute, PluginTaskRequest } from '../../shared/pluginTasks.js';import { createHash as pluginTaskConfigHash } from 'node:crypto';import { finishCompanionEnvironmentRemoval } from '../bot-import/runtime.js';@@ -10954,7 +10954,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)assertRequestCurrent();// Busy/preflight failures have not asked the user anything; do not consume an attempt.return await pluginWriteAccessGate.request(JSON.stringify([pluginId, task.taskId]), identity, mode, explicitWriteAccess, async () => {- const result = await dialog.showMessageBox({+ const result = request.mobilePageId ? { response: await showMobilePluginTaskPermission(pluginId, request.mobilePageId, {+ title: t(mode === 'auto' ? 'pluginTaskWriteAccess.autoTitle' : 'pluginTaskWriteAccess.title'),+ message: t(mode === 'auto' ? 'pluginTaskWriteAccess.autoMessage' : 'pluginTaskWriteAccess.message').replace('{{name}}', getInstalledGhostName(pluginId) ?? pluginId),+ detail: `${task.title}\n\n${t(mode === 'auto' ? 'pluginTaskWriteAccess.autoDetail' : 'pluginTaskWriteAccess.detail')}`,+ allow: t('pluginTaskWriteAccess.allow'), cancel: t('pluginTaskWriteAccess.cancel'),+ }) ? 0 : 1 } : await dialog.showMessageBox({type: 'question', title: t(mode === 'auto' ? 'pluginTaskWriteAccess.autoTitle' : 'pluginTaskWriteAccess.title'),message: t(mode === 'auto' ? 'pluginTaskWriteAccess.autoMessage' : 'pluginTaskWriteAccess.message').replace('{{name}}', getInstalledGhostName(pluginId) ?? pluginId),detail: t(mode === 'auto' ? 'pluginTaskWriteAccess.autoDetail' : 'pluginTaskWriteAccess.detail'),diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/pluginAuthorizationController.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/pluginAuthorizationController.test.tsnew file mode 100644index 0000000000..795c614ab3--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/__tests__/pluginAuthorizationController.test.ts@@ -0,0 +1,201 @@+// Cross-platform tests use the Node host environment; importing Desktop main+// from Mobile tests pulls Node-only APIs into the React Native type environment.+import { describe, expect, it, vi } from "vitest";+import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";+import { OauthTransactions } from "../transactions";+import { getRemoteOauthContext } from "../context";+import { runMobilePluginAuthorization } from "../../../../../mobile/src/plugins/pluginAuthorizationController";+import { mobilePluginSetupActions } from "../../../../../mobile/src/plugins/pluginSetupActions";+import type { PluginOauthCrypto } from "../../../../../mobile/src/plugins/pluginOauthCrypto";+const crypto: PluginOauthCrypto = {+ random: (n) => new Uint8Array(randomBytes(n)),+ encrypt: async (key, iv, body, aad) => {+ const c = createCipheriv("aes-256-gcm", key, iv);+ c.setAAD(aad);+ return new Uint8Array(+ Buffer.concat([+ Buffer.from(iv),+ c.update(body),+ c.final(),+ c.getAuthTag(),+ ]),+ );+ },+ decrypt: async (key, data, aad) => {+ const c = createDecipheriv("aes-256-gcm", key, data.subarray(0, 12));+ c.setAAD(aad);+ c.setAuthTag(data.subarray(-16));+ return new Uint8Array(+ Buffer.concat([c.update(data.subarray(12, -16)), c.final()]),+ );+ },+};+const secretPresentation = {+ ghostName: "Practice",+ title: "Connect",+ description: "API key",+ intro: "Private account",+ fieldLabel: "Key",+ fieldDescription: "Keep private",+ maxLength: 4096,+};+const connectionPresentation = {+ ghostName: "Practice",+ title: "Connect",+ description: "Connection",+ intro: "Private account",+ connectionKey: "account",+};+const action = { requestId: "card", actionId: "connect", expectedRevision: 0 };+function setup(kind: "secret" | "connection") {+ const saved = vi.fn(),+ requests: unknown[] = [];+ const host = new OauthTransactions({+ owner: () => "account",+ available: () => true,+ bind: async () => ({ ghostId: "practice", current: () => true }),+ run: () => {+ const remote = getRemoteOauthContext()!;+ void (async () => {+ try {+ const state = randomBytes(32).toString("base64url");+ const value =+ kind === "secret"+ ? await remote.submitSecret!({+ kind: "secret-entry",+ state,+ presentation: secretPresentation,+ })+ : await remote.submitConnection!({+ kind: "connection-entry",+ state,+ presentation: connectionPresentation,+ });+ saved(value);+ remote.finish(true);+ } catch {+ remote.finish(false);+ }+ })();+ return true;+ },+ });+ return {+ saved,+ requests,+ invoke: async (request: Parameters<OauthTransactions["request"]>[1]) => {+ requests.push(request);+ return host.request("phone", request);+ },+ };+}+describe("native plugin configuration exchange", () => {+ it.each(["secret", "connection"] as const)(+ "saves %s only after matching the real Host offer and passes no plaintext through the tunnel",+ async (kind) => {+ const h = setup(kind),+ clear = vi.fn();+ await runMobilePluginAuthorization({+ crypto,+ action,+ kind,+ invoke: h.invoke,+ assertCurrent: () => {},+ pause: async () => {},+ clearInput: clear,+ secretPresentation,+ connectionPresentation,+ inputSecret: "fake-private-test-value",+ inputConnection: {+ host: "https://example.org",+ token: "fake-private-test-value",+ },+ showAuthorization: async () => {+ throw Error("No browser expected");+ },+ });+ expect(h.saved).toHaveBeenCalledTimes(1);+ expect(h.saved).toHaveBeenCalledWith(+ kind === "secret"+ ? "fake-private-test-value"+ : { host: "example.org", token: "fake-private-test-value" },+ );+ expect(JSON.stringify(h.requests)).not.toContain(+ "fake-private-test-value",+ );+ expect(clear).toHaveBeenCalled();+ },+ );+ it("rejects an offer that differs from the displayed form and cancels without a vault write", async () => {+ const h = setup("secret");+ await expect(+ runMobilePluginAuthorization({+ crypto,+ action,+ kind: "secret",+ invoke: h.invoke,+ assertCurrent: () => {},+ pause: async () => {},+ clearInput: () => {},+ secretPresentation: {+ ...secretPresentation,+ fieldLabel: "Another field",+ },+ inputSecret: "fake-private-test-value",+ showAuthorization: async () => {},+ }),+ ).rejects.toThrow("OAUTH_BRIDGE_UNAVAILABLE");+ expect(h.saved).not.toHaveBeenCalled();+ expect(h.requests.at(-1)).toMatchObject({ op: "cancel" });+ });+ it("projects only pending Host-enabled steps; no secret value or arbitrary setup action becomes a native capability", () => {+ const raw = {+ kind: "plugin_setup",+ requestId: "card",+ revision: 0,+ ghost: { id: "practice", name: "Practice" },+ remoteSecret: true,+ intro: "Private account",+ steps: [+ {+ id: "key",+ phase: "pending",+ title: "Connect",+ description: "API key",+ action: {+ id: "connect",+ kind: "inline_form",+ form: {+ fields: [+ {+ label: "Key",+ description: "Keep private",+ maxLength: 4096,+ value: "must never project",+ },+ ],+ },+ },+ },+ ],+ };+ expect(mobilePluginSetupActions(raw)[0]).toMatchObject({+ kind: "secret",+ action,+ secret: secretPresentation,+ });+ expect(JSON.stringify(mobilePluginSetupActions(raw))).not.toContain(+ "must never project",+ );+ expect(mobilePluginSetupActions({ ...raw, remoteSecret: false })).toEqual(+ [],+ );+ expect(mobilePluginSetupActions({ ...raw, terminal: true })).toEqual([]);+ expect(+ mobilePluginSetupActions({+ ...raw,+ steps: [{ ...raw.steps[0], phase: "satisfied" }],+ }),+ ).toEqual([]);+ });+});diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/pluginOauthCrypto.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/pluginOauthCrypto.test.tsnew file mode 100644index 0000000000..51b2c50dae--- /dev/null+++ b/apps/desktop/src/main/plugin-oauth/__tests__/pluginOauthCrypto.test.ts@@ -0,0 +1,140 @@+// Cross-platform tests use the Node host environment; importing Desktop main+// from Mobile tests pulls Node-only APIs into the React Native type environment.+import { describe, expect, it } from "vitest";+import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";+import {+ MobileOauthBox,+ type PluginOauthCrypto,+} from "../../../../../mobile/src/plugins/pluginOauthCrypto";+import { authenticateMobilePluginOauth } from "../../../../../mobile/src/plugins/pluginOauthClient";+import { OauthBox } from "../box";+import {+ AuthenticatedOauthHost,+ OauthHostIdentity,+} from "../authentication";+import type { PluginOauthPeerIdentity } from "@cindy/device-link";+const crypto: PluginOauthCrypto = {+ random: (n) => new Uint8Array(randomBytes(n)),+ encrypt: async (key, iv, body, aad) => {+ const cipher = createCipheriv("aes-256-gcm", key, iv);+ cipher.setAAD(aad);+ return new Uint8Array(+ Buffer.concat([+ Buffer.from(iv),+ cipher.update(body),+ cipher.final(),+ cipher.getAuthTag(),+ ]),+ );+ },+ decrypt: async (key, data, aad) => {+ const cipher = createDecipheriv("aes-256-gcm", key, data.subarray(0, 12));+ cipher.setAAD(aad);+ cipher.setAuthTag(data.subarray(-16));+ return new Uint8Array(+ Buffer.concat([cipher.update(data.subarray(12, -16)), cipher.final()]),+ );+ },+};+describe("mobile native plugin authorization cryptography", () => {+ it("interoperates with the actual execution Host in both directions and rejects tampering, domain substitution and disposed keys", async () => {+ const mobile = new MobileOauthBox(crypto),+ desktop = new OauthBox();+ const box = await mobile.seal(+ desktop.publicKey,+ "transaction",+ "callback",+ { value: "私有测试值 🎵" },+ );+ expect(+ desktop.open(mobile.publicKey, "transaction", "callback", box),+ ).toEqual({ value: "私有测试值 🎵" });+ const offer = desktop.seal(mobile.publicKey, "transaction", "offer", {+ state: "trusted",+ });+ expect(+ await mobile.open(desktop.publicKey, "transaction", "offer", offer),+ ).toEqual({ state: "trusted" });+ const bytes = Buffer.from(offer, "base64url");+ bytes[15] ^= 1;+ await expect(+ mobile.open(+ desktop.publicKey,+ "transaction",+ "offer",+ bytes.toString("base64url"),+ ),+ ).rejects.toThrow("OAUTH_BRIDGE_INVALID");+ await expect(+ mobile.open(desktop.publicKey, "another-transaction", "offer", offer),+ ).rejects.toThrow("OAUTH_BRIDGE_INVALID");+ mobile.dispose();+ await expect(+ mobile.seal(desktop.publicKey, "transaction", "callback", {}),+ ).rejects.toThrow("OAUTH_BRIDGE_INVALID");+ });+ it("verifies the actual signed Host handshake before transmitting authenticated requests", async () => {+ const identity = new OauthHostIdentity(),+ now = Date.now(),+ raw: unknown[] = [];+ const scope = {+ realm: "global" as const,+ membershipId: "membership",+ deviceId: "computer",+ key: identity,+ };+ const host = new AuthenticatedOauthHost({+ owner: () => "membership",+ available: () => true,+ identity: () => scope,+ bind: async () => ({ ghostId: "practice", current: () => true }),+ request: async (_peer, request) => ({ received: request }),+ now: () => now,+ });+ const target: PluginOauthPeerIdentity = {+ ...identity.descriptor,+ ...scope,+ observedAtMs: now,+ expiresAtMs: now + 60000,+ };+ let trusted = false;+ const client = await authenticateMobilePluginOauth({+ crypto,+ target,+ peer: "phone",+ ghostId: "practice",+ action: { requestId: "card", actionId: "connect", expectedRevision: 3 },+ now: () => now,+ assertCurrent: () => {},+ trustIdentity: async () => {+ trusted = true;+ },+ invoke: async (value) => {+ raw.push(value);+ return host.request("phone", value);+ },+ });+ expect(trusted).toBe(true);+ expect(await client.request({ op: "capabilities" })).toEqual({+ received: { op: "capabilities" },+ });+ expect(raw[1]).toMatchObject({ op: "exchange" });+ expect(JSON.stringify(raw[1])).not.toContain("capabilities");+ client.dispose();+ await expect(+ authenticateMobilePluginOauth({+ crypto,+ target,+ peer: "different-phone",+ ghostId: "practice",+ action: { requestId: "card", actionId: "connect", expectedRevision: 3 },+ now: () => now,+ assertCurrent: () => {},+ trustIdentity: async () => {+ throw new Error("must not reach trust");+ },+ invoke: (value) => host.request("phone", value),+ }),+ ).rejects.toThrow("OAUTH_BRIDGE_UNAVAILABLE");+ });+});diff --git a/apps/desktop/src/main/plugin-oauth/authentication.ts b/apps/desktop/src/main/plugin-oauth/authentication.tsindex 8744121f56..c64da20966 100644--- a/apps/desktop/src/main/plugin-oauth/authentication.ts+++ b/apps/desktop/src/main/plugin-oauth/authentication.ts@@ -9,6 +9,7 @@ import {} from 'node:crypto';import {PLUGIN_OAUTH_TTL_MS,+ pluginOauthTranscript,oauthExact,oauthNonce,parsePluginOauthHello,@@ -69,26 +70,7 @@ function transcript(target: OauthIdentityScope & { publicKey: string },peer: string,): Buffer {- return Buffer.from(- JSON.stringify([- 'cindy-plugin-oauth-authentication-v3',- target.realm,- target.membershipId,- target.deviceId,- peer,- target.publicKey,- reply.bootId,- hello.nonce,- hello.publicKey,- reply.publicKey,- reply.id,- reply.expiresAtMs,- hello.action.requestId,- hello.action.actionId,- hello.action.expectedRevision,- reply.ghostId,- ]),- );+ return Buffer.from(pluginOauthTranscript(hello, reply, target, peer));}interface Connection {id: string;diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 8d8248a778..3b1cb33cb6 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -1456,6 +1456,8 @@ export interface GhostManifest {* Secret 不得写入 `/kv`。*/settingsHtml?: string;+ /** Optional mobile page projection; unknown/invalid declarations leave desktop behavior unchanged. */+ mobile?: { channels: string[]; panel?: string; mainView?: string; settings?: string };/*** 自定义设置区固定高度(px,可选;160–800)。缺省 = 宿主量 guest 内容* 高度自适应(同区间收口);声明本字段 = 固定高度(内容动态增减的设置@@ -5958,6 +5960,7 @@ function validateGhostManifestInput(value: unknown, preserveHistoricalTasks: booentry: raw.entry,...(raw.launch !== undefined ? { launch: raw.launch as GhostLaunchMode } : {}),...(raw.settingsHtml !== undefined ? { settingsHtml: raw.settingsHtml as string } : {}),+ ...(raw.mobile !== undefined ? { mobile: raw.mobile as GhostManifest['mobile'] } : {}),...(raw.settingsHeight !== undefined ? { settingsHeight: raw.settingsHeight as number } : {}),...(tools !== undefined ? { tools } : {}),...(card !== undefined || prepared.v3BaseCard || slots.includes('card')@@ -6527,6 +6530,7 @@ export const GHOST_PICK_MIN_INTERVAL_MS = 3000;*/export interface GhostPipePickRequest {type: 'pick-request';+ mobilePageId?: string;/** v1 只支持选目录;将来扩文件类型时在此收窄枚举。 */mode: 'directory';/** 选择框内的用途说明(净化后随插件名一起展示,让用户知道谁在要、要来干嘛)。 */@@ -6592,6 +6596,7 @@ export const GHOST_WORKSPACE_MIN_INTERVAL_MS = 3000;export type GhostPipeWorkspaceRequest =| {type: 'workspace-request';+ mobilePageId?: string;kind: 'ensure-session';mode: 'pick';/** pick 模式选择框里的用途说明(净化后随插件名展示);也用作新会话标题。 */@@ -6601,6 +6606,7 @@ export type GhostPipeWorkspaceRequest =}| {type: 'workspace-request';+ mobilePageId?: string;kind: 'ensure-session';mode: 'dir';/** 目标项目目录的本机绝对路径。 */@@ -6675,10 +6681,10 @@ export type GhostIOSSimulatorStatusProbeResult =| { ok: false; errorCode: IOSSimulatorMcpErrorCode; message: string };/** 插件只能请求能力摘要、当前台前任务状态,或打开 Host 面板。 */-export type GhostPipeIOSSimulatorRequest =+export type GhostPipeIOSSimulatorRequest = { mobilePageId?: string } & (| { type: 'ios-simulator-request'; kind: 'capabilities' }| { type: 'ios-simulator-request'; kind: 'status' }- | { type: 'ios-simulator-request'; kind: 'open-panel'; instanceId?: string };+ | { type: 'ios-simulator-request'; kind: 'open-panel'; instanceId?: string });export type GhostPipeIOSSimulatorErrorCode =| IOSSimulatorMcpErrorCode@@ -6722,6 +6728,7 @@ export type GhostPipeIOSSimulatorResult =*/export interface GhostPipePreviewRequest {type: 'preview-request';+ mobilePageId?: string;url: string;sessionId?: string;}@@ -6750,6 +6757,7 @@ export type GhostPipePreviewResult =*/export interface GhostPipeScheduleDraftRequest {type: 'schedule-request';+ mobilePageId?: string;/** 预填的自动化名称(净化后按 GHOST_SCHEDULE_DRAFT_NAME_MAX_CHARS 截断)。 */name: string;/** 预填提示词:这条自动化到点要干什么(净化后按 …PROMPT_MAX_CHARS 截断)。 */@@ -7045,6 +7053,7 @@ export type GhostNotifyTone = (typeof GHOST_NOTIFY_TONES)[number];*/export interface GhostPipeNotify {type: 'notify';+ mobilePageId?: string;/** 提示正文(纯文本,≤ GHOST_NOTIFY_MAX_CHARS;允许 \n 换行)。 */text: string;/** 语气(图标/配色);缺省 'info'。 */@@ -7133,6 +7142,8 @@ export const GHOST_NOTIFY_MIN_INTERVAL_MS = 5000;*/export interface GhostPipeConfirm {type: 'confirm-request';+ /** Forward the originating mobile business request's opaque page ID, if present. */+ mobilePageId?: string;/** 问句正文(纯文本,≤ GHOST_CONFIRM_BODY_MAX_CHARS;允许 \n 换行)。 */body: string;/** 主按钮文案(≤ GHOST_CONFIRM_BUTTON_MAX_CHARS);缺省用主机的「确认」。 */@@ -8024,6 +8035,8 @@ export type GhostPipeEventPush =*/type: 'event';name: 'card-action';+ /** Opaque origin for host confirmation routing. Forward it to cindy.confirm. */+ mobilePageId?: string;callId: string;actionId: string;/** 被点卡片所属会话;老卡可能没有归属,缺省时不能唤起 Agent。 */diff --git a/apps/desktop/src/shared/pluginTasks.ts b/apps/desktop/src/shared/pluginTasks.tsindex 541ce4d2a9..f3e5e3db7f 100644--- a/apps/desktop/src/shared/pluginTasks.ts+++ b/apps/desktop/src/shared/pluginTasks.ts@@ -56,7 +56,7 @@ export function isPluginTeamPlanWithinBudget(plan: unknown): boolean {return typeof json === 'string' && json.length <= PLUGIN_TEAM_PLAN_MAX_JSON_CHARS;} catch { return false; }}-export type PluginTaskRequest =+export type PluginTaskRequest = (| { type: 'tasks-request'; kind: 'capabilities' | 'models' }| { type: 'tasks-request'; kind: 'setModel'; taskId: string; expectedRevision: number; route: PluginTaskRoute }| {@@ -86,7 +86,8 @@ export type PluginTaskRequest =}| { type: 'tasks-request'; kind: 'getRun'; runId: string }| { type: 'tasks-request'; kind: 'listRuns'; taskId: string; after?: string; limit?: number }- | { type: 'tasks-request'; kind: 'cancel'; runId: string; requestKey: string };+ | { type: 'tasks-request'; kind: 'cancel'; runId: string; requestKey: string }+) & { /** Opaque page origin; never a permission grant. */ mobilePageId?: string };export type PluginTaskResult =| { ok: true; data: unknown }| {diff --git a/apps/mobile/app/plugins.tsx b/apps/mobile/app/plugins.tsxnew file mode 100644index 0000000000..af3fd9729a--- /dev/null+++ b/apps/mobile/app/plugins.tsx@@ -0,0 +1 @@+export { default } from "@/plugins/PluginsScreen";diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsxindex c497b929b2..bbb6030d64 100644--- a/apps/mobile/app/sessions/new.tsx+++ b/apps/mobile/app/sessions/new.tsx@@ -467,6 +467,7 @@ export default function NewRemoteSessionScreen() {composerMorph?: string;visualDraft?: string;suggestion?: string;+ draft?: string;recoverySessionId?: string;}>();const routeDeviceId = String(params.deviceId ?? '');@@ -557,7 +558,7 @@ export default function NewRemoteSessionScreen() {);const [draft, setDraft] = useState<NewSessionDraft>({...DEFAULT_NEW_SESSION_DRAFT,- firstMessage: visualInitialDraft ?? (isRemoteTaskSuggestionId(params.suggestion)+ firstMessage: visualInitialDraft ?? readRouteString(params.draft) ?? (isRemoteTaskSuggestionId(params.suggestion)? t(`devices.list.taskSuggestions.items.${params.suggestion}.prompt`): DEFAULT_NEW_SESSION_DRAFT.firstMessage),// 无记忆时默认对话;偏好加载后恢复上次选择,显式项目入口优先。diff --git a/apps/mobile/package.json b/apps/mobile/package.jsonindex 099f208344..fca5f92a62 100644--- a/apps/mobile/package.json+++ b/apps/mobile/package.json@@ -13,6 +13,7 @@"@expo/metro-runtime": "^57.0.14","@expo/ui": "~57.0.14","@legendapp/list": "^3.3.3",+ "@noble/curves": "1.9.7","@noble/hashes": "^1.8.0","@react-native-async-storage/async-storage": "2.2.0","@react-native-google-signin/google-signin": "16.1.2",diff --git a/apps/mobile/src/__tests__/homeChromeDrawer.test.tsx b/apps/mobile/src/__tests__/homeChromeDrawer.test.tsxindex 19d6976004..92726d68ce 100644--- a/apps/mobile/src/__tests__/homeChromeDrawer.test.tsx+++ b/apps/mobile/src/__tests__/homeChromeDrawer.test.tsx@@ -113,6 +113,8 @@ vi.mock('@/platform/gestureHandler', () => {};});+// Keep native device polling outside the drawer window/lifecycle fixture.+vi.mock('@/plugins/PluginMenuUnreadDot', () => ({ PluginMenuUnreadDot: () => null }));vi.mock('@/session/HomeModeSwitch', () => ({ HomeModeSwitch: () => null }));vi.mock('@/auth/AuthContext', () => ({ useAuth: () => h.auth }));diff --git a/apps/mobile/src/__tests__/homeChromeDrawerAccount.test.tsx b/apps/mobile/src/__tests__/homeChromeDrawerAccount.test.tsxindex 6ec9922deb..e61bf89268 100644--- a/apps/mobile/src/__tests__/homeChromeDrawerAccount.test.tsx+++ b/apps/mobile/src/__tests__/homeChromeDrawerAccount.test.tsx@@ -71,11 +71,13 @@ vi.mock('@/platform/gestureHandler', async () => {vi.mock('react-native-screens', () => ({ FullWindowOverlay: ({ children }: { children: ReactNode }) => children }));vi.mock('react-native-safe-area-context', () => ({ useSafeAreaInsets: () => ({ left: 0, top: 0, bottom: 0 }) }));vi.mock('lucide-react-native', () => Object.fromEntries(- ['Building2', 'LogOut', 'Monitor', 'Search', 'Settings', 'UsersRound'].map(name => [name, () => null]),+ ['Building2', 'LogOut', 'Monitor', 'Puzzle', 'Search', 'Settings', 'UsersRound'].map(name => [name, () => null]),));vi.mock('@/components/AppText', async () => ({ Text: (await import('react-native')).View }));vi.mock('@/theme', () => ({ useThemedStyles: () => ({}), useTheme: () => ({ colors: {} }) }));vi.mock('@/hooks/useReduceMotion', () => ({ useReduceMotionEnabled: () => driver.reduceMotion }));+// The drawer tests navigation/animation; plugin polling belongs to its own boundary.+vi.mock('@/plugins/PluginMenuUnreadDot', () => ({ PluginMenuUnreadDot: () => null }));vi.mock('@/session/HomeModeSwitch', () => ({ HomeModeSwitch: () => null }));describe('home navigation drawer', () => {diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.tsindex e4306a9040..6c353944d6 100644--- a/apps/mobile/src/__tests__/newSession.test.ts+++ b/apps/mobile/src/__tests__/newSession.test.ts@@ -1948,7 +1948,7 @@ describe('new session composer surface', () => {expect(newSource).toContain("import { MOBILE_VISUAL_MOCK_ENABLED } from '@/config/env';");expect(newSource).toContain("const visualFocusComposer = MOBILE_VISUAL_MOCK_ENABLED && readRouteString(params.visualFocusComposer) === '1';");expect(newSource).toContain('const visualInitialDraft = MOBILE_VISUAL_MOCK_ENABLED ? readRouteString(params.visualDraft) : null;');- expect(newSource).toContain('firstMessage: visualInitialDraft ?? (isRemoteTaskSuggestionId(params.suggestion)');+ expect(newSource).toContain('firstMessage: visualInitialDraft ?? readRouteString(params.draft) ?? (isRemoteTaskSuggestionId(params.suggestion)');expect(newSource).toContain('t(`devices.list.taskSuggestions.items.${params.suggestion}.prompt`)');expect(newSource).toContain(': DEFAULT_NEW_SESSION_DRAFT.firstMessage)');expect(newComposerSource).toContain('inputTestID="newSession.firstMessageInput"');diff --git a/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsx b/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsxindex 184a77621e..12f60842fe 100644--- a/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsx+++ b/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsx@@ -88,7 +88,11 @@ const bindingNames = ['setAttachmentError', 'setBrowseOpen', 'setBrowseError','setShowHiddenDirectories', 'setWorkspacePickerOpen',];-const compiled = ts.transpileModule(`function usePageWorkspace(bindings) {+const readRouteString = source.statements.find((node): node is ts.FunctionDeclaration =>+ ts.isFunctionDeclaration(node) && node.name?.text === 'readRouteString');+if (!readRouteString) throw new Error('readRouteString not found');+const compiled = ts.transpileModule(`${readRouteString.getText(source)}+function usePageWorkspace(bindings) {const { ${bindingNames.join(', ')} } = bindings;${selected.map((statement) => statement.getText(source)).join('\n')}const switchDevice = (deviceId) => {@@ -107,13 +111,13 @@ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });let root: Root | undefined;afterEach(() => { act(() => root?.unmount()); root = undefined; });-function mountWorkspace(options: { initialWorkingDir?: string; restoredKind?: NewSessionWorkspaceKind; suggestion?: string; deviceExplicit?: boolean } = {}) {+function mountWorkspace(options: { initialWorkingDir?: string; restoredKind?: NewSessionWorkspaceKind; suggestion?: string; routeDraft?: string | string[]; deviceExplicit?: boolean } = {}) {let resolveRead!: (value: NewSessionStoredPreferences) => void;const pendingRead = new Promise<NewSessionStoredPreferences>((resolve) => { resolveRead = resolve; });const deviceOptions = [{ deviceId: 'a', name: 'A' }, { deviceId: 'b', name: 'B' }];const initialWorkingDir = options.initialWorkingDir ?? null;const bindings = {- isRemoteTaskSuggestionId, params: { suggestion: options.suggestion }, t: i18n.getFixedT('zh-CN'),+ isRemoteTaskSuggestionId, params: { suggestion: options.suggestion, draft: options.routeDraft }, t: i18n.getFixedT('zh-CN'),useState, useRef, useMemo, useEffect, useCallback, DEFAULT_NEW_SESSION_DRAFT,pickNewSessionDefaultDevice, buildRecentWorkspaceOptions,pickInitialNewSessionWorkspace: vi.fn(pickInitialNewSessionWorkspace),@@ -179,6 +183,13 @@ describe('new session workspace page effects', () => {expect(page.current.draft.firstMessage).toBe(prompt);});+ it('preserves the plugin route draft over recommendations and late preferences', async () => {+ const page = mountWorkspace({ suggestion: 'findFile', routeDraft: '使用练习场学习 DJ' });+ expect(page.current.draft.firstMessage).toBe('使用练习场学习 DJ');+ await page.resolvePreferences('project', 'b');+ expect(page.current.draft.firstMessage).toBe('使用练习场学习 DJ');+ });+it('leaves an unknown recommendation empty and keeps recovery drafts authoritative', async () => {const page = mountWorkspace({ suggestion: 'unknown' });expect(page.current.draft.firstMessage).toBe(DEFAULT_NEW_SESSION_DRAFT.firstMessage);diff --git a/apps/mobile/src/__tests__/pluginCardActions.test.tsx b/apps/mobile/src/__tests__/pluginCardActions.test.tsxnew file mode 100644index 0000000000..27dcf2ceff--- /dev/null+++ b/apps/mobile/src/__tests__/pluginCardActions.test.tsx@@ -0,0 +1,110 @@+// @vitest-environment jsdom+import { act, createElement, type ReactNode } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, describe, expect, it, vi } from "vitest";+import { PluginCardActions } from "../plugins/PluginCardActions";++const h = vi.hoisted(() => ({ invoke: vi.fn() }));+vi.mock("react-native", () => {+ const View = ({ children }: { children?: ReactNode }) =>+ createElement("div", {}, children);+ return {+ View,+ KeyboardAvoidingView: View,+ Pressable: ({+ children,+ onPress,+ disabled,+ }: {+ children?: ReactNode;+ onPress(): void;+ disabled: boolean;+ }) => createElement("button", { onClick: onPress, disabled }, children),+ Modal: ({+ children,+ visible,+ }: {+ children?: ReactNode;+ visible: boolean;+ }) => (visible ? createElement("div", {}, children) : null),+ Platform: { OS: "ios" },+ StyleSheet: { create: (value: unknown) => value },+ AppState: {+ currentState: "active",+ addEventListener: () => ({ remove: () => {} }),+ },+ Alert: { alert: vi.fn() },+ Linking: { openURL: vi.fn() },+ };+});+vi.mock("@/components/AppText", () => ({+ Text: ({ children }: { children?: ReactNode }) =>+ createElement("span", {}, children),+ TextInput: () => null,+}));+vi.mock("@/theme", () => ({ useThemedStyles: () => ({}) }));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));+vi.mock("expo-router", () => ({ useIsFocused: () => true }));+vi.mock("@/device-link/DeviceLinkContext", () => ({+ useDeviceLink: () => ({ invoke: h.invoke, status: "online" }),+}));+vi.mock("@/auth/authOwnerGeneration", () => ({+ getMobileAuthOwner: () => ({ accountKey: "owner" }),+ isMobileAuthOwnerCurrent: () => true,+}));+(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;+let unmount: (() => void) | undefined;+afterEach(() => {+ unmount?.();+ unmount = undefined;+ vi.clearAllMocks();+});+describe("native plugin card deliberate actions", () => {+ it.each([false, true])(+ "releases only a known successful delivery (unknown=%s)",+ async (unknown) => {+ const dispatch = vi.fn(async () => {+ if (unknown) throw new Error("lost receipt");+ return { effects: [] };+ });+ h.invoke.mockImplementation(+ async (_device: string, _channel: string, args: any[]) => {+ if (args[0].collectionId === "plugin-results") return dispatch();+ if (args[0].actionId === "open-interaction")+ return { result: { pageId: "page" } };+ if (args[0].actionId === "poll") return { result: { confirms: [] } };+ return { effects: [] };+ },+ );+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);+ unmount = () => {+ act(() => root.unmount());+ container.remove();+ };+ await act(async () =>+ root.render(+ createElement(PluginCardActions, {+ deviceId: "device",+ sessionId: "session",+ callId: "call",+ data: {+ pluginId: "practice",+ revision: "unchanged",+ items: [{ id: "again", label: "Again", disabled: false }],+ },+ }),+ ),+ );+ const button = container.querySelector("button")!;+ await act(async () => button.click());+ expect(dispatch).toHaveBeenCalledTimes(1);+ expect(button.disabled).toBe(unknown);+ await act(async () => button.click());+ expect(dispatch).toHaveBeenCalledTimes(unknown ? 1 : 2);+ },+ );+});diff --git a/apps/mobile/src/__tests__/pluginLocalPreview.test.ts b/apps/mobile/src/__tests__/pluginLocalPreview.test.tsnew file mode 100644index 0000000000..eb97beabc7--- /dev/null+++ b/apps/mobile/src/__tests__/pluginLocalPreview.test.ts@@ -0,0 +1,111 @@+import { describe, expect, it, vi } from "vitest";+const native = vi.hoisted(() => ({+ listener: undefined as+ ((event: { token: string; id: string; path: string }) => void) | undefined,+ startOnDemand: vi.fn(async (_root: string, _entry: string, _token: string, _csp: string) => "http://127.0.0.1:8080/__cindy/preview"),+ resolveRequest: vi.fn(+ async (_token: string, _id: string, _path: string | null) => true,+ ),+ stop: vi.fn(async () => {}),+ addListener: vi.fn((_, listener) => {+ native.listener = listener;+ return { remove: vi.fn() };+ }),+}));+const disk = vi.hoisted(() => ({+ files: new Map<string, string | Uint8Array>(),+ removed: [] as string[],+}));+vi.mock("../../modules/cindy-html-preview/src/CindyHtmlPreviewModule", () => ({+ default: native,+}));+vi.mock("expo-crypto", () => ({+ getRandomBytes: (size: number) => new Uint8Array(size).fill(1),+}));+vi.mock("expo-file-system", () => ({+ Paths: { cache: "file:///cache" },+ Directory: class {+ uri: string;+ exists = false;+ constructor(...parts: string[]) {+ this.uri = parts.join("/");+ }+ create() {+ this.exists = true;+ }+ delete() {+ this.exists = false;+ disk.removed.push(this.uri);+ }+ },+ File: class {+ name: string;+ exists = false;+ constructor(_: unknown, name: string) {+ this.name = name;+ }+ create() {+ this.exists = true;+ }+ write(value: string | Uint8Array) {+ disk.files.set(this.name, value);+ }+ delete() {+ this.exists = false;+ disk.files.delete(this.name);+ }+ },+}));+import { preparePluginLocalPreview } from "../plugins/pluginLocalPreview";+describe("computer preview on the existing native resource viewer", () => {+ it("binds resources to the source computer, reconstructs chunks and cleans only its own temporary directory", async () => {+ native.resolveRequest.mockClear();+ disk.files.clear();+ disk.removed.length = 0;+ const source = "http://localhost:1234/course/?topic=music",+ content =+ '<html><script src="http://localhost:1234/course/app.js"></script><p>' ++ "a".repeat(60000) ++ "</p></html>";+ const bytes = Buffer.from(content),+ controller = new AbortController();+ const read = vi.fn(async (_url: string, offset: number) => ({+ status: 200,+ mime: "text/html",+ revision: "revision",+ base64: bytes.subarray(offset, offset + 49152).toString("base64"),+ ...(offset + 49152 < bytes.length ? { nextOffset: offset + 49152 } : {}),+ }));+ const preview = await preparePluginLocalPreview(+ source,+ read,+ controller.signal,+ );+ const token = native.startOnDemand.mock.calls[0][2] as string;+ native.listener!({+ token: "another-preview",+ id: "foreign",+ path: "secret",+ });+ expect(read).not.toHaveBeenCalled();+ native.listener!({ token, id: "entry", path: "course/index.html" });+ await vi.waitFor(() =>+ expect(native.resolveRequest).toHaveBeenCalledWith(+ token,+ "entry",+ "0",+ "text/html",+ 200,+ ),+ );+ expect(read.mock.calls[0]).toEqual([source, 0, undefined]);+ expect(read.mock.calls[1]).toEqual([source, 49152, "revision"]);+ const html = disk.files.get("0") as string;+ expect(html).toContain("Content-Security-Policy");+ expect(html).toContain("http://127.0.0.1:8080/course/app.js");+ expect(html).toContain("__cindy_plugin_query");+ await preview.close();+ expect(native.stop).toHaveBeenCalledWith(token);+ expect(disk.removed).toEqual([`file:///cache/html-previews/${token}`]);+ });+});diff --git a/apps/mobile/src/__tests__/pluginMediaFile.test.ts b/apps/mobile/src/__tests__/pluginMediaFile.test.tsnew file mode 100644index 0000000000..e91c7047a8--- /dev/null+++ b/apps/mobile/src/__tests__/pluginMediaFile.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it, vi } from 'vitest';+const disk = vi.hoisted(() => ({ chunks: [] as Uint8Array[], closes: 0, removed: [] as string[] }));+vi.mock('expo-crypto', () => ({ getRandomBytes: (size: number) => new Uint8Array(size).fill(3) }));+vi.mock('expo-file-system', () => ({+ Paths: { cache: 'file:///cache' },+ Directory: class {+ uri: string; exists = false;+ constructor(...parts: string[]) { this.uri = parts.join('/'); }+ create() { this.exists = true; }+ delete() { this.exists = false; disk.removed.push(this.uri); }+ },+ File: class {+ uri: string;+ constructor(directory: { uri: string }, name: string) { this.uri = `${directory.uri}/${name}`; }+ create() {}+ open() { return { writeBytes: (bytes: Uint8Array) => disk.chunks.push(bytes), close: () => { disk.closes++; } }; }+ },+}));+import { readPluginMediaFile } from '../plugins/pluginMediaFile';+describe('native plugin media file ownership', () => {+ it('writes ordered chunks, validates content type and cleans its own cache after close or cancellation', async () => {+ const path = '/media/' + 'a'.repeat(64) + '.png', abort = new AbortController();+ const read = vi.fn(async (_path, offset: number) => ({ status: 200, mime: 'image/png', base64: offset === 0 ? 'YWJj' : 'ZA==', ...(offset === 0 ? { nextOffset: 3 } : {}) }));+ const file = await readPluginMediaFile(path, 'image', read, abort.signal);+ expect(read.mock.calls).toEqual([[path, 0], [path, 3]]);+ expect(Buffer.concat(disk.chunks).toString()).toBe('abcd');+ expect(disk.closes).toBe(1); expect(disk.removed).toHaveLength(0);+ file.close(); expect(disk.removed).toHaveLength(1);+ await expect(readPluginMediaFile(path, 'video', read, abort.signal)).rejects.toThrow('PLUGIN_MEDIA_INVALID');+ expect(disk.closes).toBe(2); expect(disk.removed).toHaveLength(2);+ const late = vi.fn(async () => { abort.abort(); return { status: 200, mime: 'image/png', base64: 'YWJj' }; });+ await expect(readPluginMediaFile(path, 'image', late, abort.signal)).rejects.toThrow('PLUGIN_MEDIA_CLOSED');+ expect(disk.removed).toHaveLength(3); expect(disk.chunks).toHaveLength(2);+ });+});diff --git a/apps/mobile/src/__tests__/pluginOauthPins.test.ts b/apps/mobile/src/__tests__/pluginOauthPins.test.tsnew file mode 100644index 0000000000..e1562553d1--- /dev/null+++ b/apps/mobile/src/__tests__/pluginOauthPins.test.ts@@ -0,0 +1,92 @@+import { describe, expect, it } from "vitest";+import { pinMobilePluginIdentity } from "../plugins/pluginOauthPins";+import type { PluginOauthPeerIdentity } from "@cindy/device-link";++const peer: PluginOauthPeerIdentity = {+ version: 1,+ realm: "global",+ membershipId: "owner",+ deviceId: "computer",+ publicKey: "signed-key",+ bootId: "boot",+ observedAtMs: 0,+ expiresAtMs: 60000,+};+describe("native plugin authorization pins", () => {+ it("serializes first registration and rejects key changes without overwriting the secure pin", async () => {+ const saved = new Map<string, string>();+ const store = {+ get: async (key: string) => saved.get(key) ?? null,+ set: async (key: string, value: string) => {+ saved.set(key, value);+ },+ };+ const results = await Promise.allSettled([+ pinMobilePluginIdentity(store, peer, "phone", () => {}),+ pinMobilePluginIdentity(+ store,+ { ...peer, publicKey: "replacement" },+ "phone",+ () => {},+ ),+ ]);+ expect(results[0].status).toBe("fulfilled");+ expect(results[1]).toMatchObject({+ status: "rejected",+ reason: new Error("PLUGIN_AUTHORIZATION_IDENTITY_CHANGED"),+ });+ expect([...saved.values()]).toEqual(["signed-key"]);+ await pinMobilePluginIdentity(+ store,+ { ...peer, bootId: "restarted" },+ "phone",+ () => {},+ );+ for (const target of [+ { ...peer, realm: "cn" as const },+ { ...peer, membershipId: "other" },+ { ...peer, deviceId: "other" },+ ])+ await pinMobilePluginIdentity(store, target, "phone", () => {});+ await pinMobilePluginIdentity(store, peer, "other-phone", () => {});+ expect(saved.size).toBe(5);+ });+ it("propagates secure storage and stale-owner failures without registering another key", async () => {+ let writes = 0;+ await expect(+ pinMobilePluginIdentity(+ {+ get: async () => {+ throw new Error("locked");+ },+ set: async () => {+ writes++;+ },+ },+ peer,+ "phone",+ () => {},+ ),+ ).rejects.toThrow("locked");+ let current = true;+ await expect(+ pinMobilePluginIdentity(+ {+ get: async () => {+ current = false;+ return null;+ },+ set: async () => {+ writes++;+ },+ },+ peer,+ "phone",+ () => {+ if (!current) throw new Error("stale");+ },+ ),+ ).rejects.toThrow("stale");+ expect(writes).toBe(0);+ });+});diff --git a/apps/mobile/src/__tests__/pluginPage.test.ts b/apps/mobile/src/__tests__/pluginPage.test.tsnew file mode 100644index 0000000000..873086754f--- /dev/null+++ b/apps/mobile/src/__tests__/pluginPage.test.ts@@ -0,0 +1,279 @@+import { describe, expect, it, vi } from "vitest";+import { createRequire } from "node:module";+const { JSDOM } = createRequire(import.meta.url)("jsdom");+import { pluginPageHtml } from "../plugins/pluginPageHtml";+import { loadPluginPageAssets } from "../plugins/pluginClient";+import type { PluginPageDocument } from "@cindy/device-link";++const document: PluginPageDocument = {+ pageId: "page",+ pluginId: "practice",+ title: "Practice",+ entry: "panel.html",+ surface: "panel",+ channels: ["practice-ui"],+ files: [],+};+describe("mobile plugin page transport", () => {+ it("assembles chunk boundaries without corrupting base64 and stops when the owner changes", async () => {+ const data = Buffer.alloc(48 * 1024 + 13, 65);+ const doc = {+ ...document,+ files: [{ path: "panel.html", mime: "text/html", size: data.length }],+ };+ const read = vi.fn(async (_path: string, offset: number) => ({+ mime: "text/html",+ base64: data.subarray(offset, offset + 48 * 1024).toString("base64"),+ }));+ const loaded = await loadPluginPageAssets(doc, read, () => true);+ expect(Buffer.from(loaded["panel.html"].base64, "base64")).toEqual(data);+ expect(read).toHaveBeenCalledTimes(2);+ await expect(loadPluginPageAssets(doc, read, () => false)).rejects.toThrow(+ "PLUGIN_PAGE_CLOSED",+ );+ });+ it("runs the channel bridge in the actual generated document, denies other origins and updates theme without reloading", async () => {+ const html =+ '<html><head></head><body><button id="saved">Keep my draft</button></body></html>';+ const messages: string[] = [];+ const dom = new JSDOM(+ pluginPageHtml({+ document,+ assets: {+ "panel.html": {+ mime: "text/html",+ base64: Buffer.from(html).toString("base64"),+ },+ },+ theme: "light",+ colors: { surface: "#fff" },+ }),+ {+ runScripts: "dangerously",+ url: "https://plugin.invalid/",+ pretendToBeVisual: true,+ beforeParse(window: Window & typeof globalThis) {+ Object.assign(window, {+ ReactNativeWebView: {+ postMessage: (message: string) => messages.push(message),+ },+ TextEncoder,+ TextDecoder,+ Request,+ Response,+ fetch,+ });+ },+ },+ );+ try {+ await new Promise((resolve) => setTimeout(resolve, 0));+ const window = dom.window;+ const channel = window.eval("new BroadcastChannel('practice-ui')");+ channel.postMessage({ requestId: "stable", save: true });+ expect(messages.map((message) => JSON.parse(message))).toContainEqual({+ type: "post",+ pageId: "page",+ channel: "practice-ui",+ data: { requestId: "stable", save: true },+ });+ const receive = vi.fn();+ channel.onmessage = receive;+ const payload = JSON.stringify({+ type: "events",+ events: [+ { sequence: 1, channel: "practice-ui", data: { saved: true } },+ ],+ });+ window.dispatchEvent(+ new window.MessageEvent("message", { data: payload }),+ );+ window.document.dispatchEvent(+ new window.MessageEvent("message", { data: payload }),+ );+ expect(receive).toHaveBeenCalledTimes(1);+ const back = vi.fn(),+ lifecycle = vi.fn();+ const helper = window.eval("window.cindyMobile");+ helper.onBack(back);+ helper.onLifecycle(lifecycle);+ helper.setNavigation(true, "Course");+ window.dispatchEvent(+ new window.MessageEvent("message", {+ data: JSON.stringify({ type: "back" }),+ }),+ );+ window.dispatchEvent(+ new window.MessageEvent("message", {+ data: JSON.stringify({ type: "lifecycle", active: false }),+ }),+ );+ expect(back).toHaveBeenCalledTimes(1);+ expect(lifecycle).toHaveBeenCalledWith(false);+ const draft = helper.readDraft("learning.v1");+ const draftRequest = JSON.parse(messages.at(-1)!);+ expect(draftRequest).toMatchObject({+ type: "draft:get",+ key: "learning.v1",+ pageId: "page",+ });+ window.dispatchEvent(+ new window.MessageEvent("message", {+ data: JSON.stringify({+ type: "draft:reply",+ id: draftRequest.id,+ value: { answer: "a" },+ }),+ }),+ );+ await expect(draft).resolves.toEqual({ answer: "a" });+ expect(window.document.documentElement.dataset.mobile).toBe("true");+ expect(() =>+ window.eval("new BroadcastChannel('another-plugin')"),+ ).toThrow();+ await expect(window.fetch("https://evil.invalid/steal")).rejects.toThrow(+ "PLUGIN_ORIGIN_DENIED",+ );+ window.document.getElementById("saved")!.textContent = "Unsaved draft";+ window.dispatchEvent(+ new window.MessageEvent("message", {+ data: JSON.stringify({+ type: "theme",+ theme: "dark",+ colors: { surface: "#222" },+ }),+ }),+ );+ expect(window.document.documentElement.dataset.theme).toBe("dark");+ expect(window.document.getElementById("saved")!.textContent).toBe(+ "Unsaved draft",+ );+ expect(+ window.document+ .querySelector("meta[http-equiv]")+ ?.getAttribute("content"),+ ).toContain("connect-src 'none'");+ } finally {+ dom.window.close();+ }+ });+});++describe("mobile plugin render and empty-response receipts", () => {+ async function harness() {+ const messages: Array<Record<string, any>> = [];+ const frames: FrameRequestCallback[] = [];+ const dom = new JSDOM(+ pluginPageHtml({+ document: { ...document, unreadAt: 42 },+ assets: {+ "panel.html": {+ mime: "text/html",+ base64: Buffer.from("<html><body>Loading…</body></html>").toString(+ "base64",+ ),+ },+ },+ theme: "light",+ colors: {},+ }),+ {+ runScripts: "dangerously",+ url: "https://plugin.invalid/",+ pretendToBeVisual: true,+ beforeParse(window: Window & typeof globalThis) {+ Object.assign(window, {+ TextEncoder,+ TextDecoder,+ Request,+ Response,+ fetch,+ ReactNativeWebView: {+ postMessage: (message: string) =>+ messages.push(JSON.parse(message)),+ },+ requestAnimationFrame: (frame: FrameRequestCallback) => {+ frames.push(frame);+ return frames.length;+ },+ });+ },+ },+ );+ const receive = (message: unknown) =>+ dom.window.dispatchEvent(+ new dom.window.MessageEvent("message", {+ data: JSON.stringify(message),+ }),+ );+ const frame = () => {+ for (const callback of frames.splice(0)) callback(0);+ };+ await new Promise((resolve) => setTimeout(resolve, 0));+ return { dom, messages, receive, frame };+ }+ it.each([204, 205, 304])(+ "reconstructs HTTP %i without a body at both fetch layers",+ async (status) => {+ const h = await harness();+ try {+ const result = h.dom.window.fetch("/kv", {+ method: "POST",+ body: "{}",+ });+ const request = h.messages.find((message) => message.type === "fetch")!;+ h.receive({+ type: "reply",+ id: request.id,+ result: { status, mime: "application/json", base64: "" },+ });+ const response = await result;+ expect(response.status).toBe(status);+ expect(await response.text()).toBe("");+ expect(+ h.messages.filter((message) => message.type === "fetch"),+ ).toHaveLength(1);+ } finally {+ h.dom.window.close();+ }+ },+ );+ it("requires the author's matching content receipt; polling, load and stale/covered frames cannot mark read", async () => {+ const h = await harness();+ try {+ const helper = h.dom.window.eval("window.cindyMobile");+ const unread = vi.fn();+ helper.onUnread(unread);+ await Promise.resolve();+ expect(unread).toHaveBeenCalledWith(42);+ h.receive({ type: "lifecycle", active: true });+ h.receive({ type: "events", events: [], unreadAt: 43 });+ h.frame();+ expect(+ h.messages.filter((message) => message.type === "content-rendered"),+ ).toEqual([]);+ helper.contentRendered(42);+ helper.contentRendered(43);+ h.receive({ type: "events", events: [], unreadAt: 44 });+ h.frame();+ expect(+ h.messages.filter((message) => message.type === "content-rendered"),+ ).toEqual([]);+ helper.contentRendered(44);+ h.receive({ type: "lifecycle", active: false });+ h.frame();+ expect(+ h.messages.filter((message) => message.type === "content-rendered"),+ ).toEqual([]);+ h.receive({ type: "lifecycle", active: true });+ h.dom.window.document.body.textContent = "New course displayed";+ helper.contentRendered(44);+ h.frame();+ expect(+ h.messages.filter((message) => message.type === "content-rendered"),+ ).toEqual([{ type: "content-rendered", seenAt: 44, pageId: "page" }]);+ } finally {+ h.dom.window.close();+ }+ });+});diff --git a/apps/mobile/src/__tests__/pluginPreviewQueries.test.ts b/apps/mobile/src/__tests__/pluginPreviewQueries.test.tsnew file mode 100644index 0000000000..e885efbcfc--- /dev/null+++ b/apps/mobile/src/__tests__/pluginPreviewQueries.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it } from "vitest";+import { createRequire } from "node:module";+const { JSDOM } = createRequire(import.meta.url)("jsdom");+import {+ PLUGIN_PREVIEW_QUERY_SCRIPT,+ pluginPreviewQueryTarget,+} from "../plugins/pluginPreviewQueries";++describe("computer preview query resource paths", () => {+ it("preserves browser GET and XHR query strings through the existing native resource server", async () => {+ const calls: string[] = [],+ xhr: string[] = [];+ const dom = new JSDOM(PLUGIN_PREVIEW_QUERY_SCRIPT, {+ url: "http://127.0.0.1:8080/page",+ runScripts: "dangerously",+ beforeParse(window: Window & typeof globalThis) {+ Object.assign(window, {+ Request,+ fetch: async (url: string) => {+ calls.push(String(url));+ return new Response("{}");+ },+ });+ window.XMLHttpRequest.prototype.open = ((+ _method: string,+ url: string,+ ) => {+ xhr.push(String(url));+ }) as typeof window.XMLHttpRequest.prototype.open;+ },+ });+ try {+ await dom.window.fetch("/api?topic=%E4%B8%AD%E6%96%87&v=2");+ const request = new dom.window.XMLHttpRequest();+ request.open("GET", "/api?next=3");+ const resource = new URL(calls[0]).pathname.slice(1);+ expect(pluginPreviewQueryTarget(resource, "http://localhost:1234")).toBe(+ "http://localhost:1234/api?topic=%E4%B8%AD%E6%96%87&v=2",+ );+ expect(+ pluginPreviewQueryTarget(+ new URL(xhr[0]).pathname.slice(1),+ "http://localhost:1234",+ ),+ ).toBe("http://localhost:1234/api?next=3");+ const foreign =+ "__cindy_plugin_query/" ++ Buffer.from("https://other.invalid/private").toString("hex");+ expect(() =>+ pluginPreviewQueryTarget(foreign, "http://localhost:1234"),+ ).toThrow("INVALID_PREVIEW_QUERY");+ } finally {+ dom.window.close();+ }+ });+});diff --git a/apps/mobile/src/device-link/remoteResources.ts b/apps/mobile/src/device-link/remoteResources.tsindex 1a1e97da32..34811ea972 100644--- a/apps/mobile/src/device-link/remoteResources.ts+++ b/apps/mobile/src/device-link/remoteResources.ts@@ -42,6 +42,8 @@ const RICH_REMOTE_RESOURCE_PRIMITIVES: readonly string[] = ['routine-list','routine-detail',BOT_GROUP_CHAT_PRIMITIVE,+ 'plugin-capabilities',+ 'plugin-card-actions',];/** Routines remain a desktop feature; other portable collections stay available. */@@ -150,7 +152,7 @@ function normalizeRemoteStatus(value: unknown): RemoteResourceStatus | null {function normalizeRemoteAvatar(value: unknown): RemoteResourceAvatar | null {const record = recordOf(value);const kind = boundedString(record?.kind, 64);- const avatarValue = boundedString(record?.value, 4_096, true);+ const avatarValue = boundedString(record?.value, 256_000, true);const fallbackText = boundedString(record?.fallbackText, 64, true);if (!record || !kind || avatarValue === null || fallbackText === null) return null;const color = boundedString(record.color, 64);@@ -188,6 +190,11 @@ function normalizeRemoteDisplay(value: unknown): RemoteResourceDisplay | null {...(normalizeRemoteTimestamp(record.lastReplyAt) !== undefined ? { lastReplyAt: record.lastReplyAt as number } : {}),...(avatar ? { avatar } : {}),...(status ? { status } : {}),+ ...(Array.isArray(record.badges) ? { badges: record.badges.slice(0, 8).flatMap(value => {+ const badge = recordOf(value);+ const accessibilityLabel = normalizeRemoteText(badge?.accessibilityLabel, 512);+ return accessibilityLabel ? [{ accessibilityLabel, tone: boundedString(badge?.tone, 64) ?? 'neutral' }] : [];+ }) } : {}),};}@@ -433,7 +440,9 @@ function normalizeRemoteCollectionItem(return normalized ? [normalized] : [];}): [];- return { ref, display, links, revision };+ return { ref, display, links, revision,+ ...(collectionId === 'plugins' ? { actions: normalizeRemoteActions(item.actions) } : {}),+ };}export function normalizeRemoteCollectionItems(diff --git a/apps/mobile/src/i18n/locales/en/index.ts b/apps/mobile/src/i18n/locales/en/index.tsindex 5a06acd366..e53a1ef086 100644--- a/apps/mobile/src/i18n/locales/en/index.ts+++ b/apps/mobile/src/i18n/locales/en/index.ts@@ -1,3 +1,4 @@+import plugins from './plugins.json';import taskTags from './taskTags.json';/*** 本 locale 的 catalog 组装:每个区域一个 JSON 文件、一个顶级 key,@@ -26,6 +27,7 @@ import startup from './startup.json';import update from './update.json';export default {+ plugins,taskTags,remoteDesktop,apiErrors,diff --git a/apps/mobile/src/i18n/locales/en/plugins.json b/apps/mobile/src/i18n/locales/en/plugins.jsonnew file mode 100644index 0000000000..203a547e9e--- /dev/null+++ b/apps/mobile/src/i18n/locales/en/plugins.json@@ -0,0 +1,90 @@+{+ "title": "Plugins",+ "all": "All",+ "unread": "Unread",+ "recent": "Recent",+ "installed": "Installed",+ "search": "Search plugins",+ "computer": "Choose computer",+ "allComputers": "All computers",+ "cancel": "Cancel",+ "open": "Open",+ "confirm": "Confirm",+ "externalTitle": "Open external link",+ "openTask": "Open task",+ "details": "Plugin details",+ "detailsFor": "Details for {{name}}",+ "offline": "This computer is not connected. Reconnect to continue.",+ "notConnected": "Not connected",+ "loadFailed": "Could not load plugin details. Try again.",+ "actionFailed": "The action did not complete. Check your connection and retry.",+ "noResults": "No matching plugins.",+ "noPlugins": "No plugins are installed on this computer.",+ "noComputer": "Connect a computer to use its installed plugins.",+ "connectComputer": "Connect computer",+ "listUnavailable": "Some plugin lists are unavailable. Previously loaded content is retained.",+ "selectPlugin": "Choose a plugin to begin",+ "panel": "Open panel",+ "mainView": "Open page",+ "settings": "Plugin settings",+ "useInTask": "Use in a task",+ "newTask": "New task",+ "chooseTask": "Open existing task",+ "taskHint": "Describe what you need in a task. Cindy will use the appropriate plugin. Existing tasks keep their model and permissions.",+ "noMobilePage": "This plugin has no mobile page yet. Its tools can be used in a task.",+ "enable": "Enable plugin",+ "disable": "Disable plugin",+ "pageUnconfirmed": "The connection or page state is unconfirmed. Sent actions will not be replayed. Check the original task or saved content first.",+ "reopen": "Reopen page",+ "loadingPage": "Opening plugin…",+ "searchTasks": "Search tasks",+ "retry": "Retry",+ "noTasks": "No tasks on this computer yet",+ "taskDraft": "Use the {{name}} plugin to ",+ "taskSettings": "Task settings",+ "taskModel": "Task model",+ "taskPermission": "Task permissions",+ "followDefault": "Follow defaults",+ "taskSettingsHint": "Applies to tasks created by this plugin from now on. Existing tasks keep their model and permissions.",+ "permissionHint": "Choose permissions for new plugin tasks. The current task’s permissions are not inherited.",+ "autoPermissionHint": "Automatic approval lets Cindy assess permission requests automatically. Use it for future plugin tasks?",+ "settingsReload": "Reload settings to check whether the action was saved",+ "modelsUnavailable": "The computer’s model catalog is unavailable. Check the connection and retry.",+ "identityChanged": "Computer identity changed",+ "identityChangedHint": "Configuration stopped because this computer’s authorization identity changed. Verify the computer and register its device identity again before connecting. This card cannot replace a registered identity.",+ "connectAccount": "Connect account",+ "computerAuthorization": "Computer callback required",+ "computerAuthorizationHint": "This sign-in method uses a callback on the computer. Complete it using this card’s computer entry, then return to check its status.",+ "authorizationCheckHint": "Check this setup step’s status. Unconfirmed actions are not automatically replayed.",+ "connectionHost": "Connection host (HTTPS domain)",+ "connectionToken": "Connection token",+ "copyCode": "Copy code",+ "waitingAuthorization": "Waiting for account connection…",+ "saveConfiguration": "Save configuration",+ "nativeSetupHint": "Complete the configuration below on your phone. Account connections that require a computer-local callback can continue through the computer entry.",+ "chooseComputerFolder": "Choose a folder on your computer",+ "folderReadFailed": "Could not read this folder. Check the connection or choose another folder.",+ "parentFolder": "Parent folder",+ "selectFolder": "Select this folder",+ "automationDraft": "New automation",+ "automationDraftHint": "Confirm the content, timing and model, then save to create this automation.",+ "automationName": "Name",+ "automationPrompt": "What to do",+ "automationInterval": "Interval (minutes)",+ "automationCron": "Schedule (Cron)",+ "automationTimezone": "Time zone",+ "automationInvalid": "Check the name, content and schedule.",+ "automationUnconfirmed": "The save result is unconfirmed. Check the automation list on your computer; this form will not create it again.",+ "returnToPlugin": "Return to plugin",+ "computerPreview": "Web preview from your computer",+ "previewFailed": "Could not load the preview. Check the computer connection and web service.",+ "simulatorOnComputer": "This computer hosts the simulator. Open the computer screen to view and control it.",+ "nativeStepHint": "Complete this step below",+ "shareMedia": "Share or save",+ "frequency_daily": "Daily",+ "frequency_weekdays": "Weekdays",+ "frequency_interval": "Interval",+ "frequency_custom": "Custom",+ "automationTime": "Time",+ "automationTimeInvalid": "Enter a 24-hour time, such as 09:00."+}diff --git a/apps/mobile/src/i18n/locales/ja/index.ts b/apps/mobile/src/i18n/locales/ja/index.tsindex 5a06acd366..e53a1ef086 100644--- a/apps/mobile/src/i18n/locales/ja/index.ts+++ b/apps/mobile/src/i18n/locales/ja/index.ts@@ -1,3 +1,4 @@+import plugins from './plugins.json';import taskTags from './taskTags.json';/*** 本 locale 的 catalog 组装:每个区域一个 JSON 文件、一个顶级 key,@@ -26,6 +27,7 @@ import startup from './startup.json';import update from './update.json';export default {+ plugins,taskTags,remoteDesktop,apiErrors,diff --git a/apps/mobile/src/i18n/locales/ja/plugins.json b/apps/mobile/src/i18n/locales/ja/plugins.jsonnew file mode 100644index 0000000000..bd38a9d408--- /dev/null+++ b/apps/mobile/src/i18n/locales/ja/plugins.json@@ -0,0 +1,90 @@+{+ "title": "プラグイン",+ "all": "すべて",+ "unread": "未読",+ "recent": "最近使用",+ "installed": "インストール済み",+ "search": "プラグインを検索",+ "computer": "コンピューターを選択",+ "allComputers": "すべてのコンピューター",+ "cancel": "キャンセル",+ "open": "開く",+ "confirm": "確認",+ "externalTitle": "外部リンクを開く",+ "openTask": "タスクを開く",+ "details": "プラグインの詳細",+ "detailsFor": "{{name}} の詳細",+ "offline": "コンピューターに接続されていません。再接続してください。",+ "notConnected": "未接続",+ "loadFailed": "詳細を読み込めませんでした。再試行してください。",+ "actionFailed": "操作が完了しませんでした。接続を確認してください。",+ "noResults": "一致するプラグインはありません。",+ "noPlugins": "このコンピューターにプラグインはありません。",+ "noComputer": "コンピューターに接続してプラグインを使用します。",+ "connectComputer": "コンピューターに接続",+ "listUnavailable": "一部の一覧を読み込めません。前回の内容を保持しています。",+ "selectPlugin": "プラグインを選択してください",+ "panel": "パネルを開く",+ "mainView": "ページを開く",+ "settings": "プラグイン設定",+ "useInTask": "タスクで使用",+ "newTask": "新規タスク",+ "chooseTask": "既存のタスクを開く",+ "taskHint": "タスクで要望を伝えると、Cindy が適切なプラグインを使用します。既存のタスクのモデルと権限は保持されます。",+ "noMobilePage": "モバイルページはまだありません。ツールはタスクで使用できます。",+ "enable": "有効にする",+ "disable": "無効にする",+ "pageUnconfirmed": "接続またはページの状態を確認できません。送信した操作は自動再送されません。元のタスクや保存内容を確認してください。",+ "reopen": "ページを開き直す",+ "loadingPage": "プラグインを開いています…",+ "searchTasks": "タスクを検索",+ "retry": "再試行",+ "noTasks": "このコンピューターにはまだタスクがありません",+ "taskDraft": "「{{name}}」プラグインを使って、",+ "taskSettings": "タスク設定",+ "taskModel": "タスクのモデル",+ "taskPermission": "タスクの権限",+ "followDefault": "既定に従う",+ "taskSettingsHint": "今後このプラグインが作成するタスクに適用されます。既存のタスクのモデルと権限は維持されます。",+ "permissionHint": "新しいプラグインタスクの権限を選択します。現在のタスクの権限は継承されません。",+ "autoPermissionHint": "自動承認では Cindy が権限要求を自動で判断します。今後のプラグインタスクに適用しますか?",+ "settingsReload": "設定を再読み込みして保存結果を確認",+ "modelsUnavailable": "パソコンのモデル一覧を利用できません。接続を確認して再試行してください。",+ "identityChanged": "パソコンの識別情報が変更されました",+ "identityChangedHint": "このパソコンの認証識別情報が変更されたため、設定を停止しました。パソコンを確認し、デバイスの識別情報を再登録してから接続してください。このカードで登録済みの識別情報を置き換えることはできません。",+ "connectAccount": "アカウントを接続",+ "computerAuthorization": "パソコンのコールバックが必要です",+ "computerAuthorizationHint": "この接続方式はパソコン上のコールバックを使用します。このカードのパソコン入口で接続し、戻って状態を確認してください。",+ "authorizationCheckHint": "設定手順の状態を確認してください。未確認の操作は自動で再送しません。",+ "connectionHost": "接続先(HTTPSドメイン)",+ "connectionToken": "接続トークン",+ "copyCode": "コードをコピー",+ "waitingAuthorization": "アカウント接続の完了を待っています…",+ "saveConfiguration": "設定を保存",+ "nativeSetupHint": "以下の設定はスマートフォンで完了できます。パソコンのローカルコールバックが必要なアカウント接続は、パソコンの入口から続行してください。",+ "chooseComputerFolder": "パソコンのフォルダを選択",+ "folderReadFailed": "フォルダを読み取れません。接続を確認するか、別のフォルダを選択してください。",+ "parentFolder": "上のフォルダ",+ "selectFolder": "このフォルダを選択",+ "automationDraft": "自動化を新規作成",+ "automationDraftHint": "内容、時刻、モデルを確認し、保存すると自動化が作成されます。",+ "automationName": "名前",+ "automationPrompt": "実行する内容",+ "automationInterval": "間隔(分)",+ "automationCron": "実行時刻(Cron)",+ "automationTimezone": "タイムゾーン",+ "automationInvalid": "名前、内容、実行時刻を確認してください。",+ "automationUnconfirmed": "保存結果を確認できません。パソコンの自動化一覧を確認してください。このフォームでは重複作成しません。",+ "returnToPlugin": "プラグインに戻る",+ "computerPreview": "パソコンからのウェブプレビュー",+ "previewFailed": "プレビューを読み込めません。パソコンの接続とウェブサービスを確認してください。",+ "simulatorOnComputer": "シミュレータはこのパソコンで実行されています。パソコンの画面に移動して確認・操作してください。",+ "nativeStepHint": "下でこの設定を完了できます",+ "shareMedia": "共有または保存",+ "frequency_daily": "毎日",+ "frequency_weekdays": "平日",+ "frequency_interval": "間隔",+ "frequency_custom": "カスタム",+ "automationTime": "実行時刻",+ "automationTimeInvalid": "09:00 のように24時間形式で入力してください。"+}diff --git a/apps/mobile/src/i18n/locales/ko/index.ts b/apps/mobile/src/i18n/locales/ko/index.tsindex 5a06acd366..e53a1ef086 100644--- a/apps/mobile/src/i18n/locales/ko/index.ts+++ b/apps/mobile/src/i18n/locales/ko/index.ts@@ -1,3 +1,4 @@+import plugins from './plugins.json';import taskTags from './taskTags.json';/*** 本 locale 的 catalog 组装:每个区域一个 JSON 文件、一个顶级 key,@@ -26,6 +27,7 @@ import startup from './startup.json';import update from './update.json';export default {+ plugins,taskTags,remoteDesktop,apiErrors,diff --git a/apps/mobile/src/i18n/locales/ko/plugins.json b/apps/mobile/src/i18n/locales/ko/plugins.jsonnew file mode 100644index 0000000000..5f351ee62e--- /dev/null+++ b/apps/mobile/src/i18n/locales/ko/plugins.json@@ -0,0 +1,90 @@+{+ "title": "플러그인",+ "all": "전체",+ "unread": "읽지 않음",+ "recent": "최근 사용",+ "installed": "설치됨",+ "search": "플러그인 검색",+ "computer": "컴퓨터 선택",+ "allComputers": "모든 컴퓨터",+ "cancel": "취소",+ "open": "열기",+ "confirm": "확인",+ "externalTitle": "외부 링크 열기",+ "openTask": "작업 열기",+ "details": "플러그인 정보",+ "detailsFor": "{{name}} 정보",+ "offline": "컴퓨터에 연결되어 있지 않습니다. 다시 연결해 주세요.",+ "notConnected": "연결 안 됨",+ "loadFailed": "정보를 불러오지 못했습니다. 다시 시도해 주세요.",+ "actionFailed": "작업이 완료되지 않았습니다. 연결을 확인해 주세요.",+ "noResults": "일치하는 플러그인이 없습니다.",+ "noPlugins": "이 컴퓨터에는 설치된 플러그인이 없습니다.",+ "noComputer": "컴퓨터에 연결하여 설치된 플러그인을 사용하세요.",+ "connectComputer": "컴퓨터 연결",+ "listUnavailable": "일부 목록을 불러올 수 없습니다. 이전 내용을 유지합니다.",+ "selectPlugin": "플러그인을 선택하세요",+ "panel": "패널 열기",+ "mainView": "페이지 열기",+ "settings": "플러그인 설정",+ "useInTask": "작업에서 사용",+ "newTask": "새 작업",+ "chooseTask": "기존 작업 열기",+ "taskHint": "작업에서 요청을 설명하면 Cindy가 적절한 플러그인을 사용합니다. 기존 작업의 모델과 권한은 유지됩니다.",+ "noMobilePage": "아직 모바일 페이지가 없습니다. 도구는 작업에서 사용할 수 있습니다.",+ "enable": "플러그인 활성화",+ "disable": "플러그인 비활성화",+ "pageUnconfirmed": "연결 또는 페이지 상태가 확인되지 않았습니다. 전송된 작업은 자동으로 다시 보내지 않습니다. 원래 작업이나 저장된 내용을 먼저 확인해 주세요.",+ "reopen": "페이지 다시 열기",+ "loadingPage": "플러그인 여는 중…",+ "searchTasks": "작업 검색",+ "retry": "다시 시도",+ "noTasks": "이 컴퓨터에 아직 작업이 없습니다",+ "taskDraft": "{{name}} 플러그인을 사용해서 ",+ "taskSettings": "작업 설정",+ "taskModel": "작업 모델",+ "taskPermission": "작업 권한",+ "followDefault": "기본값 따르기",+ "taskSettingsHint": "이후 플러그인이 만드는 작업에 적용됩니다. 기존 작업의 모델과 권한은 유지됩니다.",+ "permissionHint": "새 플러그인 작업의 권한을 선택하세요. 현재 작업의 권한을 자동으로 상속하지 않습니다.",+ "autoPermissionHint": "자동 승인은 Cindy가 권한 요청을 자동으로 판단하도록 허용합니다. 이후 플러그인 작업에 적용할까요?",+ "settingsReload": "설정을 다시 읽어 저장 여부 확인",+ "modelsUnavailable": "컴퓨터의 모델 목록을 사용할 수 없습니다. 연결을 확인한 후 다시 시도하세요.",+ "identityChanged": "컴퓨터 식별 정보 변경",+ "identityChangedHint": "컴퓨터의 인증 식별 정보가 변경되어 설정을 중단했습니다. 컴퓨터를 확인하고 장치 식별 정보를 다시 등록한 후 연결하세요. 이 카드에서는 등록된 식별 정보를 교체할 수 없습니다.",+ "connectAccount": "계정 연결",+ "computerAuthorization": "컴퓨터 콜백 필요",+ "computerAuthorizationHint": "이 연결 방식은 컴퓨터의 로컬 콜백을 사용합니다. 카드의 컴퓨터 진입점에서 연결을 완료하고 돌아와 상태를 확인하세요.",+ "authorizationCheckHint": "설정 단계의 상태를 확인하세요. 확인되지 않은 작업은 자동으로 재전송하지 않습니다.",+ "connectionHost": "연결 주소 (HTTPS 도메인)",+ "connectionToken": "연결 토큰",+ "copyCode": "코드 복사",+ "waitingAuthorization": "계정 연결 완료를 기다리는 중…",+ "saveConfiguration": "설정 저장",+ "nativeSetupHint": "아래 설정은 휴대폰에서 완료할 수 있습니다. 컴퓨터 로컬 콜백이 필요한 계정 연결은 컴퓨터 진입점을 통해 계속하세요.",+ "chooseComputerFolder": "컴퓨터의 폴더 선택",+ "folderReadFailed": "폴더를 읽을 수 없습니다. 연결을 확인하거나 다른 폴더를 선택하세요.",+ "parentFolder": "상위 폴더",+ "selectFolder": "이 폴더 선택",+ "automationDraft": "새 자동화",+ "automationDraftHint": "내용, 시간, 모델을 확인하고 저장하면 자동화가 생성됩니다.",+ "automationName": "이름",+ "automationPrompt": "실행할 내용",+ "automationInterval": "간격(분)",+ "automationCron": "실행 일정 (Cron)",+ "automationTimezone": "시간대",+ "automationInvalid": "이름, 내용, 실행 일정을 확인하세요.",+ "automationUnconfirmed": "저장 결과가 확인되지 않았습니다. 컴퓨터에서 자동화 목록을 확인하세요. 이 양식에서는 다시 생성하지 않습니다.",+ "returnToPlugin": "플러그인으로 돌아가기",+ "computerPreview": "컴퓨터의 웹 미리보기",+ "previewFailed": "미리보기를 불러올 수 없습니다. 컴퓨터 연결과 웹 서비스를 확인하세요.",+ "simulatorOnComputer": "시뮬레이터는 이 컴퓨터에서 실행됩니다. 컴퓨터 화면에서 확인하고 조작하세요.",+ "nativeStepHint": "아래에서 이 설정을 완료하세요",+ "shareMedia": "공유 또는 저장",+ "frequency_daily": "매일",+ "frequency_weekdays": "평일",+ "frequency_interval": "간격",+ "frequency_custom": "사용자 지정",+ "automationTime": "실행 시간",+ "automationTimeInvalid": "09:00과 같은 24시간 형식으로 입력하세요."+}diff --git a/apps/mobile/src/i18n/locales/zh-CN/index.ts b/apps/mobile/src/i18n/locales/zh-CN/index.tsindex 5a06acd366..e53a1ef086 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 plugins from './plugins.json';import taskTags from './taskTags.json';/*** 本 locale 的 catalog 组装:每个区域一个 JSON 文件、一个顶级 key,@@ -26,6 +27,7 @@ import startup from './startup.json';import update from './update.json';export default {+ plugins,taskTags,remoteDesktop,apiErrors,diff --git a/apps/mobile/src/i18n/locales/zh-CN/plugins.json b/apps/mobile/src/i18n/locales/zh-CN/plugins.jsonnew file mode 100644index 0000000000..194c701bc7--- /dev/null+++ b/apps/mobile/src/i18n/locales/zh-CN/plugins.json@@ -0,0 +1,90 @@+{+ "title": "插件",+ "all": "全部",+ "unread": "未读",+ "recent": "最近使用",+ "installed": "已安装",+ "search": "搜索插件",+ "computer": "选择电脑",+ "allComputers": "所有电脑",+ "cancel": "取消",+ "open": "打开",+ "confirm": "确认",+ "externalTitle": "打开外部链接",+ "openTask": "打开任务",+ "details": "插件详情",+ "detailsFor": "查看 {{name}} 的详情",+ "offline": "电脑未连接,连接后可继续使用。",+ "notConnected": "未连接",+ "loadFailed": "插件信息加载失败,请稍后重试。",+ "actionFailed": "操作未完成,请检查连接后重试。",+ "noResults": "没有找到匹配的插件。",+ "noPlugins": "这台电脑还没有安装插件。",+ "noComputer": "连接电脑,使用已经安装的插件。",+ "connectComputer": "连接电脑",+ "listUnavailable": "部分电脑的插件列表暂时无法读取,已保留上次内容。",+ "selectPlugin": "选择插件开始使用",+ "panel": "打开面板",+ "mainView": "打开页面",+ "settings": "插件设置",+ "useInTask": "在任务中使用",+ "newTask": "新建任务",+ "chooseTask": "打开已有任务",+ "taskHint": "在任务中说明你的需求,Cindy 会调用适合的插件。已有任务继续使用原来的模型和权限。",+ "noMobilePage": "此插件尚未提供手机页面,可在任务中使用其工具。",+ "enable": "启用插件",+ "disable": "停用插件",+ "pageUnconfirmed": "连接或页面状态尚未确认。已发出的操作不会自动重发,请先检查原任务或内容是否已保存。",+ "reopen": "重新打开页面",+ "loadingPage": "正在打开插件…",+ "searchTasks": "搜索任务",+ "retry": "重试",+ "noTasks": "这台电脑还没有任务",+ "taskDraft": "使用「{{name}}」插件,",+ "taskSettings": "任务设置",+ "taskModel": "任务模型",+ "taskPermission": "任务权限",+ "followDefault": "跟随默认",+ "taskSettingsHint": "只影响插件之后创建的任务;已有任务保留原来的模型和权限。",+ "permissionHint": "选择插件新建任务的权限,不会自动继承当前任务的权限。",+ "autoPermissionHint": "自动审批会允许 Cindy 根据请求自动判断权限。确认用于之后的插件任务?",+ "settingsReload": "重新读取设置,确认原操作是否已保存",+ "modelsUnavailable": "电脑上的模型目录暂不可用,请检查连接后重试。",+ "identityChanged": "电脑身份发生变化",+ "identityChangedHint": "这台电脑的授权身份与上次不同,已停止配置。请先核实电脑并重新登记设备身份,再连接;这里不能确认或替换已登记的身份。",+ "connectAccount": "连接账号",+ "computerAuthorization": "需要电脑上的回调",+ "computerAuthorizationHint": "此账号连接方式使用电脑本地回调。请使用此卡片的电脑入口完成连接,然后回到这里查看状态。",+ "authorizationCheckHint": "请查看此配置步骤的状态;未确认的操作不会自动重发。",+ "connectionHost": "连接地址(HTTPS 域名)",+ "connectionToken": "连接密钥",+ "copyCode": "复制验证码",+ "waitingAuthorization": "正在等待账号连接完成…",+ "saveConfiguration": "保存配置",+ "nativeSetupHint": "可在手机完成下方配置。使用电脑本地回调的账号连接,请通过电脑入口继续。",+ "chooseComputerFolder": "选择电脑上的文件夹",+ "folderReadFailed": "读取目录失败,请检查连接或选择其他目录。",+ "parentFolder": "上一级",+ "selectFolder": "选择此文件夹",+ "automationDraft": "新建自动化",+ "automationDraftHint": "确认内容、时间和模型后保存,才会创建自动化。",+ "automationName": "名称",+ "automationPrompt": "要执行的内容",+ "automationInterval": "间隔(分钟)",+ "automationCron": "执行时间(Cron)",+ "automationTimezone": "时区",+ "automationInvalid": "请检查名称、内容和执行时间。",+ "automationUnconfirmed": "保存结果尚未确认。请在电脑上查看自动化列表;这里不会重复创建。",+ "returnToPlugin": "返回插件",+ "computerPreview": "来自电脑的网页预览",+ "previewFailed": "预览加载失败,请检查电脑连接和网页服务。",+ "simulatorOnComputer": "模拟器由这台电脑承载,请进入电脑画面查看和操作。",+ "nativeStepHint": "在下方完成此项配置",+ "shareMedia": "分享或保存",+ "frequency_daily": "每天",+ "frequency_weekdays": "工作日",+ "frequency_interval": "按间隔",+ "frequency_custom": "自定义",+ "automationTime": "执行时间",+ "automationTimeInvalid": "请输入 24 小时时间,例如 09:00。"+}diff --git a/apps/mobile/src/i18n/locales/zh-TW/index.ts b/apps/mobile/src/i18n/locales/zh-TW/index.tsindex 5a06acd366..e53a1ef086 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 plugins from './plugins.json';import taskTags from './taskTags.json';/*** 本 locale 的 catalog 组装:每个区域一个 JSON 文件、一个顶级 key,@@ -26,6 +27,7 @@ import startup from './startup.json';import update from './update.json';export default {+ plugins,taskTags,remoteDesktop,apiErrors,diff --git a/apps/mobile/src/i18n/locales/zh-TW/plugins.json b/apps/mobile/src/i18n/locales/zh-TW/plugins.jsonnew file mode 100644index 0000000000..19e4db390b--- /dev/null+++ b/apps/mobile/src/i18n/locales/zh-TW/plugins.json@@ -0,0 +1,90 @@+{+ "title": "插件",+ "all": "全部",+ "unread": "未讀",+ "recent": "最近使用",+ "installed": "已安裝",+ "search": "搜尋插件",+ "computer": "選擇電腦",+ "allComputers": "所有電腦",+ "cancel": "取消",+ "open": "開啟",+ "confirm": "確認",+ "externalTitle": "開啟外部連結",+ "openTask": "開啟任務",+ "details": "插件詳細資訊",+ "detailsFor": "查看 {{name}} 的詳細資訊",+ "offline": "電腦未連線,連線後即可繼續使用。",+ "notConnected": "未連線",+ "loadFailed": "無法載入插件資訊,請稍後重試。",+ "actionFailed": "操作未完成,請檢查連線後重試。",+ "noResults": "沒有符合的插件。",+ "noPlugins": "這台電腦尚未安裝插件。",+ "noComputer": "連接電腦,使用已安裝的插件。",+ "connectComputer": "連接電腦",+ "listUnavailable": "部分電腦的清單暫時無法讀取,已保留上次內容。",+ "selectPlugin": "選擇插件開始使用",+ "panel": "開啟面板",+ "mainView": "開啟頁面",+ "settings": "插件設定",+ "useInTask": "在任務中使用",+ "newTask": "新增任務",+ "chooseTask": "開啟現有任務",+ "taskHint": "在任務中說明需求,Cindy 會使用適合的插件。現有任務保留原有模型與權限。",+ "noMobilePage": "此插件尚未提供手機頁面,可在任務中使用其工具。",+ "enable": "啟用插件",+ "disable": "停用插件",+ "pageUnconfirmed": "連線或頁面狀態尚未確認。已送出的操作不會自動重送,請先檢查原任務或內容是否已儲存。",+ "reopen": "重新開啟頁面",+ "loadingPage": "正在開啟插件…",+ "searchTasks": "搜尋任務",+ "retry": "重試",+ "noTasks": "這台電腦還沒有任務",+ "taskDraft": "使用「{{name}}」插件,",+ "taskSettings": "任務設定",+ "taskModel": "任務模型",+ "taskPermission": "任務權限",+ "followDefault": "跟隨預設",+ "taskSettingsHint": "只影響插件之後建立的任務;現有任務保留原來的模型和權限。",+ "permissionHint": "選擇插件新建任務的權限,不會自動繼承目前任務的權限。",+ "autoPermissionHint": "自動審批會允許 Cindy 根據請求自動判斷權限。確認用於之後的插件任務?",+ "settingsReload": "重新讀取設定,確認原操作是否已儲存",+ "modelsUnavailable": "電腦上的模型目錄暫時無法使用,請檢查連線後重試。",+ "identityChanged": "電腦身分已變更",+ "identityChangedHint": "這台電腦的授權身分與上次不同,已停止設定。請先核實電腦並重新登記裝置身分,再連線;此處不能確認或取代已登記的身分。",+ "connectAccount": "連接帳號",+ "computerAuthorization": "需要電腦上的回呼",+ "computerAuthorizationHint": "此帳號連接方式使用電腦本機回呼。請使用此卡片的電腦入口完成連接,再回到這裡查看狀態。",+ "authorizationCheckHint": "請查看此設定步驟的狀態;未確認的操作不會自動重送。",+ "connectionHost": "連接地址(HTTPS 網域)",+ "connectionToken": "連接金鑰",+ "copyCode": "複製驗證碼",+ "waitingAuthorization": "正在等待帳號連接完成…",+ "saveConfiguration": "儲存設定",+ "nativeSetupHint": "可在手機完成下方設定。使用電腦本機回呼的帳號連線,請透過電腦入口繼續。",+ "chooseComputerFolder": "選擇電腦上的資料夾",+ "folderReadFailed": "讀取目錄失敗,請檢查連線或選擇其他目錄。",+ "parentFolder": "上一層",+ "selectFolder": "選擇此資料夾",+ "automationDraft": "新增自動化",+ "automationDraftHint": "確認內容、時間和模型後儲存,才會建立自動化。",+ "automationName": "名稱",+ "automationPrompt": "要執行的內容",+ "automationInterval": "間隔(分鐘)",+ "automationCron": "執行時間(Cron)",+ "automationTimezone": "時區",+ "automationInvalid": "請檢查名稱、內容和執行時間。",+ "automationUnconfirmed": "儲存結果尚未確認。請在電腦上查看自動化清單;此處不會重複建立。",+ "returnToPlugin": "返回插件",+ "computerPreview": "來自電腦的網頁預覽",+ "previewFailed": "預覽載入失敗,請檢查電腦連線和網頁服務。",+ "simulatorOnComputer": "模擬器由這台電腦承載,請進入電腦畫面查看和操作。",+ "nativeStepHint": "在下方完成此項設定",+ "shareMedia": "分享或儲存",+ "frequency_daily": "每天",+ "frequency_weekdays": "工作日",+ "frequency_interval": "按間隔",+ "frequency_custom": "自訂",+ "automationTime": "執行時間",+ "automationTimeInvalid": "請輸入 24 小時時間,例如 09:00。"+}diff --git a/apps/mobile/src/plugins/PluginCardActions.tsx b/apps/mobile/src/plugins/PluginCardActions.tsxnew file mode 100644index 0000000000..e5fb79ed0c--- /dev/null+++ b/apps/mobile/src/plugins/PluginCardActions.tsx@@ -0,0 +1,452 @@+import { useEffect, useRef, useState } from "react";+import {+ Alert,+ AppState,+ Linking,+ KeyboardAvoidingView,+ Modal,+ Platform,+ Pressable,+ StyleSheet,+ View,+} from "react-native";+import { useIsFocused } from "expo-router";+import { useTranslation } from "react-i18next";+import {+ REMOTE_RESOURCE_INVOKE_CHANNEL,+ type PluginPageConfirm,+ type PluginPagePoll,+} from "@cindy/device-link";+import { Text, TextInput } from "@/components/AppText";+import { useDeviceLink } from "@/device-link/DeviceLinkContext";+import {+ getMobileAuthOwner,+ isMobileAuthOwnerCurrent,+} from "@/auth/authOwnerGeneration";+import {+ fontWeight,+ lineHeight,+ radius,+ spacing,+ typeScale,+ useThemedStyles,+ type ThemeColors,+} from "@/theme";+import { invokePlugin } from "./pluginClient";++interface Action {+ id: string;+ label: string;+ prompt?: string;+ url?: string;+ disabled: boolean;+}+function parse(+ value: unknown,+): { pluginId: string; revision: string; items: Action[] } | null {+ if (!value || typeof value !== "object") return null;+ const data = value as Record<string, unknown>;+ if (+ typeof data.pluginId !== "string" ||+ typeof data.revision !== "string" ||+ !Array.isArray(data.items) ||+ data.items.length > 64+ )+ return null;+ const items = data.items.filter(+ (item): item is Action =>+ item &&+ typeof item === "object" &&+ typeof item.id === "string" &&+ typeof item.label === "string" &&+ item.label.length <= 2048 &&+ typeof item.disabled === "boolean" &&+ (item.prompt === undefined || typeof item.prompt === "string") &&+ (item.url === undefined || typeof item.url === "string"),+ );+ return { pluginId: data.pluginId, revision: data.revision, items };+}+export function PluginCardActions({+ data,+ deviceId,+ sessionId,+ callId,+}: {+ data: unknown;+ deviceId?: string;+ sessionId: string;+ callId: string;+}) {+ const parsed = parse(data);+ return parsed && deviceId ? (+ <CardControls+ key={`${deviceId}:${sessionId}:${callId}:${parsed.pluginId}`}+ {...parsed}+ deviceId={deviceId}+ sessionId={sessionId}+ callId={callId}+ />+ ) : null;+}+function CardControls({+ pluginId,+ revision,+ items,+ deviceId,+ sessionId,+ callId,+}: {+ pluginId: string;+ revision: string;+ items: Action[];+ deviceId: string;+ sessionId: string;+ callId: string;+}) {+ const { t } = useTranslation(),+ styles = useThemedStyles(makeStyles);+ const { invoke, status } = useDeviceLink();+ const focused = useIsFocused(),+ focusedRef = useRef(focused);+ focusedRef.current = focused;+ const lifetime = useRef({ active: true, owner: getMobileAuthOwner() });+ const sending = useRef(false);+ const revisionRef = useRef(revision);+ revisionRef.current = revision;+ const page = useRef<string | undefined>(undefined);+ const [lease, setLease] = useState<string>();+ const [foreground, setForeground] = useState(+ AppState.currentState === "active",+ );+ const [prompt, setPrompt] = useState<Action>();+ const [draft, setDraft] = useState("");+ const [confirm, setConfirm] = useState<PluginPageConfirm>();+ const [busy, setBusy] = useState(false),+ [unknown, setUnknown] = useState(false),+ [answering, setAnswering] = useState(false);+ const current = () =>+ lifetime.current.active && isMobileAuthOwnerCurrent(lifetime.current.owner);+ useEffect(() => {+ sending.current = false;+ setBusy(false);+ setUnknown(false);+ }, [revision]);+ useEffect(() => {+ const token = { active: true, owner: getMobileAuthOwner() };+ lifetime.current = token;+ const listener = AppState.addEventListener("change", (state) => {+ setForeground(state === "active");+ setConfirm(undefined);+ });+ return () => {+ token.active = false;+ listener.remove();+ if (page.current && isMobileAuthOwnerCurrent(lifetime.current.owner))+ void invokePlugin(invoke, deviceId, pluginId, "close", {+ pageId: page.current,+ }).catch(() => {});+ };+ }, [invoke, deviceId, pluginId]);+ useEffect(() => {+ if (!lease) return;+ if (!focused || !foreground || status !== "online") {+ if (current() && status === "online")+ void invokePlugin(invoke, deviceId, pluginId, "suspend", {+ pageId: lease,+ }).catch(() => {});+ return;+ }+ let disposed = false,+ timer: ReturnType<typeof setTimeout> | undefined;+ const poll = async () => {+ if (disposed || !current()) return;+ try {+ const result = await invokePlugin<PluginPagePoll>(+ invoke,+ deviceId,+ pluginId,+ "poll",+ { pageId: lease, after: 0 },+ );+ if (!disposed && current()) setConfirm(result.confirms[0]);+ } catch {+ if (!disposed && current()) {+ setUnknown(true);+ setConfirm(undefined);+ }+ }+ if (!disposed && current()) timer = setTimeout(() => void poll(), 1000);+ };+ void poll();+ return () => {+ disposed = true;+ if (timer) clearTimeout(timer);+ };+ }, [lease, focused, foreground, status, invoke, deviceId, pluginId]);+ const submit = async (action: Action, text?: string) => {+ if (+ sending.current ||+ busy ||+ unknown ||+ action.disabled ||+ status !== "online" ||+ !focusedRef.current ||+ AppState.currentState !== "active"+ )+ return;+ const token = lifetime.current,+ expectedRevision = revision;+ const valid = () =>+ token.active &&+ lifetime.current === token &&+ isMobileAuthOwnerCurrent(token.owner);+ sending.current = true;+ setBusy(true);+ try {+ if (!page.current) {+ const opened = await invokePlugin<{ pageId: string }>(+ invoke,+ deviceId,+ pluginId,+ "open-interaction",+ );+ if (!valid()) {+ if (isMobileAuthOwnerCurrent(token.owner))+ void invokePlugin(+ invoke,+ deviceId,+ pluginId,+ "close",+ opened,+ ).catch(() => {});+ return;+ }+ page.current = opened.pageId;+ setLease(opened.pageId);+ }+ await invoke(+ deviceId,+ REMOTE_RESOURCE_INVOKE_CHANNEL,+ [+ {+ client: { protocolVersion: 1, primitives: ["plugin-card-actions"] },+ collectionId: "plugin-results",+ resourceRef: {+ collectionId: "plugin-results",+ kind: "card",+ id: JSON.stringify([sessionId, callId]),+ },+ actionId: action.id,+ input: {+ revision,+ pageId: page.current,+ ...(text !== undefined ? { prompt: text } : {}),+ },+ },+ ],+ {+ preSend: () => {+ if (+ !valid() ||+ !focusedRef.current ||+ AppState.currentState !== "active" ||+ revisionRef.current !== expectedRevision+ )+ throw new Error("PLUGIN_PAGE_CLOSED");+ },+ },+ );+ if (valid() && revisionRef.current === expectedRevision) {+ setPrompt(undefined);+ setDraft("");+ sending.current = false;+ setBusy(false);+ }+ // A known delivery permits a new deliberate click, never an automatic replay.+ } catch {+ if (valid() && revisionRef.current === expectedRevision) setUnknown(true);+ }+ };+ const choose = (action: Action) => {+ if (action.url) {+ let url: URL;+ try {+ url = new URL(action.url);+ } catch {+ return;+ }+ if (!["http:", "https:"].includes(url.protocol)) return;+ Alert.alert(t("plugins.externalTitle"), url.href, [+ { text: t("plugins.cancel"), style: "cancel" },+ {+ text: t("plugins.open"),+ onPress: () => {+ void Linking.openURL(url.href).catch(() => setUnknown(true));+ },+ },+ ]);+ } else if (action.prompt !== undefined) {+ setPrompt(action);+ setDraft("");+ } else void submit(action);+ };+ const answer = async (confirmed: boolean) => {+ if (!confirm || answering) return;+ setAnswering(true);+ try {+ await invokePlugin(invoke, deviceId, pluginId, "answer", {+ pageId: page.current,+ confirmId: confirm.id,+ confirmed,+ });+ if (current()) setConfirm(undefined);+ } catch {+ if (current()) {+ setUnknown(true);+ setConfirm(undefined);+ }+ } finally {+ if (current()) setAnswering(false);+ }+ };+ return (+ <View style={styles.root}>+ <View style={styles.actions}>+ {items.map((action) => (+ <Pressable+ key={action.id}+ accessibilityRole="button"+ disabled={action.disabled || busy || unknown || status !== "online"}+ style={styles.button}+ onPress={() => choose(action)}+ >+ <Text style={styles.label}>{action.label}</Text>+ </Pressable>+ ))}+ </View>+ {unknown ? (+ <Text style={styles.note}>{t("plugins.pageUnconfirmed")}</Text>+ ) : null}+ <Modal+ visible={Boolean(focused && foreground && (prompt || confirm))}+ transparent+ onRequestClose={() => {+ if (confirm) void answer(false);+ else setPrompt(undefined);+ }}+ >+ <KeyboardAvoidingView+ behavior={Platform.OS === "ios" ? "padding" : undefined}+ style={styles.scrim}+ >+ <View style={styles.dialog} accessibilityViewIsModal>+ <Text style={styles.title}>{confirm?.title ?? prompt?.label}</Text>+ {confirm ? (+ <Text style={styles.body}>{confirm.body}</Text>+ ) : (+ <TextInput+ autoFocus+ multiline+ value={draft}+ onChangeText={setDraft}+ maxLength={2000}+ placeholder={prompt?.prompt}+ style={styles.input}+ />+ )}+ <View style={styles.actions}>+ <Pressable+ style={styles.button}+ disabled={answering}+ onPress={() => {+ if (confirm) void answer(false);+ else setPrompt(undefined);+ }}+ >+ <Text style={styles.label}>+ {confirm?.cancelText ?? t("plugins.cancel")}+ </Text>+ </Pressable>+ <Pressable+ style={styles.button}+ disabled={+ answering || (!confirm && (!draft.trim() || busy || unknown))+ }+ onPress={() => {+ if (confirm) void answer(true);+ else if (prompt) void submit(prompt, draft.trim());+ }}+ >+ <Text style={[styles.label, confirm?.danger && styles.danger]}>+ {confirm?.confirmText ?? t("plugins.confirm")}+ </Text>+ </Pressable>+ </View>+ </View>+ </KeyboardAvoidingView>+ </Modal>+ </View>+ );+}+const makeStyles = (c: ThemeColors) =>+ StyleSheet.create({+ root: { gap: spacing.sm },+ actions: { flexDirection: "row", flexWrap: "wrap", gap: spacing.sm },+ button: {+ minHeight: 44,+ padding: spacing.md,+ borderRadius: radius.pill,+ justifyContent: "center",+ backgroundColor: c.surfaceChip,+ },+ label: {+ color: c.textPrimary,+ fontSize: typeScale.body,+ lineHeight: lineHeight.body,+ fontWeight: fontWeight.medium,+ },+ note: {+ color: c.textSecondary,+ fontSize: typeScale.footnote,+ lineHeight: lineHeight.caption,+ fontWeight: fontWeight.regular,+ },+ body: {+ color: c.textPrimary,+ fontSize: typeScale.bodySmall,+ lineHeight: lineHeight.bodySmall,+ fontWeight: fontWeight.regular,+ },+ title: {+ color: c.textPrimary,+ fontSize: typeScale.title,+ lineHeight: lineHeight.title,+ fontWeight: fontWeight.semibold,+ },+ input: {+ color: c.textPrimary,+ fontSize: typeScale.bodySmall,+ lineHeight: lineHeight.bodySmall,+ fontWeight: fontWeight.regular,+ minHeight: 100,+ padding: spacing.md,+ borderRadius: radius.control,+ backgroundColor: c.surface,+ },+ danger: { color: c.destructive },+ scrim: {+ flex: 1,+ alignItems: "center",+ justifyContent: "center",+ padding: spacing.lg,+ backgroundColor: c.overlay,+ },+ dialog: {+ backgroundColor: c.surfaceElevated,+ padding: spacing.lg,+ gap: spacing.md,+ borderRadius: radius.container,+ width: "100%",+ maxWidth: 420,+ },+ });diff --git a/apps/mobile/src/plugins/PluginDirectoryPicker.tsx b/apps/mobile/src/plugins/PluginDirectoryPicker.tsxnew file mode 100644index 0000000000..487139e422--- /dev/null+++ b/apps/mobile/src/plugins/PluginDirectoryPicker.tsx@@ -0,0 +1,260 @@+import { useEffect, useRef, useState } from "react";+import {+ ActivityIndicator,+ Pressable,+ ScrollView,+ StyleSheet,+ View,+} from "react-native";+import { Folder, ChevronLeft } from "lucide-react-native";+import { useTranslation } from "react-i18next";+import type { PluginDirectoryRequest } from "@cindy/device-link";+import { Text } from "@/components/AppText";+import { useDeviceLink } from "@/device-link/DeviceLinkContext";+import type { RemoteDirectoryListResult } from "@/device-link/mobileMakerTransport";+import {+ getMobileAuthOwner,+ isMobileAuthOwnerCurrent,+} from "@/auth/authOwnerGeneration";+import { SheetModal } from "@/session/SheetModal";+import {+ fontWeight,+ iconSize,+ iconStroke,+ lineHeight,+ spacing,+ typeScale,+ useTheme,+ useThemedStyles,+ type ThemeColors,+} from "@/theme";++/** Paths are displayed only in trusted native UI and submitted only after an explicit selection. */+export function PluginDirectoryPicker({+ request,+ deviceId,+ onAnswer,+}: {+ request: PluginDirectoryRequest;+ deviceId: string;+ onAnswer(path: string | null): Promise<void>;+}) {+ const { t } = useTranslation(),+ { colors } = useTheme(),+ styles = useThemedStyles(makeStyles);+ const link = useDeviceLink(),+ owner = useRef(getMobileAuthOwner()).current;+ const liveEpoch = useRef(link.connectionEpoch);+ liveEpoch.current = link.connectionEpoch;+ const live = useRef(true),+ generation = useRef(0),+ lock = useRef(false);+ const [directory, setDirectory] = useState<RemoteDirectoryListResult>();+ const [loading, setLoading] = useState(false),+ [busy, setBusy] = useState(false),+ [failed, setFailed] = useState(false);+ useEffect(+ () => () => {+ live.current = false;+ generation.current++;+ },+ [],+ );+ const browse = async (path: string) => {+ if (lock.current) return;+ const current = ++generation.current,+ epoch = link.connectionEpoch;+ const assertCurrent = () => {+ if (+ !live.current ||+ current !== generation.current ||+ !isMobileAuthOwnerCurrent(owner) ||+ liveEpoch.current !== epoch ||+ Date.now() >= request.expiresAt+ )+ throw new Error("PLUGIN_DIRECTORY_CLOSED");+ };+ setLoading(true);+ setFailed(false);+ try {+ const result = await link.invoke<RemoteDirectoryListResult>(+ deviceId,+ "fs:list-dir",+ [{ path }],+ { preSend: assertCurrent },+ );+ assertCurrent();+ if (+ !result ||+ typeof result.resolvedPath !== "string" ||+ !Array.isArray(result.entries)+ )+ throw new Error("INVALID_DIRECTORY");+ setDirectory(result);+ } catch {+ if (live.current && current === generation.current) {+ setFailed(true);+ setDirectory(undefined);+ }+ } finally {+ if (live.current && current === generation.current) setLoading(false);+ }+ };+ useEffect(() => {+ void browse("~");+ }, []);+ const answer = async (path: string | null) => {+ if (lock.current) return;+ lock.current = true;+ setBusy(true);+ try {+ await onAnswer(path);+ } catch {+ if (live.current) setFailed(true);+ } finally {+ if (live.current) setBusy(false);+ lock.current = false;+ }+ };+ return (+ <SheetModal+ visible+ onRequestClose={() => void answer(null)}+ onBackdropPress={() => {}}+ >+ <View style={styles.sheet}>+ <Text style={styles.title}>{request.ghostName}</Text>+ <Text style={styles.body}>{t("plugins.chooseComputerFolder")}</Text>+ {request.purpose ? (+ <Text style={styles.hint}>{request.purpose}</Text>+ ) : null}+ {directory ? (+ <Text style={styles.hint} selectable>+ {directory.resolvedPath}+ </Text>+ ) : null}+ {loading ? <ActivityIndicator color={colors.textSecondary} /> : null}+ {failed ? (+ <Text style={styles.hint}>{t("plugins.folderReadFailed")}</Text>+ ) : null}+ <ScrollView style={styles.list}>+ {directory?.parent ? (+ <Pressable+ accessibilityRole="button"+ disabled={busy || loading}+ style={styles.row}+ onPress={() => void browse(directory.parent!)}+ >+ <ChevronLeft+ color={colors.textPrimary}+ size={iconSize.action}+ strokeWidth={iconStroke.regular}+ />+ <Text style={styles.body}>{t("plugins.parentFolder")}</Text>+ </Pressable>+ ) : null}+ {directory?.drives+ ?.filter((drive) => !drive.current)+ .map((drive) => (+ <Pressable+ key={drive.path}+ accessibilityRole="button"+ disabled={busy || loading}+ style={styles.row}+ onPress={() => void browse(drive.path)}+ >+ <Folder+ color={colors.textSecondary}+ size={iconSize.action}+ strokeWidth={iconStroke.regular}+ />+ <Text style={styles.body}>{drive.name}</Text>+ </Pressable>+ ))}+ {directory?.entries+ .filter((entry) => entry.kind === "dir" || entry.kind === "symlink")+ .map((entry) => (+ <Pressable+ key={entry.path}+ accessibilityRole="button"+ disabled={busy || loading}+ style={styles.row}+ onPress={() => void browse(entry.path)}+ >+ <Folder+ color={colors.textSecondary}+ size={iconSize.action}+ strokeWidth={iconStroke.regular}+ />+ <Text style={styles.body}>{entry.name}</Text>+ </Pressable>+ ))}+ </ScrollView>+ <View style={styles.buttons}>+ <Pressable+ accessibilityRole="button"+ disabled={busy}+ style={styles.row}+ onPress={() => void answer(null)}+ >+ <Text style={styles.body}>{t("plugins.cancel")}</Text>+ </Pressable>+ {failed ? (+ <Pressable+ accessibilityRole="button"+ disabled={busy || loading}+ style={styles.row}+ onPress={() => void browse("~")}+ >+ <Text style={styles.body}>{t("plugins.retry")}</Text>+ </Pressable>+ ) : null}+ <Pressable+ accessibilityRole="button"+ disabled={busy || loading || !directory || failed}+ style={styles.row}+ onPress={() => directory && void answer(directory.resolvedPath)}+ >+ <Text style={styles.body}>{t("plugins.selectFolder")}</Text>+ </Pressable>+ </View>+ </View>+ </SheetModal>+ );+}+const makeStyles = (colors: ThemeColors) =>+ StyleSheet.create({+ sheet: {+ backgroundColor: colors.surfaceElevated,+ padding: spacing.lg,+ gap: spacing.md,+ maxHeight: "85%",+ },+ list: { flexShrink: 1 },+ buttons: { flexDirection: "row", gap: spacing.md, flexWrap: "wrap" },+ row: {+ minHeight: 44,+ paddingVertical: spacing.sm,+ flexDirection: "row",+ alignItems: "center",+ gap: spacing.sm,+ },+ title: {+ fontSize: typeScale.title,+ lineHeight: lineHeight.title,+ fontWeight: fontWeight.semibold,+ color: colors.textPrimary,+ },+ body: {+ fontSize: typeScale.body,+ lineHeight: lineHeight.body,+ fontWeight: fontWeight.regular,+ color: colors.textPrimary,+ },+ hint: {+ fontSize: typeScale.footnote,+ lineHeight: lineHeight.bodySmall,+ fontWeight: fontWeight.regular,+ color: colors.textTertiary,+ },+ });diff --git a/apps/mobile/src/plugins/PluginMediaViewer.tsx b/apps/mobile/src/plugins/PluginMediaViewer.tsxnew file mode 100644index 0000000000..97b6937f86--- /dev/null+++ b/apps/mobile/src/plugins/PluginMediaViewer.tsx@@ -0,0 +1,174 @@+import { useEffect, useMemo, useRef, useState } from "react";+import {+ ActivityIndicator,+ Alert,+ Modal,+ Pressable,+ StyleSheet,+ View,+} from "react-native";+import { useTranslation } from "react-i18next";+import { useSafeAreaInsets } from "react-native-safe-area-context";+import * as Sharing from "expo-sharing";+import type {+ PluginNativeIntent,+ PluginPageFetchResult,+} from "@cindy/device-link";+import { Text } from "@/components/AppText";+import { ImageLightbox } from "@/session/ImageLightbox";+import { buildMediaPayload } from "@/session/messagePayload";+import { lightboxImagesForPayload } from "@/session/messageGallery";+import { RemoteMediaPlayerWebView } from "@/session/mediaPlayerWebView";+import {+ fontWeight,+ lineHeight,+ spacing,+ typeScale,+ useTheme,+ useThemedStyles,+ type ThemeColors,+} from "@/theme";+import { readPluginMediaFile } from "./pluginMediaFile";++export function PluginMediaViewer({+ intent,+ read,+ onClose,+}: {+ intent: Extract<PluginNativeIntent, { kind: "media" }>;+ read(path: string, offset: number): Promise<PluginPageFetchResult>;+ onClose(): void;+}) {+ const { t } = useTranslation(),+ { colors } = useTheme(),+ styles = useThemedStyles(makeStyles),+ insets = useSafeAreaInsets();+ const [media, setMedia] =+ useState<Awaited<ReturnType<typeof readPluginMediaFile>>>(),+ [failed, setFailed] = useState(false);+ const sharing = useRef<Promise<void> | undefined>(undefined),+ alive = useRef(true);+ useEffect(() => {+ const abort = new AbortController();+ let owned: typeof media;+ void readPluginMediaFile(intent.path, intent.mediaKind, read, abort.signal)+ .then((value) => {+ owned = value;+ if (abort.signal.aborted) value.close();+ else setMedia(value);+ })+ .catch(() => {+ if (!abort.signal.aborted) setFailed(true);+ });+ return () => {+ alive.current = false;+ abort.abort();+ void Promise.resolve(sharing.current)+ .finally(() => owned?.close())+ .catch(() => {});+ };+ }, [intent.id]);+ const images = useMemo(+ () =>+ media+ ? lightboxImagesForPayload(+ [],+ buildMediaPayload(+ { kind: "image", url: media.uri, previewable: true },+ intent.ghostName,+ ),+ )+ : [],+ [media, intent.ghostName],+ );+ const share = async () => {+ if (!media || !alive.current || sharing.current) return;+ const work = Sharing.shareAsync(media.uri, { mimeType: media.mime });+ sharing.current = work;+ try {+ await work;+ } catch {+ if (alive.current) Alert.alert(t("plugins.actionFailed"));+ } finally {+ if (sharing.current === work) sharing.current = undefined;+ }+ };+ if (media && intent.mediaKind === "image")+ return (+ <ImageLightbox+ images={images}+ initialUrl={media.uri}+ onClose={onClose}+ onShareImage={share}+ showFileHeader+ />+ );+ return (+ <Modal visible animationType="slide" onRequestClose={onClose}>+ <View+ style={[+ styles.root,+ {+ paddingTop: insets.top,+ paddingBottom: insets.bottom,+ paddingLeft: insets.left,+ paddingRight: insets.right,+ },+ ]}+ >+ <View style={styles.header}>+ <Pressable+ accessibilityRole="button"+ style={styles.button}+ onPress={onClose}+ >+ <Text style={styles.body}>{t("plugins.returnToPlugin")}</Text>+ </Pressable>+ {media ? (+ <Pressable+ accessibilityRole="button"+ style={styles.button}+ onPress={() => void share()}+ onLongPress={() => void share()}+ >+ <Text style={styles.body}>{t("plugins.shareMedia")}</Text>+ </Pressable>+ ) : null}+ </View>+ {media ? (+ <RemoteMediaPlayerWebView+ kind="video"+ url={media.uri}+ mimeType={media.mime}+ title={intent.ghostName}+ style={styles.root}+ />+ ) : failed ? (+ <Text style={styles.body}>{t("plugins.previewFailed")}</Text>+ ) : (+ <ActivityIndicator color={colors.textSecondary} />+ )}+ </View>+ </Modal>+ );+}+const makeStyles = (colors: ThemeColors) =>+ StyleSheet.create({+ root: { flex: 1, backgroundColor: colors.surface },+ header: {+ flexDirection: "row",+ justifyContent: "space-between",+ paddingHorizontal: spacing.md,+ },+ button: {+ minHeight: 44,+ justifyContent: "center",+ paddingHorizontal: spacing.sm,+ },+ body: {+ fontSize: typeScale.body,+ lineHeight: lineHeight.body,+ fontWeight: fontWeight.regular,+ color: colors.textPrimary,+ },+ });diff --git a/apps/mobile/src/plugins/PluginMenuUnreadDot.tsx b/apps/mobile/src/plugins/PluginMenuUnreadDot.tsxnew file mode 100644index 0000000000..e2a0dd4a33--- /dev/null+++ b/apps/mobile/src/plugins/PluginMenuUnreadDot.tsx@@ -0,0 +1,40 @@+import { useMemo } from "react";+import { StyleSheet, View } from "react-native";+import { useTranslation } from "react-i18next";+import { useAuth } from "@/auth/AuthContext";+import { useDeviceManagement } from "@/device-link/useDeviceManagement";+import { useRemoteResourceList } from "@/session/useRemoteResourceList";+import { radius, useTheme } from "@/theme";++/** Reading the directory is not an acknowledgement of any plugin's panel. */+export function PluginMenuUnreadDot({ active }: { active: boolean }) {+ const auth = useAuth(),+ { t } = useTranslation(),+ { colors } = useTheme();+ const devices = useDeviceManagement(auth.apiFetch, active);+ const targets = useMemo(+ () =>+ devices.devices+ .filter(+ (device) =>+ device.remoteControlEnabled &&+ !device.isSelf &&+ !["ios", "android"].includes(device.platform ?? ""),+ )+ .map((device) => ({+ deviceId: device.deviceId,+ deviceName: device.name,+ })),+ [devices.devices],+ );+ const plugins = useRemoteResourceList("plugins", targets, active);+ return plugins.items.some((row) => row.item.display.badges?.length) ? (+ <View+ accessibilityLabel={t("plugins.unread")}+ style={[styles.dot, { backgroundColor: colors.statusDone }]}+ />+ ) : null;+}+const styles = StyleSheet.create({+ dot: { width: 6, height: 6, borderRadius: radius.pill },+});diff --git a/apps/mobile/src/plugins/PluginNativeIntent.tsx b/apps/mobile/src/plugins/PluginNativeIntent.tsxnew file mode 100644index 0000000000..ba9978b224--- /dev/null+++ b/apps/mobile/src/plugins/PluginNativeIntent.tsx@@ -0,0 +1,206 @@+import { useEffect, useRef, useState } from "react";+import {+ ActivityIndicator,+ Modal,+ Pressable,+ StyleSheet,+ View,+} from "react-native";+import { useTranslation } from "react-i18next";+import { useSafeAreaInsets } from "react-native-safe-area-context";+import type {+ PluginNativeIntent as Intent,+ PluginPageFetchResult,+} from "@cindy/device-link";+import { useGuardedPush } from "@/utils/useGuardedPush";+import { SheetModal } from "@/session/SheetModal";+import { Text } from "@/components/AppText";+import { HtmlWebsiteBrowser } from "@/session/HtmlWebsiteBrowser";+import { HtmlSnapshotReader } from "@/session/HtmlFileReader";+import type { MobileHtmlPreview } from "@/session/mobileHtmlPreview";+import { PluginScheduleDraft } from "./PluginScheduleDraft";+import { PluginMediaViewer } from "./PluginMediaViewer";+import {+ fontWeight,+ lineHeight,+ spacing,+ typeScale,+ useTheme,+ useThemedStyles,+ type ThemeColors,+} from "@/theme";++export function PluginNativeIntent({+ intent,+ deviceId,+ onClose,+ readPreview,+ readMedia,+}: {+ intent: Intent;+ deviceId: string;+ onClose(): void;+ readPreview(+ url: string,+ offset: number,+ revision?: string,+ ): Promise<PluginPageFetchResult>;+ readMedia(path: string, offset: number): Promise<PluginPageFetchResult>;+}) {+ const { t } = useTranslation(),+ { colors } = useTheme(),+ styles = useThemedStyles(makeStyles),+ insets = useSafeAreaInsets();+ const push = useGuardedPush();+ const [preview, setPreview] = useState<MobileHtmlPreview>(),+ [failed, setFailed] = useState(false);+ const closed = useRef(Promise.resolve()).current;+ const local =+ intent.kind === "preview" &&+ ["localhost", "127.0.0.1", "[::1]"].includes(new URL(intent.url).hostname);+ useEffect(() => {+ if (intent.kind !== "preview" || !local) return;+ const controller = new AbortController();+ let prepared: MobileHtmlPreview | undefined;+ void import("./pluginLocalPreview")+ .then((module) =>+ module.preparePluginLocalPreview(+ intent.url,+ readPreview,+ controller.signal,+ ),+ )+ .then((value) => {+ prepared = value;+ if (controller.signal.aborted) void value.close();+ else setPreview(value);+ })+ .catch(() => {+ if (!controller.signal.aborted) setFailed(true);+ });+ return () => {+ controller.abort();+ void prepared?.close().catch(() => {});+ };+ }, [intent.id]);+ if (intent.kind === "schedule")+ return (+ <PluginScheduleDraft+ intent={intent}+ deviceId={deviceId}+ onClose={onClose}+ />+ );+ if (intent.kind === "media")+ return (+ <PluginMediaViewer intent={intent} read={readMedia} onClose={onClose} />+ );+ if (intent.kind === "simulator")+ return (+ <SheetModal visible onRequestClose={onClose} onBackdropPress={() => {}}>+ <View style={styles.fallback}>+ <Text style={styles.body}>{intent.ghostName}</Text>+ <Text style={styles.hint}>{t("plugins.simulatorOnComputer")}</Text>+ <Pressable+ accessibilityRole="button"+ style={styles.button}+ onPress={() => {+ onClose();+ push({+ pathname: "/devices/desktop/[deviceId]",+ params: { deviceId },+ });+ }}+ >+ <Text style={styles.body}>+ {t("interaction.pluginSetup.remoteDesktop")}+ </Text>+ </Pressable>+ <Pressable+ accessibilityRole="button"+ style={styles.button}+ onPress={onClose}+ >+ <Text style={styles.body}>{t("plugins.returnToPlugin")}</Text>+ </Pressable>+ </View>+ </SheetModal>+ );+ if (intent.kind !== "preview") return null;+ return (+ <Modal visible animationType="slide" onRequestClose={onClose}>+ <View+ style={[+ styles.root,+ {+ paddingTop: insets.top,+ paddingBottom: insets.bottom,+ paddingLeft: insets.left,+ paddingRight: insets.right,+ },+ ]}+ >+ <View style={styles.header}>+ <Text style={styles.body}>{intent.ghostName}</Text>+ <Pressable+ accessibilityRole="button"+ style={styles.button}+ onPress={onClose}+ >+ <Text style={styles.body}>{t("plugins.returnToPlugin")}</Text>+ </Pressable>+ </View>+ {local ? (+ <>+ <Text style={styles.hint}>{t("plugins.computerPreview")}</Text>+ {preview ? (+ <HtmlSnapshotReader+ preview={preview}+ onError={() => setFailed(true)}+ />+ ) : !failed ? (+ <ActivityIndicator color={colors.textSecondary} />+ ) : null}+ {failed ? (+ <Text style={styles.hint}>{t("plugins.previewFailed")}</Text>+ ) : null}+ </>+ ) : (+ <HtmlWebsiteBrowser+ visit={{ url: intent.url, snapshotClosed: closed }}+ insets={{ top: 0, bottom: 44, left: 0, right: 0 }}+ chrome={{ top: 0, bottom: 0, left: 0, right: 0, onClose }}+ onReturn={onClose}+ />+ )}+ </View>+ </Modal>+ );+}+const makeStyles = (colors: ThemeColors) =>+ StyleSheet.create({+ fallback: { padding: spacing.lg, backgroundColor: colors.surfaceElevated },+ root: { flex: 1, backgroundColor: colors.surface },+ header: {+ minHeight: 44,+ paddingHorizontal: spacing.md,+ flexDirection: "row",+ justifyContent: "space-between",+ alignItems: "center",+ gap: spacing.sm,+ },+ button: { minHeight: 44, paddingVertical: spacing.sm },+ body: {+ fontSize: typeScale.body,+ lineHeight: lineHeight.body,+ fontWeight: fontWeight.regular,+ color: colors.textPrimary,+ },+ hint: {+ fontSize: typeScale.footnote,+ lineHeight: lineHeight.bodySmall,+ fontWeight: fontWeight.regular,+ color: colors.textTertiary,+ padding: spacing.md,+ },+ });diff --git a/apps/mobile/src/plugins/PluginPage.tsx b/apps/mobile/src/plugins/PluginPage.tsxnew file mode 100644index 0000000000..1434c0125f--- /dev/null+++ b/apps/mobile/src/plugins/PluginPage.tsx@@ -0,0 +1,792 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import {+ ActivityIndicator,+ Alert,+ AppState,+ Linking,+ Modal,+ Pressable,+ StyleSheet,+ View,+} from "react-native";+import WebView, { type WebViewMessageEvent } from "react-native-webview";+import { useIsFocused } from "expo-router";+import AsyncStorage from "@react-native-async-storage/async-storage";+import { useTranslation } from "react-i18next";+import type {+ PluginPageAsset,+ PluginPageConfirm,+ PluginPageDocument,+ PluginPagePoll,+ PluginPageSurface,+ PluginDirectoryRequest,+ PluginNativeIntent as NativeIntent,+ PluginPageFetchResult,+} from "@cindy/device-link";+import { Text } from "@/components/AppText";+import { useDeviceLink } from "@/device-link/DeviceLinkContext";+import {+ getMobileAuthOwner,+ isMobileAuthOwnerCurrent,+} from "@/auth/authOwnerGeneration";+import {+ fontWeight,+ lineHeight,+ radius,+ spacing,+ typeScale,+ useTheme,+ useThemedStyles,+ type ThemeColors,+} from "@/theme";+import { invokePlugin, loadPluginPageAssets } from "./pluginClient";+import { PluginNativeIntent } from "./PluginNativeIntent";+import { PluginDirectoryPicker } from "./PluginDirectoryPicker";+import { pluginPageHtml } from "./pluginPageHtml";++function pageColors(colors: ThemeColors) {+ return {+ background: colors.surface,+ surface: colors.surface,+ "surface-elevated": colors.surfaceElevated,+ "surface-chip": colors.surfaceChip,+ "text-primary": colors.textPrimary,+ "text-secondary": colors.textSecondary,+ "text-tertiary": colors.textTertiary,+ "text-placeholder": colors.textPlaceholder,+ border: colors.border,+ "border-strong": colors.borderStrong,+ "status-error": colors.statusError,+ "status-done": colors.statusDone,+ };+}++export function PluginPage({+ deviceId,+ pluginId,+ surface,+ onTask,+ visible = true,+ registerBack,+ onTitle,+}: {+ deviceId: string;+ pluginId: string;+ surface: PluginPageSurface;+ visible?: boolean;+ registerBack?(handler: (() => void) | null): void;+ onTitle?(title: string): void;+ onTask(id: string): void;+}) {+ const { t } = useTranslation();+ const { invoke, status } = useDeviceLink();+ const { mode, colors } = useTheme();+ const styles = useThemedStyles(makeStyles);+ const routeFocused = useIsFocused(),+ focused = routeFocused && visible;+ const webview = useRef<WebView>(null);+ const draftOwner = useRef(getMobileAuthOwner()).current;+ const draftQueue = useRef(Promise.resolve());+ const [attempt, setAttempt] = useState(0);+ const [content, setContent] = useState<{+ document: PluginPageDocument;+ assets: Record<string, PluginPageAsset>;+ }>();+ const [error, setError] = useState(false);+ const [nativeIntent, setNativeIntent] = useState<NativeIntent>();+ const taskIntent = useRef<string | undefined>(undefined);+ const [directoryRequest, setDirectoryRequest] =+ useState<PluginDirectoryRequest>();+ const [confirm, setConfirm] = useState<PluginPageConfirm>();+ const [answering, setAnswering] = useState(false);+ const [notice, setNotice] = useState("");+ const focusedRef = useRef(focused);+ const delivery = useRef(0);+ focusedRef.current = focused;+ const send = useCallback(+ (value: unknown) =>+ webview.current?.postMessage(+ JSON.stringify({+ ...(value as Record<string, unknown>),+ deliveryId: ++delivery.current,+ }),+ ),+ [],+ );+ const request = useRef<+ (<T>(action: string, input?: Record<string, unknown>) => Promise<T>) | null+ >(null);+ const documentRef = useRef<PluginPageDocument | undefined>(undefined);+ const cursor = useRef(0),+ rendered = useRef(false);++ useEffect(() => {+ const owner = getMobileAuthOwner();+ let disposed = false,+ timer: ReturnType<typeof setTimeout> | undefined;+ let page: PluginPageDocument | undefined,+ polling = false;+ const current = () => !disposed && isMobileAuthOwnerCurrent(owner);+ const visible = () =>+ current() && focusedRef.current && AppState.currentState === "active";+ const call = <T,>(action: string, input: Record<string, unknown> = {}) =>+ invokePlugin<T>(+ (device, channel, args) =>+ invoke(device, channel, args, {+ preSend: () => {+ if (+ !current() ||+ ([+ "post",+ "fetch",+ "media:open",+ "answer",+ "answer-directory",+ "intent:ack",+ "preview:fetch",+ "seen",+ ].includes(action) &&+ !visible())+ )+ throw new Error("PLUGIN_PAGE_CLOSED");+ },+ }),+ deviceId,+ pluginId,+ action,+ { ...input, ...(page ? { pageId: page.pageId } : {}) },+ );+ request.current = call;+ documentRef.current = undefined;+ cursor.current = 0;+ rendered.current = false;+ setContent(undefined);+ setError(false);+ setConfirm(undefined);+ setDirectoryRequest(undefined);+ setNativeIntent(undefined);+ const poll = async () => {+ if (!visible() || !page || !rendered.current || polling) return;+ polling = true;+ try {+ const result = await call<PluginPagePoll>("poll", {+ after: cursor.current,+ });+ if (!visible()) return;+ if (+ !result ||+ !Array.isArray(result.events) ||+ !Array.isArray(result.confirms)+ )+ throw new Error("PLUGIN_PAGE_INVALID");+ send({+ type: "events",+ events: result.events,+ unreadAt: result.unreadAt,+ });+ setConfirm(result.confirms[0]);+ setDirectoryRequest(result.directories?.[0]);+ setNativeIntent(result.intents?.[0]);+ if (result.notifications?.length)+ setNotice(result.notifications.at(-1)!.text);+ setError(false);+ } catch {+ if (current()) setError(true);+ } finally {+ polling = false;+ if (visible()) timer = setTimeout(() => void poll(), 1_000);+ }+ };+ void (async () => {+ try {+ page = await call<PluginPageDocument>(`open:${surface}`);+ if (!current()) return;+ const assets = await loadPluginPageAssets(+ page,+ (path, offset) => call("asset", { path, offset }),+ current,+ );+ if (!current()) return;+ documentRef.current = page;+ setContent({ document: page, assets });+ // Polling starts only after ready, so startup events cannot disappear before the WebView mounts.+ } catch {+ if (current()) setError(true);+ } finally {+ if (!current() && page && isMobileAuthOwnerCurrent(owner))+ void invokePlugin(invoke, deviceId, pluginId, "close", {+ pageId: page.pageId,+ }).catch(() => {});+ }+ })();+ const ready = () => {+ if (timer) clearTimeout(timer);+ void poll();+ };+ startPolling.current = ready;+ const foreground = AppState.addEventListener("change", (state) => {+ send({+ type: "lifecycle",+ active: state === "active" && focusedRef.current,+ });+ if (timer) clearTimeout(timer);+ if (state === "active" && documentRef.current) ready();+ else {+ setConfirm(undefined);+ setDirectoryRequest(undefined);+ setNativeIntent(undefined);+ if (page) void call("suspend").catch(() => {});+ }+ });+ return () => {+ disposed = true;+ request.current = null;+ startPolling.current = null;+ if (timer) clearTimeout(timer);+ foreground.remove();+ if (page && isMobileAuthOwnerCurrent(owner))+ void invokePlugin(invoke, deviceId, pluginId, "close", {+ pageId: page.pageId,+ }).catch(() => {});+ };+ }, [deviceId, pluginId, surface, attempt, invoke, send]);+ const startPolling = useRef<(() => void) | null>(null);+ useEffect(() => {+ send({+ type: "lifecycle",+ active: focused && AppState.currentState === "active",+ });+ if (focused) startPolling.current?.();+ else {+ setConfirm(undefined);+ setDirectoryRequest(undefined);+ setNativeIntent(undefined);+ if (documentRef.current)+ void request.current?.("suspend").catch(() => {});+ }+ }, [focused]);+ useEffect(() => () => registerBack?.(null), [registerBack]);+ useEffect(() => {+ if (!notice) return;+ const timer = setTimeout(() => setNotice(""), 4_000);+ return () => clearTimeout(timer);+ }, [notice]);+ const closeIntent = async () => {+ const call = request.current;+ if (!call || !nativeIntent) return false;+ try {+ await call("intent:ack", { intentId: nativeIntent.id });+ if (call !== request.current) return false;+ setNativeIntent(undefined);+ return true;+ } catch {+ if (call === request.current) {+ setNativeIntent(undefined);+ setError(true);+ }+ return false;+ }+ };+ useEffect(() => {+ if (+ nativeIntent?.kind !== "task" ||+ !focused ||+ taskIntent.current === nativeIntent.id+ )+ return;+ taskIntent.current = nativeIntent.id;+ void closeIntent().then((acknowledged) => {+ if (+ acknowledged &&+ focusedRef.current &&+ isMobileAuthOwnerCurrent(draftOwner)+ )+ onTask(nativeIntent.taskId);+ });+ }, [nativeIntent?.id, focused]);+ useEffect(() => {+ const call = request.current;+ if (+ !call ||+ !focused ||+ !documentRef.current ||+ AppState.currentState !== "active"+ )+ return;+ const hidden = !!nativeIntent && nativeIntent.kind !== "task";+ send({ type: "lifecycle", active: !hidden });+ void call("cover", { hidden }).catch(() => {+ if (request.current === call) setError(true);+ });+ }, [nativeIntent?.id, focused]);+ const appearance = useRef({ mode, colors });+ appearance.current = { mode, colors };+ const html = useMemo(+ () =>+ content+ ? pluginPageHtml({+ ...content,+ theme: appearance.current.mode,+ colors: pageColors(appearance.current.colors),+ })+ : "",+ [content],+ );+ useEffect(+ () =>+ send({+ type: "theme",+ theme: mode,+ colors: pageColors(colors),+ }),+ [send, mode, colors],+ );+ const answer = async (confirmed: boolean) => {+ if (!confirm || answering || !request.current) return;+ const call = request.current;+ setAnswering(true);+ try {+ await call("answer", { confirmId: confirm.id, confirmed });+ if (request.current === call) setConfirm(undefined);+ } catch {+ if (request.current === call) {+ setError(true);+ setConfirm(undefined);+ }+ } finally {+ if (request.current === call) setAnswering(false);+ }+ };+ const onMessage = async (event: WebViewMessageEvent) => {+ if (!request.current || !isMobileAuthOwnerCurrent(draftOwner)) return;+ let message: Record<string, unknown>;+ try {+ if (event.nativeEvent.data.length > 65_536) return;+ message = JSON.parse(event.nativeEvent.data);+ } catch {+ return;+ }+ const call = request.current,+ pageId = documentRef.current?.pageId;+ if (+ !message ||+ typeof message !== "object" ||+ !pageId ||+ message.pageId !== pageId+ )+ return;+ const current = () =>+ request.current === call && documentRef.current?.pageId === pageId;+ const reply = (value: unknown) => {+ if (current()) send(value);+ };+ try {+ if (message.type === "draft:get" || message.type === "draft:set") {+ if (+ typeof message.id !== "string" ||+ message.id.length > 64 ||+ typeof message.key !== "string" ||+ !/^[a-zA-Z0-9._-]{1,64}$/.test(message.key)+ )+ return;+ const key = `cindy.pluginDraft.v1.${JSON.stringify([draftOwner.accountKey, deviceId, pluginId, surface, message.key])}`;+ const operation = draftQueue.current.then(async () => {+ if (!current() || !isMobileAuthOwnerCurrent(draftOwner))+ throw new Error("PLUGIN_PAGE_CLOSED");+ if (message.type === "draft:set") {+ const json = JSON.stringify(message.value);+ if (typeof json !== "string" || json.length > 48 * 1024)+ throw new Error("PLUGIN_DRAFT_TOO_LARGE");+ await AsyncStorage.setItem(key, json);+ return null;+ }+ const json = await AsyncStorage.getItem(key);+ if (!isMobileAuthOwnerCurrent(draftOwner))+ throw new Error("PLUGIN_PAGE_CLOSED");+ return json ? JSON.parse(json) : null;+ });+ draftQueue.current = operation.then(+ () => {},+ () => {},+ );+ try {+ reply({+ type: "draft:reply",+ id: message.id,+ value: await operation,+ });+ } catch {+ reply({ type: "draft:reply", id: message.id, error: true });+ }+ return;+ }+ if (+ !focusedRef.current ||+ AppState.currentState !== "active" ||+ (nativeIntent && ["post", "link"].includes(String(message.type)))+ )+ return;+ if (+ message.type === "navigation" &&+ typeof message.canGoBack === "boolean"+ ) {+ registerBack?.(+ message.canGoBack+ ? () => {+ if (current()) send({ type: "back" });+ }+ : null,+ );+ if (+ typeof message.title === "string" &&+ message.title.trim().length <= 40 &&+ !/[\x00-\x1f]/.test(message.title)+ )+ onTitle?.(message.title.trim());+ } else if (message.type === "resource-error") {+ setError(true);+ } else if (message.type === "ready") {+ rendered.current = true;+ send({+ type: "lifecycle",+ active: focusedRef.current && AppState.currentState === "active",+ });+ startPolling.current?.();+ } else if (+ message.type === "content-rendered" &&+ documentRef.current?.surface === "panel" &&+ rendered.current &&+ Number.isSafeInteger(message.seenAt)+ ) {+ // An older frame acknowledgement must not clear a newer mark.+ await call("seen", { seenAt: message.seenAt }).catch(() => {});+ } else if (+ message.type === "events-ack" &&+ message.pageId === documentRef.current?.pageId &&+ Number.isSafeInteger(message.sequence)+ ) {+ cursor.current = Math.max(cursor.current, message.sequence as number);+ } else if (+ message.type === "post" &&+ typeof message.channel === "string"+ ) {+ await call("post", { channel: message.channel, data: message.data });+ } else if (message.type === "fetch" && typeof message.id === "string") {+ try {+ reply({+ type: "reply",+ id: message.id,+ result: await call("fetch", {+ path: message.path,+ method: message.method,+ body: message.body,+ offset: message.offset,+ revision: message.revision,+ }),+ });+ } catch {+ reply({ type: "reply", id: message.id, error: true });+ }+ } else if (message.type === "link" && typeof message.url === "string") {+ let url: URL;+ try {+ url = new URL(+ message.url,+ `cindy-ghost://${pluginId}/${documentRef.current?.entry ?? ""}`,+ );+ } catch {+ return;+ }+ if (+ url.protocol === "cindy-ghost:" &&+ url.hostname === pluginId &&+ url.pathname.startsWith("/preview/")+ ) {+ await call("media:open", { url: url.href });+ return;+ }+ if (url.protocol === "https:")+ Alert.alert(t("plugins.externalTitle"), url.href, [+ { text: t("plugins.cancel"), style: "cancel" },+ {+ text: t("plugins.open"),+ onPress: () => {+ if (!current()) return;+ void Linking.openURL(url.href).catch(() => setError(true));+ },+ },+ ]);+ else if (+ url.protocol === "cindy:" &&+ url.hostname === "sessions" &&+ /^\/[a-zA-Z0-9-]+$/.test(url.pathname)+ ) {+ const id = url.pathname.slice(1);+ Alert.alert(t("plugins.openTask"), undefined, [+ { text: t("plugins.cancel"), style: "cancel" },+ {+ text: t("plugins.open"),+ onPress: () => {+ if (current()) onTask(id);+ },+ },+ ]);+ }+ }+ } catch {+ if (current()) setError(true);+ }+ };+ const unavailable = error || status !== "online";+ return (+ <View style={styles.root}>+ {unavailable ? (+ <View style={styles.banner}>+ <Text style={styles.note}>{t("plugins.pageUnconfirmed")}</Text>+ <Pressable+ accessibilityRole="button"+ style={styles.button}+ onPress={() => setAttempt((n) => n + 1)}+ >+ <Text style={styles.buttonText}>{t("plugins.reopen")}</Text>+ </Pressable>+ </View>+ ) : null}+ {html ? (+ <View+ style={styles.root}+ pointerEvents={unavailable || !!nativeIntent ? "none" : "auto"}+ >+ <WebView+ ref={webview}+ source={{ html }}+ style={styles.webview}+ originWhitelist={["*"]}+ incognito+ sharedCookiesEnabled={false}+ thirdPartyCookiesEnabled={false}+ allowFileAccess={false}+ allowFileAccessFromFileURLs={false}+ allowUniversalAccessFromFileURLs={false}+ setSupportMultipleWindows={false}+ javaScriptCanOpenWindowsAutomatically={false}+ allowsInlineMediaPlayback+ onShouldStartLoadWithRequest={(request) =>+ request.url === "about:blank"+ }+ onMessage={(event) => {+ void onMessage(event);+ }}+ onError={() => setError(true)}+ onContentProcessDidTerminate={() => setError(true)}+ />+ </View>+ ) : !error ? (+ <View style={styles.loading}>+ <ActivityIndicator color={colors.textSecondary} />+ <Text style={styles.note}>{t("plugins.loadingPage")}</Text>+ </View>+ ) : null}+ {notice ? (+ <View accessibilityLiveRegion="polite" style={styles.banner}>+ <Text style={styles.note}>{notice}</Text>+ </View>+ ) : null}+ {nativeIntent &&+ nativeIntent.kind !== "task" &&+ focused &&+ !unavailable ? (+ <PluginNativeIntent+ key={nativeIntent.id}+ intent={nativeIntent}+ deviceId={deviceId}+ onClose={() => void closeIntent()}+ readMedia={async (path, offset) => {+ const call = request.current;+ if (+ !call ||+ !focusedRef.current ||+ AppState.currentState !== "active"+ )+ throw new Error("PLUGIN_PAGE_CLOSED");+ return call<PluginPageFetchResult>("fetch", {+ path,+ offset,+ method: "GET",+ });+ }}+ readPreview={(url, offset, revision) => {+ const call = request.current;+ if (!call || !focusedRef.current)+ return Promise.reject(new Error("PLUGIN_PAGE_CLOSED"));+ return call<PluginPageFetchResult>("preview:fetch", {+ intentId: nativeIntent.id,+ url,+ offset,+ ...(revision ? { revision } : {}),+ });+ }}+ />+ ) : null}+ {directoryRequest && focused && !unavailable ? (+ <PluginDirectoryPicker+ key={directoryRequest.id}+ request={directoryRequest}+ deviceId={deviceId}+ onAnswer={async (path) => {+ const call = request.current;+ if (+ !call ||+ !focusedRef.current ||+ AppState.currentState !== "active"+ )+ return;+ try {+ await call("answer-directory", {+ requestId: directoryRequest.id,+ path,+ });+ if (request.current === call) setDirectoryRequest(undefined);+ } catch {+ if (request.current === call) {+ setDirectoryRequest(undefined);+ setError(true);+ }+ throw new Error("PLUGIN_PAGE_UNCONFIRMED");+ }+ }}+ />+ ) : null}+ <Modal+ visible={Boolean(+ confirm &&+ !directoryRequest &&+ !nativeIntent &&+ focused &&+ !unavailable,+ )}+ transparent+ animationType="fade"+ onRequestClose={() => {+ void answer(false);+ }}+ >+ <View style={styles.scrim}>+ <View accessibilityViewIsModal style={styles.dialog}>+ <Text style={styles.title}>{confirm?.title}</Text>+ <Text style={styles.body}>{confirm?.body}</Text>+ <View style={styles.actions}>+ <Pressable+ disabled={answering}+ style={styles.button}+ onPress={() => {+ void answer(false);+ }}+ >+ <Text style={styles.buttonText}>+ {confirm?.cancelText ?? t("plugins.cancel")}+ </Text>+ </Pressable>+ <Pressable+ disabled={answering}+ style={[styles.button, !confirm?.danger && styles.primary]}+ onPress={() => {+ void answer(true);+ }}+ >+ <Text+ style={+ confirm?.danger ? styles.destructive : styles.primaryText+ }+ >+ {confirm?.confirmText ?? t("plugins.confirm")}+ </Text>+ </Pressable>+ </View>+ </View>+ </View>+ </Modal>+ </View>+ );+}+const makeStyles = (c: ThemeColors) =>+ StyleSheet.create({+ root: { flex: 1, backgroundColor: c.surface },+ webview: { flex: 1, backgroundColor: c.surface },+ loading: {+ flex: 1,+ alignItems: "center",+ justifyContent: "center",+ gap: spacing.md,+ },+ banner: {+ padding: spacing.md,+ gap: spacing.sm,+ backgroundColor: c.surface,+ },+ note: {+ fontSize: typeScale.footnote,+ lineHeight: lineHeight.caption,+ fontWeight: fontWeight.regular,+ color: c.textSecondary,+ },+ body: {+ fontSize: typeScale.bodySmall,+ lineHeight: lineHeight.bodySmall,+ fontWeight: fontWeight.regular,+ color: c.textSecondary,+ },+ title: {+ fontSize: typeScale.title,+ lineHeight: lineHeight.title,+ fontWeight: fontWeight.semibold,+ color: c.textPrimary,+ },+ button: {+ minHeight: 44,+ paddingHorizontal: spacing.md,+ paddingVertical: spacing.sm,+ borderRadius: radius.pill,+ alignItems: "center",+ justifyContent: "center",+ },+ buttonText: {+ fontSize: typeScale.body,+ lineHeight: lineHeight.body,+ fontWeight: fontWeight.medium,+ color: c.textPrimary,+ },+ primaryText: {+ fontSize: typeScale.body,+ lineHeight: lineHeight.body,+ fontWeight: fontWeight.medium,+ color: c.ctaText,+ },+ destructive: {+ fontSize: typeScale.body,+ lineHeight: lineHeight.body,+ fontWeight: fontWeight.medium,+ color: c.destructive,+ },+ primary: { backgroundColor: c.textPrimary },+ actions: {+ flexDirection: "row",+ justifyContent: "flex-end",+ gap: spacing.sm,+ },+ scrim: {+ flex: 1,+ alignItems: "center",+ justifyContent: "center",+ padding: spacing.lg,+ backgroundColor: c.overlay,+ },+ dialog: {+ backgroundColor: c.surfaceElevated,+ borderRadius: radius.container,+ padding: spacing.lg,+ gap: spacing.md,+ width: "100%",+ maxWidth: 420,+ },+ });diff --git a/apps/mobile/src/plugins/PluginScheduleDraft.tsx b/apps/mobile/src/plugins/PluginScheduleDraft.tsxnew file mode 100644index 0000000000..52cb77e74e--- /dev/null+++ b/apps/mobile/src/plugins/PluginScheduleDraft.tsx@@ -0,0 +1,435 @@+import { useEffect, useRef, useState } from "react";+import {+ ActivityIndicator,+ AppState,+ Platform,+ Pressable,+ ScrollView,+ StyleSheet,+ View,+} from "react-native";+import { useTranslation } from "react-i18next";+import type { PluginNativeIntent } from "@cindy/device-link";+import {+ createMobileScheduleDraft,+ buildMobileScheduleInput,+ validateMobileScheduleDraft,+} from "@cindy/maker-shared/schedule-form";+import { Text, TextInput } from "@/components/AppText";+import { useDeviceLink } from "@/device-link/DeviceLinkContext";+import { useDeviceProviders } from "@/device-link/useDeviceProviders";+import { useMobileMakerTransport } from "@/device-link/useMobileMakerTransport";+import {+ getMobileAuthOwner,+ isMobileAuthOwnerCurrent,+} from "@/auth/authOwnerGeneration";+import { normalizeMobileAgentCapabilities } from "@/session/agentCapabilities";+import { ModelPickerSheet } from "@/session/ModelPickerSheet";+import { SheetModal } from "@/session/SheetModal";+import {+ fontWeight,+ lineHeight,+ radius,+ spacing,+ typeScale,+ useTheme,+ useThemedStyles,+ type ThemeColors,+} from "@/theme";++/** Opening this draft never writes a schedule. Only the native Save gesture may create one. */+export function PluginScheduleDraft({+ intent,+ deviceId,+ onClose,+}: {+ intent: Extract<PluginNativeIntent, { kind: "schedule" }>;+ deviceId: string;+ onClose(): void;+}) {+ const { t } = useTranslation(),+ { colors } = useTheme(),+ styles = useThemedStyles(makeStyles);+ const link = useDeviceLink(),+ maker = useMobileMakerTransport(deviceId),+ providers = useDeviceProviders(deviceId);+ const owner = useRef(getMobileAuthOwner()).current,+ alive = useRef(true),+ sent = useRef(false),+ epoch = useRef(link.connectionEpoch).current;+ const liveEpoch = useRef(link.connectionEpoch);+ liveEpoch.current = link.connectionEpoch;+ const [draft, setDraft] = useState(() => ({+ ...createMobileScheduleDraft(),+ name: intent.name,+ prompt: intent.prompt,+ model: "",+ providerId: "",+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,+ ...(intent.intervalMs ? { sourceIntervalMs: intent.intervalMs } : {}),+ }));+ const [frequency, setFrequency] = useState<+ "daily" | "weekdays" | "interval" | "custom"+ >(intent.intervalMs ? "interval" : "daily");+ const [clock, setClock] = useState("09:00");+ const applyFrequency = (next: typeof frequency) => {+ setFrequency(next);+ const [hour, minute] = clock.split(":").map(Number);+ setDraft((d) => ({+ ...d,+ intervalMinutes: "",+ intervalMinutesTouched: next !== "interval",+ sourceIntervalMs:+ next === "interval" ? (intent.intervalMs ?? 3600000) : undefined,+ cronExpr:+ next === "daily" || next === "weekdays"+ ? `${minute} ${hour} * * ${next === "weekdays" ? "1-5" : "*"}`+ : d.cronExpr,+ }));+ };+ const [picker, setPicker] = useState(false),+ [busy, setBusy] = useState(false),+ [unknown, setUnknown] = useState(false);+ useEffect(+ () => () => {+ alive.current = false;+ },+ [],+ );+ const assertCurrent = () => {+ if (+ !alive.current ||+ !isMobileAuthOwnerCurrent(owner) ||+ liveEpoch.current !== epoch ||+ AppState.currentState !== "active"+ )+ throw new Error("PLUGIN_DRAFT_CLOSED");+ };+ const save = async () => {+ if (sent.current || !draft.model || !draft.providerId) return;+ const validation =+ frequency === "interval" &&+ draft.intervalMinutesTouched &&+ !draft.intervalMinutes.trim()+ ? { message: t("plugins.automationInvalid") }+ : (frequency === "daily" || frequency === "weekdays") &&+ !/^([01]\d|2[0-3]):[0-5]\d$/.test(clock)+ ? { message: t("plugins.automationTimeInvalid") }+ : validateMobileScheduleDraft(draft, {+ translate: (_key, _fallback, _values) =>+ t("plugins.automationInvalid"),+ });+ if (validation) return;+ try {+ assertCurrent();+ } catch {+ return;+ }+ sent.current = true;+ setBusy(true);+ try {+ const result = await link.invoke<{ id: string }>(+ deviceId,+ "maker:schedule:create",+ [buildMobileScheduleInput(draft)],+ { preSend: assertCurrent },+ );+ if (!result || typeof result.id !== "string")+ throw new Error("PLUGIN_DRAFT_UNCONFIRMED");+ assertCurrent();+ onClose();+ } catch {+ if (alive.current) setUnknown(true);+ } finally {+ if (alive.current) setBusy(false);+ }+ };+ const validation =+ frequency === "interval" &&+ draft.intervalMinutesTouched &&+ !draft.intervalMinutes.trim()+ ? { message: t("plugins.automationInvalid") }+ : (frequency === "daily" || frequency === "weekdays") &&+ !/^([01]\d|2[0-3]):[0-5]\d$/.test(clock)+ ? { message: t("plugins.automationTimeInvalid") }+ : validateMobileScheduleDraft(draft, {+ translate: (_key, _fallback, _values) =>+ t("plugins.automationInvalid"),+ });+ const modelName =+ providers.providers+ .find((provider) => provider.id === draft.providerId)+ ?.models[draft.agentKind]?.find((model) => model.id === draft.model)+ ?.name ?? draft.model;+ return (+ <>+ <SheetModal+ visible={!picker}+ keyboardAvoiding+ onBackdropPress={() => {}}+ onRequestClose={onClose}+ >+ <ScrollView+ keyboardShouldPersistTaps="handled"+ contentContainerStyle={styles.sheet}+ >+ <Text style={styles.title}>{t("plugins.automationDraft")}</Text>+ <Text style={styles.hint}>+ {intent.ghostName} · {t("plugins.automationDraftHint")}+ </Text>+ <Text style={styles.body}>{t("plugins.automationName")}</Text>+ <TextInput+ accessibilityLabel={t("plugins.automationName")}+ value={draft.name}+ editable={!sent.current}+ maxLength={80}+ onChangeText={(name) => setDraft((d) => ({ ...d, name }))}+ style={styles.input}+ />+ <Text style={styles.body}>{t("plugins.automationPrompt")}</Text>+ <TextInput+ accessibilityLabel={t("plugins.automationPrompt")}+ value={draft.prompt}+ editable={!sent.current}+ multiline+ maxLength={12000}+ onChangeText={(prompt) => setDraft((d) => ({ ...d, prompt }))}+ style={styles.input}+ />+ <View style={styles.frequencies}>+ {(["daily", "weekdays", "interval", "custom"] as const).map(+ (value) => (+ <Pressable+ key={value}+ accessibilityRole="radio"+ accessibilityState={{ checked: frequency === value }}+ disabled={sent.current}+ style={[+ styles.frequency,+ frequency === value && styles.selectedFrequency,+ ]}+ onPress={() => applyFrequency(value)}+ >+ <Text style={styles.body}>+ {t(`plugins.frequency_${value}`)}+ </Text>+ </Pressable>+ ),+ )}+ </View>+ {frequency === "daily" || frequency === "weekdays" ? (+ <TextInput+ accessibilityLabel={t("plugins.automationTime")}+ value={clock}+ placeholder="09:00"+ placeholderTextColor={colors.textPlaceholder}+ maxLength={5}+ autoCorrect={false}+ editable={!sent.current}+ onChangeText={(value) => {+ setClock(value);+ if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(value)) return;+ const [hour, minute] = value.split(":").map(Number);+ setDraft((d) => ({+ ...d,+ cronExpr: `${minute} ${hour} * * ${frequency === "weekdays" ? "1-5" : "*"}`,+ }));+ }}+ style={styles.input}+ />+ ) : frequency === "interval" ? (+ <>+ <Text style={styles.body}>{t("plugins.automationInterval")}</Text>+ <TextInput+ accessibilityLabel={t("plugins.automationInterval")}+ placeholder={+ draft.sourceIntervalMs+ ? String(draft.sourceIntervalMs / 60000)+ : ""+ }+ placeholderTextColor={colors.textPlaceholder}+ value={draft.intervalMinutes}+ keyboardType="number-pad"+ editable={!sent.current}+ onChangeText={(intervalMinutes) =>+ setDraft((d) => ({+ ...d,+ intervalMinutes,+ intervalMinutesTouched: true,+ }))+ }+ style={styles.input}+ />+ </>+ ) : (+ <>+ <Text style={styles.body}>{t("plugins.automationCron")}</Text>+ <TextInput+ accessibilityLabel={t("plugins.automationCron")}+ value={draft.cronExpr}+ autoCapitalize="none"+ autoCorrect={false}+ editable={!sent.current}+ onChangeText={(cronExpr) =>+ setDraft((d) => ({ ...d, cronExpr }))+ }+ style={styles.input}+ />+ </>+ )}+ <TextInput+ accessibilityLabel={t("plugins.automationTimezone")}+ value={draft.timezone}+ autoCapitalize="none"+ autoCorrect={false}+ editable={!sent.current}+ onChangeText={(timezone) => setDraft((d) => ({ ...d, timezone }))}+ style={styles.input}+ />+ <Pressable+ accessibilityRole="button"+ disabled={sent.current}+ style={styles.row}+ onPress={() => setPicker(true)}+ >+ <Text style={styles.body}>+ {modelName || t("plugins.taskModel")}+ </Text>+ </Pressable>+ {validation ? (+ <Text style={styles.hint}>{validation.message}</Text>+ ) : null}+ {unknown ? (+ <Text style={styles.hint}>+ {t("plugins.automationUnconfirmed")}+ </Text>+ ) : null}+ {busy ? <ActivityIndicator color={colors.textSecondary} /> : null}+ <View style={styles.buttons}>+ <Pressable+ accessibilityRole="button"+ style={styles.row}+ onPress={onClose}+ >+ <Text style={styles.body}>{t("plugins.cancel")}</Text>+ </Pressable>+ <Pressable+ accessibilityRole="button"+ disabled={+ sent.current ||+ !!validation ||+ !draft.model ||+ !draft.providerId+ }+ style={styles.row}+ onPress={() => void save()}+ >+ <Text style={styles.body}>{t("plugins.saveConfiguration")}</Text>+ </Pressable>+ </View>+ </ScrollView>+ </SheetModal>+ <ModelPickerSheet+ visible={picker}+ onClose={() => setPicker(false)}+ agentKind={draft.agentKind}+ providers={providers.providers}+ providersReady={providers.ready}+ providersUnsupported={providers.unsupported}+ modelVisibilityOverrides={providers.modelVisibilityOverrides}+ flatOptions={[]}+ capabilities={null}+ activeModelId={draft.model}+ selectedProviderId={draft.providerId || null}+ selectedEffort={draft.effort}+ selectedFastMode={draft.fastMode}+ loading={providers.loading}+ disabled={busy || sent.current}+ hidePermissionTrigger+ activePermissionMode=""+ permissionOptions={[]}+ onSelectPermissionMode={() => {}}+ onSelectFlatModel={() => {}}+ onSelectProviderRow={() => {}}+ keyboardAvoidingBehavior={Platform.OS === "ios" ? "padding" : "height"}+ emptyHint={t("plugins.modelsUnavailable")}+ unified={{+ scope: JSON.stringify([owner.accountKey, deviceId]),+ agents: ["claude-code", "codex", "pi"],+ loadCapabilities: async (kind) => {+ const caps = normalizeMobileAgentCapabilities(+ await maker.getCapabilities(kind),+ );+ if (!caps) throw new Error("CAPABILITIES_UNAVAILABLE");+ return caps;+ },+ onSelect: async (value) => {+ assertCurrent();+ setDraft((d) => ({+ ...d,+ agentKind: value.agent,+ model: value.modelId,+ providerId: value.providerId,+ effort: value.effort || "",+ fastMode: value.fast,+ }));+ setPicker(false);+ return true;+ },+ }}+ />+ </>+ );+}+const makeStyles = (colors: ThemeColors) =>+ StyleSheet.create({+ sheet: {+ backgroundColor: colors.surfaceElevated,+ padding: spacing.lg,+ gap: spacing.md,+ },+ frequencies: { flexDirection: "row", flexWrap: "wrap", gap: spacing.sm },+ frequency: {+ minHeight: 44,+ justifyContent: "center",+ paddingHorizontal: spacing.sm,+ borderRadius: radius.control,+ borderWidth: 1,+ borderColor: colors.border,+ },+ selectedFrequency: {+ backgroundColor: colors.surfaceChip,+ borderColor: colors.borderStrong,+ },+ buttons: { flexDirection: "row", gap: spacing.lg },+ row: { minHeight: 44, paddingVertical: spacing.sm },+ title: {+ fontSize: typeScale.title,+ lineHeight: lineHeight.title,+ fontWeight: fontWeight.semibold,+ color: colors.textPrimary,+ },+ body: {+ fontSize: typeScale.body,+ lineHeight: lineHeight.body,+ fontWeight: fontWeight.regular,+ color: colors.textPrimary,+ },+ hint: {+ fontSize: typeScale.footnote,+ lineHeight: lineHeight.bodySmall,+ fontWeight: fontWeight.regular,+ color: colors.textTertiary,+ },+ input: {+ fontSize: typeScale.bodySmall,+ lineHeight: lineHeight.bodySmall,+ fontWeight: fontWeight.regular,+ color: colors.textPrimary,+ borderColor: colors.border,+ borderWidth: StyleSheet.hairlineWidth,+ borderRadius: radius.control,+ minHeight: 44,+ padding: spacing.sm,+ },+ });diff --git a/apps/mobile/src/plugins/PluginSetupNativeActions.tsx b/apps/mobile/src/plugins/PluginSetupNativeActions.tsxnew file mode 100644index 0000000000..a07f0066de--- /dev/null+++ b/apps/mobile/src/plugins/PluginSetupNativeActions.tsx@@ -0,0 +1,98 @@+import { useEffect, useState, type ComponentType } from "react";+import { Alert, Pressable, StyleSheet, View } from "react-native";+import { Text } from "@/components/AppText";+import { useTranslation } from "react-i18next";+import {+ fontWeight,+ lineHeight,+ spacing,+ typeScale,+ useThemedStyles,+ type ThemeColors,+} from "@/theme";+import {+ mobilePluginSetupActions,+ type MobilePluginSetupAction,+} from "./pluginSetupActions";+type FormProps = {+ initialAction: MobilePluginSetupAction;+ requestRevision: unknown;+ requestIdentity: string;+ deviceId: string;+ disabled: boolean;+ onClosed(): void;+};+/** Loading a card never initializes native authorization or starts a connection. */+export function PluginSetupNativeActions({+ request,+ deviceId,+ disabled,+}: {+ request: unknown;+ deviceId: string;+ disabled: boolean;+}) {+ const { t } = useTranslation(),+ styles = useThemedStyles(makeStyles);+ const [pending, setPending] = useState<{+ action: MobilePluginSetupAction;+ identity: string;+ }>();+ const [Form, setForm] = useState<ComponentType<FormProps>>();+ const raw =+ request && typeof request === "object"+ ? (request as Record<string, unknown>)+ : {};+ const ghost =+ raw.ghost && typeof raw.ghost === "object"+ ? (raw.ghost as Record<string, unknown>)+ : {};+ const requestIdentity = JSON.stringify([deviceId, raw.requestId, ghost.id]);+ useEffect(() => {+ if (pending && pending.identity !== requestIdentity) setPending(undefined);+ }, [requestIdentity, pending]);+ const actions = mobilePluginSetupActions(request);+ return (+ <View>+ {actions.map((action) => (+ <Pressable+ key={action.action.actionId}+ accessibilityRole="button"+ disabled={disabled || !!pending}+ style={styles.row}+ onPress={() => {+ setPending({ action, identity: requestIdentity });+ void import("./PluginSetupNativeForm")+ .then((module) => setForm(() => module.default))+ .catch(() => {+ setPending(undefined);+ Alert.alert(t("plugins.actionFailed"));+ });+ }}+ >+ <Text style={styles.body}>{action.title}</Text>+ </Pressable>+ ))}+ {pending && pending.identity === requestIdentity && Form ? (+ <Form+ initialAction={pending.action}+ requestRevision={raw.revision}+ requestIdentity={requestIdentity}+ deviceId={deviceId}+ disabled={disabled}+ onClosed={() => setPending(undefined)}+ />+ ) : null}+ </View>+ );+}+const makeStyles = (colors: ThemeColors) =>+ StyleSheet.create({+ row: { minHeight: 44, paddingVertical: spacing.sm },+ body: {+ fontSize: typeScale.body,+ lineHeight: lineHeight.body,+ fontWeight: fontWeight.regular,+ color: colors.textPrimary,+ },+ });diff --git a/apps/mobile/src/plugins/PluginSetupNativeForm.tsx b/apps/mobile/src/plugins/PluginSetupNativeForm.tsxnew file mode 100644index 0000000000..5ed3ad04e1--- /dev/null+++ b/apps/mobile/src/plugins/PluginSetupNativeForm.tsx@@ -0,0 +1,485 @@+import { useEffect, useRef, useState } from "react";+import {+ ActivityIndicator,+ Alert,+ AppState,+ Pressable,+ ScrollView,+ StyleSheet,+ View,+} from "react-native";+import { useIsFocused } from "expo-router";+import * as WebBrowser from "expo-web-browser";+import * as Clipboard from "expo-clipboard";+import * as SecureStore from "expo-secure-store";+import { pinMobilePluginIdentity } from "./pluginOauthPins";+import { accountVaultKey } from "@cindy/auth-client";+import {+ PLUGIN_OAUTH_CHANNEL,+ parsePluginOauthPeerIdentity,+} from "@cindy/device-link";+import { useTranslation } from "react-i18next";+import { Text, TextInput } from "@/components/AppText";+import { useAuth } from "@/auth/AuthContext";+import {+ getMobileAuthOwner,+ isMobileAuthOwnerCurrent,+} from "@/auth/authOwnerGeneration";+import { useDeviceLink } from "@/device-link/DeviceLinkContext";+import { SheetModal } from "@/session/SheetModal";+import {+ fontWeight,+ lineHeight,+ radius,+ spacing,+ typeScale,+ useTheme,+ useThemedStyles,+ type ThemeColors,+} from "@/theme";+import { type MobilePluginSetupAction } from "./pluginSetupActions";+import { authenticateMobilePluginOauth } from "./pluginOauthClient";+import { pluginOauthPlatformCrypto } from "./pluginOauthPlatformCrypto";+import { runMobilePluginAuthorization } from "./pluginAuthorizationController";++export default function PluginSetupNativeForm({+ initialAction,+ requestRevision,+ requestIdentity,+ deviceId,+ disabled,+ onClosed,+}: {+ initialAction: MobilePluginSetupAction;+ requestRevision: unknown;+ requestIdentity: string;+ deviceId: string;+ disabled: boolean;+ onClosed(): void;+}) {+ const { t } = useTranslation(),+ { colors } = useTheme(),+ styles = useThemedStyles(makeStyles);+ const auth = useAuth(),+ link = useDeviceLink(),+ focused = useIsFocused();+ const initialIdentity = useRef(requestIdentity).current;+ const owner = useRef(getMobileAuthOwner()).current,+ alive = useRef(true),+ lock = useRef(false),+ operation = useRef(0),+ copiedCode = useRef<string | undefined>(undefined);+ const live = useRef({ focused, epoch: link.connectionEpoch });+ live.current = { focused, epoch: link.connectionEpoch };+ const [selected, setSelected] = useState<MobilePluginSetupAction | undefined>(+ initialAction,+ ),+ [secret, setSecret] = useState(""),+ [host, setHost] = useState("");+ const [busy, setBusy] = useState(false),+ [browser, setBrowser] = useState<{ url: string; code?: string }>();+ useEffect(+ () => () => {+ alive.current = false;+ operation.current++;+ void clearCopiedCode();+ },+ [],+ );+ const clearCopiedCode = async () => {+ const code = copiedCode.current;+ copiedCode.current = undefined;+ if (code && (await Clipboard.getStringAsync().catch(() => "")) === code)+ await Clipboard.setStringAsync("").catch(() => {});+ };+ const clear = () => {+ setSecret("");+ setHost("");+ };+ const close = () => {+ operation.current++;+ clear();+ setSelected(undefined);+ setBrowser(undefined);+ void clearCopiedCode();+ onClosed();+ };+ useEffect(() => {+ if (+ requestIdentity !== initialIdentity ||+ (!lock.current &&+ requestRevision !== initialAction.action.expectedRevision)+ )+ close();+ }, [requestIdentity, requestRevision]);+ const submit = async (action: MobilePluginSetupAction) => {+ if (+ lock.current ||+ disabled ||+ !auth.deviceId ||+ !live.current.focused ||+ AppState.currentState !== "active"+ )+ return;+ lock.current = true;+ setBusy(true);+ const generation = ++operation.current,+ epoch = link.connectionEpoch;+ const assertCurrent = () => {+ if (+ !alive.current ||+ generation !== operation.current ||+ !isMobileAuthOwnerCurrent(owner) ||+ !live.current.focused ||+ live.current.epoch !== epoch+ )+ throw new Error("OAUTH_BRIDGE_UNAVAILABLE");+ };+ const invoke = (raw: unknown, cleanup = false) =>+ link.invoke(deviceId, PLUGIN_OAUTH_CHANNEL, [raw], {+ preSend: () => {+ if (cleanup) {+ if (+ !isMobileAuthOwnerCurrent(owner) ||+ live.current.epoch !== epoch+ )+ throw new Error("OAUTH_BRIDGE_UNAVAILABLE");+ } else assertCurrent();+ if (!cleanup && AppState.currentState !== "active")+ throw new Error("OAUTH_BRIDGE_UNAVAILABLE");+ },+ });+ let client:+ Awaited<ReturnType<typeof authenticateMobilePluginOauth>> | undefined;+ try {+ const target = parsePluginOauthPeerIdentity(+ await invoke({ op: "identity", version: 3 }),+ );+ assertCurrent();+ if (+ target.deviceId !== deviceId ||+ target.membershipId !== owner.accountId ||+ accountVaultKey(target.realm, target.membershipId) !== owner.accountKey+ )+ throw new Error("OAUTH_BRIDGE_UNAVAILABLE");+ client = await authenticateMobilePluginOauth({+ crypto: pluginOauthPlatformCrypto,+ target,+ peer: auth.deviceId,+ ghostId: action.ghostId,+ action: action.action,+ assertCurrent,+ invoke,+ trustIdentity: (identity, check) =>+ pinMobilePluginIdentity(+ {+ get: (key) => SecureStore.getItemAsync(key),+ set: (key, value) =>+ SecureStore.setItemAsync(key, value, {+ keychainAccessible:+ SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY,+ }),+ },+ identity,+ auth.deviceId!,+ check,+ ),+ });+ await runMobilePluginAuthorization({+ crypto: pluginOauthPlatformCrypto,+ action: action.action,+ kind: action.kind,+ invoke: client.request,+ assertCurrent,+ secretPresentation: action.secret,+ connectionPresentation: action.connection,+ ...(action.kind === "secret" ? { inputSecret: secret } : {}),+ ...(action.kind === "connection"+ ? { inputConnection: { host, token: secret } }+ : {}),+ clearInput: clear,+ pause: async () => {+ await new Promise((resolve) => setTimeout(resolve, 600));+ while (AppState.currentState !== "active") {+ assertCurrent();+ await new Promise((resolve) => setTimeout(resolve, 600));+ }+ },+ showAuthorization: async (url, code, expiresAt) => {+ assertCurrent();+ if (Date.now() >= expiresAt)+ throw new Error("OAUTH_BRIDGE_UNAVAILABLE");+ setBrowser({ url, code });+ // In-app system browser; it is never a plugin WebView. A device code is only copied on explicit touch.+ const accepted = await new Promise<boolean>((resolve) =>+ Alert.alert(+ t("plugins.connectAccount"),+ new URL(url).hostname + (code ? "\n" + code : ""),+ [+ {+ text: t("plugins.cancel"),+ style: "cancel",+ onPress: () => resolve(false),+ },+ { text: t("plugins.open"), onPress: () => resolve(true) },+ ],+ { cancelable: false },+ ),+ );+ assertCurrent();+ if (!accepted) throw new Error("OAUTH_BRIDGE_UNAVAILABLE");+ await WebBrowser.openBrowserAsync(url, { showTitle: true });+ assertCurrent();+ },+ });+ assertCurrent();+ setSelected(undefined);+ setBrowser(undefined);+ onClosed();+ } catch (e) {+ clear();+ if (+ alive.current &&+ isMobileAuthOwnerCurrent(owner) &&+ generation === operation.current+ ) {+ const identityChanged =+ e instanceof Error &&+ e.message === "PLUGIN_AUTHORIZATION_IDENTITY_CHANGED";+ const computerCallback =+ e instanceof Error &&+ e.message === "PLUGIN_AUTHORIZATION_COMPUTER_CALLBACK";+ Alert.alert(+ identityChanged+ ? t("plugins.identityChanged")+ : computerCallback+ ? t("plugins.computerAuthorization")+ : t("plugins.actionFailed"),+ identityChanged+ ? t("plugins.identityChangedHint")+ : computerCallback+ ? t("plugins.computerAuthorizationHint")+ : t("plugins.authorizationCheckHint"),+ );+ }+ } finally {+ client?.dispose();+ void clearCopiedCode();+ lock.current = false;+ if (alive.current) {+ setBusy(false);+ setBrowser(undefined);+ }+ }+ };+ useEffect(() => {+ if (initialAction.kind === "oauth") void submit(initialAction);+ }, []);+ return (+ <View>+ <SheetModal+ visible={!!selected}+ onRequestClose={close}+ onBackdropPress={() => {}}+ keyboardAvoiding+ >+ <View style={styles.sheet}>+ <ScrollView+ keyboardShouldPersistTaps="handled"+ contentContainerStyle={styles.content}+ >+ <Text style={styles.title}>+ {selected?.secret?.ghostName ??+ selected?.connection?.ghostName ??+ t("plugins.connectAccount")}+ </Text>+ <Text style={styles.body}>{selected?.title}</Text>+ {selected?.secret?.intro || selected?.connection?.intro ? (+ <Text style={styles.hint}>+ {selected.secret?.intro ?? selected.connection?.intro}+ </Text>+ ) : null}+ {selected?.kind === "secret" ? (+ <>+ <Text style={styles.hint}>{selected.secret?.description}</Text>+ <Text style={styles.body}>{selected.secret?.fieldLabel}</Text>+ <TextInput+ accessibilityLabel={selected.secret?.fieldLabel}+ value={secret}+ onChangeText={setSecret}+ secureTextEntry+ autoCapitalize="none"+ autoCorrect={false}+ textContentType="none"+ autoComplete="off"+ editable={!busy}+ maxLength={selected.secret?.maxLength}+ style={styles.input}+ />+ <Text style={styles.hint}>+ {selected.secret?.fieldDescription}+ </Text>+ </>+ ) : null}+ {selected?.kind === "connection" ? (+ <>+ <Text style={styles.hint}>+ {selected.connection?.description}+ </Text>+ <TextInput+ accessibilityLabel={t("plugins.connectionHost")}+ placeholder={t("plugins.connectionHost")}+ placeholderTextColor={colors.textPlaceholder}+ value={host}+ onChangeText={setHost}+ autoCapitalize="none"+ autoCorrect={false}+ editable={!busy}+ maxLength={512}+ style={styles.input}+ />+ <TextInput+ accessibilityLabel={t("plugins.connectionToken")}+ placeholder={t("plugins.connectionToken")}+ placeholderTextColor={colors.textPlaceholder}+ value={secret}+ onChangeText={setSecret}+ secureTextEntry+ autoCapitalize="none"+ autoCorrect={false}+ textContentType="none"+ autoComplete="off"+ editable={!busy}+ maxLength={4096}+ style={styles.input}+ />+ </>+ ) : null}+ {browser ? (+ <>+ <Text style={styles.hint}>{new URL(browser.url).hostname}</Text>+ {browser.code ? (+ <Pressable+ style={styles.row}+ accessibilityRole="button"+ onPress={() => {+ const code = browser.code!;+ void Clipboard.setStringAsync(code)+ .then(() => {+ copiedCode.current = code;+ if (!alive.current) void clearCopiedCode();+ })+ .catch(() => {});+ }}+ >+ <Text style={styles.body}>+ {browser.code} · {t("plugins.copyCode")}+ </Text>+ </Pressable>+ ) : null}+ </>+ ) : null}+ {busy ? (+ <View style={styles.row}>+ <ActivityIndicator color={colors.textSecondary} />+ <Text style={styles.hint}>+ {t("plugins.waitingAuthorization")}+ </Text>+ </View>+ ) : null}+ <View style={styles.buttons}>+ <Pressable+ accessibilityRole="button"+ style={styles.button}+ onPress={close}+ >+ <Text style={styles.body}>{t("plugins.cancel")}</Text>+ </Pressable>+ {selected?.kind !== "oauth" ? (+ <Pressable+ accessibilityRole="button"+ disabled={+ busy ||+ !secret.trim() ||+ (selected?.kind === "connection" && !host.trim())+ }+ style={[styles.button, styles.primary]}+ onPress={() => {+ if (selected) void submit(selected);+ }}+ >+ <Text style={styles.ctaText}>+ {t("plugins.saveConfiguration")}+ </Text>+ </Pressable>+ ) : null}+ </View>+ </ScrollView>+ </View>+ </SheetModal>+ </View>+ );+}+const makeStyles = (colors: ThemeColors) =>+ StyleSheet.create({+ row: {+ minHeight: 44,+ flexDirection: "row",+ alignItems: "center",+ gap: spacing.sm,+ paddingVertical: spacing.sm,+ },+ sheet: {+ backgroundColor: colors.surfaceElevated,+ borderTopLeftRadius: radius.container,+ borderTopRightRadius: radius.container,+ maxHeight: "90%",+ },+ content: { padding: spacing.lg, gap: spacing.md },+ title: {+ fontSize: typeScale.title,+ lineHeight: lineHeight.title,+ fontWeight: fontWeight.semibold,+ color: colors.textPrimary,+ },+ body: {+ fontSize: typeScale.body,+ lineHeight: lineHeight.body,+ fontWeight: fontWeight.regular,+ color: colors.textPrimary,+ },+ hint: {+ fontSize: typeScale.footnote,+ lineHeight: lineHeight.bodySmall,+ fontWeight: fontWeight.regular,+ color: colors.textTertiary,+ },+ input: {+ fontSize: typeScale.bodySmall,+ lineHeight: lineHeight.bodySmall,+ fontWeight: fontWeight.regular,+ color: colors.textPrimary,+ borderWidth: StyleSheet.hairlineWidth,+ borderColor: colors.border,+ borderRadius: radius.control,+ paddingHorizontal: spacing.md,+ minHeight: 44,+ },+ buttons: { flexDirection: "row", gap: spacing.sm },+ button: {+ minHeight: 44,+ paddingHorizontal: spacing.md,+ alignItems: "center",+ justifyContent: "center",+ borderWidth: StyleSheet.hairlineWidth,+ borderColor: colors.border,+ borderRadius: radius.control,+ },+ primary: { backgroundColor: colors.cta },+ ctaText: {+ fontSize: typeScale.body,+ lineHeight: lineHeight.body,+ fontWeight: fontWeight.medium,+ color: colors.ctaText,+ },+ });diff --git a/apps/mobile/src/plugins/PluginTaskPicker.tsx b/apps/mobile/src/plugins/PluginTaskPicker.tsxnew file mode 100644index 0000000000..599820e85c--- /dev/null+++ b/apps/mobile/src/plugins/PluginTaskPicker.tsx@@ -0,0 +1,205 @@+import { useEffect, useMemo, useState } from "react";+import {+ ActivityIndicator,+ Pressable,+ StyleSheet,+ View,+ useWindowDimensions,+} from "react-native";+import { useSafeAreaInsets } from "react-native-safe-area-context";+import { useTranslation } from "react-i18next";+import { Text, TextInput } from "@/components/AppText";+import { useDeviceLink } from "@/device-link/DeviceLinkContext";+import {+ getMobileAuthOwner,+ isMobileAuthOwnerCurrent,+} from "@/auth/authOwnerGeneration";+import { SheetModal } from "@/session/SheetModal";+import { SheetSurface } from "@/session/SheetSurface";+import {+ computeContextSheetSnapHeights,+ type ContextSheetSnap,+} from "@/session/contextSheetModel";+import type { RemoteSession } from "@/session/types";+import {+ fontWeight,+ lineHeight,+ radius,+ spacing,+ typeScale,+ useTheme,+ useThemedStyles,+ type ThemeColors,+} from "@/theme";++/** Host task chooser. Its list is never exposed to plugin JavaScript or cindy.tasks. */+export function PluginTaskPicker({+ deviceId,+ visible,+ onClose,+ onSelect,+}: {+ deviceId: string;+ visible: boolean;+ onClose(): void;+ onSelect(sessionId: string): void;+}) {+ const { invoke } = useDeviceLink(),+ { t } = useTranslation();+ const { colors } = useTheme(),+ styles = useThemedStyles(makeStyles);+ const insets = useSafeAreaInsets(),+ { height } = useWindowDimensions();+ const heights = useMemo(+ () =>+ computeContextSheetSnapHeights({+ safeAreaTopInset: insets.top,+ screenHeight: height,+ }),+ [height, insets.top],+ );+ const [snap, setSnap] = useState<ContextSheetSnap>("half");+ const [query, setQuery] = useState("");+ const [rows, setRows] = useState<RemoteSession[]>([]);+ const [loading, setLoading] = useState(false),+ [error, setError] = useState(false),+ [attempt, setAttempt] = useState(0);+ useEffect(() => {+ if (!visible) return;+ const owner = getMobileAuthOwner();+ let disposed = false;+ const current = () => !disposed && isMobileAuthOwnerCurrent(owner);+ setRows([]);+ setQuery("");+ setLoading(true);+ setError(false);+ setSnap("half");+ void invoke<RemoteSession[]>(+ deviceId,+ "local-db:sessions:list",+ [500, "active", { includePinned: true, fresh: true }],+ {+ preSend: () => {+ if (!current()) throw new Error("PLUGIN_TASK_PICKER_CLOSED");+ },+ },+ )+ .then((value) => {+ if (current())+ setRows(+ Array.isArray(value)+ ? value.filter(+ (row) =>+ row &&+ typeof row.id === "string" &&+ typeof row.title === "string" &&+ row.status === "active" &&+ row.orcaRole !== "worker",+ )+ : [],+ );+ })+ .catch(() => {+ if (current()) setError(true);+ })+ .finally(() => {+ if (current()) setLoading(false);+ });+ return () => {+ disposed = true;+ };+ }, [deviceId, visible, invoke, attempt]);+ return (+ <SheetModal+ nativePresentation+ visible={visible}+ onRequestClose={onClose}+ onBackdropPress={onClose}+ keyboardAvoiding+ >+ <SheetSurface+ title={t("plugins.chooseTask")}+ onClose={onClose}+ heights={heights}+ snap={snap}+ onSnapChange={setSnap}+ bottomInset={insets.bottom}+ pinnedTop={+ <TextInput+ value={query}+ onChangeText={setQuery}+ placeholder={t("plugins.searchTasks")}+ accessibilityLabel={t("plugins.searchTasks")}+ placeholderTextColor={colors.textPlaceholder}+ style={styles.search}+ />+ }+ >+ {loading ? (+ <ActivityIndicator color={colors.textSecondary} />+ ) : error ? (+ <View style={styles.empty}>+ <Text style={styles.note}>{t("plugins.loadFailed")}</Text>+ <Pressable+ style={styles.row}+ onPress={() => setAttempt((value) => value + 1)}+ >+ <Text style={styles.title}>{t("plugins.retry")}</Text>+ </Pressable>+ </View>+ ) : (+ rows+ .filter((row) =>+ row.title.toLocaleLowerCase().includes(query.toLocaleLowerCase()),+ )+ .map((row) => (+ <Pressable+ key={row.id}+ style={styles.row}+ onPress={() => onSelect(row.id)}+ >+ <Text numberOfLines={1} style={styles.title}>+ {row.title}+ </Text>+ {row.preview ? (+ <Text numberOfLines={2} style={styles.note}>+ {row.preview}+ </Text>+ ) : null}+ </Pressable>+ ))+ )}+ {!loading && !error && !rows.length ? (+ <Text style={styles.note}>{t("plugins.noTasks")}</Text>+ ) : null}+ </SheetSurface>+ </SheetModal>+ );+}+const makeStyles = (c: ThemeColors) =>+ StyleSheet.create({+ row: { minHeight: 56, padding: spacing.md, gap: spacing.xs },+ empty: { padding: spacing.md, gap: spacing.sm },+ search: {+ margin: spacing.md,+ padding: spacing.md,+ borderRadius: radius.control,+ backgroundColor: c.surfaceChip,+ color: c.textPrimary,+ fontSize: typeScale.bodySmall,+ lineHeight: lineHeight.bodySmall,+ fontWeight: fontWeight.regular,+ },+ title: {+ color: c.textPrimary,+ fontSize: typeScale.body,+ lineHeight: lineHeight.body,+ fontWeight: fontWeight.medium,+ },+ note: {+ color: c.textSecondary,+ fontSize: typeScale.footnote,+ lineHeight: lineHeight.caption,+ fontWeight: fontWeight.regular,+ },+ });diff --git a/apps/mobile/src/plugins/PluginTaskSettings.tsx b/apps/mobile/src/plugins/PluginTaskSettings.tsxnew file mode 100644index 0000000000..1afabce13a--- /dev/null+++ b/apps/mobile/src/plugins/PluginTaskSettings.tsx@@ -0,0 +1,344 @@+import { useEffect, useRef, useState } from "react";+import {+ ActivityIndicator,+ Alert,+ Platform,+ Pressable,+ StyleSheet,+ View,+} from "react-native";+import { ChevronRight } from "lucide-react-native";+import { useTranslation } from "react-i18next";+import type { PluginTaskPreferences } from "@cindy/device-link";+import { Text } from "@/components/AppText";+import { useDeviceLink } from "@/device-link/DeviceLinkContext";+import { useDeviceProviders } from "@/device-link/useDeviceProviders";+import { useMobileMakerTransport } from "@/device-link/useMobileMakerTransport";+import {+ getMobileAuthOwner,+ isMobileAuthOwnerCurrent,+} from "@/auth/authOwnerGeneration";+import { ModelPickerSheet } from "@/session/ModelPickerSheet";+import {+ normalizeMobileAgentCapabilities,+ type MobileAgentCapabilities,+} from "@/session/agentCapabilities";+import { permissionPresentation } from "@/session/permissionPresentation";+import {+ iconSize,+ fontWeight,+ lineHeight,+ radius,+ spacing,+ typeScale,+ useTheme,+ useThemedStyles,+ type ThemeColors,+} from "@/theme";+import { invokePlugin } from "./pluginClient";++/** Native Host settings. Author content has no access to this invoke or stored configuration. */+export function PluginTaskSettings({+ deviceId,+ pluginId,+}: {+ deviceId: string;+ pluginId: string;+}) {+ const { t } = useTranslation(),+ { invoke } = useDeviceLink(),+ { colors } = useTheme(),+ styles = useThemedStyles(makeStyles);+ const maker = useMobileMakerTransport(deviceId),+ providers = useDeviceProviders(deviceId);+ const [preferences, setPreferences] = useState<PluginTaskPreferences>();+ const [error, setError] = useState(false),+ [picker, setPicker] = useState(false),+ [busy, setBusy] = useState(false);+ const [capabilities, setCapabilities] =+ useState<MobileAgentCapabilities | null>(null);+ const alive = useRef(true),+ lock = useRef(false),+ owner = useRef(getMobileAuthOwner()).current;+ const current = () => alive.current && isMobileAuthOwnerCurrent(owner);+ const call = <T,>(action: string, input: Record<string, unknown> = {}) =>+ invokePlugin<T>(+ (device, channel, args) =>+ invoke(device, channel, args, {+ preSend: () => {+ if (!current()) throw new Error("PLUGIN_SETTINGS_CLOSED");+ },+ }),+ deviceId,+ pluginId,+ action,+ input,+ );+ const load = async () => {+ try {+ const value = await call<PluginTaskPreferences>("task-settings:get");+ if (+ !value ||+ typeof value.revision !== "string" ||+ !value.config ||+ !Array.isArray(value.permissionModes)+ )+ throw new Error("PLUGIN_SETTINGS_INVALID");+ if (current()) {+ setPreferences(value);+ setError(false);+ }+ } catch {+ if (current()) setError(true);+ }+ };+ useEffect(() => {+ alive.current = true;+ void load();+ return () => {+ alive.current = false;+ };+ }, []);+ const config = preferences?.config;+ const agent =+ config?.agentKind === "cc" ? "claude-code" : (config?.agentKind ?? "codex");+ useEffect(() => {+ let cancelled = false;+ if (!picker) return;+ setCapabilities(null);+ void maker+ .getCapabilities(agent)+ .then((raw) => {+ if (!cancelled && current())+ setCapabilities(normalizeMobileAgentCapabilities(raw));+ })+ .catch(() => {});+ return () => {+ cancelled = true;+ };+ }, [picker, maker, agent]);+ const save = async (patch: Record<string, unknown>) => {+ if (!preferences || lock.current || !current()) return false;+ lock.current = true;+ setBusy(true);+ try {+ const value = await call<PluginTaskPreferences>("task-settings:set", {+ expectedRevision: preferences.revision,+ ...patch,+ });+ if (!current()) return false;+ setPreferences(value);+ setError(false);+ return true;+ } catch {+ if (current()) {+ setError(true);+ Alert.alert(t("plugins.actionFailed"));+ }+ // Unknown receipt is read back only; configuration writes are never automatically replayed.+ return false;+ } finally {+ lock.current = false;+ if (current()) setBusy(false);+ }+ };+ const choosePermission = () => {+ if (!preferences || busy) return;+ Alert.alert(t("plugins.taskPermission"), t("plugins.permissionHint"), [+ ...preferences.permissionModes.map((mode) => ({+ text: permissionPresentation(mode).label,+ onPress: () => {+ if (mode === "auto")+ Alert.alert(+ t("plugins.taskPermission"),+ t("plugins.autoPermissionHint"),+ [+ { text: t("plugins.cancel"), style: "cancel" },+ {+ text: t("plugins.confirm"),+ onPress: () => {+ void save({ permissionMode: mode });+ },+ },+ ],+ );+ else void save({ permissionMode: mode });+ },+ })),+ {+ text: t("plugins.followDefault"),+ onPress: () => {+ void save({ permissionMode: null });+ },+ },+ { text: t("plugins.cancel"), style: "cancel" },+ ]);+ };+ const name =+ providers.providers+ .find((p) => p.id === config?.providerId)+ ?.models[agent]?.find((m) => m.id === config?.model)?.name ??+ config?.model;+ return (+ <View>+ <Text style={styles.label}>{t("plugins.taskSettings")}</Text>+ <View style={styles.card}>+ <Pressable+ accessibilityRole="button"+ disabled={!preferences || busy || error}+ style={styles.row}+ onPress={() => setPicker(true)}+ >+ <View style={styles.fill}>+ <Text style={styles.title}>{t("plugins.taskModel")}</Text>+ <Text style={styles.secondary}>+ {name ?? t("plugins.followDefault")}+ </Text>+ </View>+ <ChevronRight size={iconSize.md} color={colors.textTertiary} />+ </Pressable>+ <Pressable+ accessibilityRole="button"+ disabled={!preferences || busy || error}+ style={styles.row}+ onPress={choosePermission}+ >+ <Text style={[styles.title, styles.fill]}>+ {t("plugins.taskPermission")}+ </Text>+ <Text style={styles.secondary}>+ {preferences+ ? permissionPresentation(+ config?.permissionMode ?? preferences.defaultPermissionMode,+ ).label+ : ""}+ </Text>+ <ChevronRight size={iconSize.md} color={colors.textTertiary} />+ </Pressable>+ {config?.model ? (+ <Pressable+ accessibilityRole="button"+ disabled={busy || error}+ style={styles.row}+ onPress={() => {+ void save({ model: null });+ }}+ >+ <Text style={styles.secondary}>{t("plugins.followDefault")}</Text>+ </Pressable>+ ) : null}+ </View>+ <Text style={styles.hint}>{t("plugins.taskSettingsHint")}</Text>+ {busy || (!preferences && !error) ? (+ <ActivityIndicator color={colors.textSecondary} />+ ) : null}+ {error ? (+ <Pressable+ accessibilityRole="button"+ style={styles.row}+ onPress={() => {+ void load();+ }}+ >+ <Text style={styles.secondary}>{t("plugins.settingsReload")}</Text>+ </Pressable>+ ) : null}+ <ModelPickerSheet+ visible={picker}+ onClose={() => setPicker(false)}+ agentKind={agent}+ providers={providers.providers}+ providersReady={providers.ready}+ providersUnsupported={providers.unsupported}+ modelVisibilityOverrides={providers.modelVisibilityOverrides}+ flatOptions={[]}+ capabilities={capabilities}+ activeModelId={config?.model ?? ""}+ selectedProviderId={config?.providerId ?? null}+ selectedEffort={config?.effort ?? ""}+ selectedFastMode={config?.fastMode ?? false}+ loading={providers.loading}+ disabled={busy || error}+ hidePermissionTrigger+ activePermissionMode={+ config?.permissionMode ?? preferences?.defaultPermissionMode ?? ""+ }+ permissionOptions={[]}+ onSelectPermissionMode={() => {}}+ onSelectFlatModel={() => {}}+ onSelectProviderRow={() => {}}+ keyboardAvoidingBehavior={Platform.OS === "ios" ? "padding" : "height"}+ emptyHint={t("plugins.modelsUnavailable")}+ unified={{+ scope: JSON.stringify([owner.accountKey, deviceId]),+ agents: ["claude-code", "codex", "pi"],+ loadCapabilities: async (kind) => {+ const caps = normalizeMobileAgentCapabilities(+ await maker.getCapabilities(kind),+ );+ if (!caps) throw new Error("CAPABILITIES_UNAVAILABLE");+ return caps;+ },+ onSelect: async (value) => {+ const result = await save({+ model: {+ agentKind: value.agent === "claude-code" ? "cc" : value.agent,+ model: value.modelId,+ providerId: value.providerId,+ ...(value.effort ? { effort: value.effort } : {}),+ fastMode: value.fast,+ },+ });+ if (result && current()) setPicker(false);+ return result;+ },+ }}+ />+ </View>+ );+}+const makeStyles = (colors: ThemeColors) =>+ StyleSheet.create({+ fill: { flex: 1 },+ label: {+ fontSize: typeScale.footnote,+ lineHeight: lineHeight.bodySmall,+ fontWeight: fontWeight.regular,+ color: colors.textTertiary,+ marginBottom: spacing.sm,+ },+ card: {+ borderWidth: StyleSheet.hairlineWidth,+ borderColor: colors.border,+ borderRadius: radius.container,+ backgroundColor: colors.surfaceElevated,+ overflow: "hidden",+ },+ row: {+ minHeight: 52,+ paddingHorizontal: spacing.md,+ paddingVertical: spacing.sm,+ flexDirection: "row",+ alignItems: "center",+ gap: spacing.sm,+ },+ title: {+ fontSize: typeScale.body,+ lineHeight: lineHeight.body,+ fontWeight: fontWeight.regular,+ color: colors.textPrimary,+ },+ secondary: {+ fontSize: typeScale.bodySmall,+ lineHeight: lineHeight.bodySmall,+ fontWeight: fontWeight.regular,+ color: colors.textSecondary,+ },+ hint: {+ fontSize: typeScale.footnote,+ lineHeight: lineHeight.bodySmall,+ fontWeight: fontWeight.regular,+ color: colors.textTertiary,+ marginVertical: spacing.sm,+ },+ });diff --git a/apps/mobile/src/plugins/PluginsScreen.tsx b/apps/mobile/src/plugins/PluginsScreen.tsxnew file mode 100644index 0000000000..ed2fa7db22--- /dev/null+++ b/apps/mobile/src/plugins/PluginsScreen.tsx@@ -0,0 +1,764 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import {+ ActivityIndicator,+ Alert,+ BackHandler,+ Image,+ Pressable,+ RefreshControl,+ ScrollView,+ StyleSheet,+ View,+ useWindowDimensions,+} from "react-native";+import { useIsFocused, useRouter } from "expo-router";+import { goBackGuarded } from "@/utils/backGuard";+import { SafeAreaView } from "react-native-safe-area-context";+import { useTranslation } from "react-i18next";+import {+ ChevronDown,+ ChevronRight,+ Info,+ Monitor,+ Puzzle,+ Search,+ Settings,+} from "lucide-react-native";+import {+ resolveRemoteText,+ type PluginPageSurface,+ type RemoteResource,+} from "@cindy/device-link";+import { Text, TextInput } from "@/components/AppText";+import { useAuth } from "@/auth/AuthContext";+import { useDeviceLink } from "@/device-link/DeviceLinkContext";+import { useDeviceManagement } from "@/device-link/useDeviceManagement";+import {+ getRemoteResource,+ type HostedRemoteCollectionItem,+} from "@/device-link/remoteResources";+import { useRemoteResourceList } from "@/session/useRemoteResourceList";+import {+ SimpleStackHeader,+ simpleScreenSafeAreaEdges,+} from "@/platform/chrome/SimpleStackHeader";+import {+ fontWeight,+ iconSize,+ lineHeight,+ radius,+ spacing,+ typeScale,+ useTheme,+ useThemedStyles,+ type ThemeColors,+} from "@/theme";+import AsyncStorage from "@react-native-async-storage/async-storage";+import {+ getMobileAuthOwner,+ isMobileAuthOwnerCurrent,+} from "@/auth/authOwnerGeneration";+import { PluginTaskPicker } from "./PluginTaskPicker";+import { PluginTaskSettings } from "./PluginTaskSettings";+import { PluginPage } from "./PluginPage";+import { invokePlugin } from "./pluginClient";++export default function PluginsScreen() {+ const auth = useAuth();+ return <PluginDirectory key={auth.accountGeneration} />;+}+function PluginDirectory() {+ const auth = useAuth(),+ router = useRouter(),+ focused = useIsFocused();+ const { t, i18n } = useTranslation();+ const { invoke } = useDeviceLink();+ const { colors } = useTheme(),+ styles = useThemedStyles(makeStyles);+ const { width } = useWindowDimensions();+ const wide = width >= 768;+ const devices = useDeviceManagement(auth.apiFetch, focused);+ const targets = useMemo(+ () =>+ devices.devices+ .filter(+ (d) =>+ d.remoteControlEnabled &&+ !d.isSelf &&+ !["ios", "android"].includes(d.platform ?? ""),+ )+ .map((d) => ({ deviceId: d.deviceId, deviceName: d.name })),+ [devices.devices],+ );+ const list = useRemoteResourceList("plugins", targets);+ const [deviceId, setDeviceId] = useState("");+ const [query, setQuery] = useState("");+ const [filter, setFilter] = useState<"all" | "unread">("all");+ const [selected, setSelected] = useState<{+ row: HostedRemoteCollectionItem;+ surface?: PluginPageSurface;+ }>();+ const [detailOpen, setDetailOpen] = useState(false);+ const [detail, setDetail] = useState<RemoteResource>();+ const [recent, setRecent] = useState<string[]>([]);+ const [busy, setBusy] = useState(false);+ const [taskPicker, setTaskPicker] = useState(false);+ const [pageTitle, setPageTitle] = useState("");+ useEffect(() => {+ setPageTitle("");+ }, [selected?.row.key, selected?.surface]);+ const pageBack = useRef<(() => void) | null>(null);+ const registerBack = useCallback((handler: (() => void) | null) => {+ pageBack.current = handler;+ }, []);+ const goBack = useCallback(() => {+ if (detailOpen && selected?.surface) setDetailOpen(false);+ else if (selected?.surface && pageBack.current) pageBack.current();+ else if (selected && !wide) {+ detailGeneration.current += 1;+ setSelected(undefined);+ } else goBackGuarded(router);+ }, [detailOpen, selected, wide, router]);+ useEffect(() => {+ if (!focused || !selected || wide) return;+ const listener = BackHandler.addEventListener("hardwareBackPress", () => {+ goBack();+ return true;+ });+ return () => listener.remove();+ }, [focused, selected, wide, goBack]);+ const detailGeneration = useRef(0),+ recentTouched = useRef(false);+ const recentOwner = useRef(getMobileAuthOwner()).current;+ const recentKey = `cindy.pluginRecent.v1.${recentOwner.accountKey}`;+ useEffect(() => {+ let disposed = false;+ void AsyncStorage.getItem(recentKey)+ .then((raw) => {+ if (+ disposed ||+ !isMobileAuthOwnerCurrent(recentOwner) ||+ recentTouched.current ||+ !raw ||+ raw.length > 8000+ )+ return;+ try {+ const value = JSON.parse(raw);+ if (Array.isArray(value))+ setRecent(+ value.filter((key) => typeof key === "string").slice(0, 6),+ );+ } catch {+ /* optional local history */+ }+ })+ .catch(() => {});+ return () => {+ disposed = true;+ detailGeneration.current += 1;+ };+ }, [recentKey, recentOwner]);+ useEffect(() => {+ if (recentTouched.current && isMobileAuthOwnerCurrent(recentOwner))+ void AsyncStorage.setItem(recentKey, JSON.stringify(recent)).catch(+ () => {},+ );+ }, [recent, recentKey, recentOwner]);+ const text = (value: Parameters<typeof resolveRemoteText>[0]) =>+ resolveRemoteText(value, i18n.language);+ const items = list.items.filter(+ ({ host, item }) =>+ (!deviceId || host.deviceId === deviceId) &&+ (filter === "all" || item.display.badges?.length) &&+ `${text(item.display.title)} ${item.display.subtitle ? text(item.display.subtitle) : ""}`+ .toLocaleLowerCase()+ .includes(query.toLocaleLowerCase()),+ );+ const showDetail = async (row: HostedRemoteCollectionItem) => {+ const generation = ++detailGeneration.current,+ owner = getMobileAuthOwner();+ setSelected((current) =>+ current?.row.key === row.key ? { ...current, row } : { row },+ );+ setDetailOpen(true);+ setDetail(undefined);+ try {+ const resource = await getRemoteResource(+ invoke,+ row.host,+ row.item.ref,+ i18n.language,+ ["plugin-capabilities"],+ );+ if (+ generation === detailGeneration.current &&+ isMobileAuthOwnerCurrent(owner)+ )+ setDetail(resource);+ } catch {+ if (+ generation === detailGeneration.current &&+ isMobileAuthOwnerCurrent(owner)+ )+ Alert.alert(t("plugins.loadFailed"));+ }+ };+ const open = (+ row: HostedRemoteCollectionItem,+ surface?: PluginPageSurface,+ ) => {+ if (!list.isOnline(row.host)) {+ Alert.alert(t("plugins.offline"));+ return;+ }+ const action = surface+ ? row.item.actions?.find((a) => a.id === `open:${surface}`)+ : (row.item.actions?.find((a) => a.id === "open:panel") ??+ row.item.actions?.find((a) => a.id === "open:mainView"));+ if (!action || action.disabled) {+ void showDetail(row);+ return;+ }+ detailGeneration.current += 1;+ recentTouched.current = true;+ setDetailOpen(false);+ setSelected({ row, surface: action.id.slice(5) as PluginPageSurface });+ setRecent((current) =>+ [row.key, ...current.filter((key) => key !== row.key)].slice(0, 6),+ );+ };+ const openTask = useCallback(+ (sessionId: string) => {+ if (selected)+ router.push({+ pathname: "/sessions/[sessionId]",+ params: { sessionId, deviceId: selected.row.host.deviceId },+ });+ },+ [router, selected],+ );+ const selectDevice = () =>+ Alert.alert(t("plugins.computer"), undefined, [+ { text: t("plugins.allComputers"), onPress: () => setDeviceId("") },+ ...targets.map((host) => ({+ text: host.deviceName,+ onPress: () => setDeviceId(host.deviceId),+ })),+ { text: t("plugins.cancel"), style: "cancel" },+ ]);+ const icon = (row: HostedRemoteCollectionItem) => {+ const uri = row.item.display.avatar?.value;+ return uri &&+ /^data:image\/(?:png|jpeg|webp|svg\+xml);base64,/.test(uri) ? (+ <Image source={{ uri }} style={styles.icon} />+ ) : (+ <View style={[styles.icon, styles.fallback]}>+ <Puzzle color={colors.textSecondary} size={iconSize.lg} />+ </View>+ );+ };+ const renderRow = (row: HostedRemoteCollectionItem) => (+ <View+ key={row.key}+ style={[+ styles.row,+ selected?.row.key === row.key && wide && styles.selected,+ ]}+ >+ <Pressable+ accessibilityRole="button"+ onPress={() => open(row)}+ style={styles.rowMain}+ >+ {icon(row)}+ <View style={styles.rowText}>+ <View style={styles.inline}>+ <Text numberOfLines={1} style={styles.rowTitle}>+ {text(row.item.display.title)}+ </Text>+ {row.item.display.badges?.length ? (+ <View+ accessibilityLabel={t("plugins.unread")}+ style={styles.dot}+ />+ ) : null}+ </View>+ <Text numberOfLines={2} style={styles.preview}>+ {row.item.display.preview+ ? text(row.item.display.preview)+ : row.item.display.subtitle+ ? text(row.item.display.subtitle)+ : ""}+ </Text>+ {targets.length > 1 || !list.isOnline(row.host) ? (+ <Text style={styles.meta}>+ {row.host.deviceName}+ {!list.isOnline(row.host)+ ? ` · ${t("plugins.notConnected")}`+ : ""}+ </Text>+ ) : null}+ </View>+ </Pressable>+ <Pressable+ accessibilityRole="button"+ accessibilityLabel={t("plugins.detailsFor", {+ name: text(row.item.display.title),+ })}+ style={styles.info}+ onPress={() => {+ void showDetail(row);+ }}+ >+ <Info color={colors.textTertiary} size={iconSize.md} />+ </Pressable>+ </View>+ );+ const directory = (+ <View style={[styles.directory, wide && styles.sidebar]}>+ <View style={styles.controls}>+ <Pressable+ accessibilityRole="button"+ style={styles.device}+ onPress={selectDevice}+ >+ <Monitor size={iconSize.sm} color={colors.textSecondary} />+ <Text style={styles.controlText}>+ {targets.find((h) => h.deviceId === deviceId)?.deviceName ??+ t("plugins.allComputers")}+ </Text>+ <ChevronDown size={iconSize.sm} color={colors.textSecondary} />+ </Pressable>+ <View style={styles.search}>+ <Search size={iconSize.md} color={colors.textTertiary} />+ <TextInput+ value={query}+ onChangeText={setQuery}+ placeholder={t("plugins.search")}+ placeholderTextColor={colors.textPlaceholder}+ style={styles.input}+ accessibilityLabel={t("plugins.search")}+ clearButtonMode="while-editing"+ />+ </View>+ <View style={styles.inline}>+ {(["all", "unread"] as const).map((value) => (+ <Pressable+ key={value}+ accessibilityRole="button"+ accessibilityState={{ selected: filter === value }}+ onPress={() => setFilter(value)}+ style={[styles.chip, filter === value && styles.selected]}+ >+ <Text style={styles.controlText}>{t(`plugins.${value}`)}</Text>+ </Pressable>+ ))}+ </View>+ </View>+ <ScrollView+ contentContainerStyle={styles.content}+ refreshControl={+ <RefreshControl+ refreshing={list.refreshing}+ onRefresh={() => {+ devices.refresh();+ void list.refresh();+ }}+ tintColor={colors.textSecondary}+ />+ }+ >+ {list.loading && !items.length ? (+ <ActivityIndicator color={colors.textSecondary} />+ ) : null}+ {!query &&+ filter === "all" &&+ recent.some((key) => items.some((row) => row.key === key)) ? (+ <>+ <Text style={styles.groupLabel}>{t("plugins.recent")}</Text>+ <View style={styles.groupCard}>+ {recent.flatMap((key) => {+ const row = items.find((r) => r.key === key);+ return row ? [renderRow(row)] : [];+ })}+ </View>+ </>+ ) : null}+ <Text style={styles.groupLabel}>{t("plugins.installed")}</Text>+ <View style={styles.groupCard}>{items.map(renderRow)}</View>+ {!list.loading && !items.length ? (+ <View style={styles.empty}>+ <Puzzle size={iconSize.xl} color={colors.textTertiary} />+ <Text style={styles.preview}>+ {t(+ query+ ? "plugins.noResults"+ : targets.length+ ? "plugins.noPlugins"+ : "plugins.noComputer",+ )}+ </Text>+ {!targets.length ? (+ <Pressable+ style={styles.button}+ onPress={() => router.push("/devices/manage")}+ >+ <Text style={styles.controlText}>+ {t("plugins.connectComputer")}+ </Text>+ </Pressable>+ ) : null}+ </View>+ ) : null}+ {list.error ? (+ <Text style={styles.note}>{t("plugins.listUnavailable")}</Text>+ ) : null}+ </ScrollView>+ </View>+ );+ const enable = async () => {+ if (!selected || busy) return;+ setBusy(true);+ try {+ const action = selected.row.item.actions?.find(+ (a) => a.id === "enable" || a.id === "disable",+ );+ if (action)+ await invokePlugin(+ invoke,+ selected.row.host.deviceId,+ selected.row.item.ref.id,+ action.id,+ );+ await list.refresh();+ setSelected(undefined);+ } catch {+ Alert.alert(t("plugins.actionFailed"));+ } finally {+ setBusy(false);+ }+ };+ const detailView = selected ? (+ <ScrollView contentContainerStyle={styles.detail}>+ <View style={styles.identity}>+ {icon(selected.row)}+ <View style={styles.rowText}>+ <Text style={styles.title}>+ {text(selected.row.item.display.title)}+ </Text>+ <Text style={styles.meta}>{selected.row.host.deviceName}</Text>+ </View>+ </View>+ <Text style={styles.preview}>+ {selected.row.item.display.subtitle+ ? text(selected.row.item.display.subtitle)+ : ""}+ </Text>+ <View style={styles.groupCard}>+ {selected.row.item.actions+ ?.filter((action) => action.id.startsWith("open:"))+ .map((action) => (+ <Pressable+ key={action.id}+ disabled={action.disabled}+ style={styles.settingRow}+ onPress={() =>+ open(selected.row, action.id.slice(5) as PluginPageSurface)+ }+ >+ <Text style={styles.controlText}>+ {t(`plugins.${action.id.slice(5)}`)}+ </Text>+ <ChevronRight size={iconSize.md} color={colors.textTertiary} />+ </Pressable>+ ))}+ </View>+ {detail?.blocks?.some(+ (block) =>+ block.id === "capabilities" &&+ (block.data as { tasks?: boolean } | undefined)?.tasks,+ ) ? (+ <PluginTaskSettings+ key={selected.row.key}+ deviceId={selected.row.host.deviceId}+ pluginId={selected.row.item.ref.id}+ />+ ) : null}+ <Text style={styles.groupLabel}>{t("plugins.useInTask")}</Text>+ <View style={styles.groupCard}>+ <Pressable+ style={styles.settingRow}+ onPress={() =>+ router.push({+ pathname: "/sessions/new",+ params: {+ deviceId: selected.row.host.deviceId,+ deviceName: selected.row.host.deviceName,+ draft: t("plugins.taskDraft", {+ name: text(selected.row.item.display.title),+ }),+ },+ })+ }+ >+ <Text style={styles.controlText}>{t("plugins.newTask")}</Text>+ <ChevronRight size={iconSize.md} color={colors.textTertiary} />+ </Pressable>+ <Pressable+ style={styles.settingRow}+ onPress={() => setTaskPicker(true)}+ >+ <Text style={styles.controlText}>{t("plugins.chooseTask")}</Text>+ <ChevronRight size={iconSize.md} color={colors.textTertiary} />+ </Pressable>+ </View>+ <Text style={styles.note}>{t("plugins.taskHint")}</Text>+ {!selected.row.item.actions?.some(+ (a) => a.id === "open:panel" || a.id === "open:mainView",+ ) ? (+ <Text style={styles.note}>{t("plugins.noMobilePage")}</Text>+ ) : null}+ {detail?.blocks+ ?.filter((block) => block.id === "version")+ .map((block) => (+ <Text key={block.id} style={styles.meta}>+ {block.fallbackMarkdown}+ </Text>+ ))}+ <Pressable+ disabled={busy}+ style={styles.settingRow}+ onPress={() => {+ void enable();+ }}+ >+ <Text style={styles.controlText}>+ {t(+ selected.row.item.actions?.some((a) => a.id === "disable")+ ? "plugins.disable"+ : "plugins.enable",+ )}+ </Text>+ {busy ? (+ <ActivityIndicator />+ ) : (+ <Settings color={colors.textSecondary} size={iconSize.md} />+ )}+ </Pressable>+ </ScrollView>+ ) : (+ <View style={styles.empty}>+ <Puzzle color={colors.textTertiary} size={iconSize.xl} />+ <Text style={styles.preview}>{t("plugins.selectPlugin")}</Text>+ </View>+ );+ return (+ <SafeAreaView edges={simpleScreenSafeAreaEdges()} style={styles.root}>+ <SimpleStackHeader+ title={+ selected && !wide+ ? (!detailOpen && selected.surface && pageTitle) ||+ text(selected.row.item.display.title)+ : t("plugins.title")+ }+ onBack={goBack}+ right={+ selected?.surface && !detailOpen ? (+ <Pressable+ accessibilityLabel={t("plugins.details")}+ style={styles.info}+ onPress={() => {+ void showDetail(selected.row);+ }}+ >+ <Info size={iconSize.md} color={colors.textPrimary} />+ </Pressable>+ ) : undefined+ }+ />+ {selected ? (+ <PluginTaskPicker+ deviceId={selected.row.host.deviceId}+ visible={taskPicker}+ onClose={() => setTaskPicker(false)}+ onSelect={(sessionId) => {+ setTaskPicker(false);+ router.push({+ pathname: "/sessions/[sessionId]",+ params: {+ sessionId,+ deviceId: selected.row.host.deviceId,+ deviceName: selected.row.host.deviceName,+ draft: t("plugins.taskDraft", {+ name: text(selected.row.item.display.title),+ }),+ },+ });+ }}+ />+ ) : null}+ <View style={styles.layout}>+ {wide || !selected ? directory : null}+ {wide || selected ? (+ <View style={styles.main}>+ {selected?.surface ? (+ <View style={[styles.main, detailOpen && styles.hidden]}>+ <PluginPage+ visible={!detailOpen}+ key={`${selected.row.key}:${selected.surface}`}+ deviceId={selected.row.host.deviceId}+ pluginId={selected.row.item.ref.id}+ surface={selected.surface}+ onTask={openTask}+ registerBack={registerBack}+ onTitle={setPageTitle}+ />+ </View>+ ) : null}+ {!selected?.surface || detailOpen ? detailView : null}+ </View>+ ) : null}+ </View>+ </SafeAreaView>+ );+}+const makeStyles = (c: ThemeColors) =>+ StyleSheet.create({+ hidden: { display: "none" },+ root: { flex: 1, backgroundColor: c.surface },+ layout: { flex: 1, flexDirection: "row" },+ main: { flex: 1 },+ directory: { flex: 1 },+ sidebar: {+ flex: 0,+ width: 320,+ borderRightWidth: StyleSheet.hairlineWidth,+ borderRightColor: c.border,+ },+ controls: { padding: spacing.md, gap: spacing.sm },+ content: { padding: spacing.md, gap: spacing.md },+ detail: { padding: spacing.lg, gap: spacing.lg },+ inline: { flexDirection: "row", alignItems: "center", gap: spacing.sm },+ device: {+ minHeight: 44,+ flexDirection: "row",+ alignItems: "center",+ gap: spacing.sm,+ },+ search: {+ flexDirection: "row",+ alignItems: "center",+ gap: spacing.sm,+ paddingHorizontal: spacing.md,+ minHeight: 44,+ borderRadius: radius.control,+ backgroundColor: c.surfaceElevated,+ },+ input: {+ flex: 1,+ color: c.textPrimary,+ fontSize: typeScale.bodySmall,+ fontWeight: fontWeight.regular,+ paddingVertical: spacing.sm,+ },+ chip: {+ minHeight: 44,+ paddingHorizontal: spacing.md,+ justifyContent: "center",+ borderRadius: radius.pill,+ },+ selected: { backgroundColor: c.surfaceChip },+ groupCard: {+ borderRadius: radius.container,+ backgroundColor: c.surfaceElevated,+ overflow: "hidden",+ },+ row: { flexDirection: "row", alignItems: "center" },+ rowMain: {+ flex: 1,+ flexDirection: "row",+ alignItems: "center",+ padding: spacing.md,+ gap: spacing.md,+ minHeight: 88,+ },+ rowText: { flex: 1, gap: spacing.xs },+ icon: { width: 44, height: 44, borderRadius: radius.control },+ fallback: {+ alignItems: "center",+ justifyContent: "center",+ backgroundColor: c.surfaceChip,+ },+ info: {+ width: 44,+ minHeight: 44,+ alignItems: "center",+ justifyContent: "center",+ },+ dot: {+ width: 6,+ height: 6,+ borderRadius: radius.pill,+ backgroundColor: c.statusDone,+ },+ identity: { flexDirection: "row", alignItems: "center", gap: spacing.md },+ empty: {+ flex: 1,+ padding: spacing.xl,+ alignItems: "center",+ justifyContent: "center",+ gap: spacing.md,+ },+ settingRow: {+ minHeight: 52,+ flexDirection: "row",+ alignItems: "center",+ justifyContent: "space-between",+ padding: spacing.md,+ },+ button: { padding: spacing.md, minHeight: 44 },+ title: {+ fontSize: typeScale.title,+ lineHeight: lineHeight.title,+ fontWeight: fontWeight.semibold,+ color: c.textPrimary,+ },+ rowTitle: {+ flexShrink: 1,+ fontSize: typeScale.subtitle,+ lineHeight: lineHeight.subtitle,+ fontWeight: fontWeight.medium,+ color: c.textPrimary,+ },+ controlText: {+ fontSize: typeScale.body,+ lineHeight: lineHeight.body,+ fontWeight: fontWeight.medium,+ color: c.textPrimary,+ },+ preview: {+ fontSize: typeScale.bodySmall,+ lineHeight: lineHeight.bodySmall,+ fontWeight: fontWeight.regular,+ color: c.textSecondary,+ },+ note: {+ fontSize: typeScale.footnote,+ lineHeight: lineHeight.caption,+ fontWeight: fontWeight.regular,+ color: c.textSecondary,+ },+ meta: {+ fontSize: typeScale.caption,+ lineHeight: lineHeight.caption,+ fontWeight: fontWeight.regular,+ color: c.textTertiary,+ },+ groupLabel: {+ fontSize: typeScale.footnote,+ lineHeight: lineHeight.caption,+ fontWeight: fontWeight.semibold,+ color: c.textTertiary,+ },+ });diff --git a/apps/mobile/src/plugins/pluginAuthorizationController.ts b/apps/mobile/src/plugins/pluginAuthorizationController.tsnew file mode 100644index 0000000000..3fc132cb25--- /dev/null+++ b/apps/mobile/src/plugins/pluginAuthorizationController.ts@@ -0,0 +1,181 @@+import {+ PLUGIN_OAUTH_TTL_MS,+ oauthExact,+ oauthId,+ oauthPublicKey,+ parsePluginSecretOffer,+ parsePluginSecretInput,+ parsePluginConnectionOffer,+ parsePluginConnectionInput,+ parsePluginAuthorizationOffer,+ parsePluginDeviceOffer,+ type PluginOauthRequest,+ type PluginOauthAction,+ type PluginSecretPresentation,+ type PluginConnectionPresentation,+} from "@cindy/device-link";+import { MobileOauthBox, type PluginOauthCrypto } from "./pluginOauthCrypto";+const object = (v: unknown): Record<string, unknown> => {+ if (!v || typeof v !== "object" || Array.isArray(v))+ throw new Error("OAUTH_BRIDGE_UNAVAILABLE");+ return v as Record<string, unknown>;+};+/** Presentation/inputs remain in a dedicated native form. The execution Host owns exchange, vault save and result. */+export async function runMobilePluginAuthorization(deps: {+ crypto: PluginOauthCrypto;+ invoke(request: PluginOauthRequest): Promise<unknown>;+ action: PluginOauthAction;+ kind: "oauth" | "secret" | "connection";+ secretPresentation?: PluginSecretPresentation;+ connectionPresentation?: PluginConnectionPresentation;+ inputSecret?: string;+ inputConnection?: { host: string; token: string };+ showAuthorization(+ url: string,+ code: string | undefined,+ expiresAt: number,+ ): Promise<void>;+ clearInput(): void;+ assertCurrent(): void;+ pause(): Promise<void>;+ now?(): number;+}): Promise<void> {+ const now = deps.now ?? Date.now,+ deadline = now() + PLUGIN_OAUTH_TTL_MS,+ key = new MobileOauthBox(deps.crypto);+ let id: string | undefined,+ finished = false;+ try {+ deps.assertCurrent();+ const caps = object(await deps.invoke({ op: "capabilities" }));+ if (+ caps.version !== 1 ||+ caps.encrypted !== true ||+ caps.callback !== "desktop-loopback" ||+ (deps.kind === "secret" && caps.secretSubmission !== true) ||+ (deps.kind === "connection" && caps.connectionSubmission !== true)+ )+ throw new Error("OAUTH_BRIDGE_UNAVAILABLE");+ deps.assertCurrent();+ const start = object(+ await deps.invoke({+ op: "start",+ ...deps.action,+ publicKey: key.publicKey,+ ...(caps.deviceUserCode === true+ ? { deviceUserCode: true as const }+ : {}),+ ...(caps.authorizationV1 === true+ ? { authorizationV1: true as const }+ : {}),+ ...(deps.kind === "secret" ? { secretSubmission: true as const } : {}),+ ...(deps.kind === "connection"+ ? { connectionSubmission: true as const }+ : {}),+ }),+ );+ if (!oauthId(start.id) || !oauthPublicKey(start.publicKey))+ throw new Error("OAUTH_BRIDGE_UNAVAILABLE");+ id = start.id;+ const peerKey = start.publicKey;+ let opened = false;+ const deliver = async (value: unknown) => {+ deps.assertCurrent();+ const box = await key.seal(peerKey, id!, "callback", value);+ deps.clearInput();+ deps.inputSecret = undefined;+ deps.inputConnection = undefined;+ deps.assertCurrent();+ const result = object(+ await deps.invoke({ op: "callback", id: id!, box }),+ );+ if (result.accepted !== true) throw new Error("OAUTH_BRIDGE_UNAVAILABLE");+ };+ while (now() < deadline) {+ await deps.pause();+ deps.assertCurrent();+ const status = object(await deps.invoke({ op: "status", id }));+ deps.assertCurrent();+ if (status.phase === "succeeded") {+ finished = true;+ return;+ }+ if (+ !["starting", "authorizing", "exchanging"].includes(+ String(status.phase),+ )+ )+ throw new Error("OAUTH_BRIDGE_UNAVAILABLE");+ if (status.phase !== "authorizing" || opened) continue;+ if (typeof status.offer !== "string")+ throw new Error("OAUTH_BRIDGE_UNAVAILABLE");+ const raw = object(await key.open(peerKey, id, "offer", status.offer));+ if (deps.kind === "secret") {+ const offer = parsePluginSecretOffer(raw);+ if (+ JSON.stringify(offer.presentation) !==+ JSON.stringify(deps.secretPresentation)+ )+ throw new Error("OAUTH_BRIDGE_UNAVAILABLE");+ const value = parsePluginSecretInput(deps.inputSecret);+ if (value.length > offer.presentation.maxLength)+ throw new Error("PLUGIN_SECRET_UNAVAILABLE");+ await deliver({ kind: "secret-value", state: offer.state, value });+ } else if (deps.kind === "connection") {+ const offer = parsePluginConnectionOffer(raw);+ if (+ JSON.stringify(offer.presentation) !==+ JSON.stringify(deps.connectionPresentation)+ )+ throw new Error("OAUTH_BRIDGE_UNAVAILABLE");+ await deliver({+ kind: "connection-value",+ state: offer.state,+ value: parsePluginConnectionInput(deps.inputConnection),+ });+ } else if (raw.kind === "authorization") {+ if (caps.authorizationV1 !== true)+ throw new Error("OAUTH_BRIDGE_UNAVAILABLE");+ const offer = parsePluginAuthorizationOffer(raw);+ // A computer loopback callback cannot be reinterpreted as the phone's localhost.+ if (offer.request.kind === "loopback")+ throw new Error("PLUGIN_AUTHORIZATION_COMPUTER_CALLBACK");+ await deps.showAuthorization(+ offer.request.url,+ offer.request.kind === "device" ? offer.request.userCode : undefined,+ Math.min(deadline, offer.request.expiresAt ?? deadline),+ );+ await deliver({ kind: "device-opened", state: offer.state });+ } else if (raw.kind === "device") {+ if (caps.deviceAuthorization !== true)+ throw new Error("OAUTH_BRIDGE_UNAVAILABLE");+ const offer = parsePluginDeviceOffer(raw);+ await deps.showAuthorization(+ offer.authorizeUrl,+ offer.userCode,+ deadline,+ );+ await deliver({ kind: "device-opened", state: offer.state });+ } else {+ // Legacy PKCE loopback offers need the computer's callback listener.+ oauthExact(raw, [+ "authorizeUrl",+ "callbackUrl",+ "corsHosts",+ "corsOrigins",+ "state",+ ]);+ throw new Error("PLUGIN_AUTHORIZATION_COMPUTER_CALLBACK");+ }+ opened = true;+ }+ throw new Error("OAUTH_BRIDGE_UNAVAILABLE");+ } finally {+ deps.clearInput();+ deps.inputSecret = undefined;+ deps.inputConnection = undefined;+ if (!finished && id)+ await deps.invoke({ op: "cancel", id }).catch(() => {});+ key.dispose();+ }+}diff --git a/apps/mobile/src/plugins/pluginClient.ts b/apps/mobile/src/plugins/pluginClient.tsnew file mode 100644index 0000000000..7a61e687c0--- /dev/null+++ b/apps/mobile/src/plugins/pluginClient.ts@@ -0,0 +1,93 @@+import {+ REMOTE_RESOURCE_INVOKE_CHANNEL,+ PLUGIN_COLLECTION,+ PLUGIN_PAGE_PRIMITIVE,+ PLUGIN_PAGE_MAX_BUNDLE_BYTES,+ type PluginPageDocument,+ type PluginPageAsset,+ type RemoteActionInvokeResponse,+} from "@cindy/device-link";+import type { RemoteInvoke } from "@/device-link/mobileMakerTransport";++export async function invokePlugin<T>(+ invoke: RemoteInvoke,+ deviceId: string,+ pluginId: string,+ actionId: string,+ input: Record<string, unknown> = {},+): Promise<T> {+ const reply = await invoke<RemoteActionInvokeResponse>(+ deviceId,+ REMOTE_RESOURCE_INVOKE_CHANNEL,+ [+ {+ client: { protocolVersion: 1, primitives: [PLUGIN_PAGE_PRIMITIVE] },+ collectionId: PLUGIN_COLLECTION,+ resourceRef: {+ collectionId: PLUGIN_COLLECTION,+ kind: "plugin",+ id: pluginId,+ },+ actionId,+ input,+ },+ ],+ );+ return reply.result as T;+}++/** No partial page is mounted. Assets are read from this lease's immutable file list. */+export async function loadPluginPageAssets(+ document: PluginPageDocument,+ read: (path: string, offset: number) => Promise<PluginPageAsset>,+ current: () => boolean,+) {+ if (+ !document ||+ typeof document.pageId !== "string" ||+ !Array.isArray(document.files) ||+ document.files.length > 10_000 ||+ !document.files.some((file) => file.path === document.entry)+ )+ throw new Error("PLUGIN_PAGE_INVALID");+ if (+ document.files.reduce((size, file) => size + file.size, 0) >+ PLUGIN_PAGE_MAX_BUNDLE_BYTES+ )+ throw new Error("PLUGIN_PAGE_BUNDLE_TOO_LARGE");+ const assets: Record<string, PluginPageAsset> = Object.create(null);+ for (let start = 0; start < document.files.length; start += 4) {+ await Promise.all(+ document.files.slice(start, start + 4).map(async (file) => {+ if (+ typeof file.path !== "string" ||+ file.path+ .split("/")+ .some((part) => !part || part === ".." || part === ".") ||+ file.path.includes("\\") ||+ !Number.isSafeInteger(file.size) ||+ file.size < 0+ )+ throw new Error("PLUGIN_ASSET_INVALID");+ const chunks: string[] = [];+ for (let offset = 0; offset < file.size; offset += 48 * 1024) {+ if (!current()) throw new Error("PLUGIN_PAGE_CLOSED");+ const chunk = await read(file.path, offset);+ const expected = Math.min(48 * 1024, file.size - offset);+ if (+ !chunk ||+ chunk.mime !== file.mime ||+ typeof chunk.base64 !== "string" ||+ chunk.base64.length !== 4 * Math.ceil(expected / 3) ||+ !/^[A-Za-z0-9+/]*={0,2}$/.test(chunk.base64)+ )+ throw new Error("PLUGIN_ASSET_INVALID");+ chunks.push(chunk.base64);+ }+ assets[file.path] = { mime: file.mime, base64: chunks.join("") };+ }),+ );+ }+ if (!current()) throw new Error("PLUGIN_PAGE_CLOSED");+ return assets;+}diff --git a/apps/mobile/src/plugins/pluginLocalPreview.ts b/apps/mobile/src/plugins/pluginLocalPreview.tsnew file mode 100644index 0000000000..d58e5942b6--- /dev/null+++ b/apps/mobile/src/plugins/pluginLocalPreview.ts@@ -0,0 +1,171 @@+import {+ pluginPreviewQueryTarget,+ PLUGIN_PREVIEW_QUERY_SCRIPT,+} from "./pluginPreviewQueries";+import { Directory, File, Paths } from "expo-file-system";+import { getRandomBytes } from "expo-crypto";+import native from "../../modules/cindy-html-preview/src/CindyHtmlPreviewModule";+import {+ HTML_SNAPSHOT_CSP,+ withSnapshotHtmlCsp,+} from "@/session/htmlPreviewCsp";+import type { MobileHtmlPreview } from "@/session/mobileHtmlPreview";+import { createFileReadQueue } from "@cindy/device-link";+import type { PluginPageFetchResult } from "@cindy/device-link";++/** Reuse the installed native resource server. Remote localhost is fetched by its execution Host. */+export async function preparePluginLocalPreview(+ source: string,+ read: (+ url: string,+ offset: number,+ revision?: string,+ ) => Promise<PluginPageFetchResult>,+ signal: AbortSignal,+): Promise<MobileHtmlPreview> {+ if (!native?.startOnDemand || !native.resolveRequest)+ throw new Error("PLUGIN_PREVIEW_NATIVE_UNAVAILABLE");+ const server = native,+ remote = new URL(source);+ const entry =+ remote.pathname.replace(/^\//, "") ++ (remote.pathname.endsWith("/") ? "index.html" : "");+ const token = Array.from(getRandomBytes(24), (byte) =>+ byte.toString(16).padStart(2, "0"),+ ).join("");+ const dir = new Directory(Paths.cache, "html-previews", token);+ dir.create({ intermediates: true });+ let closed = false,+ sequence = 0,+ phoneOrigin = "";+ const pending = new Set<Promise<void>>();+ const queue = createFileReadQueue();+ const check = () => {+ if (closed || signal.aborted) throw new Error("PLUGIN_PREVIEW_CLOSED");+ };+ const listener = server.addListener("resourceRequest", (event) => {+ if (event.token !== token || closed) return;+ const work = queue(+ "preview",+ async () => {+ const destination = new File(dir, String(sequence++));+ let accepted = false;+ try {+ check();+ const relative = event.path;+ if (+ !relative ||+ relative.includes("\\") ||+ relative.includes(":") ||+ relative.split("/").some((part) => !part || part.startsWith("."))+ )+ throw new Error("INVALID_PREVIEW_PATH");+ const url =+ pluginPreviewQueryTarget(relative, remote.origin) ??+ (relative === entry+ ? remote.href+ : new URL("/" + relative, remote.origin).href);+ const chunks: Uint8Array[] = [];+ let offset = 0,+ revision: string | undefined,+ mime = "",+ status = 200,+ size = 0;+ do {+ const response = await read(url, offset, revision);+ check();+ if (+ !response ||+ typeof response.base64 !== "string" ||+ typeof response.revision !== "string"+ )+ throw new Error("INVALID_PREVIEW_RESPONSE");+ if (revision && revision !== response.revision)+ throw new Error("PREVIEW_CHANGED");+ revision = response.revision;+ mime = response.mime;+ status = response.status;+ const bytes = Uint8Array.from(atob(response.base64), (char) =>+ char.charCodeAt(0),+ );+ size += bytes.length;+ if (size > 8 * 1024 * 1024) throw new Error("PREVIEW_TOO_LARGE");+ chunks.push(bytes);+ if (response.nextOffset === undefined) break;+ if (+ response.nextOffset !== offset + bytes.length ||+ bytes.length === 0+ )+ throw new Error("INVALID_PREVIEW_RESPONSE");+ offset = response.nextOffset;+ } while (true);+ const bytes = new Uint8Array(size);+ let at = 0;+ for (const part of chunks) {+ bytes.set(part, at);+ at += part.length;+ }+ destination.create();+ if (/^(text\/|application\/(javascript|json))/.test(mime)) {+ let text = new TextDecoder("utf-8", { fatal: true })+ .decode(bytes)+ .split(remote.origin)+ .join(phoneOrigin);+ if (mime === "text/html")+ text = withSnapshotHtmlCsp(PLUGIN_PREVIEW_QUERY_SCRIPT + text);+ destination.write(text);+ } else destination.write(bytes);+ check();+ accepted = await server.resolveRequest!(+ token,+ event.id,+ destination.name,+ mime,+ status,+ );+ } catch {+ if (!closed)+ await server.resolveRequest!(token, event.id, "", "", 502).catch(+ () => false,+ );+ } finally {+ if (!accepted && destination.exists) destination.delete();+ }+ },+ signal,+ );+ pending.add(work);+ void work.finally(() => pending.delete(work)).catch(() => {});+ });+ const close = async () => {+ if (closed) return;+ closed = true;+ signal.removeEventListener("abort", abort);+ listener.remove();+ try {+ await server.stop(token);+ } finally {+ await Promise.allSettled([...pending]);+ if (dir.exists) dir.delete();+ }+ };+ const abort = () => {+ void close().catch(() => {});+ };+ signal.addEventListener("abort", abort, { once: true });+ try {+ check();+ const url = await server.startOnDemand!(+ decodeURIComponent(dir.uri.replace(/^file:\/\//, "")),+ entry,+ token,+ HTML_SNAPSHOT_CSP,+ );+ phoneOrigin = new URL(url).origin;+ check();+ return { url, documents: [], onDemand: true, close };+ } catch (error) {+ await close();+ throw error;+ }+}diff --git a/apps/mobile/src/plugins/pluginMediaFile.ts b/apps/mobile/src/plugins/pluginMediaFile.tsnew file mode 100644index 0000000000..34fda3e1f4--- /dev/null+++ b/apps/mobile/src/plugins/pluginMediaFile.ts@@ -0,0 +1,64 @@+import { Directory, File, Paths } from "expo-file-system";+import { getRandomBytes } from "expo-crypto";+import type { PluginPageFetchResult } from "@cindy/device-link";++/** One viewer owns one temporary file. Bytes still pass the execution computer's plugin ledger. */+export async function readPluginMediaFile(+ path: string,+ kind: "image" | "video",+ read: (path: string, offset: number) => Promise<PluginPageFetchResult>,+ signal: AbortSignal,+) {+ if (!/^\/media\/[a-f0-9]{64}\.[a-z0-9]+$/.test(path))+ throw new Error("PLUGIN_MEDIA_INVALID");+ const token = Array.from(getRandomBytes(24), (byte) =>+ byte.toString(16).padStart(2, "0"),+ ).join("");+ const directory = new Directory(Paths.cache, "plugin-media", token);+ directory.create({ intermediates: true });+ const file = new File(directory, path.split("/").pop()!);+ const close = () => {+ if (directory.exists) directory.delete();+ };+ const check = () => {+ if (signal.aborted) throw new Error("PLUGIN_MEDIA_CLOSED");+ };+ let handle: ReturnType<File["open"]> | undefined,+ completed = false;+ let offset = 0,+ mime = "";+ try {+ file.create();+ handle = file.open();+ for (;;) {+ check();+ const response = await read(path, offset);+ check();+ if (+ response.status !== 200 ||+ !response.mime.startsWith(`${kind}/`) ||+ (mime && mime !== response.mime)+ )+ throw new Error("PLUGIN_MEDIA_INVALID");+ mime = response.mime;+ const bytes = Uint8Array.from(atob(response.base64), (char) =>+ char.charCodeAt(0),+ );+ if (offset + bytes.length > 256 * 1024 * 1024)+ throw new Error("PLUGIN_MEDIA_TOO_LARGE");+ handle.writeBytes(bytes);+ if (response.nextOffset === undefined) break;+ if (!bytes.length || response.nextOffset !== offset + bytes.length)+ throw new Error("PLUGIN_MEDIA_INVALID");+ offset = response.nextOffset;+ }+ completed = true;+ return { uri: file.uri, mime, close };+ } finally {+ try {+ handle?.close();+ } finally {+ if (!completed) close();+ }+ }+}diff --git a/apps/mobile/src/plugins/pluginOauthClient.ts b/apps/mobile/src/plugins/pluginOauthClient.tsnew file mode 100644index 0000000000..f92ea3a4b2--- /dev/null+++ b/apps/mobile/src/plugins/pluginOauthClient.ts@@ -0,0 +1,110 @@+import {+ PLUGIN_OAUTH_TTL_MS,+ oauthExact,+ parsePluginOauthHelloReply,+ pluginOauthTranscript,+ type PluginOauthAction,+ type PluginOauthPeerIdentity,+ type PluginOauthHello,+ type PluginOauthRequest,+} from "@cindy/device-link";+import {+ MobileOauthBox,+ encodeOauthBytes,+ verifyOauthSignature,+ type PluginOauthCrypto,+} from "./pluginOauthCrypto";+const fail = () => new Error("OAUTH_BRIDGE_UNAVAILABLE");+/** Dedicated native channel client; no URL, token, offer or plaintext is returned to a plugin page. */+export async function authenticateMobilePluginOauth(deps: {+ crypto: PluginOauthCrypto;+ target: PluginOauthPeerIdentity;+ trustIdentity(+ target: PluginOauthPeerIdentity,+ assertCurrent: () => void,+ ): Promise<void>;+ peer: string;+ action: PluginOauthAction;+ ghostId: string;+ invoke(raw: unknown, cleanup?: boolean): Promise<unknown>;+ assertCurrent(): void;+ now?(): number;+}) {+ const now = deps.now ?? Date.now;+ deps.assertCurrent();+ if (+ deps.target.observedAtMs > now() + 1000 ||+ now() - deps.target.observedAtMs > 60000 ||+ deps.target.expiresAtMs <= now() ||+ deps.target.expiresAtMs > deps.target.observedAtMs + 60000+ )+ throw fail();+ const key = new MobileOauthBox(deps.crypto);+ try {+ const hello: PluginOauthHello = {+ op: "hello",+ version: 3,+ nonce: encodeOauthBytes(deps.crypto.random(32)),+ publicKey: key.publicKey,+ action: deps.action,+ };+ const reply = parsePluginOauthHelloReply(await deps.invoke(hello));+ deps.assertCurrent();+ if (+ deps.target.expiresAtMs <= now() ||+ reply.bootId !== deps.target.bootId ||+ reply.ghostId !== deps.ghostId ||+ reply.expiresAtMs <= now() ||+ reply.expiresAtMs > now() + PLUGIN_OAUTH_TTL_MS + 1000 ||+ !verifyOauthSignature(+ deps.target.publicKey,+ reply.signature,+ pluginOauthTranscript(hello, reply, deps.target, deps.peer),+ )+ )+ throw fail();+ await deps.trustIdentity(deps.target, deps.assertCurrent);+ deps.assertCurrent();+ return {+ dispose: () => key.dispose(),+ request: async (request: PluginOauthRequest) => {+ if (request.op !== "cancel") deps.assertCurrent();+ if (now() >= reply.expiresAtMs) throw fail();+ const nonce = encodeOauthBytes(deps.crypto.random(32));+ const response = oauthExact(+ await deps.invoke(+ {+ op: "exchange",+ id: reply.id,+ box: await key.seal(+ reply.publicKey,+ `authenticated-plugin-oauth-v3:${reply.id}`,+ "callback",+ { nonce, request },+ ),+ },+ request.op === "cancel",+ ),+ ["box"],+ );+ if (request.op !== "cancel") deps.assertCurrent();+ if (typeof response.box !== "string") throw fail();+ const opened = (await key.open(+ reply.publicKey,+ `authenticated-plugin-oauth-v3:${reply.id}`,+ "offer",+ response.box,+ )) as { ok?: unknown };+ const value = oauthExact(+ opened,+ opened?.ok === true ? ["nonce", "ok", "result"] : ["nonce", "ok"],+ );+ if (value.nonce !== nonce || value.ok !== true) throw fail();+ return value.result;+ },+ };+ } catch (e) {+ key.dispose();+ throw e;+ }+}diff --git a/apps/mobile/src/plugins/pluginOauthCrypto.ts b/apps/mobile/src/plugins/pluginOauthCrypto.tsnew file mode 100644index 0000000000..c47228840e--- /dev/null+++ b/apps/mobile/src/plugins/pluginOauthCrypto.ts@@ -0,0 +1,175 @@+import { ed25519, x25519 } from "@noble/curves/ed25519";+import { hkdf } from "@noble/hashes/hkdf";+import { sha256 } from "@noble/hashes/sha256";+/** Bounded UTF-8 helpers work without TextEncoder/TextDecoder on Hermes. */+export function oauthUtf8Bytes(value: string): Uint8Array {+ const encoded = encodeURIComponent(value),+ bytes: number[] = [];+ for (let i = 0; i < encoded.length; i++) {+ if (encoded[i] === "%") {+ bytes.push(parseInt(encoded.slice(i + 1, i + 3), 16));+ i += 2;+ } else bytes.push(encoded.charCodeAt(i));+ }+ return Uint8Array.from(bytes);+}+function oauthUtf8Text(bytes: Uint8Array): string {+ return decodeURIComponent(+ Array.from(bytes, (byte) => "%" + byte.toString(16).padStart(2, "0")).join(+ "",+ ),+ );+}++export interface PluginOauthCrypto {+ random(size: number): Uint8Array;+ encrypt(+ key: Uint8Array,+ iv: Uint8Array,+ body: Uint8Array,+ aad: Uint8Array,+ ): Promise<Uint8Array>;+ decrypt(+ key: Uint8Array,+ combined: Uint8Array,+ aad: Uint8Array,+ ): Promise<Uint8Array>;+}+const alphabet =+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";+export function encodeOauthBytes(bytes: Uint8Array): string {+ let result = "";+ for (let i = 0; i < bytes.length; i += 3) {+ const a = bytes[i],+ b = bytes[i + 1],+ c = bytes[i + 2];+ result += alphabet[a >> 2] + alphabet[((a & 3) << 4) | ((b ?? 0) >> 4)];+ if (b !== undefined) result += alphabet[((b & 15) << 2) | ((c ?? 0) >> 6)];+ if (c !== undefined) result += alphabet[c & 63];+ }+ return result;+}+export function decodeOauthBytes(value: string): Uint8Array {+ if (!/^[A-Za-z0-9_-]+$/.test(value) || value.length % 4 === 1)+ throw new Error("OAUTH_BRIDGE_INVALID");+ const bytes = new Uint8Array(Math.floor((value.length * 3) / 4));+ let bits = 0,+ accumulated = 0,+ at = 0;+ for (const c of value) {+ accumulated = (accumulated << 6) | alphabet.indexOf(c);+ bits += 6;+ if (bits >= 8) {+ bits -= 8;+ bytes[at++] = (accumulated >> bits) & 255;+ }+ }+ if (encodeOauthBytes(bytes) !== value)+ throw new Error("OAUTH_BRIDGE_INVALID");+ return bytes;+}+const xPrefix = new Uint8Array([48, 42, 48, 5, 6, 3, 43, 101, 110, 3, 33, 0]);+const edPrefix = new Uint8Array([48, 42, 48, 5, 6, 3, 43, 101, 112, 3, 33, 0]);+function rawPublic(value: string, prefix: Uint8Array) {+ const bytes = decodeOauthBytes(value);+ if (bytes.length !== 44 || prefix.some((b, i) => bytes[i] !== b))+ throw new Error("OAUTH_BRIDGE_INVALID");+ return bytes.subarray(prefix.length);+}+export function verifyOauthSignature(+ publicKey: string,+ signature: string,+ transcript: string,+): boolean {+ try {+ return ed25519.verify(+ decodeOauthBytes(signature),+ oauthUtf8Bytes(transcript),+ rawPublic(publicKey, edPrefix),+ { zip215: false },+ );+ } catch {+ return false;+ }+}+/** Same wire format as the desktop OauthBox. Secure randomness and AES come from the platform. */+export class MobileOauthBox {+ private privateKey: Uint8Array;+ readonly publicKey: string;+ private disposed = false;+ constructor(private readonly crypto: PluginOauthCrypto) {+ this.privateKey = crypto.random(32);+ this.publicKey = encodeOauthBytes(+ new Uint8Array([...xPrefix, ...x25519.getPublicKey(this.privateKey)]),+ );+ }+ dispose() {+ this.disposed = true;+ this.privateKey.fill(0);+ }+ private key(peer: string, id: string, direction: "offer" | "callback") {+ if (this.disposed) throw new Error("OAUTH_BRIDGE_INVALID");+ const shared = x25519.getSharedSecret(+ this.privateKey,+ rawPublic(peer, xPrefix),+ );+ try {+ return hkdf(+ sha256,+ shared,+ oauthUtf8Bytes(id),+ oauthUtf8Bytes(`cindy-plugin-oauth-v1:${direction}`),+ 32,+ );+ } finally {+ shared.fill(0);+ }+ }+ async seal(+ peer: string,+ id: string,+ direction: "offer" | "callback",+ value: unknown,+ ): Promise<string> {+ const key = this.key(peer, id, direction),+ body = oauthUtf8Bytes(JSON.stringify(value));+ try {+ if (body.length > 32000) throw new Error("OAUTH_BRIDGE_INVALID");+ return encodeOauthBytes(+ await this.crypto.encrypt(+ key,+ this.crypto.random(12),+ body,+ oauthUtf8Bytes(`cindy-plugin-oauth-v1:${id}:${direction}`),+ ),+ );+ } finally {+ key.fill(0);+ body.fill(0);+ }+ }+ async open(+ peer: string,+ id: string,+ direction: "offer" | "callback",+ box: string,+ ): Promise<unknown> {+ let key: Uint8Array | undefined, body: Uint8Array | undefined;+ try {+ if (!/^[A-Za-z0-9_-]{40,48000}$/.test(box)) throw 0;+ key = this.key(peer, id, direction);+ body = await this.crypto.decrypt(+ key,+ decodeOauthBytes(box),+ oauthUtf8Bytes(`cindy-plugin-oauth-v1:${id}:${direction}`),+ );+ if (body.length > 32000) throw 0;+ return JSON.parse(oauthUtf8Text(body));+ } catch {+ throw new Error("OAUTH_BRIDGE_INVALID");+ } finally {+ key?.fill(0);+ body?.fill(0);+ }+ }+}diff --git a/apps/mobile/src/plugins/pluginOauthPins.ts b/apps/mobile/src/plugins/pluginOauthPins.tsnew file mode 100644index 0000000000..bf729d9eea--- /dev/null+++ b/apps/mobile/src/plugins/pluginOauthPins.ts@@ -0,0 +1,46 @@+import { oauthUtf8Bytes } from "./pluginOauthCrypto";+import { sha256 } from "@noble/hashes/sha256";+import { bytesToHex } from "@noble/hashes/utils";+import type { PluginOauthPeerIdentity } from "@cindy/device-link";++type PinStore = {+ get(key: string): Promise<string | null>;+ set(key: string, value: string): Promise<void>;+};+const pending = new Map<string, Promise<void>>();+/** Native secure storage only. A changed pin can never be approved by an authorization card. */+export async function pinMobilePluginIdentity(+ store: PinStore,+ identity: PluginOauthPeerIdentity,+ localDeviceId: string,+ assertCurrent: () => void,+): Promise<void> {+ const scope = JSON.stringify([+ identity.realm,+ identity.membershipId,+ localDeviceId,+ identity.deviceId,+ ]);+ const key = `cindy.pluginOauthIdentity.v1.${bytesToHex(sha256(oauthUtf8Bytes(scope)))}`;+ const previousOperation = pending.get(key) ?? Promise.resolve();+ const operation = previousOperation+ .catch(() => {})+ .then(async () => {+ assertCurrent();+ const previous = await store.get(key); // A failed read is never an empty pin.+ assertCurrent();+ if (previous !== null) {+ if (previous !== identity.publicKey)+ throw new Error("PLUGIN_AUTHORIZATION_IDENTITY_CHANGED");+ return;+ }+ await store.set(key, identity.publicKey);+ assertCurrent();+ });+ pending.set(key, operation);+ try {+ await operation;+ } finally {+ if (pending.get(key) === operation) pending.delete(key);+ }+}diff --git a/apps/mobile/src/plugins/pluginOauthPlatformCrypto.ts b/apps/mobile/src/plugins/pluginOauthPlatformCrypto.tsnew file mode 100644index 0000000000..68e5fd53ec--- /dev/null+++ b/apps/mobile/src/plugins/pluginOauthPlatformCrypto.ts@@ -0,0 +1,29 @@+import {+ AESSealedData,+ AESEncryptionKey,+ aesEncryptAsync,+ aesDecryptAsync,+ getRandomBytes,+} from "expo-crypto";+import type { PluginOauthCrypto } from "./pluginOauthCrypto";+/** Uses the already-installed Expo AES module; no secret reaches an author WebView. */+export const pluginOauthPlatformCrypto: PluginOauthCrypto = {+ random: getRandomBytes,+ encrypt: async (bytes, iv, body, aad) => {+ const key = await AESEncryptionKey.import(bytes);+ const sealed = await aesEncryptAsync(body, key, {+ nonce: { bytes: iv },+ additionalData: aad,+ tagLength: 16,+ });+ return sealed.combined();+ },+ decrypt: async (bytes, combined, aad) => {+ const key = await AESEncryptionKey.import(bytes);+ return aesDecryptAsync(+ AESSealedData.fromCombined(combined, { ivLength: 12, tagLength: 16 }),+ key,+ { additionalData: aad },+ );+ },+};diff --git a/apps/mobile/src/plugins/pluginPageBootstrap.generated.ts b/apps/mobile/src/plugins/pluginPageBootstrap.generated.tsnew file mode 100644index 0000000000..7f2c3bc2ce--- /dev/null+++ b/apps/mobile/src/plugins/pluginPageBootstrap.generated.ts@@ -0,0 +1,2 @@+// Generated by scripts/generate-mobile-plugin-bootstrap.mjs. Edit pluginPageBootstrap.ts.+export const PLUGIN_PAGE_BOOTSTRAP = "/** This bootstrap runs only in the isolated WebView; no native credential/IPC object. */\nfunction bootstrap(config) {\n const native = window.ReactNativeWebView;\n const send = (value) => native.postMessage(JSON.stringify({ ...value, pageId: config.document.pageId }));\n const pending = new Map();\n const channels = new Map();\n const localRequests = new Map();\n const backListeners = new Set();\n const lifecycleListeners = new Set();\n const unreadListeners = new Set();\n let unreadVersion = config.document.unreadAt;\n let active = false;\n let request = 0, delivered = 0;\n let closed = false;\n const receivedDeliveries = new Set();\n const localRequest = (type, key, value) => new Promise((resolve, reject) => {\n const id = `local:${++request}`;\n const timeout = setTimeout(() => {\n localRequests.delete(id);\n reject(new Error(\"PLUGIN_DRAFT_UNCONFIRMED\"));\n }, 5_000);\n localRequests.set(id, { resolve, reject, timeout });\n send({ type, id, key, value });\n });\n Object.defineProperty(window, \"cindyMobile\", {\n value: Object.freeze({\n version: 1,\n setNavigation: (canGoBack, title) => send({ type: \"navigation\", canGoBack: canGoBack === true, title }),\n onBack: (listener) => {\n backListeners.add(listener);\n return () => backListeners.delete(listener);\n },\n onLifecycle: (listener) => {\n lifecycleListeners.add(listener);\n return () => lifecycleListeners.delete(listener);\n },\n onUnread: (listener) => {\n unreadListeners.add(listener);\n if (Number.isSafeInteger(unreadVersion)) {\n const version = unreadVersion;\n queueMicrotask(() => {\n if (unreadListeners.has(listener) && unreadVersion === version)\n listener(version);\n });\n }\n return () => unreadListeners.delete(listener);\n },\n contentRendered: (version) => {\n if (config.document.surface !== \"panel\" ||\n !Number.isSafeInteger(version) ||\n version !== unreadVersion)\n return;\n requestAnimationFrame(() => {\n if (!closed && active && version === unreadVersion)\n send({ type: \"content-rendered\", seenAt: version });\n });\n },\n openTask: (taskId) => send({\n type: \"link\",\n url: `cindy://sessions/${encodeURIComponent(taskId)}`,\n }),\n readDraft: (key) => localRequest(\"draft:get\", key),\n writeDraft: (key, value) => localRequest(\"draft:set\", key, value),\n }),\n });\n const base = `https://plugin.invalid/${config.document.entry}`;\n const pathFor = (value, from = base) => {\n const url = new URL(value, from);\n if (url.origin !== \"https://plugin.invalid\" &&\n !(url.protocol === \"cindy-ghost:\" && url.host === config.document.pluginId))\n throw new Error(\"PLUGIN_ORIGIN_DENIED\");\n return decodeURIComponent(url.pathname.slice(1));\n };\n class MobileBroadcastChannel extends EventTarget {\n name;\n onmessage = null;\n constructor(name) {\n super();\n if (!config.document.channels.includes(name))\n throw new Error(\"PLUGIN_CHANNEL_UNAVAILABLE\");\n this.name = name;\n const set = channels.get(name) ?? new Set();\n set.add(this);\n channels.set(name, set);\n }\n postMessage(data) {\n send({ type: \"post\", channel: this.name, data });\n }\n close() {\n channels.get(this.name)?.delete(this);\n }\n }\n Object.defineProperty(window, \"BroadcastChannel\", {\n value: MobileBroadcastChannel,\n });\n const decode = (asset) => Uint8Array.from(atob(asset.base64), (c) => c.charCodeAt(0));\n window.fetch = async (input, init) => {\n const url = typeof input === \"string\"\n ? input\n : input instanceof URL\n ? input.href\n : input.url;\n const path = pathFor(url);\n const method = (init?.method ?? (input instanceof Request ? input.method : \"GET\")).toUpperCase();\n if (path === \"wake\")\n return new Response(JSON.stringify({ ok: true }), {\n headers: { \"content-type\": \"application/json\" },\n });\n const asset = config.assets[path];\n if (asset && method === \"GET\")\n return new Response(decode(asset), {\n headers: { \"content-type\": asset.mime },\n });\n if (init?.body !== undefined && typeof init.body !== \"string\")\n throw new Error(\"PLUGIN_BODY_UNSUPPORTED\");\n const parts = [];\n let offset, revision, response;\n do {\n const id = String(++request);\n response = await new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n pending.delete(id);\n reject(new Error(\"PLUGIN_REQUEST_UNCONFIRMED\"));\n }, 30_000);\n pending.set(id, { resolve, reject, timeout });\n send({\n type: \"fetch\",\n id,\n path: \"/\" + path + new URL(url, base).search,\n method,\n body: init?.body,\n offset,\n revision,\n });\n });\n revision = response.headers.get(\"x-cindy-revision\") ?? undefined;\n parts.push(await response.arrayBuffer());\n const next = response.headers.get(\"x-cindy-next-offset\");\n if (next && Number(next) <= (offset ?? 0))\n throw new Error(\"PLUGIN_RESPONSE_INVALID\");\n offset = next ? Number(next) : undefined;\n } while (offset !== undefined);\n return new Response([204, 205, 304].includes(response.status) ? null : new Blob(parts), {\n status: response.status,\n headers: {\n \"content-type\": response.headers.get(\"content-type\") ?? \"application/octet-stream\",\n },\n });\n };\n const receive = (event) => {\n let message;\n try {\n message = JSON.parse(event.data);\n }\n catch {\n return;\n }\n if (Number.isSafeInteger(message.deliveryId)) {\n if (receivedDeliveries.has(message.deliveryId))\n return;\n receivedDeliveries.add(message.deliveryId);\n if (receivedDeliveries.size > 128)\n receivedDeliveries.delete(receivedDeliveries.values().next().value);\n }\n if (message.type === \"back\") {\n for (const listener of backListeners)\n listener();\n }\n else if (message.type === \"lifecycle\") {\n active = message.active === true;\n for (const listener of lifecycleListeners)\n listener(active);\n }\n else if (message.type === \"draft:reply\") {\n const waiter = localRequests.get(message.id);\n if (!waiter)\n return;\n localRequests.delete(message.id);\n clearTimeout(waiter.timeout);\n if (message.error)\n waiter.reject(new Error(\"PLUGIN_DRAFT_UNCONFIRMED\"));\n else\n waiter.resolve(message.value);\n }\n else if (message.type === \"events\") {\n if (message.unreadAt !== unreadVersion) {\n unreadVersion = Number.isSafeInteger(message.unreadAt)\n ? message.unreadAt\n : undefined;\n if (unreadVersion !== undefined)\n for (const listener of unreadListeners)\n listener(unreadVersion);\n }\n for (const item of message.events) {\n if (!Number.isSafeInteger(item.sequence) || item.sequence <= delivered)\n continue;\n for (const channel of channels.get(item.channel) ?? []) {\n const received = new MessageEvent(\"message\", { data: item.data });\n channel.dispatchEvent(received);\n channel.onmessage?.(received);\n }\n delivered = item.sequence;\n }\n send({ type: \"events-ack\", sequence: delivered });\n }\n else if (message.type === \"theme\") {\n document.documentElement.dataset.theme = message.theme;\n document.documentElement.classList.toggle(\"dark\", message.theme === \"dark\");\n document.documentElement.style.colorScheme = message.theme;\n for (const [key, value] of Object.entries(message.colors))\n document.documentElement.style.setProperty(`--${key}`, value);\n }\n else if (message.type === \"reply\") {\n const waiter = pending.get(message.id);\n if (!waiter)\n return;\n pending.delete(message.id);\n clearTimeout(waiter.timeout);\n if (message.error)\n waiter.reject(new Error(\"PLUGIN_REQUEST_UNCONFIRMED\"));\n else\n waiter.resolve(new Response([204, 205, 304].includes(message.result.status)\n ? null\n : decode(message.result), {\n status: message.result.status,\n headers: {\n \"content-type\": message.result.mime,\n ...(message.result.revision\n ? { \"x-cindy-revision\": message.result.revision }\n : {}),\n ...(message.result.nextOffset === undefined\n ? {}\n : {\n \"x-cindy-next-offset\": String(message.result.nextOffset),\n }),\n },\n }));\n }\n };\n const urls = new Map();\n const mediaUrls = new Set();\n const assetUrl = (relative, from = base) => {\n if (/^(?:data:|blob:|https:)/.test(relative))\n return relative;\n let key;\n try {\n key = pathFor(relative, from);\n }\n catch {\n return \"\";\n }\n if (urls.has(key))\n return urls.get(key);\n const asset = config.assets[key];\n if (!asset)\n return \"\";\n let data = decode(asset);\n if (asset.mime.startsWith(\"text/css\"))\n data = new TextDecoder()\n .decode(data)\n .replace(/url\\(\\s*(['\"]?)([^)'\"\\s]+)\\1\\s*\\)/g, (_match, _quote, value) => `url(\"${assetUrl(value, `https://plugin.invalid/${key}`)}\")`);\n const url = URL.createObjectURL(new Blob([data], { type: asset.mime }));\n urls.set(key, url);\n return url;\n };\n const source = config.assets[config.document.entry];\n const doc = new DOMParser().parseFromString(new TextDecoder().decode(decode(source)), \"text/html\");\n doc.querySelectorAll(\"base,meta[http-equiv]\").forEach((el) => el.remove());\n for (const element of Array.from(doc.querySelectorAll(\"[src],link[href]\"))) {\n const key = element.hasAttribute(\"src\") ? \"src\" : \"href\";\n const original = element.getAttribute(key);\n const resolved = assetUrl(original);\n if (resolved || element.tagName === \"SCRIPT\" || element.tagName === \"LINK\")\n element.setAttribute(key, resolved);\n }\n doc.documentElement.dataset.theme = config.theme;\n doc.documentElement.dataset.mobile = \"true\";\n const viewport = doc.createElement(\"meta\");\n viewport.name = \"viewport\";\n viewport.content = \"width=device-width,initial-scale=1,viewport-fit=cover\";\n doc\n .querySelectorAll('meta[name=\"viewport\"]')\n .forEach((element) => element.remove());\n doc.head.prepend(viewport);\n doc.documentElement.classList.toggle(\"dark\", config.theme === \"dark\");\n const theme = doc.createElement(\"style\");\n theme.textContent = `:root{color-scheme:${config.theme};${Object.entries(config.colors)\n .map(([key, value]) => `--${key}:${value}`)\n .join(\";\")}}html,body{max-width:100%;overscroll-behavior:none}body{margin:0}input,textarea,select{font-size:max(16px,1em)}button,a,input,select{touch-action:manipulation}`;\n doc.head.append(theme);\n const csp = doc.createElement(\"meta\");\n csp.httpEquiv = \"Content-Security-Policy\";\n csp.content =\n \"default-src 'none'; script-src blob: 'unsafe-inline'; style-src blob: 'unsafe-inline'; img-src data: blob: https:; font-src data: blob:; media-src data: blob:; connect-src 'none'; frame-src 'none'; form-action 'none'; base-uri 'none'\";\n doc.head.prepend(csp);\n document.open();\n document.write(\"<!doctype html>\" + doc.documentElement.outerHTML);\n document.close();\n window.addEventListener(\"message\", receive);\n document.addEventListener(\"message\", receive);\n document.addEventListener(\"click\", (event) => {\n const link = event.target?.closest?.(\"a[href]\");\n if (link) {\n event.preventDefault();\n send({ type: \"link\", url: link.getAttribute(\"href\") });\n }\n }, true);\n const resources = new WeakMap();\n const resolveImages = () => {\n if (!window.document)\n return;\n for (const element of Array.from(document.querySelectorAll(\"img[src],video[src],audio[src],source[src]\"))) {\n const src = element.getAttribute(\"src\");\n if (/^(?:data:|blob:|https:)/.test(src) || resources.get(element) === src)\n continue;\n resources.set(element, src);\n const local = assetUrl(src);\n if (local) {\n element.setAttribute(\"src\", local);\n continue;\n }\n void window\n .fetch(src)\n .then((response) => {\n if (!response.ok)\n throw new Error(\"PLUGIN_RESOURCE_UNAVAILABLE\");\n return response.blob();\n })\n .then((blob) => {\n if (!closed &&\n element.isConnected &&\n element.getAttribute(\"src\") === src) {\n const url = URL.createObjectURL(blob);\n mediaUrls.add(url);\n element.setAttribute(\"src\", url);\n }\n })\n .catch(() => send({ type: \"resource-error\" }));\n }\n };\n const observer = new MutationObserver(resolveImages);\n observer.observe(document.documentElement, {\n subtree: true,\n childList: true,\n attributes: true,\n attributeFilter: [\"src\"],\n });\n window.addEventListener(\"pagehide\", () => {\n closed = true;\n observer.disconnect();\n for (const url of [...urls.values(), ...mediaUrls])\n URL.revokeObjectURL(url);\n for (const waiter of pending.values()) {\n clearTimeout(waiter.timeout);\n waiter.reject(new Error(\"PLUGIN_PAGE_CLOSED\"));\n }\n pending.clear();\n for (const waiter of localRequests.values()) {\n clearTimeout(waiter.timeout);\n waiter.reject(new Error(\"PLUGIN_PAGE_CLOSED\"));\n }\n localRequests.clear();\n backListeners.clear();\n lifecycleListeners.clear();\n unreadListeners.clear();\n receivedDeliveries.clear();\n channels.clear();\n });\n resolveImages();\n // Read acknowledgement belongs to the native focused page, after it has rendered.\n const ready = () => requestAnimationFrame(() => send({ type: \"ready\" }));\n if (document.readyState === \"complete\")\n ready();\n else\n window.addEventListener(\"load\", ready, { once: true });\n}\n";diff --git a/apps/mobile/src/plugins/pluginPageBootstrap.ts b/apps/mobile/src/plugins/pluginPageBootstrap.tsnew file mode 100644index 0000000000..f99e8289d9--- /dev/null+++ b/apps/mobile/src/plugins/pluginPageBootstrap.ts@@ -0,0 +1,433 @@+import type { PluginPageAsset, PluginPageDocument } from "@cindy/device-link";++export interface PageConfig {+ document: PluginPageDocument;+ assets: Record<string, PluginPageAsset>;+ theme: "light" | "dark";+ colors: Record<string, string>;+}++/** This bootstrap runs only in the isolated WebView; no native credential/IPC object. */+export function bootstrap(config: PageConfig) {+ const native = (+ window as unknown as {+ ReactNativeWebView: { postMessage(value: string): void };+ }+ ).ReactNativeWebView;+ const send = (value: Record<string, unknown>) =>+ native.postMessage(+ JSON.stringify({ ...value, pageId: config.document.pageId }),+ );+ const pending = new Map<+ string,+ {+ resolve(value: Response): void;+ reject(error: Error): void;+ timeout: ReturnType<typeof setTimeout>;+ }+ >();+ const channels = new Map<string, Set<MobileBroadcastChannel>>();+ const localRequests = new Map<+ string,+ {+ resolve(value: unknown): void;+ reject(error: Error): void;+ timeout: ReturnType<typeof setTimeout>;+ }+ >();+ const backListeners = new Set<() => void>();+ const lifecycleListeners = new Set<(active: boolean) => void>();+ const unreadListeners = new Set<(version: number) => void>();+ let unreadVersion = config.document.unreadAt;+ let active = false;+ let request = 0,+ delivered = 0;+ let closed = false;+ const receivedDeliveries = new Set<number>();+ const localRequest = (type: string, key: string, value?: unknown) =>+ new Promise<unknown>((resolve, reject) => {+ const id = `local:${++request}`;+ const timeout = setTimeout(() => {+ localRequests.delete(id);+ reject(new Error("PLUGIN_DRAFT_UNCONFIRMED"));+ }, 5_000);+ localRequests.set(id, { resolve, reject, timeout });+ send({ type, id, key, value });+ });+ Object.defineProperty(window, "cindyMobile", {+ value: Object.freeze({+ version: 1,+ setNavigation: (canGoBack: boolean, title?: string) =>+ send({ type: "navigation", canGoBack: canGoBack === true, title }),+ onBack: (listener: () => void) => {+ backListeners.add(listener);+ return () => backListeners.delete(listener);+ },+ onLifecycle: (listener: (active: boolean) => void) => {+ lifecycleListeners.add(listener);+ return () => lifecycleListeners.delete(listener);+ },+ onUnread: (listener: (version: number) => void) => {+ unreadListeners.add(listener);+ if (Number.isSafeInteger(unreadVersion)) {+ const version = unreadVersion!;+ queueMicrotask(() => {+ if (unreadListeners.has(listener) && unreadVersion === version)+ listener(version);+ });+ }+ return () => unreadListeners.delete(listener);+ },+ contentRendered: (version: number) => {+ if (+ config.document.surface !== "panel" ||+ !Number.isSafeInteger(version) ||+ version !== unreadVersion+ )+ return;+ requestAnimationFrame(() => {+ if (!closed && active && version === unreadVersion)+ send({ type: "content-rendered", seenAt: version });+ });+ },+ openTask: (taskId: string) =>+ send({+ type: "link",+ url: `cindy://sessions/${encodeURIComponent(taskId)}`,+ }),+ readDraft: (key: string) => localRequest("draft:get", key),+ writeDraft: (key: string, value: unknown) =>+ localRequest("draft:set", key, value),+ }),+ });+ const base = `https://plugin.invalid/${config.document.entry}`;+ const pathFor = (value: string, from = base) => {+ const url = new URL(value, from);+ if (+ url.origin !== "https://plugin.invalid" &&+ !(+ url.protocol === "cindy-ghost:" && url.host === config.document.pluginId+ )+ )+ throw new Error("PLUGIN_ORIGIN_DENIED");+ return decodeURIComponent(url.pathname.slice(1));+ };+ class MobileBroadcastChannel extends EventTarget {+ name: string;+ onmessage: ((event: MessageEvent) => void) | null = null;+ constructor(name: string) {+ super();+ if (!config.document.channels.includes(name))+ throw new Error("PLUGIN_CHANNEL_UNAVAILABLE");+ this.name = name;+ const set = channels.get(name) ?? new Set();+ set.add(this);+ channels.set(name, set);+ }+ postMessage(data: unknown) {+ send({ type: "post", channel: this.name, data });+ }+ close() {+ channels.get(this.name)?.delete(this);+ }+ }+ Object.defineProperty(window, "BroadcastChannel", {+ value: MobileBroadcastChannel,+ });+ const decode = (asset: PluginPageAsset) =>+ Uint8Array.from(atob(asset.base64), (c) => c.charCodeAt(0));+ window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {+ const url =+ typeof input === "string"+ ? input+ : input instanceof URL+ ? input.href+ : input.url;+ const path = pathFor(url);+ const method = (+ init?.method ?? (input instanceof Request ? input.method : "GET")+ ).toUpperCase();+ if (path === "wake")+ return new Response(JSON.stringify({ ok: true }), {+ headers: { "content-type": "application/json" },+ });+ const asset = config.assets[path];+ if (asset && method === "GET")+ return new Response(decode(asset), {+ headers: { "content-type": asset.mime },+ });+ if (init?.body !== undefined && typeof init.body !== "string")+ throw new Error("PLUGIN_BODY_UNSUPPORTED");+ const parts: BlobPart[] = [];+ let offset: number | undefined,+ revision: string | undefined,+ response: Response;+ do {+ const id = String(++request);+ response = await new Promise<Response>((resolve, reject) => {+ const timeout = setTimeout(() => {+ pending.delete(id);+ reject(new Error("PLUGIN_REQUEST_UNCONFIRMED"));+ }, 30_000);+ pending.set(id, { resolve, reject, timeout });+ send({+ type: "fetch",+ id,+ path: "/" + path + new URL(url, base).search,+ method,+ body: init?.body,+ offset,+ revision,+ });+ });+ revision = response.headers.get("x-cindy-revision") ?? undefined;+ parts.push(await response.arrayBuffer());+ const next = response.headers.get("x-cindy-next-offset");+ if (next && Number(next) <= (offset ?? 0))+ throw new Error("PLUGIN_RESPONSE_INVALID");+ offset = next ? Number(next) : undefined;+ } while (offset !== undefined);+ return new Response(+ [204, 205, 304].includes(response.status) ? null : new Blob(parts),+ {+ status: response.status,+ headers: {+ "content-type":+ response.headers.get("content-type") ?? "application/octet-stream",+ },+ },+ );+ };+ const receive = (event: MessageEvent) => {+ let message;+ try {+ message = JSON.parse(event.data);+ } catch {+ return;+ }+ if (Number.isSafeInteger(message.deliveryId)) {+ if (receivedDeliveries.has(message.deliveryId)) return;+ receivedDeliveries.add(message.deliveryId);+ if (receivedDeliveries.size > 128)+ receivedDeliveries.delete(receivedDeliveries.values().next().value!);+ }+ if (message.type === "back") {+ for (const listener of backListeners) listener();+ } else if (message.type === "lifecycle") {+ active = message.active === true;+ for (const listener of lifecycleListeners) listener(active);+ } else if (message.type === "draft:reply") {+ const waiter = localRequests.get(message.id);+ if (!waiter) return;+ localRequests.delete(message.id);+ clearTimeout(waiter.timeout);+ if (message.error) waiter.reject(new Error("PLUGIN_DRAFT_UNCONFIRMED"));+ else waiter.resolve(message.value);+ } else if (message.type === "events") {+ if (message.unreadAt !== unreadVersion) {+ unreadVersion = Number.isSafeInteger(message.unreadAt)+ ? message.unreadAt+ : undefined;+ if (unreadVersion !== undefined)+ for (const listener of unreadListeners) listener(unreadVersion);+ }+ for (const item of message.events) {+ if (!Number.isSafeInteger(item.sequence) || item.sequence <= delivered)+ continue;+ for (const channel of channels.get(item.channel) ?? []) {+ const received = new MessageEvent("message", { data: item.data });+ channel.dispatchEvent(received);+ channel.onmessage?.(received);+ }+ delivered = item.sequence;+ }+ send({ type: "events-ack", sequence: delivered });+ } else if (message.type === "theme") {+ document.documentElement.dataset.theme = message.theme;+ document.documentElement.classList.toggle(+ "dark",+ message.theme === "dark",+ );+ document.documentElement.style.colorScheme = message.theme;+ for (const [key, value] of Object.entries(+ message.colors as Record<string, string>,+ ))+ document.documentElement.style.setProperty(`--${key}`, value);+ } else if (message.type === "reply") {+ const waiter = pending.get(message.id);+ if (!waiter) return;+ pending.delete(message.id);+ clearTimeout(waiter.timeout);+ if (message.error) waiter.reject(new Error("PLUGIN_REQUEST_UNCONFIRMED"));+ else+ waiter.resolve(+ new Response(+ [204, 205, 304].includes(message.result.status)+ ? null+ : decode(message.result),+ {+ status: message.result.status,+ headers: {+ "content-type": message.result.mime,+ ...(message.result.revision+ ? { "x-cindy-revision": message.result.revision }+ : {}),+ ...(message.result.nextOffset === undefined+ ? {}+ : {+ "x-cindy-next-offset": String(message.result.nextOffset),+ }),+ },+ },+ ),+ );+ }+ };+ const urls = new Map<string, string>();+ const mediaUrls = new Set<string>();+ const assetUrl = (relative: string, from = base): string => {+ if (/^(?:data:|blob:|https:)/.test(relative)) return relative;+ let key;+ try {+ key = pathFor(relative, from);+ } catch {+ return "";+ }+ if (urls.has(key)) return urls.get(key)!;+ const asset = config.assets[key];+ if (!asset) return "";+ let data: BlobPart = decode(asset);+ if (asset.mime.startsWith("text/css"))+ data = new TextDecoder()+ .decode(data as Uint8Array)+ .replace(+ /url\(\s*(['"]?)([^)'"\s]+)\1\s*\)/g,+ (_match, _quote, value) =>+ `url("${assetUrl(value, `https://plugin.invalid/${key}`)}")`,+ );+ const url = URL.createObjectURL(new Blob([data], { type: asset.mime }));+ urls.set(key, url);+ return url;+ };+ const source = config.assets[config.document.entry];+ const doc = new DOMParser().parseFromString(+ new TextDecoder().decode(decode(source)),+ "text/html",+ );+ doc.querySelectorAll("base,meta[http-equiv]").forEach((el) => el.remove());+ for (const element of Array.from(doc.querySelectorAll("[src],link[href]"))) {+ const key = element.hasAttribute("src") ? "src" : "href";+ const original = element.getAttribute(key)!;+ const resolved = assetUrl(original);+ if (resolved || element.tagName === "SCRIPT" || element.tagName === "LINK")+ element.setAttribute(key, resolved);+ }+ doc.documentElement.dataset.theme = config.theme;+ doc.documentElement.dataset.mobile = "true";+ const viewport = doc.createElement("meta");+ viewport.name = "viewport";+ viewport.content = "width=device-width,initial-scale=1,viewport-fit=cover";+ doc+ .querySelectorAll('meta[name="viewport"]')+ .forEach((element) => element.remove());+ doc.head.prepend(viewport);+ doc.documentElement.classList.toggle("dark", config.theme === "dark");+ const theme = doc.createElement("style");+ theme.textContent = `:root{color-scheme:${config.theme};${Object.entries(+ config.colors,+ )+ .map(([key, value]) => `--${key}:${value}`)+ .join(+ ";",+ )}}html,body{max-width:100%;overscroll-behavior:none}body{margin:0}input,textarea,select{font-size:max(16px,1em)}button,a,input,select{touch-action:manipulation}`;+ doc.head.append(theme);+ const csp = doc.createElement("meta");+ csp.httpEquiv = "Content-Security-Policy";+ csp.content =+ "default-src 'none'; script-src blob: 'unsafe-inline'; style-src blob: 'unsafe-inline'; img-src data: blob: https:; font-src data: blob:; media-src data: blob:; connect-src 'none'; frame-src 'none'; form-action 'none'; base-uri 'none'";+ doc.head.prepend(csp);+ document.open();+ document.write("<!doctype html>" + doc.documentElement.outerHTML);+ document.close();+ window.addEventListener("message", receive);+ document.addEventListener("message", receive as EventListener);+ document.addEventListener(+ "click",+ (event) => {+ const link = (event.target as Element)?.closest?.("a[href]");+ if (link) {+ event.preventDefault();+ send({ type: "link", url: link.getAttribute("href") });+ }+ },+ true,+ );+ const resources = new WeakMap<Element, string>();+ const resolveImages = () => {+ if (!window.document) return;+ for (const element of Array.from(+ document.querySelectorAll("img[src],video[src],audio[src],source[src]"),+ )) {+ const src = element.getAttribute("src")!;+ if (/^(?:data:|blob:|https:)/.test(src) || resources.get(element) === src)+ continue;+ resources.set(element, src);+ const local = assetUrl(src);+ if (local) {+ element.setAttribute("src", local);+ continue;+ }+ void window+ .fetch(src)+ .then((response) => {+ if (!response.ok) throw new Error("PLUGIN_RESOURCE_UNAVAILABLE");+ return response.blob();+ })+ .then((blob) => {+ if (+ !closed &&+ element.isConnected &&+ element.getAttribute("src") === src+ ) {+ const url = URL.createObjectURL(blob);+ mediaUrls.add(url);+ element.setAttribute("src", url);+ }+ })+ .catch(() => send({ type: "resource-error" }));+ }+ };+ const observer = new MutationObserver(resolveImages);+ observer.observe(document.documentElement, {+ subtree: true,+ childList: true,+ attributes: true,+ attributeFilter: ["src"],+ });+ window.addEventListener("pagehide", () => {+ closed = true;+ observer.disconnect();+ for (const url of [...urls.values(), ...mediaUrls])+ URL.revokeObjectURL(url);+ for (const waiter of pending.values()) {+ clearTimeout(waiter.timeout);+ waiter.reject(new Error("PLUGIN_PAGE_CLOSED"));+ }+ pending.clear();+ for (const waiter of localRequests.values()) {+ clearTimeout(waiter.timeout);+ waiter.reject(new Error("PLUGIN_PAGE_CLOSED"));+ }+ localRequests.clear();+ backListeners.clear();+ lifecycleListeners.clear();+ unreadListeners.clear();+ receivedDeliveries.clear();+ channels.clear();+ });+ resolveImages();+ // Read acknowledgement belongs to the native focused page, after it has rendered.+ const ready = () => requestAnimationFrame(() => send({ type: "ready" }));+ if (document.readyState === "complete") ready();+ else window.addEventListener("load", ready, { once: true });+}diff --git a/apps/mobile/src/plugins/pluginPageHtml.ts b/apps/mobile/src/plugins/pluginPageHtml.tsnew file mode 100644index 0000000000..30af288ad4--- /dev/null+++ b/apps/mobile/src/plugins/pluginPageHtml.ts@@ -0,0 +1,10 @@+import type { PageConfig } from "./pluginPageBootstrap";+import { PLUGIN_PAGE_BOOTSTRAP } from "./pluginPageBootstrap.generated";++export function pluginPageHtml(config: PageConfig): string {+ const json = JSON.stringify(config)+ .replace(/</g, "\\u003c")+ .replace(/\u2028/g, "\\u2028")+ .replace(/\u2029/g, "\\u2029");+ return `<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"></head><body><script>document.addEventListener('DOMContentLoaded',()=>(${PLUGIN_PAGE_BOOTSTRAP})(${json}),{once:true})</script></body></html>`;+}diff --git a/apps/mobile/src/plugins/pluginPreviewQueries.ts b/apps/mobile/src/plugins/pluginPreviewQueries.tsnew file mode 100644index 0000000000..a606e4ebd2--- /dev/null+++ b/apps/mobile/src/plugins/pluginPreviewQueries.ts@@ -0,0 +1,32 @@+const prefix = "__cindy_plugin_query/";+/** Existing native snapshots strip query strings. Encode GET query targets as opaque resource paths. */+export function pluginPreviewQueryTarget(+ path: string,+ origin: string,+): string | undefined {+ if (!path.startsWith(prefix)) return undefined;+ const hex = path.slice(prefix.length);+ if (!/^(?:[a-f0-9]{2}){1,4096}$/.test(hex))+ throw new Error("INVALID_PREVIEW_QUERY");+ const target = new URL(+ Array.from({ length: hex.length / 2 }, (_, index) =>+ String.fromCharCode(parseInt(hex.slice(index * 2, index * 2 + 2), 16)),+ ).join(""),+ origin,+ );+ if (+ target.origin !== origin ||+ target.username ||+ target.password ||+ target.hash+ )+ throw new Error("INVALID_PREVIEW_QUERY");+ return target.href;+}+export const PLUGIN_PREVIEW_QUERY_SCRIPT = `<script>(()=>{+ const map=(raw)=>{const u=new URL(raw,location.href);if(u.origin!==location.origin||!u.search)return raw;+ const value=u.pathname+u.search;if(value.length>4096)throw new Error('PREVIEW_QUERY_TOO_LARGE');+ return location.origin+'/__cindy_plugin_query/'+Array.from(value,c=>c.charCodeAt(0).toString(16).padStart(2,'0')).join('');};+ const fetch=window.fetch.bind(window);window.fetch=(input,init)=>fetch(input instanceof Request?new Request(map(input.url),input):map(String(input)),init);+ const open=XMLHttpRequest.prototype.open;XMLHttpRequest.prototype.open=function(method,url,...rest){return open.call(this,method,map(String(url)),...rest);};+})();</script>`;diff --git a/apps/mobile/src/plugins/pluginSetupActions.ts b/apps/mobile/src/plugins/pluginSetupActions.tsnew file mode 100644index 0000000000..7a90b4c328--- /dev/null+++ b/apps/mobile/src/plugins/pluginSetupActions.ts@@ -0,0 +1,97 @@+import {+ parsePluginOauthAction,+ parsePluginSecretPresentation,+ parsePluginConnectionPresentation,+ type PluginOauthAction,+ type PluginSecretPresentation,+ type PluginConnectionPresentation,+} from "@cindy/device-link";+export interface MobilePluginSetupAction {+ action: PluginOauthAction;+ ghostId: string;+ stepId: string;+ title: string;+ kind: "oauth" | "secret" | "connection";+ secret?: PluginSecretPresentation;+ connection?: PluginConnectionPresentation;+}+const record = (v: unknown): Record<string, unknown> =>+ v && typeof v === "object" && !Array.isArray(v)+ ? (v as Record<string, unknown>)+ : {};+/** Only projected eligible pending Host steps. The encrypted offer must match what the native form shows. */+export function mobilePluginSetupActions(+ raw: unknown,+): MobilePluginSetupAction[] {+ const r = record(raw),+ ghost = record(r.ghost);+ if (+ r.kind !== "plugin_setup" ||+ r.terminal ||+ typeof ghost.id !== "string" ||+ typeof ghost.name !== "string" ||+ !Array.isArray(r.steps)+ )+ return [];+ return r.steps.flatMap<MobilePluginSetupAction>((step, index) => {+ const s = record(step),+ a = record(s.action);+ const action = parsePluginOauthAction({+ requestId: r.requestId,+ expectedRevision: r.revision,+ actionId: a.id,+ });+ if (+ !action ||+ !["pending", "failed"].includes(s.phase as string) ||+ typeof s.title !== "string" ||+ typeof s.description !== "string"+ )+ return [];+ const base = {+ action,+ ghostId: ghost.id as string,+ title: s.title,+ stepId:+ typeof s.id === "string" && s.id.trim() ? s.id.trim() : `step-${index}`,+ };+ try {+ if (a.kind === "oauth_connect" && r.remoteOauth === true)+ return [{ ...base, kind: "oauth" as const }];+ if (a.kind === "inline_form" && r.remoteSecret === true) {+ const fields = record(a.form).fields;+ if (!Array.isArray(fields) || fields.length !== 1) return [];+ const field = record(fields[0]);+ const secret = parsePluginSecretPresentation({+ ghostName: ghost.name,+ title: s.title,+ description: s.description,+ intro: r.intro ?? "",+ fieldLabel: field.label,+ fieldDescription: field.description ?? "",+ maxLength: field.maxLength,+ });+ return [{ ...base, kind: "secret" as const, secret }];+ }+ if (+ a.kind === "manage_connection" &&+ r.remoteConnection === true &&+ action.actionId.startsWith("manage_connection:connection:")+ ) {+ const connection = parsePluginConnectionPresentation({+ ghostName: ghost.name,+ title: s.title,+ description: s.description,+ intro: r.intro ?? "",+ connectionKey: action.actionId.slice(+ "manage_connection:connection:".length,+ ),+ });+ return [{ ...base, kind: "connection" as const, connection }];+ }+ } catch {+ /* Invalid/unsupported steps retain the existing computer entry. */+ }+ return [];+ });+}diff --git a/apps/mobile/src/session/HomeChromeDrawer.tsx b/apps/mobile/src/session/HomeChromeDrawer.tsxindex 63f134bbe4..5608208bae 100644--- a/apps/mobile/src/session/HomeChromeDrawer.tsx+++ b/apps/mobile/src/session/HomeChromeDrawer.tsx@@ -10,7 +10,7 @@* 走透明 RN Modal(独立 Dialog 窗口),返回键由 onRequestClose 接管。* 新窗口里要自带 GestureHandlerRootView,左滑关闭才有效。动画遵循 reduce-motion。*/-import { Building2, LogOut, Monitor, Search, Settings, UsersRound } from 'lucide-react-native';+import { Building2, LogOut, Monitor, Puzzle, Search, Settings, UsersRound } from 'lucide-react-native';import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import {AccessibilityInfo,@@ -59,6 +59,7 @@ import {typeScale,} from "@/theme/tokens";+import { PluginMenuUnreadDot } from '@/plugins/PluginMenuUnreadDot';import { confirmLogout } from './confirmLogout';import { HomeModeSwitch } from './HomeModeSwitch';import type { HomeMode } from './homeViewPreferenceStore';@@ -75,6 +76,7 @@ export function HomeChromeDrawer({onOpenSearch,onOpenAccounts,onOpenDevices,+ onOpenPlugins,onOpenSettings,onLogout,hasRunningTasks = false,@@ -91,6 +93,7 @@ export function HomeChromeDrawer({onOpenSearch(): void;onOpenAccounts(): void;onOpenDevices(): void;+ onOpenPlugins?(): void;onOpenSettings(): void;/** 确认后才调用:抽屉内部先弹 confirmLogout,调用方不要再重复确认。 */onLogout(): void;@@ -347,6 +350,13 @@ export function HomeChromeDrawer({</Text></Pressable>+ {onOpenPlugins ? <Pressable accessibilityRole="button" accessibilityLabel={t('plugins.title')}+ onPress={onOpenPlugins} style={({ pressed }) => [styles.menuRow, pressed && styles.pressed]} testID="home.chromeDrawer.plugins">+ <Puzzle color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} />+ <Text numberOfLines={1} style={styles.menuLabel}>{t('plugins.title')}</Text>+ <PluginMenuUnreadDot active={open} />+ </Pressable> : null}+<PressableaccessibilityLabel={t('devices.management.title')}accessibilityRole="button"diff --git a/apps/mobile/src/session/HomeSurface.tsx b/apps/mobile/src/session/HomeSurface.tsxindex 23b16d03d5..8e2d6742bd 100644--- a/apps/mobile/src/session/HomeSurface.tsx+++ b/apps/mobile/src/session/HomeSurface.tsx@@ -3086,6 +3086,12 @@ function HomeScreenContent({ active = true, onModeChange, width, onDismiss, newSsetChromeMenuCloseInstant(false);setChromeMenuOpen(false);}}+ onOpenPlugins={() => {+ pendingMenuActionRef.current = null;+ guardedPush('/plugins');+ setChromeMenuCloseInstant(true);+ setChromeMenuOpen(false);+ }}onOpenDevices={() => {pendingMenuActionRef.current = null;guardedPush('/devices/manage');diff --git a/apps/mobile/src/session/InteractionPanel.tsx b/apps/mobile/src/session/InteractionPanel.tsxindex 24d9b0e9c2..974cefcab8 100644--- a/apps/mobile/src/session/InteractionPanel.tsx+++ b/apps/mobile/src/session/InteractionPanel.tsx@@ -1,3 +1,5 @@+import { PluginSetupNativeActions } from '@/plugins/PluginSetupNativeActions';+import { mobilePluginSetupActions } from '@/plugins/pluginSetupActions';import { usePaneViewport } from '@/platform/AdaptiveWindowContext';import { createContext, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';@@ -632,9 +634,8 @@ function InteractionItem({/>);}- // plugin_setup:配置动作(OAuth / 写本地设置)只能在被控端完成,被控端的 IPC- // 边界也只放 cancel 过来。手机侧因此给只读摘要 + 取消出口,让用户至少能把- // 会话从等待里放出来,而不是对着一张没有任何按钮的卡干等。+ // 配置通过独立加密 v3 原生入口;通用交互 resolve 仍只允许取消。+ // 旧 Host、共享访客及电脑本地回调保留电脑入口。if (kind === 'plugin_setup') {// 取消入口以共享分类器为准:terminal 快照(被控端 settle 后短暂保留的收尾帧)// 归 desktop-only,此时被控端已 complete、不再受理 resolve,给按钮只会让用户点出@@ -1567,10 +1568,8 @@ function PlanReviewCard({/*** plugin_setup 的**只读**状态卡。*- * 手机端做不了配置动作(Secret 输入与 OAuth 必须留在被控端,见- * docs/dev-rules/plugin-security-and-authoring.md §4 与 desktop 的- * interactionResolveOrigin),所以这张卡的价值全在「看懂」:哪个插件、卡在哪一步、- * 为什么失败、回电脑端要做什么。可进入目标电脑的远程桌面或取消请求。+ * 手机原生配置只处理 Host 明确投影的专用加密动作。电脑专属步骤仍使用远程桌面入口;+ * 普通 interaction resolve 不传 Secret/OAuth 内容。*/export function PluginSetupMessageContent({ request, busy, onCancel, deviceId }: {request: PendingInteraction['request']; busy: boolean; onCancel?: () => void; deviceId?: string;@@ -1606,6 +1605,8 @@ function PluginSetupCard({() => buildRemotePluginSetupPresentation(item.request),[item.request],);+ const nativeSteps = new Set(deviceId && !isSharedTaskPeer(deviceId) ? mobilePluginSetupActions(item.request).map(action => action.stepId) : []);+ const nativeSetup = nativeSteps.size > 0;const title = presentation.ghostName ?? t('interaction.kinds.plugin_setup.title');return (<View style={cardStyle(styles, touchLayout, companion)} testID="interaction.pluginSetup.card">@@ -1622,7 +1623,7 @@ function PluginSetupCard({/>) : null}<View style={styles.compactCardTitleWrap}>- <Text style={styles.kind}>{t(presentation.terminal ? 'interaction.kinds.plugin_setup.label' : 'interaction.panel.desktopOnlyKind')}</Text>+ <Text style={styles.kind}>{t(presentation.terminal || nativeSetup ? 'interaction.kinds.plugin_setup.label' : 'interaction.panel.desktopOnlyKind')}</Text><Text numberOfLines={1} style={styles.compactCardTitle}>{title}</Text></View>{presentation.stepCount > 0 && !presentation.terminal ? (@@ -1643,13 +1644,14 @@ function PluginSetupCard({<Text style={styles.pluginSetupGroupHint}>{t('interaction.pluginSetup.chooseOne')}</Text>) : null}{group.steps.map((step) => (- <PluginSetupStepRow key={step.id} step={step} terminal={presentation.terminal} />+ <PluginSetupStepRow key={step.id} step={step} terminal={presentation.terminal} native={nativeSteps.has(step.id)} />))}</View>))}+ {deviceId && !isSharedTaskPeer(deviceId) ? <PluginSetupNativeActions request={item.request} deviceId={deviceId} disabled={busy || presentation.terminal} /> : null}{/* 收尾帧已经 settle,再让用户「去电脑端完成」是错的引导。 */}{presentation.terminal ? null : (- <Text style={styles.pluginSetupFootnote}>{t('interaction.pluginSetup.completeOnDesktop')}</Text>+ <Text style={styles.pluginSetupFootnote}>{t(nativeSetup ? 'plugins.nativeSetupHint' : 'interaction.pluginSetup.completeOnDesktop')}</Text>)}{!presentation.terminal && deviceId && !isSharedTaskPeer(deviceId) ? (<PluginSetupRemoteDesktopButton deviceId={deviceId} busy={busy} />@@ -1694,7 +1696,7 @@ const PLUGIN_SETUP_RUNNING_PHASES: ReadonlySet<RemotePluginSetupPhase> = new Set'verifying',]);-function PluginSetupStepRow({ step, terminal }: { step: RemotePluginSetupStep; terminal: boolean }) {+function PluginSetupStepRow({ step, terminal, native }: { step: RemotePluginSetupStep; terminal: boolean; native: boolean }) {const styles = useInteractionStyles();const { colors } = useTheme();const { t } = useTranslation();@@ -1704,7 +1706,7 @@ function PluginSetupStepRow({ step, terminal }: { step: RemotePluginSetupStep; t? colors.statusAccent: colors.textTertiary;const phaseText = step.phase ? t(`interaction.pluginSetup.phase.${step.phase}`) : null;- const actionHint = step.actionKind === 'inline_form'+ const actionHint = native ? t('plugins.nativeStepHint') : step.actionKind === 'inline_form'? (step.inlineFieldLabel? t('interaction.pluginSetup.inlineFormAction', { label: step.inlineFieldLabel }): t('interaction.pluginSetup.inlineFormActionGeneric'))diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex 0a39de7902..14fd22d4d5 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -1,3 +1,4 @@+import { PluginCardActions } from '@/plugins/PluginCardActions';import { CompanionLearningFooter } from './CompanionLearningFooter';import { CompanionTaskResultCard } from './CompanionTaskResultCard';import { botTaskResultKey, readBotTaskResults } from '@cindy/maker-shared/botCollaboration';@@ -6442,6 +6443,7 @@ function PluginResultCard({ callId, sessionId, excludedUrls, actions }: {const { t } = useTranslation();return <View style={styles.toolMediaBlock} testID="message.pluginResultCard">{blocks?.map((block) => {+ if (block.primitive === 'plugin-card-actions') return <PluginCardActions key={block.id} data={block.data} deviceId={actions.remoteDeviceId} sessionId={sessionId} callId={callId} />;const url = (block.data as { url?: unknown } | undefined)?.url;const kind = managedToolMediaKind(url);if (typeof url === 'string' && excludedUrls.includes(url)) return null;diff --git a/apps/mobile/src/session/TeammateHomeScreen.tsx b/apps/mobile/src/session/TeammateHomeScreen.tsxindex e4d1ed4d71..b22b145d22 100644--- a/apps/mobile/src/session/TeammateHomeScreen.tsx+++ b/apps/mobile/src/session/TeammateHomeScreen.tsx@@ -96,6 +96,7 @@ export function TeammateHomeScreen({ active = true }: { active?: boolean }) {onModeChange={(mode) => afterDrawer(() => { void navigation.setMode(mode); })}onClose={() => { pending.current = null; setDrawer(false); }} onClosed={finishOverlay}onOpenSearch={() => afterDrawer(() => setSearchEpoch((epoch) => epoch + 1))}+ onOpenPlugins={() => afterDrawer(() => push('/plugins'))}onOpenDevices={() => afterDrawer(() => push('/devices/manage'))}onOpenSettings={() => afterDrawer(() => push('/settings'))}onOpenAccounts={() => afterDrawer(() => setAccounts(true))}diff --git a/apps/mobile/src/session/usePluginResultCard.ts b/apps/mobile/src/session/usePluginResultCard.tsindex 11d2021dfa..f93cca9bde 100644--- a/apps/mobile/src/session/usePluginResultCard.ts+++ b/apps/mobile/src/session/usePluginResultCard.ts@@ -7,7 +7,7 @@ import { useDeviceLink } from '@/device-link/DeviceLinkContext';import { getRemoteResource } from '@/device-link/remoteResources';import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscription';-/** A card is a read-only remote resource, scoped to account + device + task.+/** Card content and Host-projected actions are scoped to account + device + task.* Refresh after foreground/reconnect and host invalidation; stale replies cannot* replace a recycled row or another account's card. */export function usePluginResultCard(deviceId: string | undefined, sessionId: string, callId: string) {@@ -35,7 +35,7 @@ export function useSessionPluginResource(deviceId: string | undefined, sessionIdconst expected = ++generation;const valid = () => !disposed && current.current === binding && generation === expected && AppState.currentState === 'active';try {- const resource = await getRemoteResource(invoke, { deviceId, deviceName: deviceId }, { collectionId, kind, id });+ const resource = await getRemoteResource(invoke, { deviceId, deviceName: deviceId }, { collectionId, kind, id }, undefined, collectionId === 'plugin-results' ? ['plugin-card-actions'] : []);if (valid()) setState({ binding, blocks: resource.blocks ?? [], title: typeof resource.display.title === 'string' ? resource.display.title : resource.display.title.fallback, error: kind === 'card' && !resource.blocks?.length });} catch (error) {const code = error && typeof error === 'object' ? (error as { code?: unknown }).code : undefined;diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.mdindex 25f5d362f6..1e3aef58a6 100644--- a/docs/design-rules/design-inventory.md+++ b/docs/design-rules/design-inventory.md@@ -11,7 +11,7 @@计数快照日期:2026-10-01。生成命令:`pnpm design:inventory`。裸颜色匹配与 `scripts/hardcoded-color-audit.mjs` 共用 `scripts/shared/hardcoded-color-match.mjs`(HEX / RGB / HSL / OKLCH 等字面通道),两者在共享 matcher 内统一排除纯语义包装、注释及 PR 编号;数值颜色函数还需位于样式属性、CSS 声明/函数或任意值语境,普通文案字符串里的颜色函数文本不计入;字面 fallback 仍计入——语义 token 消费与注释引用不是迁移债务;裸圆角为粗粒度(`rounded*` class、`border-radius:` 与 React style 对象的 `borderRadius:`)。Token 计数为样式源里 `var(--token)` / `hsl(var(--token)` 的去重 ID 数;Mobile 的 ThemeColors / typeScale 等 RN 属性不计入此列,不能将 0 解释为未使用 Token。-登记 surface 数:51。平台包含 Desktop 与 Mobile;静态入口发现不表示已迁移或已实机验证。+登记 surface 数:52。平台包含 Desktop 与 Mobile;静态入口发现不表示已迁移或已实机验证。| ID | 平台 | 标题 | 生产入口 | 可达组件 | 样式来源 | Token 数 | 裸颜色 | 裸圆角 || --- | --- | --- | --- | --- | --- | ---: | ---: | ---: |@@ -54,15 +54,16 @@| `mobile.account-deletion` | mobile | 账号注销 | app/account-deletion.tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ClipboardSharedTaskPrompt, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, 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, ResidentHomeList, SharedTaskAdmissionDialog, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, account-deletion, gestureHandler, 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/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/ClipboardSharedTaskPrompt.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/ResidentHomeList.tsx, apps/mobile/src/session/SharedTaskAdmissionDialog.tsx, apps/mobile/src/session/SharedTaskScreen.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 | 210 | 62 || `mobile.auth` | mobile | 登录与添加账号 | app/(auth)/login.tsx / app/add-account.tsx | AccountSwitcherSheet, AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ClipboardSharedTaskPrompt, 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, ResidentHomeList, SharedTaskAdmissionDialog, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, 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/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/AccountSwitcherSheet.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ClipboardSharedTaskPrompt.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/ResidentHomeList.tsx, apps/mobile/src/session/SharedTaskAdmissionDialog.tsx, apps/mobile/src/session/SharedTaskScreen.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 | 217 | 84 || `mobile.chat.new` | mobile | 新建任务 | app/sessions/new.tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AnnotationBurnInWebView, AppText, AuthContext, BlurBackdrop, CenteredScreen, ClipboardSharedTaskPrompt, 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, DeviceLinkContext, FileTypeIcon, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, 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, NewTaskSelectionRow, NewTaskSelectionSheet, NewTaskSelectionSheet.android, NewTaskSelectionSheet.ios, 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, ResidentHomeList, SharedTaskAdmissionDialog, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, VoiceRecordingPill, _layout, gestureHandler, 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/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/AnnotationBurnInWebView.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ClipboardSharedTaskPrompt.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/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/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/PlanModeChip.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SharedTaskAdmissionDialog.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/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/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 | 242 | 109 |-| `mobile.chat.session` | mobile | 任务内容与输入 | app/sessions/[sessionId].tsx | AccountSwitcherSheet, AdaptiveWindow, AgentErrorDetails, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AnnotationBurnInWebView, AppText, AuthContext, AuthorizationMessageCard, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ChatFileChipMenuSheet, ChatIdentityHeader, ClipboardSharedTaskPrompt, 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, CompanionWorkingStatus, 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, ConversationSearchFilterSheet, ConversationShareSvg, ConversationShareWebView, DeviceLinkContext, FailedScheduleNotice, FileTypeIcon, FoldTouchpad, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeListVisuals, HomeModeSwitch, HomeNativeStackHeader, HomeNewTaskButton, HomeProjectMachineLabel, HomeSearchBar, HomeSurface, HomeUnreadContext, ImageLightbox, IncomingShareBridge, InlineQueueSection, InlineQuoteChip, InlineReferenceChip, InteractionPanel, MarkdownBlockContent, MessageActionSheet, 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.ios, NativeChromeButton.ios, NativePermissionSheet, NativePermissionSheet.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PaperPlaneIcon, PendingSendBubble, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PlanModeChip, PluginInvocationHeader, PromptRecommendation, PushNotificationsBridge, QuietSyncIndicator, QuoteCapsule, 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, RemoteTaskSuggestions, RenameSessionModal, ResidentHomeList, RewindPreviewPanel, RunningTokenRatePopover, SentInlineAtomBody, SessionActionSheet, SessionActionSheetFrame, SessionActionSheetFrame.android, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionListDrawer, SessionMenuSheet, SessionOptionsExpoSheet, SessionResourceCards, SessionRightSpinner, SessionSearchNative, SessionSearchNative.ios, SessionTailBanner, SessionTransientNotice, SessionUsageSummary, ShareImageNativeButton, ShareImageNativeButton.ios, ShareMessageCheckbox, ShareSelectAllButton, ShareSelectionBar, SharedTaskAdmissionDialog, SharedTaskEndedState, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, StreamingStatusText, SwipeableSessionRow, SwipeableSessionRow.ios, SystemNavigationBack, TaskTags, TaskTagsSheet, ThemeProvider, ThinkingDots, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, VoiceRecordingPill, WorkingStatusText, [sessionId], _layout, gestureHandler, listDisclosureTransition, mathWebView, mediaPlayerWebView, mermaidWebView, 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/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/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/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/ClipboardSharedTaskPrompt.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/CompanionWorkingStatus.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/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/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/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/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/RecentMessageHistories.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/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/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/SlowSendNotice.tsx, apps/mobile/src/session/StreamingStatusText.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/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/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 | 243 | 301 |+| `mobile.chat.session` | mobile | 任务内容与输入 | app/sessions/[sessionId].tsx | AccountSwitcherSheet, AdaptiveWindow, AgentErrorDetails, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AnnotationBurnInWebView, AppText, AuthContext, AuthorizationMessageCard, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ChatFileChipMenuSheet, ChatIdentityHeader, ClipboardSharedTaskPrompt, 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, CompanionWorkingStatus, 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, ConversationSearchFilterSheet, ConversationShareSvg, ConversationShareWebView, DeviceLinkContext, FailedScheduleNotice, FileTypeIcon, FoldTouchpad, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeListVisuals, HomeModeSwitch, HomeNativeStackHeader, HomeNewTaskButton, HomeProjectMachineLabel, HomeSearchBar, HomeSurface, HomeUnreadContext, ImageLightbox, IncomingShareBridge, InlineQueueSection, InlineQuoteChip, InlineReferenceChip, InteractionPanel, MarkdownBlockContent, MessageActionSheet, 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.ios, NativeChromeButton.ios, NativePermissionSheet, NativePermissionSheet.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PaperPlaneIcon, PendingSendBubble, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PlanModeChip, PluginCardActions, PluginInvocationHeader, PluginMenuUnreadDot, PluginSetupNativeActions, PluginSetupNativeForm, PromptRecommendation, PushNotificationsBridge, QuietSyncIndicator, QuoteCapsule, 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, RemoteTaskSuggestions, RenameSessionModal, ResidentHomeList, RewindPreviewPanel, RunningTokenRatePopover, SentInlineAtomBody, SessionActionSheet, SessionActionSheetFrame, SessionActionSheetFrame.android, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionListDrawer, SessionMenuSheet, SessionOptionsExpoSheet, SessionResourceCards, SessionRightSpinner, SessionSearchNative, SessionSearchNative.ios, SessionTailBanner, SessionTransientNotice, SessionUsageSummary, ShareImageNativeButton, ShareImageNativeButton.ios, ShareMessageCheckbox, ShareSelectAllButton, ShareSelectionBar, SharedTaskAdmissionDialog, SharedTaskEndedState, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, StreamingStatusText, SwipeableSessionRow, SwipeableSessionRow.ios, SystemNavigationBack, TaskTags, TaskTagsSheet, ThemeProvider, ThinkingDots, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, VoiceRecordingPill, WorkingStatusText, [sessionId], _layout, gestureHandler, listDisclosureTransition, mathWebView, mediaPlayerWebView, mermaidWebView, 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/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/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/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/ClipboardSharedTaskPrompt.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/CompanionWorkingStatus.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/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/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/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/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/RecentMessageHistories.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/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/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/SlowSendNotice.tsx, apps/mobile/src/session/StreamingStatusText.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/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/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 | 243 | 307 || `mobile.chat.sharing` | mobile | 共享任务邀请与成员 | app/shared-session.tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ClipboardSharedTaskPrompt, 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, ResidentHomeList, SharedTaskAdmissionDialog, SharedTaskEndedState, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, peerFileTransport, shared-session, useLocale, useSharedTaskConfirmation | apps/mobile/app/_layout.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/ClipboardSharedTaskPrompt.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/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 | 210 | 68 || `mobile.companions.direct` | mobile | 伙伴私聊回看 | app/companions/direct/[threadId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ClipboardSharedTaskPrompt, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, 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, ResidentHomeList, SharedTaskAdmissionDialog, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [threadId], _layout, gestureHandler, 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/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/ClipboardSharedTaskPrompt.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/ResidentHomeList.tsx, apps/mobile/src/session/SharedTaskAdmissionDialog.tsx, apps/mobile/src/session/SharedTaskScreen.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 | 210 | 60 |-| `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, BotGroupSettingsSheet, BotGroupSpeakerRow, CenteredScreen, ChatIdentityHeader, ClipboardSharedTaskPrompt, CompanionCardButton, CompanionEntering, CompanionLearningFooter, CompanionMessageActions, CompanionMessageCard, 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, ImageLightbox, IncomingShareBridge, InlineQuoteChip, InlineReferenceChip, InteractionPanel, MarkdownBlockContent, MessageActionSheet, MessageRenderer, MobileBoundaryNotice, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PaperPlaneIcon, PendingSendBubble, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PluginInvocationHeader, 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, ResidentHomeList, SentInlineAtomBody, ShareMessageCheckbox, SharedTaskAdmissionDialog, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, StreamingStatusText, ThemeProvider, ThinkingDots, WorkingStatusText, [groupId], _layout, gestureHandler, mathWebView, mediaPlayerWebView, mermaidWebView, 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/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/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/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/BotGroupSettingsSheet.tsx, apps/mobile/src/session/BotGroupSpeakerRow.tsx, apps/mobile/src/session/ChatIdentityHeader.tsx, apps/mobile/src/session/ClipboardSharedTaskPrompt.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/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/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/PendingSendBubble.tsx, apps/mobile/src/session/PluginInvocationHeader.tsx, apps/mobile/src/session/QuoteCapsule.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SentInlineAtomBody.tsx, apps/mobile/src/session/ShareMessageCheckbox.tsx, apps/mobile/src/session/SharedTaskAdmissionDialog.tsx, apps/mobile/src/session/SharedTaskScreen.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/StreamingStatusText.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 | 242 | 183 |+| `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, BotGroupSettingsSheet, BotGroupSpeakerRow, CenteredScreen, ChatIdentityHeader, ClipboardSharedTaskPrompt, CompanionCardButton, CompanionEntering, CompanionLearningFooter, CompanionMessageActions, CompanionMessageCard, 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, ImageLightbox, IncomingShareBridge, InlineQuoteChip, InlineReferenceChip, InteractionPanel, MarkdownBlockContent, MessageActionSheet, MessageRenderer, MobileBoundaryNotice, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, 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, ResidentHomeList, SentInlineAtomBody, ShareMessageCheckbox, SharedTaskAdmissionDialog, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, StreamingStatusText, ThemeProvider, ThinkingDots, WorkingStatusText, [groupId], _layout, gestureHandler, mathWebView, mediaPlayerWebView, mermaidWebView, 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/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/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/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/BotGroupSettingsSheet.tsx, apps/mobile/src/session/BotGroupSpeakerRow.tsx, apps/mobile/src/session/ChatIdentityHeader.tsx, apps/mobile/src/session/ClipboardSharedTaskPrompt.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/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/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/PendingSendBubble.tsx, apps/mobile/src/session/PluginInvocationHeader.tsx, apps/mobile/src/session/QuoteCapsule.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SentInlineAtomBody.tsx, apps/mobile/src/session/ShareMessageCheckbox.tsx, apps/mobile/src/session/SharedTaskAdmissionDialog.tsx, apps/mobile/src/session/SharedTaskScreen.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/StreamingStatusText.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 | 242 | 188 || `mobile.device-management` | mobile | 设备管理 | app/devices/manage.tsx / app/devices/manage/[deviceId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ClipboardSharedTaskPrompt, 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, 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, RenameDeviceModal, ResidentHomeList, SettingsGroupRows, SharedTaskAdmissionDialog, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, listDisclosureTransition, manage, 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/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/ClipboardSharedTaskPrompt.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/RenameDeviceModal.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SettingsGroupRows.tsx, apps/mobile/src/session/SharedTaskAdmissionDialog.tsx, apps/mobile/src/session/SharedTaskScreen.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 | 210 | 60 |-| `mobile.devices` | mobile | 主机详情 | app/devices/[deviceId].tsx | AccountSwitcherSheet, AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ClipboardSharedTaskPrompt, 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, 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, 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, RemoteTaskSuggestions, RenameSessionModal, ResidentHomeList, SessionActionSheet, SessionActionSheetFrame, SessionActionSheetFrame.android, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionOptionsExpoSheet, SessionRightSpinner, SharedTaskAdmissionDialog, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, TaskTags, ThemeProvider, [deviceId], _layout, gestureHandler, listDisclosureTransition, 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/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/AccountSwitcherSheet.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ClipboardSharedTaskPrompt.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/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/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/SharedTaskAdmissionDialog.tsx, apps/mobile/src/session/SharedTaskScreen.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 | 210 | 112 |+| `mobile.devices` | mobile | 主机详情 | app/devices/[deviceId].tsx | AccountSwitcherSheet, AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ClipboardSharedTaskPrompt, 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, 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, RemoteTaskSuggestions, RenameSessionModal, ResidentHomeList, SessionActionSheet, SessionActionSheetFrame, SessionActionSheetFrame.android, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionOptionsExpoSheet, SessionRightSpinner, SharedTaskAdmissionDialog, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, TaskTags, ThemeProvider, [deviceId], _layout, gestureHandler, listDisclosureTransition, 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/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/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/ClipboardSharedTaskPrompt.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/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/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/SharedTaskAdmissionDialog.tsx, apps/mobile/src/session/SharedTaskScreen.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 | 210 | 113 || `mobile.files` | mobile | 任务文件与预览 | app/files/[sessionId].tsx / app/files/preview/[sessionId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ClipboardSharedTaskPrompt, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FileBrowserSegmentedControl, 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, 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, ResidentHomeList, SharedTaskAdmissionDialog, SharedTaskScreen, 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/ClipboardSharedTaskPrompt.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/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/RecentMessageHistories.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SharedTaskAdmissionDialog.tsx, apps/mobile/src/session/SharedTaskScreen.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 | 242 | 81 |-| `mobile.home` | mobile | 主机与资源首页 | app/index.tsx / app/devices/index.tsx | AccountSwitcherSheet, AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, BotGroupAvatars, BotGroupCreateSheet, BotGroupList, CenteredScreen, ClipboardSharedTaskPrompt, 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, 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, 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, RemoteTaskSuggestions, RenameSessionModal, ResidentHomeList, SessionActionSheet, SessionActionSheetFrame, SessionActionSheetFrame.android, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionOptionsExpoSheet, SessionRightSpinner, SharedTaskAdmissionDialog, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, TaskTags, TeammateCreateButton, TeammateGenerationLabel, TeammateHomeScreen, TeammateList, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, WorkingStatusText, _layout, gestureHandler, index, listDisclosureTransition, 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/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/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/ClipboardSharedTaskPrompt.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/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/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/SharedTaskAdmissionDialog.tsx, apps/mobile/src/session/SharedTaskScreen.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 | 210 | 144 |+| `mobile.home` | mobile | 主机与资源首页 | app/index.tsx / app/devices/index.tsx | AccountSwitcherSheet, AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, BotGroupAvatars, BotGroupCreateSheet, BotGroupList, CenteredScreen, ClipboardSharedTaskPrompt, 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, 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, RemoteTaskSuggestions, RenameSessionModal, ResidentHomeList, SessionActionSheet, SessionActionSheetFrame, SessionActionSheetFrame.android, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionOptionsExpoSheet, SessionRightSpinner, SharedTaskAdmissionDialog, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, TaskTags, TeammateCreateButton, TeammateGenerationLabel, TeammateHomeScreen, TeammateList, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, WorkingStatusText, _layout, gestureHandler, index, listDisclosureTransition, 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/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/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/ClipboardSharedTaskPrompt.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/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/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/SharedTaskAdmissionDialog.tsx, apps/mobile/src/session/SharedTaskScreen.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 | 210 | 145 || `mobile.overlay.connection-startup` | mobile | 根布局挂载的启动与连接反馈 | app/_layout.tsx → StartupSplashOverlay / ConnectionNoticeProvider;各页面 ConnectionBanner | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ClipboardSharedTaskPrompt, 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, ResidentHomeList, SharedTaskAdmissionDialog, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, 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/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/ClipboardSharedTaskPrompt.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/ResidentHomeList.tsx, apps/mobile/src/session/SharedTaskAdmissionDialog.tsx, apps/mobile/src/session/SharedTaskScreen.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 | 210 | 55 |+| `mobile.plugins` | mobile | 插件目录、页面与原生交互 | app/plugins.tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ClipboardSharedTaskPrompt, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, 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, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PluginDirectoryPicker, PluginMediaViewer, PluginNativeIntent, PluginPage, PluginScheduleDraft, PluginTaskPicker, PluginTaskSettings, 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, ResidentHomeList, SharedTaskAdmissionDialog, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, _layout, gestureHandler, mediaPlayerWebView, 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/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/plugins/PluginDirectoryPicker.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/PluginTaskSettings.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/ClipboardSharedTaskPrompt.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/RecentMessageHistories.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SharedTaskAdmissionDialog.tsx, apps/mobile/src/session/SharedTaskScreen.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 | 242 | 83 || `mobile.remote-desktop` | mobile | 远程桌面 | app/devices/desktop/[deviceId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ClipboardSharedTaskPrompt, 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, ResidentHomeList, SharedTaskAdmissionDialog, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, 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/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/ClipboardSharedTaskPrompt.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/ResidentHomeList.tsx, apps/mobile/src/session/SharedTaskAdmissionDialog.tsx, apps/mobile/src/session/SharedTaskScreen.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 | 210 | 55 || `mobile.resources` | mobile | 远程资源列表与详情 | app/resources/[collectionId].tsx / app/resources/[collectionId]/[resourceId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, BotGroupAvatars, BotGroupList, CenteredScreen, ClipboardSharedTaskPrompt, CompanionListRow, CompanionPresenceRing, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, 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, ResidentHomeList, SessionRightSpinner, SharedTaskAdmissionDialog, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, TeammateGenerationLabel, TeammateList, ThemeProvider, WorkingStatusText, [collectionId], [resourceId], _layout, gestureHandler, 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/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/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/BotGroupAvatars.tsx, apps/mobile/src/session/BotGroupList.tsx, apps/mobile/src/session/ClipboardSharedTaskPrompt.tsx, apps/mobile/src/session/CompanionListRow.tsx, apps/mobile/src/session/CompanionPresenceRing.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/ResidentHomeList.tsx, apps/mobile/src/session/SessionRightSpinner.tsx, apps/mobile/src/session/SharedTaskAdmissionDialog.tsx, apps/mobile/src/session/SharedTaskScreen.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/TeammateGenerationLabel.tsx, apps/mobile/src/session/TeammateList.tsx, apps/mobile/src/session/WorkingStatusText.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 | 210 | 71 || `mobile.settings` | mobile | 设置(含调试与日志上传可见入口) | app/settings.tsx / app/settings/device-name.tsx / app/settings/voice-dictionary.tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ClipboardSharedTaskPrompt, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, 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, ResidentHomeList, SettingsGroupRows, SharedTaskAdmissionDialog, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, device-name, gestureHandler, listDisclosureTransition, peerFileTransport, settings, useLocale, voice-dictionary | apps/mobile/app/_layout.tsx, apps/mobile/app/settings.tsx, apps/mobile/app/settings/device-name.tsx, apps/mobile/app/settings/voice-dictionary.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/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/ClipboardSharedTaskPrompt.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/ResidentHomeList.tsx, apps/mobile/src/session/SettingsGroupRows.tsx, apps/mobile/src/session/SharedTaskAdmissionDialog.tsx, apps/mobile/src/session/SharedTaskScreen.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 | 210 | 63 |@@ -135,6 +136,7 @@| apps/mobile/app/files/[sessionId].tsx | RemoteFileBrowserScreen | `mobile.files` || apps/mobile/app/files/preview/[sessionId].tsx | RemoteFilePreviewScreen | `mobile.files` || apps/mobile/app/index.tsx | IndexScreen | `mobile.home` |+| apps/mobile/app/plugins.tsx | @/plugins/PluginsScreen | `mobile.plugins` || apps/mobile/app/resources/[collectionId]/[resourceId].tsx | RemoteResourceResolverScreen | `mobile.resources` || apps/mobile/app/resources/[collectionId].tsx | RemoteCollectionScreen | `mobile.resources` || apps/mobile/app/sessions/[sessionId].tsx | SessionScreen | `mobile.chat.session` |@@ -225,6 +227,7 @@ Mobile 已由 DS-7 纳入同一台账(2026-09-10 静态入口发现),保| `mobile.files` | kirozeng 协调 / Codex 发现维护;页面 owner 待认领 | legacy | — | DS-7 已发现入口;Mobile 独立阶段接管,未迁移 | 2026-09-17 复查入口变化和页面 owner;动态内容、平台实际呈现留 Mobile 独立阶段验证 || `mobile.home` | kirozeng 协调 / Codex 发现维护;页面 owner 待认领 | legacy | — | DS-7 已发现入口;Mobile 独立阶段接管,未迁移 | 2026-09-17 复查入口变化和页面 owner;动态内容、平台实际呈现留 Mobile 独立阶段验证 || `mobile.overlay.connection-startup` | kirozeng 协调 / Codex 发现维护;页面 owner 待认领 | legacy | — | DS-7 已发现入口;Mobile 独立阶段接管,未迁移 | 2026-09-17 复查入口变化和页面 owner;动态内容、平台实际呈现留 Mobile 独立阶段验证 |+| `mobile.plugins` | unassigned | legacy | — | DS-7 发现入口,Mobile 独立阶段接管;未迁移 | 保持现状;发现问题记下一动作,本张不修视觉 || `mobile.remote-desktop` | kirozeng 协调 / Codex 发现维护;页面 owner 待认领 | legacy | — | DS-7 已发现入口;Mobile 独立阶段接管,未迁移 | 2026-09-17 复查入口变化和页面 owner;动态内容、平台实际呈现留 Mobile 独立阶段验证 || `mobile.resources` | kirozeng 协调 / Codex 发现维护;页面 owner 待认领 | legacy | — | DS-7 已发现入口;Mobile 独立阶段接管,未迁移 | 2026-09-17 复查入口变化和页面 owner;动态内容、平台实际呈现留 Mobile 独立阶段验证 || `mobile.settings` | kirozeng 协调 / Codex 发现维护;页面 owner 待认领 | legacy | — | DS-7 已发现入口;Mobile 独立阶段接管,未迁移 | 2026-09-17 复查入口变化和页面 owner;动态内容、平台实际呈现留 Mobile 独立阶段验证 |diff --git a/docs/dev-rules/plugin-mobile-implementation.md b/docs/dev-rules/plugin-mobile-implementation.mdnew file mode 100644index 0000000000..156740d129--- /dev/null+++ b/docs/dev-rules/plugin-mobile-implementation.md@@ -0,0 +1,76 @@+# 移动插件接入++手机通过设备互联使用执行电脑上的已装插件。插件业务逻辑、Library 和任务仍在电脑上;+手机提供入口、隔离页面及原生交互,不复制插件安装或另造任务类型。++## 入口与页面++- 主菜单提供插件入口和聚合未读点;目录按电脑展示,支持搜索、最近使用、未读筛选、详情和启停。+ 宽屏目录与内容并列,样式使用 Light/Dark 语义 token,文案覆盖现有五种语言。+- manifest 的可选 `mobile` 包含 `channels`、`panel`、`mainView`、`settings`;路径只覆盖+ 已声明的原能力。未声明移动适配的插件仍可被发现和在任务中使用,旧桌面行为保留。+- 页面租约绑定账号、控制端连接、插件安装版本和页面实例。页面关闭或来源失效后,+ 旧响应不能修改状态;原生弹层覆盖页面时暂停页面业务操作。+- BroadcastChannel 仅桥接声明频道,每条 JSON 最多 48 KiB;Host 覆盖消息的 `mobilePageId`。+ 作者显式传递来源,不得保存“最近手机”全局值。未知写入回执按原 requestId 查询,不自动重发。+- 内部返回、动态标题、主题、前后台及隔离草稿由页面桥接支持。静态资源按文件身份读取,+ 整页最多 64 MiB;Library 分块固定版本,媒体按已有归属账本读取固定大小块。++## 原生交互与普通任务++- confirm 由手机原生确认,关闭、遮挡、过期或撤权均拒绝;notify 只发送给来源页面。+ badge 沿用 boolean + summary,未引入计数字段。只有实际展示 panel 才按观察版本清未读。+ 作者用 `cindyMobile.onUnread(version => …)` 捕获版本,读取并呈现内容后调用+ `cindyMobile.contentRendered(version)`;宿主校验当前可见页面与版本,下一帧提交回执。+ 页面加载和轮询本身不确认已读;读取失败不回报,前台恢复时重新呈现再回报。+- 任务卡从已保存且净化的 HTML 投影动作,手机不执行卡片脚本;提交复核卡片版本、归属和真实点击。+- 新建任务复用普通创建页面,选择已有任务复用原生选择器,仅预填使用文字,用户发送后执行。+ workspace 打开对应普通任务;任务能力批准和写权限仍沿用 Host 校验、确认与回滚链。+- `cindy.tasks` 与统一任务接口共用创建、继续、结果查询、模型目录和改模型能力。+ 任务设置复用 `pluginTaskPrefsStore` 和 `validatePluginTaskConfig`,保留旧偏好及私有工作目录。+- 目录由原生选择器确认;schedule 打开普通自动化草稿,支持每天、工作日、间隔和自定义 Cron,+ 使用统一模型选择器,只有用户保存才创建。模拟器入口复用已有电脑控制能力,不授予额外输入权限。+- 图片进入原生图片查看器;视频进入已有媒体播放器并提供原生分享。外部预览沿用 Host URL 白名单。+ 电脑 localhost 预览固定获批 origin,资源分块经设备互联交给现有本机预览服务器。+ 当前本机预览服务器仅支持 GET/HEAD,不支持 POST/WebSocket/HMR;不能宣称任意开发服务器完全可用。++## 配置与授权++手机原生表单负责密钥、设备码和可远程完成的浏览器授权;PKCE/电脑 loopback 场景明确返回电脑操作。+加密复用 v3 Host 授权协议,使用 X25519、Ed25519、HKDF 与 Expo AES。+执行电脑身份固定在 SecureStore,换钥拒绝;来源变化或未知提交结果不静默重试。+凭证不进入插件页面或普通桥接;表单关闭清空临时输入。++## 实现位置与作者约束++- `packages/device-link/src/pluginPages.ts`:远程资源和页面类型。+- `apps/desktop/src/main/cindy-brain/mobilePageService.ts`:页面租约、原生意图、来源校验与回执。+- `apps/desktop/src/main/cindy-brain/mobilePageAssets.ts`:包内资源;`mobilePreview.ts`:电脑预览。+- `apps/desktop/src/main/cindy-brain/runtime/mobilePageRelay.ts`:原逻辑页频道桥接。+- `apps/mobile/src/plugins/`:目录、页面、配置、任务设置和原生交互。+- `apps/desktop/src/main/cindy-brain/forge.ts`:插件作者公开契约。++修改 `pluginPageBootstrap.ts` 后运行 `node scripts/generate-mobile-plugin-bootstrap.mjs`,+检查时加 `--check`。预生成脚本避免依赖 Hermes 的函数源码序列化。+作者必须提供真正可触屏使用的布局及 Light/Dark,保存业务去重记录和草稿;添加声明不代表完成适配。+模块动态加载、键盘、返回和前后台行为需要在目标平台验证。++## 验证边界++直接相关用例覆盖页面/控制端隔离、确认与未读、资源替换、任务归属、模型配置、卡片动作、+原生授权密码学互通和身份固定,以及移动桥接脚本、预览查询和媒体临时文件回收。+浏览器模拟宿主、JSDOM、原生边界 mock 和局部类型检查均不能替代手机实机验收。+本次未启动 Desktop DEV、Metro 或原生构建;iOS、Android、iPad 的键盘、系统浏览器返回、+断线恢复及 Light/Dark 实机视觉仍待验证。未执行整仓测试和整包构建,完整门禁交 CI。++## 兼容、冷更与回退++现有插件不需要重装、重新批准或重配凭证;mobile 为可选扩展,新增远程集合由能力协商发现。+插件批准格式、安装布局、旧任务偏好文件和 Library 数据未迁移。插件基座改动合并前需白名单明确批准。++新增纯 JavaScript `@noble/[email protected]` 复用现有 Expo 随机数与 AES,未新增原生模块,+但依赖仍改变 runtime fingerprint,必须按冷更发布新安装包并由指定把关人明确批准。+iOS 指纹从 `d8cd3b87cb7dcf418004eeb36b0ff1b8f29a44c7` 变为+`25a5a753aaf7740670f9588e976b4770b0817999`;Android 从+`c2eb49bea3303f89edf8de95af3a0cf45179faca` 变为 `d1d89bd866a64c681f3ded59075536abccb84c9a`。+旧安装保持原能力,不向旧 runtime 投送本次 OTA。回退客户端代码即可撤销移动入口;不删除插件数据。diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.mdindex 33f91bd961..11e8deed1e 100644--- a/docs/dev-rules/plugin-security-and-authoring.md+++ b/docs/dev-rules/plugin-security-and-authoring.md@@ -619,6 +619,14 @@## 8. 远程与手机版+移动页面契约见 [移动插件接入](plugin-mobile-implementation.md)。可选 `mobile` 声明+只选择已有能力的页面入口,不改变旧插件批准、凭证或安装布局。逻辑仍由执行电脑运行。+Host 为页面消息附加 `mobilePageId`,原生弹窗、任务操作、目录选择和预览等必须保留+该来源;页面覆盖、关闭、账号/连接/安装代次改变后,旧响应不得继续写入或清除未读。+手机任务配置复用普通任务配置校验。密钥/连接表单走 Host 原生 v3 加密授权通道,+不得通过 WebView、BroadcastChannel 或通用插件 fetch 传递凭证。++插件能力可能运行在 SSH 远程工作区、设备互联远程控制或手机版控制端。新增或修改 IPCchannel 与推送事件时,若手机/远程控制场景需要用到,必须按`packages/device-link/src/allowlist.ts` 顶部注释的准入判据登记 invoke/push 白名单并同步diff --git a/docs/remote-plugin-oauth.md b/docs/remote-plugin-oauth.mdindex d636e13d8b..f33cc9bef5 100644--- a/docs/remote-plugin-oauth.md+++ b/docs/remote-plugin-oauth.md@@ -1,7 +1,7 @@# 远程插件授权与配置-本功能连接两台已登录同账号、已允许 Device Link 控制的 Desktop。执行任务的 Host-拥有插件及凭据,控制端 Desktop 提供浏览器和保密卡片。协议及实现正本为+本功能连接已登录同账号、已允许 Device Link 控制的客户端。执行任务的 Desktop Host+拥有插件及凭据,控制端 Desktop 或新版 Mobile 提供受信原生配置界面。协议及实现正本为`packages/device-link/src/plugin*.ts` 与 `apps/desktop/src/main/plugin-oauth/`。它不依赖 CIS、云实例配置、定制发行包或新的服务端接口。@@ -47,7 +47,7 @@ sequenceDiagram恶意 relay 同时替换描述符及握手。不得称为独立身份认证、双向设备证明或 CIS 验证。执行端对控制端的身份和准入仍依赖既有 Device Link 链路;持久 pin 保护控制端所认的执行设备,不把它解释成可抵御账号服务或 relay 冒充控制端的双向独立认证。-- 执行端使用独立用途的持久 Ed25519 密钥;控制端验签成功后才固定对端公钥。两端+- 执行端使用独立用途的持久 Ed25519 密钥;控制端验签成功后才固定对端公钥。Desktop 两端按 realm/membership/local device 分域,使用 Electron safeStorage 加密落盘,原子写入和跨进程锁;不复用通讯录密钥,不在启动/能力投影时访问钥匙串。- 文件在 `ownerScopedUserDataPath('plugin-oauth', <scope-sha256>.v1.enc)`,含本机签名@@ -179,9 +179,14 @@ gh-cli、oidc-token 或账号 vault 写入;临时 Node Secret 卡只允许其保持上游独立 RPC 行为,不自动弹卡或结束后台进程。已停止的调用不能迟到启用新授权。- 两端 Desktop 必须支持 v3。旧版仍可使用原本的远控及执行设备本地设置;新授权动作不走旧通道/明文降级,不会替用户清空已有凭据。-- Mobile 是目标电脑的遥控器:配置卡保留查看/取消,并提供进入目标电脑远程桌面的入口。- 用户在电脑端 UI 完成输入、浏览器登录和授权;回调、交换及凭据保存全部在电脑执行。- 手机不实现插件凭据表单、OAuth 回调或授权码转发。网站 Cookie/全量 vault 同步不在范围。+- 新版 Mobile 的原生配置表单经同一个 v3 签名握手与加密通道提交 API Key/PAT、连接地址与+ Token;支持由 Host 声明的设备码和浏览器确认页。目标、字段展示、当前账号、设备代次及+ 卡片动作在提交前复核,插件 WebView、普通频道和通用 invoke 不能收取这些输入。+ 手机使用 Expo SecureStore 固定执行电脑公钥,按 realm/membership/本手机/执行电脑分域;+ 安全存储失败拒绝,已登记身份换钥直接拒绝,不能通过卡片信任或替换新钥。+ PKCE 和 loopback 回调仍需电脑端入口;手机不能把电脑 localhost 当作手机地址。+ 旧手机继续查看/取消并通过电脑入口完成。网站 Cookie/全量 vault 同步不在范围。+ 新版路径尚须真实 iOS/Android 验收,单测不代表第三方实际授权成功。- Auth、relay、CIS、Model Access 不需要本功能的新服务接口或部署;双方客户端需升级。### 各端范围与后续门禁@@ -189,7 +194,7 @@ gh-cli、oidc-token 或账号 vault 写入;临时 Node Secret 卡只允许其| 场景 | 本 PR 的处理 || --- | --- || Desktop → Desktop Device Link | 已适配:新私有通道经同账号授权、卡片绑定及签名握手;原有 invoke/push 规则不放宽。 |-| Mobile → Desktop Device Link | 配置卡提供目标电脑远程桌面入口,保留状态与取消;手机仅通过既有远程画面与输入控制电脑。无手机授权桥接,不依赖新的 Google 移动客户端或手机回调;共享任务访客及终态卡片不提供远控入口。 |+| Mobile → Desktop Device Link | 原生表单和设备码/浏览器确认通过加密 v3 接入;电脑本地 OAuth 回调继续走电脑入口。共享任务访客不提供授权动作;旧端不降级到明文。真实手机授权尚未验收。 || SSH 工作区 | 本 PR 不新增 SSH 凭据转发或远端插件安装。SSH 的 Agent/workdir 仍经 maker-remote-ssh、cc-manager 与 remote-file-service;插件由提供 MCP 的 Desktop Host 管理,授权仅改变该 Host 的连接。SSH 主机没有本桥的 Desktop 身份、OS 密钥存储和 Device Link peer,不能把它当作另一个被控 Desktop,也不向其 HOME/workdir 复制本机凭据。原有远端文件、网络与 Forge 限制保留。 |故障范围:单卡片取消/超时只收口该事务;单 peer 失效只取消该 peer 的事务;账号退出diff --git a/packages/device-link/src/index.ts b/packages/device-link/src/index.tsindex 7378936994..4c5fe55299 100644--- a/packages/device-link/src/index.ts+++ b/packages/device-link/src/index.ts@@ -54,3 +54,4 @@ export * from "./pluginDeviceAuthorization.js";export * from "./pluginOauthAuthentication.js";export * from "./inputDelivery.js";export * from "./taskMigration.js";+export * from './pluginPages.js';diff --git a/packages/device-link/src/pluginOauthAuthentication.ts b/packages/device-link/src/pluginOauthAuthentication.tsindex ed12af8580..66d321a9c8 100644--- a/packages/device-link/src/pluginOauthAuthentication.ts+++ b/packages/device-link/src/pluginOauthAuthentication.ts@@ -127,3 +127,33 @@ export function parsePluginOauthHelloReply(throw new Error("OAUTH_BRIDGE_UNAVAILABLE");return v as unknown as PluginOauthHelloReply;}++/** Canonical signed transcript shared by both native controllers and the execution Host. */+export function pluginOauthTranscript(+ hello: PluginOauthHello,+ reply: Omit<PluginOauthHelloReply, "signature">,+ target: Pick<+ PluginOauthPeerIdentity,+ "realm" | "membershipId" | "deviceId" | "publicKey"+ >,+ peer: string,+): string {+ return JSON.stringify([+ "cindy-plugin-oauth-authentication-v3",+ target.realm,+ target.membershipId,+ target.deviceId,+ peer,+ target.publicKey,+ reply.bootId,+ hello.nonce,+ hello.publicKey,+ reply.publicKey,+ reply.id,+ reply.expiresAtMs,+ hello.action.requestId,+ hello.action.actionId,+ hello.action.expectedRevision,+ reply.ghostId,+ ]);+}diff --git a/packages/device-link/src/pluginPages.ts b/packages/device-link/src/pluginPages.tsnew file mode 100644index 0000000000..3204b822b5--- /dev/null+++ b/packages/device-link/src/pluginPages.ts@@ -0,0 +1,130 @@+/** Optional, versioned plugin-page projection. No host path or credential is a wire value. */+export const PLUGIN_COLLECTION = "plugins";+export const PLUGIN_PAGE_PRIMITIVE = "plugin-page";+export type PluginPageSurface = "panel" | "mainView" | "settings";+export interface PluginMobileDeclaration {+ channels: string[];+ panel?: string;+ mainView?: string;+ settings?: string;+}+/** Unknown/invalid extensions do not disable a legacy installation. They simply cannot open a mobile page. */+export function parsePluginMobileDeclaration(+ value: unknown,+): PluginMobileDeclaration | null {+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;+ const v = value as Record<string, unknown>;+ if (+ !Array.isArray(v.channels) ||+ v.channels.length > 16 ||+ !v.channels.every(+ (c) =>+ typeof c === "string" && /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(c),+ )+ )+ return null;+ const result: PluginMobileDeclaration = {+ channels: [...new Set(v.channels as string[])],+ };+ for (const key of ["panel", "mainView", "settings"] as const) {+ if (v[key] === undefined) continue;+ if (+ typeof v[key] !== "string" ||+ !/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*(\/[a-zA-Z0-9_][a-zA-Z0-9_.-]*)*\.html$/.test(+ v[key] as string,+ )+ )+ return null;+ result[key] = v[key] as string;+ }+ return result;+}+export interface PluginPageAsset {+ mime: string;+ base64: string;+}+export interface PluginPageFetchResult extends PluginPageAsset {+ status: number;+ nextOffset?: number;+ revision?: string;+}+export interface PluginPageFile {+ path: string;+ mime: string;+ size: number;+}+export interface PluginPageDocument {+ pageId: string;+ pluginId: string;+ title: string;+ surface: PluginPageSurface;+ entry: string;+ channels: string[];+ files: PluginPageFile[];+ unreadAt?: number;+}+export interface PluginPageEvent {+ sequence: number;+ channel: string;+ data: unknown;+}+export interface PluginPageConfirm {+ id: string;+ pluginId: string;+ title: string;+ body: string;+ confirmText: string | null;+ cancelText: string | null;+ danger: boolean;+ expiresAt: number;+}+export interface PluginPagePoll {+ events: PluginPageEvent[];+ confirms: PluginPageConfirm[];+ notifications: Array<{ id: string; text: string }>;+ unreadAt?: number;+ directories?: PluginDirectoryRequest[];+ intents?: PluginNativeIntent[];+}+export type PluginNativeIntent = {+ id: string;+ pluginId: string;+ ghostName: string;+} & (+ | { kind: "task"; taskId: string }+ | { kind: "preview"; url: string }+ | { kind: "schedule"; name: string; prompt: string; intervalMs?: number }+ | { kind: "simulator" }+ | { kind: "media"; path: string; mediaKind: "image" | "video" }+);+/** Trusted native picker presentation, never forwarded into an author page. */+export interface PluginDirectoryRequest {+ id: string;+ pluginId: string;+ ghostName: string;+ purpose: string | null;+ expiresAt: number;+}+// Pages preload code/assets; large user media remains streamed through owned media/library resources.+export const PLUGIN_PAGE_MAX_BUNDLE_BYTES = 64 * 1024 * 1024;+export const PLUGIN_PAGE_MAX_MESSAGE_BYTES = 48 * 1024;+export function isPluginPageSurface(+ value: unknown,+): value is PluginPageSurface {+ return value === "panel" || value === "mainView" || value === "settings";+}++/** Trusted native settings; no directory, credentials or provider execution routing on the wire. */+export interface PluginTaskPreferences {+ revision: string;+ config: {+ agentKind?: "cc" | "codex" | "pi";+ model?: string;+ providerId?: string;+ effort?: string;+ fastMode?: boolean;+ permissionMode?: string;+ };+ permissionModes: string[];+ defaultPermissionMode: string;+}diff --git a/packages/device-link/src/remoteResources.ts b/packages/device-link/src/remoteResources.tsindex f2a8fdc9eb..4d5ecc0327 100644--- a/packages/device-link/src/remoteResources.ts+++ b/packages/device-link/src/remoteResources.ts@@ -212,7 +212,9 @@ export type RemoteActionEffect =| { kind: 'navigate'; target: RemoteLinkTarget }| { kind: 'toast'; message: RemoteText };+/** Optional opaque reply for an explicitly negotiated resource primitive. */export interface RemoteActionInvokeResponse {+ result?: unknown;effects: RemoteActionEffect[];}diff --git a/packages/plugin-protocol/src/__tests__/manifest.forward-compat.test.ts b/packages/plugin-protocol/src/__tests__/manifest.forward-compat.test.tsindex 762fddf2f8..22d6dd80f0 100644--- a/packages/plugin-protocol/src/__tests__/manifest.forward-compat.test.ts+++ b/packages/plugin-protocol/src/__tests__/manifest.forward-compat.test.ts@@ -9,6 +9,7 @@ const extension = { mode: 'future', options: [1, null, { enabled: true }] };describe('declaration forward compatibility is not Host authorization', () => {it.each([+ ['mobile', { channels: ['practice-ui'], panel: 'mobile/panel.html' }],['mainView', { html: 'view.html' }],['panel', { html: 'panel.html' }],['card', {}],diff --git a/packages/plugin-protocol/src/manifest.ts b/packages/plugin-protocol/src/manifest.tsindex 832d48a4db..22b3191d8e 100644--- a/packages/plugin-protocol/src/manifest.ts+++ b/packages/plugin-protocol/src/manifest.ts@@ -918,6 +918,8 @@ export interface GhostManifest {* `/kv`;其它自定义参数持久化走同源 `fetch('/kv')`。*/settingsHtml?: string;+ /** Optional mobile page projection; unknown/invalid declarations leave desktop behavior unchanged. */+ mobile?: { channels: string[]; panel?: string; mainView?: string; settings?: string };/*** 自定义设置区固定高度(px,可选;160–800)。缺省 = 宿主量 guest 内容* 高度自适应(同区间收口);声明本字段 = 固定高度(内容动态增减的设置@@ -3734,6 +3736,7 @@ export function validateGhostManifest(value: unknown): ManifestValidation {: {}),...(node !== undefined ? { node } : {}),...(raw.settingsHtml !== undefined ? { settingsHtml: raw.settingsHtml as string } : {}),+ ...(raw.mobile !== undefined ? { mobile: raw.mobile as GhostManifest['mobile'] } : {}),...(raw.settingsHeight !== undefined ? { settingsHeight: raw.settingsHeight as number } : {}),...(prepared.schemaVersion === 2 ? { slots } : {}),...(card !== undefineddiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex f3020555c4..9a8e8506ad 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -629,6 +629,9 @@ importers:'@legendapp/list':specifier: ^3.3.3version: 3.3.3([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])+ '@noble/curves':+ specifier: 1.9.7+ version: 1.9.7'@noble/hashes':specifier: ^1.8.0version: 1.8.0@@ -3708,6 +3711,10 @@ packages:resolution: {integrity: sha512-dJst7XDaCsXjz9y8UYQhg120cloaKDSH+fS96M87HutzO/RdK9E1JNKq9JGNYWRCiYOlDRX0rUqJnL0rLDsOCw==}engines: {node: '>= 10'}+ '@noble/[email protected]':+ resolution: {integrity: sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==}+ engines: {node: ^14.21.3 || >=16}+'@noble/[email protected]':resolution: {integrity: sha512-V1JJ1WTRUqHHrOSh597hURcMqVKVGL/ea3kv0gSnEdsEZ0/+VyPghM1lMNGc00z7CIQorSvbKpuJkxvuHbvdbg==}engines: {node: '>= 16'}@@ -14151,6 +14158,10 @@ snapshots:- '@emnapi/core'- '@emnapi/runtime'+ '@noble/[email protected]':+ dependencies:+ '@noble/hashes': 1.8.0+'@noble/[email protected]': {}'@noble/[email protected]': {}diff --git a/scripts/__tests__/design-inventory.test.mjs b/scripts/__tests__/design-inventory.test.mjsindex e85a8f29dd..ceda8d9113 100644--- a/scripts/__tests__/design-inventory.test.mjs+++ b/scripts/__tests__/design-inventory.test.mjs@@ -1277,6 +1277,7 @@ test('Mobile actual route families and shared visible consumers are discoverable['mobile.chat.session', ['MessageRenderer.tsx', 'CompanionMessageCard.tsx', 'AuthorizationMessageCard.tsx', 'FailedScheduleNotice.tsx']],['mobile.remote-desktop', ['RemoteDesktopScreen.tsx', 'viewerHtml.ts']],['mobile.settings', ['settings.tsx']],+ ['mobile.plugins', ['PluginsScreen.tsx', 'PluginPage.tsx', 'PluginTaskSettings.tsx', 'PluginNativeIntent.tsx']],['mobile.overlay.connection-startup', ['ConnectionNoticeOverlay.tsx', 'ConnectionBanner.tsx']],]) {const surface = surfaces.find(s=>s.id===id);diff --git a/scripts/generate-mobile-plugin-bootstrap.mjs b/scripts/generate-mobile-plugin-bootstrap.mjsnew file mode 100644index 0000000000..b07b8276d2--- /dev/null+++ b/scripts/generate-mobile-plugin-bootstrap.mjs@@ -0,0 +1,17 @@+/** Generate source text for the isolated WebView. Hermes does not retain Function#toString source. */+import fs from 'node:fs';+import ts from 'typescript';+import { fileURLToPath } from 'node:url';+const source = fileURLToPath(new URL('../apps/mobile/src/plugins/pluginPageBootstrap.ts', import.meta.url));+const target = fileURLToPath(new URL('../apps/mobile/src/plugins/pluginPageBootstrap.generated.ts', import.meta.url));+const compiled = ts.transpileModule(fs.readFileSync(source, 'utf8'), {+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext },+}).outputText.replace('export function bootstrap(', 'function bootstrap(').replace(/export \{\};?\s*$/, '');+const output = '// Generated by scripts/generate-mobile-plugin-bootstrap.mjs. Edit pluginPageBootstrap.ts.\n'+ + 'export const PLUGIN_PAGE_BOOTSTRAP = ' + JSON.stringify(compiled) + ';\n';+if (process.argv.includes('--check')) {+ if (!fs.existsSync(target) || fs.readFileSync(target, 'utf8') !== output) {+ process.stderr.write('Mobile plugin bootstrap is stale; run node scripts/generate-mobile-plugin-bootstrap.mjs\n');+ process.exitCode = 1;+ }+} else fs.writeFileSync(target, output);diff --git a/scripts/shared/design-inventory.mjs b/scripts/shared/design-inventory.mjsindex 730b7a6dd6..de7967c809 100644--- a/scripts/shared/design-inventory.mjs+++ b/scripts/shared/design-inventory.mjs@@ -1402,6 +1402,7 @@ export function mobileCatalogSurfaces() {['device-management', '设备管理', ['devices/manage.tsx', 'devices/manage/[deviceId].tsx']],['remote-desktop', '远程桌面', ['devices/desktop/[deviceId].tsx']],['resources', '远程资源列表与详情', ['resources/[collectionId].tsx', 'resources/[collectionId]/[resourceId].tsx']],+ ['plugins', '插件目录、页面与原生交互', ['plugins.tsx']],['companions.direct', '伙伴私聊回看', ['companions/direct/[threadId].tsx']],['companions.groups', '伙伴群聊与分工', ['companions/groups/[groupId].tsx']],['chat.session', '任务内容与输入', ['sessions/[sessionId].tsx']],