The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { |
| 2 | getPromptControlledTraits, |
| 3 | getTraitSelectChange, |
| 4 | } from "@t3tools/client-runtime/model-traits"; |
| 5 | import { T, useGT, useLocale, useMessages } from "gt-react-native"; |
| 6 | import * as Dialog from "../../components/ui/Dialog"; |
| 7 | import { createV5StackNavigator as createNativeStackNavigator } from "../../native/createV5StackNavigator"; |
| 8 | import { useSheetStackOptions } from "../layout/nested-stacks"; |
| 9 | import { DEFAULT_SERVER_SETTINGS, ProviderInstanceId } from "@t3tools/contracts"; |
| 10 | import { |
| 11 | modelPreferencesMigrationPatch, |
| 12 | resolveModelPreferences, |
| 13 | } from "@t3tools/shared/serverSettings"; |
| 14 | import type { |
| 15 | EnvironmentId, |
| 16 | ModelSelection, |
| 17 | ProjectId, |
| 18 | ProviderOptionDescriptor, |
| 19 | ProviderOptionSelection, |
| 20 | RuntimeMode, |
| 21 | ServerSettings, |
| 22 | ThreadId, |
| 23 | } from "@t3tools/contracts"; |
| 24 | import type { LegendListRenderItemProps } from "@legendapp/list/react-native"; |
| 25 | import { RegistryContext, useAtomMount, useAtomValue } from "@effect/atom-react"; |
| 26 | import { AnimatedLegendList } from "@legendapp/list/reanimated"; |
| 27 | import { |
| 28 | getProviderOptionCurrentLabel, |
| 29 | getProviderOptionCurrentValue, |
| 30 | } from "@t3tools/shared/model"; |
| 31 | import { |
| 32 | useNavigation, |
| 33 | useRoute, |
| 34 | type RouteProp, |
| 35 | type StaticScreenProps, |
| 36 | } from "@react-navigation/native"; |
| 37 | import { type NativeStackNavigationProp } from "@react-navigation/native-stack"; |
| 38 | import * as Haptics from "expo-haptics"; |
| 39 | import { AsyncResult } from "effect/reactivity"; |
| 40 | import { |
| 41 | createContext, |
| 42 | use, |
| 43 | useEffect, |
| 44 | useEffectEvent, |
| 45 | useRef, |
| 46 | useState, |
| 47 | type ReactNode, |
| 48 | } from "react"; |
| 49 | import { Pressable, ScrollView, View } from "react-native"; |
| 50 | import { READABLE_WIDTH_STYLE, ROW_MIN_HEIGHT } from "../../components/ui/listMetrics"; |
| 51 | import { RefreshControl } from "../../components/ui/RefreshControl"; |
| 52 | import Animated, { |
| 53 | FadeIn, |
| 54 | FadeOut, |
| 55 | LinearTransition, |
| 56 | useReducedMotion, |
| 57 | } from "react-native-reanimated"; |
| 58 | import { useSafeAreaInsets } from "react-native-safe-area-context"; |
| 59 | |
| 60 | import { SymbolView } from "../../components/ui/AppSymbol"; |
| 61 | import { AppText as Text } from "../../components/ui/AppText"; |
| 62 | import { AppBar } from "../../components/ui/AppBar"; |
| 63 | import { ProviderIcon } from "../../components/ProviderIcon"; |
| 64 | import { ThemedSwitch } from "../../components/ui/ThemedSwitch"; |
| 65 | import { cn } from "../../lib/cn"; |
| 66 | import { useReduceMotionEnabled } from "../../lib/appState"; |
| 67 | import { |
| 68 | buildModelOptions, |
| 69 | groupByProvider, |
| 70 | serverConfigForCwd, |
| 71 | type ModelOption, |
| 72 | type ProviderGroup, |
| 73 | withStoredThreadModelOptions, |
| 74 | } from "../../lib/modelOptions"; |
| 75 | import { groupModelsBySubProvider } from "@t3tools/client-runtime/providerSubProviders"; |
| 76 | import { applyProviderOptionSelection } from "../../lib/providerOptions"; |
| 77 | import { resolveProviderOptionDescriptors } from "../../lib/providerOptions"; |
| 78 | import { |
| 79 | rememberModelOptions, |
| 80 | withRememberedModelOptions, |
| 81 | } from "../../state/use-model-option-memory"; |
| 82 | import { ChatGptSharingStatus } from "./ChatGptSharingStatus"; |
| 83 | import { environmentCatalog } from "../../connection/catalog"; |
| 84 | import { useEnvironmentQuery } from "../../state/query"; |
| 85 | import { scopedThreadKey } from "../../lib/scopedEntities"; |
| 86 | import { useThreadReportedModelSelection } from "../../state/entities"; |
| 87 | import { |
| 88 | setComposerDraftText, |
| 89 | updateComposerDraftSettings, |
| 90 | useComposerDraft, |
| 91 | useComposerDraftSettings, |
| 92 | } from "../../state/use-composer-drafts"; |
| 93 | import { useQuietThreadStructure } from "../../state/use-thread-detail"; |
| 94 | import { activeComposerDraftKey, useQueuedRunEdit } from "../../state/queued-run-edit"; |
| 95 | import { selectThreadModel } from "../../state/thread-model-selection"; |
| 96 | import { useThreadSelection } from "../../state/use-thread-selection"; |
| 97 | import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree"; |
| 98 | import { providerWorkspaceSnapshotRefresh } from "../../state/provider-workspace-snapshot-refresh"; |
| 99 | import { threadAllowsProviderSwitch } from "../../state/thread-provider-switching"; |
| 100 | import { environmentServerConfigsAtom, serverEnvironment } from "../../state/server"; |
| 101 | import { mobilePreferencesAtom } from "../../state/preferences"; |
| 102 | import { useAtomCommand } from "../../state/use-atom-command"; |
| 103 | import { useNewTaskFlow } from "./new-task-flow-provider"; |
| 104 | import { ScreenContent } from "../../components/ui/ScreenContent"; |
| 105 | import { |
| 106 | createProviderCatalogRefreshRunner, |
| 107 | providerCatalogRefreshError, |
| 108 | } from "./provider-catalog-refresh"; |
| 109 | import { useSearchToolbarInset } from "../../components/ui/useBarInset"; |
| 110 | import type { AppBarSearch } from "../../components/ui/AppBar"; |
| 111 | import { ModelRow, ChoiceRow } from "./ThreadSettingsRows"; |
| 112 | import { |
| 113 | compatibleRuntimeModeForChoices, |
| 114 | runtimeModeChoicesForSupportedModes, |
| 115 | withManagedRuntimeModeLimits, |
| 116 | type RuntimeModeChoice, |
| 117 | selectableChoices, |
| 118 | } from "./thread-settings-options"; |
| 119 | import { |
| 120 | canCommitPendingModel, |
| 121 | favoritesFirst, |
| 122 | modelFavoriteKey, |
| 123 | modelMatchesCatalogQuery, |
| 124 | pendingModelAfterPress, |
| 125 | providerSectionIsCollapsed, |
| 126 | } from "./thread-settings-sheet-state"; |
| 127 | import { formatProviderUpdateRequiredNotice } from "@t3tools/client-runtime/providerUpdateRequiredModels"; |
| 128 | import type { MessageResolver } from "../../i18n/messages"; |
| 129 | |
| 130 | const PRIMARY_PROVIDER_DRIVERS: ReadonlySet<string> = new Set([ |
| 131 | "claudeAgent", |
| 132 | "codex", |
| 133 | "antigravity", |
| 134 | ]); |
| 135 | /** Keep measured size changes stable; let catalog mutations return underflowing filtered lists to the top. */ |
| 136 | const THREAD_SETTINGS_MAINTAIN_VISIBLE_CONTENT_POSITION = { |
| 137 | data: false, |
| 138 | size: true, |
| 139 | } as const; |
| 140 | const THREAD_SETTINGS_CATALOG_LAYOUT_TRANSITION = LinearTransition.duration(180); |
| 141 | const THREAD_SETTINGS_CATALOG_ENTER_TRANSITION = FadeIn.duration(140); |
| 142 | const THREAD_SETTINGS_CATALOG_EXIT_TRANSITION = FadeOut.duration(120); |
| 143 | const THREAD_SETTINGS_OPTIONS_LAYOUT_TRANSITION = LinearTransition.duration(180); |
| 144 | const THREAD_SETTINGS_OPTION_ENTER_TRANSITION = FadeIn.duration(140); |
| 145 | const THREAD_SETTINGS_OPTION_EXIT_TRANSITION = FadeOut.duration(100); |
| 146 | const EMPTY_MODEL_FAVORITES: ReadonlyArray<{ |
| 147 | readonly provider: ProviderInstanceId; |
| 148 | readonly model: string; |
| 149 | }> = []; |
| 150 | const FAVORITES_PROVIDER_FILTER = "@favorites"; |
| 151 | // Servers that predate `migrateModelPreferences` drop it and keep reporting null favorites. |
| 152 | const attemptedMigrationGenerations = new Map<EnvironmentId, number>(); |
| 153 | function ProviderHeader(props: { |
| 154 | readonly driver: string | undefined; |
| 155 | readonly iconUrl: string | undefined; |
| 156 | readonly label: string; |
| 157 | /** A backend inside a provider's section, such as one of fx's: no icon. */ |
| 158 | readonly nested?: boolean; |
| 159 | /** Why the section has no usable models, such as a signed-out backend. */ |
| 160 | readonly detail?: string | undefined; |
| 161 | readonly collapsible: boolean; |
| 162 | readonly collapsed: boolean; |
| 163 | readonly modelCount: number; |
| 164 | readonly onToggle: () => void; |
| 165 | }) { |
| 166 | const gt = useGT(); |
| 167 | const content = ( |
| 168 | <> |
| 169 | {props.nested ? null : ( |
| 170 | <ProviderIcon iconUrl={props.iconUrl} provider={props.driver} size={15} /> |
| 171 | )} |
| 172 | {props.detail ? ( |
| 173 | <View className="min-w-0 flex-1 py-1"> |
| 174 | <Text className="text-sm font-t3-medium text-foreground-muted">{props.label}</Text> |
| 175 | <Text className="text-xs text-foreground-muted">{props.detail}</Text> |
| 176 | </View> |
| 177 | ) : ( |
| 178 | <Text className="text-sm font-t3-medium text-foreground-muted">{props.label}</Text> |
| 179 | )} |
| 180 | {props.collapsible ? ( |
| 181 | <> |
| 182 | <View className="flex-1" /> |
| 183 | {props.collapsed ? ( |
| 184 | <Text className="text-2xs font-t3-medium text-foreground-muted"> |
| 185 | {props.modelCount} |
| 186 | </Text> |
| 187 | ) : null} |
| 188 | <SymbolView |
| 189 | name={props.collapsed ? "chevron.down" : "chevron.up"} |
| 190 | size={12} |
| 191 | tintColorClassName="accent-icon-subtle" |
| 192 | type="monochrome" |
| 193 | /> |
| 194 | </> |
| 195 | ) : null} |
| 196 | </> |
| 197 | ); |
| 198 | |
| 199 | if (props.collapsible) { |
| 200 | return ( |
| 201 | <Pressable |
| 202 | accessibilityLabel={gt( |
| 203 | "{provider}, {count, plural, one {{count} model} other {{count} models}}", |
| 204 | { |
| 205 | provider: props.label, |
| 206 | count: props.modelCount, |
| 207 | }, |
| 208 | )} |
| 209 | accessibilityRole="button" |
| 210 | accessibilityState={{ expanded: !props.collapsed }} |
| 211 | className="mx-4 mt-1 flex-row items-center gap-2 rounded-xl px-1 pt-2 active:opacity-60" |
| 212 | style={{ minHeight: ROW_MIN_HEIGHT.control }} |
| 213 | onPress={props.onToggle} |
| 214 | > |
| 215 | {content} |
| 216 | </Pressable> |
| 217 | ); |
| 218 | } |
| 219 | |
| 220 | return ( |
| 221 | <View |
| 222 | accessibilityRole="header" |
| 223 | className={cn("mx-4 min-h-9 flex-row items-center gap-2 px-1 pt-1", props.nested && "mt-1")} |
| 224 | > |
| 225 | {content} |
| 226 | </View> |
| 227 | ); |
| 228 | } |
| 229 | |
| 230 | function DisclosureRow(props: { |
| 231 | readonly label: string; |
| 232 | readonly value: string | undefined; |
| 233 | readonly onPress: () => void; |
| 234 | readonly isLast?: boolean; |
| 235 | }) { |
| 236 | return ( |
| 237 | <Pressable |
| 238 | accessibilityRole="button" |
| 239 | onPress={props.onPress} |
| 240 | className={cn( |
| 241 | "flex-row items-center gap-2 bg-grouped-card px-4 py-2 active:bg-subtle", |
| 242 | !props.isLast && "border-b border-border-subtle", |
| 243 | )} |
| 244 | style={{ minHeight: ROW_MIN_HEIGHT.item }} |
| 245 | > |
| 246 | <Text className="text-sm font-t3-medium text-foreground">{props.label}</Text> |
| 247 | <View className="flex-1" /> |
| 248 | {props.value ? ( |
| 249 | <Text className="text-sm text-foreground-muted" numberOfLines={1}> |
| 250 | {props.value} |
| 251 | </Text> |
| 252 | ) : null} |
| 253 | <SymbolView |
| 254 | name="chevron.right" |
| 255 | size={12} |
| 256 | tintColorClassName="accent-icon-subtle" |
| 257 | type="monochrome" |
| 258 | /> |
| 259 | </Pressable> |
| 260 | ); |
| 261 | } |
| 262 | |
| 263 | function SwitchRow(props: { |
| 264 | readonly label: string; |
| 265 | readonly value: boolean; |
| 266 | readonly onValueChange: (value: boolean) => void; |
| 267 | readonly isLast?: boolean; |
| 268 | }) { |
| 269 | return ( |
| 270 | <View |
| 271 | className={cn( |
| 272 | "min-h-11 flex-row items-center justify-between bg-grouped-card px-4 py-1", |
| 273 | !props.isLast && "border-b border-border-subtle", |
| 274 | )} |
| 275 | > |
| 276 | <Text className="text-sm font-t3-medium text-foreground">{props.label}</Text> |
| 277 | <ThemedSwitch |
| 278 | accessibilityLabel={props.label} |
| 279 | onValueChange={props.onValueChange} |
| 280 | value={props.value} |
| 281 | /> |
| 282 | </View> |
| 283 | ); |
| 284 | } |
| 285 | |
| 286 | type ThreadSettingsSubmenuPage = |
| 287 | | { readonly kind: "descriptor"; readonly id: string } |
| 288 | | { readonly kind: "runtime" }; |
| 289 | |
| 290 | type ThreadSettingsSessionProps = { |
| 291 | readonly environmentId: EnvironmentId | null; |
| 292 | readonly projectId: ProjectId | null; |
| 293 | readonly cwd: string | null; |
| 294 | readonly providerInstanceId?: ProviderInstanceId; |
| 295 | readonly lockedProviderInstanceId?: ProviderInstanceId; |
| 296 | readonly providerGroups: ReadonlyArray<ProviderGroup>; |
| 297 | readonly selectedModel: ModelSelection | null; |
| 298 | readonly prompt: string; |
| 299 | readonly onPromptChange: (prompt: string) => void; |
| 300 | readonly reportedModelSelection?: ModelSelection | null; |
| 301 | readonly onSelectModel: (option: ModelOption) => void; |
| 302 | readonly restoreSelection?: (selection: ModelSelection) => ModelSelection; |
| 303 | readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>; |
| 304 | readonly onUpdateOptionSelections: (selections: ReadonlyArray<ProviderOptionSelection>) => void; |
| 305 | readonly runtimeMode: RuntimeMode; |
| 306 | readonly onUpdateRuntimeMode: (mode: RuntimeMode) => void; |
| 307 | }; |
| 308 | |
| 309 | /** The composer draft the sheet edits: the thread's own, or a queued message being edited. */ |
| 310 | export type ExistingThreadSettingsRouteParams = { |
| 311 | readonly environmentId: EnvironmentId; |
| 312 | readonly threadId: ThreadId; |
| 313 | readonly draftKey: string; |
| 314 | }; |
| 315 | |
| 316 | type ThreadSettingsSessionValue = { |
| 317 | readonly environmentId: EnvironmentId | null; |
| 318 | readonly providerInstanceId?: ProviderInstanceId; |
| 319 | readonly providerGroups: ReadonlyArray<ProviderGroup>; |
| 320 | readonly favoriteKeys: ReadonlySet<string>; |
| 321 | readonly favoritesLoaded: boolean; |
| 322 | readonly toggleFavorite: (option: ModelOption) => void; |
| 323 | readonly toggleHidden: (option: ModelOption) => void; |
| 324 | readonly pendingHiddenKeys: ReadonlySet<string>; |
| 325 | readonly manageHidden: boolean; |
| 326 | readonly setManageHidden: (value: boolean) => void; |
| 327 | readonly runtimeMode: RuntimeMode; |
| 328 | readonly runtimeModeChoices: ReadonlyArray<RuntimeModeChoice>; |
| 329 | readonly onUpdateRuntimeMode: (mode: RuntimeMode) => void; |
| 330 | readonly displayedDescriptors: ReadonlyArray<ProviderOptionDescriptor>; |
| 331 | readonly promptTraits: ReturnType<typeof getPromptControlledTraits>; |
| 332 | readonly displayedModelSelection: ModelSelection | null; |
| 333 | readonly reportedModelSelection: ModelSelection | null; |
| 334 | readonly providerExpansionOverrides: ReadonlySet<string>; |
| 335 | readonly hasLegacyModels: boolean; |
| 336 | readonly pendingModel: ModelOption | null; |
| 337 | readonly providerFilter: string | null; |
| 338 | readonly searchQuery: string; |
| 339 | readonly showLegacy: boolean; |
| 340 | readonly applyOptionChange: (id: string, value: string | boolean) => void; |
| 341 | readonly commitPendingModel: () => boolean; |
| 342 | readonly isApplied: (option: ModelOption) => boolean; |
| 343 | readonly isDisplayed: (option: ModelOption) => boolean; |
| 344 | readonly pressModel: (option: ModelOption) => void; |
| 345 | readonly setProviderFilter: (providerKey: string | null) => void; |
| 346 | readonly setSearchQuery: (query: string) => void; |
| 347 | readonly setShowLegacy: (showLegacy: boolean) => void; |
| 348 | readonly toggleProvider: (providerKey: string) => void; |
| 349 | /** The provider whose catalog for this folder the picker keeps fresh. */ |
| 350 | readonly workspaceScan: { readonly instanceId: ProviderInstanceId; readonly cwd: string } | null; |
| 351 | }; |
| 352 | |
| 353 | const ThreadSettingsSessionContext = createContext<ThreadSettingsSessionValue | null>(null); |
| 354 | |
| 355 | function ThreadSettingsSessionProvider( |
| 356 | props: ThreadSettingsSessionProps & { readonly children: ReactNode }, |
| 357 | ) { |
| 358 | const gt = useGT(); |
| 359 | const messages = useMessages(); |
| 360 | const registry = use(RegistryContext); |
| 361 | const preferences = useAtomValue(mobilePreferencesAtom); |
| 362 | const configs = useAtomValue(environmentServerConfigsAtom); |
| 363 | const config = props.environmentId ? configs.get(props.environmentId) : undefined; |
| 364 | const settings = config?.settings; |
| 365 | const connection = useEnvironmentQuery( |
| 366 | props.environmentId ? environmentCatalog.stateAtom(props.environmentId) : null, |
| 367 | ).data; |
| 368 | const connectionGeneration = connection?.phase === "connected" ? connection.generation : null; |
| 369 | const [manageHidden, setManageHidden] = useState(false); |
| 370 | const pendingHidden = useRef(new Set<string>()); |
| 371 | const pendingFavorites = useRef( |
| 372 | new Map<string, { favorite: boolean; settings: ServerSettings; pending: boolean }>(), |
| 373 | ); |
| 374 | const [pendingHiddenKeys, setPendingHiddenKeys] = useState<ReadonlySet<string>>(() => new Set()); |
| 375 | const providerGroups = |
| 376 | manageHidden && config |
| 377 | ? groupByProvider( |
| 378 | buildModelOptions( |
| 379 | serverConfigForCwd(config, props.cwd), |
| 380 | props.selectedModel, |
| 381 | props.lockedProviderInstanceId, |
| 382 | props.projectId, |
| 383 | true, |
| 384 | ), |
| 385 | ) |
| 386 | : props.providerGroups; |
| 387 | const legacyFavorites = AsyncResult.isSuccess(preferences) |
| 388 | ? (preferences.value.modelFavorites ?? EMPTY_MODEL_FAVORITES) |
| 389 | : EMPTY_MODEL_FAVORITES; |
| 390 | const favoritesLoaded = |
| 391 | settings !== undefined && (settings.favorites !== null || AsyncResult.isSuccess(preferences)); |
| 392 | const modelFavorites = resolveModelPreferences(settings ?? DEFAULT_SERVER_SETTINGS, { |
| 393 | favorites: legacyFavorites, |
| 394 | }).favorites; |
| 395 | const saveSettings = useAtomCommand(serverEnvironment.updateSettings, "model favorites update"); |
| 396 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- writes the one-time legacy model favorites migration to server settings once per connection |
| 397 | useEffect(() => { |
| 398 | if ( |
| 399 | !props.environmentId || |
| 400 | !settings || |
| 401 | !AsyncResult.isSuccess(preferences) || |
| 402 | connectionGeneration === null || |
| 403 | attemptedMigrationGenerations.get(props.environmentId) === connectionGeneration |
| 404 | ) |
| 405 | return; |
| 406 | const patch = modelPreferencesMigrationPatch(settings, { favorites: legacyFavorites }); |
| 407 | if (!patch) return; |
| 408 | attemptedMigrationGenerations.set(props.environmentId, connectionGeneration); |
| 409 | void saveSettings({ environmentId: props.environmentId, input: { patch } }); |
| 410 | }, [ |
| 411 | connectionGeneration, |
| 412 | legacyFavorites, |
| 413 | preferences, |
| 414 | props.environmentId, |
| 415 | saveSettings, |
| 416 | settings, |
| 417 | ]); |
| 418 | const favoriteKeys = new Set( |
| 419 | modelFavorites.map((favorite) => modelFavoriteKey(favorite.provider, favorite.model)), |
| 420 | ); |
| 421 | const toggleFavorite = async (option: ModelOption) => { |
| 422 | const environmentId = props.environmentId; |
| 423 | if (!favoritesLoaded || !environmentId) return; |
| 424 | const currentSettings = registry.get(environmentServerConfigsAtom).get(environmentId)?.settings; |
| 425 | if (!currentSettings) return; |
| 426 | const favorites = resolveModelPreferences(currentSettings, { |
| 427 | favorites: legacyFavorites, |
| 428 | }).favorites; |
| 429 | const key = JSON.stringify([ |
| 430 | environmentId, |
| 431 | option.selection.instanceId, |
| 432 | option.selection.model, |
| 433 | ]); |
| 434 | const previous = pendingFavorites.current.get(key); |
| 435 | const previousFavorite = |
| 436 | previous && (previous.pending || previous.settings.favorites === currentSettings.favorites) |
| 437 | ? previous.favorite |
| 438 | : favorites.some( |
| 439 | (favorite) => |
| 440 | favorite.provider === option.selection.instanceId && |
| 441 | favorite.model === option.selection.model, |
| 442 | ); |
| 443 | const pending = { favorite: !previousFavorite, settings: currentSettings, pending: true }; |
| 444 | pendingFavorites.current.set(key, pending); |
| 445 | void Haptics.selectionAsync(); |
| 446 | const result = await saveSettings({ |
| 447 | environmentId: environmentId, |
| 448 | input: { |
| 449 | patch: { |
| 450 | setModelFavorites: [ |
| 451 | { |
| 452 | provider: option.selection.instanceId, |
| 453 | model: option.selection.model, |
| 454 | favorite: pending.favorite, |
| 455 | }, |
| 456 | ], |
| 457 | ...(currentSettings.favorites === null ? { migrateModelPreferences: { favorites } } : {}), |
| 458 | }, |
| 459 | }, |
| 460 | }); |
| 461 | if ( |
| 462 | AsyncResult.isSuccess(result) && |
| 463 | registry.get(environmentServerConfigsAtom).get(environmentId)?.settings.favorites === |
| 464 | currentSettings.favorites |
| 465 | ) { |
| 466 | pending.pending = false; |
| 467 | } |
| 468 | if (pending.pending && pendingFavorites.current.get(key) === pending) { |
| 469 | if ( |
| 470 | previous && |
| 471 | !previous.pending && |
| 472 | registry.get(environmentServerConfigsAtom).get(environmentId)?.settings.favorites === |
| 473 | previous.settings.favorites |
| 474 | ) { |
| 475 | pendingFavorites.current.set(key, previous); |
| 476 | } else { |
| 477 | pendingFavorites.current.delete(key); |
| 478 | } |
| 479 | } |
| 480 | }; |
| 481 | const toggleHidden = (option: ModelOption) => { |
| 482 | if ( |
| 483 | !settings || |
| 484 | !props.environmentId || |
| 485 | !option.canHide || |
| 486 | pendingHidden.current.has(option.key) |
| 487 | ) |
| 488 | return; |
| 489 | pendingHidden.current.add(option.key); |
| 490 | setPendingHiddenKeys(new Set(pendingHidden.current)); |
| 491 | void Haptics.selectionAsync(); |
| 492 | void saveSettings({ |
| 493 | environmentId: props.environmentId, |
| 494 | input: { |
| 495 | patch: { |
| 496 | setModelsHidden: [ |
| 497 | { |
| 498 | provider: option.selection.instanceId, |
| 499 | model: option.selection.model, |
| 500 | hidden: !option.isHidden, |
| 501 | }, |
| 502 | ], |
| 503 | }, |
| 504 | }, |
| 505 | }).then(() => { |
| 506 | pendingHidden.current.delete(option.key); |
| 507 | setPendingHiddenKeys(new Set(pendingHidden.current)); |
| 508 | }); |
| 509 | }; |
| 510 | const [showLegacyToggle, setShowLegacyToggle] = useState(false); |
| 511 | const [providerFilter, setProviderFilter] = useState<string | null>(null); |
| 512 | const [searchQuery, setSearchQuery] = useState(""); |
| 513 | const [providerExpansionOverrides, setProviderExpansionOverrides] = useState<ReadonlySet<string>>( |
| 514 | () => new Set(), |
| 515 | ); |
| 516 | const [pendingModel, setPendingModel] = useState<ModelOption | null>(null); |
| 517 | const [pendingPrompt, setPendingPrompt] = useState<string | null>(null); |
| 518 | const displayedPrompt = pendingModel ? (pendingPrompt ?? props.prompt) : props.prompt; |
| 519 | |
| 520 | const isApplied = (option: ModelOption) => |
| 521 | option.selection.instanceId === props.selectedModel?.instanceId && |
| 522 | option.selection.model === props.selectedModel.model; |
| 523 | const isDisplayed = (option: ModelOption) => |
| 524 | pendingModel ? option.key === pendingModel.key : isApplied(option); |
| 525 | |
| 526 | const displayedDescriptors = pendingModel |
| 527 | ? resolveProviderOptionDescriptors({ |
| 528 | capabilities: pendingModel.capabilities, |
| 529 | selections: pendingModel.selection.options, |
| 530 | }) |
| 531 | : props.optionDescriptors; |
| 532 | const promptTraits = getPromptControlledTraits(displayedDescriptors, displayedPrompt); |
| 533 | const displayedModel = |
| 534 | pendingModel ?? |
| 535 | props.providerGroups.flatMap((group) => group.models).find((option) => isApplied(option)) ?? |
| 536 | null; |
| 537 | const runtimeModeChoices = withManagedRuntimeModeLimits( |
| 538 | runtimeModeChoicesForSupportedModes(displayedModel?.supportedRuntimeModes), |
| 539 | [config?.managedPolicy], |
| 540 | messages, |
| 541 | ); |
| 542 | const compatibleRuntimeMode = compatibleRuntimeModeForChoices( |
| 543 | props.runtimeMode, |
| 544 | runtimeModeChoices, |
| 545 | ); |
| 546 | |
| 547 | const hasLegacyModels = props.providerGroups.some((group) => |
| 548 | group.models.some((model) => model.isLegacy), |
| 549 | ); |
| 550 | const commitPendingModel = () => { |
| 551 | if (pendingModel) { |
| 552 | if (!canCommitPendingModel(pendingModel, props.providerGroups)) { |
| 553 | Dialog.alert( |
| 554 | gt("Model unavailable"), |
| 555 | gt("Set up this provider on web or desktop, or select another model."), |
| 556 | ); |
| 557 | return false; |
| 558 | } |
| 559 | void Haptics.selectionAsync(); |
| 560 | props.onSelectModel(pendingModel); |
| 561 | if (pendingPrompt !== null && pendingPrompt !== props.prompt) { |
| 562 | props.onPromptChange(pendingPrompt); |
| 563 | } |
| 564 | } |
| 565 | return true; |
| 566 | }; |
| 567 | |
| 568 | const applyOptionChange = (id: string, value: string | boolean) => { |
| 569 | const descriptor = displayedDescriptors.find((entry) => entry.id === id); |
| 570 | const change = |
| 571 | descriptor?.type === "select" && typeof value === "string" |
| 572 | ? getTraitSelectChange( |
| 573 | { ...promptTraits, descriptors: displayedDescriptors }, |
| 574 | descriptor, |
| 575 | displayedPrompt, |
| 576 | value, |
| 577 | ) |
| 578 | : null; |
| 579 | if (descriptor?.type === "select") { |
| 580 | if (!change) return; |
| 581 | if (change.prompt !== displayedPrompt) { |
| 582 | if (pendingModel) { |
| 583 | setPendingPrompt(change.prompt); |
| 584 | } else { |
| 585 | props.onPromptChange(change.prompt); |
| 586 | } |
| 587 | } |
| 588 | } |
| 589 | const next = change |
| 590 | ? (change.modelOptions ?? []) |
| 591 | : applyProviderOptionSelection(displayedDescriptors, { id, value }); |
| 592 | if (!next) { |
| 593 | return; |
| 594 | } |
| 595 | if (pendingModel) { |
| 596 | rememberModelOptions(pendingModel.selection.instanceId, pendingModel.selection.model, next); |
| 597 | setPendingModel({ |
| 598 | ...pendingModel, |
| 599 | selection: { ...pendingModel.selection, options: next }, |
| 600 | }); |
| 601 | } else { |
| 602 | props.onUpdateOptionSelections(next); |
| 603 | } |
| 604 | }; |
| 605 | |
| 606 | const toggleProvider = (providerKey: string) => { |
| 607 | setProviderExpansionOverrides((current) => { |
| 608 | const next = new Set(current); |
| 609 | if (!next.delete(providerKey)) { |
| 610 | next.add(providerKey); |
| 611 | } |
| 612 | return next; |
| 613 | }); |
| 614 | }; |
| 615 | |
| 616 | const pressModel = (option: ModelOption) => { |
| 617 | void Haptics.selectionAsync(); |
| 618 | if (isApplied(option) || option.key !== pendingModel?.key) { |
| 619 | setPendingPrompt(null); |
| 620 | } |
| 621 | setPendingModel((current) => |
| 622 | pendingModelAfterPress({ |
| 623 | current, |
| 624 | pressed: option, |
| 625 | pressedIsApplied: isApplied(option), |
| 626 | restoreSelection: props.restoreSelection, |
| 627 | }), |
| 628 | ); |
| 629 | }; |
| 630 | |
| 631 | const environmentId = props.environmentId; |
| 632 | // Like the web picker's open tab: scanning every provider would spawn a probe per provider. |
| 633 | const scannedInstanceId = |
| 634 | providerFilter !== null && providerFilter !== FAVORITES_PROVIDER_FILTER |
| 635 | ? ProviderInstanceId.make(providerFilter) |
| 636 | : props.providerInstanceId; |
| 637 | const workspaceScan = |
| 638 | props.cwd && scannedInstanceId ? { instanceId: scannedInstanceId, cwd: props.cwd } : null; |
| 639 | |
| 640 | const value = { |
| 641 | environmentId, |
| 642 | providerInstanceId: props.providerInstanceId, |
| 643 | providerGroups, |
| 644 | manageHidden, |
| 645 | setManageHidden, |
| 646 | toggleHidden, |
| 647 | pendingHiddenKeys, |
| 648 | runtimeMode: compatibleRuntimeMode, |
| 649 | runtimeModeChoices, |
| 650 | onUpdateRuntimeMode: props.onUpdateRuntimeMode, |
| 651 | displayedDescriptors, |
| 652 | promptTraits, |
| 653 | displayedModelSelection: pendingModel?.selection ?? props.selectedModel, |
| 654 | reportedModelSelection: pendingModel ? null : (props.reportedModelSelection ?? null), |
| 655 | favoriteKeys, |
| 656 | favoritesLoaded, |
| 657 | providerExpansionOverrides, |
| 658 | hasLegacyModels, |
| 659 | pendingModel, |
| 660 | providerFilter, |
| 661 | searchQuery, |
| 662 | showLegacy: showLegacyToggle, |
| 663 | applyOptionChange, |
| 664 | commitPendingModel, |
| 665 | isApplied, |
| 666 | isDisplayed, |
| 667 | pressModel, |
| 668 | setProviderFilter, |
| 669 | setSearchQuery, |
| 670 | setShowLegacy: setShowLegacyToggle, |
| 671 | toggleProvider, |
| 672 | toggleFavorite, |
| 673 | workspaceScan, |
| 674 | } satisfies ThreadSettingsSessionValue; |
| 675 | |
| 676 | return ( |
| 677 | <ThreadSettingsSessionContext.Provider value={value}> |
| 678 | {environmentId && workspaceScan ? ( |
| 679 | <ProviderWorkspaceSnapshotScan |
| 680 | key={workspaceScan.instanceId} |
| 681 | environmentId={environmentId} |
| 682 | instanceId={workspaceScan.instanceId} |
| 683 | cwd={workspaceScan.cwd} |
| 684 | /> |
| 685 | ) : null} |
| 686 | {props.children} |
| 687 | </ThreadSettingsSessionContext.Provider> |
| 688 | ); |
| 689 | } |
| 690 | |
| 691 | /** A project's own provider config can add models only its workspace scan lists. */ |
| 692 | function ProviderWorkspaceSnapshotScan(props: { |
| 693 | readonly environmentId: EnvironmentId; |
| 694 | readonly instanceId: ProviderInstanceId; |
| 695 | readonly cwd: string; |
| 696 | }) { |
| 697 | useAtomMount(providerWorkspaceSnapshotRefresh(props)); |
| 698 | return null; |
| 699 | } |
| 700 | |
| 701 | function useThreadSettingsSession() { |
| 702 | const value = use(ThreadSettingsSessionContext); |
| 703 | if (!value) { |
| 704 | throw new Error("useThreadSettingsSession must be used inside ThreadSettingsSessionProvider."); |
| 705 | } |
| 706 | return value; |
| 707 | } |
| 708 | |
| 709 | type ThreadSettingsProviderCatalog = { |
| 710 | readonly key: string; |
| 711 | readonly driver: string | undefined; |
| 712 | readonly iconUrl: string | undefined; |
| 713 | readonly label: string; |
| 714 | readonly collapsible: boolean; |
| 715 | readonly collapsed: boolean; |
| 716 | readonly modelCount: number; |
| 717 | readonly models: ReadonlyArray<ModelOption>; |
| 718 | }; |
| 719 | |
| 720 | type ThreadSettingsCatalogItem = |
| 721 | | { |
| 722 | readonly kind: "provider"; |
| 723 | readonly key: string; |
| 724 | readonly provider: ThreadSettingsProviderCatalog; |
| 725 | } |
| 726 | | { |
| 727 | readonly kind: "subProvider"; |
| 728 | readonly key: string; |
| 729 | readonly expansionKey: string; |
| 730 | readonly label: string; |
| 731 | readonly detail: string | undefined; |
| 732 | readonly collapsed: boolean; |
| 733 | readonly modelCount: number; |
| 734 | } |
| 735 | | { |
| 736 | readonly kind: "model"; |
| 737 | readonly key: string; |
| 738 | readonly option: ModelOption; |
| 739 | readonly isFirst: boolean; |
| 740 | readonly isLast: boolean; |
| 741 | } |
| 742 | | { |
| 743 | readonly kind: "notice"; |
| 744 | readonly key: string; |
| 745 | readonly text: string; |
| 746 | } |
| 747 | | { |
| 748 | readonly kind: "empty"; |
| 749 | readonly key: "empty"; |
| 750 | } |
| 751 | | { |
| 752 | readonly kind: "options"; |
| 753 | readonly key: "options"; |
| 754 | }; |
| 755 | |
| 756 | function ThreadSettingsModelListRow(props: { |
| 757 | readonly option: ModelOption; |
| 758 | readonly isFirst: boolean; |
| 759 | readonly isLast: boolean; |
| 760 | }) { |
| 761 | const session = useThreadSettingsSession(); |
| 762 | const onPress = () => session.pressModel(props.option); |
| 763 | |
| 764 | return ( |
| 765 | <ModelRow |
| 766 | isFirst={props.isFirst} |
| 767 | isLast={props.isLast} |
| 768 | onPress={onPress} |
| 769 | isFavorite={session.favoriteKeys.has(props.option.key)} |
| 770 | favoritesLoaded={session.favoritesLoaded} |
| 771 | onToggleFavorite={() => session.toggleFavorite(props.option)} |
| 772 | onToggleHidden={ |
| 773 | session.manageHidden && props.option.canHide |
| 774 | ? () => session.toggleHidden(props.option) |
| 775 | : undefined |
| 776 | } |
| 777 | hiddenUpdatePending={session.pendingHiddenKeys.has(props.option.key)} |
| 778 | option={props.option} |
| 779 | selected={session.isDisplayed(props.option)} |
| 780 | /> |
| 781 | ); |
| 782 | } |
| 783 | |
| 784 | function ThreadSettingsProviderListHeader(props: { |
| 785 | readonly provider: ThreadSettingsProviderCatalog; |
| 786 | }) { |
| 787 | const session = useThreadSettingsSession(); |
| 788 | const onToggle = () => session.toggleProvider(props.provider.key); |
| 789 | |
| 790 | return ( |
| 791 | <ProviderHeader |
| 792 | collapsible={props.provider.collapsible} |
| 793 | collapsed={props.provider.collapsed} |
| 794 | driver={props.provider.driver} |
| 795 | iconUrl={props.provider.iconUrl} |
| 796 | label={props.provider.label} |
| 797 | modelCount={props.provider.modelCount} |
| 798 | onToggle={onToggle} |
| 799 | /> |
| 800 | ); |
| 801 | } |
| 802 | |
| 803 | function ThreadSettingsSubProviderListHeader(props: { |
| 804 | readonly item: Extract<ThreadSettingsCatalogItem, { kind: "subProvider" }>; |
| 805 | }) { |
| 806 | const session = useThreadSettingsSession(); |
| 807 | const onToggle = () => session.toggleProvider(props.item.expansionKey); |
| 808 | |
| 809 | return ( |
| 810 | <ProviderHeader |
| 811 | nested |
| 812 | collapsible={props.item.detail === undefined} |
| 813 | collapsed={props.item.collapsed} |
| 814 | detail={props.item.detail} |
| 815 | driver={undefined} |
| 816 | iconUrl={undefined} |
| 817 | label={props.item.label} |
| 818 | modelCount={props.item.modelCount} |
| 819 | onToggle={onToggle} |
| 820 | /> |
| 821 | ); |
| 822 | } |
| 823 | |
| 824 | const modelItems = (models: ReadonlyArray<ModelOption>) => |
| 825 | models.map((option, index) => ({ |
| 826 | kind: "model" as const, |
| 827 | key: `model:${option.key}`, |
| 828 | option, |
| 829 | isFirst: index === 0, |
| 830 | isLast: index === models.length - 1, |
| 831 | })); |
| 832 | |
| 833 | /** |
| 834 | * A provider whose models run on several backends, such as fx, lists each |
| 835 | * backend under its own collapsible heading; the thread's backend opens. |
| 836 | * Search and Favorites stay flat. |
| 837 | */ |
| 838 | function subProviderCatalogItems( |
| 839 | session: ThreadSettingsSessionValue, |
| 840 | group: ProviderGroup, |
| 841 | models: ReadonlyArray<ModelOption>, |
| 842 | ): ReadonlyArray<ThreadSettingsCatalogItem> | null { |
| 843 | if ( |
| 844 | !group.subProviders?.length || |
| 845 | session.searchQuery.trim().length > 0 || |
| 846 | session.providerFilter === FAVORITES_PROVIDER_FILTER |
| 847 | ) { |
| 848 | return null; |
| 849 | } |
| 850 | const { ungrouped, groups } = groupModelsBySubProvider( |
| 851 | models, |
| 852 | group.subProviders, |
| 853 | (option) => option.subtitle, |
| 854 | ); |
| 855 | return [ |
| 856 | ...modelItems(ungrouped), |
| 857 | ...groups.flatMap(({ subProvider, models: backendModels }) => { |
| 858 | const expansionKey = `${group.providerKey}:sub-provider:${subProvider.name}`; |
| 859 | const collapsed = |
| 860 | subProvider.unavailableReason !== undefined || |
| 861 | providerSectionIsCollapsed({ |
| 862 | defaultExpanded: backendModels.some(session.isApplied), |
| 863 | hasExpansionOverride: session.providerExpansionOverrides.has(expansionKey), |
| 864 | isNarrowed: false, |
| 865 | }); |
| 866 | return [ |
| 867 | { |
| 868 | kind: "subProvider" as const, |
| 869 | key: `sub-provider:${expansionKey}`, |
| 870 | expansionKey, |
| 871 | label: subProvider.name, |
| 872 | detail: subProvider.unavailableReason, |
| 873 | collapsed, |
| 874 | modelCount: backendModels.length, |
| 875 | }, |
| 876 | // The heading names the backend, so rows drop it. |
| 877 | ...(collapsed |
| 878 | ? [] |
| 879 | : modelItems(backendModels.map((option) => ({ ...option, subtitle: "" })))), |
| 880 | ]; |
| 881 | }), |
| 882 | ]; |
| 883 | } |
| 884 | |
| 885 | function buildThreadSettingsCatalogItems( |
| 886 | session: ThreadSettingsSessionValue, |
| 887 | resolve: MessageResolver, |
| 888 | locale: string, |
| 889 | ): ReadonlyArray<ThreadSettingsCatalogItem> { |
| 890 | return session.providerGroups.flatMap((group) => { |
| 891 | if ( |
| 892 | session.providerFilter !== null && |
| 893 | session.providerFilter !== FAVORITES_PROVIDER_FILTER && |
| 894 | group.providerKey !== session.providerFilter |
| 895 | ) { |
| 896 | return []; |
| 897 | } |
| 898 | const driver = group.models[0]?.providerDriver ?? group.providerKey; |
| 899 | const catalogModels = |
| 900 | session.manageHidden || |
| 901 | session.showLegacy || |
| 902 | session.providerFilter === FAVORITES_PROVIDER_FILTER |
| 903 | ? group.models |
| 904 | : group.models.filter( |
| 905 | (model) => |
| 906 | !model.isLegacy || session.isDisplayed(model) || session.favoriteKeys.has(model.key), |
| 907 | ); |
| 908 | const visibleModels = favoritesFirst( |
| 909 | catalogModels.filter( |
| 910 | (model) => |
| 911 | (session.providerFilter !== FAVORITES_PROVIDER_FILTER || |
| 912 | session.favoriteKeys.has(model.key)) && |
| 913 | modelMatchesCatalogQuery({ |
| 914 | model, |
| 915 | providerLabel: group.providerLabel, |
| 916 | query: session.searchQuery, |
| 917 | }), |
| 918 | ), |
| 919 | session.favoriteKeys, |
| 920 | ); |
| 921 | const updateRequiredNotice = |
| 922 | group.updateRequired && session.providerFilter !== FAVORITES_PROVIDER_FILTER |
| 923 | ? formatProviderUpdateRequiredNotice( |
| 924 | group.updateRequired, |
| 925 | session.searchQuery, |
| 926 | resolve, |
| 927 | locale, |
| 928 | ) |
| 929 | : null; |
| 930 | if (visibleModels.length === 0 && !updateRequiredNotice) { |
| 931 | return []; |
| 932 | } |
| 933 | const isPrimary = driver !== undefined && PRIMARY_PROVIDER_DRIVERS.has(driver); |
| 934 | const containsAppliedSelection = group.models.some(session.isApplied); |
| 935 | const isNarrowed = session.providerFilter !== null || session.searchQuery.trim().length > 0; |
| 936 | const collapsible = !isNarrowed; |
| 937 | const collapsed = providerSectionIsCollapsed({ |
| 938 | defaultExpanded: isPrimary || containsAppliedSelection, |
| 939 | hasExpansionOverride: session.providerExpansionOverrides.has(group.providerKey), |
| 940 | isNarrowed, |
| 941 | }); |
| 942 | const provider: ThreadSettingsProviderCatalog = { |
| 943 | key: group.providerKey, |
| 944 | driver, |
| 945 | iconUrl: group.models[0]?.providerIconUrl, |
| 946 | label: group.providerLabel, |
| 947 | collapsible, |
| 948 | collapsed, |
| 949 | modelCount: visibleModels.length, |
| 950 | models: collapsed ? [] : visibleModels, |
| 951 | }; |
| 952 | return [ |
| 953 | { |
| 954 | kind: "provider" as const, |
| 955 | key: `provider:${group.providerKey}`, |
| 956 | provider, |
| 957 | }, |
| 958 | ...((collapsed ? null : subProviderCatalogItems(session, group, provider.models)) ?? |
| 959 | modelItems(provider.models)), |
| 960 | ...(!collapsed && updateRequiredNotice |
| 961 | ? [ |
| 962 | { |
| 963 | kind: "notice" as const, |
| 964 | key: `notice:${group.providerKey}`, |
| 965 | text: updateRequiredNotice, |
| 966 | }, |
| 967 | ] |
| 968 | : []), |
| 969 | ]; |
| 970 | }); |
| 971 | } |
| 972 | |
| 973 | function ThreadSettingsOptionsItem(props: { |
| 974 | readonly animationsReady: boolean; |
| 975 | readonly bottomInset: number; |
| 976 | readonly onOpenSubmenu: (submenu: ThreadSettingsSubmenuPage) => void; |
| 977 | }) { |
| 978 | const insets = useSafeAreaInsets(); |
| 979 | const gt = useGT(); |
| 980 | const m = useMessages(); |
| 981 | const session = useThreadSettingsSession(); |
| 982 | const configs = useAtomValue(environmentServerConfigsAtom); |
| 983 | const selectedProvider = session.environmentId |
| 984 | ? (configs |
| 985 | .get(session.environmentId) |
| 986 | ?.providers.find((provider) => provider.instanceId === session.providerInstanceId) ?? null) |
| 987 | : null; |
| 988 | |
| 989 | return ( |
| 990 | <View style={{ paddingBottom: insets.bottom + props.bottomInset + 12 }}> |
| 991 | <ChatGptSharingStatus provider={selectedProvider} /> |
| 992 | <Text className="px-5 pb-2 pt-2 text-sm font-t3-medium text-foreground-muted"> |
| 993 | <T>Options</T> |
| 994 | </Text> |
| 995 | <Animated.View |
| 996 | className="mx-4 overflow-hidden rounded-2xl bg-grouped-card" |
| 997 | layout={THREAD_SETTINGS_OPTIONS_LAYOUT_TRANSITION} |
| 998 | > |
| 999 | {session.displayedDescriptors.map((descriptor) => { |
| 1000 | if (descriptor.type === "select") { |
| 1001 | return ( |
| 1002 | <Animated.View |
| 1003 | key={descriptor.id} |
| 1004 | entering={ |
| 1005 | props.animationsReady ? THREAD_SETTINGS_OPTION_ENTER_TRANSITION : undefined |
| 1006 | } |
| 1007 | exiting={props.animationsReady ? THREAD_SETTINGS_OPTION_EXIT_TRANSITION : undefined} |
| 1008 | layout={THREAD_SETTINGS_OPTIONS_LAYOUT_TRANSITION} |
| 1009 | > |
| 1010 | <DisclosureRow |
| 1011 | label={descriptor.label} |
| 1012 | value={ |
| 1013 | session.promptTraits.ultrathinkPromptControlled && |
| 1014 | descriptor.id === session.promptTraits.primarySelectDescriptor?.id |
| 1015 | ? "Ultrathink" |
| 1016 | : getProviderOptionCurrentLabel( |
| 1017 | descriptor, |
| 1018 | session.displayedModelSelection, |
| 1019 | session.reportedModelSelection, |
| 1020 | ) |
| 1021 | } |
| 1022 | onPress={() => props.onOpenSubmenu({ kind: "descriptor", id: descriptor.id })} |
| 1023 | /> |
| 1024 | </Animated.View> |
| 1025 | ); |
| 1026 | } |
| 1027 | return ( |
| 1028 | <Animated.View |
| 1029 | key={descriptor.id} |
| 1030 | entering={props.animationsReady ? THREAD_SETTINGS_OPTION_ENTER_TRANSITION : undefined} |
| 1031 | exiting={props.animationsReady ? THREAD_SETTINGS_OPTION_EXIT_TRANSITION : undefined} |
| 1032 | layout={THREAD_SETTINGS_OPTIONS_LAYOUT_TRANSITION} |
| 1033 | > |
| 1034 | <SwitchRow |
| 1035 | label={descriptor.label} |
| 1036 | value={descriptor.currentValue ?? false} |
| 1037 | onValueChange={(value) => session.applyOptionChange(descriptor.id, value)} |
| 1038 | /> |
| 1039 | </Animated.View> |
| 1040 | ); |
| 1041 | })} |
| 1042 | <Animated.View layout={THREAD_SETTINGS_OPTIONS_LAYOUT_TRANSITION}> |
| 1043 | <DisclosureRow |
| 1044 | isLast |
| 1045 | label={gt("Runtime", { $context: "agent permission mode setting" })} |
| 1046 | value={(() => { |
| 1047 | const label = session.runtimeModeChoices.find( |
| 1048 | (choice) => choice.mode === session.runtimeMode, |
| 1049 | )?.label; |
| 1050 | return label === undefined ? undefined : m(label); |
| 1051 | })()} |
| 1052 | onPress={() => props.onOpenSubmenu({ kind: "runtime" })} |
| 1053 | /> |
| 1054 | </Animated.View> |
| 1055 | </Animated.View> |
| 1056 | |
| 1057 | <Text className="px-5 pb-2 pt-7 text-sm font-t3-medium text-foreground-muted"> |
| 1058 | {gt("Catalog", { $context: "section heading for the model catalog" })} |
| 1059 | </Text> |
| 1060 | <View className="mx-4 overflow-hidden rounded-2xl bg-grouped-card"> |
| 1061 | <SwitchRow |
| 1062 | label={gt("Manage hidden models")} |
| 1063 | value={session.manageHidden} |
| 1064 | onValueChange={session.setManageHidden} |
| 1065 | isLast |
| 1066 | /> |
| 1067 | </View> |
| 1068 | </View> |
| 1069 | ); |
| 1070 | } |
| 1071 | |
| 1072 | function ThreadSettingsMainContent(props: { |
| 1073 | readonly bottomInset: number; |
| 1074 | readonly onOpenSubmenu: (submenu: ThreadSettingsSubmenuPage) => void; |
| 1075 | }) { |
| 1076 | const gt = useGT(); |
| 1077 | const m = useMessages(); |
| 1078 | const locale = useLocale(); |
| 1079 | const session = useThreadSettingsSession(); |
| 1080 | const refreshProvidersCommand = useAtomCommand(serverEnvironment.refreshProviders, { |
| 1081 | reportFailure: false, |
| 1082 | }); |
| 1083 | const refreshProviderCatalog = createProviderCatalogRefreshRunner(refreshProvidersCommand); |
| 1084 | const registry = use(RegistryContext); |
| 1085 | const refreshModelCatalog = useEffectEvent(() => { |
| 1086 | const environmentId = session.environmentId; |
| 1087 | if (!environmentId) return; |
| 1088 | // An older server drops the field and probes every provider. |
| 1089 | const config = registry.get(environmentServerConfigsAtom).get(environmentId); |
| 1090 | if (config?.environment.capabilities.modelCatalogRefresh !== true) return; |
| 1091 | void refreshProvidersCommand({ environmentId, input: { modelCatalogOnly: true } }); |
| 1092 | }); |
| 1093 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- asks the server for newly released models when the model list opens |
| 1094 | useEffect(() => { |
| 1095 | refreshModelCatalog(); |
| 1096 | }, []); |
| 1097 | const [isRefreshingProviders, setIsRefreshingProviders] = useState(false); |
| 1098 | const refreshProviders = () => { |
| 1099 | if (!session.environmentId || isRefreshingProviders) return; |
| 1100 | setIsRefreshingProviders(true); |
| 1101 | const environmentId = session.environmentId; |
| 1102 | const workspaceScan = session.workspaceScan; |
| 1103 | void refreshProviderCatalog(environmentId) |
| 1104 | .then(async (result) => { |
| 1105 | // A project's own models are read per folder, so the machine refresh alone keeps them stale. |
| 1106 | // A failed folder read keeps its previous models and retries, so only the machine result alerts. |
| 1107 | if (result._tag === "Success" && workspaceScan) { |
| 1108 | await refreshProvidersCommand({ |
| 1109 | environmentId, |
| 1110 | input: { ...workspaceScan, fresh: true }, |
| 1111 | }); |
| 1112 | } |
| 1113 | return result; |
| 1114 | }) |
| 1115 | .then((result) => { |
| 1116 | setIsRefreshingProviders(false); |
| 1117 | const error = providerCatalogRefreshError(result); |
| 1118 | if (error) Dialog.alert(gt("Could not refresh models"), error); |
| 1119 | }); |
| 1120 | }; |
| 1121 | const [listLoaded, setListLoaded] = useState(false); |
| 1122 | // Android can drop the first frame of a reduced-motion fade, leaving rows invisible. |
| 1123 | const reducedMotion = useReducedMotion(); |
| 1124 | const reduceMotionEnabled = useReduceMotionEnabled(); |
| 1125 | const animationsReady = listLoaded && !reducedMotion && !reduceMotionEnabled; |
| 1126 | const catalogItems = buildThreadSettingsCatalogItems(session, m, locale); |
| 1127 | const hasActiveCatalogFilter = |
| 1128 | session.providerFilter !== null || session.searchQuery.trim().length > 0; |
| 1129 | const listItems = [ |
| 1130 | ...(catalogItems.length === 0 ? ([{ kind: "empty", key: "empty" }] as const) : catalogItems), |
| 1131 | { kind: "options", key: "options" }, |
| 1132 | ] satisfies ReadonlyArray<ThreadSettingsCatalogItem>; |
| 1133 | const renderCatalogItem = (itemProps: LegendListRenderItemProps<ThreadSettingsCatalogItem>) => { |
| 1134 | const item = itemProps.item; |
| 1135 | let content: ReactNode; |
| 1136 | |
| 1137 | if (item.kind === "provider") { |
| 1138 | content = <ThreadSettingsProviderListHeader provider={item.provider} />; |
| 1139 | } else if (item.kind === "subProvider") { |
| 1140 | content = <ThreadSettingsSubProviderListHeader item={item} />; |
| 1141 | } else if (item.kind === "model") { |
| 1142 | content = ( |
| 1143 | <ThreadSettingsModelListRow |
| 1144 | isFirst={item.isFirst} |
| 1145 | isLast={item.isLast} |
| 1146 | option={item.option} |
| 1147 | /> |
| 1148 | ); |
| 1149 | } else if (item.kind === "notice") { |
| 1150 | content = <Text className="mx-8 mt-2 text-xs text-foreground-muted">{item.text}</Text>; |
| 1151 | } else if (item.kind === "empty") { |
| 1152 | content = ( |
| 1153 | <View className="items-center px-8 py-14"> |
| 1154 | <Text className="text-center text-sm text-foreground-muted"> |
| 1155 | {session.providerFilter === FAVORITES_PROVIDER_FILTER && |
| 1156 | session.searchQuery.trim().length === 0 |
| 1157 | ? gt("No favorite models") |
| 1158 | : hasActiveCatalogFilter |
| 1159 | ? gt("No matching models") |
| 1160 | : gt("No available models")} |
| 1161 | </Text> |
| 1162 | </View> |
| 1163 | ); |
| 1164 | } else { |
| 1165 | content = ( |
| 1166 | <ThreadSettingsOptionsItem |
| 1167 | animationsReady={animationsReady} |
| 1168 | bottomInset={props.bottomInset} |
| 1169 | onOpenSubmenu={props.onOpenSubmenu} |
| 1170 | /> |
| 1171 | ); |
| 1172 | } |
| 1173 | |
| 1174 | return ( |
| 1175 | <Animated.View |
| 1176 | key={item.key} |
| 1177 | entering={animationsReady ? THREAD_SETTINGS_CATALOG_ENTER_TRANSITION : undefined} |
| 1178 | exiting={animationsReady ? THREAD_SETTINGS_CATALOG_EXIT_TRANSITION : undefined} |
| 1179 | > |
| 1180 | {content} |
| 1181 | </Animated.View> |
| 1182 | ); |
| 1183 | }; |
| 1184 | |
| 1185 | return ( |
| 1186 | // oxlint-disable-next-line t3code/require-registered-list-scroll -- Sheet content; sheets sit outside workspace columns and keep their own header handling. |
| 1187 | <AnimatedLegendList |
| 1188 | alwaysBounceVertical |
| 1189 | automaticallyAdjustsScrollIndicatorInsets |
| 1190 | className="flex-1 bg-sheet" |
| 1191 | style={READABLE_WIDTH_STYLE} |
| 1192 | contentContainerStyle={{ paddingTop: 4 }} |
| 1193 | contentInsetAdjustmentBehavior="automatic" |
| 1194 | data={listItems} |
| 1195 | estimatedItemSize={ROW_MIN_HEIGHT.item} |
| 1196 | extraData={animationsReady} |
| 1197 | getItemType={(item) => item.kind} |
| 1198 | itemLayoutAnimation={THREAD_SETTINGS_CATALOG_LAYOUT_TRANSITION} |
| 1199 | keyExtractor={(item) => item.key} |
| 1200 | keyboardDismissMode="on-drag" |
| 1201 | keyboardShouldPersistTaps="handled" |
| 1202 | maintainVisibleContentPosition={THREAD_SETTINGS_MAINTAIN_VISIBLE_CONTENT_POSITION} |
| 1203 | recycleItems |
| 1204 | refreshControl={ |
| 1205 | session.environmentId ? ( |
| 1206 | <RefreshControl refreshing={isRefreshingProviders} onRefresh={refreshProviders} /> |
| 1207 | ) : undefined |
| 1208 | } |
| 1209 | onLoad={() => setListLoaded(true)} |
| 1210 | renderItem={renderCatalogItem} |
| 1211 | showsVerticalScrollIndicator={false} |
| 1212 | /> |
| 1213 | ); |
| 1214 | } |
| 1215 | |
| 1216 | function ThreadSettingsChoiceContent(props: { |
| 1217 | readonly submenu: ThreadSettingsSubmenuPage; |
| 1218 | readonly onSelected: () => void; |
| 1219 | }) { |
| 1220 | const insets = useSafeAreaInsets(); |
| 1221 | const gt = useGT(); |
| 1222 | const m = useMessages(); |
| 1223 | const session = useThreadSettingsSession(); |
| 1224 | const descriptorId = props.submenu.kind === "descriptor" ? props.submenu.id : null; |
| 1225 | |
| 1226 | const activeDescriptor = |
| 1227 | descriptorId !== null |
| 1228 | ? session.displayedDescriptors.find( |
| 1229 | (descriptor) => descriptor.type === "select" && descriptor.id === descriptorId, |
| 1230 | ) |
| 1231 | : undefined; |
| 1232 | |
| 1233 | const submenuContent = |
| 1234 | props.submenu.kind === "runtime" |
| 1235 | ? { |
| 1236 | rows: session.runtimeModeChoices.map((choice) => ({ |
| 1237 | id: choice.mode, |
| 1238 | label: m(choice.label), |
| 1239 | description: choice.disabledReason ?? m(choice.description), |
| 1240 | disabled: choice.disabledReason !== undefined, |
| 1241 | selected: choice.mode === session.runtimeMode, |
| 1242 | onPress: () => { |
| 1243 | void Haptics.selectionAsync(); |
| 1244 | session.onUpdateRuntimeMode(choice.mode); |
| 1245 | props.onSelected(); |
| 1246 | }, |
| 1247 | })), |
| 1248 | } |
| 1249 | : activeDescriptor?.type === "select" |
| 1250 | ? { |
| 1251 | rows: selectableChoices(activeDescriptor).map((choice) => ({ |
| 1252 | id: choice.id, |
| 1253 | label: choice.label, |
| 1254 | description: choice.description, |
| 1255 | disabled: false, |
| 1256 | selected: |
| 1257 | choice.id === |
| 1258 | (session.promptTraits.ultrathinkPromptControlled && |
| 1259 | activeDescriptor.id === session.promptTraits.primarySelectDescriptor?.id |
| 1260 | ? "ultrathink" |
| 1261 | : getProviderOptionCurrentValue( |
| 1262 | activeDescriptor, |
| 1263 | session.displayedModelSelection, |
| 1264 | session.reportedModelSelection, |
| 1265 | )), |
| 1266 | onPress: () => { |
| 1267 | void Haptics.selectionAsync(); |
| 1268 | if ( |
| 1269 | session.promptTraits.ultrathinkInBodyText && |
| 1270 | activeDescriptor.id === session.promptTraits.primarySelectDescriptor?.id |
| 1271 | ) { |
| 1272 | Dialog.alert( |
| 1273 | gt("Reasoning controlled by prompt"), |
| 1274 | gt( |
| 1275 | 'Your prompt contains "ultrathink" in the text. Remove it to change this option.', |
| 1276 | ), |
| 1277 | ); |
| 1278 | return; |
| 1279 | } |
| 1280 | session.applyOptionChange(activeDescriptor.id, choice.id); |
| 1281 | props.onSelected(); |
| 1282 | }, |
| 1283 | })), |
| 1284 | } |
| 1285 | : null; |
| 1286 | |
| 1287 | if (!submenuContent) { |
| 1288 | return <View className="flex-1 bg-sheet" />; |
| 1289 | } |
| 1290 | |
| 1291 | return ( |
| 1292 | <ScrollView |
| 1293 | className="flex-1 bg-sheet" |
| 1294 | style={READABLE_WIDTH_STYLE} |
| 1295 | contentContainerStyle={{ |
| 1296 | paddingBottom: insets.bottom + 12, |
| 1297 | paddingHorizontal: 16, |
| 1298 | paddingTop: 16, |
| 1299 | }} |
| 1300 | contentInsetAdjustmentBehavior="automatic" |
| 1301 | showsVerticalScrollIndicator={false} |
| 1302 | > |
| 1303 | <View className="overflow-hidden rounded-2xl bg-grouped-card"> |
| 1304 | {submenuContent.rows.map((row, index) => ( |
| 1305 | <ChoiceRow |
| 1306 | key={row.id} |
| 1307 | description={row.description} |
| 1308 | isLast={index === submenuContent.rows.length - 1} |
| 1309 | label={row.label} |
| 1310 | selected={row.selected} |
| 1311 | disabled={row.disabled} |
| 1312 | onPress={row.onPress} |
| 1313 | /> |
| 1314 | ))} |
| 1315 | </View> |
| 1316 | </ScrollView> |
| 1317 | ); |
| 1318 | } |
| 1319 | |
| 1320 | type ThreadSettingsPickerStackParams = { |
| 1321 | ThreadSettingsModels: undefined; |
| 1322 | ThreadSettingsChoice: ThreadSettingsSubmenuPage & { readonly title: string }; |
| 1323 | }; |
| 1324 | |
| 1325 | type ThreadSettingsPickerPresentation = { |
| 1326 | readonly onClose: () => void; |
| 1327 | }; |
| 1328 | |
| 1329 | const ThreadSettingsPickerStack = createNativeStackNavigator<ThreadSettingsPickerStackParams>(); |
| 1330 | const ThreadSettingsPickerPresentationContext = |
| 1331 | createContext<ThreadSettingsPickerPresentation | null>(null); |
| 1332 | |
| 1333 | function useThreadSettingsPickerPresentation() { |
| 1334 | const value = use(ThreadSettingsPickerPresentationContext); |
| 1335 | if (!value) { |
| 1336 | throw new Error( |
| 1337 | "useThreadSettingsPickerPresentation must be used inside ThreadSettingsPickerNavigator.", |
| 1338 | ); |
| 1339 | } |
| 1340 | return value; |
| 1341 | } |
| 1342 | |
| 1343 | function ThreadSettingsModelsScreen() { |
| 1344 | const gt = useGT(); |
| 1345 | const session = useThreadSettingsSession(); |
| 1346 | const presentation = useThreadSettingsPickerPresentation(); |
| 1347 | const navigation = useNavigation<NativeStackNavigationProp<ThreadSettingsPickerStackParams>>(); |
| 1348 | const hasCustomCatalogFilter = session.providerFilter !== null || session.showLegacy; |
| 1349 | const commitAndClose = useEffectEvent(() => { |
| 1350 | if (!session.commitPendingModel()) return; |
| 1351 | presentation.onClose(); |
| 1352 | }); |
| 1353 | const search: AppBarSearch = { |
| 1354 | value: session.searchQuery, |
| 1355 | onChangeText: session.setSearchQuery, |
| 1356 | placeholder: gt("Find a model"), |
| 1357 | clearAccessibilityLabel: gt("Clear model search"), |
| 1358 | mode: "inline", |
| 1359 | compactToolbar: true, |
| 1360 | }; |
| 1361 | const searchToolbarInset = useSearchToolbarInset(search); |
| 1362 | const providerFilters = [ |
| 1363 | { id: "all-providers", title: gt("All providers"), value: null }, |
| 1364 | { id: "favorites", title: gt("Favorites"), value: FAVORITES_PROVIDER_FILTER }, |
| 1365 | ...session.providerGroups.map((group) => ({ |
| 1366 | id: `provider:${group.providerKey}`, |
| 1367 | title: group.providerLabel, |
| 1368 | value: group.providerKey, |
| 1369 | })), |
| 1370 | ]; |
| 1371 | |
| 1372 | return ( |
| 1373 | <> |
| 1374 | <AppBar |
| 1375 | title={gt("Thread settings")} |
| 1376 | onClose={presentation.onClose} |
| 1377 | closeAccessibilityLabel={gt("Cancel thread settings")} |
| 1378 | search={search} |
| 1379 | menus={[ |
| 1380 | { |
| 1381 | title: gt("Model filters"), |
| 1382 | icon: hasCustomCatalogFilter |
| 1383 | ? "line.3.horizontal.decrease.circle.fill" |
| 1384 | : "line.3.horizontal.decrease", |
| 1385 | items: [ |
| 1386 | { |
| 1387 | id: "provider", |
| 1388 | title: gt("Provider"), |
| 1389 | items: providerFilters.map((filter) => ({ |
| 1390 | id: filter.id, |
| 1391 | title: filter.title, |
| 1392 | selected: session.providerFilter === filter.value, |
| 1393 | onPress: () => session.setProviderFilter(filter.value), |
| 1394 | })), |
| 1395 | }, |
| 1396 | ...(session.hasLegacyModels |
| 1397 | ? [ |
| 1398 | { |
| 1399 | id: "show-legacy", |
| 1400 | title: gt("Show legacy models"), |
| 1401 | selected: session.showLegacy, |
| 1402 | onPress: () => session.setShowLegacy(!session.showLegacy), |
| 1403 | }, |
| 1404 | ] |
| 1405 | : []), |
| 1406 | ], |
| 1407 | }, |
| 1408 | ]} |
| 1409 | optionsVersion={[ |
| 1410 | session.providerFilter, |
| 1411 | session.providerGroups.map((group) => group.providerKey), |
| 1412 | session.showLegacy, |
| 1413 | session.hasLegacyModels, |
| 1414 | ]} |
| 1415 | confirm={{ |
| 1416 | label: session.pendingModel |
| 1417 | ? gt("Save", { $context: "verb, button" }) |
| 1418 | : gt("Done", { $context: "button that closes the sheet" }), |
| 1419 | onPress: commitAndClose, |
| 1420 | }} |
| 1421 | hideBottomBorder |
| 1422 | /> |
| 1423 | <ScreenContent> |
| 1424 | <ThreadSettingsMainContent |
| 1425 | bottomInset={searchToolbarInset} |
| 1426 | onOpenSubmenu={(submenu) => { |
| 1427 | const title = |
| 1428 | submenu.kind === "runtime" |
| 1429 | ? gt("Runtime", { $context: "agent permission mode setting" }) |
| 1430 | : (session.displayedDescriptors.find( |
| 1431 | (descriptor) => descriptor.type === "select" && descriptor.id === submenu.id, |
| 1432 | )?.label ?? gt("Option")); |
| 1433 | navigation.navigate("ThreadSettingsChoice", { ...submenu, title }); |
| 1434 | }} |
| 1435 | /> |
| 1436 | </ScreenContent> |
| 1437 | </> |
| 1438 | ); |
| 1439 | } |
| 1440 | |
| 1441 | function ThreadSettingsChoiceScreen() { |
| 1442 | const navigation = useNavigation<NativeStackNavigationProp<ThreadSettingsPickerStackParams>>(); |
| 1443 | const route = useRoute<RouteProp<ThreadSettingsPickerStackParams, "ThreadSettingsChoice">>(); |
| 1444 | |
| 1445 | return ( |
| 1446 | <> |
| 1447 | <AppBar title={route.params.title} onBack={() => navigation.goBack()} hideBottomBorder /> |
| 1448 | <ScreenContent> |
| 1449 | <ThreadSettingsChoiceContent |
| 1450 | submenu={route.params} |
| 1451 | onSelected={() => navigation.goBack()} |
| 1452 | /> |
| 1453 | </ScreenContent> |
| 1454 | </> |
| 1455 | ); |
| 1456 | } |
| 1457 | |
| 1458 | function ThreadSettingsPickerNavigator(props: ThreadSettingsPickerPresentation) { |
| 1459 | const screenOptions = useSheetStackOptions(); |
| 1460 | const gt = useGT(); |
| 1461 | const presentation = { |
| 1462 | onClose: props.onClose, |
| 1463 | }; |
| 1464 | |
| 1465 | return ( |
| 1466 | <ThreadSettingsPickerPresentationContext.Provider value={presentation}> |
| 1467 | <ThreadSettingsPickerStack.Navigator |
| 1468 | initialRouteName="ThreadSettingsModels" |
| 1469 | screenOptions={screenOptions} |
| 1470 | > |
| 1471 | <ThreadSettingsPickerStack.Screen |
| 1472 | name="ThreadSettingsModels" |
| 1473 | component={ThreadSettingsModelsScreen} |
| 1474 | options={{ headerBackVisible: false, title: gt("Thread settings") }} |
| 1475 | /> |
| 1476 | <ThreadSettingsPickerStack.Screen |
| 1477 | name="ThreadSettingsChoice" |
| 1478 | component={ThreadSettingsChoiceScreen} |
| 1479 | options={({ route }) => ({ title: route.params.title })} |
| 1480 | /> |
| 1481 | </ThreadSettingsPickerStack.Navigator> |
| 1482 | </ThreadSettingsPickerPresentationContext.Provider> |
| 1483 | ); |
| 1484 | } |
| 1485 | |
| 1486 | export function ThreadSettingsPickerScreen( |
| 1487 | props: ThreadSettingsSessionProps & { readonly onClose: () => void }, |
| 1488 | ) { |
| 1489 | return ( |
| 1490 | <ThreadSettingsSessionProvider {...props}> |
| 1491 | <ThreadSettingsPickerNavigator onClose={props.onClose} /> |
| 1492 | </ThreadSettingsSessionProvider> |
| 1493 | ); |
| 1494 | } |
| 1495 | |
| 1496 | export function ExistingThreadSettingsRouteScreen({ |
| 1497 | route, |
| 1498 | }: StaticScreenProps<ExistingThreadSettingsRouteParams>) { |
| 1499 | const navigation = useNavigation<NativeStackNavigationProp<Record<string, object | undefined>>>(); |
| 1500 | // Reads the same environmentId/threadId params as the Thread route beneath it. |
| 1501 | const { selectedThread, selectedThreadDetailRef, selectedEnvironmentRuntime } = |
| 1502 | useThreadSelection(); |
| 1503 | const { selectedThreadCwd } = useSelectedThreadWorktree(); |
| 1504 | // Streamed text would otherwise re-render the whole model picker on every delta. |
| 1505 | const structure = useQuietThreadStructure(selectedThreadDetailRef); |
| 1506 | const reportedModelSelection = useThreadReportedModelSelection(selectedThreadDetailRef); |
| 1507 | const threadKey = scopedThreadKey(route.params.environmentId, route.params.threadId); |
| 1508 | const draftSettings = useComposerDraftSettings(threadKey); |
| 1509 | const queuedRunEdit = useQueuedRunEdit(threadKey); |
| 1510 | // A queued edit can end while the sheet is open; the prompt then belongs to the thread's draft. |
| 1511 | const draftKey = activeComposerDraftKey(threadKey, route.params.draftKey, queuedRunEdit); |
| 1512 | const prompt = useComposerDraft(draftKey).text; |
| 1513 | |
| 1514 | if (!selectedThread) { |
| 1515 | return <View className="flex-1 bg-sheet" />; |
| 1516 | } |
| 1517 | |
| 1518 | const serverConfig = serverConfigForCwd( |
| 1519 | selectedEnvironmentRuntime?.serverConfig ?? null, |
| 1520 | selectedThreadCwd, |
| 1521 | ); |
| 1522 | const modelSelection = draftSettings.modelSelection ?? selectedThread.modelSelection; |
| 1523 | const lockedProviderInstanceId = threadAllowsProviderSwitch({ |
| 1524 | thread: selectedThread, |
| 1525 | projection: structure?.projection, |
| 1526 | }) |
| 1527 | ? undefined |
| 1528 | : modelSelection.instanceId; |
| 1529 | const modelOptions = buildModelOptions( |
| 1530 | serverConfig, |
| 1531 | modelSelection, |
| 1532 | lockedProviderInstanceId, |
| 1533 | selectedThread.projectId, |
| 1534 | ); |
| 1535 | const currentModelOption = |
| 1536 | modelOptions.find( |
| 1537 | (option) => |
| 1538 | option.selection.instanceId === modelSelection.instanceId && |
| 1539 | option.selection.model === modelSelection.model, |
| 1540 | ) ?? null; |
| 1541 | const updateModelSelection = (selection: ModelSelection) => |
| 1542 | selectThreadModel(route.params, selection); |
| 1543 | |
| 1544 | return ( |
| 1545 | <ThreadSettingsPickerScreen |
| 1546 | environmentId={selectedThread.environmentId} |
| 1547 | projectId={selectedThread.projectId} |
| 1548 | cwd={selectedThreadCwd} |
| 1549 | providerInstanceId={modelSelection.instanceId} |
| 1550 | {...(lockedProviderInstanceId ? { lockedProviderInstanceId } : {})} |
| 1551 | providerGroups={groupByProvider(modelOptions)} |
| 1552 | selectedModel={modelSelection} |
| 1553 | prompt={prompt} |
| 1554 | onPromptChange={(text) => setComposerDraftText(draftKey, text)} |
| 1555 | reportedModelSelection={reportedModelSelection} |
| 1556 | onSelectModel={(option) => |
| 1557 | updateModelSelection( |
| 1558 | withStoredThreadModelOptions( |
| 1559 | withRememberedModelOptions(option.selection), |
| 1560 | selectedThread.modelSelection, |
| 1561 | ), |
| 1562 | ) |
| 1563 | } |
| 1564 | restoreSelection={withRememberedModelOptions} |
| 1565 | optionDescriptors={resolveProviderOptionDescriptors({ |
| 1566 | capabilities: currentModelOption?.capabilities, |
| 1567 | selections: modelSelection.options, |
| 1568 | })} |
| 1569 | onUpdateOptionSelections={(options) => { |
| 1570 | rememberModelOptions(modelSelection.instanceId, modelSelection.model, options ?? []); |
| 1571 | updateModelSelection({ ...modelSelection, options }); |
| 1572 | }} |
| 1573 | runtimeMode={draftSettings.runtimeMode ?? selectedThread.runtimeMode} |
| 1574 | onUpdateRuntimeMode={(runtimeMode) => updateComposerDraftSettings(threadKey, { runtimeMode })} |
| 1575 | onClose={() => navigation.goBack()} |
| 1576 | /> |
| 1577 | ); |
| 1578 | } |
| 1579 | |
| 1580 | /** RNS owns nested sheet dismissal; Reasoning and Runtime remain ordinary pushes. */ |
| 1581 | export function NewTaskThreadSettingsRouteScreen() { |
| 1582 | const flow = useNewTaskFlow(); |
| 1583 | const navigation = useNavigation<NativeStackNavigationProp<Record<string, object | undefined>>>(); |
| 1584 | const optionDescriptors = resolveProviderOptionDescriptors({ |
| 1585 | capabilities: flow.selectedModelOption?.capabilities, |
| 1586 | selections: flow.selectedModel?.options, |
| 1587 | }); |
| 1588 | |
| 1589 | return ( |
| 1590 | <ThreadSettingsPickerScreen |
| 1591 | environmentId={flow.selectedEnvironmentId} |
| 1592 | projectId={flow.selectedProject?.id ?? null} |
| 1593 | cwd={flow.workspaceCwd} |
| 1594 | {...(flow.selectedModel ? { providerInstanceId: flow.selectedModel.instanceId } : {})} |
| 1595 | providerGroups={flow.providerGroups} |
| 1596 | selectedModel={flow.selectedModel} |
| 1597 | prompt={flow.prompt} |
| 1598 | onPromptChange={flow.setPrompt} |
| 1599 | onSelectModel={(option) => flow.setSelectedModelKey(option.key, option.selection.options)} |
| 1600 | restoreSelection={withRememberedModelOptions} |
| 1601 | optionDescriptors={optionDescriptors} |
| 1602 | onUpdateOptionSelections={flow.setSelectedModelOptions} |
| 1603 | runtimeMode={flow.runtimeMode} |
| 1604 | onUpdateRuntimeMode={flow.setRuntimeMode} |
| 1605 | onClose={() => navigation.goBack()} |
| 1606 | /> |
| 1607 | ); |
| 1608 | } |