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。

27.5 KB
Raw Blame
import { modelNeedsReselection } from './modelReselection';
/**
 * Shared model and permission selection for new and existing tasks.
 * iOS presents native Form pages inside one system sheet; options and permissions
 * replace its content. Android retains the existing layered SheetSurface flow.
 * Selected-model options apply live; other models retain their remembered options.
 */
import { UnifiedModelPickerSheet, type UnifiedMobilePickerOptions } from './UnifiedModelPickerSheet';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ChevronRight, Search, X } from 'lucide-react-native';
import {
  Animated,
  Easing,
  Platform,
  Pressable,
  ScrollView,
  StyleSheet,
  View,
  useWindowDimensions,
} from 'react-native';
import type { TextInput as RNTextInput } from 'react-native';
import { Text, TextInput } from '@/components/AppText';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

import type { MobileAgentCapabilities, MobileChoiceOption, MobileModelOption } from '@/session/agentCapabilities';
import type { DeviceApiKeyStatus } from '@/device-link/deviceModelMetaCache';
import type { MobileModelPricingMap } from '@/device-link/mobileMakerTransport';
import type { ProviderView } from '@cindy/model-providers/registry';
import type { AgentKind } from '@cindy/model-providers/types';
import { MobileModelPickerList, type ModelOptionsOpenTarget } from '@/session/MobileModelPickerList';
import { MobileAgentSwitcher } from '@/session/MobileAgentSwitcher';
import { MobilePermissionPickerList } from '@/session/MobilePermissionPickerList';
import { ModelOptionsSheetView } from '@/session/ModelOptionsSheetView';
import { ComposerSheet } from './ComposerSheet';
import { ModelPickerNativeHeader } from './ModelPickerNativeHeader';
import { SheetModal } from '@/session/SheetModal';
import { SheetSurface } from '@/session/SheetSurface';
import { computeContextSheetSnapHeights, type ContextSheetSnap } from '@/session/contextSheetModel';
import type { MobileModelMemoryAccessors } from '@/session/draftModelMemory';
import {
  canUseFlatModelFallback,
  filterFlatModelOptions,
  findOptionsTarget,
  modelPickerSheetTitle,
  settleModelPickerSheetBack,
  type ModelPickerSheetView,
} from '@/session/modelPickerSheetModel';
import { rowFastEditable } from '@/session/modelPickerRows';
import { permissionPresentation } from '@/session/permissionPresentation';
import {
  buildMobileModelSections,
  flattenProviderSections,
  type ProviderModelRow,
} from '@/session/providerModelSections';
import { iconSize, iconStroke, useTheme, useThemedStyles, type ThemeColors } from '@/theme';
import { fontWeight, lineHeight, motionDuration, motionEasing, radius, spacing, typeScale } from '@/theme/tokens';
import { useReduceMotionEnabled } from '@/hooks/useReduceMotion';
import {
  mobileAgentLabel,
  type MobileSessionAgentKind,
} from '@/session/sessionAgentSwitch';

/** 二级 Surface 是重浮层:入场 enter / 退场 exit(DESIGN.md §14.4);减弱动态效果直接到位。 */
const SECONDARY_SLIDE_IN_EASING = Easing.bezier(...motionEasing.out);
const SECONDARY_SLIDE_OUT_EASING = Easing.bezier(...motionEasing.in);

/** provider-aware 模式下传给列表的空 flat 集(身份稳定,防无谓重渲)。 */
const EMPTY_FLAT_OPTIONS: readonly MobileModelOption[] = [];

