Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadSettingsSheet.tsx

1,421 lines48.7 KB

1import type {
2 EnvironmentId,
3 ModelSelection,
4 ProviderInstanceId,
5 ProviderOptionDescriptor,
6 ProviderOptionSelection,
7 RuntimeMode,
8} from "@t3tools/contracts";
9import type { LegendListRenderItemProps } from "@legendapp/list/react-native";
10import { useAtomSet, useAtomValue } from "@effect/atom-react";
11import { AnimatedLegendList } from "@legendapp/list/reanimated";
12import {
13 getProviderOptionCurrentLabel,
14 getProviderOptionCurrentValue,
15 getProviderOptionDescriptors,
16} from "@t3tools/shared/model";
17import { useNavigation, useRoute, type RouteProp } from "@react-navigation/native";
18import {
19 createNativeStackNavigator,
20 type NativeStackNavigationProp,
21} from "@react-navigation/native-stack";
22import * as Haptics from "expo-haptics";
23import { AsyncResult } from "effect/unstable/reactivity";
24import {
25 createContext,
26 use,
27 useCallback,
28 useEffect,
29 useMemo,
30 useState,
31 type ReactNode,
32} from "react";
33import {
34 Alert,
35 Platform,
36 Pressable,
37 RefreshControl,
38 ScrollView,
39 TextInput,
40 View,
41} from "react-native";
42import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
43import { useSafeAreaInsets } from "react-native-safe-area-context";
44​
45import { SymbolView } from "../../components/AppSymbol";
46import { AppText as Text } from "../../components/AppText";
47import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
48import { AndroidAnchoredMenu } from "../../components/AndroidAnchoredMenu";
49import { MaterialButton } from "../../components/MaterialButton";
50import { MaterialIconButton } from "../../components/MaterialIconButton";
51import { ProviderIcon } from "../../components/ProviderIcon";
52import { ThemedSwitch } from "../../components/ThemedSwitch";
53import { cn } from "../../lib/cn";
54import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
55import { applyProviderOptionSelection } from "../../lib/providerOptions";
56import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
57import { useUniwindTheme } from "../../lib/useUniwindTheme";
58import { rememberModelOptions } from "../../state/use-model-option-memory";
59import {
60 NativeHeaderToolbar,
61 NativeStackScreenOptions,
62 nativeHeaderScrollEdgeEffects,
63} from "../../native/StackHeader";
64import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
65import { serverEnvironment } from "../../state/server";
66import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
67import { useAtomCommand } from "../../state/use-atom-command";
68import { useNewTaskFlow } from "./new-task-flow-provider";
69import { MaterialScreenContent } from "../../components/MaterialScreenContent";
70import {
71 createProviderCatalogRefreshRunner,
72 providerCatalogRefreshError,
73} from "./provider-catalog-refresh";
74import {
75 createNativeMailSearchToolbarItem,
76 NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET,
77 NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED,
78} from "../layout/native-mail-search-toolbar";
79import { ModelRow, ChoiceRow } from "./ThreadSettingsRows";
80import {
81 compatibleRuntimeModeForChoices,
82 runtimeModeChoicesForSupportedModes,
83 selectableChoices,
84} from "./thread-settings-options";
85import {
86 canCommitPendingModel,
87 favoritesFirst,
88 modelFavoriteKey,
89 modelMatchesCatalogQuery,
90 pendingModelAfterPress,
91 providerSectionIsCollapsed,
92 toggleModelFavorite,
93} from "./thread-settings-sheet-state";
94​
95/**
96 * Everyday harnesses start expanded; every other provider (OpenRouter catalogs
97 * and friends) starts folded so a 300-model catalog cannot bury the list. All
98 * provider headers remain user-collapsible.
99 */
100const PRIMARY_PROVIDER_DRIVERS: ReadonlySet<string> = new Set([
101 "claudeAgent",
102 "codex",
103 "antigravity",
104]);
105/**
106 * Keep measured row changes stable, but let catalog mutations use the list's
107 * native bounds so a filtered catalog that underflows returns to the top.
108 */
109const THREAD_SETTINGS_MAINTAIN_VISIBLE_CONTENT_POSITION = {
110 data: false,
111 size: true,
112} as const;
113const THREAD_SETTINGS_CATALOG_LAYOUT_TRANSITION = LinearTransition.duration(180);
114const THREAD_SETTINGS_CATALOG_ENTER_TRANSITION = FadeIn.duration(140);
115const THREAD_SETTINGS_CATALOG_EXIT_TRANSITION = FadeOut.duration(120);
116const THREAD_SETTINGS_OPTIONS_LAYOUT_TRANSITION = LinearTransition.duration(180);
117const THREAD_SETTINGS_OPTION_ENTER_TRANSITION = FadeIn.duration(140);
118const THREAD_SETTINGS_OPTION_EXIT_TRANSITION = FadeOut.duration(100);
119const THREAD_SETTINGS_HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(
120 Platform.OS,
121 Platform.Version,
122);
123const EMPTY_MODEL_FAVORITES: ReadonlyArray<{
124 readonly provider: ProviderInstanceId;
125 readonly model: string;
126}> = [];
127const FAVORITES_PROVIDER_FILTER = "@favorites";
128/** Provider catalog header with its harness logo and disclosure state. */
129function ProviderHeader(props: {
130 readonly driver: string | undefined;
131 readonly iconUrl: string | undefined;
132 readonly label: string;
133 readonly collapsible: boolean;
134 readonly collapsed: boolean;
135 readonly modelCount: number;
136 readonly onToggle: () => void;
137}) {
138 const content = (
139 <>
140 <ProviderIcon iconUrl={props.iconUrl} provider={props.driver} size={15} />
141 <Text className="text-sm font-t3-medium text-foreground-muted">{props.label}</Text>
142 {props.collapsible ? (
143 <>
144 <View className="flex-1" />
145 {props.collapsed ? (
146 <Text className="text-2xs font-t3-medium text-foreground-muted">
147 {props.modelCount}
148 </Text>
149 ) : null}
150 <SymbolView
151 name={props.collapsed ? "chevron.down" : "chevron.up"}
152 size={12}
153 tintColorClassName="accent-icon-subtle"
154 type="monochrome"
155 />
156 </>
157 ) : null}
158 </>
159 );
160​
161 if (props.collapsible) {
162 return (
163 <Pressable
164 accessibilityLabel={`${props.label}, ${props.modelCount} models`}
165 accessibilityRole="button"
166 accessibilityState={{ expanded: !props.collapsed }}
167 className="mx-4 mt-1 min-h-11 flex-row items-center gap-2 rounded-xl px-1 pt-2 active:opacity-60"
168 onPress={props.onToggle}
169 style={Platform.OS === "android" ? { minHeight: 48 } : undefined}
170 >
171 {content}
172 </Pressable>
173 );
174 }
175​
176 return (
177 <View accessibilityRole="header" className="mx-4 min-h-9 flex-row items-center gap-2 px-1 pt-1">
178 {content}
179 </View>
180 );
182​
183/** Compact row that opens a single-choice submenu panel. */
184function DisclosureRow(props: {
185 readonly label: string;
186 readonly value: string | undefined;
187 readonly onPress: () => void;
188 readonly isLast?: boolean;
189}) {
190 return (
191 <Pressable
192 accessibilityRole="button"
193 onPress={props.onPress}
194 style={Platform.OS === "android" ? { minHeight: 56 } : undefined}
195 className={cn(
196 "min-h-11 flex-row items-center gap-2 bg-card px-4 py-2 active:bg-subtle",
197 !props.isLast && "border-b border-border-subtle",
198 )}
199 >
200 <Text className="text-sm font-t3-medium text-foreground">{props.label}</Text>
201 <View className="flex-1" />
202 {props.value ? (
203 <Text className="text-sm text-foreground-muted" numberOfLines={1}>
204 {props.value}
205 </Text>
206 ) : null}
207 <SymbolView
208 name="chevron.right"
209 size={12}
210 tintColorClassName="accent-icon-subtle"
211 type="monochrome"
212 />
213 </Pressable>
214 );
216​
217function SwitchRow(props: {
218 readonly label: string;
219 readonly value: boolean;
220 readonly onValueChange: (value: boolean) => void;
221 readonly isLast?: boolean;
222}) {
223 return (
224 <View
225 className={cn(
226 "min-h-11 flex-row items-center justify-between bg-card px-4 py-1",
227 !props.isLast && "border-b border-border-subtle",
228 )}
229 >
230 <Text className="text-sm font-t3-medium text-foreground">{props.label}</Text>
231 <ThemedSwitch
232 accessibilityLabel={props.label}
233 onValueChange={props.onValueChange}
234 value={props.value}
235 />
236 </View>
237 );
239​
240type ThreadSettingsSubmenuPage =
241 | { readonly kind: "descriptor"; readonly id: string }
242 | { readonly kind: "runtime" };
243​
244type ThreadSettingsSessionProps = {
245 readonly environmentId: EnvironmentId | null;
246 readonly providerInstanceId?: ProviderInstanceId;
247 readonly providerGroups: ReadonlyArray<ProviderGroup>;
248 readonly selectedModel: ModelSelection | null;
249 readonly onSelectModel: (option: ModelOption) => void;
250 readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
251 readonly onUpdateOptionSelections: (selections: ReadonlyArray<ProviderOptionSelection>) => void;
252 readonly runtimeMode: RuntimeMode;
253 readonly onUpdateRuntimeMode: (mode: RuntimeMode) => void;
254};
255​
256export type ExistingThreadSettingsRouteSession = ThreadSettingsSessionProps & {
257 readonly ownerId: string;
258};
259​
260type ExistingThreadSettingsRouteContextValue = {
261 readonly session: ExistingThreadSettingsRouteSession | null;
262 readonly present: (session: ExistingThreadSettingsRouteSession) => void;
263 readonly clear: (ownerId: string) => void;
264};
265​
266const ExistingThreadSettingsRouteContext =
267 createContext<ExistingThreadSettingsRouteContextValue | null>(null);
268​
269/** Bridges the active thread's settings state into the root native sheet route. */
270export function ExistingThreadSettingsRouteProvider(props: { readonly children: ReactNode }) {
271 const [session, setSession] = useState<ExistingThreadSettingsRouteSession | null>(null);
272 const present = useCallback((nextSession: ExistingThreadSettingsRouteSession) => {
273 setSession(nextSession);
274 }, []);
275 const clear = useCallback((ownerId: string) => {
276 setSession((current) => (current?.ownerId === ownerId ? null : current));
277 }, []);
278 const value = useMemo(() => ({ session, present, clear }), [clear, present, session]);
279​
280 return (
281 <ExistingThreadSettingsRouteContext.Provider value={value}>
282 {props.children}
283 </ExistingThreadSettingsRouteContext.Provider>
284 );
286​
287export function useExistingThreadSettingsRoutePresentation() {
288 const value = use(ExistingThreadSettingsRouteContext);
289 if (!value) {
290 throw new Error(
291 "useExistingThreadSettingsRoutePresentation must be used inside ExistingThreadSettingsRouteProvider.",
292 );
293 }
294 return value;
296​
297type ThreadSettingsSessionValue = {
298 readonly environmentId: EnvironmentId | null;
299 readonly providerInstanceId?: ProviderInstanceId;
300 readonly providerGroups: ReadonlyArray<ProviderGroup>;
301 readonly favoriteKeys: ReadonlySet<string>;
302 readonly favoritesLoaded: boolean;
303 readonly toggleFavorite: (option: ModelOption) => void;
304 readonly runtimeMode: RuntimeMode;
305 readonly runtimeModeChoices: ReturnType<typeof runtimeModeChoicesForSupportedModes>;
306 readonly onUpdateRuntimeMode: (mode: RuntimeMode) => void;
307 readonly displayedDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
308 readonly providerExpansionOverrides: ReadonlySet<string>;
309 readonly hasLegacyModels: boolean;
310 readonly pendingModel: ModelOption | null;
311 readonly providerFilter: string | null;
312 readonly searchQuery: string;
313 readonly showLegacy: boolean;
314 readonly applyOptionChange: (id: string, value: string | boolean) => void;
315 readonly commitPendingModel: () => boolean;
316 readonly isApplied: (option: ModelOption) => boolean;
317 readonly isDisplayed: (option: ModelOption) => boolean;
318 readonly pressModel: (option: ModelOption) => void;
319 readonly setProviderFilter: (providerKey: string | null) => void;
320 readonly setSearchQuery: (query: string) => void;
321 readonly setShowLegacy: (showLegacy: boolean) => void;
322 readonly toggleProvider: (providerKey: string) => void;
323};
324​
325const ThreadSettingsSessionContext = createContext<ThreadSettingsSessionValue | null>(null);
326​
327/** Owns the staged model and option state for one picker presentation. */
328function ThreadSettingsSessionProvider(
329 props: ThreadSettingsSessionProps & { readonly children: ReactNode },
330) {
331 const preferences = useAtomValue(mobilePreferencesAtom);
332 const savePreferences = useAtomSet(updateMobilePreferencesAtom);
333 const favoritesLoaded = AsyncResult.isSuccess(preferences);
334 const modelFavorites = favoritesLoaded
335 ? (preferences.value.modelFavorites ?? EMPTY_MODEL_FAVORITES)
336 : EMPTY_MODEL_FAVORITES;
337 const favoriteKeys = useMemo(
338 () =>
339 new Set(
340 modelFavorites.map((favorite) => modelFavoriteKey(favorite.provider, favorite.model)),
341 ),
342 [modelFavorites],
343 );
344 const toggleFavorite = useCallback(
345 (option: ModelOption) => {
346 if (!favoritesLoaded) return;
347 void Haptics.selectionAsync();
348 savePreferences({
349 transform: (current) => ({
350 modelFavorites: toggleModelFavorite(
351 current.modelFavorites ?? EMPTY_MODEL_FAVORITES,
352 option,
353 ),
354 }),
355 });
356 },
357 [favoritesLoaded, savePreferences],
358 );
359 const [showLegacyToggle, setShowLegacyToggle] = useState(false);
360 const [providerFilter, setProviderFilter] = useState<string | null>(null);
361 const [searchQuery, setSearchQuery] = useState("");
362 const [providerExpansionOverrides, setProviderExpansionOverrides] = useState<ReadonlySet<string>>(
363 () => new Set(),
364 );
365 const [pendingModel, setPendingModel] = useState<ModelOption | null>(null);
366​
367 const isApplied = useCallback(
368 (option: ModelOption) =>
369 option.selection.instanceId === props.selectedModel?.instanceId &&
370 option.selection.model === props.selectedModel.model,
371 [props.selectedModel],
372 );
373 // The list highlights the staged pick; Save turns it into the applied one.
374 const isDisplayed = useCallback(
375 (option: ModelOption) => (pendingModel ? option.key === pendingModel.key : isApplied(option)),
376 [isApplied, pendingModel],
377 );
378​
379 // While a model is staged, the settings rows describe and edit the staged
380 // model's options (kept on its pending selection); Save applies model and
381 // options together. Otherwise they edit the applied selection directly.
382 const displayedDescriptors = useMemo(
383 () =>
384 pendingModel
385 ? pendingModel.capabilities
386 ? getProviderOptionDescriptors({
387 caps: pendingModel.capabilities,
388 selections: pendingModel.selection.options,
389 })
390 : []
391 : props.optionDescriptors,
392 [pendingModel, props.optionDescriptors],
393 );
394 const displayedModel = useMemo(
395 () =>
396 pendingModel ??
397 props.providerGroups.flatMap((group) => group.models).find((option) => isApplied(option)) ??
398 null,
399 [isApplied, pendingModel, props.providerGroups],
400 );
401 const runtimeModeChoices = runtimeModeChoicesForSupportedModes(
402 displayedModel?.supportedRuntimeModes,
403 );
404 const compatibleRuntimeMode = compatibleRuntimeModeForChoices(
405 props.runtimeMode,
406 runtimeModeChoices,
407 );
408​
409 const hasLegacyModels = useMemo(
410 () => props.providerGroups.some((group) => group.models.some((model) => model.isLegacy)),
411 [props.providerGroups],
412 );
413 const commitPendingModel = useCallback(() => {
414 if (pendingModel) {
415 if (!canCommitPendingModel(pendingModel, props.providerGroups)) {
416 Alert.alert(
417 "Model unavailable",
418 "Set up this provider on web or desktop, or select another model.",
419 );
420 return false;
421 }
422 void Haptics.selectionAsync();
423 props.onSelectModel(pendingModel);
424 }
425 return true;
426 }, [pendingModel, props.onSelectModel, props.providerGroups]);
427​
428 const applyOptionChange = useCallback(
429 (id: string, value: string | boolean) => {
430 const next = applyProviderOptionSelection(displayedDescriptors, { id, value });
431 if (!next) {
432 return;
433 }
434 if (pendingModel) {
435 rememberModelOptions(pendingModel.selection.instanceId, pendingModel.selection.model, next);
436 setPendingModel({
437 ...pendingModel,
438 selection: { ...pendingModel.selection, options: next },
439 });
440 } else {
441 props.onUpdateOptionSelections(next);
442 }
443 },
444 [displayedDescriptors, pendingModel, props.onUpdateOptionSelections],
445 );
446​
447 const toggleProvider = useCallback((providerKey: string) => {
448 setProviderExpansionOverrides((current) => {
449 const next = new Set(current);
450 if (!next.delete(providerKey)) {
451 next.add(providerKey);
452 }
453 return next;
454 });
455 }, []);
456​
457 const pressModel = useCallback(
458 (option: ModelOption) => {
459 void Haptics.selectionAsync();
460 setPendingModel((current) =>
461 pendingModelAfterPress({
462 current,
463 pressed: option,
464 pressedIsApplied: isApplied(option),
465 }),
466 );
467 },
468 [isApplied],
469 );
470​
471 const value = useMemo<ThreadSettingsSessionValue>(
472 () => ({
473 environmentId: props.environmentId,
474 providerInstanceId: props.providerInstanceId,
475 providerGroups: props.providerGroups,
476 runtimeMode: compatibleRuntimeMode,
477 runtimeModeChoices,
478 onUpdateRuntimeMode: props.onUpdateRuntimeMode,
479 displayedDescriptors,
480 favoriteKeys,
481 favoritesLoaded,
482 providerExpansionOverrides,
483 hasLegacyModels,
484 pendingModel,
485 providerFilter,
486 searchQuery,
487 showLegacy: showLegacyToggle,
488 applyOptionChange,
489 commitPendingModel,
490 isApplied,
491 isDisplayed,
492 pressModel,
493 setProviderFilter,
494 setSearchQuery,
495 setShowLegacy: setShowLegacyToggle,
496 toggleProvider,
497 toggleFavorite,
498 }),
499 [
500 applyOptionChange,
501 commitPendingModel,
502 compatibleRuntimeMode,
503 displayedDescriptors,
504 favoriteKeys,
505 favoritesLoaded,
506 providerExpansionOverrides,
507 hasLegacyModels,
508 isApplied,
509 isDisplayed,
510 props.environmentId,
511 props.providerInstanceId,
512 pendingModel,
513 pressModel,
514 providerFilter,
515 props.onUpdateRuntimeMode,
516 props.providerGroups,
517 runtimeModeChoices,
518 searchQuery,
519 showLegacyToggle,
520 toggleProvider,
521 toggleFavorite,
522 ],
523 );
524​
525 return (
526 <ThreadSettingsSessionContext.Provider value={value}>
527 {props.children}
528 </ThreadSettingsSessionContext.Provider>
529 );
531​
532function useThreadSettingsSession() {
533 const value = use(ThreadSettingsSessionContext);
534 if (!value) {
535 throw new Error("useThreadSettingsSession must be used inside ThreadSettingsSessionProvider.");
536 }
537 return value;
539​
540type ThreadSettingsProviderCatalog = {
541 readonly key: string;
542 readonly driver: string | undefined;
543 readonly iconUrl: string | undefined;
544 readonly label: string;
545 readonly collapsible: boolean;
546 readonly collapsed: boolean;
547 readonly modelCount: number;
548 readonly models: ReadonlyArray<ModelOption>;
549};
550​
551type ThreadSettingsCatalogItem =
552 | {
553 readonly kind: "provider";
554 readonly key: string;
555 readonly provider: ThreadSettingsProviderCatalog;
556 }
557 | {
558 readonly kind: "model";
559 readonly key: string;
560 readonly option: ModelOption;
561 readonly isFirst: boolean;
562 readonly isLast: boolean;
563 }
564 | {
565 readonly kind: "empty";
566 readonly key: "empty";
567 }
568 | {
569 readonly kind: "options";
570 readonly key: "options";
571 };
572​
573function ThreadSettingsModelListRow(props: {
574 readonly option: ModelOption;
575 readonly isFirst: boolean;
576 readonly isLast: boolean;
577}) {
578 const session = useThreadSettingsSession();
579 const onPress = useCallback(
580 () => session.pressModel(props.option),
581 [props.option, session.pressModel],
582 );
583​
584 return (
585 <ModelRow
586 isFirst={props.isFirst}
587 isLast={props.isLast}
588 onPress={onPress}
589 isFavorite={session.favoriteKeys.has(props.option.key)}
590 favoritesLoaded={session.favoritesLoaded}
591 onToggleFavorite={() => session.toggleFavorite(props.option)}
592 option={props.option}
593 selected={session.isDisplayed(props.option)}
594 />
595 );
597​
598function ThreadSettingsProviderListHeader(props: {
599 readonly provider: ThreadSettingsProviderCatalog;
600}) {
601 const session = useThreadSettingsSession();
602 const onToggle = useCallback(
603 () => session.toggleProvider(props.provider.key),
604 [props.provider.key, session.toggleProvider],
605 );
606​
607 return (
608 <ProviderHeader
609 collapsible={props.provider.collapsible}
610 collapsed={props.provider.collapsed}
611 driver={props.provider.driver}
612 iconUrl={props.provider.iconUrl}
613 label={props.provider.label}
614 modelCount={props.provider.modelCount}
615 onToggle={onToggle}
616 />
617 );
619​
620function useThreadSettingsCatalogItems(
621 session: ThreadSettingsSessionValue,
622): ReadonlyArray<ThreadSettingsCatalogItem> {
623 return useMemo(
624 () =>
625 session.providerGroups.flatMap((group) => {
626 if (
627 session.providerFilter !== null &&
628 session.providerFilter !== FAVORITES_PROVIDER_FILTER &&
629 group.providerKey !== session.providerFilter
630 ) {
631 return [];
632 }
633 const driver = group.models[0]?.providerDriver ?? group.providerKey;
634 const catalogModels =
635 session.showLegacy || session.providerFilter === FAVORITES_PROVIDER_FILTER
636 ? group.models
637 : group.models.filter(
638 (model) =>
639 !model.isLegacy ||
640 session.isDisplayed(model) ||
641 session.favoriteKeys.has(model.key),
642 );
643 const visibleModels = favoritesFirst(
644 catalogModels.filter(
645 (model) =>
646 (session.providerFilter !== FAVORITES_PROVIDER_FILTER ||
647 session.favoriteKeys.has(model.key)) &&
648 modelMatchesCatalogQuery({
649 model,
650 providerLabel: group.providerLabel,
651 query: session.searchQuery,
652 }),
653 ),
654 session.favoriteKeys,
655 );
656 if (visibleModels.length === 0) {
657 return [];
658 }
659 const isPrimary = driver !== undefined && PRIMARY_PROVIDER_DRIVERS.has(driver);
660 // Staging a model must not change disclosure state. The applied model
661 // stays stable for the lifetime of this picker (Save closes it), so it
662 // is safe to use as the initial selected-provider default.
663 const containsAppliedSelection = group.models.some(session.isApplied);
664 const isNarrowed = session.providerFilter !== null || session.searchQuery.trim().length > 0;
665 const collapsible = !isNarrowed;
666 const collapsed = providerSectionIsCollapsed({
667 defaultExpanded: isPrimary || containsAppliedSelection,
668 hasExpansionOverride: session.providerExpansionOverrides.has(group.providerKey),
669 isNarrowed,
670 });
671 const provider: ThreadSettingsProviderCatalog = {
672 key: group.providerKey,
673 driver,
674 iconUrl: group.models[0]?.providerIconUrl,
675 label: group.providerLabel,
676 collapsible,
677 collapsed,
678 modelCount: visibleModels.length,
679 models: collapsed ? [] : visibleModels,
680 };
681 return [
682 {
683 kind: "provider" as const,
684 key: `provider:${group.providerKey}`,
685 provider,
686 },
687 ...provider.models.map((option, index) => ({
688 kind: "model" as const,
689 key: `model:${option.key}`,
690 option,
691 isFirst: index === 0,
692 isLast: index === provider.models.length - 1,
693 })),
694 ];
695 }),
696 [
697 session.isApplied,
698 session.isDisplayed,
699 session.favoriteKeys,
700 session.providerExpansionOverrides,
701 session.providerFilter,
702 session.providerGroups,
703 session.searchQuery,
704 session.showLegacy,
705 ],
706 );
708​
709function ThreadSettingsOptionsItem(props: {
710 readonly animationsReady: boolean;
711 readonly onOpenSubmenu: (submenu: ThreadSettingsSubmenuPage) => void;
712}) {
713 const insets = useSafeAreaInsets();
714 const session = useThreadSettingsSession();
715 const bottomToolbarInset =
716 Platform.OS === "ios" && NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED
717 ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET
718 : 0;
719​
720 return (
721 <View style={{ paddingBottom: insets.bottom + bottomToolbarInset + 12 }}>
722 <Text className="px-5 pb-2 pt-2 text-sm font-t3-medium text-foreground-muted">Options</Text>
723 <Animated.View
724 className="mx-4 overflow-hidden rounded-2xl bg-card"
725 layout={THREAD_SETTINGS_OPTIONS_LAYOUT_TRANSITION}
726 >
727 {session.displayedDescriptors.map((descriptor) => {
728 if (descriptor.type === "select") {
729 return (
730 <Animated.View
731 key={descriptor.id}
732 entering={
733 props.animationsReady ? THREAD_SETTINGS_OPTION_ENTER_TRANSITION : undefined
734 }
735 exiting={props.animationsReady ? THREAD_SETTINGS_OPTION_EXIT_TRANSITION : undefined}
736 layout={THREAD_SETTINGS_OPTIONS_LAYOUT_TRANSITION}
737 >
738 <DisclosureRow
739 label={descriptor.label}
740 value={getProviderOptionCurrentLabel(descriptor)}
741 onPress={() => props.onOpenSubmenu({ kind: "descriptor", id: descriptor.id })}
742 />
743 </Animated.View>
744 );
745 }
746 return (
747 <Animated.View
748 key={descriptor.id}
749 entering={props.animationsReady ? THREAD_SETTINGS_OPTION_ENTER_TRANSITION : undefined}
750 exiting={props.animationsReady ? THREAD_SETTINGS_OPTION_EXIT_TRANSITION : undefined}
751 layout={THREAD_SETTINGS_OPTIONS_LAYOUT_TRANSITION}
752 >
753 <SwitchRow
754 label={descriptor.label}
755 value={descriptor.currentValue ?? false}
756 onValueChange={(value) => session.applyOptionChange(descriptor.id, value)}
757 />
758 </Animated.View>
759 );
760 })}
761 <Animated.View layout={THREAD_SETTINGS_OPTIONS_LAYOUT_TRANSITION}>
762 <DisclosureRow
763 isLast
764 label="Runtime"
765 value={
766 session.runtimeModeChoices.find((choice) => choice.mode === session.runtimeMode)
767 ?.label
768 }
769 onPress={() => props.onOpenSubmenu({ kind: "runtime" })}
770 />
771 </Animated.View>
772 </Animated.View>
773​
774 {Platform.OS !== "ios" && session.hasLegacyModels ? (
775 <>
776 <Text className="px-5 pb-2 pt-7 text-sm font-t3-medium text-foreground-muted">
777 Catalog
778 </Text>
779 <View className="mx-4 overflow-hidden rounded-2xl bg-card">
780 <SwitchRow
781 isLast
782 label="Legacy models"
783 onValueChange={session.setShowLegacy}
784 value={session.showLegacy}
785 />
786 </View>
787 </>
788 ) : null}
789 </View>
790 );
792​
793/** One native scroll owner for the model catalog and its related settings. */
794function ThreadSettingsMainContent(props: {
795 readonly onOpenSubmenu: (submenu: ThreadSettingsSubmenuPage) => void;
796}) {
797 const session = useThreadSettingsSession();
798 const refreshProvidersCommand = useAtomCommand(serverEnvironment.refreshProviders, {
799 reportFailure: false,
800 });
801 const refreshProviderCatalog = useMemo(
802 () => createProviderCatalogRefreshRunner(refreshProvidersCommand),
803 [refreshProvidersCommand],
804 );
805 const [isRefreshingProviders, setIsRefreshingProviders] = useState(false);
806 const refreshProviders = useCallback(() => {
807 if (!session.environmentId || isRefreshingProviders) return;
808 setIsRefreshingProviders(true);
809 void refreshProviderCatalog(session.environmentId).then((result) => {
810 setIsRefreshingProviders(false);
811 const error = providerCatalogRefreshError(result);
812 if (error) Alert.alert("Could not refresh models", error);
813 });
814 }, [isRefreshingProviders, refreshProviderCatalog, session.environmentId]);
815 const catalogItems = useThreadSettingsCatalogItems(session);
816 const [animationsReady, setAnimationsReady] = useState(false);
817 const hasActiveCatalogFilter =
818 session.providerFilter !== null || session.searchQuery.trim().length > 0;
819 const listItems = useMemo<ReadonlyArray<ThreadSettingsCatalogItem>>(
820 () => [
821 ...(catalogItems.length === 0 ? ([{ kind: "empty", key: "empty" }] as const) : catalogItems),
822 { kind: "options", key: "options" },
823 ],
824 [catalogItems],
825 );
826 const renderCatalogItem = useCallback(
827 (itemProps: LegendListRenderItemProps<ThreadSettingsCatalogItem>) => {
828 const item = itemProps.item;
829 let content: ReactNode;
830​
831 if (item.kind === "provider") {
832 content = <ThreadSettingsProviderListHeader provider={item.provider} />;
833 } else if (item.kind === "model") {
834 content = (
835 <ThreadSettingsModelListRow
836 isFirst={item.isFirst}
837 isLast={item.isLast}
838 option={item.option}
839 />
840 );
841 } else if (item.kind === "empty") {
842 content = (
843 <View className="items-center px-8 py-14">
844 <Text className="text-center text-sm text-foreground-muted">
845 {session.providerFilter === FAVORITES_PROVIDER_FILTER &&
846 session.searchQuery.trim().length === 0
847 ? "No favorite models"
848 : hasActiveCatalogFilter
849 ? "No matching models"
850 : "No available models"}
851 </Text>
852 </View>
853 );
854 } else {
855 content = (
856 <ThreadSettingsOptionsItem
857 animationsReady={animationsReady}
858 onOpenSubmenu={props.onOpenSubmenu}
859 />
860 );
861 }
862​
863 return (
864 <Animated.View
865 key={item.key}
866 entering={animationsReady ? THREAD_SETTINGS_CATALOG_ENTER_TRANSITION : undefined}
867 exiting={animationsReady ? THREAD_SETTINGS_CATALOG_EXIT_TRANSITION : undefined}
868 >
869 {content}
870 </Animated.View>
871 );
872 },
873 [
874 animationsReady,
875 hasActiveCatalogFilter,
876 props.onOpenSubmenu,
877 session.providerFilter,
878 session.searchQuery,
879 ],
880 );
881​
882 return (
883 <AnimatedLegendList
884 alwaysBounceVertical
885 automaticallyAdjustsScrollIndicatorInsets
886 className="flex-1 bg-sheet"
887 style={
888 Platform.OS === "android"
889 ? { width: "100%", maxWidth: 720, alignSelf: "center" }
890 : undefined
891 }
892 contentContainerStyle={{ paddingTop: 4 }}
893 contentInsetAdjustmentBehavior="automatic"
894 data={listItems}
895 estimatedItemSize={Platform.OS === "android" ? 56 : 48}
896 extraData={animationsReady}
897 getItemType={(item) => item.kind}
898 itemLayoutAnimation={THREAD_SETTINGS_CATALOG_LAYOUT_TRANSITION}
899 keyExtractor={(item) => item.key}
900 keyboardDismissMode="on-drag"
901 keyboardShouldPersistTaps="handled"
902 maintainVisibleContentPosition={THREAD_SETTINGS_MAINTAIN_VISIBLE_CONTENT_POSITION}
903 ListHeaderComponent={
904 <>
905 {Platform.OS === "android" ? (
906 <View className="px-4 pb-2 pt-3">
907 <View
908 className="flex-row items-center rounded-full bg-input px-2"
909 style={{ minHeight: 56 }}
910 >
911 <View pointerEvents="none" className="px-2">
912 <SymbolView
913 name="magnifyingglass"
914 size={24}
915 tintColorClassName="accent-icon-subtle"
916 />
917 </View>
918 <TextInput
919 accessibilityLabel="Find a model"
920 autoCapitalize="none"
921 autoCorrect={false}
922 className="min-w-0 flex-1 px-2 py-0 text-base text-foreground"
923 style={{ minHeight: 56, includeFontPadding: false, textAlignVertical: "center" }}
924 onChangeText={session.setSearchQuery}
925 placeholder="Find a model"
926 placeholderTextColorClassName="accent-placeholder"
927 selectionColorClassName="accent-primary/32"
928 cursorColorClassName="accent-primary"
929 selectionHandleColorClassName="accent-primary"
930 value={session.searchQuery}
931 />
932 {session.searchQuery.length > 0 ? (
933 <MaterialIconButton
934 accessibilityLabel="Clear model search"
935 icon="xmark"
936 onPress={() => session.setSearchQuery("")}
937 />
938 ) : null}
939 </View>
940 </View>
941 ) : null}
942 </>
943 }
944 recycleItems
945 refreshControl={
946 session.environmentId ? (
947 <RefreshControl refreshing={isRefreshingProviders} onRefresh={refreshProviders} />
948 ) : undefined
949 }
950 onLoad={() => setAnimationsReady(true)}
951 renderItem={renderCatalogItem}
952 showsVerticalScrollIndicator={false}
953 />
954 );
956​
957/** Compact choice page pushed by the picker navigator. */
958function ThreadSettingsChoiceContent(props: {
959 readonly submenu: ThreadSettingsSubmenuPage;
960 readonly onSelected: () => void;
961}) {
962 const insets = useSafeAreaInsets();
963 const session = useThreadSettingsSession();
964 const descriptorId = props.submenu.kind === "descriptor" ? props.submenu.id : null;
965​
966 const activeDescriptor =
967 descriptorId !== null
968 ? session.displayedDescriptors.find(
969 (descriptor) => descriptor.type === "select" && descriptor.id === descriptorId,
970 )
971 : undefined;
972​
973 const submenuContent =
974 props.submenu.kind === "runtime"
975 ? {
976 rows: session.runtimeModeChoices.map((choice) => ({
977 id: choice.mode,
978 label: choice.label,
979 description: choice.description,
980 selected: choice.mode === session.runtimeMode,
981 onPress: () => {
982 void Haptics.selectionAsync();
983 session.onUpdateRuntimeMode(choice.mode);
984 props.onSelected();
985 },
986 })),
987 }
988 : activeDescriptor?.type === "select"
989 ? {
990 rows: selectableChoices(activeDescriptor).map((choice) => ({
991 id: choice.id,
992 label: choice.label,
993 description: undefined,
994 selected: choice.id === getProviderOptionCurrentValue(activeDescriptor),
995 onPress: () => {
996 void Haptics.selectionAsync();
997 session.applyOptionChange(activeDescriptor.id, choice.id);
998 props.onSelected();
999 },
1000 })),
1002 : null;
1003​
1004 if (!submenuContent) {
1005 return <View className="flex-1 bg-sheet" />;
1007​
1008 return (
1009 <ScrollView
1010 className="flex-1 bg-sheet"
1011 style={
1012 Platform.OS === "android"
1013 ? { width: "100%", maxWidth: 720, alignSelf: "center" }
1014 : undefined
1016 contentContainerStyle={{
1017 paddingBottom: insets.bottom + 12,
1018 paddingHorizontal: 16,
1019 paddingTop: 16,
1020 }}
1021 contentInsetAdjustmentBehavior="automatic"
1022 showsVerticalScrollIndicator={false}
1024 <View className="overflow-hidden rounded-2xl bg-card">
1025 {submenuContent.rows.map((row, index) => (
1026 <ChoiceRow
1027 key={row.id}
1028 description={row.description}
1029 isLast={index === submenuContent.rows.length - 1}
1030 label={row.label}
1031 selected={row.selected}
1032 onPress={row.onPress}
1033 />
1034 ))}
1035 </View>
1036 </ScrollView>
1037 );
1039​
1040type ThreadSettingsPickerStackParams = {
1041 ThreadSettingsModels: undefined;
1042 ThreadSettingsChoice: ThreadSettingsSubmenuPage & { readonly title: string };
1044​
1045type ThreadSettingsPickerPresentation = {
1046 readonly onClose: () => void;
1048​
1049const ThreadSettingsPickerStack = createNativeStackNavigator<ThreadSettingsPickerStackParams>();
1050const ThreadSettingsPickerPresentationContext =
1051 createContext<ThreadSettingsPickerPresentation | null>(null);
1052​
1053function useThreadSettingsPickerPresentation() {
1054 const value = use(ThreadSettingsPickerPresentationContext);
1055 if (!value) {
1056 throw new Error(
1057 "useThreadSettingsPickerPresentation must be used inside ThreadSettingsPickerNavigator.",
1058 );
1060 return value;
1062​
1063function ThreadSettingsModelsScreen() {
1064 const session = useThreadSettingsSession();
1065 const presentation = useThreadSettingsPickerPresentation();
1066 const navigation = useNavigation<NativeStackNavigationProp<ThreadSettingsPickerStackParams>>();
1067 const usesNativeMailSearchToolbar = Platform.OS === "ios" && NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED;
1068 const hasCustomCatalogFilter = session.providerFilter !== null || session.showLegacy;
1069 const commitAndClose = useCallback(() => {
1070 if (!session.commitPendingModel()) return;
1071 presentation.onClose();
1072 }, [presentation, session]);
1073 const providerFilters = useMemo(
1074 () => [
1075 { id: "all-providers", title: "All providers", value: null },
1076 { id: "favorites", title: "Favorites", value: FAVORITES_PROVIDER_FILTER },
1077 ...session.providerGroups.map((group) => ({
1078 id: `provider:${group.providerKey}`,
1079 title: group.providerLabel,
1080 value: group.providerKey,
1081 })),
1082 ],
1083 [session.providerGroups],
1084 );
1085 const filterMenu = useMemo(
1086 () => ({
1087 title: "Model filters",
1088 items: [
1090 type: "submenu" as const,
1091 title: "Provider",
1092 items: providerFilters.map((filter) => ({
1093 type: "action" as const,
1094 title: filter.title,
1095 state: session.providerFilter === filter.value ? ("on" as const) : ("off" as const),
1096 onPress: () => session.setProviderFilter(filter.value),
1097 })),
1098 },
1099 ...(session.hasLegacyModels
1100 ? [
1102 type: "action" as const,
1103 title: "Show legacy models",
1104 state: session.showLegacy ? ("on" as const) : ("off" as const),
1105 onPress: () => session.setShowLegacy(!session.showLegacy),
1106 },
1108 : []),
1109 ],
1110 }),
1111 [providerFilters, session],
1112 );
1113​
1114 return (
1115 <>
1116 {Platform.OS === "android" ? (
1117 <AndroidScreenHeader
1118 trailing={
1119 <View className="flex-row items-center">
1120 <AndroidAnchoredMenu
1121 title="Model filters"
1122 actions={[
1124 title: "Provider",
1125 subactions: providerFilters.map((filter) => ({
1126 id: filter.id,
1127 title: filter.title,
1128 state: session.providerFilter === filter.value ? "on" : "off",
1129 })),
1130 },
1131 ...(session.hasLegacyModels
1132 ? [
1134 id: "show-legacy",
1135 title: "Show legacy models",
1136 state: session.showLegacy ? ("on" as const) : ("off" as const),
1137 },
1139 : []),
1140 ]}
1141 onPressAction={({ nativeEvent }) => {
1142 if (nativeEvent.event === "show-legacy") {
1143 session.setShowLegacy(!session.showLegacy);
1144 } else {
1145 const filter = providerFilters.find((item) => item.id === nativeEvent.event);
1146 if (filter) session.setProviderFilter(filter.value);
1148 }}
1150 {(open) => (
1151 <MaterialIconButton
1152 accessibilityLabel="Filter models"
1153 icon="line.3.horizontal.decrease"
1154 selected={hasCustomCatalogFilter}
1155 variant={hasCustomCatalogFilter ? "tonal" : "standard"}
1156 onPress={open}
1157 />
1158 )}
1159 </AndroidAnchoredMenu>
1160 {session.pendingModel ? (
1161 <MaterialButton label="Save" tone="text" onPress={commitAndClose} />
1162 ) : null}
1163 </View>
1165 onBack={presentation.onClose}
1166 title="Thread settings"
1167 hideBottomBorder
1168 />
1169 ) : null}
1170 <NativeStackScreenOptions
1171 optionsVersion={[
1172 session.providerFilter,
1173 session.providerGroups.map((group) => group.providerKey),
1174 session.showLegacy,
1175 ]}
1176 options={{
1177 unstable_headerToolbarItems: usesNativeMailSearchToolbar
1178 ? () => [
1179 createNativeMailSearchToolbarItem({
1180 filterButtonId: "thread-settings-model-filter",
1181 filterMenu,
1182 filterSystemImageName: hasCustomCatalogFilter
1183 ? "line.3.horizontal.decrease.circle.fill"
1184 : "line.3.horizontal.decrease",
1185 onSearchTextChange: session.setSearchQuery,
1186 placeholder: "Find a model",
1187 searchTextChangeId: "thread-settings-model-search-text",
1188 showsSearchDismissButton: true,
1189 }),
1191 : undefined,
1192 headerShown: Platform.OS !== "android",
1193 headerSearchBarOptions:
1194 Platform.OS === "ios" && !usesNativeMailSearchToolbar
1195 ? {
1196 autoCapitalize: "none",
1197 hideNavigationBar: false,
1198 obscureBackground: false,
1199 onCancelButtonPress: () => session.setSearchQuery(""),
1200 onChangeText: (event) => session.setSearchQuery(event.nativeEvent.text),
1201 placeholder: "Find a model",
1203 : undefined,
1204 }}
1205 />
1206 <MaterialScreenContent>
1207 <ThreadSettingsMainContent
1208 onOpenSubmenu={(submenu) => {
1209 const title =
1210 submenu.kind === "runtime"
1211 ? "Runtime"
1212 : (session.displayedDescriptors.find(
1213 (descriptor) => descriptor.type === "select" && descriptor.id === submenu.id,
1214 )?.label ?? "Option");
1215 navigation.navigate("ThreadSettingsChoice", { ...submenu, title });
1216 }}
1217 />
1218 </MaterialScreenContent>
1219 <NativeHeaderToolbar placement="left">
1220 <NativeHeaderToolbar.Button
1221 accessibilityLabel="Cancel thread settings"
1222 label="Cancel"
1223 onPress={presentation.onClose}
1224 />
1225 </NativeHeaderToolbar>
1226 <NativeHeaderToolbar placement="right">
1227 <NativeHeaderToolbar.Button
1228 accessibilityLabel={session.pendingModel ? "Save thread settings" : "Done"}
1229 label={session.pendingModel ? "Save" : "Done"}
1230 onPress={commitAndClose}
1231 />
1232 </NativeHeaderToolbar>
1233 {Platform.OS === "ios" && !usesNativeMailSearchToolbar ? (
1234 <NativeHeaderToolbar placement="bottom">
1235 <NativeHeaderToolbar.Menu
1236 accessibilityLabel="Filter models"
1237 icon={
1238 hasCustomCatalogFilter
1239 ? "line.3.horizontal.decrease.circle.fill"
1240 : "line.3.horizontal.decrease.circle"
1242 separateBackground
1243 title="Model filters"
1245 <NativeHeaderToolbar.Menu title="Provider">
1246 <NativeHeaderToolbar.Label>Provider</NativeHeaderToolbar.Label>
1247 <NativeHeaderToolbar.MenuAction
1248 isOn={session.providerFilter === null}
1249 onPress={() => session.setProviderFilter(null)}
1251 All providers
1252 </NativeHeaderToolbar.MenuAction>
1253 <NativeHeaderToolbar.MenuAction
1254 isOn={session.providerFilter === FAVORITES_PROVIDER_FILTER}
1255 onPress={() => session.setProviderFilter(FAVORITES_PROVIDER_FILTER)}
1257 Favorites
1258 </NativeHeaderToolbar.MenuAction>
1259 {session.providerGroups.map((group) => (
1260 <NativeHeaderToolbar.MenuAction
1261 key={group.providerKey}
1262 isOn={session.providerFilter === group.providerKey}
1263 onPress={() => session.setProviderFilter(group.providerKey)}
1265 {group.providerLabel}
1266 </NativeHeaderToolbar.MenuAction>
1267 ))}
1268 </NativeHeaderToolbar.Menu>
1269 {session.hasLegacyModels ? (
1270 <NativeHeaderToolbar.MenuAction
1271 isOn={session.showLegacy}
1272 onPress={() => session.setShowLegacy(!session.showLegacy)}
1274 Show legacy models
1275 </NativeHeaderToolbar.MenuAction>
1276 ) : null}
1277 </NativeHeaderToolbar.Menu>
1278 </NativeHeaderToolbar>
1279 ) : null}
1280 </>
1281 );
1283​
1284function ThreadSettingsChoiceScreen() {
1285 const navigation = useNavigation<NativeStackNavigationProp<ThreadSettingsPickerStackParams>>();
1286 const route = useRoute<RouteProp<ThreadSettingsPickerStackParams, "ThreadSettingsChoice">>();
1287​
1288 return (
1289 <>
1290 <NativeStackScreenOptions options={{ headerShown: Platform.OS !== "android" }} />
1291 {Platform.OS === "android" ? (
1292 <AndroidScreenHeader
1293 title={route.params.title}
1294 onBack={() => navigation.goBack()}
1295 hideBottomBorder
1296 />
1297 ) : null}
1298 <MaterialScreenContent>
1299 <ThreadSettingsChoiceContent
1300 submenu={route.params}
1301 onSelected={() => navigation.goBack()}
1302 />
1303 </MaterialScreenContent>
1304 </>
1305 );
1307​
1308function ThreadSettingsPickerNavigator(props: ThreadSettingsPickerPresentation) {
1309 const theme = useUniwindTheme();
1310 const solidSheetBackground = theme["--color-sheet-solid"];
1311 const foreground = theme["--color-foreground"];
1312 const presentation = useMemo(
1313 () => ({
1314 onClose: props.onClose,
1315 }),
1316 [props.onClose],
1317 );
1318​
1319 return (
1320 <ThreadSettingsPickerPresentationContext.Provider value={presentation}>
1321 <ThreadSettingsPickerStack.Navigator
1322 initialRouteName="ThreadSettingsModels"
1323 screenOptions={{
1324 animation: Platform.OS === "android" ? "default" : "slide_from_right",
1325 contentStyle: { backgroundColor: solidSheetBackground },
1326 gestureEnabled: true,
1327 headerBackButtonDisplayMode: "minimal",
1328 headerBackTitle: "",
1329 headerShown: Platform.OS !== "android",
1330 headerShadowVisible: false,
1331 headerStyle: {
1332 backgroundColor: NATIVE_LIQUID_GLASS_SUPPORTED ? "transparent" : solidSheetBackground,
1333 },
1334 headerTransparent: NATIVE_LIQUID_GLASS_SUPPORTED,
1335 headerTintColor: foreground,
1336 headerTitleStyle: { fontSize: 17, fontWeight: "700" },
1337 scrollEdgeEffects: NATIVE_LIQUID_GLASS_SUPPORTED
1338 ? THREAD_SETTINGS_HEADER_SCROLL_EDGE_EFFECTS
1339 : undefined,
1340 }}
1342 <ThreadSettingsPickerStack.Screen
1343 name="ThreadSettingsModels"
1344 component={ThreadSettingsModelsScreen}
1345 options={{ headerBackVisible: false, title: "Thread settings" }}
1346 />
1347 <ThreadSettingsPickerStack.Screen
1348 name="ThreadSettingsChoice"
1349 component={ThreadSettingsChoiceScreen}
1350 options={({ route }) => ({ title: route.params.title })}
1351 />
1352 </ThreadSettingsPickerStack.Navigator>
1353 </ThreadSettingsPickerPresentationContext.Provider>
1354 );
1356​
1357/** Shared model catalog and option screens, bound to the caller's draft. */
1358export function ThreadSettingsPickerScreen(
1359 props: ThreadSettingsSessionProps & { readonly onClose: () => void },
1360) {
1361 return (
1362 <ThreadSettingsSessionProvider {...props}>
1363 <ThreadSettingsPickerNavigator onClose={props.onClose} />
1364 </ThreadSettingsSessionProvider>
1365 );
1367​
1368/** Existing-thread model picker hosted by the root RNS form-sheet route. */
1369export function ExistingThreadSettingsRouteScreen() {
1370 const navigation = useNavigation<NativeStackNavigationProp<Record<string, object | undefined>>>();
1371 const presentation = useExistingThreadSettingsRoutePresentation();
1372 const session = presentation.session;
1373​
1374 useEffect(() => {
1375 if (session) {
1376 return;
1378​
1379 navigation.goBack();
1380 }, [navigation, session]);
1381​
1382 if (!session) {
1383 return <View className="flex-1 bg-sheet" />;
1385​
1386 const { ownerId: _ownerId, ...settings } = session;
1387​
1388 return <ThreadSettingsPickerScreen {...settings} onClose={() => navigation.goBack()} />;
1390​
1391/**
1392 * Native stack hosted by the New Task navigator's form-sheet route. Keeping
1393 * the sheet presentation in RNS gives UIKit ownership of nested dismissal,
1394 * while Reasoning and Runtime remain regular pushes inside this navigator.
1395 */
1396export function NewTaskThreadSettingsRouteScreen() {
1397 const flow = useNewTaskFlow();
1398 const navigation = useNavigation<NativeStackNavigationProp<Record<string, object | undefined>>>();
1399 const optionDescriptors = useMemo(
1400 () =>
1401 resolveProviderOptionDescriptors({
1402 capabilities: flow.selectedModelOption?.capabilities,
1403 selections: flow.selectedModel?.options,
1404 }),
1405 [flow.selectedModel?.options, flow.selectedModelOption?.capabilities],
1406 );
1407​
1408 return (
1409 <ThreadSettingsPickerScreen
1410 environmentId={flow.selectedEnvironmentId}
1411 providerGroups={flow.providerGroups}
1412 selectedModel={flow.selectedModel}
1413 onSelectModel={(option) => flow.setSelectedModelKey(option.key, option.selection.options)}
1414 optionDescriptors={optionDescriptors}
1415 onUpdateOptionSelections={flow.setSelectedModelOptions}
1416 runtimeMode={flow.runtimeMode}
1417 onUpdateRuntimeMode={flow.setRuntimeMode}
1418 onClose={() => navigation.goBack()}
1419 />
1420 );