Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(mobile): load large model catalogs and keep send controls visible

Chris4304a582e3c4
diff --git a/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts b/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts
index 78ca227391..b9d2798773 100644
--- a/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts
@@ -18,6 +18,8 @@ import { describe, it, expect, vi } from 'vitest';
import { connectedProvidersForAgent, pickRecommendedAgent, type ProviderView } from '@cindy/model-providers';
import { TEST_XD_GATEWAY_BASE_URL as XD_GATEWAY_BASE_URL } from '../../../test/vitest/clientEndpointsFixture';
+// The projection never reads persistence; avoid loading Electron through transitive stores.
+vi.mock('electron-store', () => ({ default: class {} }));
vi.mock('electron', () => ({
app: {
getAppPath: () => '/tmp/xdt-maker-test/app',
@@ -34,6 +36,7 @@ vi.mock('../../logger', () => ({
}));
import { __testing } from '../dispatch';
+import { readProviderCatalog } from '@cindy/device-link';
const project = (result: unknown) =>
__testing.projectInvokeResultForTunnel('maker:provider:list', result) as {
@@ -97,6 +100,15 @@ function xdProviderWithFullRouting() {
}
describe('projectInvokeResultForTunnel — maker:provider:list 投影', () => {
+ it('pages only the credential-free projection and preserves all model options', async () => {
+ const value = { providers: [xdProviderWithFullRouting()], modelVisibilityOverrides: { hidden: false } };
+ const result = await readProviderCatalog({ channel: 'maker:provider:list', args: [] }, async payload => ({
+ ok: true, result: __testing.projectInvokeResultForTunnel(payload.channel, value, true, payload.args),
+ }));
+ expect(result).toEqual({ ok: true, result: projectForCurrentController(value) });
+ expect(JSON.stringify(result)).not.toContain('leak-me');
+ expect(JSON.stringify(result)).not.toContain(XD_GATEWAY_BASE_URL);
+ });
it('keeps the remote native Codex preference after stripping OAuth execution details', () => {
const model = {
id: 'gpt-6-astra', name: 'GPT-6 Astra', contextWindow: 400000,
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts
index f25118613a..bd2cc025b4 100644
--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts
@@ -11,6 +11,17 @@ function capture(): SharedTaskPeerCapture {
}
afterEach(() => { setSharedTaskQueueReader(null); setSharedTaskInteractionReader(null); });
describe('sharedTask dispatch scope', () => {
+ it('authorizes each provider page as a history read and rejects malformed cursors', () => {
+ const options = { capabilities: ['provider-catalog-pages-v1'], catalogPage: { offset: 262144, revision: 'a'.repeat(64) } };
+ const request = { channel: 'maker:provider:list', args: [options] };
+ expect(() => assertSharedTaskInvoke(capture(), request)).not.toThrow();
+ expect(() => assertSharedTaskInvoke({ ...capture(), authorize: () => false }, request)).toThrow('PERMISSION_DENIED');
+ for (const invalid of [
+ { ...options, catalogPage: { offset: -1, revision: 'a'.repeat(64) } },
+ { ...options, capabilities: [] },
+ { ...options, path: '/private' },
+ ]) expect(() => assertSharedTaskInvoke(capture(), { ...request, args: [invalid] })).toThrow('PERMISSION_DENIED');
+ });
it('reads subagent context only through the shared parent task', () => {
for (const channel of ['local-db:subagent-runs:list', 'local-db:subagent-runs:detail', 'local-db:subagent-runs:transcript']) {
const request = { sessionId: 'task', provider: 'pi', runIdOrAlias: 'child' };
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 42fc3d6209..7b361073f6 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -1,3 +1,4 @@
+import { createHash } from 'node:crypto';
import { executeTaskTags, TASK_TAG_CHANNEL } from '../localDb/ipc/taskTags.js';
import type { TaskTagRequest } from '@cindy/maker-shared';
import {
@@ -5,6 +6,7 @@ import {
TASK_MIGRATION_CHANNEL,
encodeSessionTagCatalog,
decodeSessionTagCatalog,
+ encodeProviderCatalogPage,
} from '@cindy/device-link';
import { requestFilePeer, stopFilePeers } from './filePeer';
import { requestTaskMigration } from '../task-migration/service';
@@ -630,11 +632,11 @@ function projectInvokeResultForTunnel(
.filter((entry): entry is [string, boolean] => typeof entry[1] === 'boolean'),
)
: undefined;
- return {
+ return encodeProviderCatalogPage(args, {
providers,
...(modelVisibilityOverrides !== undefined ? { modelVisibilityOverrides } : {}),
...(Array.isArray(r.providerOrder) ? { providerOrder: normalizeProviderOrder(r.providerOrder) } : {}),
- };
+ }, json => createHash('sha256').update(json).digest('hex'));
}
/** 持有 client 的引用(转发 push 用);wireInboundDispatch 接入时设置。 */
diff --git a/apps/desktop/src/main/device-link/sharedTaskDispatch.ts b/apps/desktop/src/main/device-link/sharedTaskDispatch.ts
index 75ea66ea01..235a101bdb 100644
--- a/apps/desktop/src/main/device-link/sharedTaskDispatch.ts
+++ b/apps/desktop/src/main/device-link/sharedTaskDispatch.ts
@@ -1,5 +1,6 @@
import { isSharedTaskPeer, parseSharedTaskPeer, isSharedTaskAttachment, type InvokePayload, type InvokeResultPayload, type SharedTaskQueueItem } from '@cindy/device-link';
import type { SharedTaskHost } from './sharedTaskHost.js';
+import { isProviderCatalogCursor, PROVIDER_CATALOG_PAGES_CAPABILITY } from '@cindy/device-link';
export type SharedTaskPeerCapture = NonNullable<ReturnType<SharedTaskHost['capturePeer']>>;
export interface SharedTaskInteractionCapture {
@@ -205,8 +206,10 @@ export function assertSharedTaskInvoke(
if (channel === 'maker:get-capabilities' && !['claude-code', 'codex', 'pi'].includes(String(args[0]))) deny();
if (channel === 'maker:provider:list' && args[0] !== undefined) {
const options = record(args[0]);
- if (!options || Object.keys(options).some((key) => key !== 'capabilities') ||
+ if (!options || Object.keys(options).some((key) => key !== 'capabilities' && key !== 'catalogPage') ||
!Array.isArray(options.capabilities) || options.capabilities.some((item) => typeof item !== 'string')) deny();
+ if (options.catalogPage !== undefined && (!options.capabilities.includes(PROVIDER_CATALOG_PAGES_CAPABILITY)
+ || !isProviderCatalogCursor(options.catalogPage))) deny();
}
return;
}
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index f124a5d29a..9f71085e38 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -93,7 +93,6 @@ import {
} from 'react-native';
import { Text, TextInput } from '@/components/AppText';
import Reanimated, { useAnimatedStyle } from 'react-native-reanimated';
-import { GestureDetector } from '@/platform/gestureHandler';
import { MobileAgentMark } from '@/components/MobileAgentMark';
import { mobileInteractionStyles } from '@/components/mobileInteractionStyles';
import { SessionHeaderNativeBack, SessionHeaderNativeActions, SessionHeaderNativeTitle, SessionHeaderNativeBlur } from '@/session/SessionHeaderNativeControls';
@@ -11232,17 +11231,6 @@ function SessionComposerInput({
unframed={!nativeComposerFrameAvailable}
style={styles.composerScrollFrame}
>
- <GestureDetector gesture={composerResize.scrollGesture}>
- <ScrollView
- ref={composerScrollViewRef}
- contentContainerStyle={styles.composerScrollContent}
- keyboardShouldPersistTaps="handled"
- scrollEnabled={composerScrollEnabled}
- showsVerticalScrollIndicator={composerScrollEnabled}
- style={styles.composerScroll}
- testID="session.composerScroll"
- >
-
<View style={[
styles.composerSurface,
compactComposer && !composerCardActive && styles.composerSurfaceCompact,
@@ -11250,6 +11238,10 @@ function SessionComposerInput({
<MobileComposerInputRow
key={sessionId}
frameOutside={nativeComposerFrameAvailable}
+ bodyScrollGesture={composerResize.scrollGesture}
+ bodyScrollRef={composerScrollViewRef}
+ bodyScrollTestID="session.composerScroll"
+ bodyScrollEnabled={composerScrollEnabled}
collapsedHeight={composerDock.enabled ? composerDock.pillHeight : undefined}
onCollapsedPress={composerPillOpen.onCollapsedPress}
accessibilityLabel={t('session.screen.composerPlaceholder')}
@@ -11337,8 +11329,6 @@ function SessionComposerInput({
voicePlacement={composerVoicePlacement}
/>
</View>
- </ScrollView>
- </GestureDetector>
</ComposerFrame>
</Reanimated.View>
</>
@@ -12308,18 +12298,12 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
paddingBottom: spacing.xs,
paddingTop: spacing.sm,
},
- composerScroll: {
- flexShrink: 1,
- maxHeight: '100%',
- },
composerScrollFrame: {
flexShrink: 1,
overflow: 'visible',
},
- composerScrollContent: {
- gap: spacing.sm,
- },
composerSurface: {
+ flexShrink: 1,
gap: 6,
},
composerSurfaceCompact: {
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index bbb6030d64..c006e1d092 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -377,7 +377,7 @@ import { MobileModelIconMark } from '@/session/MobileProviderMark';
import { draftModelMemoryFor, hydrateDraftModelMemory } from '@/session/draftModelMemory';
import { effortLabelFromRuntime, rowFastEditable } from '@/session/modelPickerRows';
import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';
-import { fontWeight, iconSize, iconStroke, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';
+import { fontWeight, iconSize, iconStroke, lineHeight, navigationChrome, radius, spacing, typeScale } from '@/theme/tokens';
const COMPOSER_INPUT_MULTILINE_CONTENT_THRESHOLD = 34;
// composer 除输入区外的 chrome 高度估算(输入行上下 padding + 边框),
@@ -6097,7 +6097,13 @@ export default function NewRemoteSessionScreen() {
</Text>
) : null}
- <View style={styles.composerCard} testID="newSession.composer">
+ </ScrollView>
+ <View style={[styles.composerCard, {
+ maxHeight: Math.max(COMPOSER_CARD_CHROME_HEIGHT + MOBILE_COMPOSER_INPUT_SINGLE_LINE_HEIGHT, windowDimensions.height
+ - (keyboardState.visible ? keyboardState.height : safeAreaInsets.bottom)
+ - safeAreaInsets.top - navigationChrome.target - spacing.xl),
+ paddingBottom: composerDock.enabled ? 0 : spacing.md,
+ }]} testID="newSession.composer">
{composerTrigger.kind === 'slash' ? (
<NewComposerPaletteFrame
emptyText={t('session.common.noMatchingCommands')}
@@ -6164,6 +6170,8 @@ export default function NewRemoteSessionScreen() {
<View style={styles.composerToolbarWrap}>
<MobileComposerInputRow
accessibilityLabel={t('session.new.firstMessagePlaceholder')}
+ bodyScrollGesture={composerResize.scrollGesture}
+ bodyScrollEnabled={!composerResize.dragging}
accessoryAbove={attachments.length > 0 || pendingUploads.length > 0 || pastePlaceholderCount > 0 ? renderComposerAttachmentTray() : null}
autoFocus={visualFocusComposer}
entryTransitionId={entryMorph?.id}
@@ -6262,7 +6270,6 @@ export default function NewRemoteSessionScreen() {
/>
</View>
</View>
- </ScrollView>
{composerDock.enabled ? (
<DockKeyboardBottomSpacer restingBottom={composerDock.restingBottom} keyboardGap={composerDock.keyboardGap} />
) : null}
@@ -7408,6 +7415,7 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
...MOBILE_COMPOSER_DRAFT_TEXT_STYLE,
},
composerToolbarWrap: {
+ flexShrink: 1,
position: 'relative',
zIndex: 30,
},
diff --git a/apps/mobile/docs/navigation-and-composer.md b/apps/mobile/docs/navigation-and-composer.md
index 37e2f1a05b..2f77da6db1 100644
--- a/apps/mobile/docs/navigation-and-composer.md
+++ b/apps/mobile/docs/navigation-and-composer.md
@@ -13,6 +13,7 @@
- 输入框:新建、已有任务、伙伴聊天统一为 55pt 药丸,下沿同一条线;不自动聚焦。手动点药丸先向上
拉开成完整卡片(原生),约 0.05s 后原生聚焦,键盘随后升起;输入框逐帧跟随键盘
(均在 `ComposerDockKeyboardFollow.tsx`:新建页 `DockKeyboardBottomSpacer`,已有任务 `DockKeyboardLift` / `DockKeyboardViewportSpacer`)。
+- 新建页输入卡固定在页面滚动区之外;已有任务输入卡仅正文与附件可滚动,发送、语音与拖拽把手保留在滚动视口之外。长文本、附件及键盘改变可用高度时仍能直接发送,收起再展开不重挂编辑器。
- 减弱动态效果:不播形变与拉开,直接到位。
- 伙伴对话:左上角为返回(回到伙伴列表);Duo 系统栏已有返回时保留侧栏按钮,不出现两个返回。
- 设置等整页滚动的二级页:顶栏透明、系统柔和边缘,内容滚到顶栏和底部指示条下面,无硬分界(设置、语音词典、账号注销、伙伴私聊、共享任务管理、资源列表);设备详情只去掉底部色带。
diff --git a/apps/mobile/src/__tests__/composerToolbarViewport.test.tsx b/apps/mobile/src/__tests__/composerToolbarViewport.test.tsx
new file mode 100644
index 0000000000..11b6b46e50
--- /dev/null
+++ b/apps/mobile/src/__tests__/composerToolbarViewport.test.tsx
@@ -0,0 +1,68 @@
+// @vitest-environment jsdom
+import React, { act, type ReactNode } from 'react';
+import { createRoot } from 'react-dom/client';
+import { expect, it, vi } from 'vitest';
+import { MobileComposerInputRow } from '@/session/MobileComposerInputRow';
+
+vi.mock('expo-constants', () => ({ default: { executionEnvironment: 'bare' }, ExecutionEnvironment: { StoreClient: 'storeClient' } }));
+vi.mock('react-native', async () => {
+ const React = await import('react');
+ const View = ({ children, testID }: { children?: ReactNode; testID?: string }) =>
+ React.createElement('div', { 'data-testid': testID }, children);
+ const ScrollView = ({ children, testID, scrollEnabled }: { children?: ReactNode; testID?: string; scrollEnabled?: boolean }) =>
+ React.createElement('div', { 'data-testid': testID, 'data-scroll': String(scrollEnabled) }, children);
+ return { View, ScrollView, Pressable: View, Platform: { OS: 'ios' },
+ StyleSheet: { hairlineWidth: 1, absoluteFill: {} }, Animated: {}, Easing: {} };
+});
+vi.mock('@/components/AppText', () => ({ TextInput: () => null }));
+vi.mock('@/platform/gestureHandler', () => ({ GestureDetector: ({ children }: { children: ReactNode }) => children }));
+vi.mock('expo-paste-input', () => ({ TextInputWrapper: ({ children }: { children: ReactNode }) => children }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (value: string) => value }) }));
+vi.mock('lucide-react-native', () => ({ Mic: () => null }));
+vi.mock('@/hooks/useReduceMotion', () => ({ useReduceMotionEnabled: () => true }));
+vi.mock('@/session/voicePillWidthMotion', () => ({ useVoicePillWidthStyle: () => ({}) }));
+vi.mock('@/theme', async () => {
+ const tokens = await import('@/theme/tokens');
+ return { ...tokens, useTheme: () => ({ mode: 'dark', colors: tokens.darkColors }),
+ useThemedStyles: (make: (colors: typeof tokens.darkColors) => unknown) => make(tokens.darkColors) };
+});
+vi.mock('react-native-reanimated', async () => {
+ const { View } = await import('react-native');
+ const { useRef } = await import('react');
+ return { default: { View }, useSharedValue: (value: unknown) => useRef({ value }).current,
+ useAnimatedStyle: (calculate: () => unknown) => calculate() };
+});
+
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+it('keeps send/voice/grabber outside the scrolling body and retains the editor across collapse', () => {
+ const container = document.createElement('div');
+ const root = createRoot(container);
+ const send = vi.fn();
+ const gesture = {} as NonNullable<React.ComponentProps<typeof MobileComposerInputRow>['bodyScrollGesture']>;
+ const render = (cardActive: boolean) => act(() => root.render(<MobileComposerInputRow
+ accessibilityLabel="Message" inputTestID="input" placeholder="Message" placeholderTextColor="inherit"
+ value={'Long text\n'.repeat(300)} onChangeText={() => {}} cardActive={cardActive}
+ bodyScrollGesture={gesture} inputElement={<textarea defaultValue={'Long text\n'.repeat(300)} />}
+ accessoryAbove={<div data-testid="attachment">Image</div>}
+ toolbar={<button onClick={send}>Send</button>} resizeHandle={<div data-testid="grabber" />}
+ voicePlacement={{ inline: false, floating: true }} floatingVoiceButton={() => <button>Voice</button>}
+ testID="composer"
+ />));
+ try {
+ render(true);
+ const body = container.querySelector('[data-testid="composer.bodyScroll"]')!;
+ const editor = container.querySelector('textarea');
+ expect(body.contains(editor)).toBe(true);
+ expect(body.querySelector('[data-testid="attachment"]')).not.toBeNull();
+ for (const selector of ['button', '[data-testid="grabber"]']) expect(body.querySelector(selector)).toBeNull();
+ const button = container.querySelector<HTMLButtonElement>('[data-testid="composer.toolbar"] button')!;
+ act(() => button.click());
+ expect(send).toHaveBeenCalledOnce();
+ render(false);
+ expect(container.querySelector('textarea')).toBe(editor);
+ expect(body.getAttribute('data-scroll')).toBe('false');
+ render(true);
+ expect(container.querySelector('textarea')).toBe(editor);
+ expect(body.getAttribute('data-scroll')).toBe('true');
+ } finally { act(() => root.unmount()); }
+});
diff --git a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
index 030123be08..e2925550d9 100644
--- a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
@@ -117,14 +117,14 @@ describe('mobile session composer desktop-first surface', () => {
const inputEnd = sharedSource.indexOf('resizeGrabberTouch:', inputStart);
const inputStyle = sharedSource.slice(inputStart, inputEnd);
const composerStyleStart = source.indexOf('composer: {');
- const composerStyleEnd = source.indexOf('composerScroll:', composerStyleStart);
+ const composerStyleEnd = source.indexOf('composerScrollFrame:', composerStyleStart);
const composerStyle = source.slice(composerStyleStart, composerStyleEnd);
const composerStatusCallIndex = source.indexOf('<ComposerActivityStatus');
const composerViewStart = source.indexOf('testID="session.composer"');
- const composerScrollEnd = source.indexOf('</ScrollView>', composerViewStart);
+ const composerScrollEnd = source.indexOf('</ComposerFrame>', composerViewStart);
const composerViewSource = source.slice(composerViewStart, composerScrollEnd);
const voiceStatusIndex = composerViewSource.indexOf('testID="session.voiceStatus"');
- const composerScrollIndex = composerViewSource.indexOf('testID="session.composerScroll"');
+ const composerScrollIndex = composerViewSource.indexOf('bodyScrollTestID="session.composerScroll"');
const voiceDraftTextStart = source.indexOf('onTextLayout={handleVoiceDraftTextLayout}');
const voiceDraftTextEnd = source.indexOf('</Text>', voiceDraftTextStart);
const voiceDraftTextSource = source.slice(voiceDraftTextStart, voiceDraftTextEnd);
@@ -159,7 +159,7 @@ describe('mobile session composer desktop-first surface', () => {
expect(source).toContain('toolbar: renderComposerToolbar()');
expect(source).toContain('trailing: renderComposerTrailingActions()');
expect(source).toContain('gesture={composerResize.gesture}');
- expect(source).toContain('<GestureDetector gesture={composerResize.scrollGesture}>');
+ expect(source).toContain('bodyScrollGesture={composerResize.scrollGesture}');
expect(source).not.toContain('styles.composerCompactAttachmentSlot');
expect(source).toContain('styles.composerCompactAttachmentHit');
expect(source).not.toContain('styles.composerCompactAttachmentHitArea');
@@ -367,7 +367,7 @@ describe('mobile session composer desktop-first surface', () => {
expect(source).toContain('const handleGrabberTouchActiveChange = useCallback((active: boolean) => {');
expect(source).toContain('composerScrollViewRef.current?.setNativeProps({');
expect(source).toContain('onGrabberTouchActiveChange: handleGrabberTouchActiveChange,');
- expect(source).toContain('ref={composerScrollViewRef}');
+ expect(source).toContain('bodyScrollRef={composerScrollViewRef}');
expect(source).not.toContain('const composerScrollEnabled = nativeShellLayout.composerScrollEnabled || voiceIsListening || composerInputScrollEnabled;');
expect(source).toContain('onContentSizeChange={handleComposerInputContentSizeChange}');
expect(source).not.toContain('voiceIsListening && { height: composerInputVisibleHeight }');
diff --git a/apps/mobile/src/session/MobileComposerInputRow.tsx b/apps/mobile/src/session/MobileComposerInputRow.tsx
index 95ea6ecf98..ab6dfe0b20 100644
--- a/apps/mobile/src/session/MobileComposerInputRow.tsx
+++ b/apps/mobile/src/session/MobileComposerInputRow.tsx
@@ -3,6 +3,7 @@ import {
Animated,
Platform,
Pressable,
+ ScrollView,
Easing,
StyleSheet,
View,
@@ -16,7 +17,7 @@ import {
import { TextInput } from '@/components/AppText';
import Reanimated, { useAnimatedStyle, useSharedValue, type SharedValue } from 'react-native-reanimated';
import { GestureDetector } from '@/platform/gestureHandler';
-import type { PanGesture } from 'react-native-gesture-handler';
+import type { NativeGesture, PanGesture } from 'react-native-gesture-handler';
import Constants, { ExecutionEnvironment } from 'expo-constants';
import { TextInputWrapper, type PasteEventPayload } from 'expo-paste-input';
import { Mic } from 'lucide-react-native';
@@ -107,6 +108,11 @@ export interface MobileComposerInputRowProps {
collapseProgress?: SharedValue<number>;
/** The enclosing scroll surface owns the native glass frame. */
frameOutside?: boolean;
+ /** Scroll attachments/text independently; the toolbar remains outside this viewport. */
+ bodyScrollGesture?: NativeGesture;
+ bodyScrollRef?: Ref<ScrollView>;
+ bodyScrollEnabled?: boolean;
+ bodyScrollTestID?: string;
caretHidden?: boolean;
compact?: boolean;
autoFocus?: TextInputProps['autoFocus'];
@@ -210,6 +216,10 @@ export function MobileComposerInputRow({
autoFocus,
cardActive,
frameOutside,
+ bodyScrollGesture,
+ bodyScrollRef,
+ bodyScrollEnabled = true,
+ bodyScrollTestID,
collapseProgress,
caretHidden,
compact,
@@ -317,32 +327,8 @@ export function MobileComposerInputRow({
value={value}
/>
);
- return (
- <ComposerFrame
- entryTransitionId={entryTransitionId}
- onEntryTransitionComplete={onEntryTransitionComplete}
- expandToken={expandToken}
- expanded={cardLayout}
- unframed={frameOutside}
- style={[
- styles.row,
- compact && styles.rowCompact,
- geometricSingleLine && styles.rowCollapsedTouch,
- geometricSingleLine && collapsedHeight != null && { minHeight: collapsedHeight },
- concentricInset != null && {
- paddingLeft: Math.max(0, concentricInset - (MOBILE_COMPOSER_MIN_TOUCH_TARGET - MOBILE_COMPOSER_CONTROL_SIZE) / 2),
- paddingRight: concentricInset,
- },
- !geometricSingleLine && multilineShape && styles.rowMultiline,
- cardLayout && styles.rowCard,
- Platform.OS === 'ios' && cardLayout && styles.rowNativeCard,
- // The native frame owns the contour; its child must not add a second corner.
- nativeComposerFrameAvailable && { backgroundColor: 'transparent', borderWidth: 0, borderRadius: 0 },
- rowStyle,
- ]}
- testID={testID}
- >
- {resizeHandle}
+ const inputBody = (
+ <>
{cardLayout && accessoryAbove ? <ComposerFoldingSection progress={collapseProgress}>{accessoryAbove}</ComposerFoldingSection> : null}
<View
style={[
@@ -377,6 +363,50 @@ export function MobileComposerInputRow({
</Reanimated.View>
{cardLayout ? null : trailing}
</View>
+ </>
+ );
+ return (
+ <ComposerFrame
+ entryTransitionId={entryTransitionId}
+ onEntryTransitionComplete={onEntryTransitionComplete}
+ expandToken={expandToken}
+ expanded={cardLayout}
+ unframed={frameOutside}
+ style={[
+ styles.row,
+ compact && styles.rowCompact,
+ geometricSingleLine && styles.rowCollapsedTouch,
+ geometricSingleLine && collapsedHeight != null && { minHeight: collapsedHeight },
+ concentricInset != null && {
+ paddingLeft: Math.max(0, concentricInset - (MOBILE_COMPOSER_MIN_TOUCH_TARGET - MOBILE_COMPOSER_CONTROL_SIZE) / 2),
+ paddingRight: concentricInset,
+ },
+ !geometricSingleLine && multilineShape && styles.rowMultiline,
+ cardLayout && styles.rowCard,
+ Platform.OS === 'ios' && cardLayout && styles.rowNativeCard,
+ // The native frame owns the contour; its child must not add a second corner.
+ nativeComposerFrameAvailable && { backgroundColor: 'transparent', borderWidth: 0, borderRadius: 0 },
+ rowStyle,
+ ]}
+ testID={testID}
+ >
+ {resizeHandle}
+ {bodyScrollGesture ? (
+ <GestureDetector gesture={bodyScrollGesture}>
+ <ScrollView
+ ref={bodyScrollRef}
+ style={styles.bodyScroll}
+ contentContainerStyle={styles.bodyScrollContent}
+ keyboardShouldPersistTaps="handled"
+ bounces={false}
+ scrollEnabled={cardLayout && bodyScrollEnabled}
+ showsVerticalScrollIndicator={cardLayout && bodyScrollEnabled}
+ testID={bodyScrollTestID ?? (testID ? `${testID}.bodyScroll` : undefined)}
+ >
+ {inputBody}
+ </ScrollView>
+ </GestureDetector>
+ ) : inputBody}
{cardLayout && toolbar != null ? (
<ComposerFoldingSection progress={collapseProgress}>
<View
@@ -478,6 +508,7 @@ function ComposerFoldingSection({ progress, children }: { progress?: SharedValue
height: measuredHeight.value > 0 ? measuredHeight.value * (1 - amount) : 'auto' as const,
opacity: 1 - amount,
overflow: 'hidden' as const,
+ flexShrink: 0,
};
});
return <Reanimated.View style={style}>
@@ -648,6 +679,7 @@ const makeMobileComposerInputRowStyles = (colors: ThemeColors) => ({
borderRadius: radius.pill,
borderWidth: StyleSheet.hairlineWidth,
flexDirection: 'column',
+ flexShrink: 1,
minHeight: 50,
overflow: 'visible',
paddingHorizontal: spacing.md,
@@ -711,6 +743,8 @@ const makeMobileComposerInputRowStyles = (colors: ThemeColors) => ({
flexDirection: 'row',
minWidth: 0,
},
+ bodyScroll: { flexShrink: 1 },
+ bodyScrollContent: { flexGrow: 1 },
toolbarRow: {
alignItems: 'center',
flexDirection: 'row',
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 8d9f667e80..d695def3f6 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -635,3 +635,17 @@ Mobile 原生 fingerprint 输入,服务端无需改动。
桌面能力页新增仅限可信本地 renderer 的 `local-db:bots:skills:list` 读取伙伴自有技能;
远程端继续使用已有 `settings:<botId>/skills` 资源,不扩 IPC allowlist。
SSH 继续沿用现有伙伴远端技能限制,不读取控制端本机资料;设备互联由执行宿主保存与复盘。
+
+## 模型目录分段读取
+
+`maker:provider:list` 通过请求的 `capabilities: ['provider-catalog-pages-v1']` 协商分段响应。
+主机先完成原有授权、路由凭证剥离和模型投影,再将完整 JSON 按至多 256 Ki 个 UTF-16
+码元分段;`provider-catalog-page-v1` 携带 `revision`(完整投影的 SHA-256)、`offset`、
+`total` 与 `data`。后续请求的可选 `catalogPage: { offset, revision }` 必须匹配当前目录,
+每次仍执行授权与投影,目录改变则明确失败,不拼接不同快照。控制端仅在完整重组后发布目录,
+限制重组至 64 Mi 个码元;单段即使全部需要 JSON 转义也低于既有 2 MiB 帧限制。
+
+共享 DeviceLinkClient 为手机和远程桌面统一协商与重组,保留模型、顺序、偏好和能力字段。
+旧主机忽略能力声明并返回原格式;旧控制端不声明能力,新主机也返回原格式。共享任务仍要求
+`history.read`,游标不增加权限。服务端、relay、传输帧限制和 Mobile 原生指纹均不改变;
+超大目录的完整修复需要执行主机及控制端均升级,单端回退保留原有大小限制。
diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.ts
index 1b73d4d26e..b01e8dd80c 100644
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@ -3,6 +3,8 @@
* 握手 / 请求配对 / 超时 / relay-error / 重连退避 / 心跳僵死 / token 缺失。
*/
import { describe, it, expect, vi } from 'vitest';
+import { createHash } from 'node:crypto';
+import { encodeProviderCatalogPage } from '../providerCatalogTransport.js';
import { DeviceLinkClient, computeReconnectDelayMs, type WsLike } from '../client.js';
import {
PROTOCOL_VERSION,
@@ -965,6 +967,27 @@ describe('DeviceLinkClient', () => {
await expect(p).resolves.toMatchObject({ ok: true, result: ['s1'] });
h.client.stop();
});
+ it('assembles provider pages through invoke and checks ownership before each page', async () => {
+ const h = makeHarness();
+ h.client.start();
+ await tick();
+ h.current().ack();
+ const preSend = vi.fn();
+ const value = { providers: [{ id: 'custom', models: { pi: [{ id: 'model', description: 'x'.repeat(300000) }] } }] };
+ const pending = h.client.invoke('dev-b', { channel: 'maker:provider:list', args: [] }, undefined, { preSend });
+ for (let i = 0; i < 2; i++) {
+ const sent = h.current().sent.filter(e => e.kind === 'invoke')[i];
+ expect(sent).toBeDefined();
+ const request = sent.payload as { args: unknown[] };
+ h.current().push({ v: PROTOCOL_VERSION, kind: 'invoke-result', id: sent.id, src: 'dev-b',
+ payload: { ok: true, result: encodeProviderCatalogPage(request.args, value,
+ json => createHash('sha256').update(json).digest('hex')) } });
+ await tick();
+ }
+ await expect(pending).resolves.toEqual({ ok: true, result: value });
+ expect(preSend).toHaveBeenCalledTimes(2);
+ h.client.stop();
+ });
it("negotiates a tag catalog and returns the original session array to callers", async () => {
const h = makeHarness();
h.client.start();
diff --git a/packages/device-link/src/__tests__/providerCatalogTransport.test.ts b/packages/device-link/src/__tests__/providerCatalogTransport.test.ts
new file mode 100644
index 0000000000..08285c78e3
--- /dev/null
+++ b/packages/device-link/src/__tests__/providerCatalogTransport.test.ts
@@ -0,0 +1,66 @@
+import { createHash } from 'node:crypto';
+import { describe, expect, it, vi } from 'vitest';
+import { encodeProviderCatalogPage, readProviderCatalog, PROVIDER_CATALOG_PAGES_CAPABILITY } from '../providerCatalogTransport.js';
+import { encodeReliableFrames } from '../transport.js';
+import type { InvokePayload, InvokeResultPayload } from '../protocol.js';
+
+const revisionOf = (json: string) => createHash('sha256').update(json).digest('hex');
+const payload: InvokePayload = { channel: 'maker:provider:list', args: [{ capabilities: ['provider-logo-kinds-v2'] }] };
+const catalog = (count = 1) => ({
+ providers: [{ id: 'custom', connected: true, models: { pi: Array.from({ length: count }, (_, i) => ({
+ id: `model-${i}`, name: `模型 🐈 ${i}`, description: '引用 "\\\n🐈'.repeat(80), efforts: ['low', 'high'],
+ })) } }],
+ providerOrder: ['custom'], modelVisibilityOverrides: { 'pi:custom:model-0': false },
+});
+
+describe('provider catalog pages', () => {
+ it('round-trips every model/option in a >4MiB catalog through bounded reliable frames', async () => {
+ const value = catalog(4000);
+ expect(Buffer.byteLength(JSON.stringify(value))).toBeGreaterThan(4 * 1024 * 1024);
+ const request = vi.fn(async (next: InvokePayload): Promise<InvokeResultPayload> => {
+ const result = encodeProviderCatalogPage(next.args, value, revisionOf);
+ const envelope = { v: 1 as const, kind: 'invoke-result' as const, src: 'host', dst: 'phone', id: 'read', payload: { ok: true as const, result } };
+ expect(Buffer.byteLength(JSON.stringify(envelope))).toBeLessThan(2 * 1024 * 1024);
+ expect(() => encodeReliableFrames(envelope, 'stream', 1)).not.toThrow();
+ return envelope.payload;
+ });
+ expect(await readProviderCatalog(payload, request)).toEqual({ ok: true, result: value });
+ expect(request.mock.calls.length).toBeGreaterThan(1);
+ expect(payload.args).toEqual([{ capabilities: ['provider-logo-kinds-v2'] }]);
+ });
+
+ it('keeps old hosts, old controllers and unrelated invokes compatible', async () => {
+ const value = catalog();
+ expect(encodeProviderCatalogPage(payload.args, value, revisionOf)).toBe(value);
+ const reply = { ok: true as const, result: value };
+ const legacy = vi.fn(async () => reply);
+ expect(await readProviderCatalog(payload, legacy)).toBe(reply);
+ expect(legacy).toHaveBeenCalledTimes(1);
+ const unrelated = { channel: 'maker:list-active', args: [] };
+ await readProviderCatalog(unrelated, legacy);
+ expect(legacy).toHaveBeenLastCalledWith(unrelated);
+ });
+
+ it('rejects changed snapshots, malformed cursors and out-of-order pages', async () => {
+ const value = catalog(1000);
+ const options = { capabilities: [PROVIDER_CATALOG_PAGES_CAPABILITY] };
+ expect(() => encodeProviderCatalogPage([{ ...options, catalogPage: { offset: -1, revision: 'x' } }], value, revisionOf)).toThrow('Invalid provider catalog cursor');
+ let calls = 0;
+ await expect(readProviderCatalog(payload, async next => {
+ calls++;
+ return { ok: true, result: encodeProviderCatalogPage(next.args, calls > 1 ? catalog(999) : value, revisionOf) };
+ })).rejects.toThrow('Provider catalog changed');
+ await expect(readProviderCatalog(payload, async next => ({
+ ok: true, result: { ...(encodeProviderCatalogPage(next.args, value, revisionOf) as object), offset: 1 },
+ }))).rejects.toThrow('Inconsistent provider catalog page');
+ });
+
+ it('propagates a later authorization failure without exposing a partial catalog', async () => {
+ let calls = 0;
+ const denied = { ok: false as const, error: { code: 'ACCESS_REVOKED' as const, message: 'revoked' } };
+ expect(await readProviderCatalog(payload, async next => ++calls > 1 ? denied : ({
+ ok: true, result: encodeProviderCatalogPage(next.args, catalog(1000), revisionOf),
+ }))).toBe(denied);
+ expect(calls).toBe(2);
+ });
+});
diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.ts
index b998502bbe..3765c065b6 100644
--- a/packages/device-link/src/client.ts
+++ b/packages/device-link/src/client.ts
@@ -1,5 +1,6 @@
import { isPeerResetRetryableReadChannel, isBackgroundInvoke, bypassInvokeScheduling } from './invokePolicy.js';
import { InvokeScheduler } from './invokeScheduler.js';
+import { readProviderCatalog } from './providerCatalogTransport.js';
import { encodeSharedTaskEnvelope, decodeSharedTaskEnvelope } from './sharedTaskEnvelope.js';
import { isSharedTaskPeer } from './sharedTaskPeer.js';
import { SHARED_TASK_RELAY_CAPABILITY } from '@cindy/device-link-protocol';
@@ -1347,6 +1348,15 @@ export class DeviceLinkClient {
payload: InvokePayload,
timeoutMs?: number,
options?: { preSend?: () => void },
+ ): Promise<InvokeResultPayload> {
+ return readProviderCatalog(payload, page => this.invokeOnce(dst, page, timeoutMs, options));
+ }
+
+ private async invokeOnce(
+ dst: string,
+ payload: InvokePayload,
+ timeoutMs?: number,
+ options?: { preSend?: () => void },
): Promise<InvokeResultPayload> {
if (this.status !== 'online') throw new DeviceLinkError('NOT_CONNECTED', 'not connected to relay');
const send = () => {
diff --git a/packages/device-link/src/index.ts b/packages/device-link/src/index.ts
index 4c5fe55299..a9556c448f 100644
--- a/packages/device-link/src/index.ts
+++ b/packages/device-link/src/index.ts
@@ -41,6 +41,7 @@ export * from "./sharedTaskInvitation.js";
export * from "./sharedTaskProbe.js";
export * from "./modelFavorites.js";
export * from "./sessionListTransport.js";
+export * from './providerCatalogTransport.js';
export * from "./clipboardSync.js";
export * from "./clipboardSyncFailure.js";
diff --git a/packages/device-link/src/providerCatalogTransport.ts b/packages/device-link/src/providerCatalogTransport.ts
new file mode 100644
index 0000000000..98d2460961
--- /dev/null
+++ b/packages/device-link/src/providerCatalogTransport.ts
@@ -0,0 +1,81 @@
+import { DeviceLinkError, type InvokePayload, type InvokeResultPayload } from './protocol.js';
+
+export const PROVIDER_CATALOG_PAGES_CAPABILITY = 'provider-catalog-pages-v1';
+export const PROVIDER_CATALOG_PAGE_CHARS = 256 * 1024;
+const channel = 'maker:provider:list';
+const format = 'provider-catalog-page-v1';
+// Bound controller-side assembly independently of the per-message transport limit.
+const maxCatalogChars = 64 * 1024 * 1024;
+const record = (value: unknown): value is Record<string, unknown> =>
+ !!value && typeof value === 'object' && !Array.isArray(value);
+
+export function isProviderCatalogCursor(value: unknown): value is { offset: number; revision: string } {
+ return record(value) && Object.keys(value).every(key => key === 'offset' || key === 'revision')
+ && Number.isSafeInteger(value.offset) && (value.offset as number) > 0
+ && (value.offset as number) < maxCatalogChars
+ && typeof value.revision === 'string' && /^[a-f0-9]{64}$/.test(value.revision);
+}
+
+/** Called only after the host's normal authorization and credential-free projection. */
+export function encodeProviderCatalogPage(
+ args: readonly unknown[], value: unknown, revisionOf: (json: string) => string,
+): unknown {
+ const options = args[0];
+ if (!record(options) || !Array.isArray(options.capabilities)
+ || !options.capabilities.includes(PROVIDER_CATALOG_PAGES_CAPABILITY)) return value;
+ const json = JSON.stringify(value);
+ if (json === undefined) return value;
+ if (json.length > maxCatalogChars) throw new Error('[PRECONDITION_FAILED] Provider catalog exceeds assembly budget');
+ const revision = revisionOf(json);
+ const cursor = options.catalogPage;
+ if (cursor !== undefined && !isProviderCatalogCursor(cursor)) {
+ throw new Error('[INVALID_PARAMS] Invalid provider catalog cursor');
+ }
+ if (cursor && (cursor.revision !== revision || cursor.offset >= json.length)) {
+ throw new Error('[PRECONDITION_FAILED] Provider catalog changed during read');
+ }
+ const offset = cursor?.offset ?? 0;
+ // Even worst-case JSON escaping stays below the legacy 2MiB frame budget.
+ return { format, revision, offset, total: json.length, data: json.slice(offset, offset + PROVIDER_CATALOG_PAGE_CHARS) };
+}
+
+/** Preserve the public invoke result, assembling the entire catalog before publishing it. */
+export async function readProviderCatalog(
+ payload: InvokePayload,
+ invoke: (payload: InvokePayload) => Promise<InvokeResultPayload>,
+): Promise<InvokeResultPayload> {
+ if (payload.channel !== channel) return invoke(payload);
+ const original = payload.args?.[0];
+ if (original !== undefined && !record(original)) return invoke(payload);
+ const options = {
+ ...original,
+ capabilities: [...new Set([
+ ...(Array.isArray(original?.capabilities) ? original.capabilities : []),
+ PROVIDER_CATALOG_PAGES_CAPABILITY,
+ ])],
+ };
+ let response = await invoke({ ...payload, args: [options, ...(payload.args?.slice(1) ?? [])] });
+ // Old hosts ignore the capability and return the original complete catalog.
+ if (!response.ok || !record(response.result) || response.result.format !== format) return response;
+ const revision = response.result.revision;
+ const total = response.result.total;
+ if (typeof revision !== 'string' || !/^[a-f0-9]{64}$/.test(revision)
+ || !Number.isSafeInteger(total) || (total as number) <= 0 || (total as number) > maxCatalogChars) {
+ throw new DeviceLinkError('BAD_REQUEST', 'Invalid provider catalog page');
+ }
+ const parts: string[] = [];
+ let offset = 0;
+ while (response.ok) {
+ const page = response.result;
+ if (!record(page) || page.format !== format || page.revision !== revision || page.total !== total
+ || page.offset !== offset || typeof page.data !== 'string' || !page.data.length
+ || page.data.length !== Math.min(PROVIDER_CATALOG_PAGE_CHARS, (total as number) - offset)) {
+ throw new DeviceLinkError('BAD_REQUEST', 'Inconsistent provider catalog page');
+ }
+ parts.push(page.data);
+ offset += page.data.length;
+ if (offset === total) return { ...response, result: JSON.parse(parts.join('')) };
+ response = await invoke({ ...payload, args: [{ ...options, catalogPage: { offset, revision } }, ...(payload.args?.slice(1) ?? [])] });
+ }
+ return response;
+}