export interface ModelPickerSheetProps {
  /** Host-owned context, such as the plugin requesting this selection. */
  title?: string;
  unified?: UnifiedMobilePickerOptions;
  visible: boolean;
  onClose(): void;
  onClosed?(): void;
  // —— 模型目录(与旧 drop-up 面板同口径) ——
  providers: readonly ProviderView[];
  /** 被控端「模型显示/隐藏」override 快照(useDeviceProviders 透传);undefined = 不过滤。 */
  modelVisibilityOverrides?: Record<string, boolean>;
  flatOptions: readonly MobileModelOption[];
  /** A successfully loaded empty catalog must not revive cached capability rows. */
  providersReady?: boolean;
  /** True only when the host explicitly lacks provider:list. */
  providersUnsupported?: boolean;
  agentKind: AgentKind;
  /** 已建会话可选:先浏览 Agent,再选模型登记下一条消息的切换意图。 */
  agentSwitch?: {
    currentAgentKind: MobileSessionAgentKind;
    browsingAgentKind: MobileSessionAgentKind;
    disabled?: boolean;
    onBrowseAgent(next: MobileSessionAgentKind): boolean | void | Promise<boolean | void>;
  };
  capabilities: MobileAgentCapabilities | null;
  activeModelId: string;
  /** 已建会话的选择器传 true:当前来源按实际路由口径解析(见 buildMobileModelSections)。 */
  existingSessionRoute?: boolean;
  /** 显式选中的来源 id(null = 跟随被控端默认路由;内部据此算高亮来源)。 */
  selectedProviderId: string | null;
  selectedEffort: string;
  selectedFastMode: boolean | 'ultrafast';
  loading?: boolean;
  disabled?: boolean;
  emptyHint?: string;
  loadingHint?: string;
  /** 选行(调用方负责落草稿/写穿并关浮窗,与旧 drop-up 语义一致)。 */
  onSelectProviderRow(row: ProviderModelRow): void;
  onSelectFlatModel(option: MobileModelOption): void;
  onChangeSelectedEffort?(effort: string): void;
  onChangeSelectedFastMode?(enabled: boolean | 'ultrafast'): void | Promise<void>;
  modelMemory?: MobileModelMemoryAccessors;
  pricing?: MobileModelPricingMap | null;
  apiKeyStatus?: DeviceApiKeyStatus;
  // —— 权限(合并进本浮窗) ——
  permissionOptions: readonly MobileChoiceOption[];
  /** 权限行展示的当前模式(会话页 plan 激活时传底层权限档)。 */
  activePermissionMode: string;
  /** 选权限(调用方落草稿/写穿);浮窗内部自动回一级,不关浮窗。 */
  onSelectPermissionMode(mode: string): void;
  permissionDisabled?: boolean;
  /**
   * 隐藏 header 右侧权限入口(新建页已把权限提为 composer 独立选择器,浮窗只留模型;
   * 默认 false —— 会话页行为不变)。
   */
  hidePermissionTrigger?: boolean;
  keyboardAvoidingBehavior: 'height' | 'padding' | undefined;
  testID?: string;
}

