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