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

ThreadSettingsSheet.tsx

1,494 lines52.0 KB

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