export function ModelPickerSheet(props: ModelPickerSheetProps) {
  if (props.unified && !props.providersUnsupported) return <UnifiedModelPickerSheet {...props} unified={props.unified} />;
  return <LegacyModelPickerSheet {...props} />;
}
function LegacyModelPickerSheet({
  visible,
  title,
  onClose,
  onClosed,
  providers,
  modelVisibilityOverrides,
  flatOptions,
  providersReady = false,
  providersUnsupported = false,
  agentKind,
  agentSwitch,
  capabilities,
  activeModelId,
  selectedProviderId,
  existingSessionRoute,
  selectedEffort,
  selectedFastMode,
  loading = false,
  disabled = false,
  emptyHint,
  loadingHint,
  onSelectProviderRow,
  onSelectFlatModel,
  onChangeSelectedEffort,
  onChangeSelectedFastMode,
  modelMemory,
  pricing = null,
  apiKeyStatus = 'unknown',
  permissionOptions,
  activePermissionMode,
  onSelectPermissionMode,
  permissionDisabled = false,
  hidePermissionTrigger = false,
  keyboardAvoidingBehavior,
  testID = 'modelSheet',
}: ModelPickerSheetProps) {
  const styles = useThemedStyles(makeStyles);
  const { colors } = useTheme();
  const { t } = useTranslation();
  const { height: windowHeight } = useWindowDimensions();
  const insets = useSafeAreaInsets();

  const [view, setView] = useState<ModelPickerSheetView>({ kind: 'models' });
  const [primarySnap, setPrimarySnap] = useState<ContextSheetSnap>('half');
  const [secondarySnap, setSecondarySnap] = useState<ContextSheetSnap>('half');
  const [query, setQuery] = useState('');
  const scrollRef = useRef<ScrollView | null>(null);
  const searchInputRef = useRef<RNTextInput>(null);
  const didAutoScrollRef = useRef(false);
  // 二级 Surface 滑入/滑出动画(0 = 就位;windowHeight = 屏下)。动画期间锁交互防连点。
  const secondaryTranslate = useRef(new Animated.Value(windowHeight)).current;
  const secondaryAnimatingRef = useRef(false);

  // Android adjustResize 会在键盘开合时改变 windowHeight。重置 effect 只应由一次新的
  // visible 周期触发;否则浮窗打开期间的缩窗会把二级视图、snap 和搜索状态全部重置,
  // 并与 SheetSurface 对新高度的正常吸附动画叠加。最新高度只供下次打开时初始化位移。
  const windowHeightRef = useRef(windowHeight);
  useEffect(() => {
    windowHeightRef.current = windowHeight;
  }, [windowHeight]);

  // 每次重新打开重置(view 回一级、snap 回 half、清搜索、允许再次自动滚到选中行)。
  useEffect(() => {
    if (!visible) return;
    setView({ kind: 'models' });
    setPrimarySnap('half');
    setSecondarySnap('half');
    setQuery('');
    didAutoScrollRef.current = false;
    secondaryTranslate.setValue(windowHeightRef.current);
    secondaryAnimatingRef.current = false;
  }, [visible, secondaryTranslate]);

  const heights = useMemo(
    () => computeContextSheetSnapHeights({ safeAreaTopInset: insets.top, screenHeight: windowHeight }),
    [insets.top, windowHeight],
  );

  const sections = useMemo(
    () =>
      buildMobileModelSections({
        providers,
        agentKind,
        selectedModelId: activeModelId,
        selectedProviderId,
        query,
        visibilityOverrides: modelVisibilityOverrides,
        existingSessionRoute,
      }),
    [providers, modelVisibilityOverrides, agentKind, activeModelId, selectedProviderId, query, existingSessionRoute],
  );
  const providerRows = useMemo(() => flattenProviderSections(sections.sections), [sections]);
  // 二级 options 目标行按**未过滤**行集现查(搜索 query 不应让已打开的二级视图失效)。
  const allSections = useMemo(
    () =>
      buildMobileModelSections({
        providers,
        agentKind,
        selectedModelId: activeModelId,
        selectedProviderId,
        visibilityOverrides: modelVisibilityOverrides,
        existingSessionRoute,
      }),
    [providers, modelVisibilityOverrides, agentKind, activeModelId, selectedProviderId, existingSessionRoute],
  );
  const allRows = useMemo(() => flattenProviderSections(allSections.sections), [allSections]);
  const filteredFlatOptions = useMemo(
    () => filterFlatModelOptions(flatOptions, query),
    [flatOptions, query],
  );
  const browsingOtherAgent = !!agentSwitch
    && agentSwitch.browsingAgentKind !== agentSwitch.currentAgentKind;
  // Disconnected/disabled routes and an authoritative empty catalog must stay empty.
  // Only hosts without a provider catalog retain the capabilities fallback.
  const allowFlatFallback = canUseFlatModelFallback({ providers, providersReady, providersUnsupported, browsingOtherAgent, loading });
  const availableFlatOptions = allowFlatFallback ? flatOptions : EMPTY_FLAT_OPTIONS;
  const effectiveFlatOptions = allowFlatFallback ? filteredFlatOptions : EMPTY_FLAT_OPTIONS;

  const hasQuery = query.trim().length > 0;
  const noResults = hasQuery && providerRows.length === 0 && effectiveFlatOptions.length === 0;

  // —— 二级视图开合(translateY 滑入滑出,动画期间锁重复触发) ——
  const reduceMotion = useReduceMotionEnabled();
  const animateSecondary = reduceMotion === false;
  const openSecondary = useCallback(
    (next: ModelPickerSheetView) => {
      if (Platform.OS === 'ios') { setView(next); return; }
      if (secondaryAnimatingRef.current) return;
      secondaryAnimatingRef.current = true;
      setSecondarySnap('half');
      setView(next);
      secondaryTranslate.setValue(windowHeight);
      Animated.timing(secondaryTranslate, {
        duration: animateSecondary ? motionDuration.enter : 0,
        easing: SECONDARY_SLIDE_IN_EASING,
        toValue: 0,
        useNativeDriver: true,
      }).start(() => {
        secondaryAnimatingRef.current = false;
      });
    },
    [animateSecondary, secondaryTranslate, windowHeight],
  );
  // 行内配置图标 → 二级「模型选项」:useCallback 稳定引用,避免每次 render 都给
  // MobileModelPickerList 递新函数(破坏其下行组件的 memo 短路)。
  const handleOpenOptions = useCallback(
    (target: ModelOptionsOpenTarget) =>
      openSecondary({ kind: 'options', providerId: target.providerId, modelId: target.modelId }),
    [openSecondary],
  );
  const backToModels = useCallback(() => {
    if (Platform.OS === 'ios') { setView({ kind: 'models' }); return; }
    if (secondaryAnimatingRef.current) return;
    secondaryAnimatingRef.current = true;
    Animated.timing(secondaryTranslate, {
      duration: animateSecondary ? motionDuration.exit : 0,
      easing: SECONDARY_SLIDE_OUT_EASING,
      toValue: windowHeight,
      useNativeDriver: true,
    }).start(() => {
      secondaryAnimatingRef.current = false;
      setView({ kind: 'models' });
    });
  }, [animateSecondary, secondaryTranslate, windowHeight]);

  // Android 返回键 / iOS 关闭手势:两段式(二级先回一级,一级才关浮窗)。
  const handleRequestClose = useCallback(() => {
    const settled = settleModelPickerSheetBack(view);
    if (settled.close) {
      onClose();
      return;
    }
    backToModels();
  }, [view, onClose, backToModels]);

  // options 目标行现查:providers 目录热更新后目标消失 → 自动回一级,绝不渲染悬空数据。
  const optionsTarget = useMemo(
    () => findOptionsTarget(view, allRows, availableFlatOptions),
    [view, allRows, availableFlatOptions],
  );
  useEffect(() => {
    if (view.kind === 'options' && !optionsTarget) backToModels();
  }, [view, optionsTarget, backToModels]);

  // Android:搜索聚焦(→full,键盘开)后再把面板拖回 half,列表会重新被键盘挤成一条,
  // 而 onFocus 不会再触发(见搜索框注释)。把「拖到 half」当作用户想收起键盘——blur 搜索框
  // 让键盘落下,adjustResize 恢复窗高后 half 即正常半屏,不再被遮挡。iOS 无此路径(不吸 full、
  // 由 KAV 处理),原样透传。blur 对未聚焦输入是 no-op,故无需额外跟踪聚焦态。
  const handlePrimarySnapChange = useCallback((next: ContextSheetSnap) => {
    if (next === 'half' && Platform.OS === 'android') searchInputRef.current?.blur();
    setPrimarySnap(next);
  }, []);

  const handleSelectedRowLayout = useCallback(
    (y: number): void => {
      if (didAutoScrollRef.current || hasQuery) return;
      didAutoScrollRef.current = true;
      // 留一行余量,让选中行上方能看到相邻行(对齐桌面「滚动到选中行」的观感)。
      scrollRef.current?.scrollTo({ y: Math.max(0, y - 44), animated: false });
    },
    [hasQuery],
  );

  const secondaryTitle = modelPickerSheetTitle(view, allRows, availableFlatOptions);
  // 权限行文案:已知模式用 permissionPresentation 的中文标签(与二级权限列表一致),
  // 未知模式回退被控端 capabilities 给的 label(presentation 内部兜底)。
  const permission = permissionPresentation(
    activePermissionMode,
    permissionOptions.find((o) => o.id === activePermissionMode)?.label,
  );
  const permissionLabel = permission.label;

  const searchRow = (
    <View style={styles.searchRow}>
      <Search color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
      <TextInput
        accessibilityLabel={t('models.picker.searchAccessibility')}
        autoCapitalize="none"
        autoCorrect={false}
        // Android 靠原生 adjustResize 避让键盘(SheetModal 在 Android 不套 KAV,见其头注释):
        // 停在 half 档时键盘一开,面板缩成「0.56 ×(屏高−键盘)」的一小条,列表几乎没了。
        // 聚焦搜索时吸到 full,铺满键盘上方全部可用高度,边打字边看列表。失焦不收回(留 full,
        // 少一次跳动)。iOS 走 KAV padding 把 half 面板顶到键盘上方即可,吸 full 反而会把面板
        // 顶部(含搜索框)推出屏幕外,故不在 iOS 触发。
        onFocus={Platform.OS === 'android' ? () => setPrimarySnap('full') : undefined}
        onChangeText={setQuery}
        placeholder={t('models.picker.searchPlaceholder')}
        placeholderTextColor={colors.textPlaceholder}
        ref={searchInputRef}
        style={styles.searchInput}
        testID={`${testID}.search`}
        value={query}
      />
      {query ? (
        <Pressable
          accessibilityLabel={t('devices.detail.search.clearA11y')}
          accessibilityRole="button"
          hitSlop={8}
          onPress={() => setQuery('')}
          style={({ pressed }) => [styles.searchClear, pressed && { opacity: 0.6 }]}
          testID={`${testID}.search.clear`}
        >
          <X color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
        </Pressable>
      ) : null}
    </View>
  );

  const agentContent = (<>
      {providersReady && modelNeedsReselection(modelVisibilityOverrides, agentKind, activeModelId, selectedProviderId) ? (
        <Text style={styles.modelHiddenHint} testID={`${testID}.modelHiddenHint`}>
          {t('session.common.modelHiddenReselect', { model: activeModelId })}
        </Text>
      ) : null}
      {agentSwitch ? (
        <>
          <MobileAgentSwitcher
            disabled={disabled || agentSwitch.disabled}
            onChange={async (next) => {
              const changed = await agentSwitch.onBrowseAgent(next);
              if (changed === false) return false;
              setQuery('');
              if (view.kind !== 'models') backToModels();
              return true;
            }}
            value={agentSwitch.browsingAgentKind}
          />
          {browsingOtherAgent ? (
            <Text style={styles.agentSwitchHint} testID={`${testID}.agentSwitchHint`}>
              {t('models.picker.agentSwitchHint', { agent: mobileAgentLabel(agentSwitch.browsingAgentKind) })}
            </Text>
          ) : null}
        </>
      ) : null}
    </>);

  const primaryPinnedTop = (
    <View style={styles.pinnedTop}>
      {agentContent}
      {searchRow}
    </View>
  );

  // 权限入口:与 iOS ModelPickerNativeHeader 同构的独立「权限」行(标题 + 副标题为当前模式),
  // 位于搜索之后、模型列表之前;点开二级权限选择。Android 外观沿用 RN 自绘行 + chevron。
  const permissionRowDisabled = permissionDisabled || browsingOtherAgent;
  const permissionRow = hidePermissionTrigger ? null : (
    <Pressable
      accessibilityLabel={t('models.picker.permissionModeAccessibility', { mode: permissionLabel })}
      accessibilityRole="button"
      accessibilityState={{ disabled: permissionRowDisabled }}
      disabled={permissionRowDisabled}
      onPress={() => openSecondary({ kind: 'permission' })}
      style={({ pressed }) => [
        styles.permissionRow,
        permissionRowDisabled && styles.permissionRowDisabled,
        pressed && { opacity: 0.6 },
      ]}
      testID={`${testID}.permissionTrigger`}
    >
      <View style={styles.permissionRowMain}>
        <Text numberOfLines={1} style={styles.permissionRowTitle}>
          {t('models.picker.permissionTitle')}
        </Text>
        <Text numberOfLines={1} style={styles.permissionRowSubtitle}>
          {permissionLabel}
        </Text>
      </View>
      <ChevronRight color={colors.textTertiary} size={iconSize.md} strokeWidth={iconStroke.regular} />
    </Pressable>
  );

  const modelList = (          <MobileModelPickerList
            activeModelId={activeModelId}
            activeSourceId={sections.activeSourceId}
            agentKind={agentKind}
            apiKeyStatus={apiKeyStatus}
            capabilities={capabilities}
            disabled={disabled}
            emptyHint={browsingOtherAgent
              ? t('models.picker.crossAgentEmptyHint', { agent: mobileAgentLabel(agentSwitch!.browsingAgentKind) })
              : emptyHint}
            flatOptions={effectiveFlatOptions}
            loading={loading}
            loadingHint={loadingHint}
            modelMemory={modelMemory}
            providerRows={providerRows}
            onOpenOptions={handleOpenOptions}
            onSelectFlatModel={onSelectFlatModel}
            onSelectProviderRow={onSelectProviderRow}
            onSelectedRowLayout={handleSelectedRowLayout}
            selectedEffort={selectedEffort}
            selectedFastMode={selectedFastMode}
            testID={`${testID}.option`}
          />);
  const secondaryContent = (view.kind === 'permission' ? (
              <MobilePermissionPickerList
                activeMode={activePermissionMode}
                disabled={permissionDisabled}
                onSelect={(mode) => {
                  onSelectPermissionMode(mode);
                  backToModels();
                }}
                options={permissionOptions}
                testID={`${testID}.permissionOption`}
              />
            ) : view.kind === 'options' && optionsTarget ? (
              <ModelOptionsSheetView
                agentKind={agentKind}
                capabilities={capabilities}
                contextWindow={optionsTarget.contextWindow}
                disabled={disabled}
                displayName={optionsTarget.displayName}
                fastEditable={optionsTarget.provider
                  // provider-aware 行:agent gate × 该 (来源, 模型) 目录条目的 supportsFastMode。
                  ? rowFastEditable({
                      provider: optionsTarget.provider,
                      modelId: optionsTarget.model.id,
                      agentKind,
                      hasFastModeCap: capabilities?.hasFastMode === true,
                    })
                  // flat 回退无供应商结构:退化为模型自述(与列表行口径一致)。不能走
                  // rowFastEditable —— 它对 undefined provider 恒 false,会把开关吞掉。
                  : capabilities?.hasFastMode === true &&
                    optionsTarget.model.supportsFastMode === true}
                model={optionsTarget.model}
                modelMemory={modelMemory}
                onChangeSelectedEffort={onChangeSelectedEffort}
                onChangeSelectedFastMode={onChangeSelectedFastMode}
                pricing={pricing}
                provider={optionsTarget.provider}
                providerId={view.providerId}
                selected={
                  view.modelId === activeModelId &&
                  (view.providerId === null || view.providerId === sections.activeSourceId)
                }
                selectedEffort={selectedEffort}
                selectedFastMode={selectedFastMode}
                testID={`${testID}.options`}
              />
            ) : null);
  if (Platform.OS === 'ios') {
    return (
      <ComposerSheet nativeContent visible={visible} onClose={onClose} onClosed={onClosed} backLabel={t('models.picker.backToModels')}
        title={view.kind === 'models' ? title ?? t('models.picker.title') : secondaryTitle}
        onBack={view.kind === 'models' ? undefined : backToModels} testID={testID}>
        {view.kind === 'models' ? <>
          <ModelPickerNativeHeader query={query} onChangeQuery={setQuery}
            agentContent={agentContent} noResults={noResults} permissionLabel={permissionLabel}
            permissionDisabled={permissionDisabled || browsingOtherAgent}
            onPermission={hidePermissionTrigger ? undefined : () => openSecondary({ kind: 'permission' })}
            testID={testID} />
          {!noResults ? modelList : null}
        </> : secondaryContent}
      </ComposerSheet>
    );
  }

  return (
    <SheetModal
      onClosed={onClosed}
      backdropTestID={`${testID}.backdrop`}
      keyboardAvoiding
      keyboardAvoidingBehavior={keyboardAvoidingBehavior}
      onBackdropPress={onClose}
      onRequestClose={handleRequestClose}
      visible={visible}
    >
      <SheetSurface
        bottomInset={insets.bottom}
        heights={heights}
        onClose={onClose}
        onSnapChange={handlePrimarySnapChange}
        pinnedTop={primaryPinnedTop}
        scrollRef={scrollRef}
        snap={primarySnap}
        testID={testID}
        title={title ?? t('models.picker.title')}
      >
        {permissionRow}
        {noResults ? (
          <Text style={styles.noResults} testID={`${testID}.noResults`}>{t('models.picker.noResults')}</Text>
        ) : (
          modelList
        )}
      </SheetSurface>
      {view.kind !== 'models' ? (
        <Animated.View
          style={[styles.secondaryLayer, { transform: [{ translateY: secondaryTranslate }] }]}
          testID={`${testID}.secondaryLayer`}
        >
          <Pressable
            accessibilityLabel={t('models.picker.backToModels')}
            accessibilityRole="button"
            onPress={backToModels}
            style={styles.secondaryBackdrop}
            testID={`${testID}.secondaryBackdrop`}
          />
          <SheetSurface
            backAccessibilityLabel={t('models.picker.backToModels')}
            bottomInset={insets.bottom}
            heights={heights}
            onBack={backToModels}
            onClose={backToModels}
            onSnapChange={setSecondarySnap}
            snap={secondarySnap}
            testID={view.kind === 'permission' ? `${testID}.permissionSheet` : `${testID}.optionsSheet`}
            title={secondaryTitle}
          >
            {secondaryContent}
          </SheetSurface>
        </Animated.View>
      ) : null}
    </SheetModal>
  );
}

