Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 重整已装插件页面与详情布局 (#5730)
nanacof3c263a36651
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostRecommendations.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostRecommendations.test.tsindex 8302ab9978..cf42ea816d 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostRecommendations.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostRecommendations.test.ts@@ -26,6 +26,7 @@ import {readGhostRecommendationEntries,replaceGhostRecommendations,markGhostRecommendationInstalled,+ recordGhostAdded,consumeGhostRecommendationPriority,forgetGhostRecommendations,} from '../ghostRecommendationStore';@@ -45,7 +46,7 @@ describe('plugin recommendation state', () => {const installedAt = readGhostRecommendationEntries()[0].installedAt;expect(replaceGhostRecommendations('example', [item])).toEqual({ ok: true });expect(replaceGhostRecommendations('example', [])).toEqual({ ok: true });- expect(readGhostRecommendationEntries()[0]).toEqual({ id: 'example', items: [], installedAt });+ expect(readGhostRecommendationEntries()[0]).toEqual({ id: 'example', items: [], installedAt, addedAt: installedAt });expect(buildGhostRecommendationSnapshot(state.owner, [ghost], readGhostRecommendationEntries(), []).sources[0].items,@@ -118,3 +119,24 @@ describe('plugin recommendation state', () => {},);});++it('retains addition chronology when priority is consumed or an install is recorded again', () => {+ vi.spyOn(Date, 'now').mockReturnValue(1000);+ recordGhostAdded('example');+ markGhostRecommendationInstalled('example');+ consumeGhostRecommendationPriority('example');+ expect(readGhostRecommendationEntries()[0].addedAt).toBe(1000);+ vi.mocked(Date.now).mockReturnValue(2000);+ recordGhostAdded('example');+ expect(readGhostRecommendationEntries()[0].addedAt).toBe(1000);+ forgetGhostRecommendations('example');+ recordGhostAdded('example');+ expect(readGhostRecommendationEntries()[0].addedAt).toBe(2000);+ vi.restoreAllMocks();+});+it('preserves an existing real install timestamp without fabricating legacy chronology', () => {+ state.buckets.set('owner-a', { entries: [{ id: 'example', installedAt: 1234 }, { id: 'older' }] });+ consumeGhostRecommendationPriority('example');+ expect(readGhostRecommendationEntries().find(item => item.id === 'example')?.addedAt).toBe(1234);+ expect(readGhostRecommendationEntries().find(item => item.id === 'older')?.addedAt).toBeUndefined();+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/mobilePageService.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/mobilePageService.test.tsindex 4d74022eb8..f68aab0ede 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/mobilePageService.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/mobilePageService.test.ts@@ -1,8 +1,14 @@import { describe, expect, it, vi } from 'vitest';import { MobilePluginPages } from '../mobilePageService.js';import type { InstalledGhost } from '../../../shared/ghost.js';+import { toGhostPluginDetail } from '../../../renderer/features/plugin/lib/ghostPluginViewModel.js';-function setup() {+function setup(+ projection: Pick<+ ConstructorParameters<typeof MobilePluginPages>[0],+ 'setupAssessment' | 'runtimeState' | 'listOrder'+ > = {},+) {let owner = 'a',now = 1_000,revision = 'r1';@@ -15,6 +21,7 @@ function setup() {mobile: { channels: ['practice-ui'] },},enabled: true,+ approval: { state: 'approved', revision: 'r1' },} as InstalledGhost;const clearUnread = vi.fn(),post = vi.fn(),@@ -26,6 +33,7 @@ function setup() {let peerGeneration = 0;let unreadAt = 42;const service = new MobilePluginPages({+ ...projection,captureController: () => {const captured = peerGeneration;return () => captured === peerGeneration;@@ -97,6 +105,36 @@ function setup() {};}describe('mobile plugin pages', () => {+ it('adds usage facts to the existing capabilities block and preserves unknown setup on a failed read', async () => {+ const h = setup({+ setupAssessment: () => {+ throw new Error('READ_FAILED');+ },+ runtimeState: () => 'crashed',+ });+ const detail = await h.provider.get!(+ { controllerDeviceId: 'phone-a' },+ {+ ref: { collectionId: 'plugins', kind: 'plugin', id: 'practice' },+ client: { protocolVersion: 1, primitives: ['plugin-capabilities'] },+ },+ );+ expect(detail.blocks?.find((block) => block.id === 'capabilities')?.data).toMatchObject({+ tasks: false,+ mobile: true,+ usage: { taskUsable: false, runtimeIssue: 'crashed', setup: { state: 'unknown' } },+ });+ h.ghost.enabled = false;+ h.ghost.approval = { state: 'invalid' };+ const list = await h.provider.list(+ { controllerDeviceId: 'phone-a' },+ {+ collectionId: 'plugins',+ client: { protocolVersion: 1, primitives: [] },+ },+ );+ expect(list.items[0].actions?.find((action) => action.id === 'enable')?.disabled).toBe(true);+ });it('keeps a covered native preview readable but rejects source writes, unread consumption and another controller', async () => {const h = setup(),page = await h.open();@@ -271,15 +309,22 @@ describe('mobile plugin pages', () => {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();+ 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();+ 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('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);@@ -390,3 +435,67 @@ describe('native remote plugin directory consent', () => {expect(await next).toBeNull();});});++it('projects optional Host ordering facts without changing legacy lists on metadata failure', async () => {+ const h = setup({ listOrder: () => new Map([['practice', { addedAt: 1234, recentIndex: 0 }]]) });+ const request = { collectionId: 'plugins', client: { protocolVersion: 1, primitives: [] } };+ const result = await h.provider.list({ controllerDeviceId: 'phone-a' }, request);+ expect(result.items[0].pluginOrder).toEqual({ addedAt: 1234, recentIndex: 0 });+ const broken = setup({ listOrder: () => { throw new Error('READ_FAILED'); } });+ expect((await broken.provider.list({ controllerDeviceId: 'phone-a' }, request)).items[0].pluginOrder).toBeUndefined();+});+++it('projects PC permission facts in the phone locale, excludes tools and keeps OAuth scopes', async () => {+ const h = setup();+ h.ghost.manifest.tools = [{name: 'calendar_events', description: 'Read events', parameters: {type: 'object'}}];+ h.ghost.manifest.network = {+ hosts: ['calendar.example'],+ secrets: [{key: 'account', label: 'Calendar account', source: 'oauth', inject: {header: 'Authorization', format: 'Bearer {value}'}, oauth: {+ clientId: 'public-client-id', authorizeUrl: 'https://accounts.example/authorize',+ tokenUrl: 'https://accounts.example/token', scopes: ['calendar.read'],+ }}],+ };+ const detail = await h.provider.get!({controllerDeviceId: 'phone-a'}, {+ ref: {collectionId: 'plugins', kind: 'plugin', id: 'practice'},+ client: {protocolVersion: 1, primitives: ['plugin-capabilities'], locale: 'zh-CN'},+ });+ const facts = detail.blocks?.find(block => block.id === 'capabilities')?.data as {tools: unknown[]; permissions: Array<{title: string; description: string}>};+ expect(facts.tools).toEqual([{name: 'calendar_events', description: 'Read events'}]);+ expect(facts.permissions.some(item => item.title.includes('calendar.example'))).toBe(true);+ expect(facts.permissions.some(item => item.description.includes('calendar.read'))).toBe(true);+ expect(JSON.stringify(facts.permissions)).not.toContain('calendar_events');+ expect(JSON.stringify(facts.permissions)).not.toContain('public-client-id');+ expect(JSON.stringify(facts.permissions)).not.toContain('settings.ghosts.perm');+ expect(JSON.stringify(facts.permissions)).not.toContain('{{');+ expect(facts.permissions.some(item => /[\u4e00-\u9fff]/.test(item.title))).toBe(true);+});+++it('projects the same installed Details as PC, with factual unsigned trust and no invented panel status', async () => {+ const h = setup();+ h.ghost.manifest.author = 'Cindy';+ h.ghost.manifest.version = '1.3.13';+ h.ghost.manifest.settingsHtml = 'settings.html';+ h.ghost.dir = '/plugin-install/practice';+ delete h.ghost.manifest.panel;+ const read = async () => {+ const detail = await h.provider.get!({controllerDeviceId: 'phone-a'}, {+ ref: {collectionId: 'plugins', kind: 'plugin', id: 'practice'},+ client: {protocolVersion: 1, primitives: ['plugin-capabilities'], locale: 'en'},+ });+ return (detail.blocks?.find(block => block.id === 'capabilities')?.data as {details: Array<{key: string; title: string; value: string}>}).details;+ };+ const pc = toGhostPluginDetail(h.ghost);+ const facts = await read();+ const values = Object.fromEntries(facts.map(fact => [fact.key, fact.value]));+ expect(values).toMatchObject({version: 'v' + pc.version, author: pc.author, identifier: pc.id, location: pc.installDir, trust: 'Unverified / unsigned', panel: 'This plugin has no panel'});+ expect(facts.map(fact => fact.title)).toEqual(['Version', 'Author', 'Source & signature', 'Identifier', 'Contains', 'Panel', 'Install location']);+ expect(values.contents).toBe('Custom settings UI · Executable code');+ h.ghost.trust = {level: 'unverified', publisherSigned: true, publisherVerified: false, reviewed: false, publisherName: 'Independent publisher', publisherKeyId: 'not-a-display-field'};+ const signed = await read();+ expect(signed.find(fact => fact.key === 'trust')?.value).toBe('Signed, but publisher identity is unverified: Independent publisher');+ expect(JSON.stringify(signed)).not.toContain('not-a-display-field');+ h.ghost.manifest.panel = {html: 'panel.html', position: 'tab'};+ expect((await read()).find(fact => fact.key === 'panel')?.value).toBe('Panel');+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/mobilePluginConfiguration.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/mobilePluginConfiguration.test.tsnew file mode 100644index 0000000000..acb1154b0b--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/mobilePluginConfiguration.test.ts@@ -0,0 +1,177 @@+import { expect, it, vi } from 'vitest';+import { parsePluginConfigurationSummary, parsePluginUsageSummary } from '@cindy/device-link';+import type { GhostManifest, GhostSetupAssessment } from '../../../shared/ghost.js';+import { mobilePluginConfiguration } from '../mobilePluginConfiguration.js';+import { mobilePluginUsage } from '../mobilePluginUsage.js';+import type { GhostSetupProbes } from '../ghostSetupStatus.js';+const manifest = {+ id: 'demo-config',+ name: 'Demo config',+ version: '1',+ settingsHtml: 'settings.html',+ network: {+ secrets: [+ {+ key: 'api_key',+ label: 'Service API key',+ hint: 'From the service console',+ inject: { header: 'Authorization', template: 'Bearer {value}' },+ },+ {+ key: 'account',+ label: 'Calendar account',+ source: 'oauth',+ oauth: {},+ inject: { header: 'Authorization', template: 'Bearer {value}' },+ },+ ],+ connections: [{ key: 'instances', label: 'GitLab instances' }],+ },+ setup: { requires: [] },+} as unknown as GhostManifest;+const probes = (): GhostSetupProbes => ({+ secretSaved: () => true,+ oauthStatus: () => ({ clientConfigured: true, connected: 2, expired: 1 }),+ connectionCount: () => 2,+ kvValue: () => undefined,+});+it('includes optional declarations omitted from the use gate and only projects status/counts', () => {+ const value = mobilePluginConfiguration(manifest, probes());+ expect(value.items).toEqual([+ {+ id: 'secret:api_key',+ label: 'Service API key',+ hint: 'From the service console',+ kind: 'secret',+ state: 'configured',+ },+ {+ id: 'secret:account',+ label: 'Calendar account',+ kind: 'oauth',+ state: 'configured',+ count: 2,+ expiredCount: 1,+ },+ {+ id: 'connection:instances',+ label: 'GitLab instances',+ kind: 'connection',+ state: 'configured',+ count: 2,+ },+ ]);+ expect(value.alternatives).toEqual([]);+ expect(parsePluginConfigurationSummary(value)).toEqual(value);+ expect(JSON.stringify(value)).not.toContain('Bearer');+});+it('reports individual missing/expired/unknown facts without fabricating configured status', () => {+ expect(+ mobilePluginConfiguration(manifest, {+ ...probes(),+ secretSaved: () => false,+ oauthStatus: () => ({ clientConfigured: true, connected: 0, expired: 1 }),+ connectionCount: () => 0,+ }).items.map((item) => item.state),+ ).toEqual(['missing', 'expired', 'missing']);+ const throwing = () => {+ throw new Error('read failed');+ };+ expect(+ mobilePluginConfiguration(manifest, {+ secretSaved: throwing,+ oauthStatus: throwing,+ connectionCount: throwing,+ kvValue: throwing,+ }).items.map((item) => item.state),+ ).toEqual(['unknown', 'unknown', 'unknown']);+ expect(mobilePluginConfiguration(manifest).items.map((item) => item.state)).toEqual([+ 'unknown',+ 'unknown',+ 'unknown',+ ]);+});+it('does not probe derived identity as a user-entered key', () => {+ const p = probes(),+ secretSaved = vi.fn(p.secretSaved);+ const value = mobilePluginConfiguration(+ {+ ...manifest,+ network: { hosts: [], secrets: [{ ...manifest.network!.secrets![0], source: 'oidc-token' }] },+ },+ { ...p, secretSaved },+ );+ expect(value.items[0]).toMatchObject({ kind: 'managed', state: 'managed' });+ expect(secretSaved).not.toHaveBeenCalled();+});+it('preserves any-of relationships and false/zero parameter existence without exporting values', () => {+ const m = {+ ...manifest,+ setup: {+ requires: [+ {+ anyOf: [+ { kind: 'secret' as const, key: 'api_key' },+ { kind: 'secret' as const, key: 'account' },+ ],+ },+ { anyOf: [{ kind: 'kv' as const, key: 'notify', label: 'Notifications' }] },+ { anyOf: [{ kind: 'kv' as const, key: 'limit', label: 'Limit' }] },+ ],+ },+ };+ const assessment = {+ state: 'ready',+ revision: 1,+ groups: [+ {+ id: 'either',+ mode: 'any_of',+ items: [+ {+ ref: 'secret:api_key',+ kind: 'secret',+ label: 'API key',+ state: 'satisfied',+ actions: [],+ },+ { ref: 'secret:account', kind: 'oauth', label: 'Account', state: 'missing', actions: [] },+ ],+ },+ ],+ } as GhostSetupAssessment;+ const value = mobilePluginConfiguration(+ m,+ { ...probes(), kvValue: (key) => (key === 'notify' ? false : 0) },+ assessment,+ );+ expect(value.alternatives).toEqual([['secret:api_key', 'secret:account']]);+ expect(value.items.filter((item) => item.kind === 'parameter')).toEqual([+ { id: 'kv:notify', kind: 'parameter', label: 'Notifications', state: 'configured' },+ { id: 'kv:limit', kind: 'parameter', label: 'Limit', state: 'configured' },+ ]);+ expect(value.items.every((item) => !('value' in item))).toBe(true);+});+it('validates the additive config summary without copying arbitrary remote fields', () => {+ const value = mobilePluginConfiguration(manifest, probes());+ expect(+ parsePluginConfigurationSummary({+ ...value,+ items: [{ ...value.items[0], value: 'must-not-copy' }],+ }),+ ).toEqual({ items: [value.items[0]], alternatives: [] });+ expect(+ parsePluginConfigurationSummary({ ...value, items: [{ ...value.items[0], count: -1 }] }),+ ).toBeNull();+ expect(+ parsePluginConfigurationSummary({ ...value, alternatives: [['secret:api_key', 'unknown']] }),+ ).toBeNull();+ const usage = mobilePluginUsage(+ { manifest, approval: { state: 'approved' } } as any,+ undefined,+ undefined,+ value,+ );+ expect(parsePluginUsageSummary(usage)?.configuration).toEqual(value);+ expect(parsePluginUsageSummary({ ...usage, configuration: { items: 'bad' } })).toBeNull();+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/mobilePluginUsage.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/mobilePluginUsage.test.tsnew file mode 100644index 0000000000..62e3380bd8--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/mobilePluginUsage.test.ts@@ -0,0 +1,124 @@+import { expect, it } from 'vitest';+import { parsePluginUsageSummary } from '@cindy/device-link';+import { mobilePluginUsage } from '../mobilePluginUsage.js';+import type { GhostSetupAssessment, InstalledGhost } from '../../../shared/ghost.js';+const ghost = {+ manifest: {+ id: 'demo',+ name: 'Demo',+ version: '1',+ tools: [{ name: 'lookup', description: 'Find things' }],+ settingsHtml: 'settings.html',+ },+ enabled: true,+ approval: { state: 'approved', revision: '1' },+} as InstalledGhost;+it('projects only setup status labels, with any-of alternatives correctly satisfied', () => {+ const assessment: GhostSetupAssessment = {+ state: 'required',+ revision: 1,+ groups: [+ {+ id: 'optional',+ mode: 'any_of',+ items: [+ {+ ref: 'secret:key',+ kind: 'secret',+ label: 'Unneeded key',+ state: 'missing',+ actions: [],+ },+ {+ ref: 'secret:oauth',+ kind: 'oauth',+ label: 'Connected account',+ state: 'satisfied',+ actions: [],+ },+ ],+ },+ {+ id: 'needed',+ mode: 'any_of',+ items: [+ {+ ref: 'secret:other',+ kind: 'oauth',+ label: 'Work account',+ state: 'expired',+ actions: [],+ },+ ],+ },+ ],+ };+ const projected = mobilePluginUsage(ghost, assessment, 'off');+ expect(projected).toMatchObject({+ taskUsable: true,+ hasSettings: true,+ setup: { state: 'required', missing: [], expired: ['Work account'] },+ });+ expect(projected.runtimeIssue).toBeUndefined();+ expect(JSON.stringify(projected)).not.toContain('secret:');+ expect(parsePluginUsageSummary(projected)).toEqual(projected);+});+it('distinguishes approval, retirement, runtime faults, and unavailable assessment', () => {+ const projected = mobilePluginUsage(+ {+ ...ghost,+ approval: { state: 'invalid' },+ retirement: { id: 'old', eligible: true, unread: false },+ },+ undefined,+ 'fused',+ );+ expect(projected).toMatchObject({+ approvalRequired: true,+ retired: true,+ runtimeIssue: 'fused',+ setup: { state: 'unknown' },+ });+ expect(+ mobilePluginUsage({+ ...ghost,+ manifest: {+ ...ghost.manifest,+ tools: [],+ command: undefined,+ id: 'page',+ name: 'Page',+ version: '1',+ panel: { html: 'panel.html' },+ },+ }).taskUsable,+ ).toBe(false);+});+it('rejects malformed status data rather than trusting remote booleans or unbounded labels', () => {+ const valid = mobilePluginUsage(ghost);+ expect(parsePluginUsageSummary({ ...valid, taskUsable: 'yes' })).toBeNull();+ expect(+ parsePluginUsageSummary({+ ...valid,+ setup: { state: 'ready', missing: ['x'.repeat(161)], expired: [] },+ }),+ ).toBeNull();+ expect(parsePluginUsageSummary({ ...valid, runtimeIssue: 'running' })).toBeNull();+});+it('keeps unmet alternative groups intact for minimal settings copy', () => {+ const projected = mobilePluginUsage(ghost, {+ state: 'required',+ revision: 2,+ groups: [+ {+ id: 'either',+ mode: 'any_of',+ items: [+ { ref: 'secret:key', label: 'API key', kind: 'secret', state: 'missing', actions: [] },+ { ref: 'secret:oauth', label: 'Account', kind: 'oauth', state: 'expired', actions: [] },+ ],+ },+ ],+ });+ expect(projected.setup.groups).toEqual([{ missing: ['API key'], expired: ['Account'] }]);+});diff --git a/apps/desktop/src/main/cindy-brain/ghostRecommendationStore.ts b/apps/desktop/src/main/cindy-brain/ghostRecommendationStore.tsindex 99db76e364..75004f2078 100644--- a/apps/desktop/src/main/cindy-brain/ghostRecommendationStore.ts+++ b/apps/desktop/src/main/cindy-brain/ghostRecommendationStore.ts@@ -7,6 +7,8 @@ interface Entry {id: string;items?: GhostRecommendation[];installedAt?: number;+ /** Durable successful first-install time; independent of consumed recommendation priority. */+ addedAt?: number;}interface Shape {entries: Entry[];@@ -41,6 +43,9 @@ export function readGhostRecommendationEntries(): Entry[] {...(typeof entry.installedAt === 'number' && Number.isFinite(entry.installedAt)? { installedAt: entry.installedAt }: {}),+ ...(typeof (entry.addedAt ?? entry.installedAt) === 'number' && Number.isFinite(entry.addedAt ?? entry.installedAt)+ ? { addedAt: entry.addedAt ?? entry.installedAt }+ : {}),},];});@@ -70,7 +75,15 @@ export function replaceGhostRecommendations(/** Explicit first installs only. Updates/default installs must not call this. */export function markGhostRecommendationInstalled(id: string): void {- update(id, { installedAt: Date.now() });+ const now = Date.now();+ const existing = readGhostRecommendationEntries().find(entry => entry.id === id);+ update(id, { installedAt: now, addedAt: existing?.addedAt ?? now });+}++/** New installation only. Updates never overwrite chronology or grant recommendation priority. */+export function recordGhostAdded(id: string): void {+ const existing = readGhostRecommendationEntries().find(entry => entry.id === id);+ if (existing?.addedAt === undefined) update(id, { addedAt: Date.now() });}export function consumeGhostRecommendationPriority(id: string): void {diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 79826b290f..67a6a38652 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -88,6 +88,7 @@ import {readGhostRecommendationEntries,replaceGhostRecommendations,markGhostRecommendationInstalled,+ recordGhostAdded,consumeGhostRecommendationPriority,forgetGhostRecommendations,} from './ghostRecommendationStore.js';@@ -208,7 +209,9 @@ import {evaluateGhostSetupAssessment,handleGhostSetupStatusRequest,parseOauthConnectSecretKey,+ type GhostSetupProbes,} from './ghostSetupStatus.js';+import { mobilePluginConfiguration } from './mobilePluginConfiguration.js';import { getGhostSetupChangeBus } from './ghostSetupChangeBus.js';import { GhostSetupManifestTracker } from './ghostSetupManifestTracker.js';import {@@ -5069,18 +5072,12 @@ function getGhostOauthReauthSuggest(* omit setup; ghost_call preflight is strict, so storage or manifest drift* errors block dispatch.*/-export function getGhostSetupAssessment(ghostId: string): GhostSetupAssessment {- const ghost = findAvailableGhost(ghostId);- if (!ghost || !ghostSetupKvStore) {- throw new Error(`ghost setup unavailable: ${ghostId}`);- }- const runtimeManifest = withRuntimeFiloGoogleClient(ghost.manifest);+function getGhostSetupProbes(ghostId: string, runtimeManifest: GhostManifest): GhostSetupProbes {+ if (!ghostSetupKvStore) throw new Error(`ghost setup unavailable: ${ghostId}`);const oauthManager = getGhostOauthAccountManager();const connectionManager = getGhostConnectionManager();let kvSnapshot: Record<string, unknown> | null = null;- const assessment = evaluateGhostSetupAssessment(- runtimeManifest,- {+ return {secretSaved: (key) => ghostSecretSaved(ghostId, key),oauthStatus: (key) => {const decl = runtimeManifest.network?.secrets?.find((secret) => secret.key === key)?.oauth;@@ -5096,7 +5093,18 @@ export function getGhostSetupAssessment(ghostId: string): GhostSetupAssessment {if (kvSnapshot === null) kvSnapshot = ghostSetupKvStore?.readStrict(ghostId) ?? {};return kvSnapshot[key];},- },+ };+}++export function getGhostSetupAssessment(ghostId: string): GhostSetupAssessment {+ const ghost = findAvailableGhost(ghostId);+ if (!ghost || !ghostSetupKvStore) {+ throw new Error(`ghost setup unavailable: ${ghostId}`);+ }+ const runtimeManifest = withRuntimeFiloGoogleClient(ghost.manifest);+ const assessment = evaluateGhostSetupAssessment(+ runtimeManifest,+ getGhostSetupProbes(ghostId, runtimeManifest),{revision: getGhostSetupChangeBus().currentRevision(ghostId),strict: true,@@ -5917,6 +5925,10 @@ async function installAndDockLocked(`装入包的 ghostId(${result.ghost.manifest.id})与加锁使用的 id(${opts.ghostId})不一致`,);}+ if (!installedBefore) {+ try { recordGhostAdded(result.ghost.manifest.id); }+ catch { log.warn('ghost addition history unavailable'); }+ }// 内置墓碑清除已并入 GhostManager 的 durable install journal(marker.clearBuiltinTombstone// + 提交时清除 + 崩溃恢复补清),此处不再直接调用:瞬时状态写失败会保留 marker 交由// 启动恢复,而不是把已提交的安装误报成错误。@@ -6719,6 +6731,26 @@ export function registerGhostIpc(): void {const runtime = getGhostRuntime();mobilePluginPages = new MobilePluginPages({list: availableGhosts,+ listOrder: () => {+ const order = new Map<string, { addedAt?: number; recentIndex?: number }>();+ try {+ for (const entry of readGhostRecommendationEntries()) {+ if (entry.addedAt !== undefined) order.set(entry.id, { addedAt: entry.addedAt });+ }+ } catch { log.warn('ghost addition history unavailable'); }+ try {+ loadGhostRecentIds().forEach((id, recentIndex) => order.set(id, { ...order.get(id), recentIndex }));+ } catch { log.warn('ghost recent usage unavailable'); }+ return order;+ },+ setupAssessment: getGhostSetupAssessment,+ configuration: (id, assessment) => {+ const ghost = findAvailableGhost(id);+ if (!ghost) throw new Error('PLUGIN_UNAVAILABLE');+ const manifest = withRuntimeFiloGoogleClient(ghost.manifest);+ return mobilePluginConfiguration(manifest, getGhostSetupProbes(id, manifest), assessment);+ },+ runtimeState: id => runtime.stateOf(id),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.diff --git a/apps/desktop/src/main/cindy-brain/mobilePageService.ts b/apps/desktop/src/main/cindy-brain/mobilePageService.tsindex 6025bf307c..b7821055af 100644--- a/apps/desktop/src/main/cindy-brain/mobilePageService.ts+++ b/apps/desktop/src/main/cindy-brain/mobilePageService.ts@@ -11,8 +11,13 @@ import {type PluginPageAsset,type PluginPageFile,type RemoteCollectionItem,+ type PluginConfigurationSummary,} from '@cindy/device-link';-import type { InstalledGhost } from '../../shared/ghost.js';+import { ghostContentKeys, ghostPermissionItems, ghostTrustLabelKey, type GhostSetupAssessment, type InstalledGhost } from '../../shared/ghost.js';+import { resolvePreferredSystemLocale } from '../../shared/locale.js';+import { t } from '../i18n.js';+import { mobilePluginUsage } from './mobilePluginUsage.js';+import { mobilePluginConfiguration } from './mobilePluginConfiguration.js';import type { GhostConfirmShowParams } from './confirmSlot.js';import {RemoteResourceRegistryError,@@ -54,6 +59,10 @@ interface Page {}interface Dependencies {list(): InstalledGhost[];+ listOrder?(): ReadonlyMap<string, NonNullable<RemoteCollectionItem['pluginOrder']>>;+ setupAssessment?(id: string): GhostSetupAssessment;+ configuration?(id: string, assessment?: GhostSetupAssessment): PluginConfigurationSummary;+ runtimeState?(id: string): string;revision(ghost: InstalledGhost): string;captureOwner(): () => boolean;captureController(controllerId: string): () => boolean;@@ -294,13 +303,14 @@ export class MobilePluginPages {});});}- private item(ghost: InstalledGhost): RemoteCollectionItem {+ private item(ghost: InstalledGhost, order?: RemoteCollectionItem['pluginOrder']): 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),+ ...(order ? { pluginOrder: order } : {}),display: {title: m.name,subtitle: m.description ?? '',@@ -329,7 +339,13 @@ export class MobilePluginPages {? [{ id: `open:${surface}`, label: surface, disabled: !ghost.enabled }]: [];}),- { id: ghost.enabled ? 'disable' : 'enable', label: ghost.enabled ? 'Disable' : 'Enable' },+ {+ id: ghost.enabled ? 'disable' : 'enable',+ label: ghost.enabled ? 'Disable' : 'Enable',+ ...(!ghost.enabled && (ghost.approval.state !== 'approved' || ghost.retirement)+ ? { disabled: true }+ : {}),+ },],};}@@ -343,6 +359,8 @@ export class MobilePluginPages {},list: async (_ctx, request) => {this.sweep();+ let order: ReturnType<NonNullable<Dependencies['listOrder']>> | undefined;+ try { order = this.deps.listOrder?.(); } catch { /* Optional ordering cannot block the list. */ }const q = request.query?.toLocaleLowerCase();const items = this.deps.list()@@ -351,7 +369,7 @@ export class MobilePluginPages {!q ||`${g.manifest.name} ${g.manifest.description ?? ''}`.toLocaleLowerCase().includes(q),)- .map((g) => this.item(g));+ .map((g) => this.item(g, order?.get(g.manifest.id)));return {collectionId: PLUGIN_COLLECTION,revision: createHash('sha256').update(JSON.stringify(items)).digest('hex'),@@ -361,6 +379,40 @@ export class MobilePluginPages {get: async (_ctx, request) => {const ghost = this.ghost(request.ref.id);const item = this.item(ghost);+ const locale = resolvePreferredSystemLocale([request.client.locale ?? 'en']);+ // Read-only declaration facts and copy shared with PC; no saved values leave Host.+ const permissionText = (key: string, args?: Record<string, string>) =>+ t(`settings.ghosts.perm.${key}`, locale).replace(/\{\{(\w+)\}\}/g, (match, name: string) => args?.[name] ?? match);+ const permissions = ghostPermissionItems(ghost.manifest)+ .filter(permission => permission.kind !== 'tool')+ .map(permission => ({+ title: permissionText(permission.labelKey, permission.labelArgs),+ description: [+ permission.detailKey ? permissionText(permission.detailKey, permission.detailArgs) : '',+ permission.detail ?? '',+ ].filter(Boolean).join('\n\n'),+ }));+ const detailFacts = [+ {key: 'version', title: t('settings.ghosts.detail.infoVersion', locale), value: 'v' + ghost.manifest.version},+ ...(ghost.manifest.author ? [{key: 'author', title: t('settings.ghosts.detail.infoAuthor', locale), value: ghost.manifest.author}] : []),+ {key: 'trust', title: t('settings.ghosts.detail.infoTrust', locale), value: t('settings.ghosts.trust.' + ghostTrustLabelKey(ghost.trust), locale).replaceAll('{{publisher}}', ghost.trust?.publisherName ?? t('settings.ghosts.trust.unknownPublisher', locale))},+ {key: 'identifier', title: t('settings.ghosts.detail.infoId', locale), value: ghost.manifest.id},+ {key: 'contents', title: t('settings.ghosts.detail.infoContents', locale), value: ghostContentKeys(ghost.manifest).map(key => t('settings.ghosts.contents.' + key, locale)).join(' · ')},+ {key: 'panel', title: t('settings.ghosts.detail.infoPanel', locale), value: t(ghost.manifest.panel ? 'settings.ghosts.contents.panel' : 'settings.ghosts.detail.panelNone', locale)},+ ...(ghost.dir ? [{key: 'location', title: t('settings.ghosts.detail.infoLocation', locale), value: ghost.dir}] : []),+ ];+ let assessment: GhostSetupAssessment | undefined;+ try {+ assessment = this.deps.setupAssessment?.(ghost.manifest.id);+ } catch {+ // A failed read is unknown, never a fabricated missing configuration.+ }+ let configuration = mobilePluginConfiguration(ghost.manifest, undefined, assessment);+ try {+ configuration = this.deps.configuration?.(ghost.manifest.id, assessment) ?? configuration;+ } catch {+ // A failed configuration read retains declarations with unknown status.+ }return {...item,blocks: [@@ -378,10 +430,18 @@ export class MobilePluginPages {tools:ghost.manifest.tools?.map((tool) => ({name: tool.name,- description: tool.description,+ description: tool.description ?? '',})) ?? [],+ permissions,+ details: detailFacts,tasks: Boolean(ghost.manifest.agent?.tasks || ghost.manifest.agent?.errand),mobile: parsePluginMobileDeclaration(ghost.manifest.mobile) !== null,+ usage: mobilePluginUsage(+ ghost,+ assessment,+ this.deps.runtimeState?.(ghost.manifest.id),+ configuration,+ ),},},],diff --git a/apps/desktop/src/main/cindy-brain/mobilePluginConfiguration.ts b/apps/desktop/src/main/cindy-brain/mobilePluginConfiguration.tsnew file mode 100644index 0000000000..dd392e8130--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/mobilePluginConfiguration.ts@@ -0,0 +1,117 @@+import type { PluginConfigurationItem, PluginConfigurationSummary } from '@cindy/device-link';+import type { GhostManifest, GhostSetupAssessment } from '../../shared/ghost.js';+import { evaluateGhostSetupAssessment, type GhostSetupProbes } from './ghostSetupStatus.js';++/** Project every declared item, including optional items omitted from the use gate. No values leave Host. */+export function mobilePluginConfiguration(+ manifest: GhostManifest,+ probes?: GhostSetupProbes,+ assessment?: GhostSetupAssessment,+): PluginConfigurationSummary {+ const items: PluginConfigurationItem[] = [];+ const add = (item: PluginConfigurationItem) => {+ if (!items.some((other) => other.id === item.id)) items.push(item);+ };+ const assessed = new Map(+ assessment?.groups.flatMap((group) => group.items.map((item) => [item.ref, item] as const)),+ );+ const stateFor = (+ kind: 'secret' | 'connection' | 'kv',+ key: string,+ label: string,+ ): PluginConfigurationItem['state'] => {+ if (!probes) {+ const state = assessed.get(`${kind}:${key}`)?.state;+ return state === 'satisfied' ? 'configured' : (state ?? 'unknown');+ }+ try {+ const checked = evaluateGhostSetupAssessment(+ {+ ...manifest,+ setup: { requires: [{ anyOf: [kind === 'kv' ? { kind, key, label } : { kind, key }] }] },+ },+ probes,+ { revision: 0 },+ );+ const state = checked.groups[0].items[0].state;+ return state === 'satisfied' ? 'configured' : state;+ } catch {+ return 'unknown';+ }+ };+ for (const secret of manifest.network?.secrets ?? []) {+ const managed = ['login-email', 'gh-cli', 'oidc-token'].includes(secret.source ?? 'user');+ const item: PluginConfigurationItem = {+ id: `secret:${secret.key}`,+ label: secret.label.slice(0, 160),+ ...(secret.hint ? { hint: secret.hint.slice(0, 512) } : {}),+ kind: managed ? 'managed' : secret.source === 'oauth' ? 'oauth' : 'secret',+ state: managed ? 'managed' : stateFor('secret', secret.key, secret.label),+ };+ if (item.kind === 'oauth' && probes && item.state !== 'unknown') {+ try {+ const accounts = probes.oauthStatus(secret.key);+ item.count = accounts.connected;+ item.expiredCount = accounts.expired;+ } catch {+ item.state = 'unknown';+ }+ }+ add(item);+ }+ for (const secret of manifest.node?.secretBindings ?? []) {+ if (secret.oauthSecret) continue; // Same network OAuth declaration; no duplicate row.+ add({+ id: `secret:${secret.key}`,+ kind: 'secret',+ label: secret.label.slice(0, 160),+ ...(secret.hint ? { hint: secret.hint.slice(0, 512) } : {}),+ state: stateFor('secret', secret.key, secret.label),+ });+ }+ for (const connection of manifest.network?.connections ?? []) {+ const item: PluginConfigurationItem = {+ id: `connection:${connection.key}`,+ kind: 'connection',+ label: connection.label.slice(0, 160),+ state: stateFor('connection', connection.key, connection.label),+ };+ if (probes && item.state !== 'unknown') {+ try {+ item.count = probes.connectionCount(connection.key);+ } catch {+ item.state = 'unknown';+ }+ }+ add(item);+ }+ for (const group of manifest.setup?.requires ?? [])+ for (const req of group.anyOf) {+ if (req.kind === 'kv')+ add({+ id: `kv:${req.key}`,+ kind: 'parameter',+ label: req.label.slice(0, 160),+ state: stateFor('kv', req.key, req.label),+ });+ }+ for (const group of assessment?.groups ?? [])+ for (const requirement of group.items) {+ if (requirement.kind === 'client_config')+ add({+ id: requirement.ref,+ kind: 'client',+ label: requirement.label.slice(0, 160),+ state: requirement.state === 'satisfied' ? 'configured' : requirement.state,+ });+ }+ return {+ items,+ alternatives: (assessment?.groups ?? []).flatMap((group) => {+ const ids = group.items+ .map((item) => item.ref)+ .filter((ref) => items.some((item) => item.id === ref));+ return ids.length > 1 ? [ids] : [];+ }),+ };+}diff --git a/apps/desktop/src/main/cindy-brain/mobilePluginUsage.ts b/apps/desktop/src/main/cindy-brain/mobilePluginUsage.tsnew file mode 100644index 0000000000..f2e4e744aa--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/mobilePluginUsage.ts@@ -0,0 +1,51 @@+import type { PluginUsageSummary, PluginConfigurationSummary } from '@cindy/device-link';+import type { GhostSetupAssessment, InstalledGhost } from '../../shared/ghost.js';++/** Read-only detail projection; setup presence checks are not credential validity checks. */+export function mobilePluginUsage(+ ghost: InstalledGhost,+ assessment?: GhostSetupAssessment,+ runtimeState?: string,+ configuration?: PluginConfigurationSummary,+): PluginUsageSummary {+ const m = ghost.manifest;+ const unmet =+ assessment?.groups.filter((group) => !group.items.some((item) => item.state === 'satisfied')) ??+ [];+ const labels = (state: 'missing' | 'expired') =>+ [+ ...new Set(+ unmet.flatMap((group) =>+ group.items+ .filter((item) => item.state === state)+ .map((item) => item.label.slice(0, 160)),+ ),+ ),+ ].slice(0, 64);+ return {+ taskUsable: Boolean(m.command || m.tools?.length || m.skill?.items.length),+ hasSettings: Boolean(m.settingsHtml),+ approvalRequired: ghost.approval.state !== 'approved',+ builtin: ghost.builtin === true,+ retired: Boolean(ghost.retirement),+ ...(configuration ? { configuration } : {}),+ ...(runtimeState === 'crashed' || runtimeState === 'fused'+ ? { runtimeIssue: runtimeState }+ : {}),+ setup: {+ state: assessment?.state ?? 'unknown',+ missing: labels('missing'),+ expired: labels('expired'),+ groups: unmet.slice(0, 64).map((group) => ({+ missing: group.items+ .filter((item) => item.state === 'missing')+ .map((item) => item.label.slice(0, 160))+ .slice(0, 64),+ expired: group.items+ .filter((item) => item.state === 'expired')+ .map((item) => item.label.slice(0, 160))+ .slice(0, 64),+ })),+ },+ };+}diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsxindex 7ba278e9fc..dcccf7f5ae 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx@@ -46,6 +46,7 @@ import { toast } from '@/lib/toast';import { cn } from '@/lib/utils';import {isOfficialGhostId,+ ghostTrustLabelKey,type GhostPermissionItem,type GhostToolDecl,type InstalledGhost,@@ -808,16 +809,7 @@ export function DetailsSection({panelStatus: string | null;}) {const { t } = useTranslation();- const trustLabelKey =- detail.trust.level === 'cindy-official'- ? 'official'- : detail.trust.level === 'reviewed'- ? 'reviewed'- : detail.trust.level === 'verified-publisher'- ? 'verifiedPublisher'- : detail.trust.publisherSigned- ? 'signedUnverified'- : 'unsigned';+ const trustLabelKey = ghostTrustLabelKey(detail.trust);const facts: Array<{key: string;label: string;diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex a08f41aa65..821f9b92b0 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -1658,6 +1658,15 @@ export interface GhostTrustInfo {unknownReviewer?: boolean;}+/** Shared PC/mobile display label; only Host-owned trust facts affect this result. */+export function ghostTrustLabelKey(trust: GhostTrustInfo | undefined):+ 'official' | 'reviewed' | 'verifiedPublisher' | 'signedUnverified' | 'unsigned' {+ return trust?.level === 'cindy-official' ? 'official'+ : trust?.level === 'reviewed' ? 'reviewed'+ : trust?.level === 'verified-publisher' ? 'verifiedPublisher'+ : trust?.publisherSigned ? 'signedUnverified' : 'unsigned';+}+/** 意识面板的 panelKind(布局树寻址用)。 */// 返回类型收窄到模板字面量:右侧栏 TabKindId 含 `ghost:${string}` 分支,// 调用方无需再 as 断言;对既有 string 消费方完全兼容。diff --git a/apps/mobile/docs/ios-native-components.md b/apps/mobile/docs/ios-native-components.mdindex f1e064f307..79bd85a5f4 100644--- a/apps/mobile/docs/ios-native-components.md+++ b/apps/mobile/docs/ios-native-components.md@@ -14,9 +14,11 @@| 顶栏圆形按钮、浮动新建按钮 | SwiftUI Button,原生玻璃/禁用反馈 | 保留 Cindy 业务图标,图标可以放在 RNHostView 里。首页浮动新建按钮外包一层原生形变视图:触摸由它接管(不播放按钮自身按压),按下即拉长成输入框药丸。[按钮](../src/platform/chrome/NativeChromeButton.ios.tsx)、[形变](../modules/cindy-composer-morph/ios/CindyComposerMorphModule.swift) || 登录页继续、Apple / SSO 等按钮 | SwiftUI Button + Cindy 的标签、品牌图案和布局 | 登录整页、手机号框、协议勾选与法律文字链接仍有自定义实现。[实现](../src/components/LoginNativeButton.ios.tsx) || SSO 登录窗口 | ASWebAuthenticationSession | 登录网页由认证服务提供。[调用](../src/auth/AuthContext.tsx) |+| 插件的已有任务选择器 | SwiftUI plain List、TextField、Button 与系统 BottomSheet | 无分组卡片,搜索常驻,系统填充背景与键盘;真实活跃任务按标题过滤,选择等待原生关闭完成后导航。此处搜索为 SwiftUI 输入框,不是目录页的 UIKit UISearchBar。[实现](../src/plugins/PluginTaskPickerView.ios.tsx) || 任务内搜索 | SwiftUI TextField、Button、原生 sheet | 与首页的搜索框不是同一个实现。[实现](../src/session/SessionSearchNative.ios.tsx) || 模型选择、模型设置 | 原生 Form / Section / Picker / Toggle / TextField 与原生按钮 | 业务图标、部分状态/内容由 RN 嵌入。[选择](../src/session/UnifiedModelPickerView.ios.tsx)、[设置](../src/session/ModelOptionsSheetView.ios.tsx) || 设备管理列表 | SwiftUI List、ListItem、SwipeActions | 与任务列表的自定义侧滑实现不同。[实现](../src/device-link/DeviceManagementList.ios.tsx) |+| 已装插件目录与详情 | UIKit UISearchController / UISearchBar,SwiftUI List / Section、Menu、Picker、Toggle、DisclosureGroup | 搜索由现有导航栈提供并常驻;电脑菜单和内容标题随列表滚出;隐藏 All/Unread 筛选。54pt 方形列表图标与更宽行距;详情名称右侧启停开关可视目标 48×24pt,操作区域 56×44pt。Use it in 下仅两个 secondary 使用按钮;Tools 沿用 PC 的弱胶囊样式,工具名前显示图标,按屏幕宽度自然换行,收起态最多两行,Show all/Show less 展开或收起全部工具,不展示描述;Permissions 可展开。分组不画线,仅 Details 条目之间使用系统 Divider;首行顶部 inset 8pt。Details 展示与 PC 同源的版本、作者、签名、标识、包含能力、面板及只读安装位置;旧 Host 缺字段直接隐藏。配置提示到电脑完成。插件图标继续复用 RN。[搜索](../src/plugins/PluginsScreen.tsx)、[目录](../src/plugins/PluginDirectoryView.ios.tsx)、[详情](../src/plugins/PluginDetailView.ios.tsx) || 系统照片、相机、文件选择、分享 | 系统选择器 / 分享面板,经 Expo 模块调用 | 附件面板内的“最近媒体”网格不等于系统相册。[附件入口](../src/session/useMobileLocalAttachments.ts) |## 原生容器或原生编辑核心,内容仍有定制@@ -39,3 +41,6 @@以上是代码事实。真实界面还受系统版本、原生模块是否已装入、回退条件和入口影响。导航与新建输入框的交互细节和已知未完成项见 [导航与新建输入框](./navigation-and-composer.md)。++已装插件精简详情使用 SwiftUI List、原生主次 Button 和 Toggle;配置/任务偏好位于设置子页,正常状态不显示状态标签。+可选信息缺失时隐藏字段或空的 Tools/Permissions 模块,不展示电脑未提供数据的提示;有真实字段的 Details 保留。diff --git a/apps/mobile/src/__tests__/composerSheetOrientation.test.tsx b/apps/mobile/src/__tests__/composerSheetOrientation.test.tsxindex d5feb29e41..e09967fb47 100644--- a/apps/mobile/src/__tests__/composerSheetOrientation.test.tsx+++ b/apps/mobile/src/__tests__/composerSheetOrientation.test.tsx@@ -12,13 +12,27 @@ vi.mock('react-native', () => ({vi.mock('@expo/ui', () => ({ Host: ({ children }: any) => <div>{children}</div> }));vi.mock('@expo/ui/swift-ui', () => {const Container = ({ children }: any) => <div>{children}</div>;- return { Form: Container, Button: Container, Group: Container, HStack: Container, Image: Container,+ return { Form: ({ children }: any) => <div data-native="Form">{children}</div>,+ List: ({ children }: any) => <div data-native="List">{children}</div>, Button: Container, Group: Container, HStack: Container, Image: Container,RNHostView: Container, Spacer: Container, Text: Container, VStack: Container, ZStack: Container,BottomSheet: (props: any) => { state.sheet = props; return <div>{props.children}</div>; },};});++it('uses a plain list only when requested and preserves form sheets', () => {+ const container = document.createElement('div');+ const root = createRoot(container);+ try {+ act(() => root.render(<ComposerSheet visible title="" nativeContent nativeList onClose={() => {}}><span>Tasks</span></ComposerSheet>));+ expect(container.querySelector('[data-native="List"]')).not.toBeNull();+ expect(container.querySelector('[data-native="Form"]')).toBeNull();+ act(() => root.render(<ComposerSheet visible title="" nativeContent onClose={() => {}}><span>Settings</span></ComposerSheet>));+ expect(container.querySelector('[data-native="Form"]')).not.toBeNull();+ expect(container.querySelector('[data-native="List"]')).toBeNull();+ } finally { act(() => root.unmount()); }+});vi.mock('@expo/ui/swift-ui/modifiers', () => ({- ...Object.fromEntries(['accessibilityLabel', 'contentShape', 'buttonStyle', 'font', 'foregroundStyle', 'frame', 'padding', 'presentationDetents', 'presentationDragIndicator', 'interactiveDismissDisabled', 'scrollContentBackground'].map(name => [name, vi.fn(() => ({}))])),+ ...Object.fromEntries(['accessibilityLabel', 'contentShape', 'buttonStyle', 'font', 'foregroundStyle', 'frame', 'padding', 'presentationDetents', 'presentationDragIndicator', 'interactiveDismissDisabled', 'scrollContentBackground', 'listStyle', 'scrollDismissesKeyboard'].map(name => [name, vi.fn(() => ({}))])),shapes: { rectangle: () => ({}) },}));vi.mock('@/theme', () => ({ iconSize: { lg: 20 }, useTheme: () => ({ mode: 'light', colors: {} }) }));diff --git a/apps/mobile/src/__tests__/pluginDetailModel.test.ts b/apps/mobile/src/__tests__/pluginDetailModel.test.tsnew file mode 100644index 0000000000..371d42d1fe--- /dev/null+++ b/apps/mobile/src/__tests__/pluginDetailModel.test.ts@@ -0,0 +1,358 @@+import { describe, expect, it } from "vitest";+import { pluginDetailModel } from "@/plugins/pluginDetailModel";+import type { PluginUsageSummary, RemoteResource } from "@cindy/device-link";+import type { HostedRemoteCollectionItem } from "@/device-link/remoteResources";+const row = (enabled = true): HostedRemoteCollectionItem => ({+ key: "mac:demo",+ host: { deviceId: "mac", deviceName: "Mac" },+ item: {+ ref: { collectionId: "plugins", kind: "plugin", id: "demo" },+ revision: "1",+ links: [],+ display: { title: "Demo" },+ actions: [+ { id: enabled ? "disable" : "enable", label: "Toggle" },+ { id: "open:panel", label: "Panel" },+ { id: "open:mainView", label: "Page" },+ ],+ },+});+const usage = (+ patch: Partial<PluginUsageSummary> = {},+): PluginUsageSummary => ({+ taskUsable: true,+ hasSettings: false,+ approvalRequired: false,+ builtin: false,+ retired: false,+ setup: { state: "ready", missing: [], expired: [] },+ ...patch,+});+const resource = (value: PluginUsageSummary): RemoteResource => ({+ ...row().item,+ blocks: [+ {+ id: "capabilities",+ primitive: "plugin-capabilities",+ fallbackMarkdown: "",+ data: { usage: value },+ },+ ],+});+describe("minimal plugin detail state", () => {+ it("keeps the switch available to recover a fuse without advertising task usage", () => {+ expect(+ pluginDetailModel(+ row(),+ resource(usage({ runtimeIssue: "fused" })),+ true,+ false,+ false,+ ),+ ).toMatchObject({+ runtimeIssue: "fused",+ canUseTasks: false,+ canToggle: true,+ });+ });+ it("keeps ready tasks usable and collapses panel/mainView into one entry", () => {+ expect(+ pluginDetailModel(row(), resource(usage()), true, false, false),+ ).toMatchObject({+ canUseTasks: true,+ canToggle: true,+ status: undefined,+ mainSurface: "panel",+ hasSettings: false,+ });+ });+ it("preserves legacy Host usage without inventing configured status", () => {+ const m = pluginDetailModel(+ row(),+ { ...row().item, blocks: [] },+ true,+ false,+ false,+ );+ expect(m.canUseTasks).toBe(true);+ expect(m.missing).toEqual([]);+ expect(m.status).toBeUndefined();+ });+ it.each([+ [false, false, false, "offline", "connect"],+ [true, true, false, "loading", undefined],+ [true, false, true, "loadFailed", "retry"],+ ] as const)(+ "blocks usage for transport/read status",+ (online, loading, failed, status, action) => {+ const m = pluginDetailModel(+ row(),+ resource(usage()),+ online,+ loading,+ failed,+ );+ expect(m).toMatchObject({+ status,+ statusAction: action,+ canUseTasks: false,+ canToggle: false,+ });+ },+ );+ it("keeps stop and missing approval distinct, and does not offer an invalid enable", () => {+ expect(+ pluginDetailModel(row(false), resource(usage()), true, false, false),+ ).toMatchObject({+ status: "disabled",+ statusAction: "enable",+ canToggle: true,+ canUseTasks: false,+ });+ expect(+ pluginDetailModel(+ row(false),+ resource(usage({ approvalRequired: true })),+ true,+ false,+ false,+ ),+ ).toMatchObject({+ status: "approvalRequired",+ statusAction: undefined,+ canToggle: false,+ });+ expect(+ pluginDetailModel(+ row(false),+ resource(usage({ retired: true })),+ true,+ false,+ false,+ ),+ ).toMatchObject({+ status: "retired",+ canToggle: false,+ });+ });+ it("uses Host missing/expired facts and moves completion into settings", () => {+ expect(+ pluginDetailModel(+ row(),+ resource(+ usage({+ setup: {+ state: "required",+ missing: ["API key"],+ expired: ["Account"],+ },+ }),+ ),+ true,+ false,+ false,+ ),+ ).toMatchObject({+ status: "setupRequired",+ statusAction: "settings",+ hasSettings: true,+ canUseTasks: false,+ missing: ["API key"],+ expired: ["Account"],+ });+ });+ it("never treats an unknown assessment as ready", () => {+ expect(+ pluginDetailModel(+ row(),+ resource(+ usage({ setup: { state: "unknown", missing: [], expired: [] } }),+ ),+ true,+ false,+ false,+ ),+ ).toMatchObject({+ status: "setupUnknown",+ statusAction: "retry",+ canUseTasks: false,+ });+ });+ it("does not advertise tasks for page-only plugins or confuse a crash with disabled", () => {+ expect(+ pluginDetailModel(+ row(),+ resource(usage({ taskUsable: false })),+ true,+ false,+ false,+ ),+ ).toMatchObject({+ taskUsable: false,+ canUseTasks: false,+ mainSurface: "panel",+ });+ expect(+ pluginDetailModel(+ row(),+ resource(usage({ runtimeIssue: "crashed" })),+ true,+ false,+ false,+ ),+ ).toMatchObject({+ status: undefined,+ runtimeIssue: "crashed",+ canUseTasks: true,+ });+ });+});+it("treats malformed new-host facts as unknown rather than legacy readiness", () => {+ const broken = resource(usage());+ (broken.blocks![0].data as any).usage.taskUsable = "yes";+ expect(pluginDetailModel(row(), broken, true, false, false)).toMatchObject({+ status: "setupUnknown",+ canUseTasks: false,+ });+});++describe("real plugin information", () => {+ it("reads full tools, permission summaries and existing metadata blocks", () => {+ const detail: RemoteResource = {+ ...row().item,+ blocks: [+ {+ id: "about",+ primitive: "markdown",+ fallbackMarkdown: "Full introduction",+ },+ { id: "version", primitive: "status", fallbackMarkdown: "2.3.0" },+ {+ id: "capabilities",+ primitive: "plugin-capabilities",+ fallbackMarkdown: "",+ data: {+ tools: [+ { name: "calendar_events", description: "Read calendar events" },+ ],+ permissions: [+ {+ title: "Connect to calendar.example",+ description: "Calendar access",+ },+ ],+ },+ },+ ],+ };+ expect(pluginDetailModel(row(), detail, true, false, false)).toMatchObject({+ description: "Full introduction",+ version: "2.3.0",+ tools: [{ name: "calendar_events", description: "Read calendar events" }],+ permissions: [+ {+ title: "Connect to calendar.example",+ description: "Calendar access",+ },+ ],+ });+ });+ it("distinguishes old Host and malformed data from explicit empty declarations", () => {+ const withFacts = (data: unknown) => ({+ ...row().item,+ blocks: [+ {+ id: "capabilities",+ primitive: "plugin-capabilities",+ fallbackMarkdown: "",+ data,+ },+ ],+ });+ const empty = pluginDetailModel(+ row(),+ withFacts({ tools: [], permissions: [] }),+ true,+ false,+ false,+ );+ expect(empty.tools).toEqual([]);+ expect(empty.permissions).toEqual([]);+ for (const data of [+ {},+ {+ tools: [{ description: "missing name" }],+ permissions: [{ title: 123 }],+ },+ null,+ ]) {+ const model = pluginDetailModel(+ row(),+ withFacts(data),+ true,+ false,+ false,+ );+ expect(model.tools).toBeUndefined();+ expect(model.permissions).toBeUndefined();+ }+ });+});++it("reads complete PC metadata only when the Host actually supplies it", () => {+ const details = [+ { key: "author", title: "Author", value: "Cindy" },+ {+ key: "trust",+ title: "Source & signature",+ value: "Unverified / unsigned",+ },+ {+ key: "location",+ title: "Install location",+ value: "/plugin-install/calendar",+ },+ ];+ const model = pluginDetailModel(+ row(),+ {+ ...row().item,+ blocks: [+ {+ id: "capabilities",+ primitive: "plugin-capabilities",+ fallbackMarkdown: "",+ data: { details },+ },+ ],+ },+ true,+ false,+ false,+ );+ expect(model.details).toEqual(details);+ expect(+ pluginDetailModel(row(), undefined, true, false, false).details,+ ).toBeUndefined();+ expect(+ pluginDetailModel(+ row(),+ {+ ...row().item,+ blocks: [+ {+ id: "capabilities",+ primitive: "plugin-capabilities",+ fallbackMarkdown: "",+ data: {+ details: [{ key: "trust", title: "Source", value: false }],+ },+ },+ ],+ },+ true,+ false,+ false,+ ).details,+ ).toBeUndefined();+});diff --git a/apps/mobile/src/__tests__/pluginListOrder.test.ts b/apps/mobile/src/__tests__/pluginListOrder.test.tsnew file mode 100644index 0000000000..cba64aff8f--- /dev/null+++ b/apps/mobile/src/__tests__/pluginListOrder.test.ts@@ -0,0 +1,90 @@+import { describe, expect, it } from "vitest";+import { sortPluginItems } from "@/plugins/pluginListOrder";+import { normalizeRemoteCollectionItems } from "@/device-link/remoteResources";+import type { HostedRemoteCollectionItem } from "@/device-link/remoteResources";++const row = (+ id: string,+ order?: HostedRemoteCollectionItem["item"]["pluginOrder"],+ device = "mac",+): HostedRemoteCollectionItem => ({+ key: device + ":" + id,+ host: { deviceId: device, deviceName: device },+ item: {+ ref: { collectionId: "plugins", kind: "plugin", id },+ display: { title: id, timestamp: 999999 },+ revision: "1",+ links: [],+ ...(order ? { pluginOrder: order } : {}),+ },+});+describe("installed plugin ordering", () => {+ it("preserves legacy order and promotes only known recent use", () => {+ const items = [row("a"), row("b")];+ expect(sortPluginItems(items, []).map((i) => i.key)).toEqual([+ "mac:a",+ "mac:b",+ ]);+ expect(sortPluginItems(items, ["mac:b"]).map((i) => i.key)).toEqual([+ "mac:b",+ "mac:a",+ ]);+ expect(sortPluginItems(items, ["other:b"]).map((i) => i.key)).toEqual([+ "mac:a",+ "mac:b",+ ]);+ });+ it("sorts real addition dates newest-first and keeps unknown chronology stable", () => {+ const items = [+ row("unknown"),+ row("old", { addedAt: 10 }),+ row("new", { addedAt: 20 }),+ row("also-unknown"),+ ];+ expect(sortPluginItems(items, []).map((item) => item.item.ref.id)).toEqual([+ "new",+ "old",+ "unknown",+ "also-unknown",+ ]);+ expect(items[0].item.ref.id).toBe("unknown");+ });+ it("uses local MRU before Host MRU, isolates the same plugin on different computers", () => {+ const items = [+ row("p", { addedAt: 10 }, "a"),+ row("p", { addedAt: 20 }, "b"),+ row("other", { recentIndex: 0 }),+ ];+ expect(sortPluginItems(items, ["a:p"]).map((item) => item.key)).toEqual([+ "a:p",+ "mac:other",+ "b:p",+ ]);+ });+ it("ignores malformed metadata and never uses notification time as an addition date", () => {+ const items = [+ row("first", { addedAt: NaN, recentIndex: -1 }),+ row("second", { addedAt: Infinity }),+ ];+ expect(sortPluginItems(items, []).map((item) => item.key)).toEqual([+ "mac:first",+ "mac:second",+ ]);+ });+ it("normalizes only inert plugin ordering facts, without dropping legacy items", () => {+ const items = normalizeRemoteCollectionItems(+ {+ items: [+ row("valid", { addedAt: 1234, recentIndex: 0 }).item,+ row("invalid", { addedAt: -1, recentIndex: 1.5 }).item,+ row("legacy").item,+ ],+ },+ "plugins",+ );+ expect(items).toHaveLength(3);+ expect(items[0].pluginOrder).toEqual({ addedAt: 1234, recentIndex: 0 });+ expect(items[1].pluginOrder).toBeUndefined();+ expect(items[2].pluginOrder).toBeUndefined();+ });+});diff --git a/apps/mobile/src/__tests__/pluginNativeViews.test.tsx b/apps/mobile/src/__tests__/pluginNativeViews.test.tsxnew file mode 100644index 0000000000..5475dad4bf--- /dev/null+++ b/apps/mobile/src/__tests__/pluginNativeViews.test.tsx@@ -0,0 +1,779 @@+// @vitest-environment jsdom+import { act, createElement } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, expect, it, vi } from "vitest";+import { PluginDirectoryView } from "@/plugins/PluginDirectoryView.ios";+import { PluginDetailView } from "@/plugins/PluginDetailView.ios";+import { PluginTaskPickerView } from "@/plugins/PluginTaskPickerView.ios";+import { PluginTaskPickerView as AndroidTaskPickerView } from "@/plugins/PluginTaskPickerView";+import { pluginDetailModel } from "@/plugins/pluginDetailModel";+import { palettes } from "@/theme/tokens";++const bridge = vi.hoisted(() => ({+ props: new Map<string, any>(),+ ownerCurrent: true,+ mode: "light" as "light" | "dark",+}));+vi.mock("@expo/ui/swift-ui", async () => {+ const React = await import("react");+ const TextField = Object.assign(+ (p: any) => {+ if (p.testID) bridge.props.set(p.testID, p);+ return React.createElement(+ "div",+ { "data-native": "TextField", "data-testid": p.testID },+ p.children,+ );+ },+ { Placeholder: (p: any) => p.children },+ );+ return {+ TextField,+ useNativeState: (initial: string) =>+ React.useRef({+ value: initial,+ get() {+ return this.value;+ },+ set(value: string) {+ this.value = value;+ },+ }).current,+ Host: (p: any) => {+ React.useEffect(() => {+ p.onLayoutContent?.({ nativeEvent: { width: 390, height: 844 } });+ }, []);+ bridge.props.set("host", p);+ return createElement("main", null, p.children);+ },+ ...Object.fromEntries(+ [+ "Button",+ "Circle",+ "DisclosureGroup",+ "Divider",+ "HStack",+ "Image",+ "List",+ "Menu",+ "Picker",+ "ProgressView",+ "RNHostView",+ "Section",+ "Spacer",+ "Text",+ "Toggle",+ "VStack",+ ].map((name) => [+ name,+ (p: any) => {+ if (p.testID) bridge.props.set(p.testID, p);+ return React.createElement(+ "div",+ { "data-native": name, "data-testid": p.testID },+ p.title,+ p.label,+ p.header ? React.createElement("header", null, p.header) : null,+ name === "DisclosureGroup" && p.isExpanded === false+ ? null+ : p.children,+ );+ },+ ]),+ ),+ };+});+vi.mock("@expo/ui/swift-ui/modifiers", () => ({+ shapes: {+ capsule: () => "capsule",+ rectangle: () => "rectangle",+ roundedRectangle: (p: any) => p,+ },+ ...Object.fromEntries(+ [+ "accessibilityLabel",+ "autocorrectionDisabled",+ "textInputAutocapitalization",+ "textFieldStyle",+ "submitLabel",+ "onSubmit",+ "background",+ "buttonStyle",+ "contentShape",+ "disabled",+ "font",+ "fixedSize",+ "foregroundStyle",+ "frame",+ "lineLimit",+ "labelsHidden",+ "scaleEffect",+ "listRowBackground",+ "listRowInsets",+ "listRowSeparator",+ "listRowSeparatorTint",+ "listSectionSpacing",+ "listStyle",+ "padding",+ "pickerStyle",+ "refreshable",+ "scrollContentBackground",+ "scrollDismissesKeyboard",+ "tag",+ "tint",+ ].map((name) => [name, (value: any) => ({ [name]: value })]),+ ),+}));+vi.mock("react-native", () => ({+ PlatformColor: (name: string) => name,+ useWindowDimensions: () => ({ width: 390, height: 844, fontScale: 1 }),+ Image: () => null,+ View: (p: any) => {+ if (p.testID) bridge.props.set(p.testID, p);+ return createElement(+ "div",+ { "data-testid": p.testID, "aria-hidden": p.accessibilityElementsHidden },+ p.children,+ );+ },+ Text: (p: any) => p.children,+ TextInput: () => null,+ Pressable: (p: any) => p.children,+ ActivityIndicator: () => null,+ StyleSheet: { create: (s: any) => s },+}));+vi.mock("lucide-react-native", () => ({+ Puzzle: () => null,+ Wrench: () => null,+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key, i18n: { language: "en" } }),+}));+vi.mock("@/theme", async () => ({+ ...(await import("@/theme/tokens")),+ useTheme: () => ({ mode: bridge.mode, colors: palettes[bridge.mode] }),+ useThemedStyles: (factory: any) => factory(palettes[bridge.mode]),+}));+vi.mock("react-native-safe-area-context", () => ({+ useSafeAreaInsets: () => ({ top: 0, bottom: 0 }),+}));+vi.mock("@/session/SheetModal", () => ({ SheetModal: (p: any) => p.children }));+vi.mock("@/session/SheetSurface", () => ({+ SheetSurface: (p: any) => p.children,+}));+vi.mock("@/session/ComposerNativeRow", () => ({+ ComposerNativeRow: (p: any) => {+ bridge.props.set(p.testID, p);+ return createElement("div", null, p.title);+ },+}));+vi.mock("@/session/ComposerSheet", () => ({+ ComposerSheet: (p: any) => {+ bridge.props.set("plugins.taskPicker", p);+ return createElement(+ "div",+ { "data-native": "sheet", "data-testid": p.testID },+ p.nativeHeader,+ p.children,+ );+ },+}));+vi.mock("@/session/ComposerNativeSection", () => ({+ ComposerNativeSection: (p: any) => p.children,+}));+vi.mock("@/auth/authOwnerGeneration", () => ({+ getMobileAuthOwner: () => "owner",+ isMobileAuthOwnerCurrent: () => bridge.ownerCurrent,+}));+vi.mock("@/session/CompanionNativeContent.ios", () => ({+ CompanionNativeContent: (p: any) => p.children,+}));+vi.mock("@/platform/chrome/nativeGlassButtonStyle.ios", () => ({+ useNativeGlassButtonStyle: ({ prominent = false } = {}) => [+ { nativeButton: prominent ? "primary" : "secondary" },+ ],+}));+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+const roots: ReturnType<typeof createRoot>[] = [];+afterEach(() => {+ act(() => roots.splice(0).forEach((root) => root.unmount()));+ bridge.props.clear();+ bridge.mode = "light";+ bridge.ownerCurrent = true;+});+function mount(component: any, props: any) {+ const container = document.createElement("div");+ const root = createRoot(container);+ roots.push(root);+ act(() => root.render(createElement(component, props)));+ return {+ container,+ rerender: (props: any) =>+ act(() => root.render(createElement(component, props))),+ };+}+const row = {+ key: "mac:demo",+ host: { deviceId: "mac", deviceName: "Mac" },+ item: {+ ref: { collectionId: "plugins", kind: "plugin", id: "demo" },+ display: { title: "Demo" },+ revision: "1",+ actions: [{ id: "disable", label: "Disable" }],+ },+};+const directory = () => ({+ targets: [row.host],+ deviceId: "",+ onDeviceChange: vi.fn(),+ query: "",+ items: [row],+ loading: false,+ error: false,+ isOnline: () => true,+ onRefresh: vi.fn(),+ onOpen: vi.fn(),+ onDetail: vi.fn(),+ onConnectComputer: vi.fn(),+});+it("uses a scrolling native title row without a separator or sticky section header", () => {+ const p = directory();+ const { container } = mount(PluginDirectoryView, p);+ const list = container.querySelector('[data-testid="plugins.list"]')!;+ expect(+ list.querySelector('[data-testid="plugins.installedHeader"]')?.textContent,+ ).toContain("plugins.installed");+ expect(bridge.props.get("plugins.list").modifiers).toContainEqual({+ listStyle: "plain",+ });+ expect(bridge.props.get("plugins.installedHeader").modifiers).toContainEqual({+ listRowSeparator: "hidden",+ });+ expect(bridge.props.get("plugins.installedHeader").modifiers).toContainEqual({+ listRowInsets: { leading: 20, trailing: 20, top: 0, bottom: 0 },+ });+ expect(+ bridge.props+ .get("plugins.installedHeader")+ .modifiers.filter((m: any) => m.listRowInsets),+ ).toHaveLength(1);+ expect(list.querySelector("header")).toBeNull();+ for (const id of ["plugins.computer"])+ expect(list.querySelector('[data-testid="' + id + '"]')).not.toBeNull();+ expect(container.querySelector('[data-testid="plugins.filter"]')).toBeNull();+ act(() =>+ bridge.props.get("plugins.computer.options").onSelectionChange("mac"),+ );+ expect(p.onDeviceChange).toHaveBeenCalledWith("mac");+});+it("separates open from details", () => {+ const p = { ...directory(), query: "Demo" };+ mount(PluginDirectoryView, p);+ act(() => bridge.props.get("plugins.row.demo").onPress());+ expect(p.onOpen).toHaveBeenCalledWith(row);+ act(() => bridge.props.get("plugins.row.demo").onOptions());+ expect(p.onDetail).toHaveBeenCalledWith(row);+});+it("shows a truthful empty installed state", () => {+ const { container } = mount(PluginDirectoryView, {+ ...directory(),+ items: [],+ });+ expect(container.textContent).toContain("plugins.noPlugins");+});+it("shows Retry instead of Connect computer when the computer lookup fails", () => {+ const { container } = mount(PluginDirectoryView, {+ ...directory(),+ targets: [],+ items: [],+ error: true,+ });+ expect(container.textContent).toContain("plugins.listLoadFailed");+ expect(container.textContent).not.toContain("plugins.noComputer");+ expect(+ container.querySelector('[data-testid="plugins.retryList"]'),+ ).not.toBeNull();+});+it.each(["light", "dark"] as const)(+ "uses native controls and the application theme in %s",+ (mode) => {+ bridge.mode = mode;+ const change = vi.fn();+ const p = {+ row,+ enabled: true,+ online: true,+ busy: false,+ model: pluginDetailModel(+ row as any,+ { ...row.item, blocks: [] } as any,+ true,+ false,+ false,+ ),+ settingsOpen: false,+ onSettings: vi.fn(),+ onResolveStatus: vi.fn(),++ onEnabledChange: change,+ onOpen: vi.fn(),+ onNewTask: vi.fn(),+ onChooseTask: vi.fn(),+ };+ const { rerender } = mount(PluginDetailView, p);+ expect(bridge.props.get("host").colorScheme).toBe(mode);+ expect(bridge.props.get("plugins.enabled").isOn).toBe(true);+ act(() => bridge.props.get("plugins.enabled").onIsOnChange(false));+ expect(change).toHaveBeenCalledWith(false);+ rerender({ ...p, busy: true });+ expect(bridge.props.get("plugins.enabled").modifiers).toContainEqual({+ disabled: true,+ });+ rerender({ ...p, online: false });+ expect(bridge.props.get("plugins.enabled").modifiers).toContainEqual({+ disabled: true,+ });+ },+);+it("groups use buttons under a heading, puts the switch beside the title and guides configuration to PC", () => {+ const p = {+ row,+ enabled: true,+ online: true,+ busy: false,+ settingsOpen: false,+ model: pluginDetailModel(+ row as any,+ {+ ...row.item,+ blocks: [{ id: "capabilities", data: { tasks: true } }],+ } as any,+ true,+ false,+ false,+ ),+ children: createElement("span", null, "Task preferences content"),+ onEnabledChange: vi.fn(),+ onOpen: vi.fn(),+ onNewTask: vi.fn(),+ onChooseTask: vi.fn(),+ onSettings: vi.fn(),+ onResolveStatus: vi.fn(),+ };+ const { container, rerender } = mount(PluginDetailView, p);+ expect(container.textContent).not.toContain("Task preferences content");+ expect(+ container+ .querySelector('[data-testid="plugins.newTask"]')+ ?.getAttribute("data-native"),+ ).toBe("Button");+ for (const id of ["plugins.newTask", "plugins.chooseTask"]) {+ expect(bridge.props.get(id).modifiers).toContainEqual({+ nativeButton: "secondary",+ });+ }+ expect(container.querySelector('[data-testid="plugins.tools"]')).toBeNull();+ expect(+ container.querySelector(+ '[data-testid="plugins.identity"] [data-testid="plugins.enabled"]',+ ),+ ).not.toBeNull();+ expect(+ container.querySelector('[data-testid="plugins.useHeading"]')?.textContent,+ ).toBe("plugins.detail.useItIn");+ expect(+ container.querySelector('[data-testid="plugins.computerSettings"]'),+ ).not.toBeNull();+ expect(+ container.querySelector('[data-testid="plugins.permissions"]'),+ ).toBeNull();+ expect(+ container.querySelector('[data-testid="plugins.metadata"]'),+ ).not.toBeNull();+ act(() => bridge.props.get("plugins.chooseTask").onPress());+ expect(p.onChooseTask).toHaveBeenCalledOnce();+ rerender({ ...p, settingsOpen: true });+ expect(container.textContent).not.toContain("Task preferences content");+ expect(container.querySelector('[data-testid="plugins.newTask"]')).toBeNull();+});+it("uses the title switch to recover a disabled plugin without a duplicate enable button", () => {+ const p = {+ row,+ enabled: false,+ online: true,+ busy: false,+ settingsOpen: false,+ model: {+ ...pluginDetailModel(row as any, undefined, true, false, false),+ canUseTasks: false,+ status: "disabled",+ statusAction: "enable",+ },+ onEnabledChange: vi.fn(),+ onOpen: vi.fn(),+ onNewTask: vi.fn(),+ onChooseTask: vi.fn(),+ onSettings: vi.fn(),+ onResolveStatus: vi.fn(),+ };+ const { container } = mount(PluginDetailView, p);+ expect(container.querySelector('[data-testid="plugins.newTask"]')).toBeNull();+ expect(+ container.querySelector('[data-testid="plugins.chooseTask"]'),+ ).toBeNull();+ expect(+ container.querySelector('[data-testid="plugins.resolveStatus"]'),+ ).toBeNull();+ expect(+ container.querySelector(+ '[data-testid="plugins.identity"] [data-testid="plugins.enabled"]',+ ),+ ).not.toBeNull();+});++it.each([+ { loading: true, error: false, message: undefined },+ { loading: false, error: true, message: "plugins.listLoadFailed" },+ {+ loading: false,+ error: false,+ query: "missing",+ message: "plugins.noResults",+ },+ { loading: false, error: false, targets: [], message: "plugins.noComputer" },+])(+ "keeps empty, loading and failed-list messages mutually exclusive: %j",+ (state) => {+ const p = { ...directory(), items: [], ...state };+ const { container } = mount(PluginDirectoryView, p);+ expect(container.textContent).not.toContain("plugins.noPlugins");+ if (state.message) expect(container.textContent).toContain(state.message);+ if (state.error) {+ expect(container.textContent).not.toContain("plugins.noResults");+ act(() => bridge.props.get("plugins.retryList").onPress());+ expect(p.onRefresh).toHaveBeenCalledOnce();+ }+ },+);+it("retains rows and a subdued warning for partial list failures", () => {+ const { container } = mount(PluginDirectoryView, {+ ...directory(),+ error: true,+ });+ expect(container.textContent).toContain("Demo");+ expect(container.textContent).toContain("plugins.listUnavailable");+ expect(container.textContent).not.toContain("plugins.noPlugins");+ expect(+ container.querySelector('[data-testid="plugins.retryList"]'),+ ).toBeNull();+});++it("shows connect-computer when the computer lookup succeeds with no linked computers", () => {+ const p = { ...directory(), targets: [], items: [], error: false };+ const { container } = mount(PluginDirectoryView, p);+ expect(container.textContent).toContain("plugins.noComputer");+ expect(container.textContent).not.toContain("plugins.listLoadFailed");+ expect(+ container.querySelector('[data-testid="plugins.retryList"]'),+ ).toBeNull();+});++it("keeps the offline indicator ahead of long preview text so it stays visible", () => {+ const offlineRow = {+ ...row,+ item: {+ ...row.item,+ display: {+ title: "Demo",+ preview:+ "A very long preview that would otherwise hide connection status",+ },+ },+ };+ mount(PluginDirectoryView, {+ ...directory(),+ items: [offlineRow],+ isOnline: () => false,+ });+ expect(bridge.props.get("plugins.row.demo").subtitle).toMatch(+ /^plugins.notConnected · /,+ );+});++it("renders real Host facts and hides unavailable information", () => {+ const p = {+ row,+ enabled: true,+ online: true,+ busy: false,+ settingsOpen: false,+ model: pluginDetailModel(+ row as any,+ {+ ...row.item,+ blocks: [+ {+ id: "capabilities",+ data: {+ tools: [{ name: "calendar_events", description: "Read events" }],+ },+ },+ { id: "about", fallbackMarkdown: "Full plugin introduction" },+ { id: "version", fallbackMarkdown: "2.3.0" },+ ],+ } as any,+ true,+ false,+ false,+ ),+ onEnabledChange: vi.fn(),+ onOpen: vi.fn(),+ onNewTask: vi.fn(),+ onChooseTask: vi.fn(),+ onSettings: vi.fn(),+ onResolveStatus: vi.fn(),+ };+ const { container, rerender } = mount(PluginDetailView, p);+ expect(+ container.querySelector('[data-testid="plugins.tools"]')?.textContent,+ ).toContain("calendar_events");+ expect(container.textContent).not.toContain("Read events");+ expect(+ container.querySelector('[data-testid="plugins.toolsDisclosure"]'),+ ).toBeNull();+ expect(+ container.querySelector(+ '[data-testid="plugins.tools"] [data-native="DisclosureGroup"]',+ ),+ ).toBeNull();+ expect(container.textContent).not.toContain("plugins.detail.taskHint");+ expect(+ container.querySelector(+ '[data-testid="plugins.tools"] [data-native="Divider"]',+ ),+ ).toBeNull();+ expect(+ container.querySelectorAll(+ '[data-testid="plugins.metadata"] [data-native="Divider"]',+ ),+ ).toHaveLength(1);+ expect(bridge.props.get("plugins.identity").modifiers).toContainEqual({+ listRowInsets: { leading: 20, trailing: 20, top: 8, bottom: 16 },+ });+ expect(bridge.props.get("plugins.enabled").modifiers).toContainEqual({+ scaleEffect: { x: 48 / 61, y: 24 / 28 },+ });+ expect(bridge.props.get("plugins.enabled").modifiers).toContainEqual({+ frame: { width: 56, height: 44 },+ });+ expect(+ container.querySelector('[data-testid="plugins.identity"]')?.textContent,+ ).toContain("Full plugin introduction");+ expect(+ container.querySelector('[data-testid="plugins.metadata"]')?.textContent,+ ).toContain("2.3.0");+ expect(+ container.querySelector('[data-testid="plugins.permissions"]'),+ ).toBeNull();+ expect(container.textContent).not.toContain(+ "plugins.detail.detailsUnavailable",+ );+ const manyTools = {+ ...p,+ model: {+ ...p.model,+ tools: [+ { name: "first_tool", description: "Hidden first description" },+ { name: "second_tool", description: "Hidden second description" },+ { name: "third_tool", description: "Hidden third description" },+ ],+ },+ };+ rerender(manyTools);+ expect(container.textContent).toContain("first_tool");+ expect(container.textContent).toContain("second_tool");+ expect(container.textContent).toContain("third_tool");+ act(() =>+ bridge.props.get("plugins.toolChipsFlow").onLayout({+ nativeEvent: { layout: { width: 334, height: 64 } },+ }),+ );+ expect(+ container.querySelector('[data-testid="plugins.toolsDisclosure"]'),+ ).toBeNull();+ act(() => {+ bridge.props.get("plugins.toolChipsFlow").onLayout({+ nativeEvent: { layout: { width: 200, height: 100 } },+ });+ bridge.props.get("plugins.toolChip.2").onLayout({+ nativeEvent: { layout: { y: 72, height: 28 } },+ });+ });+ expect(+ bridge.props.get("plugins.toolChip.2").accessibilityElementsHidden,+ ).toBe(true);+ expect(container.textContent).toContain("plugins.detail.showAll");+ act(() => bridge.props.get("plugins.toolsDisclosure").onPress());+ expect(container.textContent).toContain("third_tool");+ expect(container.textContent).toContain("plugins.detail.showLess");+ expect(+ bridge.props.get("plugins.toolChip.2").accessibilityElementsHidden,+ ).toBe(false);+ expect(container.textContent).not.toContain("Hidden third description");+ act(() => bridge.props.get("plugins.toolsDisclosure").onPress());+ expect(container.textContent).toContain("third_tool");+ act(() => bridge.props.get("plugins.toolsDisclosure").onPress());+ rerender({ ...manyTools, row: { ...p.row, key: "another-plugin" } });+ expect(container.textContent).toContain("third_tool");+ expect(container.textContent).toContain("plugins.detail.showAll");+ rerender({+ ...p,+ model: { ...p.model, tools: manyTools.model.tools.slice(0, 2) },+ });+ act(() =>+ bridge.props.get("plugins.toolChipsFlow").onLayout({+ nativeEvent: { layout: { width: 334, height: 28 } },+ }),+ );+ expect(+ container.querySelector('[data-testid="plugins.toolsDisclosure"]'),+ ).toBeNull();+ for (const empty of [undefined, []]) {+ rerender({ ...p, model: { ...p.model, tools: empty, permissions: empty } });+ expect(container.querySelector('[data-testid="plugins.tools"]')).toBeNull();+ expect(+ container.querySelector('[data-testid="plugins.permissions"]'),+ ).toBeNull();+ expect(container.textContent).toContain("v2.3.0");+ }+ rerender({+ ...p,+ model: {+ ...p.model,+ details: [+ { key: "author", title: "Author", value: " " },+ { key: "version", title: "Version", value: "v2.3.0" },+ ],+ permissions: [{ title: "Network", description: "" }],+ },+ });+ expect(+ container.querySelector('[data-testid="plugins.fact.author"]'),+ ).toBeNull();+ expect(+ container.querySelector('[data-testid="plugins.fact.version"]')+ ?.textContent,+ ).toContain("v2.3.0");+ expect(+ container.querySelector('[data-testid="plugins.permissions"]')?.textContent,+ ).toContain("Network");+ expect(container.textContent).not.toContain("plugins.detail.noDescription");+ rerender({ ...p, model: { ...p.model, details: [], hasSettings: false } });+ expect(+ container.querySelector('[data-testid="plugins.metadata"]'),+ ).toBeNull();+});++function taskPickerProps() {+ return {+ deviceId: "mac",+ visible: true,+ query: "",+ rows: [+ {+ id: "calendar-task",+ title: "Calendar planning",+ preview: "Real task preview",+ },+ { id: "other-task", title: "Other work" },+ ] as any,+ loading: false,+ error: false,+ onChangeQuery: vi.fn(),+ onRetry: vi.fn(),+ onClose: vi.fn(),+ onSelect: vi.fn(),+ };+}+it.each(["light", "dark"] as const)(+ "uses native task search and rows in %s and navigates after sheet dismissal",+ (mode) => {+ bridge.mode = mode;+ const p = taskPickerProps();+ const { container, rerender } = mount(PluginTaskPickerView, p);+ expect(bridge.props.get("plugins.taskPicker").nativeContent).toBe(true);+ expect(bridge.props.get("plugins.taskPicker").nativeList).toBe(true);+ expect(bridge.props.get("plugins.taskSearch").modifiers).toContainEqual({+ textFieldStyle: "plain",+ });+ expect(+ container+ .querySelector('[data-testid="plugins.taskSearch"]')+ ?.getAttribute("data-native"),+ ).toBe("TextField");+ act(() => bridge.props.get("plugins.taskSearch").onTextChange("calendar"));+ expect(p.onChangeQuery).toHaveBeenCalledWith("calendar");+ rerender({ ...p, query: "calendar" });+ expect(container.textContent).toContain("Calendar planning");+ expect(container.textContent).not.toContain("Other work");+ act(() => bridge.props.get("plugins.clearTaskSearch").onPress());+ expect(p.onChangeQuery).toHaveBeenLastCalledWith("");+ act(() => bridge.props.get("plugins.task.calendar-task").onPress());+ expect(p.onClose).toHaveBeenCalledOnce();+ expect(p.onSelect).not.toHaveBeenCalled();+ rerender({ ...p, visible: false });+ act(() => bridge.props.get("plugins.taskPicker").onClosed());+ expect(p.onSelect).toHaveBeenCalledExactlyOnceWith("calendar-task");+ act(() => bridge.props.get("plugins.taskPicker").onClosed());+ expect(p.onSelect).toHaveBeenCalledOnce();+ },+);+it("distinguishes loading, retry, empty tasks and search results without selecting on dismissal", () => {+ const p = taskPickerProps();+ const { container, rerender } = mount(PluginTaskPickerView, {+ ...p,+ loading: true,+ });+ expect(+ container.querySelector('[data-testid="plugins.tasksLoading"]'),+ ).not.toBeNull();+ expect(container.textContent).not.toContain("Calendar planning");+ rerender({ ...p, error: true });+ act(() => bridge.props.get("plugins.retryTasks").onPress());+ expect(p.onRetry).toHaveBeenCalledOnce();+ rerender({ ...p, rows: [] });+ expect(container.textContent).toContain("plugins.noTasks");+ rerender({ ...p, query: "missing" });+ expect(container.textContent).toContain("plugins.noMatchingTasks");+ act(() => bridge.props.get("plugins.taskPicker").onClose());+ act(() => bridge.props.get("plugins.taskPicker").onClosed());+ expect(p.onSelect).not.toHaveBeenCalled();+});+it("drops a pending task selection if the owner or plugin changes during dismissal", () => {+ const p = taskPickerProps();+ const { rerender } = mount(PluginTaskPickerView, p);+ act(() => bridge.props.get("plugins.task.calendar-task").onPress());+ bridge.ownerCurrent = false;+ act(() => bridge.props.get("plugins.taskPicker").onClosed());+ expect(p.onSelect).not.toHaveBeenCalled();+ bridge.ownerCurrent = true;+ act(() => bridge.props.get("plugins.task.calendar-task").onPress());+ rerender({ ...p, deviceId: "other-computer" });+ act(() => bridge.props.get("plugins.taskPicker").onClosed());+ expect(p.onSelect).not.toHaveBeenCalled();+});++it("shows Android task search empty results and restores the matching tasks", () => {+ const p = taskPickerProps();+ const { container, rerender } = mount(AndroidTaskPickerView, {+ ...p,+ query: "missing",+ });+ expect(container.textContent).toContain("plugins.noMatchingTasks");+ expect(container.textContent).not.toContain("Calendar planning");+ rerender({ ...p, query: "Calendar" });+ expect(container.textContent).toContain("Calendar planning");+ expect(container.textContent).not.toContain("plugins.noMatchingTasks");+ rerender({ ...p, rows: [] });+ expect(container.textContent).toContain("plugins.noTasks");+});diff --git a/apps/mobile/src/__tests__/pluginsScreen.test.tsx b/apps/mobile/src/__tests__/pluginsScreen.test.tsxnew file mode 100644index 0000000000..1f46d5feef--- /dev/null+++ b/apps/mobile/src/__tests__/pluginsScreen.test.tsx@@ -0,0 +1,692 @@+// @vitest-environment jsdom+import { act, createElement } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import PluginsScreen from "@/plugins/PluginsScreen";++const fixture = vi.hoisted(() => ({+ props: new Map<string, any>(),+ enabled: true,+ online: true,+ focused: true,+ owner: true,+ invoke: vi.fn(),+ read: vi.fn(),+ refresh: vi.fn(),+ alert: vi.fn(),+ push: vi.fn(),+ blocks: [] as any[],+ extraRows: [] as any[],+ devicesFailed: false,+ devicesAbsent: false,+ platform: "ios",+ storage: new Map<string, string>(),+ getStored: vi.fn(),+ setStored: vi.fn(),+}));+vi.mock("react-native", async () => {+ const React = await import("react");+ const view = ({ children }: any) =>+ React.createElement("div", null, children);+ return {+ ActivityIndicator: view,+ Alert: { alert: fixture.alert },+ BackHandler: { addEventListener: () => ({ remove() {} }) },+ Image: view,+ Pressable: view,+ RefreshControl: view,+ ScrollView: view,+ View: view,+ Platform: {+ get OS() {+ return fixture.platform;+ },+ },+ StyleSheet: { create: (s: any) => s, hairlineWidth: 1 },+ useWindowDimensions: () => ({ width: 390 }),+ };+});+vi.mock("react-native-safe-area-context", async () => ({+ SafeAreaView: ({ children }: any) => createElement("div", null, children),+}));+vi.mock("expo-router", () => ({+ Stack: {+ Screen: (p: any) => {+ fixture.props.set("stack", p.options);+ return null;+ },+ },+ useIsFocused: () => fixture.focused,+ useLocalSearchParams: () => ({}),+ useRouter: () => ({ push: fixture.push }),+}));+vi.mock("@/utils/backGuard", () => ({ goBackGuarded: vi.fn() }));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key, i18n: { language: "en" } }),+}));+vi.mock("lucide-react-native", () =>+ Object.fromEntries(+ ["ChevronDown", "ChevronRight", "Info", "Monitor", "Puzzle", "Search"].map(+ (key) => [key, () => null],+ ),+ ),+);+vi.mock("@/components/AppText", () => ({+ Text: ({ children }: any) => createElement("span", null, children),+ TextInput: () => null,+}));+vi.mock("@/auth/AuthContext", () => ({+ useAuth: () => ({ accountGeneration: 0, apiFetch: vi.fn() }),+}));+vi.mock("@/auth/authOwnerGeneration", () => ({+ getMobileAuthOwner: () => ({ accountKey: "demo" }),+ isMobileAuthOwnerCurrent: () => fixture.owner,+}));+vi.mock("@/device-link/DeviceLinkContext", () => ({+ useDeviceLink: () => ({ invoke: vi.fn() }),+}));+vi.mock("@/device-link/useDeviceManagement", () => ({+ useDeviceManagement: () => ({+ error: fixture.devicesFailed ? "throttled" : null,+ loading: false,+ devices:+ fixture.devicesFailed || fixture.devicesAbsent+ ? []+ : [+ {+ deviceId: "mac",+ name: "Mac",+ platform: "darwin",+ remoteControlEnabled: true,+ },+ ],+ refresh() {},+ }),+}));+const row = () => ({+ key: "mac:plugin",+ host: { deviceId: "mac", deviceName: "Mac" },+ item: {+ ref: { collectionId: "plugins", kind: "plugin", id: "demo" },+ revision: "1",+ display: { title: "Demo" },+ actions: [{ id: fixture.enabled ? "disable" : "enable", label: "Enabled" }],+ },+});+vi.mock("@/device-link/remoteResources", () => ({+ getRemoteResource: (...args: any[]) => fixture.read(...args),+}));+vi.mock("@/session/useRemoteResourceList", () => ({+ useRemoteResourceList: () => ({+ items:+ fixture.devicesFailed || fixture.devicesAbsent+ ? []+ : [...fixture.extraRows, row()],+ error: fixture.devicesFailed || fixture.devicesAbsent ? "noHosts" : null,+ loading: false,+ isOnline: () => fixture.online,+ refresh: fixture.refresh,+ }),+}));+vi.mock("@/theme", async () => {+ const tokens = await import("@/theme/tokens");+ return {+ ...tokens,+ useTheme: () => ({ colors: tokens.lightColors }),+ useThemedStyles: (factory: any) => factory(tokens.lightColors),+ };+});+vi.mock("@react-native-async-storage/async-storage", () => ({+ default: {+ getItem: (...args: any[]) => fixture.getStored(...args),+ setItem: (...args: any[]) => fixture.setStored(...args),+ },+}));+vi.mock("@/platform/chrome/SimpleStackHeader", () => ({+ simpleScreenSafeAreaEdges: () => [],+ SimpleStackHeader: (p: any) => {+ fixture.props.set("header", p);+ return null;+ },+}));+vi.mock("@/platform/chrome/NativeSwitch", () => ({+ NativeSwitch: (p: any) => {+ fixture.props.set("switch", p);+ return null;+ },+}));+vi.mock("@/plugins/PluginDirectoryView", () => ({+ PluginDirectoryView: (p: any) => {+ fixture.props.set("directory", p);+ return null;+ },+}));+vi.mock("@/plugins/PluginDetailView", () => ({+ PluginDetailView: (p: any) => {+ fixture.props.set("detail", p);+ return null;+ },+}));+vi.mock("@/plugins/PluginTaskPicker", () => ({+ PluginTaskPicker: (p: any) => {+ fixture.props.set("taskPicker", p);+ return null;+ },+}));+vi.mock("@/plugins/PluginPage", () => ({ PluginPage: () => null }));+vi.mock("@/plugins/pluginClient", () => ({+ invokePlugin: (...args: any[]) => fixture.invoke(...args),+}));+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+let root: ReturnType<typeof createRoot>;+beforeEach(() => {+ fixture.props.clear();+ fixture.storage.clear();+ fixture.getStored+ .mockReset()+ .mockImplementation(+ async (key: string) => fixture.storage.get(key) ?? null,+ );+ fixture.setStored+ .mockReset()+ .mockImplementation(async (key: string, value: string) => {+ fixture.storage.set(key, value);+ });+ fixture.blocks = [];+ fixture.extraRows = [];+ fixture.devicesFailed = false;+ fixture.devicesAbsent = false;+ fixture.push.mockClear();+ fixture.enabled = true;+ fixture.online = true;+ fixture.focused = true;+ fixture.owner = true;+ fixture.platform = "ios";+ fixture.invoke+ .mockReset()+ .mockImplementation(async (_invoke, _device, _plugin, action) => {+ fixture.enabled = action === "enable";+ });+ fixture.read.mockReset().mockImplementation(async () => ({+ ...row().item,+ blocks: fixture.blocks,+ }));+ fixture.refresh.mockReset().mockResolvedValue(undefined);+ fixture.alert.mockClear();+ root = createRoot(document.createElement("div"));+});+afterEach(() => act(() => root.unmount()));+async function openDetail() {+ await act(async () => root.render(createElement(PluginsScreen)));+ await act(async () => fixture.props.get("directory").onDetail(row()));+}+it("reads selected plugin details when its computer comes online", async () => {+ fixture.online = false;+ fixture.blocks = [+ {+ id: "capabilities",+ primitive: "plugin-capabilities",+ data: { tools: [{ name: "restored_tool" }] },+ },+ ];+ await openDetail();+ expect(fixture.read).not.toHaveBeenCalled();+ expect(fixture.props.get("detail").model.status).toBe("offline");+ fixture.online = true;+ await act(async () => root.render(createElement(PluginsScreen)));+ expect(fixture.read).toHaveBeenCalledTimes(1);+ expect(fixture.props.get("detail").model.tools).toEqual([+ { name: "restored_tool", description: "" },+ ]);+ await act(async () => root.render(createElement(PluginsScreen)));+ expect(fixture.read).toHaveBeenCalledTimes(1);+});+it("uses UIKit search to filter and clear without replaying JS text into native input", async () => {+ await act(async () => root.render(createElement(PluginsScreen)));+ const search = fixture.props.get("stack").headerSearchBarOptions;+ expect(search).toMatchObject({+ placement: "stacked",+ hideWhenScrolling: false,+ });+ const setText = vi.fn();+ search.ref.current = { setText };+ expect(setText).toHaveBeenCalledWith("");+ setText.mockClear();+ await act(async () =>+ search.onChangeText({ nativeEvent: { text: "No match" } }),+ );+ expect(fixture.props.get("directory").items).toEqual([]);+ expect(setText).not.toHaveBeenCalled();+ await act(async () => search.onChangeText({ nativeEvent: { text: "Demo" } }));+ expect(fixture.props.get("directory").items).toHaveLength(1);+ await act(async () => fixture.props.get("directory").onDetail(row()));+ expect(fixture.props.get("stack").headerSearchBarOptions).toBeUndefined();+ search.ref.current = null;+ act(() => fixture.props.get("header").onBack());+ const restored = fixture.props.get("stack").headerSearchBarOptions;+ restored.ref.current = { setText };+ expect(setText).toHaveBeenLastCalledWith("Demo");+ await act(async () => restored.onCancelButtonPress());+ expect(fixture.props.get("directory").query).toBe("");+});+it("keeps details open and reflects confirmed off/on host states", async () => {+ await openDetail();+ expect(fixture.props.get("detail").enabled).toBe(true);+ await act(async () => fixture.props.get("detail").onEnabledChange(false));+ expect(fixture.invoke).toHaveBeenLastCalledWith(+ expect.anything(),+ "mac",+ "demo",+ "disable",+ );+ expect(fixture.props.get("detail")).toMatchObject({+ enabled: false,+ busy: false,+ });+ await act(async () => fixture.props.get("detail").onEnabledChange(true));+ expect(fixture.props.get("detail")).toMatchObject({+ enabled: true,+ busy: false,+ });+ expect(fixture.refresh).toHaveBeenCalledTimes(2);+});+it("refreshes existing details after its computer reconnects", async () => {+ await openDetail();+ fixture.online = false;+ await act(async () => root.render(createElement(PluginsScreen)));+ expect(fixture.props.get("detail").model.status).toBe("offline");+ fixture.enabled = false;+ fixture.online = true;+ await act(async () => root.render(createElement(PluginsScreen)));+ expect(fixture.read).toHaveBeenCalledTimes(2);+ expect(fixture.props.get("detail")).toMatchObject({+ enabled: false,+ model: { status: "disabled", canUseTasks: false },+ });+ await act(async () => root.render(createElement(PluginsScreen)));+ expect(fixture.read).toHaveBeenCalledTimes(2);+ expect(fixture.invoke).not.toHaveBeenCalled();+});+it("retries failed details on reconnect without replaying writes", async () => {+ fixture.read.mockRejectedValueOnce(new Error("disconnected"));+ await openDetail();+ expect(fixture.props.get("detail").model.status).toBe("loadFailed");+ fixture.online = false;+ await act(async () => root.render(createElement(PluginsScreen)));+ fixture.online = true;+ await act(async () => root.render(createElement(PluginsScreen)));+ expect(fixture.read).toHaveBeenCalledTimes(2);+ expect(fixture.props.get("detail").model.canUseTasks).toBe(true);+ expect(fixture.invoke).not.toHaveBeenCalled();+});+it("ignores a pre-disconnect read that settles after the reconnect read", async () => {+ let finishOldRead!: (resource: any) => void;+ const stale = row().item;+ fixture.read.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishOldRead = resolve;+ }),+ );+ await openDetail();+ expect(fixture.props.get("detail").busy).toBe(true);+ fixture.online = false;+ await act(async () => root.render(createElement(PluginsScreen)));+ fixture.enabled = false;+ fixture.online = true;+ await act(async () => root.render(createElement(PluginsScreen)));+ expect(fixture.read).toHaveBeenCalledTimes(2);+ expect(fixture.props.get("detail").enabled).toBe(false);+ await act(async () => finishOldRead(stale));+ expect(fixture.props.get("detail")).toMatchObject({+ enabled: false,+ busy: false,+ model: { status: "disabled" },+ });+});+it("marks details unconfirmed when a successful state change cannot be read back", async () => {+ await openDetail();+ fixture.read.mockRejectedValueOnce(new Error("read unavailable"));+ await act(async () => fixture.props.get("detail").onEnabledChange(false));+ expect(fixture.enabled).toBe(false);+ expect(fixture.props.get("detail")).toMatchObject({+ busy: false,+ model: {+ status: "loadFailed",+ statusAction: "retry",+ canUseTasks: false,+ canToggle: false,+ },+ });+ expect(fixture.alert).not.toHaveBeenCalled();+ await act(async () => fixture.props.get("detail").onNewTask());+ await act(async () => fixture.props.get("detail").onChooseTask());+ await act(async () => fixture.props.get("detail").onEnabledChange(false));+ expect(fixture.push).not.toHaveBeenCalled();+ expect(fixture.invoke).toHaveBeenCalledTimes(1);+ await act(async () => fixture.props.get("detail").onResolveStatus());+ expect(fixture.props.get("detail")).toMatchObject({+ enabled: false,+ model: { status: "disabled" },+ });+ expect(fixture.invoke).toHaveBeenCalledTimes(1);+});+it.each(["reconnect", "return"])(+ "confirms a pending state change after %s without an overlapping automatic read",+ async (event) => {+ await openDetail();+ let finishWrite!: () => void;+ fixture.invoke.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finishWrite = () => {+ fixture.enabled = false;+ resolve();+ };+ }),+ );+ act(() => fixture.props.get("detail").onEnabledChange(false));+ if (event === "reconnect") fixture.online = false;+ else fixture.focused = false;+ await act(async () => root.render(createElement(PluginsScreen)));+ fixture.online = true;+ fixture.focused = true;+ await act(async () => root.render(createElement(PluginsScreen)));+ expect(fixture.read).toHaveBeenCalledTimes(1);+ await act(async () => finishWrite());+ expect(fixture.read).toHaveBeenCalledTimes(2);+ expect(fixture.invoke).toHaveBeenCalledTimes(1);+ expect(fixture.props.get("detail")).toMatchObject({+ enabled: false,+ busy: false,+ model: { status: "disabled", canUseTasks: false },+ });+ await act(async () => root.render(createElement(PluginsScreen)));+ expect(fixture.read).toHaveBeenCalledTimes(2);+ },+);+it.each(["reconnect", "return"])(+ "confirms Host state when the write reply fails after %s",+ async (event) => {+ await openDetail();+ let failReply!: () => void;+ fixture.invoke.mockImplementationOnce(+ () =>+ new Promise<void>((_resolve, reject) => {+ failReply = () => {+ fixture.enabled = false;+ reject(new Error("reply timed out after Host applied the action"));+ };+ }),+ );+ act(() => fixture.props.get("detail").onEnabledChange(false));+ if (event === "reconnect") fixture.online = false;+ else fixture.focused = false;+ await act(async () => root.render(createElement(PluginsScreen)));+ fixture.online = true;+ fixture.focused = true;+ await act(async () => root.render(createElement(PluginsScreen)));+ expect(fixture.read).toHaveBeenCalledTimes(1);+ await act(async () => failReply());+ expect(fixture.read).toHaveBeenCalledTimes(2);+ expect(fixture.props.get("detail")).toMatchObject({+ enabled: false,+ busy: false,+ model: { status: "disabled", canUseTasks: false },+ });+ expect(fixture.invoke).toHaveBeenCalledTimes(1);+ expect(fixture.alert).toHaveBeenCalledWith("plugins.actionFailed");+ },+);+it("offers only a read retry when both the write reply and confirmation read fail", async () => {+ await openDetail();+ fixture.invoke.mockImplementationOnce(async () => {+ fixture.enabled = false;+ throw new Error("reply timed out");+ });+ fixture.read.mockRejectedValueOnce(new Error("read unavailable"));+ await act(async () => fixture.props.get("detail").onEnabledChange(false));+ expect(fixture.props.get("detail").model).toMatchObject({+ status: "loadFailed",+ statusAction: "retry",+ canUseTasks: false,+ canToggle: false,+ });+ await act(async () => fixture.props.get("detail").onResolveStatus());+ expect(fixture.props.get("detail").enabled).toBe(false);+ expect(fixture.invoke).toHaveBeenCalledTimes(1);+});+it("locks duplicate taps, and a rejected write keeps the previous state without replay", async () => {+ await openDetail();+ let reject!: (error: Error) => void;+ fixture.invoke.mockImplementation(+ () =>+ new Promise((_resolve, fail) => {+ reject = fail;+ }),+ );+ act(() => {+ fixture.props.get("detail").onEnabledChange(false);+ fixture.props.get("detail").onEnabledChange(false);+ });+ expect(fixture.invoke).toHaveBeenCalledTimes(1);+ expect(fixture.props.get("detail").busy).toBe(true);+ await act(async () => reject(new Error("offline")));+ expect(fixture.props.get("detail")).toMatchObject({+ enabled: true,+ busy: false,+ });+ expect(fixture.alert).toHaveBeenCalledWith("plugins.actionFailed");+ expect(fixture.invoke).toHaveBeenCalledTimes(1);+});+it("does not change a plugin when its computer is offline", async () => {+ fixture.online = false;+ await openDetail();+ await act(async () => fixture.props.get("detail").onEnabledChange(false));+ expect(fixture.invoke).not.toHaveBeenCalled();+ expect(fixture.read).not.toHaveBeenCalled();+});+it("opens cached details for an offline row without sending a read or an action", async () => {+ fixture.online = false;+ await act(async () => root.render(createElement(PluginsScreen)));+ await act(async () => fixture.props.get("directory").onOpen(row()));+ const detail = fixture.props.get("detail");+ expect(detail.model).toMatchObject({+ status: "offline",+ statusAction: "connect",+ canUseTasks: false,+ canToggle: false,+ });+ expect(detail.busy).toBe(false);+ expect(fixture.read).not.toHaveBeenCalled();+ expect(fixture.invoke).not.toHaveBeenCalled();+ expect(fixture.alert).not.toHaveBeenCalled();+});+it("waits for the initial detail read before allowing a state change", async () => {+ let resolve!: (resource: any) => void;+ fixture.read.mockImplementation(+ () =>+ new Promise((done) => {+ resolve = done;+ }),+ );+ await openDetail();+ expect(fixture.props.get("detail").busy).toBe(true);+ await act(async () => fixture.props.get("detail").onEnabledChange(false));+ expect(fixture.invoke).not.toHaveBeenCalled();+ await act(async () => resolve({ ...row().item, blocks: fixture.blocks }));+ expect(fixture.props.get("detail").busy).toBe(false);+});+it("does not reopen details after the user has returned to the list", async () => {+ await openDetail();+ let resolve!: () => void;+ fixture.invoke.mockImplementation(+ () =>+ new Promise<void>((done) => {+ resolve = done;+ }),+ );+ act(() => fixture.props.get("detail").onEnabledChange(false));+ act(() => fixture.props.get("header").onBack());+ fixture.props.delete("detail");+ await act(async () => resolve());+ expect(fixture.props.has("detail")).toBe(false);+});+it("keeps the same confirmed switch behavior on Android", async () => {+ fixture.platform = "android";+ // The directory's RN row is not needed to exercise this via a native mock. It is+ // rendered before the platform switch, then details re-render on Android.+ fixture.platform = "ios";+ await openDetail();+ fixture.platform = "android";+ await act(async () => fixture.props.get("detail").onEnabledChange(false));+ expect(fixture.props.get("detail")).toMatchObject({+ enabled: false,+ busy: false,+ });+});+it("keeps plugin task preferences on PC instead of mounting a mobile form", async () => {+ fixture.blocks = [{ id: "capabilities", data: { tasks: true } }];+ await openDetail();+ expect(fixture.props.get("detail").children).toBeUndefined();+ expect(fixture.props.get("detail").settingsOpen).toBe(false);+ expect(fixture.props.get("detail").row.item.ref.id).toBe("demo");+});+it("guards both task callbacks offline and disabled, including stale native callbacks", async () => {+ fixture.online = false;+ await openDetail();+ act(() => fixture.props.get("detail").onNewTask());+ act(() => fixture.props.get("detail").onChooseTask());+ expect(fixture.push).not.toHaveBeenCalled();+ expect(fixture.props.get("detail").model.canUseTasks).toBe(false);+ fixture.online = true;+ fixture.enabled = false;+ await act(async () => fixture.props.get("directory").onDetail(row()));+ act(() => fixture.props.get("detail").onNewTask());+ expect(fixture.push).not.toHaveBeenCalled();+ await act(async () => fixture.props.get("detail").onResolveStatus());+ expect(fixture.props.get("detail").model.canUseTasks).toBe(true);+});+it("shows a recoverable detail read failure and retries reads without issuing writes", async () => {+ fixture.read.mockRejectedValueOnce(new Error("disconnected"));+ await openDetail();+ expect(fixture.props.get("detail").model).toMatchObject({+ status: "loadFailed",+ statusAction: "retry",+ });+ await act(async () => fixture.props.get("detail").onResolveStatus());+ expect(fixture.props.get("detail").model.canUseTasks).toBe(true);+ expect(fixture.invoke).not.toHaveBeenCalled();+});++it("records a task usage entry but never a details-only visit", async () => {+ await openDetail();+ expect(fixture.setStored).not.toHaveBeenCalled();+ await act(async () => fixture.props.get("detail").onNewTask());+ expect(fixture.setStored).toHaveBeenCalledWith(+ "cindy.pluginRecent.v1.demo",+ JSON.stringify(["mac:plugin"]),+ );+});+it("really moves a used plugin above an earlier row and restores that order on remount", async () => {+ fixture.extraRows = [+ {+ ...row(),+ key: "mac:earlier",+ item: {+ ...row().item,+ ref: { ...row().item.ref, id: "earlier" },+ display: { title: "Earlier" },+ },+ },+ ];+ await act(async () => root.render(createElement(PluginsScreen)));+ expect(fixture.props.get("directory").items.map((i: any) => i.key)).toEqual([+ "mac:earlier",+ "mac:plugin",+ ]);+ await act(async () => fixture.props.get("directory").onDetail(row()));+ act(() => fixture.props.get("header").onBack());+ expect(fixture.props.get("directory").items[0].key).toBe("mac:earlier");+ await act(async () => fixture.props.get("directory").onDetail(row()));+ await act(async () => fixture.props.get("detail").onNewTask());+ act(() => fixture.props.get("header").onBack());+ expect(fixture.props.get("directory").items.map((i: any) => i.key)).toEqual([+ "mac:plugin",+ "mac:earlier",+ ]);+ act(() => root.render(null));+ await act(async () => root.render(createElement(PluginsScreen)));+ expect(fixture.props.get("directory").items[0].key).toBe("mac:plugin");+});++it("shows a failed computer lookup as an error, suppressing misleading sort notices", async () => {+ fixture.devicesFailed = true;+ await act(async () => root.render(createElement(PluginsScreen)));+ expect(fixture.props.get("directory")).toMatchObject({+ targets: [],+ error: true,+ loading: false,+ });+});+it("keeps the shared no-host message as an empty state when the computer lookup succeeds", async () => {+ fixture.devicesAbsent = true;+ await act(async () => root.render(createElement(PluginsScreen)));+ expect(fixture.props.get("directory")).toMatchObject({+ targets: [],+ items: [],+ error: false,+ loading: false,+ });+});++it("guides setup to PC without opening configuration or creating a task", async () => {+ fixture.blocks = [+ {+ id: "capabilities",+ data: {+ usage: {+ taskUsable: true,+ hasSettings: true,+ approvalRequired: false,+ builtin: false,+ retired: false,+ setup: {+ state: "required",+ missing: ["Calendar account"],+ expired: [],+ },+ },+ },+ },+ ];+ await openDetail();+ const detail = fixture.props.get("detail");+ expect(detail.model.status).toBe("setupRequired");+ expect(detail.children).toBeUndefined();+ await act(async () => detail.onResolveStatus());+ expect(fixture.alert).toHaveBeenCalledWith("plugins.detail.computerSettings");+ expect(fixture.push).not.toHaveBeenCalled();+ expect(fixture.invoke).not.toHaveBeenCalled();+});++it("records recent use when choosing an existing task", async () => {+ await openDetail();+ await act(async () => fixture.props.get("detail").onChooseTask());+ await act(async () =>+ fixture.props.get("taskPicker").onSelect("existing-task"),+ );+ expect(fixture.push).toHaveBeenCalledWith(+ expect.objectContaining({+ pathname: "/sessions/[sessionId]",+ params: expect.objectContaining({+ sessionId: "existing-task",+ deviceId: "mac",+ }),+ }),+ );+ expect(fixture.setStored).toHaveBeenCalledWith(+ "cindy.pluginRecent.v1.demo",+ JSON.stringify(["mac:plugin"]),+ );+});diff --git a/apps/mobile/src/__tests__/visualMock.test.ts b/apps/mobile/src/__tests__/visualMock.test.tsindex d4dba2ae00..5ebf6d586e 100644--- a/apps/mobile/src/__tests__/visualMock.test.ts+++ b/apps/mobile/src/__tests__/visualMock.test.ts@@ -1,5 +1,7 @@import { afterEach, beforeEach, expect, it, vi } from 'vitest';-import type { DeviceView } from '@cindy/device-link';+import { PLUGIN_COLLECTION, type DeviceView } from '@cindy/device-link';+import { getRemoteResource, listRemoteCollection, normalizeRemoteCollectionItems } from '@/device-link/remoteResources';+import { invokePlugin } from '@/plugins/pluginClient';import { projectHistoryView } from '@cindy/maker-shared/message-window';import type { RemoteMessage } from '@/session/types';@@ -12,6 +14,33 @@ vi.mock('@/session/remoteSessionStore', () => ({ remoteSessionStore: {beforeEach(() => { vi.resetModules(); config.MOBILE_VISUAL_MOCK_REALDATA_URL = ''; });afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); vi.restoreAllMocks(); vi.clearAllMocks(); });+it('supplies valid demo plugin projections and confirms enable/disable through the real client', async () => {+ const mock = await import('@/debug/visualMock');+ const link = mock.createVisualMockDeviceLinkContext();+ const host = { deviceId: mock.VISUAL_MOCK_DEVICE_ID, deviceName: mock.VISUAL_MOCK_DEVICE_NAME };+ const items = normalizeRemoteCollectionItems(await listRemoteCollection(link.invoke, host, PLUGIN_COLLECTION), PLUGIN_COLLECTION);+ expect(items).toHaveLength(28);+ expect(items.filter(item => item.display.badges?.length)).toHaveLength(2);+ const ref = items[0].ref;+ await invokePlugin(link.invoke, host.deviceId, ref.id, 'disable');+ expect((await getRemoteResource(link.invoke, host, ref)).actions).toEqual([{ id: 'enable', label: 'Enable', disabled: false }]);+ await invokePlugin(link.invoke, host.deviceId, ref.id, 'enable');+ expect((await getRemoteResource(link.invoke, host, ref)).actions).toEqual([{ id: 'disable', label: 'Disable', disabled: false }]);+ await expect(invokePlugin(link.invoke, host.deviceId, ref.id, 'unexpected')).rejects.toThrow('UNSUPPORTED_DEMO_PLUGIN_ACTION');+});++it('does not add demo plugins to an imported real-data preview', async () => {+ config.MOBILE_VISUAL_MOCK_REALDATA_URL = 'https://fixture.invalid/snapshot.json';+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({+ schema: 'cindy-mobile-visual-realdata-v1', device: { deviceId: 'real-device', name: 'Snapshot' },+ sessions: [], messagesBySession: {},+ }) }));+ const mock = await import('@/debug/visualMock');+ const link = await mock.prepareVisualMockDeviceLinkContext();+ const host = { deviceId: 'real-device', deviceName: 'Snapshot' };+ expect(normalizeRemoteCollectionItems(await listRemoteCollection(link.invoke, host, PLUGIN_COLLECTION), PLUGIN_COLLECTION)).toEqual([]);+});+it('waits for all 1,000 imported tasks before seeding and publishing their device identity', async () => {vi.useFakeTimers();config.MOBILE_VISUAL_MOCK_REALDATA_URL = 'https://fixture.invalid/snapshot.json';@@ -192,3 +221,24 @@ it('persists a renamed fixture in later directory reads', async () => {)?.name,).toBe('Office Mac');});+it('returns task preferences through the same action result envelope as the real Host', async () => {+ const { pluginVisualFixture } = await import('@/debug/pluginVisualFixture');+ const { REMOTE_RESOURCE_INVOKE_CHANNEL } = await import('@cindy/device-link');+ expect(pluginVisualFixture(REMOTE_RESOURCE_INVOKE_CHANNEL, [{+ resourceRef: { collectionId: 'plugins', id: '8' }, actionId: 'task-settings:get',+ }])).toMatchObject({ effects: [], result: { revision: 'demo-prefs', config: {}, permissionModes: ['ask', 'auto'] } });+});+it('allows preview deep links only for explicit development visual mock fixtures', async () => {+ const { pluginVisualPreview } = await import('@/debug/pluginVisualFixture');+ vi.stubGlobal('__DEV__', false);+ vi.stubEnv('EXPO_PUBLIC_CINDY_MOBILE_VISUAL_MOCK', '1');+ expect(pluginVisualPreview('1-settings')).toBeUndefined();+ vi.stubGlobal('__DEV__', true);+ expect(pluginVisualPreview('1-settings')).toEqual({ id: '1', settings: true });+ expect(pluginVisualPreview('real-plugin')).toBeUndefined();+ expect(pluginVisualPreview('99')).toBeUndefined();+ vi.stubEnv('EXPO_PUBLIC_CINDY_MOBILE_VISUAL_MOCK', '0');+ expect(pluginVisualPreview('1')).toBeUndefined();+ vi.unstubAllGlobals();+ vi.unstubAllEnvs();+});diff --git a/apps/mobile/src/debug/pluginVisualFixture.ts b/apps/mobile/src/debug/pluginVisualFixture.tsnew file mode 100644index 0000000000..113dede85e--- /dev/null+++ b/apps/mobile/src/debug/pluginVisualFixture.ts@@ -0,0 +1,564 @@+import {+ PLUGIN_COLLECTION,+ REMOTE_RESOURCE_GET_CHANNEL,+ REMOTE_RESOURCE_INVOKE_CHANNEL,+ REMOTE_RESOURCE_LIST_CHANNEL,+ type RemoteCollectionItem,+ type PluginUsageSummary,+ type PluginConfigurationItem,+} from "@cindy/device-link";+export function pluginVisualDemosEnabled() {+ return (+ typeof __DEV__ !== "undefined" &&+ __DEV__ &&+ (process.env.EXPO_PUBLIC_CINDY_MOBILE_VISUAL_MOCK === "1" ||+ process.env.EXPO_PUBLIC_CINDY_PLUGIN_DEMOS === "1")+ );+}+export interface PluginVisualScenario {+ id: string;+ name: string;+ label: string;+ description: string;+ usage?: PluginUsageSummary;+ taskPreferences?: boolean;+ surface?: "panel" | "settings";+ state?: "offline" | "loading" | "loadFailed";+ disabled?: boolean;+}+const field = (+ id: string,+ label: string,+ kind: PluginConfigurationItem["kind"],+ state: PluginConfigurationItem["state"],+ extra: Partial<PluginConfigurationItem> = {},+): PluginConfigurationItem => ({ id, label, kind, state, ...extra });+const key = (+ state: PluginConfigurationItem["state"],+ id = "secret:api_key",+ label = "API key",+) =>+ field(id, label, "secret", state, {+ hint: "Create an API key in the service console.",+ });+const account = (+ state: PluginConfigurationItem["state"],+ count = 0,+ expiredCount = 0,+) =>+ field("secret:account", "Google account", "oauth", state, {+ count,+ expiredCount,+ });+const connection = (state: PluginConfigurationItem["state"], count = 0) =>+ field("connection:instances", "GitLab instances", "connection", state, {+ count,+ });+const ready = (+ items: PluginConfigurationItem[] = [],+ patch: Partial<PluginUsageSummary> = {},+): PluginUsageSummary => ({+ taskUsable: true,+ hasSettings: items.length > 0,+ approvalRequired: false,+ builtin: false,+ retired: false,+ setup: { state: "ready", missing: [], expired: [] },+ configuration: { items, alternatives: [] },+ ...patch,+});+const required = (+ items: PluginConfigurationItem[],+ alternatives: string[][] = [],+): PluginUsageSummary => ({+ ...ready(items),+ setup: {+ state: "required",+ missing: items.filter((i) => i.state === "missing").map((i) => i.label),+ expired: items.filter((i) => i.state === "expired").map((i) => i.label),+ },+ configuration: { items, alternatives },+});+const search = (configured: boolean) => {+ const items = [+ key(configured ? "configured" : "missing", "secret:brave", "Brave API key"),+ key("missing", "secret:tavily", "Tavily API key"),+ ];+ return {+ ...(configured ? ready(items) : required(items)),+ configuration: { items, alternatives: [["secret:brave", "secret:tavily"]] },+ };+};+// Fictional values matching the Host shape. Production configuration never comes from this fixture.+export const pluginVisualScenarios: PluginVisualScenario[] = [+ {+ id: "0",+ name: "Demo Art",+ label: "Ready · no configuration",+ description:+ "Create images in a task. This demo needs no account or API key.",+ usage: ready(),+ },+ {+ id: "1",+ name: "Demo Calendar",+ label: "Missing API key",+ description: "Look up calendar events with a service API key.",+ usage: required([key("missing")]),+ },+ {+ id: "2",+ name: "Demo Documents",+ label: "Custom parameter · computer editor",+ description: "Index documents from a configured workspace.",+ usage: ready([+ field("kv:workspace", "Workspace", "parameter", "configured"),+ ]),+ },+ {+ id: "3",+ name: "Demo Mail",+ label: "Account expired",+ description:+ "Read mail from your connected account. Reconnect when authorization expires.",+ usage: required([account("expired", 0, 1)]),+ },+ {+ id: "4",+ name: "Demo Notes",+ label: "Disabled · saved configuration retained",+ description: "Disabling retains the saved key.",+ disabled: true,+ usage: ready([key("configured")]),+ },+ {+ id: "5",+ name: "Demo Planner",+ label: "Page only · no task buttons",+ description:+ "Open the planner page. This plugin does not contribute task tools.",+ surface: "panel",+ usage: ready([], { taskUsable: false }),+ },+ {+ id: "6",+ name: "Demo Reading",+ label: "API key saved",+ description: "Search a reading library with a securely saved API key.",+ usage: ready([key("configured")]),+ },+ {+ id: "7",+ name: "Demo Research",+ label: "Configuration status unknown",+ description:+ "The computer could not confirm configuration. Refresh before use.",+ usage: ready([key("unknown")], {+ setup: { state: "unknown", missing: [], expired: [] },+ }),+ },+ {+ id: "8",+ name: "Demo Tasks",+ label: "Task model and permissions",+ description:+ "Create tasks with plugin-specific model and permission preferences.",+ taskPreferences: true,+ usage: ready([], { hasSettings: true }),+ },+ {+ id: "9",+ name: "Demo Translation",+ label: "Host-managed configuration",+ description: "Use the identity managed by the execution computer.",+ usage: ready([+ field("secret:identity", "Organization identity", "managed", "managed"),+ ]),+ },+ {+ id: "10",+ name: "Demo Travel",+ label: "Approval record invalid",+ description:+ "Restore the installed plugin approval on the computer before use.",+ disabled: true,+ usage: ready([], { approvalRequired: true }),+ },+ {+ id: "11",+ name: "Demo Weather",+ label: "Multiple configuration kinds",+ description:+ "A plugin can combine a key, an account and custom parameters.",+ usage: ready([+ key("configured"),+ account("configured", 1),+ field("kv:language", "Output language", "parameter", "configured"),+ ]),+ },+ {+ id: "12",+ name: "Demo Calendar Accounts",+ label: "Connected and expired accounts",+ description:+ "Connected accounts remain usable while another account needs reconnection.",+ usage: ready([account("configured", 2, 1)]),+ },+ {+ id: "13",+ name: "Demo GitLab",+ label: "Multiple connections saved",+ description:+ "Connect to multiple GitLab instances on the execution computer.",+ usage: ready([connection("configured", 2)]),+ },+ {+ id: "14",+ name: "Demo GitLab Setup",+ label: "Connection missing",+ description: "Add a GitLab instance and its token before use.",+ usage: required([connection("missing")]),+ },+ {+ id: "15",+ name: "Demo Web Search",+ label: "Any-of · one alternative configured",+ description:+ "Either search provider is sufficient. The unused key is optional.",+ usage: search(true),+ },+ {+ id: "16",+ name: "Demo Search Setup",+ label: "Any-of · neither configured",+ description: "Configure either search provider to start using the plugin.",+ usage: search(false),+ },+ {+ id: "17",+ name: "Demo Retired Plugin",+ label: "Retired plugin",+ description:+ "Review this retired plugin and its replacement on the computer.",+ usage: ready([], { retired: true }),+ },+ {+ id: "18",+ name: "Demo Built-in Recovery",+ label: "Built-in approval recovery",+ description: "Restart the computer app to restore this built-in plugin.",+ disabled: true,+ usage: ready([], { approvalRequired: true, builtin: true }),+ },+ {+ id: "19",+ name: "Demo Runtime Crash",+ label: "Runtime crashed",+ description:+ "The plugin stopped unexpectedly. The next use is checked by Host.",+ usage: ready([], { runtimeIssue: "crashed" }),+ },+ {+ id: "20",+ name: "Demo Runtime Fuse",+ label: "Runtime fused",+ description: "The computer paused the runtime after repeated failures.",+ usage: ready([], { runtimeIssue: "fused" }),+ },+ {+ id: "21",+ name: "Demo Loading",+ label: "Loading detail",+ description: "Wait while the computer reads this plugin detail.",+ state: "loading",+ usage: ready(),+ },+ {+ id: "22",+ name: "Demo Read Failure",+ label: "Detail read failed · retry",+ description: "Retry reads again; it does not replay a configuration write.",+ state: "loadFailed",+ usage: ready(),+ },+ {+ id: "23",+ name: "Demo Offline",+ label: "Computer offline",+ description:+ "Connect the execution computer before reading or changing the plugin.",+ state: "offline",+ usage: ready(),+ },+ {+ id: "24",+ name: "Demo Older Host",+ label: "Older Host · no status projection",+ description:+ "Older computers preserve task entry without inventing configuration status.",+ },+ {+ id: "25",+ name: "Demo Custom Settings",+ label: "Author-defined mobile editor",+ description:+ "Plugins may supply their own editor for custom non-secret preferences.",+ surface: "settings",+ usage: ready([+ field("kv:language", "Output language", "parameter", "configured"),+ field("kv:format", "Output format", "parameter", "configured"),+ ]),+ },+ {+ id: "26",+ name: "Demo Optional Key",+ label: "Optional key · not a use requirement",+ description:+ "This key is optional. Its missing state must not block task use.",+ usage: ready([key("missing")]),+ },+ {+ id: "27",+ name: "Demo OAuth Setup",+ label: "Account not connected",+ description: "Connect a Google account before using calendar tools.",+ usage: required([account("missing")]),+ },+];+export function pluginVisualScenario(+ deviceId: string | undefined,+ id: string | undefined,+) {+ if (!pluginVisualDemosEnabled() || deviceId !== "cindy-visual-mock-mac")+ return;+ const scenario = pluginVisualScenarios.find((item) => item.id === id);+ return scenario?.state === "loadFailed" && (reads.get(scenario.id) ?? 0) > 1+ ? { ...scenario, state: undefined }+ : scenario;+}+export function pluginVisualPreview(+ value: unknown,+): { id: string; settings: boolean } | undefined {+ if (!pluginVisualDemosEnabled() || typeof value !== "string") return;+ const parts = value.split("-");+ if (+ parts.length > 2 ||+ (parts.length === 2 && parts[1] !== "settings") ||+ !/^[0-9]{1,2}$/.test(parts[0])+ )+ return;+ const id = String(Number(parts[0]));+ if (!pluginVisualScenarios.some((item) => item.id === id)) return;+ return { id, settings: parts.length === 2 };+}+const enabled = new Map(+ pluginVisualScenarios.map((item) => [item.id, !item.disabled]),+);+const preferences = new Map<string, Record<string, unknown>>();+const reads = new Map<string, number>();+function item(id: string): RemoteCollectionItem {+ const scenario = pluginVisualScenarios.find((item) => item.id === id);+ if (!scenario) throw new Error("UNKNOWN_DEMO_PLUGIN");+ const active = enabled.get(id) === true;+ return {+ ref: { collectionId: PLUGIN_COLLECTION, kind: "plugin", id },+ revision: String(active),+ links: [],+ display: {+ title: scenario.name,+ subtitle: scenario.description,+ ...(active && Number(id) < 2+ ? {+ badges: [+ { accessibilityLabel: "Unread", tone: "positive" as const },+ ],+ preview: "A new demo result is ready to view.",+ }+ : {}),+ },+ actions: [+ ...(scenario.surface+ ? [{ id: "open:" + scenario.surface, label: "Open", disabled: !active }]+ : []),+ {+ id: active ? "disable" : "enable",+ label: active ? "Disable" : "Enable",+ ...(scenario.usage?.approvalRequired || scenario.usage?.retired+ ? { disabled: true }+ : {}),+ },+ ],+ };+}+const demoPageBase64 =+ "PCFkb2N0eXBlIGh0bWw+PGh0bWw+PGhlYWQ+PHN0eWxlPmJvZHl7Zm9udDoxN3B4IC1hcHBsZS1zeXN0ZW0sc3lzdGVtLXVpO2NvbG9yOnZhcigtLXRleHQtcHJpbWFyeSk7YmFja2dyb3VuZDp2YXIoLS1zdXJmYWNlKTtwYWRkaW5nOjI0cHh9aDF7Zm9udC1zaXplOjIycHh9cHtjb2xvcjp2YXIoLS10ZXh0LXNlY29uZGFyeSk7bGluZS1oZWlnaHQ6MS41fWxhYmVse2Rpc3BsYXk6YmxvY2s7bWFyZ2luOjI0cHggMCA4cHh9c2VsZWN0LGJ1dHRvbnt3aWR0aDoxMDAlO21pbi1oZWlnaHQ6NDhweDtib3JkZXI6MXB4IHNvbGlkIHZhcigtLWJvcmRlcik7Ym9yZGVyLXJhZGl1czoxMnB4O2JhY2tncm91bmQ6dmFyKC0tc3VyZmFjZS1lbGV2YXRlZCk7Y29sb3I6dmFyKC0tdGV4dC1wcmltYXJ5KTtwYWRkaW5nOjEycHh9YnV0dG9ue21hcmdpbi10b3A6MjRweH08L3N0eWxlPjwvaGVhZD48Ym9keT48aDE+Q3VzdG9tIHByZWZlcmVuY2VzPC9oMT48cD5EZW1vIGRhdGEuIFRoZXNlIGZpZWxkcyBhcmUgZGVmaW5lZCBieSB0aGUgcGx1Z2luLCBqdXN0IGFzIG9uIHRoZSBjb21wdXRlci48L3A+PGxhYmVsIGZvcj0ibGFuZ3VhZ2UiPk91dHB1dCBsYW5ndWFnZTwvbGFiZWw+PHNlbGVjdCBpZD0ibGFuZ3VhZ2UiPjxvcHRpb24gdmFsdWU9ImVuIj5FbmdsaXNoPC9vcHRpb24+PG9wdGlvbiB2YWx1ZT0iemgiPkNoaW5lc2U8L29wdGlvbj48b3B0aW9uIHZhbHVlPSJqYSI+SmFwYW5lc2U8L29wdGlvbj48L3NlbGVjdD48bGFiZWwgZm9yPSJmb3JtYXQiPk91dHB1dCBmb3JtYXQ8L2xhYmVsPjxzZWxlY3QgaWQ9ImZvcm1hdCI+PG9wdGlvbiB2YWx1ZT0iYnJpZWYiPkJyaWVmPC9vcHRpb24+PG9wdGlvbiB2YWx1ZT0iZGV0YWlsZWQiPkRldGFpbGVkPC9vcHRpb24+PC9zZWxlY3Q+PGJ1dHRvbiBpZD0ic2F2ZSI+U2F2ZSBkZW1vIHByZWZlcmVuY2VzPC9idXR0b24+PHAgaWQ9InJlY2VpcHQiPjwvcD48c2NyaXB0PmZldGNoKCcva3YnKS50aGVuKHI9PnIuanNvbigpKS50aGVuKHY9Pntkb2N1bWVudC5nZXRFbGVtZW50QnlJZCgnbGFuZ3VhZ2UnKS52YWx1ZT12Lmxhbmd1YWdlO2RvY3VtZW50LmdldEVsZW1lbnRCeUlkKCdmb3JtYXQnKS52YWx1ZT12LmZvcm1hdH0pO2RvY3VtZW50LmdldEVsZW1lbnRCeUlkKCdzYXZlJykub25jbGljaz1hc3luYygpPT57YXdhaXQgZmV0Y2goJy9rdicse21ldGhvZDonUFVUJyxib2R5OkpTT04uc3RyaW5naWZ5KHtsYW5ndWFnZTpkb2N1bWVudC5nZXRFbGVtZW50QnlJZCgnbGFuZ3VhZ2UnKS52YWx1ZSxmb3JtYXQ6ZG9jdW1lbnQuZ2V0RWxlbWVudEJ5SWQoJ2Zvcm1hdCcpLnZhbHVlfSl9KTtkb2N1bWVudC5nZXRFbGVtZW50QnlJZCgncmVjZWlwdCcpLnRleHRDb250ZW50PSdTYXZlZCBpbiB0aGlzIGRlbW8gb25seSd9Ozwvc2NyaXB0PjwvYm9keT48L2h0bWw+";+const demoPageSize = 1410;+let customPreferences = { language: "en", format: "brief" };+export function pluginVisualFixture(channel: string, args: unknown[]): unknown {+ const request = args[0] as+ | {+ collectionId?: string;+ ref?: { collectionId: string; id: string };+ resourceRef?: { collectionId: string; id: string };+ actionId?: string;+ input?: Record<string, unknown>;+ }+ | undefined;+ if (+ channel === REMOTE_RESOURCE_LIST_CHANNEL &&+ request?.collectionId === PLUGIN_COLLECTION+ )+ return {+ collectionId: PLUGIN_COLLECTION,+ revision: [...enabled.values()].join(),+ items: pluginVisualScenarios.map((scenario) => item(scenario.id)),+ };+ if (+ channel === REMOTE_RESOURCE_GET_CHANNEL &&+ request?.ref?.collectionId === PLUGIN_COLLECTION+ ) {+ reads.set(request.ref.id, (reads.get(request.ref.id) ?? 0) + 1);+ const current = item(request.ref.id),+ scenario = pluginVisualScenarios.find(+ (item) => item.id === request.ref!.id,+ )!;+ // The ready demo also exercises wrapping and the two-row disclosure.+ const tools =+ scenario.usage?.taskUsable === false+ ? []+ : (scenario.id === "0"+ ? [+ "demo_generate_image",+ "demo_edit_image",+ "demo_remove_background",+ "demo_upscale_image",+ "demo_generate_video",+ "demo_animate_image",+ ]+ : ["demo_tool"]+ ).map((name) => ({ name, description: "Example capability" }));+ return {+ ...current,+ blocks: [+ {+ id: "capabilities",+ primitive: "plugin-capabilities",+ fallbackMarkdown: "",+ data: {+ tools,+ tasks: scenario.taskPreferences === true,+ ...(scenario.usage ? { usage: scenario.usage } : {}),+ },+ },+ ],+ };+ }+ if (+ channel === REMOTE_RESOURCE_INVOKE_CHANNEL &&+ request?.resourceRef?.collectionId === PLUGIN_COLLECTION+ ) {+ const id = request.resourceRef.id,+ current = item(id);+ const scenario = pluginVisualScenarios.find(+ (scenario) => scenario.id === id,+ )!;+ if (+ request.actionId === "open:panel" ||+ request.actionId === "open:settings"+ ) {+ if (!scenario.surface || !enabled.get(id))+ throw new Error("DEMO_ACTION_DISABLED");+ return {+ effects: [],+ result: {+ pageId: "demo-" + id,+ pluginId: id,+ title: scenario.name,+ surface: scenario.surface,+ entry: "demo.html",+ channels: [],+ files: [{ path: "demo.html", mime: "text/html", size: demoPageSize }],+ },+ };+ }+ if (request.actionId === "asset")+ return {+ effects: [],+ result: { mime: "text/html", base64: demoPageBase64 },+ };+ if (request.actionId === "poll")+ return {+ effects: [],+ result: { events: [], confirms: [], notifications: [] },+ };+ if (["cover", "suspend", "close", "seen"].includes(request.actionId ?? ""))+ return { effects: [] };+ if (request.actionId === "fetch") {+ if (request.input?.path !== "/kv")+ throw new Error("UNSUPPORTED_DEMO_PLUGIN_ACTION");+ if (+ request.input.method === "PUT" &&+ typeof request.input.body === "string"+ ) {+ const value = JSON.parse(request.input.body);+ if (+ ["en", "zh", "ja"].includes(value.language) &&+ ["brief", "detailed"].includes(value.format)+ )+ customPreferences = {+ language: value.language,+ format: value.format,+ };+ }+ return {+ effects: [],+ result: {+ status: 200,+ mime: "application/json",+ base64: btoa(JSON.stringify(customPreferences)),+ },+ };+ }+ if (+ request.actionId === "task-settings:get" ||+ request.actionId === "task-settings:set"+ ) {+ if (request.actionId === "task-settings:set") {+ const previous = preferences.get(id) ?? {},+ patch = request.input ?? {};+ preferences.set(id, {+ ...previous,+ ...(patch.model && typeof patch.model === "object"+ ? patch.model+ : {}),+ ...(patch.permissionMode !== undefined+ ? { permissionMode: patch.permissionMode ?? undefined }+ : {}),+ });+ }+ return {+ effects: [],+ result: {+ revision: "demo-prefs",+ config: preferences.get(id) ?? {},+ permissionModes: ["ask", "auto"],+ defaultPermissionMode: "ask",+ },+ };+ }+ if (request.actionId !== "enable" && request.actionId !== "disable")+ throw new Error("UNSUPPORTED_DEMO_PLUGIN_ACTION");+ if (+ current.actions?.find((action) => action.id === request.actionId)+ ?.disabled+ )+ throw new Error("DEMO_ACTION_DISABLED");+ enabled.set(id, request.actionId === "enable");+ return {+ effects: [+ { kind: "refresh-collection", collectionId: PLUGIN_COLLECTION },+ ],+ };+ }+ return undefined;+}diff --git a/apps/mobile/src/debug/visualMock.ts b/apps/mobile/src/debug/visualMock.tsindex 2a2732229f..f122ee06ec 100644--- a/apps/mobile/src/debug/visualMock.ts+++ b/apps/mobile/src/debug/visualMock.ts@@ -19,6 +19,7 @@ import type {RemoteTextFilePreviewResult,} from '@/device-link/mobileMakerTransport';import { remoteSessionStore } from '@/session/remoteSessionStore';+import { pluginVisualFixture } from '@/debug/pluginVisualFixture';import { markdownPreviewFixture } from '@/debug/markdownPreviewFixture';import type { InputProjection, PendingInteraction, RemoteMessage, RemoteSession } from '@/session/types';@@ -212,6 +213,8 @@ async function visualMockInvoke<T = unknown>(args: unknown[] = [],): Promise<T> {const realData = await loadVisualRealDataSnapshot();+ const pluginResult = realData ? undefined : pluginVisualFixture(channel, args);+ if (pluginResult !== undefined) return pluginResult as T;if (channel === 'local-db:task-tags:execute') {const request = args[0] as TaskTagRequest;if (request.action !== 'list' && request.action !== 'get') {diff --git a/apps/mobile/src/device-link/remoteResources.ts b/apps/mobile/src/device-link/remoteResources.tsindex 0a562cf816..5d970987b9 100644--- a/apps/mobile/src/device-link/remoteResources.ts+++ b/apps/mobile/src/device-link/remoteResources.ts@@ -443,7 +443,15 @@ function normalizeRemoteCollectionItem(return normalized ? [normalized] : [];}): [];+ const rawOrder = collectionId === 'plugins' ? recordOf(item.pluginOrder) : null;+ const addedAt = rawOrder?.addedAt;+ const recentIndex = rawOrder?.recentIndex;+ const pluginOrder = rawOrder ? {+ ...(typeof addedAt === 'number' && Number.isSafeInteger(addedAt) && addedAt > 0 ? { addedAt } : {}),+ ...(typeof recentIndex === 'number' && Number.isSafeInteger(recentIndex) && recentIndex >= 0 && recentIndex < 100 ? { recentIndex } : {}),+ } : undefined;return { ref, display, links, revision,+ ...(pluginOrder && Object.keys(pluginOrder).length ? { pluginOrder } : {}),...(collectionId === 'plugins' ? { actions: normalizeRemoteActions(item.actions) } : {}),};}diff --git a/apps/mobile/src/i18n/locales/en/plugins.json b/apps/mobile/src/i18n/locales/en/plugins.jsonindex 0f9adc9853..5699533da4 100644--- a/apps/mobile/src/i18n/locales/en/plugins.json+++ b/apps/mobile/src/i18n/locales/en/plugins.json@@ -23,22 +23,23 @@"noComputer": "Connect a computer to use its installed plugins.","connectComputer": "Connect computer","listUnavailable": "Some plugin lists are unavailable. Previously loaded content is retained.",+ "listLoadFailed": "Plugin list could not be loaded. Try again.","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",+ "chooseTask": "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",+ "noMatchingTasks": "No matching tasks",+ "clearTaskSearch": "Clear search","noTasks": "No tasks on this computer yet","taskDraft": "Use the {{name}} plugin to ","taskSettings": "Task settings",@@ -86,5 +87,42 @@"frequency_interval": "Interval","frequency_custom": "Custom","automationTime": "Time",- "automationTimeInvalid": "Enter a 24-hour time, such as 09:00."+ "automationTimeInvalid": "Enter a 24-hour time, such as 09:00.",+ "enabled": "Enabled",+ "detail": {+ "useItIn": "Use it in",+ "openPlugin": "Open plugin",+ "computerSettings": "To configure this plugin, open its details in Cindy → Plugins on your computer.",+ "runtimeIssue": "The plugin stopped unexpectedly. Try opening it again or using it in a task.",+ "runtimeFused": "The plugin stopped after repeated failures. Turn it off and on to try again.",+ "status": {+ "offline": "Computer offline. Reconnect to use this plugin.",+ "loading": "Loading plugin…",+ "loadFailed": "Plugin details could not be loaded. Try again.",+ "retired": "This feature has been retired. See its replacement on the computer.",+ "approvalRequired": "The installation needs attention. Restore it in plugin details on the computer.",+ "builtinRecovery": "This built-in plugin needs attention. Restart Cindy on the computer.",+ "disabled": "Enable this plugin to use it.",+ "setupRequired": "Complete configuration before using this plugin.",+ "setupExpired": "Reconnect your account before using this plugin.",+ "setupUnknown": "Configuration status could not be confirmed. Refresh to check again."+ },+ "action": {+ "connect": "Connect computer",+ "retry": "Try again",+ "enable": "Enable plugin",+ "settings": "Complete setup",+ "reconnect": "Reconnect account"+ },+ "tools": "Tools",+ "permissions": "Permissions",+ "details": "Details",+ "version": "Version",+ "showAll": "Show all",+ "showLess": "Show less",+ "identifier": "Identifier"+ },+ "demo": {+ "hint": "Demo data · No real configuration is changed"+ }}diff --git a/apps/mobile/src/i18n/locales/ja/plugins.json b/apps/mobile/src/i18n/locales/ja/plugins.jsonindex 9726c6bec4..9b2223d8dd 100644--- a/apps/mobile/src/i18n/locales/ja/plugins.json+++ b/apps/mobile/src/i18n/locales/ja/plugins.json@@ -23,22 +23,23 @@"noComputer": "コンピューターに接続してプラグインを使用します。","connectComputer": "コンピューターに接続","listUnavailable": "一部の一覧を読み込めません。前回の内容を保持しています。",+ "listLoadFailed": "プラグイン一覧を読み込めませんでした。もう一度お試しください。","selectPlugin": "プラグインを選択してください","panel": "パネルを開く","mainView": "ページを開く","settings": "プラグイン設定","useInTask": "タスクで使用","newTask": "新規タスク",- "chooseTask": "既存のタスクを開く",+ "chooseTask": "既存のタスク","taskHint": "タスクで要望を伝えると、Cindy が適切なプラグインを使用します。既存のタスクのモデルと権限は保持されます。","noMobilePage": "モバイルページはまだありません。ツールはタスクで使用できます。",- "enable": "有効にする",- "disable": "無効にする","pageUnconfirmed": "接続またはページの状態を確認できません。送信した操作は自動再送されません。元のタスクや保存内容を確認してください。","reopen": "ページを開き直す","loadingPage": "プラグインを開いています…","searchTasks": "タスクを検索","retry": "再試行",+ "noMatchingTasks": "一致するタスクがありません",+ "clearTaskSearch": "検索をクリア","noTasks": "このコンピューターにはまだタスクがありません","taskDraft": "「{{name}}」プラグインを使って、","taskSettings": "タスク設定",@@ -86,5 +87,42 @@"frequency_interval": "間隔","frequency_custom": "カスタム","automationTime": "実行時刻",- "automationTimeInvalid": "09:00 のように24時間形式で入力してください。"+ "automationTimeInvalid": "09:00 のように24時間形式で入力してください。",+ "enabled": "有効",+ "detail": {+ "useItIn": "使用方法",+ "openPlugin": "プラグインを開く",+ "computerSettings": "コンピューターの Cindy で「プラグイン」からこのプラグインの詳細を開き、設定してください。",+ "runtimeIssue": "プラグインが予期せず停止しました。再度開くか、タスクで再試行してください。",+ "runtimeFused": "プラグインで繰り返しエラーが発生しました。一度無効にしてから再度有効にし、お試しください。",+ "status": {+ "offline": "コンピューターがオフラインです。接続すると使用できます。",+ "loading": "プラグインを読み込み中…",+ "loadFailed": "プラグイン情報を読み込めませんでした。再試行してください。",+ "retired": "この機能は終了しました。代替プラグインをコンピューターで確認してください。",+ "approvalRequired": "インストール情報の復元が必要です。コンピューターのプラグイン詳細で対応してください。",+ "builtinRecovery": "内蔵プラグインの復元が必要です。コンピューターの Cindy を再起動してください。",+ "disabled": "プラグインを有効にすると使用できます。",+ "setupRequired": "使用する前に設定を完了してください。",+ "setupExpired": "使用する前にアカウントを再接続してください。",+ "setupUnknown": "設定状態を確認できませんでした。再読み込みしてください。"+ },+ "action": {+ "connect": "コンピューターに接続",+ "retry": "再読み込み",+ "enable": "有効にする",+ "settings": "設定を完了",+ "reconnect": "アカウントを再接続"+ },+ "tools": "ツール",+ "permissions": "権限",+ "details": "詳細",+ "version": "バージョン",+ "showAll": "すべて表示",+ "showLess": "折りたたむ",+ "identifier": "識別子"+ },+ "demo": {+ "hint": "デモデータ · 実際の設定は変更されません"+ }}diff --git a/apps/mobile/src/i18n/locales/ko/plugins.json b/apps/mobile/src/i18n/locales/ko/plugins.jsonindex 1b2741b205..005c49b371 100644--- a/apps/mobile/src/i18n/locales/ko/plugins.json+++ b/apps/mobile/src/i18n/locales/ko/plugins.json@@ -23,22 +23,23 @@"noComputer": "컴퓨터에 연결하여 설치된 플러그인을 사용하세요.","connectComputer": "컴퓨터 연결","listUnavailable": "일부 목록을 불러올 수 없습니다. 이전 내용을 유지합니다.",+ "listLoadFailed": "플러그인 목록을 불러오지 못했습니다. 다시 시도하세요.","selectPlugin": "플러그인을 선택하세요","panel": "패널 열기","mainView": "페이지 열기","settings": "플러그인 설정","useInTask": "작업에서 사용","newTask": "새 작업",- "chooseTask": "기존 작업 열기",+ "chooseTask": "기존 작업","taskHint": "작업에서 요청을 설명하면 Cindy가 적절한 플러그인을 사용합니다. 기존 작업의 모델과 권한은 유지됩니다.","noMobilePage": "아직 모바일 페이지가 없습니다. 도구는 작업에서 사용할 수 있습니다.",- "enable": "플러그인 활성화",- "disable": "플러그인 비활성화","pageUnconfirmed": "연결 또는 페이지 상태가 확인되지 않았습니다. 전송된 작업은 자동으로 다시 보내지 않습니다. 원래 작업이나 저장된 내용을 먼저 확인해 주세요.","reopen": "페이지 다시 열기","loadingPage": "플러그인 여는 중…","searchTasks": "작업 검색","retry": "다시 시도",+ "noMatchingTasks": "일치하는 작업이 없습니다",+ "clearTaskSearch": "검색 지우기","noTasks": "이 컴퓨터에 아직 작업이 없습니다","taskDraft": "{{name}} 플러그인을 사용해서 ","taskSettings": "작업 설정",@@ -86,5 +87,42 @@"frequency_interval": "간격","frequency_custom": "사용자 지정","automationTime": "실행 시간",- "automationTimeInvalid": "09:00과 같은 24시간 형식으로 입력하세요."+ "automationTimeInvalid": "09:00과 같은 24시간 형식으로 입력하세요.",+ "enabled": "활성화",+ "detail": {+ "useItIn": "사용 방법",+ "openPlugin": "플러그인 열기",+ "computerSettings": "컴퓨터의 Cindy에서 플러그인 메뉴를 열고 이 플러그인의 세부 정보에서 구성하세요.",+ "runtimeIssue": "플러그인이 예기치 않게 중지되었습니다. 다시 열거나 작업에서 다시 시도하세요.",+ "runtimeFused": "플러그인에 오류가 반복되었습니다. 껐다가 다시 켠 후 시도하세요.",+ "status": {+ "offline": "컴퓨터가 오프라인입니다. 연결하면 사용할 수 있습니다.",+ "loading": "플러그인 불러오는 중…",+ "loadFailed": "플러그인 정보를 불러오지 못했습니다. 다시 시도하세요.",+ "retired": "종료된 기능입니다. 컴퓨터에서 대체 플러그인을 확인하세요.",+ "approvalRequired": "설치 기록 복구가 필요합니다. 컴퓨터의 플러그인 상세 페이지에서 처리하세요.",+ "builtinRecovery": "기본 플러그인 복구가 필요합니다. 컴퓨터의 Cindy를 다시 시작하세요.",+ "disabled": "플러그인을 활성화하면 사용할 수 있습니다.",+ "setupRequired": "사용 전에 설정을 완료하세요.",+ "setupExpired": "사용 전에 계정을 다시 연결하세요.",+ "setupUnknown": "설정 상태를 확인하지 못했습니다. 다시 불러오세요."+ },+ "action": {+ "connect": "컴퓨터 연결",+ "retry": "다시 불러오기",+ "enable": "플러그인 활성화",+ "settings": "설정 완료",+ "reconnect": "계정 다시 연결"+ },+ "tools": "도구",+ "permissions": "권한",+ "details": "세부 정보",+ "version": "버전",+ "showAll": "모두 보기",+ "showLess": "접기",+ "identifier": "식별자"+ },+ "demo": {+ "hint": "데모 데이터 · 실제 설정은 변경되지 않습니다"+ }}diff --git a/apps/mobile/src/i18n/locales/zh-CN/plugins.json b/apps/mobile/src/i18n/locales/zh-CN/plugins.jsonindex e63c72300f..0e5e4c019f 100644--- a/apps/mobile/src/i18n/locales/zh-CN/plugins.json+++ b/apps/mobile/src/i18n/locales/zh-CN/plugins.json@@ -23,22 +23,23 @@"noComputer": "连接电脑,使用已经安装的插件。","connectComputer": "连接电脑","listUnavailable": "部分电脑的插件列表暂时无法读取,已保留上次内容。",+ "listLoadFailed": "无法读取插件列表,请重试。","selectPlugin": "选择插件开始使用","panel": "打开面板","mainView": "打开页面","settings": "插件设置","useInTask": "在任务中使用","newTask": "新建任务",- "chooseTask": "打开已有任务",+ "chooseTask": "已有任务","taskHint": "在任务中说明你的需求,Cindy 会调用适合的插件。已有任务继续使用原来的模型和权限。","noMobilePage": "此插件尚未提供手机页面,可在任务中使用其工具。",- "enable": "启用插件",- "disable": "停用插件","pageUnconfirmed": "连接或页面状态尚未确认。已发出的操作不会自动重发,请先检查原任务或内容是否已保存。","reopen": "重新打开页面","loadingPage": "正在打开插件…","searchTasks": "搜索任务","retry": "重试",+ "noMatchingTasks": "没有匹配的任务",+ "clearTaskSearch": "清除搜索","noTasks": "这台电脑还没有任务","taskDraft": "使用「{{name}}」插件,","taskSettings": "任务设置",@@ -86,5 +87,42 @@"frequency_interval": "按间隔","frequency_custom": "自定义","automationTime": "执行时间",- "automationTimeInvalid": "请输入 24 小时时间,例如 09:00。"+ "automationTimeInvalid": "请输入 24 小时时间,例如 09:00。",+ "enabled": "启用",+ "detail": {+ "useItIn": "使用方式",+ "openPlugin": "打开插件",+ "computerSettings": "请在电脑端 Cindy 的「插件」中打开此插件详情,完成配置。",+ "runtimeIssue": "插件上次运行异常,可重新打开或在任务中重试。",+ "runtimeFused": "插件多次停止。关闭后重新启用,再试一次。",+ "status": {+ "offline": "电脑未连接,连接后可使用插件。",+ "loading": "正在读取插件…",+ "loadFailed": "插件信息未能读取,请重试。",+ "retired": "此功能已下线,请在电脑上查看替代插件。",+ "approvalRequired": "安装记录需要恢复,请在电脑上的插件详情中处理。",+ "builtinRecovery": "内置插件需要恢复,请重启电脑上的 Cindy。",+ "disabled": "启用插件后即可使用。",+ "setupRequired": "使用前需要完成配置。",+ "setupExpired": "使用前需要重新连接账号。",+ "setupUnknown": "配置状态尚未确认,请重新读取。"+ },+ "action": {+ "connect": "连接电脑",+ "retry": "重新读取",+ "enable": "启用插件",+ "settings": "完成配置",+ "reconnect": "重新连接账号"+ },+ "tools": "工具",+ "permissions": "权限",+ "details": "详细信息",+ "version": "版本",+ "showAll": "显示全部",+ "showLess": "收起",+ "identifier": "标识"+ },+ "demo": {+ "hint": "演示数据 · 不会修改真实配置"+ }}diff --git a/apps/mobile/src/i18n/locales/zh-TW/plugins.json b/apps/mobile/src/i18n/locales/zh-TW/plugins.jsonindex 4c59d6499f..78c6bc982a 100644--- a/apps/mobile/src/i18n/locales/zh-TW/plugins.json+++ b/apps/mobile/src/i18n/locales/zh-TW/plugins.json@@ -23,22 +23,23 @@"noComputer": "連接電腦,使用已安裝的插件。","connectComputer": "連接電腦","listUnavailable": "部分電腦的清單暫時無法讀取,已保留上次內容。",+ "listLoadFailed": "無法讀取插件列表,請重試。","selectPlugin": "選擇插件開始使用","panel": "開啟面板","mainView": "開啟頁面","settings": "插件設定","useInTask": "在任務中使用","newTask": "新增任務",- "chooseTask": "開啟現有任務",+ "chooseTask": "已有任務","taskHint": "在任務中說明需求,Cindy 會使用適合的插件。現有任務保留原有模型與權限。","noMobilePage": "此插件尚未提供手機頁面,可在任務中使用其工具。",- "enable": "啟用插件",- "disable": "停用插件","pageUnconfirmed": "連線或頁面狀態尚未確認。已送出的操作不會自動重送,請先檢查原任務或內容是否已儲存。","reopen": "重新開啟頁面","loadingPage": "正在開啟插件…","searchTasks": "搜尋任務","retry": "重試",+ "noMatchingTasks": "沒有符合的任務",+ "clearTaskSearch": "清除搜尋","noTasks": "這台電腦還沒有任務","taskDraft": "使用「{{name}}」插件,","taskSettings": "任務設定",@@ -86,5 +87,42 @@"frequency_interval": "按間隔","frequency_custom": "自訂","automationTime": "執行時間",- "automationTimeInvalid": "請輸入 24 小時時間,例如 09:00。"+ "automationTimeInvalid": "請輸入 24 小時時間,例如 09:00。",+ "enabled": "啟用",+ "detail": {+ "useItIn": "使用方式",+ "openPlugin": "開啟插件",+ "computerSettings": "請在電腦端 Cindy 的「插件」中開啟此插件詳情,完成配置。",+ "runtimeIssue": "插件上次執行異常,可重新開啟或在任務中重試。",+ "runtimeFused": "插件多次停止。關閉後重新啟用,再試一次。",+ "status": {+ "offline": "電腦未連線,連線後可使用插件。",+ "loading": "正在讀取插件…",+ "loadFailed": "未能讀取插件資訊,請重試。",+ "retired": "此功能已下線,請在電腦上查看替代插件。",+ "approvalRequired": "安裝記錄需要復原,請在電腦上的插件詳情中處理。",+ "builtinRecovery": "內建插件需要復原,請重新啟動電腦上的 Cindy。",+ "disabled": "啟用插件後即可使用。",+ "setupRequired": "使用前需要完成設定。",+ "setupExpired": "使用前需要重新連線帳號。",+ "setupUnknown": "設定狀態尚未確認,請重新讀取。"+ },+ "action": {+ "connect": "連線電腦",+ "retry": "重新讀取",+ "enable": "啟用插件",+ "settings": "完成設定",+ "reconnect": "重新連線帳號"+ },+ "tools": "工具",+ "permissions": "權限",+ "details": "詳細資訊",+ "version": "版本",+ "showAll": "顯示全部",+ "showLess": "收起",+ "identifier": "識別碼"+ },+ "demo": {+ "hint": "示範資料 · 不會修改真實設定"+ }}diff --git a/apps/mobile/src/plugins/PluginDetailView.ios.tsx b/apps/mobile/src/plugins/PluginDetailView.ios.tsxnew file mode 100644index 0000000000..0725663896--- /dev/null+++ b/apps/mobile/src/plugins/PluginDetailView.ios.tsx@@ -0,0 +1,524 @@+import {+ Host,+ List,+ HStack,+ Image as NativeImage,+ RNHostView,+ Section,+ Text,+ Toggle,+ VStack,+ Button,+ ProgressView,+ DisclosureGroup,+ Divider,+} from "@expo/ui/swift-ui";+import {+ background,+ buttonStyle,+ disabled,+ font,+ foregroundStyle,+ frame,+ lineLimit,+ labelsHidden,+ accessibilityLabel,+ listRowBackground,+ listRowInsets,+ listRowSeparator,+ listRowSeparatorTint,+ listStyle,+ padding,+ scrollContentBackground,+ tint,+ scaleEffect,+ contentShape,+ shapes,+} from "@expo/ui/swift-ui/modifiers";+import { Image, StyleSheet, View, useWindowDimensions } from "react-native";+import { useEffect, useState } from "react";+import { Puzzle } from "lucide-react-native";+import { useTranslation } from "react-i18next";+import { resolveRemoteText } from "@cindy/device-link";+import { ComposerNativeRow } from "@/session/ComposerNativeRow";+import { useNativeGlassButtonStyle } from "@/platform/chrome/nativeGlassButtonStyle.ios";+import { iconSize, radius, spacing, useTheme } from "@/theme";+import type { PluginDetailViewProps } from "./PluginDetailView";+import { PluginToolChips } from "./PluginToolChips";++export function PluginDetailView(p: PluginDetailViewProps) {+ const { t, i18n } = useTranslation();+ const { mode, colors } = useTheme();+ const { width, fontScale } = useWindowDimensions();+ const primaryStyle = useNativeGlassButtonStyle({ prominent: true });+ const secondaryStyle = useNativeGlassButtonStyle();+ const text = (value: Parameters<typeof resolveRemoteText>[0]) =>+ resolveRemoteText(value, i18n.language);+ const { model } = p;+ const [toolsExpanded, setToolsExpanded] = useState(false);+ const [toolsOverflow, setToolsOverflow] = useState(false);+ const [hostWidth, setHostWidth] = useState(width);+ useEffect(() => setToolsExpanded(false), [p.row.key]);+ const detailFacts = (+ model.details ?? [+ ...(model.version+ ? [+ {+ key: "version",+ title: t("plugins.detail.version"),+ value: "v" + model.version,+ },+ ]+ : []),+ {+ key: "identifier",+ title: t("plugins.detail.identifier"),+ value: p.row.item.ref.id,+ },+ ]+ ).filter((fact) => fact.title.trim() && fact.value.trim());+ const uri = p.row.item.display.avatar?.value;+ const Actions = fontScale > 1.2 || width < 380 ? VStack : HStack;+ const note = (value: string, id?: string) => (+ <Text+ testID={id}+ modifiers={[+ font({ textStyle: "subheadline" }),+ foregroundStyle(colors.textSecondary),+ ]}+ >+ {value}+ </Text>+ );+ const button = (+ label: string,+ onPress: () => void,+ prominent: boolean,+ id: string,+ ) => (+ <Button+ key={id}+ testID={id}+ onPress={onPress}+ modifiers={[+ ...(prominent ? primaryStyle : secondaryStyle),+ frame({ maxWidth: Infinity }),+ disabled(p.busy),+ ]}+ >+ <Text+ modifiers={[+ font({ textStyle: "body", weight: "semibold" }),+ foregroundStyle(prominent ? colors.ctaText : colors.textPrimary),+ frame({ maxWidth: Infinity, minHeight: 28 }),+ padding({ horizontal: spacing.xs }),+ ]}+ >+ {label}+ </Text>+ </Button>+ );+ const chevron = (+ <NativeImage+ systemName="chevron.right"+ size={iconSize.xs}+ modifiers={[foregroundStyle(colors.textTertiary)]}+ />+ );+ const statusKey =+ model.status === "approvalRequired" && model.builtin+ ? "builtinRecovery"+ : model.status === "setupRequired" &&+ !model.missing.length &&+ model.expired.length+ ? "setupExpired"+ : model.status;+ const status = model.status ? (+ <VStack+ alignment="leading"+ spacing={spacing.md}+ modifiers={[+ listRowSeparator("hidden"),+ padding({ vertical: spacing.sm }),+ ]}+ testID="plugins.status"+ >+ {model.status === "loading" ? <ProgressView /> : null}+ {note(t("plugins.detail.status." + statusKey))}+ {!p.settingsOpen && model.statusAction && model.statusAction !== "enable"+ ? button(+ t("plugins.detail.action." + model.statusAction),+ p.onResolveStatus,+ true,+ "plugins.resolveStatus",+ )+ : null}+ </VStack>+ ) : model.runtimeIssue ? (+ note(+ t(+ model.runtimeIssue === "fused"+ ? "plugins.detail.runtimeFused"+ : "plugins.detail.runtimeIssue",+ ),+ "plugins.runtimeIssue",+ )+ ) : null;+ return (+ <Host+ onLayoutContent={({ nativeEvent }) => setHostWidth(nativeEvent.width)}+ colorScheme={mode}+ seedColor={colors.textPrimary}+ style={styles.root}+ ignoreSafeArea="container"+ >+ <List+ key={p.settingsOpen ? "settings" : "detail"}+ modifiers={[+ listStyle("plain"),+ scrollContentBackground("hidden"),+ background(colors.surface),+ listRowSeparatorTint(colors.border),+ ]}+ testID={p.settingsOpen ? "plugins.settingsPage" : "plugins.detail"}+ >+ <Section+ modifiers={[+ listRowBackground(colors.surface),+ listRowInsets({+ leading: spacing.lg + spacing.xs,+ trailing: spacing.lg + spacing.xs,+ top: spacing.md,+ bottom: spacing.md,+ }),+ ]}+ >+ {p.previewLabel ? (+ <VStack+ alignment="leading"+ modifiers={[listRowSeparator("hidden")]}+ >+ {note(p.previewLabel)}+ </VStack>+ ) : null}+ {!p.settingsOpen ? (+ <VStack+ alignment="leading"+ spacing={spacing.lg}+ modifiers={[+ listRowSeparator("hidden"),+ listRowInsets({+ leading: spacing.lg + spacing.xs,+ trailing: spacing.lg + spacing.xs,+ top: spacing.sm,+ bottom: spacing.lg,+ }),+ ]}+ testID="plugins.identity"+ >+ <HStack spacing={spacing.lg}>+ <RNHostView matchContents>+ {uri &&+ /^data:image\/(?:png|jpeg|webp|svg\+xml);base64,/.test(+ uri,+ ) ? (+ <Image source={{ uri }} style={styles.icon} />+ ) : (+ <View+ style={[+ styles.icon,+ styles.fallback,+ { backgroundColor: colors.surfaceChip },+ ]}+ >+ <Puzzle+ size={iconSize.xxl}+ color={colors.textSecondary}+ />+ </View>+ )}+ </RNHostView>+ <VStack+ alignment="leading"+ spacing={spacing.xs}+ modifiers={[+ frame({ maxWidth: Infinity, alignment: "leading" }),+ ]}+ >+ <HStack+ spacing={spacing.sm}+ modifiers={[frame({ maxWidth: Infinity })]}+ >+ <Text+ modifiers={[+ font({ textStyle: "title2", weight: "semibold" }),+ frame({ maxWidth: Infinity, alignment: "leading" }),+ ]}+ >+ {text(p.row.item.display.title)}+ </Text>+ <Toggle+ label={t("plugins.enabled")}+ isOn={p.enabled}+ onIsOnChange={p.onEnabledChange}+ modifiers={[+ labelsHidden(),+ frame({ width: 61, height: 28 }),+ scaleEffect({ x: 48 / 61, y: 24 / 28 }),+ frame({ width: 56, height: 44 }),+ contentShape(shapes.rectangle()),+ accessibilityLabel(t("plugins.enabled")),+ disabled(p.busy || !p.online || !model.canToggle),+ tint(colors.inputCaret),+ ]}+ testID="plugins.enabled"+ />+ </HStack>+ {note(p.row.host.deviceName)}+ </VStack>+ </HStack>+ {model.description || p.row.item.display.subtitle ? (+ <Text+ modifiers={[+ font({ textStyle: "subheadline" }),+ foregroundStyle(colors.textSecondary),+ lineLimit(3),+ ]}+ >+ {model.description || text(p.row.item.display.subtitle!)}+ </Text>+ ) : null}+ </VStack>+ ) : null}+ {p.settingsOpen && model.status === "setupRequired" ? null : status}+ {!p.settingsOpen && model.canUseTasks ? (+ <VStack+ alignment="leading"+ spacing={spacing.md}+ modifiers={[+ listRowSeparator("hidden"),+ // List cells clip the native glass shadow; reserve its tail inside this row.+ padding({ bottom: spacing.xl }),+ ]}+ testID="plugins.use"+ >+ <Text+ modifiers={[font({ textStyle: "title3", weight: "semibold" })]}+ testID="plugins.useHeading"+ >+ {t("plugins.detail.useItIn")}+ </Text>+ <Actions+ spacing={spacing.md}+ modifiers={[frame({ maxWidth: Infinity })]}+ >+ {button(+ t("plugins.newTask"),+ p.onNewTask,+ false,+ "plugins.newTask",+ )}+ {button(+ t("plugins.chooseTask"),+ p.onChooseTask,+ false,+ "plugins.chooseTask",+ )}+ </Actions>+ </VStack>+ ) : null}+ {!p.settingsOpen && model.mainSurface ? (+ <ComposerNativeRow+ title={t("plugins.detail.openPlugin")}+ accessory={chevron}+ disabled={p.busy || !p.online || !p.enabled || !model.canToggle}+ onPress={() => p.onOpen(model.mainSurface!)}+ testID="plugins.openPlugin"+ />+ ) : null}+ {model.tools?.length ? (+ <VStack+ alignment="leading"+ spacing={spacing.md}+ modifiers={[+ listRowSeparator("hidden"),+ ...(model.canUseTasks && !p.settingsOpen && !model.mainSurface+ ? [+ listRowInsets({+ leading: spacing.lg + spacing.xs,+ trailing: spacing.lg + spacing.xs,+ top: 0,+ bottom: spacing.md,+ }),+ ]+ : []),+ ]}+ testID="plugins.tools"+ >+ <HStack spacing={spacing.md}>+ <Text+ modifiers={[+ font({ textStyle: "title3", weight: "semibold" }),+ frame({ maxWidth: Infinity, alignment: "leading" }),+ ]}+ >+ {t("plugins.detail.tools") + " · " + model.tools.length}+ </Text>+ {toolsOverflow ? (+ <Button+ testID="plugins.toolsDisclosure"+ onPress={() => setToolsExpanded(!toolsExpanded)}+ modifiers={[+ buttonStyle("plain"),+ frame({ minWidth: 44, minHeight: 44 }),+ contentShape(shapes.rectangle()),+ accessibilityLabel(+ t(+ toolsExpanded+ ? "plugins.detail.showLess"+ : "plugins.detail.showAll",+ ),+ ),+ ]}+ >+ <Text+ modifiers={[+ font({ textStyle: "body" }),+ foregroundStyle(colors.inputCaret),+ ]}+ >+ {t(+ toolsExpanded+ ? "plugins.detail.showLess"+ : "plugins.detail.showAll",+ )}+ </Text>+ </Button>+ ) : null}+ </HStack>+ <VStack+ alignment="leading"+ spacing={0}+ modifiers={[frame({ maxWidth: Infinity })]}+ >+ <RNHostView matchContents>+ <PluginToolChips+ key={+ p.row.key + model.tools.map((tool) => tool.name).join("|")+ }+ tools={model.tools}+ expanded={toolsExpanded}+ width={Math.max(+ 0,+ hostWidth - (spacing.lg + spacing.xs) * 2,+ )}+ onOverflowChange={setToolsOverflow}+ />+ </RNHostView>+ </VStack>+ </VStack>+ ) : null}+ {model.permissions?.length ? (+ <VStack+ alignment="leading"+ spacing={spacing.md}+ modifiers={[listRowSeparator("hidden")]}+ testID="plugins.permissions"+ >+ <Text+ modifiers={[font({ textStyle: "title3", weight: "semibold" })]}+ >+ {t("plugins.detail.permissions")}+ </Text>+ {model.permissions?.map((permission, index) =>+ permission.description ? (+ <DisclosureGroup+ key={index}+ label={permission.title}+ modifiers={[tint(colors.textSecondary)]}+ >+ {note(permission.description)}+ </DisclosureGroup>+ ) : (+ <Text key={index}>{permission.title}</Text>+ ),+ )}+ </VStack>+ ) : null}+ {detailFacts.length || model.hasSettings ? (+ <VStack+ alignment="leading"+ spacing={spacing.md}+ modifiers={[listRowSeparator("hidden")]}+ testID="plugins.metadata"+ >+ <Text+ modifiers={[font({ textStyle: "title3", weight: "semibold" })]}+ >+ {t("plugins.detail.details")}+ </Text>+ {detailFacts.map((fact, index) => (+ <VStack+ key={fact.key}+ alignment="leading"+ spacing={spacing.md}+ modifiers={[+ frame({ maxWidth: Infinity, alignment: "leading" }),+ ]}+ >+ {fact.key === "contents" || fact.key === "location" ? (+ <VStack+ key={fact.key}+ alignment="leading"+ spacing={spacing.xs}+ testID={"plugins.fact." + fact.key}+ >+ {note(fact.title)}+ <Text+ modifiers={[+ font({+ textStyle:+ fact.key === "location" ? "footnote" : "body",+ }),+ ]}+ >+ {fact.value}+ </Text>+ </VStack>+ ) : (+ <HStack+ key={fact.key}+ spacing={spacing.md}+ testID={"plugins.fact." + fact.key}+ >+ {note(fact.title)}+ <Text+ modifiers={[+ font({ textStyle: "body" }),+ frame({ maxWidth: Infinity, alignment: "trailing" }),+ ]}+ >+ {fact.value}+ </Text>+ </HStack>+ )}+ {index < detailFacts.length - 1 ? <Divider /> : null}+ </VStack>+ ))}+ {model.hasSettings ? (+ <VStack alignment="leading" testID="plugins.computerSettings">+ {note(t("plugins.detail.computerSettings"))}+ </VStack>+ ) : null}+ </VStack>+ ) : null}+ </Section>+ </List>+ </Host>+ );+}+const styles = StyleSheet.create({+ root: { flex: 1 },+ icon: { width: 72, height: 72, borderRadius: radius.container },+ fallback: { alignItems: "center", justifyContent: "center" },+});diff --git a/apps/mobile/src/plugins/PluginDetailView.tsx b/apps/mobile/src/plugins/PluginDetailView.tsxnew file mode 100644index 0000000000..5edb5a904b--- /dev/null+++ b/apps/mobile/src/plugins/PluginDetailView.tsx@@ -0,0 +1,460 @@+import { useEffect, useState } from "react";+import {+ Image,+ Pressable,+ ScrollView,+ StyleSheet,+ View,+ ActivityIndicator,+ useWindowDimensions,+} from "react-native";+import { useTranslation } from "react-i18next";+import { resolveRemoteText } from "@cindy/device-link";+import { Puzzle, ChevronRight } from "lucide-react-native";+import { Text } from "@/components/AppText";+import { NativeSwitch } from "@/platform/chrome/NativeSwitch";+import {+ fontWeight,+ iconSize,+ lineHeight,+ radius,+ spacing,+ typeScale,+ useTheme,+ useThemedStyles,+ type ThemeColors,+} from "@/theme";+import type { PluginPageSurface } from "@cindy/device-link";+import type { HostedRemoteCollectionItem } from "@/device-link/remoteResources";+import type { PluginDetailModel } from "./pluginDetailModel";+import { PluginToolChips } from "./PluginToolChips";++export interface PluginDetailViewProps {+ row: HostedRemoteCollectionItem;+ enabled: boolean;+ busy: boolean;+ online: boolean;+ model: PluginDetailModel;+ settingsOpen: boolean;+ previewLabel?: string;+ onEnabledChange(enabled: boolean): void;+ onOpen(surface: PluginPageSurface): void;+ onNewTask(): void;+ onChooseTask(): void;+ onSettings(): void;+ onResolveStatus(): void;+}++function InformationRow({+ title,+ description,+}: {+ title: string;+ description: string;+}) {+ const [expanded, setExpanded] = useState(false);+ const styles = useThemedStyles(makeStyles);+ return (+ <View>+ <Pressable+ accessibilityRole="button"+ accessibilityState={{ expanded }}+ onPress={() => setExpanded(!expanded)}+ style={styles.informationRow}+ >+ <Text style={styles.rowText}>{title}</Text>+ <Text style={styles.note}>{expanded ? "−" : "+"}</Text>+ </Pressable>+ {expanded ? <Text style={styles.note}>{description}</Text> : null}+ </View>+ );+}++/** Android shares the page hierarchy and Host facts, with its platform Switch. */+export function PluginDetailView(p: PluginDetailViewProps) {+ const { t, i18n } = useTranslation(),+ { colors } = useTheme();+ const styles = useThemedStyles(makeStyles);+ const { width, fontScale } = useWindowDimensions();+ const { model } = p;+ const [toolsExpanded, setToolsExpanded] = useState(false);+ const [toolsOverflow, setToolsOverflow] = useState(false);+ useEffect(() => setToolsExpanded(false), [p.row.key]);+ const detailFacts = (+ model.details ?? [+ ...(model.version+ ? [+ {+ key: "version",+ title: t("plugins.detail.version"),+ value: "v" + model.version,+ },+ ]+ : []),+ {+ key: "identifier",+ title: t("plugins.detail.identifier"),+ value: p.row.item.ref.id,+ },+ ]+ ).filter((fact) => fact.title.trim() && fact.value.trim());+ const text = (value: Parameters<typeof resolveRemoteText>[0]) =>+ resolveRemoteText(value, i18n.language);+ const uri = p.row.item.display.avatar?.value;+ const note = (value: string) => <Text style={styles.note}>{value}</Text>;+ const button = (+ label: string,+ onPress: () => void,+ primary: boolean,+ testID: string,+ ) => (+ <Pressable+ testID={testID}+ accessibilityRole="button"+ disabled={p.busy}+ onPress={onPress}+ style={[+ styles.button,+ primary ? styles.primary : styles.secondary,+ p.busy && styles.unavailable,+ ]}+ >+ <Text style={[styles.buttonText, primary && styles.primaryText]}>+ {label}+ </Text>+ </Pressable>+ );+ const row = (+ label: string,+ onPress: () => void,+ unavailable: boolean,+ testID: string,+ ) => (+ <Pressable+ testID={testID}+ accessibilityRole="button"+ disabled={unavailable}+ onPress={onPress}+ style={[styles.row, unavailable && styles.unavailable]}+ >+ <Text style={styles.rowText}>{label}</Text>+ <ChevronRight size={iconSize.md} color={colors.textTertiary} />+ </Pressable>+ );+ const statusKey =+ model.status === "approvalRequired" && model.builtin+ ? "builtinRecovery"+ : model.status === "setupRequired" &&+ !model.missing.length &&+ model.expired.length+ ? "setupExpired"+ : model.status;+ return (+ <ScrollView+ testID={p.settingsOpen ? "plugins.settingsPage" : "plugins.detail"}+ contentContainerStyle={styles.content}+ >+ {p.previewLabel ? note(p.previewLabel) : null}+ {!p.settingsOpen ? (+ <View style={styles.identity}>+ <View style={styles.hero}>+ {uri &&+ /^data:image\/(?:png|jpeg|webp|svg\+xml);base64,/.test(uri) ? (+ <Image source={{ uri }} style={styles.icon} />+ ) : (+ <View style={[styles.icon, styles.fallback]}>+ <Puzzle size={iconSize.xxl} color={colors.textSecondary} />+ </View>+ )}+ <View style={styles.identityText}>+ <View style={styles.titleRow}>+ <Text style={[styles.title, styles.titleText]}>+ {text(p.row.item.display.title)}+ </Text>+ <NativeSwitch+ testID="plugins.enabled"+ accessibilityLabel={t("plugins.enabled")}+ value={p.enabled}+ disabled={p.busy || !p.online || !model.canToggle}+ onValueChange={p.onEnabledChange}+ />+ </View>+ {note(p.row.host.deviceName)}+ </View>+ </View>+ {model.description || p.row.item.display.subtitle ? (+ <Text numberOfLines={3} style={styles.note}>+ {model.description || text(p.row.item.display.subtitle!)}+ </Text>+ ) : null}+ </View>+ ) : null}+ {model.status && !(p.settingsOpen && model.status === "setupRequired") ? (+ <View testID="plugins.status" style={styles.status}>+ {model.status === "loading" ? (+ <ActivityIndicator color={colors.textSecondary} />+ ) : null}+ {note(t("plugins.detail.status." + statusKey))}+ {!p.settingsOpen &&+ model.statusAction &&+ model.statusAction !== "enable"+ ? button(+ t("plugins.detail.action." + model.statusAction),+ p.onResolveStatus,+ true,+ "plugins.resolveStatus",+ )+ : null}+ </View>+ ) : model.runtimeIssue ? (+ note(+ t(+ model.runtimeIssue === "fused"+ ? "plugins.detail.runtimeFused"+ : "plugins.detail.runtimeIssue",+ ),+ )+ ) : null}+ {!p.settingsOpen && model.canUseTasks ? (+ <View style={styles.use}>+ <Text style={styles.sectionHeading} testID="plugins.useHeading">+ {t("plugins.detail.useItIn")}+ </Text>+ <View+ style={[+ styles.actions,+ (fontScale > 1.2 || width < 380) && styles.verticalActions,+ ]}+ >+ {button(+ t("plugins.newTask"),+ p.onNewTask,+ false,+ "plugins.newTask",+ )}+ {button(+ t("plugins.chooseTask"),+ p.onChooseTask,+ false,+ "plugins.chooseTask",+ )}+ </View>+ </View>+ ) : null}+ {!p.settingsOpen && model.mainSurface+ ? row(+ t("plugins.detail.openPlugin"),+ () => p.onOpen(model.mainSurface!),+ p.busy || !p.online || !p.enabled || !model.canToggle,+ "plugins.openPlugin",+ )+ : null}+ {model.tools?.length ? (+ <View style={styles.information} testID="plugins.tools">+ <View style={styles.titleRow}>+ <Text style={[styles.sectionHeading, styles.titleText]}>+ {t("plugins.detail.tools") + " · " + model.tools.length}+ </Text>+ {toolsOverflow ? (+ <Pressable+ testID="plugins.toolsDisclosure"+ accessibilityRole="button"+ accessibilityState={{ expanded: toolsExpanded }}+ onPress={() => setToolsExpanded(!toolsExpanded)}+ style={styles.toolsToggle}+ >+ <Text style={styles.toolsToggleText}>+ {t(+ toolsExpanded+ ? "plugins.detail.showLess"+ : "plugins.detail.showAll",+ )}+ </Text>+ </Pressable>+ ) : null}+ </View>+ <PluginToolChips+ key={p.row.key + model.tools.map((tool) => tool.name).join("|")}+ tools={model.tools}+ expanded={toolsExpanded}+ onOverflowChange={setToolsOverflow}+ />+ </View>+ ) : null}+ {model.permissions?.length ? (+ <View style={styles.information} testID="plugins.permissions">+ <Text style={styles.sectionHeading}>+ {t("plugins.detail.permissions")}+ </Text>+ {model.permissions?.map((permission, index) =>+ permission.description ? (+ <InformationRow+ key={index}+ title={permission.title}+ description={permission.description}+ />+ ) : (+ <Text key={index} style={styles.rowText}>+ {permission.title}+ </Text>+ ),+ )}+ </View>+ ) : null}+ {detailFacts.length || model.hasSettings ? (+ <View style={styles.information} testID="plugins.metadata">+ <Text style={styles.sectionHeading}>+ {t("plugins.detail.details")}+ </Text>+ {detailFacts.map((fact, index) => (+ <View+ key={fact.key}+ testID={"plugins.fact." + fact.key}+ style={+ fact.key === "contents" || fact.key === "location"+ ? [+ styles.toolDescription,+ index < detailFacts.length - 1 && styles.factSeparator,+ ]+ : [+ styles.metadataRow,+ index < detailFacts.length - 1 && styles.factSeparator,+ ]+ }+ >+ {note(fact.title)}+ <Text+ style={[+ styles.rowText,+ fact.key !== "contents" &&+ fact.key !== "location" &&+ styles.metadataValue,+ ]}+ >+ {fact.value}+ </Text>+ </View>+ ))}+ {model.hasSettings ? (+ <View testID="plugins.computerSettings">+ {note(t("plugins.detail.computerSettings"))}+ </View>+ ) : null}+ </View>+ ) : null}+ </ScrollView>+ );+}+const makeStyles = (c: ThemeColors) =>+ StyleSheet.create({+ content: {+ paddingHorizontal: spacing.lg + spacing.xs,+ paddingVertical: spacing.lg,+ paddingBottom: spacing.xxl,+ },+ identity: {+ gap: spacing.lg,+ paddingTop: spacing.sm,+ paddingBottom: spacing.lg,+ },+ hero: { flexDirection: "row", alignItems: "center", gap: spacing.lg },+ identityText: { flex: 1, gap: spacing.xs },+ icon: { width: 72, height: 72, borderRadius: radius.container },+ fallback: {+ alignItems: "center",+ justifyContent: "center",+ backgroundColor: c.surfaceChip,+ },+ title: {+ fontSize: typeScale.title,+ lineHeight: lineHeight.title,+ fontWeight: fontWeight.semibold,+ color: c.textPrimary,+ },+ note: {+ fontSize: typeScale.bodySmall,+ lineHeight: lineHeight.bodySmall,+ color: c.textSecondary,+ },+ status: { gap: spacing.md, paddingVertical: spacing.lg },+ use: { gap: spacing.md, paddingBottom: spacing.lg },+ titleRow: { flexDirection: "row", alignItems: "center", gap: spacing.sm },+ titleText: { flex: 1 },+ information: {+ gap: spacing.md,+ paddingVertical: spacing.lg,+ },+ factSeparator: {+ borderBottomWidth: StyleSheet.hairlineWidth,+ borderBottomColor: c.border,+ paddingBottom: spacing.md,+ },+ toolsToggle: {+ minWidth: 44,+ minHeight: 44,+ alignItems: "flex-end",+ justifyContent: "center",+ },+ toolsToggleText: {+ fontSize: typeScale.body,+ lineHeight: lineHeight.body,+ color: c.inputCaret,+ },+ informationRow: {+ flexDirection: "row",+ alignItems: "center",+ minHeight: 44,+ gap: spacing.sm,+ },+ toolDescription: { gap: spacing.xs },+ metadataValue: { textAlign: "right" },+ metadataRow: {+ flexDirection: "row",+ alignItems: "center",+ gap: spacing.md,+ },+ sectionHeading: {+ fontSize: typeScale.subtitle,+ lineHeight: lineHeight.subtitle,+ fontWeight: fontWeight.semibold,+ color: c.textPrimary,+ },+ actions: { flexDirection: "row", gap: spacing.md },+ verticalActions: { flexDirection: "column" },+ button: {+ flexGrow: 1,+ flexBasis: 0,+ minHeight: 48,+ paddingHorizontal: spacing.lg,+ paddingVertical: spacing.md,+ borderRadius: radius.pill,+ alignItems: "center",+ justifyContent: "center",+ },+ primary: { backgroundColor: c.cta },+ secondary: { backgroundColor: c.surfaceChip },+ buttonText: {+ fontSize: typeScale.body,+ lineHeight: lineHeight.body,+ fontWeight: fontWeight.semibold,+ color: c.textPrimary,+ textAlign: "center",+ },+ primaryText: { color: c.ctaText },+ row: {+ minHeight: 60,+ flexDirection: "row",+ alignItems: "center",+ gap: spacing.md,+ paddingVertical: spacing.lg,+ borderBottomWidth: StyleSheet.hairlineWidth,+ borderBottomColor: c.border,+ },+ rowText: {+ flex: 1,+ fontSize: typeScale.body,+ lineHeight: lineHeight.body,+ color: c.textPrimary,+ },+ unavailable: { opacity: 0.5 },+ });diff --git a/apps/mobile/src/plugins/PluginDirectoryView.ios.tsx b/apps/mobile/src/plugins/PluginDirectoryView.ios.tsxnew file mode 100644index 0000000000..2ff7efac66--- /dev/null+++ b/apps/mobile/src/plugins/PluginDirectoryView.ios.tsx@@ -0,0 +1,302 @@+import {+ Host,+ Button,+ Circle,+ HStack,+ Image,+ List,+ Menu,+ Picker,+ ProgressView,+ RNHostView,+ Spacer,+ Text,+ VStack,+} from "@expo/ui/swift-ui";+import {+ accessibilityLabel,+ background,+ contentShape,+ font,+ fixedSize,+ foregroundStyle,+ frame,+ lineLimit,+ listRowBackground,+ listRowInsets,+ listRowSeparatorTint,+ listRowSeparator,+ listStyle,+ pickerStyle,+ refreshable,+ scrollContentBackground,+ scrollDismissesKeyboard,+ shapes,+ tag,+} from "@expo/ui/swift-ui/modifiers";+import { Image as RNImage, StyleSheet, View } from "react-native";+import { Puzzle } from "lucide-react-native";+import { useTranslation } from "react-i18next";+import { resolveRemoteText } from "@cindy/device-link";+import { ComposerNativeRow } from "@/session/ComposerNativeRow";+import { iconSize, radius, spacing, useTheme } from "@/theme";+import type { PluginDirectoryViewProps } from "./PluginDirectoryView";++export function PluginDirectoryView(p: PluginDirectoryViewProps) {+ const { t, i18n } = useTranslation();+ const { mode, colors } = useTheme();+ const listFailed = p.error;+ const text = (value: Parameters<typeof resolveRemoteText>[0]) =>+ resolveRemoteText(value, i18n.language);+ const row = (+ item: PluginDirectoryViewProps["items"][number],+ first = false,+ ) => {+ const uri = item.item.display.avatar?.value;+ const preview = item.item.display.preview ?? item.item.display.subtitle;+ const subtitle = [+ !p.isOnline(item) ? t("plugins.notConnected") : "",+ p.targets.length > 1 ? item.host.deviceName : "",+ preview ? text(preview) : "",+ ]+ .filter(Boolean)+ .join(" · ");+ return (+ <VStack+ key={item.key}+ modifiers={[+ ...sectionModifiers,+ ...(first ? [listRowSeparator("hidden", "top")] : []),+ ]}+ >+ <ComposerNativeRow+ key={item.key}+ testID={`plugins.row.${item.item.ref.id}`}+ title={text(item.item.display.title)}+ subtitle={subtitle}+ subtitleContent={+ subtitle ? (+ <Text+ modifiers={[+ font({ textStyle: "subheadline" }),+ foregroundStyle(colors.textSecondary),+ lineLimit(1),+ ]}+ >+ {subtitle}+ </Text>+ ) : undefined+ }+ selected={p.selectedKey === item.key}+ titleAccessory={+ item.item.display.badges?.length ? (+ <Circle+ modifiers={[+ frame({ width: 6, height: 6 }),+ foregroundStyle(colors.statusDone),+ accessibilityLabel(t("plugins.unread")),+ ]}+ />+ ) : undefined+ }+ leading={+ uri &&+ /^data:image\/(?:png|jpeg|webp|svg\+xml);base64,/.test(uri) ? (+ <RNHostView matchContents>+ <RNImage source={{ uri }} style={styles.icon} />+ </RNHostView>+ ) : (+ <RNHostView matchContents>+ <View+ style={[+ styles.icon,+ styles.fallback,+ { backgroundColor: colors.surfaceChip },+ ]}+ >+ <Puzzle size={iconSize.lg} color={colors.textSecondary} />+ </View>+ </RNHostView>+ )+ }+ onPress={() => p.onOpen(item)}+ onOptions={() => p.onDetail(item)}+ optionsLabel={t("plugins.detailsFor", {+ name: text(item.item.display.title),+ })}+ optionsIcon={+ <Image+ systemName="info.circle"+ size={iconSize.lg}+ modifiers={[foregroundStyle(colors.textSecondary)]}+ />+ }+ />+ </VStack>+ );+ };+ const sectionModifiers = [+ listRowBackground(colors.surface),+ listRowInsets({+ leading: spacing.lg + spacing.xs,+ trailing: spacing.lg + spacing.xs,+ top: spacing.md,+ bottom: spacing.md,+ }),+ ];+ const installedHeader = (+ <HStack+ testID="plugins.installedHeader"+ modifiers={[+ listRowBackground(colors.surface),+ listRowSeparator("hidden"),+ fixedSize({ horizontal: false, vertical: true }),+ frame({ height: 44 }),+ listRowInsets({+ leading: spacing.lg + spacing.xs,+ trailing: spacing.lg + spacing.xs,+ top: 0,+ bottom: 0,+ }),+ ]}+ >+ <Text+ modifiers={[+ font({ textStyle: "footnote", weight: "semibold" }),+ foregroundStyle(colors.textTertiary),+ ]}+ >+ {t("plugins.installed")}+ </Text>+ <Spacer />+ <Menu+ testID="plugins.computer"+ label={+ <HStack+ spacing={spacing.xs}+ modifiers={[+ frame({ minHeight: 44 }),+ contentShape(shapes.rectangle()),+ ]}+ >+ <Text+ modifiers={[+ font({ textStyle: "footnote" }),+ lineLimit(1),+ foregroundStyle(colors.textSecondary),+ ]}+ >+ {p.targets.find((host) => host.deviceId === p.deviceId)+ ?.deviceName ?? t("plugins.allComputers")}+ </Text>+ <Image+ systemName="chevron.down"+ size={iconSize.xs}+ modifiers={[foregroundStyle(colors.textSecondary)]}+ />+ </HStack>+ }+ modifiers={[accessibilityLabel(t("plugins.computer"))]}+ >+ <Picker+ label={t("plugins.computer")}+ selection={p.deviceId}+ onSelectionChange={p.onDeviceChange}+ modifiers={[pickerStyle("inline")]}+ testID="plugins.computer.options"+ >+ <Text modifiers={[tag("")]}>{t("plugins.allComputers")}</Text>+ {p.targets.map((host) => (+ <Text key={host.deviceId} modifiers={[tag(host.deviceId)]}>+ {host.deviceName}+ </Text>+ ))}+ </Picker>+ </Menu>+ </HStack>+ );+ return (+ <Host+ colorScheme={mode}+ style={styles.root}+ seedColor={colors.textPrimary}+ ignoreSafeArea="container"+ >+ <List+ modifiers={[+ // Ordinary title rows scroll with the list and have no section boundary.+ listStyle("plain"),+ scrollContentBackground("hidden"),+ background(colors.surface),+ listRowSeparatorTint(colors.border),+ scrollDismissesKeyboard("interactively"),+ refreshable(p.onRefresh),+ ]}+ testID="plugins.list"+ >+ {installedHeader}+ {p.loading && !p.items.length ? (+ <ProgressView+ modifiers={[...sectionModifiers, listRowSeparator("hidden")]}+ />+ ) : null}+ {p.items.map((item, index) => row(item, index === 0))}+ {!p.loading && !listFailed && !p.items.length ? (+ <VStack+ alignment="leading"+ spacing={spacing.md}+ modifiers={[...sectionModifiers, listRowSeparator("hidden")]}+ >+ <Text>+ {t(+ p.query+ ? "plugins.noResults"+ : p.targets.length+ ? "plugins.noPlugins"+ : "plugins.noComputer",+ )}+ </Text>+ {!p.targets.length ? (+ <Button+ label={t("plugins.connectComputer")}+ onPress={p.onConnectComputer}+ />+ ) : null}+ </VStack>+ ) : null}+ {listFailed ? (+ <VStack+ alignment="leading"+ spacing={spacing.md}+ modifiers={[...sectionModifiers, listRowSeparator("hidden")]}+ >+ <Text+ modifiers={[+ font({ textStyle: "footnote" }),+ foregroundStyle(colors.textSecondary),+ ]}+ >+ {t(+ p.items.length+ ? "plugins.listUnavailable"+ : "plugins.listLoadFailed",+ )}+ </Text>+ {!p.items.length && !p.loading ? (+ <Button+ label={t("plugins.detail.action.retry")}+ onPress={() => void p.onRefresh()}+ testID="plugins.retryList"+ />+ ) : null}+ </VStack>+ ) : null}+ </List>+ </Host>+ );+}+const styles = StyleSheet.create({+ root: { flex: 1 },+ icon: { width: 54, height: 54, borderRadius: radius.container },+ fallback: { alignItems: "center", justifyContent: "center" },+});diff --git a/apps/mobile/src/plugins/PluginDirectoryView.tsx b/apps/mobile/src/plugins/PluginDirectoryView.tsxnew file mode 100644index 0000000000..671afd34d3--- /dev/null+++ b/apps/mobile/src/plugins/PluginDirectoryView.tsx@@ -0,0 +1,25 @@+import type {+ HostedRemoteCollectionItem,+ RemoteResourceHostTarget,+} from "@/device-link/remoteResources";++export interface PluginDirectoryViewProps {+ targets: readonly RemoteResourceHostTarget[];+ deviceId: string;+ onDeviceChange(value: string): void;+ query: string;+ items: HostedRemoteCollectionItem[];+ selectedKey?: string;+ loading: boolean;+ error: boolean;+ isOnline(row: HostedRemoteCollectionItem): boolean;+ onRefresh(): Promise<void>;+ onOpen(row: HostedRemoteCollectionItem): void;+ onDetail(row: HostedRemoteCollectionItem): void;+ onConnectComputer(): void;+}++/** iOS renders the system list; other platforms keep the directory in PluginsScreen. */+export function PluginDirectoryView(_props: PluginDirectoryViewProps) {+ return null;+}diff --git a/apps/mobile/src/plugins/PluginPage.tsx b/apps/mobile/src/plugins/PluginPage.tsxindex 1434c0125f..3c6a2f39e8 100644--- a/apps/mobile/src/plugins/PluginPage.tsx+++ b/apps/mobile/src/plugins/PluginPage.tsx@@ -69,6 +69,7 @@ export function PluginPage({visible = true,registerBack,onTitle,+ onLoaded,}: {deviceId: string;pluginId: string;@@ -76,6 +77,7 @@ export function PluginPage({visible?: boolean;registerBack?(handler: (() => void) | null): void;onTitle?(title: string): void;+ onLoaded?(): void;onTask(id: string): void;}) {const { t } = useTranslation();@@ -85,6 +87,8 @@ export function PluginPage({const routeFocused = useIsFocused(),focused = routeFocused && visible;const webview = useRef<WebView>(null);+ const loadedCallback = useRef(onLoaded);+ loadedCallback.current = onLoaded;const draftOwner = useRef(getMobileAuthOwner()).current;const draftQueue = useRef(Promise.resolve());const [attempt, setAttempt] = useState(0);@@ -209,6 +213,7 @@ export function PluginPage({if (!current()) return;documentRef.current = page;setContent({ document: page, assets });+ loadedCallback.current?.();// Polling starts only after ready, so startup events cannot disappear before the WebView mounts.} catch {if (current()) setError(true);diff --git a/apps/mobile/src/plugins/PluginTaskPicker.tsx b/apps/mobile/src/plugins/PluginTaskPicker.tsxindex 599820e85c..c93447af06 100644--- a/apps/mobile/src/plugins/PluginTaskPicker.tsx+++ b/apps/mobile/src/plugins/PluginTaskPicker.tsx@@ -1,36 +1,11 @@-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 { useEffect, useState } from "react";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";+import { PluginTaskPickerView } from "./PluginTaskPickerView";/** Host task chooser. Its list is never exposed to plugin JavaScript or cindy.tasks. */export function PluginTaskPicker({@@ -44,21 +19,7 @@ export function PluginTaskPicker({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 { invoke } = useDeviceLink();const [query, setQuery] = useState("");const [rows, setRows] = useState<RemoteSession[]>([]);const [loading, setLoading] = useState(false),@@ -73,7 +34,6 @@ export function PluginTaskPicker({setQuery("");setLoading(true);setError(false);- setSnap("half");void invoke<RemoteSession[]>(deviceId,"local-db:sessions:list",@@ -110,96 +70,17 @@ export function PluginTaskPicker({};}, [deviceId, visible, invoke, attempt]);return (- <SheetModal- nativePresentation+ <PluginTaskPickerView+ deviceId={deviceId}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>+ query={query}+ rows={rows}+ loading={loading}+ error={error}+ onChangeQuery={setQuery}+ onRetry={() => setAttempt((value) => value + 1)}+ onClose={onClose}+ onSelect={onSelect}+ />);}-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/PluginTaskPickerView.ios.tsx b/apps/mobile/src/plugins/PluginTaskPickerView.ios.tsxnew file mode 100644index 0000000000..3d248fc016--- /dev/null+++ b/apps/mobile/src/plugins/PluginTaskPickerView.ios.tsx@@ -0,0 +1,226 @@+import { useEffect, useRef } from "react";+import {+ Button,+ HStack,+ Image,+ ProgressView,+ Text,+ TextField,+ VStack,+ useNativeState,+ type TextFieldRef,+} from "@expo/ui/swift-ui";+import {+ accessibilityLabel,+ autocorrectionDisabled,+ background,+ buttonStyle,+ contentShape,+ fixedSize,+ font,+ foregroundStyle,+ frame,+ lineLimit,+ listRowBackground,+ listRowInsets,+ listRowSeparator,+ padding,+ shapes,+ textInputAutocapitalization,+ textFieldStyle,+ submitLabel,+ onSubmit,+} from "@expo/ui/swift-ui/modifiers";+import { useTranslation } from "react-i18next";+import { PlatformColor } from "react-native";+import {+ getMobileAuthOwner,+ isMobileAuthOwnerCurrent,+} from "@/auth/authOwnerGeneration";+import { ComposerSheet } from "@/session/ComposerSheet";+import { ComposerNativeRow } from "@/session/ComposerNativeRow";+import { iconSize, radius, spacing, useTheme } from "@/theme";+import type { PluginTaskPickerViewProps } from "./PluginTaskPickerView";++/** Ungrouped native task list inside the shared system sheet. */+export function PluginTaskPickerView(p: PluginTaskPickerViewProps) {+ const { t } = useTranslation();+ const { colors } = useTheme();+ const query = useNativeState(p.query);+ const input = useRef<TextFieldRef>(null);+ const pending = useRef<{+ id: string;+ owner: ReturnType<typeof getMobileAuthOwner>;+ } | null>(null);+ useEffect(() => {+ if (query.get() !== p.query) query.set(p.query);+ }, [p.query, query]);+ useEffect(() => {+ pending.current = null;+ }, [p.deviceId]);+ const rows = p.rows.filter((row) =>+ row.title.toLocaleLowerCase().includes(p.query.toLocaleLowerCase()),+ );+ return (+ <ComposerSheet+ visible={p.visible}+ title={t("plugins.chooseTask")}+ nativeContent+ nativeList+ testID="plugins.taskPicker"+ onClose={() => {+ pending.current = null;+ p.onClose();+ }}+ onClosed={() => {+ const selected = pending.current;+ pending.current = null;+ if (selected && isMobileAuthOwnerCurrent(selected.owner))+ p.onSelect(selected.id);+ }}+ nativeHeader={+ <VStack+ modifiers={[+ fixedSize({ horizontal: false, vertical: true }),+ padding({+ horizontal: spacing.lg + spacing.xs,+ bottom: spacing.sm,+ }),+ ]}+ >+ <HStack+ spacing={spacing.sm}+ modifiers={[+ padding({ horizontal: spacing.md }),+ frame({ height: 44 }),+ background(+ PlatformColor("tertiarySystemFill"),+ shapes.roundedRectangle({ cornerRadius: radius.control }),+ ),+ ]}+ >+ <Image+ systemName="magnifyingglass"+ size={iconSize.md}+ modifiers={[foregroundStyle(colors.textSecondary)]}+ />+ <TextField+ ref={input}+ text={query}+ placeholder={t("plugins.searchTasks")}+ onTextChange={p.onChangeQuery}+ testID="plugins.taskSearch"+ modifiers={[+ frame({ maxWidth: Infinity, minHeight: 44 }),+ textFieldStyle("plain"),+ font({ textStyle: "body" }),+ foregroundStyle(colors.textPrimary),+ submitLabel("search"),+ onSubmit(() => void input.current?.blur()),+ autocorrectionDisabled(true),+ textInputAutocapitalization("never"),+ accessibilityLabel(t("plugins.searchTasks")),+ ]}+ >+ <TextField.Placeholder>+ <Text modifiers={[foregroundStyle(colors.textPlaceholder)]}>+ {t("plugins.searchTasks")}+ </Text>+ </TextField.Placeholder>+ </TextField>+ {p.query ? (+ <Button+ onPress={() => {+ query.set("");+ p.onChangeQuery("");+ }}+ testID="plugins.clearTaskSearch"+ modifiers={[+ buttonStyle("plain"),+ accessibilityLabel(t("plugins.clearTaskSearch")),+ frame({ width: 44, height: 44 }),+ contentShape(shapes.rectangle()),+ ]}+ >+ <Image+ systemName="xmark.circle.fill"+ size={iconSize.md}+ modifiers={[foregroundStyle(colors.textSecondary)]}+ />+ </Button>+ ) : null}+ </HStack>+ </VStack>+ }+ >+ {p.loading ? (+ <ProgressView+ testID="plugins.tasksLoading"+ modifiers={[listRowBackground("clear"), listRowSeparator("hidden")]}+ />+ ) : p.error ? (+ <>+ <Text modifiers={[foregroundStyle(colors.textSecondary)]}>+ {t("plugins.loadFailed")}+ </Text>+ <ComposerNativeRow+ title={t("plugins.retry")}+ onPress={p.onRetry}+ testID="plugins.retryTasks"+ />+ </>+ ) : rows.length ? (+ rows.map((row) => (+ <VStack+ key={row.id}+ modifiers={[+ listRowBackground("clear"),+ listRowInsets({+ leading: spacing.lg + spacing.xs,+ trailing: spacing.lg + spacing.xs,+ top: spacing.md,+ bottom: spacing.md,+ }),+ ]}+ >+ <ComposerNativeRow+ title={row.title}+ subtitle={row.preview || undefined}+ subtitleContent={+ row.preview ? (+ <Text+ modifiers={[+ font({ textStyle: "caption" }),+ foregroundStyle(colors.textSecondary),+ lineLimit(2),+ ]}+ >+ {row.preview}+ </Text>+ ) : undefined+ }+ onPress={() => {+ if (!p.visible || p.loading || p.error || pending.current)+ return;+ pending.current = { id: row.id, owner: getMobileAuthOwner() };+ p.onClose();+ }}+ testID={"plugins.task." + row.id}+ />+ </VStack>+ ))+ ) : (+ <Text+ modifiers={[+ foregroundStyle(colors.textSecondary),+ listRowBackground("clear"),+ listRowSeparator("hidden"),+ ]}+ testID="plugins.noTasks"+ >+ {t(p.rows.length ? "plugins.noMatchingTasks" : "plugins.noTasks")}+ </Text>+ )}+ </ComposerSheet>+ );+}diff --git a/apps/mobile/src/plugins/PluginTaskPickerView.tsx b/apps/mobile/src/plugins/PluginTaskPickerView.tsxnew file mode 100644index 0000000000..56a17a6d54--- /dev/null+++ b/apps/mobile/src/plugins/PluginTaskPickerView.tsx@@ -0,0 +1,162 @@+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 { 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";++export interface PluginTaskPickerViewProps {+ deviceId: string;+ visible: boolean;+ query: string;+ rows: RemoteSession[];+ loading: boolean;+ error: boolean;+ onChangeQuery(query: string): void;+ onRetry(): void;+ onClose(): void;+ onSelect(sessionId: string): void;+}++export function PluginTaskPickerView({+ visible,+ query,+ rows,+ loading,+ error,+ onChangeQuery: setQuery,+ onRetry,+ onClose,+ onSelect,+}: PluginTaskPickerViewProps) {+ const { 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");+ useEffect(() => {+ if (visible) setSnap("half");+ }, [visible]);+ const matches = rows.filter((row) =>+ row.title.toLocaleLowerCase().includes(query.toLocaleLowerCase()),+ );+ 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={() => onRetry()}>+ <Text style={styles.title}>{t("plugins.retry")}</Text>+ </Pressable>+ </View>+ ) : (+ matches.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 && !matches.length ? (+ <Text style={styles.note}>+ {t(rows.length ? "plugins.noMatchingTasks" : "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/PluginToolChips.tsx b/apps/mobile/src/plugins/PluginToolChips.tsxnew file mode 100644index 0000000000..3adc154bd4--- /dev/null+++ b/apps/mobile/src/plugins/PluginToolChips.tsx@@ -0,0 +1,114 @@+import { useState } from "react";+import { StyleSheet, View, useWindowDimensions } from "react-native";+import { Wrench } from "lucide-react-native";+import { MAX_FONT_SIZE_MULTIPLIER, Text } from "@/components/AppText";+import {+ iconSize,+ lineHeight,+ radius,+ spacing,+ typeScale,+ useTheme,+} from "@/theme";+import type { PluginDetailModel } from "./pluginDetailModel";++/** Keep full flow layout for measurement while hiding rows after the second. */+export function PluginToolChips({+ tools,+ expanded,+ width,+ onOverflowChange,+}: {+ tools: NonNullable<PluginDetailModel["tools"]>;+ expanded: boolean;+ width?: number;+ onOverflowChange(overflow: boolean): void;+}) {+ const { colors } = useTheme();+ const { fontScale } = useWindowDimensions();+ const chipHeight =+ lineHeight.bodySmall * Math.min(fontScale, MAX_FONT_SIZE_MULTIPLIER) ++ spacing.xs * 2;+ const collapsedHeight = chipHeight * 2 + spacing.sm;+ const [hidden, setHidden] = useState<Set<number>>(new Set());+ return (+ <View+ testID="plugins.toolChips"+ style={[+ styles.clip,+ width !== undefined && { width },+ !expanded && { maxHeight: collapsedHeight },+ ]}+ >+ <View+ testID="plugins.toolChipsFlow"+ style={styles.flow}+ onLayout={({ nativeEvent: { layout } }) =>+ onOverflowChange(layout.height > collapsedHeight + 0.5)+ }+ >+ {tools.map((tool, index) => {+ const clipped = !expanded && hidden.has(index);+ return (+ <View+ key={tool.name + index}+ testID={"plugins.toolChip." + index}+ accessibilityElementsHidden={clipped}+ importantForAccessibility={+ clipped ? "no-hide-descendants" : "auto"+ }+ onLayout={({ nativeEvent: { layout } }) => {+ const beyondSecondRow =+ layout.y + layout.height > collapsedHeight + 0.5;+ setHidden((previous) => {+ if (previous.has(index) === beyondSecondRow) return previous;+ const next = new Set(previous);+ if (beyondSecondRow) next.add(index);+ else next.delete(index);+ return next;+ });+ }}+ style={[+ styles.chip,+ { height: chipHeight, backgroundColor: colors.surfaceChip },+ clipped && styles.hidden,+ ]}+ >+ <Wrench size={iconSize.xs} color={colors.textSecondary} />+ <Text+ numberOfLines={1}+ style={[styles.name, { color: colors.textSecondary }]}+ >+ {tool.name}+ </Text>+ </View>+ );+ })}+ </View>+ </View>+ );+}++const styles = StyleSheet.create({+ clip: { overflow: "hidden" },+ flow: {+ flexDirection: "row",+ flexWrap: "wrap",+ gap: spacing.sm,+ flexShrink: 0,+ },+ chip: {+ maxWidth: "100%",+ flexDirection: "row",+ alignItems: "center",+ gap: spacing.xs,+ paddingHorizontal: spacing.sm,+ borderRadius: radius.pill,+ },+ name: {+ flexShrink: 1,+ fontSize: typeScale.bodySmall,+ lineHeight: lineHeight.bodySmall,+ },+ hidden: { opacity: 0 },+});diff --git a/apps/mobile/src/plugins/PluginsScreen.tsx b/apps/mobile/src/plugins/PluginsScreen.tsxindex ed2fa7db22..afe018b88a 100644--- a/apps/mobile/src/plugins/PluginsScreen.tsx+++ b/apps/mobile/src/plugins/PluginsScreen.tsx@@ -5,24 +5,33 @@ import {BackHandler,Image,Pressable,+ Platform,RefreshControl,ScrollView,StyleSheet,View,useWindowDimensions,} from "react-native";-import { useIsFocused, useRouter } from "expo-router";+import {+ Stack,+ useIsFocused,+ useRouter,+ useLocalSearchParams,+} from "expo-router";+import {+ pluginVisualPreview,+ pluginVisualScenario,+} from "@/debug/pluginVisualFixture";+import type { SearchBarCommands } from "react-native-screens";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,@@ -58,10 +67,13 @@ import {getMobileAuthOwner,isMobileAuthOwnerCurrent,} from "@/auth/authOwnerGeneration";+import { pluginDetailModel } from "./pluginDetailModel";+import { PluginDirectoryView } from "./PluginDirectoryView";+import { PluginDetailView } from "./PluginDetailView";import { PluginTaskPicker } from "./PluginTaskPicker";-import { PluginTaskSettings } from "./PluginTaskSettings";import { PluginPage } from "./PluginPage";import { invokePlugin } from "./pluginClient";+import { sortPluginItems } from "./pluginListOrder";export default function PluginsScreen() {const auth = useAuth();@@ -72,6 +84,8 @@ function PluginDirectory() {router = useRouter(),focused = useIsFocused();const { t, i18n } = useTranslation();+ const { preview } = useLocalSearchParams<{ preview?: string }>();+ const previewSelection = useRef<string | undefined>(undefined);const { invoke } = useDeviceLink();const { colors } = useTheme(),styles = useThemedStyles(makeStyles);@@ -91,19 +105,65 @@ function PluginDirectory() {[devices.devices],);const list = useRemoteResourceList("plugins", targets);+ const listFailed = Boolean(+ devices.error || (targets.length > 0 && list.error),+ );+ const directoryLoading = Boolean(devices.loading || list.loading);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 [detailLoading, setDetailLoading] = useState(false);+ const [detailFailed, setDetailFailed] = useState(false);+ const [settingsOpen, setSettingsOpen] = useState(false);const [recent, setRecent] = useState<string[]>([]);const [busy, setBusy] = useState(false);+ const enableLock = useRef(false);const [taskPicker, setTaskPicker] = useState(false);const [pageTitle, setPageTitle] = useState("");+ const searchVisible = Platform.OS === "ios" && (!selected || wide);+ const latestQuery = useRef(query);+ latestQuery.current = query;+ const searchBar = useMemo(() => {+ let current: SearchBarCommands | null = null;+ return {+ get current() {+ return current;+ },+ set current(bar: SearchBarCommands | null) {+ current = bar;+ // Stack options attach UISearchBar after the page effect has run.+ // Initialize on attachment, never replay JS updates over native typing.+ bar?.setText(latestQuery.current);+ },+ };+ }, []);+ const searchOptions = useMemo(+ () => ({+ headerSearchBarOptions: searchVisible+ ? {+ ref: searchBar,+ placeholder: t("plugins.search"),+ placement: "stacked" as const,+ hideWhenScrolling: false,+ hideNavigationBar: false,+ obscureBackground: false,+ autoCapitalize: "none" as const,+ tintColor: colors.inputCaret,+ textColor: colors.textPrimary,+ onChangeText: (event: { nativeEvent: { text: string } }) =>+ setQuery(event.nativeEvent.text),+ onCancelButtonPress: () => setQuery(""),+ onSearchButtonPress: () => searchBar.current?.blur(),+ }+ : undefined,+ }),+ [searchVisible, searchBar, t, colors.inputCaret, colors.textPrimary],+ );useEffect(() => {setPageTitle("");}, [selected?.row.key, selected?.surface]);@@ -112,13 +172,14 @@ function PluginDirectory() {pageBack.current = handler;}, []);const goBack = useCallback(() => {- if (detailOpen && selected?.surface) setDetailOpen(false);+ if (settingsOpen) setSettingsOpen(false);+ else 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]);+ }, [detailOpen, settingsOpen, selected, wide, router]);useEffect(() => {if (!focused || !selected || wide) return;const listener = BackHandler.addEventListener("hardwareBackPress", () => {@@ -140,14 +201,14 @@ function PluginDirectory() {!isMobileAuthOwnerCurrent(recentOwner) ||recentTouched.current ||!raw ||- raw.length > 8000+ raw.length > 64_000)return;try {const value = JSON.parse(raw);if (Array.isArray(value))setRecent(- value.filter((key) => typeof key === "string").slice(0, 6),+ value.filter((key) => typeof key === "string").slice(0, 100),);} catch {/* optional local history */@@ -165,15 +226,25 @@ function PluginDirectory() {() => {},);}, [recent, recentKey, recentOwner]);+ const markUsed = (key: string) => {+ if (!isMobileAuthOwnerCurrent(recentOwner)) return;+ recentTouched.current = true;+ setRecent((current) =>+ [key, ...current.filter((item) => item !== key)].slice(0, 100),+ );+ };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) &&+ const scopedItems = list.items.filter(+ ({ host }) => !deviceId || host.deviceId === deviceId,+ );+ const items = sortPluginItems(+ scopedItems.filter(({ item }) =>`${text(item.display.title)} ${item.display.subtitle ? text(item.display.subtitle) : ""}`.toLocaleLowerCase().includes(query.toLocaleLowerCase()),+ ),+ recent,);const showDetail = async (row: HostedRemoteCollectionItem) => {const generation = ++detailGeneration.current,@@ -182,7 +253,14 @@ function PluginDirectory() {current?.row.key === row.key ? { ...current, row } : { row },);setDetailOpen(true);+ setSettingsOpen(false);setDetail(undefined);+ setDetailFailed(false);+ if (!list.isOnline(row.host)) {+ setDetailLoading(false);+ return;+ }+ setDetailLoading(true);try {const resource = await getRemoteResource(invoke,@@ -194,22 +272,79 @@ function PluginDirectory() {if (generation === detailGeneration.current &&isMobileAuthOwnerCurrent(owner)- )+ ) {setDetail(resource);+ setSelected((current) =>+ current?.row.key === row.key+ ? { ...current, row: { ...row, item: resource } }+ : current,+ );+ }} catch {if (generation === detailGeneration.current &&isMobileAuthOwnerCurrent(owner))- Alert.alert(t("plugins.loadFailed"));+ setDetailFailed(true);+ } finally {+ if (+ generation === detailGeneration.current &&+ isMobileAuthOwnerCurrent(owner)+ )+ setDetailLoading(false);}};+ // Returning from a task or reconnecting may invalidate the previous Host facts.+ const selectedOnline = selected ? list.isOnline(selected.row.host) : false;+ const previousFocus = useRef(focused);+ const previousConnection = useRef({+ key: selected?.row.key,+ online: selectedOnline,+ });+ useEffect(() => {+ const returned = focused && !previousFocus.current;+ const reconnected =+ previousConnection.current.key === selected?.row.key &&+ !previousConnection.current.online &&+ selectedOnline;+ previousFocus.current = focused;+ previousConnection.current = {+ key: selected?.row.key,+ online: selectedOnline,+ };+ if (+ focused &&+ selected &&+ detailOpen &&+ selectedOnline &&+ !enableLock.current &&+ (returned || reconnected || (!detailLoading && !detail && !detailFailed))+ )+ void showDetail(selected.row);+ }, [focused, selectedOnline, selected?.row.key]);+ useEffect(() => {+ const target = pluginVisualPreview(preview);+ if (!target || previewSelection.current === preview) return;+ const row = list.items.find(+ (row) =>+ row.host.deviceId === "cindy-visual-mock-mac" &&+ row.item.ref.id === target.id,+ );+ if (!row) return;+ previewSelection.current = preview;+ const pending = showDetail(row);+ const generation = detailGeneration.current;+ void pending.then(() => {+ if (target.settings && generation === detailGeneration.current)+ setSettingsOpen(true);+ });+ }, [preview, list.items]);const open = (row: HostedRemoteCollectionItem,surface?: PluginPageSurface,) => {if (!list.isOnline(row.host)) {- Alert.alert(t("plugins.offline"));+ void showDetail(row);return;}const action = surface@@ -221,20 +356,19 @@ function PluginDirectory() {return;}detailGeneration.current += 1;- recentTouched.current = true;setDetailOpen(false);+ setSettingsOpen(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)+ if (selected) {+ markUsed(selected.row.key);router.push({pathname: "/sessions/[sessionId]",params: { sessionId, deviceId: selected.row.host.deviceId },});+ }},[router, selected],);@@ -315,250 +449,259 @@ function PluginDirectory() {</Pressable></View>);- const directory = (- <View style={[styles.directory, wide && styles.sidebar]}>- <View style={styles.controls}>- <Pressable- accessibilityRole="button"- style={styles.device}- onPress={selectDevice}+ const directory =+ Platform.OS === "ios" ? (+ <View style={[styles.directory, wide && styles.sidebar]}>+ <PluginDirectoryView+ targets={targets}+ deviceId={deviceId}+ onDeviceChange={setDeviceId}+ query={query}+ items={items}+ selectedKey={wide ? selected?.row.key : undefined}+ loading={directoryLoading}+ error={listFailed}+ isOnline={(row) => list.isOnline(row.host)}+ onRefresh={async () => {+ devices.refresh();+ await list.refresh();+ }}+ onOpen={open}+ onDetail={(row) => {+ void showDetail(row);+ }}+ onConnectComputer={() => router.push("/devices/manage")}+ />+ </View>+ ) : (+ <View style={[styles.directory, wide && styles.sidebar]}>+ <ScrollView+ contentContainerStyle={styles.content}+ keyboardShouldPersistTaps="handled"+ keyboardDismissMode="on-drag"+ refreshControl={+ <RefreshControl+ refreshing={list.refreshing}+ onRefresh={() => {+ devices.refresh();+ void list.refresh();+ }}+ tintColor={colors.textSecondary}+ />+ }>- <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) => (+ <View style={styles.controls}><Pressable- key={value}accessibilityRole="button"- accessibilityState={{ selected: filter === value }}- onPress={() => setFilter(value)}- style={[styles.chip, filter === value && styles.selected]}+ style={styles.device}+ onPress={selectDevice}>- <Text style={styles.controlText}>{t(`plugins.${value}`)}</Text>+ <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>- </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 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>- </>- ) : 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",- )}+ </View>+ {directoryLoading && !items.length ? (+ <ActivityIndicator color={colors.textSecondary} />+ ) : null}+ <View style={styles.inline}>+ <Text style={[styles.groupLabel, { flex: 1 }]}>+ {t("plugins.installed")}</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;+ <View style={styles.groupCard}>{items.map(renderRow)}</View>+ {!directoryLoading && !listFailed && !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}+ {listFailed ? (+ <View>+ <Text style={styles.note}>+ {t(+ items.length+ ? "plugins.listUnavailable"+ : "plugins.listLoadFailed",+ )}+ </Text>+ {!items.length && !directoryLoading ? (+ <Pressable+ accessibilityRole="button"+ style={styles.button}+ onPress={() => {+ devices.refresh();+ void list.refresh();+ }}+ >+ <Text style={styles.controlText}>+ {t("plugins.detail.action.retry")}+ </Text>+ </Pressable>+ ) : null}+ </View>+ ) : null}+ </ScrollView>+ </View>+ );+ const enable = async (enabled: boolean) => {+ if (+ !selected ||+ !detail ||+ enableLock.current ||+ !list.isOnline(selected.row.host)+ )+ return;+ const actionId = enabled ? "enable" : "disable";+ if (+ !selected.row.item.actions?.some(+ (action) => action.id === actionId && !action.disabled,+ )+ )+ return;+ const row = selected.row,+ generation = detailGeneration.current,+ owner = getMobileAuthOwner();+ const current = () =>+ generation === detailGeneration.current &&+ isMobileAuthOwnerCurrent(owner);+ enableLock.current = true;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);+ await invokePlugin(invoke, row.host.deviceId, row.item.ref.id, actionId);} catch {- Alert.alert(t("plugins.actionFailed"));+ if (current()) Alert.alert(t("plugins.actionFailed"));} finally {- setBusy(false);+ // A failed reply may follow an applied write; confirm by reading, never replaying it.+ if (current()) await showDetail(row);+ enableLock.current = false;+ if (isMobileAuthOwnerCurrent(owner)) setBusy(false);+ void list.refresh();}};- 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>+ const enabled =+ selected?.row.item.actions?.some((action) => action.id === "disable") ??+ false;+ const demoScenario = pluginVisualScenario(+ selected?.row.host.deviceId,+ selected?.row.item.ref.id,);+ const online = selected+ ? list.isOnline(selected.row.host) && demoScenario?.state !== "offline"+ : false;+ const model = selected+ ? pluginDetailModel(+ selected.row,+ demoScenario?.state ? undefined : detail,+ online,+ detailLoading || demoScenario?.state === "loading",+ detailFailed || demoScenario?.state === "loadFailed",+ )+ : undefined;+ const newTask = () => {+ if (!selected || !model || busy || !online || !detail || !enabled) return;+ if (!model.canUseTasks) return;+ markUsed(selected.row.key);+ 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),+ }),+ },+ });+ };+ const resolveStatus = () => {+ if (!selected || !model || busy) return;+ switch (model.statusAction) {+ case "connect":+ router.push("/devices/manage");+ break;+ case "retry":+ void showDetail(selected.row);+ break;+ case "enable":+ void enable(true);+ break;+ case "reconnect":+ case "settings":+ Alert.alert(t("plugins.detail.computerSettings"));+ break;+ }+ };+ const detailView =+ selected && model ? (+ <PluginDetailView+ row={selected.row}+ enabled={enabled}+ busy={busy || detailLoading}+ online={online}+ model={model}+ previewLabel={+ demoScenario+ ? t("plugins.demo.hint") + " · " + demoScenario.label+ : undefined+ }+ settingsOpen={settingsOpen}+ onEnabledChange={(value) => {+ if (model.canToggle) void enable(value);+ }}+ onOpen={(surface) => open(selected.row, surface)}+ onNewTask={() => newTask()}+ onChooseTask={() => {+ if (model.canUseTasks && !busy) setTaskPicker(true);+ }}+ onSettings={() => setSettingsOpen(true)}+ onResolveStatus={resolveStatus}+ />+ ) : (+ <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}><SimpleStackHeadertitle={selected && !wide- ? (!detailOpen && selected.surface && pageTitle) ||+ ? (settingsOpen && t("plugins.settings")) ||+ (!detailOpen && selected.surface && pageTitle) ||text(selected.row.item.display.title): t("plugins.title")}@@ -577,13 +720,17 @@ function PluginDirectory() {) : undefined}/>+ {Platform.OS === "ios" ? <Stack.Screen options={searchOptions} /> : null}{selected ? (<PluginTaskPicker+ key={selected.row.key}deviceId={selected.row.host.deviceId}visible={taskPicker}onClose={() => setTaskPicker(false)}onSelect={(sessionId) => {setTaskPicker(false);+ if (!model?.canUseTasks || busy || !online) return;+ markUsed(selected.row.key);router.push({pathname: "/sessions/[sessionId]",params: {@@ -613,6 +760,7 @@ function PluginDirectory() {onTask={openTask}registerBack={registerBack}onTitle={setPageTitle}+ onLoaded={() => markUsed(selected.row.key)}/></View>) : null}@@ -636,9 +784,8 @@ const makeStyles = (c: ThemeColors) =>borderRightWidth: StyleSheet.hairlineWidth,borderRightColor: c.border,},- controls: { padding: spacing.md, gap: spacing.sm },+ controls: { 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,@@ -662,12 +809,6 @@ const makeStyles = (c: ThemeColors) =>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,@@ -679,12 +820,13 @@ const makeStyles = (c: ThemeColors) =>flex: 1,flexDirection: "row",alignItems: "center",- padding: spacing.md,+ paddingHorizontal: spacing.md,+ paddingVertical: spacing.lg,gap: spacing.md,- minHeight: 88,+ minHeight: 96,},rowText: { flex: 1, gap: spacing.xs },- icon: { width: 44, height: 44, borderRadius: radius.control },+ icon: { width: 54, height: 54, borderRadius: radius.container },fallback: {alignItems: "center",justifyContent: "center",@@ -702,7 +844,6 @@ const makeStyles = (c: ThemeColors) =>borderRadius: radius.pill,backgroundColor: c.statusDone,},- identity: { flexDirection: "row", alignItems: "center", gap: spacing.md },empty: {flex: 1,padding: spacing.xl,@@ -710,20 +851,7 @@ const makeStyles = (c: ThemeColors) =>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,diff --git a/apps/mobile/src/plugins/pluginDetailModel.ts b/apps/mobile/src/plugins/pluginDetailModel.tsnew file mode 100644index 0000000000..6f7f56fa9f--- /dev/null+++ b/apps/mobile/src/plugins/pluginDetailModel.ts@@ -0,0 +1,186 @@+import {+ parsePluginUsageSummary,+ type PluginPageSurface,+ type RemoteResource,+ type PluginConfigurationSummary,+} from "@cindy/device-link";+import type { HostedRemoteCollectionItem } from "@/device-link/remoteResources";++export type PluginDetailStatus =+ | "offline"+ | "loading"+ | "loadFailed"+ | "retired"+ | "approvalRequired"+ | "disabled"+ | "setupRequired"+ | "setupUnknown";+export interface PluginDetailModel {+ details?: Array<{ key: string; title: string; value: string }>;+ tools?: Array<{ name: string; description: string }>;+ permissions?: Array<{ title: string; description: string }>;+ description?: string;+ version?: string;+ status?: PluginDetailStatus;+ statusAction?: "connect" | "retry" | "enable" | "settings" | "reconnect";+ taskUsable: boolean;+ canUseTasks: boolean;+ canToggle: boolean;+ hasSettings: boolean;+ taskPreferences: boolean;+ mainSurface?: PluginPageSurface;+ mobileSettings: boolean;+ builtin: boolean;+ missing: string[];+ expired: string[];+ setupGroups: Array<{ missing: string[]; expired: string[] }>;+ runtimeIssue?: "crashed" | "fused";+ configuration?: PluginConfigurationSummary;+}++/** Presentation only. Every write still uses the existing Host action and authorization checks. */+export function pluginDetailModel(+ row: HostedRemoteCollectionItem,+ resource: RemoteResource | undefined,+ online: boolean,+ loading: boolean,+ loadFailed: boolean,+): PluginDetailModel {+ const capabilities = resource?.blocks?.find(+ (block) => block.id === "capabilities",+ )?.data as+ | {+ tasks?: boolean;+ usage?: unknown;+ tools?: unknown;+ permissions?: unknown;+ details?: unknown;+ }+ | undefined;+ const usage = parsePluginUsageSummary(capabilities?.usage);+ const enabled =+ row.item.actions?.some((action) => action.id === "disable") ?? false;+ const actions = row.item.actions ?? [];+ const main =+ actions.find((action) => action.id === "open:panel") ??+ actions.find((action) => action.id === "open:mainView");+ const mobileSettings = actions.some(+ (action) => action.id === "open:settings",+ );+ const taskPreferences = capabilities?.tasks === true;+ const status: PluginDetailStatus | undefined = !online+ ? "offline"+ : loadFailed+ ? "loadFailed"+ : loading+ ? "loading"+ : usage?.retired+ ? "retired"+ : usage?.approvalRequired+ ? "approvalRequired"+ : !enabled+ ? "disabled"+ : usage?.setup.state === "required"+ ? "setupRequired"+ : usage?.setup.state === "unknown"+ ? "setupUnknown"+ : capabilities?.usage !== undefined && !usage+ ? "setupUnknown"+ : undefined;+ const statusAction =+ status === "offline"+ ? "connect"+ : status === "loadFailed" || status === "setupUnknown"+ ? "retry"+ : status === "disabled"+ ? "enable"+ : status === "setupRequired"+ ? !usage?.setup.missing.length && usage?.setup.expired.length+ ? "reconnect"+ : "settings"+ : undefined;+ // Older Hosts have no usage facts; preserve their existing task entry, without claiming readiness.+ const taskUsable = usage?.taskUsable ?? true;+ const tools =+ Array.isArray(capabilities?.tools) &&+ capabilities.tools.every(+ (tool) =>+ tool &&+ typeof tool.name === "string" &&+ (tool.description === undefined ||+ typeof tool.description === "string"),+ )+ ? capabilities.tools.map((tool) => ({+ name: tool.name,+ description: tool.description ?? "",+ }))+ : undefined;+ const permissions =+ Array.isArray(capabilities?.permissions) &&+ capabilities.permissions.every(+ (permission) =>+ permission &&+ typeof permission.title === "string" &&+ typeof permission.description === "string",+ )+ ? capabilities.permissions.map((permission) => ({+ title: permission.title,+ description: permission.description,+ }))+ : undefined;+ const details =+ Array.isArray(capabilities?.details) &&+ capabilities.details.every(+ (fact) =>+ fact &&+ typeof fact.key === "string" &&+ typeof fact.title === "string" &&+ typeof fact.value === "string",+ )+ ? capabilities.details.map((fact) => ({+ key: fact.key,+ title: fact.title,+ value: fact.value,+ }))+ : undefined;+ return {+ details,+ tools,+ permissions,+ description: resource?.blocks?.find((block) => block.id === "about")+ ?.fallbackMarkdown,+ version: resource?.blocks?.find((block) => block.id === "version")+ ?.fallbackMarkdown,+ status,+ statusAction,+ taskUsable,+ canUseTasks: taskUsable && !status && usage?.runtimeIssue !== "fused",+ canToggle:+ online &&+ !loading &&+ !loadFailed &&+ !usage?.retired &&+ !usage?.approvalRequired &&+ actions.some(+ (action) =>+ (action.id === "enable" || action.id === "disable") &&+ !action.disabled,+ ),+ hasSettings: Boolean(+ usage?.hasSettings ||+ mobileSettings ||+ taskPreferences ||+ usage?.configuration?.items.length ||+ status === "setupRequired",+ ),+ taskPreferences,+ mainSurface: main?.id.slice(5) as PluginPageSurface | undefined,+ mobileSettings,+ builtin: usage?.builtin ?? false,+ missing: usage?.setup.missing ?? [],+ expired: usage?.setup.expired ?? [],+ setupGroups: usage?.setup.groups ?? [],+ runtimeIssue: usage?.runtimeIssue,+ configuration: usage?.configuration,+ };+}diff --git a/apps/mobile/src/plugins/pluginListOrder.ts b/apps/mobile/src/plugins/pluginListOrder.tsnew file mode 100644index 0000000000..c1c63afa9b--- /dev/null+++ b/apps/mobile/src/plugins/pluginListOrder.ts@@ -0,0 +1,40 @@+import type { HostedRemoteCollectionItem } from "@/device-link/remoteResources";++const addedAt = (item: HostedRemoteCollectionItem) => {+ const value = item.item.pluginOrder?.addedAt;+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0+ ? value+ : 0;+};+const hostRecentIndex = (item: HostedRemoteCollectionItem) => {+ const value = item.item.pluginOrder?.recentIndex;+ return typeof value === "number" &&+ Number.isSafeInteger(value) &&+ value >= 0 &&+ value < 100+ ? value+ : undefined;+};++/** Notification time, version and local discovery time are never installation facts. */+export function sortPluginItems(+ items: readonly HostedRemoteCollectionItem[],+ recentKeys: readonly string[],+): HostedRemoteCollectionItem[] {+ const recent = new Map(recentKeys.map((key, index) => [key, index]));+ const rank = (item: HostedRemoteCollectionItem) => {+ const local = recent.get(item.key);+ if (local !== undefined) return local;+ const host = hostRecentIndex(item);+ return host !== undefined ? recentKeys.length + host : Infinity;+ };+ return items+ .map((item, index) => ({ item, index }))+ .sort((a, b) => {+ const left = rank(a.item),+ right = rank(b.item);+ if (left !== right) return left - right;+ return addedAt(b.item) - addedAt(a.item) || a.index - b.index;+ })+ .map(({ item }) => item);+}diff --git a/apps/mobile/src/session/ComposerSheet.ios.tsx b/apps/mobile/src/session/ComposerSheet.ios.tsxindex 126014bfc9..7ca6e243ef 100644--- a/apps/mobile/src/session/ComposerSheet.ios.tsx+++ b/apps/mobile/src/session/ComposerSheet.ios.tsx@@ -3,6 +3,7 @@ import { Host } from "@expo/ui";import {BottomSheet,Form,+ List,Button,Group,HStack,@@ -31,6 +32,8 @@ import {interactiveDismissDisabled,presentationDragIndicator,scrollContentBackground,+ listStyle,+ scrollDismissesKeyboard,} from "@expo/ui/swift-ui/modifiers";import { useTranslation } from "react-i18next";import { ScrollView, View, useWindowDimensions } from "react-native";@@ -51,6 +54,7 @@ export function ComposerSheet({footer,testID,nativeContent,+ nativeList,nativeHeader,nativeRoot,preventDismiss = false,@@ -160,6 +164,14 @@ export function ComposerSheet({</VStack>) : null}</ZStack>+ ) : nativeContent && nativeList ? (+ <List testID={testID} modifiers={[+ listStyle("plain"),+ scrollContentBackground("hidden"),+ scrollDismissesKeyboard("interactively"),+ ]}>+ {children}+ </List>) : nativeContent ? (<Form testID={testID} modifiers={[scrollContentBackground("hidden"),diff --git a/apps/mobile/src/session/ComposerSheet.tsx b/apps/mobile/src/session/ComposerSheet.tsxindex e3b805132f..58a8f0672b 100644--- a/apps/mobile/src/session/ComposerSheet.tsx+++ b/apps/mobile/src/session/ComposerSheet.tsx@@ -1,6 +1,8 @@import type { ReactNode } from "react";export interface ComposerSheetProps {nativeContent?: boolean;+ /** Use an ungrouped system list instead of the default form. */+ nativeList?: boolean;/** Protect an unsaved or in-flight form; explicit Back/Save remains available. */preventDismiss?: boolean;nativeHeader?: ReactNode;diff --git a/apps/mobile/src/session/HomeChromeDrawer.tsx b/apps/mobile/src/session/HomeChromeDrawer.tsxindex 5608208bae..6ee3e9ecef 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, Puzzle, Search, Settings, UsersRound } from 'lucide-react-native';+import { Building2, LogOut, Monitor, Plug, Search, Settings, UsersRound } from 'lucide-react-native';import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import {AccessibilityInfo,@@ -352,7 +352,7 @@ export function HomeChromeDrawer({{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} />+ <Plug color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} /><Text numberOfLines={1} style={styles.menuLabel}>{t('plugins.title')}</Text><PluginMenuUnreadDot active={open} /></Pressable> : null}diff --git a/docs/design-evidence/2026-10-09/android-collapsed-light.png b/docs/design-evidence/2026-10-09/android-collapsed-light.pngnew file mode 100644index 0000000000..2e9e45f27fBinary files /dev/null and b/docs/design-evidence/2026-10-09/android-collapsed-light.png differdiff --git a/docs/design-evidence/2026-10-09/android-expanded-dark.png b/docs/design-evidence/2026-10-09/android-expanded-dark.pngnew file mode 100644index 0000000000..5babba36a2Binary files /dev/null and b/docs/design-evidence/2026-10-09/android-expanded-dark.png differdiff --git a/docs/design-evidence/2026-10-09/mobile-installed-plugins.md b/docs/design-evidence/2026-10-09/mobile-installed-plugins.mdnew file mode 100644index 0000000000..3da3b8e91a--- /dev/null+++ b/docs/design-evidence/2026-10-09/mobile-installed-plugins.md@@ -0,0 +1,36 @@+# 手机已装插件页面验收++## 最终设计++列表采用商店式图标与名称布局;iOS 使用原生 plain List 与常驻搜索。+详情依次展示插件身份、描述、使用入口、工具、权限摘要与 Details;配置与任务偏好提示到电脑设置。+输入框上方的插件选择器只展示图标与名称。++工具使用语义弱底色胶囊,名称前放工具图标,不显示描述,随容器宽度自然换行。+默认最多两行;有溢出才显示 Show all,展开后通过 Show less 收起。+头部图标的原生桥接容器按内容尺寸布局;原生使用按钮行给投影留出完整空间。++Host 提供真实启停、配置状态、权限声明与详情事实。旧 Host 缺字段时保持原入口,+不把缺失信息解释为无权限或已配置。配置投影不包含凭证、配置值与账号标识。+最近使用记录按账号与电脑隔离;只有实际使用才更新历史,安装时间不从通知时间推断。++## 实际验收(2026-10-10)++- iOS:专用 iPhone 17 Pro / iOS 26.5 Simulator,真实 PocketMind 插件。+ Light/Dark 检查头部图标、按钮投影、工具两行折叠、展开六个与收起。+ 真实任务列表检查搜索、清空、空结果、软键盘、滚动、关闭重开。+- Android:专用 Android 14 arm64 AVD,当前任务 worktree 构建的 Debug 包。+ 明确标注 Demo 的数据检查 Light/Dark、正常与窄屏宽度、工具展开收起、+ 隐藏工具的 accessibility tree、新任务预填和已有任务搜索列表。+ [浅色折叠](android-collapsed-light.png) · [深色展开](android-expanded-dark.png)。+- Android 切回正常数据入口后停在登录页:真实账号、电脑联动与插件调用未验证。+ 后续步骤是用户登录并连接电脑,重复详情与任务入口验收。++## 验收边界++Light/Dark 原始视觉证据来自主干同步前的 JS。同步后已重建并安装匹配基线的 iOS 原生包,+用真实 PocketMind 数据重复验收 Light 的图标、按钮投影与工具展开收起;Dark 未重复目检。+最终 review 对清理和 Android 空结果提示补充自动回归;启停与回读竞态的 62 项定向测试、+Mobile 类型检查通过,真实启停期间的断线恢复未实测。Desktop DEV 未启动。+不以 Demo 结果替代真实数据验收。iPad、旧 iOS 与 VoiceOver 未实测。+本 PR 不修改 Mobile 原生配置、依赖或 runtime fingerprint 输入。diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.mdindex f27b8ad005..f992bf0157 100644--- a/docs/design-rules/design-inventory.md+++ b/docs/design-rules/design-inventory.md@@ -63,7 +63,7 @@| `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, NativeVideoPlayer, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, 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/NativeVideoPlayer.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 | 247 | 84 || `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, HomeSessionInfoMeta, 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, RemoteSourceMark, 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/HomeSessionInfoMeta.tsx, apps/mobile/src/session/HomeSurface.tsx, apps/mobile/src/session/HomeUnreadContext.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileModelPickerList.ios.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/MobilePermissionPickerList.ios.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.ios.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerNativeHeader.ios.tsx, apps/mobile/src/session/ModelPickerNativeHeader.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/MountOnFirstOpen.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteSourceMark.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionActionSheetFrame.android.tsx, apps/mobile/src/session/SessionActionSheetFrame.tsx, apps/mobile/src/session/SessionDetailsNative.ios.tsx, apps/mobile/src/session/SessionDetailsNative.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SessionRightSpinner.tsx, apps/mobile/src/session/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, RemoteSourceMark, 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/RemoteSourceMark.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.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, PluginDetailView, PluginDetailView.ios, PluginDirectoryPicker, PluginDirectoryView, PluginDirectoryView.ios, PluginMediaViewer, PluginNativeIntent, PluginPage, PluginScheduleDraft, PluginTaskPicker, PluginTaskPickerView, PluginTaskPickerView.ios, PluginToolChips, PluginsScreen, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteSourceMark, 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/PluginDetailView.ios.tsx, apps/mobile/src/plugins/PluginDetailView.tsx, apps/mobile/src/plugins/PluginDirectoryPicker.tsx, apps/mobile/src/plugins/PluginDirectoryView.ios.tsx, apps/mobile/src/plugins/PluginDirectoryView.tsx, apps/mobile/src/plugins/PluginMediaViewer.tsx, apps/mobile/src/plugins/PluginNativeIntent.tsx, apps/mobile/src/plugins/PluginPage.tsx, apps/mobile/src/plugins/PluginScheduleDraft.tsx, apps/mobile/src/plugins/PluginTaskPicker.tsx, apps/mobile/src/plugins/PluginTaskPickerView.ios.tsx, apps/mobile/src/plugins/PluginTaskPickerView.tsx, apps/mobile/src/plugins/PluginToolChips.tsx, apps/mobile/src/plugins/PluginsScreen.tsx, apps/mobile/src/plugins/pluginPageHtml.ts, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/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/RemoteSourceMark.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 | 87 || `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, 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, [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/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.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 |diff --git a/docs/dev-rules/plugin-mobile-implementation.md b/docs/dev-rules/plugin-mobile-implementation.mdindex 0c472aa256..566521fff7 100644--- a/docs/dev-rules/plugin-mobile-implementation.md+++ b/docs/dev-rules/plugin-mobile-implementation.md@@ -5,8 +5,30 @@## 入口与页面-- 主菜单提供插件入口和聚合未读点;目录按电脑展示,支持搜索、最近使用、未读筛选、详情和启停。+- 主菜单提供插件入口和聚合未读点;目录按电脑展示,支持搜索、最近使用、详情和启停。宽屏目录与内容并列,样式使用 Light/Dark 语义 token,文案覆盖现有五种语言。+- iOS 已装目录使用现有 `@expo/ui` 的 SwiftUI List、Menu 和 Picker;搜索复用现有导航栈的+ UIKit UISearchController / UISearchBar,置于标题下并常驻。电脑范围和标题行是普通列表内容,+ 随页面滚出;All/Unread 筛选暂不展示,保留内容通知提示点。未读不表示可用更新。+ 两页使用平面 List;详情启用 Toggle 放在插件名称右侧,iOS 可视目标 48×24pt,保留 56×44pt 操作区域。+ Use it in 标题下仅保留新建/已有任务原生 secondary 按钮,不附加说明。+ panel/mainView 合并为一个打开插件入口;Tools、Permissions 与 Details 使用真实 Host 只读数据,+ Tools 使用弱底色胶囊与工具图标,随容器宽度自然换行,默认最多两行,标题保留总数;溢出时提供 Show all / Show less,始终隐藏描述;权限复用 PC 声明摘要(排除 tool)。+ 分组之间不画线,仅 Details 条目之间使用系统 Divider,避免重复 padding;身份首行顶部 inset 8pt。+ Details 按 PC 顺序展示版本、作者、来源与签名、标识、包含能力、面板和只读安装目录,+ 内容与信任标签复用 PC 共享规则。旧 Host 缺字段时仅显示已有真实版本/标识;可选字段为空则隐藏,+ Tools/Permissions 无数据则整组隐藏,不展示未提供数据或缺描述的占位提示。+ 不推断为无权限、不补造事实或面板停靠状态。配置和任务偏好不内联,提示到电脑插件详情设置。异常时显示必要提示和单个解决动作;+ 导航容器负责容器安全区,Host 保留键盘避让。图标与专用任务设置继续复用 RN 内容。Android+ 保留平台列表与搜索,控件同样随内容滚动,详情使用平台原生 Switch。+- Installed 固定按最近使用排序,不展示添加时间/最近使用的筛选交互,不重复展示 Recent 分组。+ 最近使用以手机 MRU 优先、Host MRU 补充;不得用没有真实来源的安装时间替代。+ 只记录实际成功打开页面/使用入口,查看详情不记。列表可选 pluginOrder 只下发+ addedAt/recentIndex:addedAt 来源于成功首装记录,不取更新/通知/首次手机发现时间;+ 老 Host 或历史缺失时间保持未知,排在已知添加时间之后并稳定原序。手机 MRU 优先,+ Host MRU 补充,同排名保持稳定。不同电脑的插件用资源 key 区分,配置与凭证不参与排序。+- 启停开关等待电脑操作回执并重新读取插件状态,操作期间禁止重复点击,成功后保留详情。+ 离线时不可操作;失败不自动重发,账号或详情已切换时旧响应不覆盖当前页面。- manifest 的可选 `mobile` 包含 `channels`、`panel`、`mainView`、`settings`;路径只覆盖已声明的原能力。未声明移动适配的插件仍可被发现和在任务中使用,旧桌面行为保留。- 页面租约绑定账号、控制端连接、插件安装版本和页面实例。页面关闭或来源失效后,@@ -25,6 +47,8 @@页面加载和轮询本身不确认已读;读取失败不回报,前台恢复时重新呈现再回报。- 任务卡从已保存且净化的 HTML 投影动作,手机不执行卡片脚本;提交复核卡片版本、归属和真实点击。- 新建任务复用普通创建页面,选择已有任务复用原生选择器,仅预填使用文字,用户发送后执行。+ iOS 已有任务选择器使用系统 sheet + SwiftUI plain List,无分组卡片;搜索 TextField 固定在标题下,+ 输入、清空、无匹配与键盘提交均消费真实任务数据。选择等待原生 onDismiss 后导航,取消或归属变化丢弃待选项。workspace 打开对应普通任务;任务能力批准和写权限仍沿用 Host 校验、确认与回滚链。- `cindy.tasks` 与统一任务接口共用创建、继续、结果查询、模型目录和改模型能力。任务设置复用 `pluginTaskPrefsStore` 和 `validatePluginTaskConfig`,保留旧偏好及私有工作目录。@@ -55,22 +79,40 @@作者必须提供真正可触屏使用的布局及 Light/Dark,保存业务去重记录和草稿;添加声明不代表完成适配。模块动态加载、键盘、返回和前后台行为需要在目标平台验证。+## 详情状态与旧端兼容++plugin-capabilities.data.usage 为可选摘要,复用宿主 getGhostSetupAssessment,只传就绪状态+与缺失/过期项目名称;保留组内 any-of 选项,不传配置值、动作授权或凭证。批准记录异常、+下线、运行崩溃/熔断与停用分开呈现;运行 off 是正常按需启动,不算错误。+离线/未加载/读取失败时不提供任务使用或设置写入。旧宿主缺少 usage 时保留原任务入口,+不宣称配置已验证;新宿主判定异常显示未知并只重读,不自动重新执行写入。+详情配置恢复入口提示在电脑端完成;任务内既有 Setup 卡流程不变。+DEV visual mock 可用 cindy://plugins?preview=<fixture-id>[-settings] 定位演示状态,+只在显式 visual mock 下生效,不选择真实已装插件。+## 验证边界直接相关用例覆盖页面/控制端隔离、确认与未读、资源替换、任务归属、模型配置、卡片动作、原生授权密码学互通和身份固定,以及移动桥接脚本、预览查询和媒体临时文件回收。浏览器模拟宿主、JSDOM、原生边界 mock 和局部类型检查均不能替代手机实机验收。-本次未启动 Desktop DEV、Metro 或原生构建;iOS、Android、iPad 的键盘、系统浏览器返回、-断线恢复及 Light/Dark 实机视觉仍待验证。未执行整仓测试和整包构建,完整门禁交 CI。+验收按各 PR 的当前提交记录,不能沿用历史接入时的未验证结论。+[已装插件页面验收](../design-evidence/2026-10-09/mobile-installed-plugins.md)记录了+iOS 原生构建、Metro 与真实 PocketMind 数据,以及 Android Debug 包的 Demo 验收。+最新 iOS 原生包重复目检为 Light;Dark 证据来自主干同步前。Android 真实账号联动、+iPad、旧 iOS、VoiceOver,以及真实启停期间的断线恢复尚未实测。+启停与回读竞态另有定向回归,不能替代运行验收;完整单测门禁由 PR CI 执行。## 兼容、冷更与回退现有插件不需要重装、重新批准或重配凭证;mobile 为可选扩展,新增远程集合由能力协商发现。插件批准格式、安装布局、旧任务偏好文件和 Library 数据未迁移。插件基座改动合并前需白名单明确批准。-新增纯 JavaScript `@noble/[email protected]` 复用现有 Expo 随机数与 AES,未新增原生模块,-但依赖仍改变 runtime fingerprint,必须按冷更发布新安装包并由指定把关人明确批准。+历史移动插件接入新增纯 JavaScript `@noble/[email protected]`,复用现有 Expo 随机数与 AES,+未新增原生模块,但当时依赖变更改变了 runtime fingerprint,需要冷更与指定把关人明确批准。iOS 指纹从 `d8cd3b87cb7dcf418004eeb36b0ff1b8f29a44c7` 变为`25a5a753aaf7740670f9588e976b4770b0817999`;Android 从`c2eb49bea3303f89edf8de95af3a0cf45179faca` 变为 `d1d89bd866a64c681f3ded59075536abccb84c9a`。-旧安装保持原能力,不向旧 runtime 投送本次 OTA。回退客户端代码即可撤销移动入口;不删除插件数据。+这些指纹记录属于历史接入,不能作为后续页面调整的冷更判据。已装插件页面调整 PR #5730+未修改原生配置、依赖或 runtime fingerprint 输入;本地重建用于匹配现有基线,不代表新增冷更。+发布仍按实际构建与目标 runtime 核对兼容性,不向不匹配的旧 runtime 投送 OTA。+回退客户端代码即可撤销移动入口;不删除插件数据。diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 957d44454e..bac616dc80 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -1375,3 +1375,23 @@ Chat Server `/me` 追加 `capabilities.groupDiscussionParity: 1`。Desktop 只新控制端连接旧执行端沿用原通知;旧控制端忽略该字段,仍可能发独立完成外部通知,完整远端去重需要两端更新。手机外部推送在执行端及远控 Desktop 的通知出口完成去重,手机无需新增协议处理;移动列表继续原 phase/attention 语义。无需服务端、数据库 migration 或 Mobile fingerprint 改动。++## 移动插件只读权限摘要++plugin-capabilities.data 可选追加 permissions(title/description 字符串数组),仅由 Host 从+PC 同源 ghostPermissionItems 声明摘要投影并排除 tool,以请求 locale 使用 PC 文案插值。+包含作者声明的 OAuth scope,不包含凭证、已存配置值或本机路径;不表示已授予运行权限。+旧控制端忽略该字段,新手机遇到旧 Host 缺字段或格式不完整时明确未提供,不推断无权限。+空数组仅表示 Host 明确投影的声明为空。工具、about 和 version 使用原字段。+不增加 channel、allowlist、relay 帧、授权或协议版本,服务端无改动,Mobile 指纹不变。+++## 移动插件 Details 事实++同一 plugin-capabilities.data 可选追加 details(key/title/value 数组),由本插件 InstalledGhost+投影 PC 同源版本、作者、签名来源、标识、包含能力与面板声明。签名标签复用 shared ghostTrustLabelKey,+不传签名文件、批准记录或密钥标识,不用作者自报推断官方。安装目录按用户明确要求单独只读投影本插件+的 ghost.dir,仅走原同账号、当前 owner 的资源通道;不提供路径写入或文件操作,不扩 IPC 白名单。+当前 PC 窗口的停靠位置不在此声明投影内,有面板只报告存在,无面板沿用 PC 文案。+旧 Host 缺字段时新手机仅显示原有 Version 与资源 Identifier,说明其余数据未提供;旧控制端忽略新增字段。+服务端、relay、协议版本及原生 fingerprint 均不变。diff --git a/packages/device-link/src/pluginPages.ts b/packages/device-link/src/pluginPages.tsindex f147c2031f..883db92ec6 100644--- a/packages/device-link/src/pluginPages.ts+++ b/packages/device-link/src/pluginPages.ts@@ -1,7 +1,190 @@-/** Optional, versioned plugin-page projection. No host path or credential is a wire value. */+/** Optional plugin-page projection. Author pages receive no host paths or credentials. */export const PLUGIN_COLLECTION = "plugins";export const PLUGIN_PAGE_PRIMITIVE = "plugin-page";export type PluginPageSurface = "panel" | "mainView" | "settings";+/** Safe configuration facts, never form values, secrets, account identifiers or action grants. */+export interface PluginConfigurationItem {+ id: string;+ kind: "secret" | "oauth" | "connection" | "parameter" | "managed" | "client";+ label: string;+ hint?: string;+ state: "configured" | "missing" | "expired" | "unknown" | "managed";+ count?: number;+ expiredCount?: number;+}+export interface PluginConfigurationSummary {+ items: PluginConfigurationItem[];+ alternatives: string[][];+}+export function parsePluginConfigurationSummary(+ value: unknown,+): PluginConfigurationSummary | null {+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;+ const v = value as Record<string, unknown>;+ const kinds = [+ "secret",+ "oauth",+ "connection",+ "parameter",+ "managed",+ "client",+ ];+ const states = ["configured", "missing", "expired", "unknown", "managed"];+ const bounded = (x: unknown, max: number): x is string =>+ typeof x === "string" && x.length > 0 && x.length <= max;+ if (+ !Array.isArray(v.items) ||+ v.items.length > 128 ||+ !Array.isArray(v.alternatives) ||+ v.alternatives.length > 16+ )+ return null;+ const items: PluginConfigurationItem[] = [];+ for (const raw of v.items) {+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;+ const item = raw as Record<string, unknown>;+ if (+ !bounded(item.id, 160) ||+ !bounded(item.label, 160) ||+ !kinds.includes(item.kind as string) ||+ !states.includes(item.state as string)+ )+ return null;+ if (+ item.hint !== undefined &&+ (typeof item.hint !== "string" || item.hint.length > 512)+ )+ return null;+ if (+ [item.count, item.expiredCount].some(+ (n) =>+ n !== undefined &&+ (!Number.isSafeInteger(n) ||+ (n as number) < 0 ||+ (n as number) > 10000),+ )+ )+ return null;+ if (items.some((other) => other.id === item.id)) return null;+ items.push({+ id: item.id,+ label: item.label,+ kind: item.kind as PluginConfigurationItem["kind"],+ state: item.state as PluginConfigurationItem["state"],+ ...(item.hint !== undefined ? { hint: item.hint as string } : {}),+ ...(item.count !== undefined ? { count: item.count as number } : {}),+ ...(item.expiredCount !== undefined+ ? { expiredCount: item.expiredCount as number }+ : {}),+ });+ }+ const alternatives: string[][] = [];+ for (const group of v.alternatives) {+ if (+ !Array.isArray(group) ||+ group.length < 2 ||+ group.length > 8 ||+ group.some(+ (id) => typeof id !== "string" || !items.some((item) => item.id === id),+ ) ||+ new Set(group).size !== group.length+ )+ return null;+ alternatives.push([...group]);+ }+ return { items, alternatives };+}+/** Optional installed-detail facts. No configuration values, action grants or host paths. */+export interface PluginUsageSummary {+ taskUsable: boolean;+ hasSettings: boolean;+ approvalRequired: boolean;+ builtin: boolean;+ retired: boolean;+ runtimeIssue?: "crashed" | "fused";+ configuration?: PluginConfigurationSummary;+ setup: {+ state: "ready" | "required" | "unknown";+ missing: string[];+ expired: string[];+ groups?: Array<{ missing: string[]; expired: string[] }>;+ };+}++export function parsePluginUsageSummary(+ value: unknown,+): PluginUsageSummary | null {+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;+ const v = value as Record<string, unknown>;+ if (+ [+ "taskUsable",+ "hasSettings",+ "approvalRequired",+ "builtin",+ "retired",+ ].some((key) => typeof v[key] !== "boolean")+ )+ return null;+ if (!v.setup || typeof v.setup !== "object" || Array.isArray(v.setup))+ return null;+ const setup = v.setup as Record<string, unknown>;+ if (!["ready", "required", "unknown"].includes(setup.state as string))+ return null;+ const labels = (input: unknown): input is string[] =>+ Array.isArray(input) &&+ input.length <= 64 &&+ input.every((label) => typeof label === "string" && label.length <= 160);+ if (!labels(setup.missing) || !labels(setup.expired)) return null;+ const groups = setup.groups;+ const configuration =+ v.configuration === undefined+ ? undefined+ : parsePluginConfigurationSummary(v.configuration);+ if (configuration === null) return null;+ if (+ groups !== undefined &&+ (!Array.isArray(groups) ||+ groups.length > 64 ||+ groups.some(+ (group) =>+ !group ||+ typeof group !== "object" ||+ !labels(group.missing) ||+ !labels(group.expired),+ ))+ )+ return null;+ if (+ v.runtimeIssue !== undefined &&+ !["crashed", "fused"].includes(v.runtimeIssue as string)+ )+ return null;+ return {+ taskUsable: v.taskUsable as boolean,+ hasSettings: v.hasSettings as boolean,+ approvalRequired: v.approvalRequired as boolean,+ builtin: v.builtin as boolean,+ retired: v.retired as boolean,+ ...(configuration ? { configuration } : {}),+ ...(v.runtimeIssue+ ? { runtimeIssue: v.runtimeIssue as "crashed" | "fused" }+ : {}),+ setup: {+ state: setup.state as PluginUsageSummary["setup"]["state"],+ missing: [...setup.missing],+ expired: [...setup.expired],+ ...(Array.isArray(groups)+ ? {+ groups: groups.map((group) => ({+ missing: [...group.missing],+ expired: [...group.expired],+ })),+ }+ : {}),+ },+ };+}export interface PluginMobileDeclaration {channels: string[];panel?: string;diff --git a/packages/device-link/src/remoteResources.ts b/packages/device-link/src/remoteResources.tsindex 4d5ecc0327..37f37b1603 100644--- a/packages/device-link/src/remoteResources.ts+++ b/packages/device-link/src/remoteResources.ts@@ -140,6 +140,8 @@ export interface RemoteResourceBlock {export interface RemoteCollectionItem {ref: RemoteResourceRef;display: RemoteResourceDisplay;+ /** Optional Host-owned plugin chronology. Missing dates remain unknown on older Hosts. */+ pluginOrder?: { addedAt?: number; recentIndex?: number };links: RemoteResourceLink[];actions?: RemoteActionDescriptor[];/** Opaque provider revision. Controllers compare it but never interpret it. */diff --git a/scripts/__tests__/design-inventory.test.mjs b/scripts/__tests__/design-inventory.test.mjsindex ceda8d9113..a383f0ca5e 100644--- a/scripts/__tests__/design-inventory.test.mjs+++ b/scripts/__tests__/design-inventory.test.mjs@@ -1277,7 +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.plugins', ['PluginsScreen.tsx', 'PluginPage.tsx', 'PluginDetailView.ios.tsx', 'PluginToolChips.tsx', 'PluginNativeIntent.tsx']],['mobile.overlay.connection-startup', ['ConnectionNoticeOverlay.tsx', 'ConnectionBanner.tsx']],]) {const surface = surfaces.find(s=>s.id===id);