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