function makeStyles(colors: ThemeColors) {
  return {
    // Modal 外壳(背板/内容层/键盘规避)样式已随 SheetModal 抽出。
    // 二级层铺满内容层区域,底部吸附;自带一层 overlay 色 backdrop = 视觉加深一档。
    secondaryLayer: {
      bottom: 0,
      justifyContent: 'flex-end' as const,
      left: 0,
      position: 'absolute' as const,
      right: 0,
      top: 0,
    },
    secondaryBackdrop: {
      backgroundColor: colors.overlay,
      flex: 1,
    },
    searchRow: {
      alignItems: 'center' as const,
      borderColor: colors.borderStrong,
      borderRadius: radius.pill,
      borderWidth: StyleSheet.hairlineWidth,
      flexDirection: 'row' as const,
      gap: spacing.sm,
      marginBottom: spacing.xs,
      minHeight: 36,
      paddingLeft: spacing.md,
      paddingRight: spacing.xs,
    },
    searchClear: {
      alignItems: 'center' as const,
      height: 36,
      justifyContent: 'center' as const,
      width: 36,
    },
    searchInput: {
      color: colors.textPrimary,
      flex: 1,
      fontSize: typeScale.footnote,
      minWidth: 0,
      paddingVertical: 0,
    },
    noResults: {
      color: colors.textTertiary,
      fontSize: typeScale.footnote,
      lineHeight: lineHeight.caption,
      paddingHorizontal: spacing.sm,
      paddingVertical: spacing.md,
      textAlign: 'center' as const,
    },
    pinnedTop: {
      gap: spacing.sm,
    },
    modelHiddenHint: {
      color: colors.textSecondary,
      fontSize: typeScale.footnote,
      lineHeight: lineHeight.caption,
      fontWeight: fontWeight.regular,
      paddingHorizontal: spacing.xs,
    },
    agentSwitchHint: {
      color: colors.textTertiary,
      fontSize: typeScale.footnote,
      lineHeight: lineHeight.caption,
      paddingHorizontal: spacing.xs,
    },
    // 独立「权限」行:行标题 body 500 + 当前模式副标题(短元数据),整行可点。
    permissionRow: {
      alignItems: 'center' as const,
      borderBottomColor: colors.border,
      borderBottomWidth: StyleSheet.hairlineWidth,
      flexDirection: 'row' as const,
      gap: spacing.md,
      minHeight: 52,
    },
    permissionRowMain: {
      flex: 1,
      minWidth: 0,
    },
    permissionRowTitle: {
      color: colors.textPrimary,
      fontSize: typeScale.body,
      lineHeight: lineHeight.body,
      fontWeight: fontWeight.medium,
    },
    permissionRowSubtitle: {
      color: colors.textSecondary,
      fontSize: typeScale.caption,
      lineHeight: lineHeight.caption,
      fontWeight: fontWeight.regular,
    },
    permissionRowDisabled: {
      opacity: 0.5,
    },
  };
}