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

ThreadSettingsSheet.tsx

1,419 lines48.6 KB

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