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

ThreadSettingsSheet.tsx

1,311 lines44.5 KB

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