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