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