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