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

ThreadSettingsSheet.tsx

1,239 lines41.8 KB

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