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