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

ThreadSettingsSheet.tsx

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