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