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