Open History to see the last commit
1import type {
2 ModelSelection,
3 ProviderInteractionMode,
4 ProviderOptionDescriptor,
5 ProviderOptionSelection,
6 RuntimeMode,
7} from "@t3tools/contracts";
8import {
9 getProviderOptionCurrentLabel,
10 getProviderOptionCurrentValue,
11 getProviderOptionDescriptors,
12} from "@t3tools/shared/model";
13import * as Haptics from "expo-haptics";
14import { useCallback, useEffect, useRef, useState } from "react";
15import {
16 Modal,
17 Platform,
18 Pressable,
19 ScrollView,
20 Switch,
21 useWindowDimensions,
22 View,
23} from "react-native";
24import { useSafeAreaInsets } from "react-native-safe-area-context";
25
26import { SymbolView } from "../../components/AppSymbol";
27import { AppText as Text } from "../../components/AppText";
28import { ProviderIcon } from "../../components/ProviderIcon";
29import { cn } from "../../lib/cn";
30import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
31import { applyProviderOptionSelection, providerOptionValueLabels } from "../../lib/providerOptions";
32import { useThemeColor } from "../../lib/useThemeColor";
33import { RUNTIME_MODE_CHOICES, selectableChoices } from "./thread-settings-menu";
34import { pendingModelAfterPress } from "./thread-settings-sheet-state";
35import type { ThreadSettingsSheetCloseReason } from "./use-thread-settings-sheet-presentation";
36
37/**
38 * The everyday harnesses stay expanded; every other provider (OpenRouter
39 * catalogs and friends) folds behind its header so a 300-model catalog can't
40 * bury the list.
41 */
42const PRIMARY_PROVIDER_DRIVERS: ReadonlySet<string> = new Set(["claudeAgent", "codex"]);
43
44/**
45 * Compact "Fable 5 · Max · Auto" style summary for the composer trigger pill,
46 * covering model, provider options, runtime mode, and plan mode in one label.
47 */
48export function threadSettingsSummaryLabel(input: {
49 readonly modelLabel: string;
50 readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
51 readonly runtimeMode: RuntimeMode;
52 readonly interactionMode: ProviderInteractionMode;
53}): string {
54 const runtime = RUNTIME_MODE_CHOICES.find((choice) => choice.mode === input.runtimeMode);
55 return [
56 input.modelLabel,
57 ...providerOptionValueLabels(input.optionDescriptors),
58 ...(runtime ? [runtime.shortLabel] : []),
59 ...(input.interactionMode === "plan" ? ["Plan"] : []),
60 ].join(" · ");
61}
62
63function ModelRow(props: {
64 readonly option: ModelOption;
65 readonly selected: boolean;
66 readonly onPress: () => void;
67}) {
68 const primaryFg = useThemeColor("--color-primary-foreground");
69 return (
70 <Pressable
71 accessibilityRole="button"
72 accessibilityState={{ selected: props.selected }}
73 onPress={props.onPress}
74 // Selected rows get the same primary treatment as the submenu rows.
75 // Subtle backgrounds (bg-subtle-strong) get overridden by the OS
76 // selection chrome on iOS 26, so use the explicit high-contrast style
77 // everywhere instead.
78 className={cn(
79 "mx-2.5 flex-row items-center gap-2 rounded-xl px-3 py-3.5 active:opacity-70",
80 props.selected ? "bg-primary" : "bg-transparent",
81 )}
82 >
83 <Text
84 className={cn(
85 "shrink text-sm font-t3-medium",
86 props.selected ? "text-primary-foreground" : "text-foreground",
87 )}
88 numberOfLines={1}
89 >
90 {props.option.label}
91 </Text>
92 {props.option.isDefault ? (
93 <View className="rounded-md bg-subtle-strong px-1.5 py-0.5">
94 <Text className="text-3xs font-t3-bold text-foreground-muted">Default</Text>
95 </View>
96 ) : null}
97 {props.option.isLegacy ? (
98 <View className="rounded-md bg-subtle px-1.5 py-0.5">
99 <Text className="text-3xs font-t3-bold text-foreground-muted">Legacy</Text>
100 </View>
101 ) : null}
102 <View className="flex-1" />
103 {props.selected ? (
104 <SymbolView name="checkmark" size={14} tintColor={primaryFg} type="monochrome" />
105 ) : null}
106 </Pressable>
107 );
108}
109
110/**
111 * Provider section header with the harness logo. Secondary providers render
112 * as a tappable fold (count + chevron while collapsed); primary providers
113 * and the group holding the current selection are static headers.
114 */
115function ProviderHeader(props: {
116 readonly driver: string | undefined;
117 readonly label: string;
118 readonly collapsible: boolean;
119 readonly collapsed: boolean;
120 readonly modelCount: number;
121 readonly onToggle: () => void;
122}) {
123 const iconSubtle = useThemeColor("--color-icon-subtle");
124 return (
125 <Pressable
126 accessibilityRole={props.collapsible ? "button" : "header"}
127 accessibilityState={props.collapsible ? { expanded: !props.collapsed } : undefined}
128 accessibilityLabel={
129 props.collapsible ? `${props.label}, ${props.modelCount} models` : props.label
130 }
131 disabled={!props.collapsible}
132 onPress={props.onToggle}
133 className={cn(
134 "mx-2.5 flex-row items-center gap-2 rounded-xl px-3",
135 props.collapsible ? "py-3.5 active:opacity-70" : "pb-2 pt-4",
136 )}
137 >
138 <ProviderIcon provider={props.driver} size={15} />
139 <Text className="text-2xs font-t3-bold uppercase tracking-widest text-foreground-muted">
140 {props.label}
141 </Text>
142 {props.collapsible ? (
143 <>
144 <View className="flex-1" />
145 {props.collapsed ? (
146 <Text className="text-2xs font-t3-medium text-foreground-muted">
147 {props.modelCount}
148 </Text>
149 ) : null}
150 <SymbolView
151 name={props.collapsed ? "chevron.down" : "chevron.up"}
152 size={11}
153 tintColor={iconSubtle}
154 type="monochrome"
155 />
156 </>
157 ) : null}
158 </Pressable>
159 );
160}
161
162/** Compact row that opens a single-choice submenu panel. */
163function DisclosureRow(props: {
164 readonly label: string;
165 readonly value: string | undefined;
166 readonly disabled?: boolean;
167 readonly onPress: () => void;
168}) {
169 const iconSubtle = useThemeColor("--color-icon-subtle");
170 return (
171 <Pressable
172 accessibilityRole="button"
173 disabled={props.disabled}
174 onPress={props.onPress}
175 className={cn(
176 "flex-row items-center gap-2 px-5 py-3 active:opacity-70",
177 props.disabled && "opacity-40",
178 )}
179 >
180 <Text className="text-sm font-t3-medium text-foreground">{props.label}</Text>
181 <View className="flex-1" />
182 {props.value ? (
183 <Text className="text-sm text-foreground-muted" numberOfLines={1}>
184 {props.value}
185 </Text>
186 ) : null}
187 <SymbolView name="chevron.right" size={12} tintColor={iconSubtle} type="monochrome" />
188 </Pressable>
189 );
190}
191
192/** Single option inside a submenu panel. */
193function ChoiceRow(props: {
194 readonly label: string;
195 readonly selected: boolean;
196 readonly onPress: () => void;
197}) {
198 const primaryFg = useThemeColor("--color-primary-foreground");
199 return (
200 <Pressable
201 accessibilityRole="button"
202 accessibilityState={{ selected: props.selected }}
203 onPress={props.onPress}
204 className={cn(
205 "mx-2.5 flex-row items-center rounded-xl px-3 py-3.5 active:opacity-70",
206 props.selected ? "bg-primary" : "bg-transparent",
207 )}
208 >
209 <Text
210 className={cn(
211 "shrink text-sm font-t3-medium",
212 props.selected ? "text-primary-foreground" : "text-foreground",
213 )}
214 >
215 {props.label}
216 </Text>
217 <View className="flex-1" />
218 {props.selected ? (
219 <SymbolView name="checkmark" size={14} tintColor={primaryFg} type="monochrome" />
220 ) : null}
221 </Pressable>
222 );
223}
224
225function SwitchRow(props: {
226 readonly label: string;
227 readonly value: boolean;
228 readonly disabled?: boolean;
229 readonly onValueChange: (value: boolean) => void;
230}) {
231 const activeTrack = String(useThemeColor("--color-switch-active"));
232 const track = String(useThemeColor("--color-secondary-border"));
233 return (
234 <View
235 className={cn(
236 "flex-row items-center justify-between px-5 py-2.5",
237 props.disabled && "opacity-40",
238 )}
239 >
240 <Text className="text-sm font-t3-medium text-foreground">{props.label}</Text>
241 <Switch
242 disabled={props.disabled}
243 ios_backgroundColor={track}
244 onValueChange={props.onValueChange}
245 trackColor={{ false: track, true: activeTrack }}
246 value={props.value}
247 />
248 </View>
249 );
250}
251
252type SubmenuPage =
253 | { readonly kind: "descriptor"; readonly id: string }
254 | { readonly kind: "runtime" };
255
256/**
257 * Unified thread settings: the sheet is the provider-grouped model list
258 * (primary harnesses expanded, other providers folded, legacy behind the
259 * top-right pill) with a Save button, plus compact disclosure rows whose
260 * single-choice submenus stack in a small panel over the sheet so it never
261 * changes size. Model changes stage until Save — while staged, the settings
262 * rows edit the staged model's options and Save applies everything together.
263 *
264 * Callers control which harnesses are offered via providerGroups: an
265 * existing thread must pass only its own provider's group, since a session
266 * can't switch harness mid-thread.
267 *
268 * Rendered through an RN Modal (not the root OverlayPortal) so it also
269 * presents above natively-presented form sheets like the new-task draft.
270 * Callers must dismiss the keyboard when opening — the iOS keyboard window
271 * would otherwise cover the lower half of the sheet.
272 */
273export function ThreadSettingsSheet(props: {
274 readonly visible: boolean;
275 /**
276 * "save" = the Save/Done button (the user is finished configuring);
277 * "dismiss" = backdrop, grabber, or system back. Hosts only restore the
278 * keyboard for "save" so a stray tap outside a control never pops it.
279 */
280 readonly onClose: (reason: ThreadSettingsSheetCloseReason) => void;
281 readonly onDismissed: () => void;
282 readonly providerGroups: ReadonlyArray<ProviderGroup>;
283 readonly selectedModel: ModelSelection | null;
284 readonly onSelectModel: (option: ModelOption) => void;
285 readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
286 readonly onUpdateOptionSelections: (selections: ReadonlyArray<ProviderOptionSelection>) => void;
287 readonly runtimeMode: RuntimeMode;
288 readonly onUpdateRuntimeMode: (mode: RuntimeMode) => void;
289}) {
290 const insets = useSafeAreaInsets();
291 const { height: windowHeight } = useWindowDimensions();
292 const [showLegacyToggle, setShowLegacyToggle] = useState(false);
293 const [expandedProviders, setExpandedProviders] = useState<ReadonlySet<string>>(() => new Set());
294 const [pendingModel, setPendingModel] = useState<ModelOption | null>(null);
295 const [submenu, setSubmenu] = useState<SubmenuPage | null>(null);
296 const wasPresentedRef = useRef(false);
297 const notifyDismissed = useCallback(() => {
298 if (!wasPresentedRef.current) {
299 return;
300 }
301 wasPresentedRef.current = false;
302 props.onDismissed();
303 }, [props.onDismissed]);
304
305 // Every open starts fresh: no staged model, no submenu, legacy hidden,
306 // secondary providers folded. The sheet stays mounted between opens, so
307 // state would otherwise stick around.
308 useEffect(() => {
309 if (props.visible) {
310 wasPresentedRef.current = true;
311 setShowLegacyToggle(false);
312 setExpandedProviders(new Set());
313 setPendingModel(null);
314 setSubmenu(null);
315 } else if (Platform.OS === "android" && wasPresentedRef.current) {
316 // React Native only emits Modal.onDismiss on iOS. Android uses no exit
317 // animation below, so the post-commit effect is its dismissal boundary.
318 notifyDismissed();
319 }
320 }, [notifyDismissed, props.visible]);
321
322 const isApplied = (option: ModelOption) =>
323 option.selection.instanceId === props.selectedModel?.instanceId &&
324 option.selection.model === props.selectedModel.model;
325 // The list highlights the staged pick; Save turns it into the applied one.
326 const isDisplayed = (option: ModelOption) =>
327 pendingModel ? option.key === pendingModel.key : isApplied(option);
328
329 // While a model is staged, the settings rows describe and edit the staged
330 // model's options (kept on its pending selection); Save applies model and
331 // options together. Otherwise they edit the applied selection directly.
332 const displayedDescriptors = pendingModel
333 ? pendingModel.capabilities
334 ? getProviderOptionDescriptors({
335 caps: pendingModel.capabilities,
336 selections: pendingModel.selection.options,
337 })
338 : []
339 : props.optionDescriptors;
340
341 const hasLegacyModels = props.providerGroups.some((group) =>
342 group.models.some((model) => model.isLegacy),
343 );
344 // Legacy stays hidden unless the pill is toggled this open; a highlighted
345 // legacy model is exempted from the filter instead of forcing the whole
346 // legacy list visible.
347 const showLegacy = showLegacyToggle;
348
349 // Stable settings rows: the union of descriptors across the primary
350 // harnesses' current models (plus whatever the displayed model advertises)
351 // always renders, with unsupported rows disabled instead of vanishing when
352 // the selection changes. Keyed by label, not id — Claude and Codex use
353 // different ids for the same "Reasoning" concept.
354 const descriptorTemplate = (() => {
355 const seen = new Map<string, { type: "select" | "boolean" }>();
356 for (const group of props.providerGroups) {
357 const driver = group.models[0]?.providerDriver;
358 if (driver === undefined || !PRIMARY_PROVIDER_DRIVERS.has(driver)) {
359 continue;
360 }
361 for (const model of group.models) {
362 if (model.isLegacy) {
363 continue;
364 }
365 for (const descriptor of model.capabilities?.optionDescriptors ?? []) {
366 if (!seen.has(descriptor.label)) {
367 seen.set(descriptor.label, { type: descriptor.type });
368 }
369 }
370 }
371 }
372 for (const descriptor of displayedDescriptors) {
373 if (!seen.has(descriptor.label)) {
374 seen.set(descriptor.label, { type: descriptor.type });
375 }
376 }
377 return [...seen.entries()].map(([label, entry]) => ({ label, ...entry }));
378 })();
379
380 const handleSave = () => {
381 if (pendingModel) {
382 void Haptics.selectionAsync();
383 props.onSelectModel(pendingModel);
384 }
385 props.onClose("save");
386 };
387
388 const handleOptionChange = (id: string, value: string | boolean) => {
389 const next = applyProviderOptionSelection(displayedDescriptors, { id, value });
390 if (!next) {
391 return;
392 }
393 if (pendingModel) {
394 setPendingModel({
395 ...pendingModel,
396 selection: { ...pendingModel.selection, options: next },
397 });
398 } else {
399 props.onUpdateOptionSelections(next);
400 }
401 };
402
403 const toggleProvider = (providerKey: string) => {
404 setExpandedProviders((current) => {
405 const next = new Set(current);
406 if (!next.delete(providerKey)) {
407 next.add(providerKey);
408 }
409 return next;
410 });
411 };
412
413 const activeDescriptor =
414 submenu?.kind === "descriptor"
415 ? displayedDescriptors.find(
416 (descriptor) => descriptor.type === "select" && descriptor.id === submenu.id,
417 )
418 : undefined;
419
420 const submenuContent =
421 submenu?.kind === "runtime"
422 ? {
423 title: "Runtime",
424 rows: RUNTIME_MODE_CHOICES.map((choice) => ({
425 id: choice.mode,
426 label: choice.label,
427 selected: choice.mode === props.runtimeMode,
428 onPress: () => {
429 void Haptics.selectionAsync();
430 props.onUpdateRuntimeMode(choice.mode);
431 setSubmenu(null);
432 },
433 })),
434 }
435 : activeDescriptor?.type === "select"
436 ? {
437 title: activeDescriptor.label,
438 rows: selectableChoices(activeDescriptor).map((choice) => ({
439 id: choice.id,
440 label: choice.label,
441 selected: choice.id === getProviderOptionCurrentValue(activeDescriptor),
442 onPress: () => {
443 void Haptics.selectionAsync();
444 handleOptionChange(activeDescriptor.id, choice.id);
445 setSubmenu(null);
446 },
447 })),
448 }
449 : null;
450
451 return (
452 <Modal
453 transparent
454 statusBarTranslucent
455 navigationBarTranslucent
456 animationType={Platform.OS === "ios" ? "fade" : "none"}
457 visible={props.visible}
458 onDismiss={notifyDismissed}
459 onRequestClose={submenuContent ? () => setSubmenu(null) : () => props.onClose("dismiss")}
460 >
461 <View className="flex-1 justify-end">
462 <Pressable
463 accessibilityLabel="Close thread settings"
464 className="absolute inset-0 bg-backdrop"
465 onPress={() => props.onClose("dismiss")}
466 />
467 <View
468 className="overflow-hidden rounded-t-[24px] border border-b-0 border-border bg-sheet"
469 style={{ maxHeight: windowHeight * 0.85 }}
470 >
471 {/* The grabber doubles as the accessible close control: the dim
472 backdrop above a tall sheet is a sliver, and VoiceOver can't
473 reach it at all. */}
474 <Pressable
475 accessibilityLabel="Close thread settings"
476 accessibilityRole="button"
477 onPress={() => props.onClose("dismiss")}
478 className="items-center pb-1 pt-2.5"
479 >
480 <View className="h-1 w-9 rounded-full bg-subtle-strong" />
481 </Pressable>
482 {hasLegacyModels ? (
483 <View className="flex-row justify-end px-4 pb-1.5">
484 <Pressable
485 accessibilityRole="button"
486 accessibilityState={{ selected: showLegacy }}
487 hitSlop={8}
488 onPress={() => {
489 void Haptics.selectionAsync();
490 setShowLegacyToggle(!showLegacy);
491 }}
492 className="rounded-full border border-border bg-subtle px-3 py-1.5 active:opacity-70"
493 >
494 <Text className="text-2xs font-t3-medium text-foreground-muted">
495 {showLegacy ? "Hide legacy models" : "Show legacy models"}
496 </Text>
497 </Pressable>
498 </View>
499 ) : null}
500 {/* Only the model list scrolls. Provider catalogs can run to
501 hundreds of models (OpenRouter), so the rows below stay pinned
502 and reachable instead of living at the end of that scroll. */}
503 <ScrollView
504 style={{ flexShrink: 1 }}
505 contentContainerStyle={{ paddingBottom: 8 }}
506 showsVerticalScrollIndicator={false}
507 >
508 {props.providerGroups.map((group) => {
509 const driver = group.models[0]?.providerDriver;
510 const isPrimary = driver !== undefined && PRIMARY_PROVIDER_DRIVERS.has(driver);
511 const visibleModels = showLegacy
512 ? group.models
513 : group.models.filter((model) => !model.isLegacy || isDisplayed(model));
514 if (visibleModels.length === 0) {
515 return null;
516 }
517 const containsSelection = group.models.some(isDisplayed);
518 const collapsible = !isPrimary && !containsSelection;
519 const collapsed = collapsible && !expandedProviders.has(group.providerKey);
520 return (
521 <View key={group.providerKey}>
522 <ProviderHeader
523 driver={driver}
524 label={group.providerLabel}
525 collapsible={collapsible}
526 collapsed={collapsed}
527 modelCount={visibleModels.length}
528 onToggle={() => toggleProvider(group.providerKey)}
529 />
530 {collapsed
531 ? null
532 : visibleModels.map((option) => (
533 <ModelRow
534 key={option.key}
535 option={option}
536 selected={isDisplayed(option)}
537 onPress={() => {
538 void Haptics.selectionAsync();
539 // Re-tapping the applied model cancels staging.
540 setPendingModel((current) =>
541 pendingModelAfterPress({
542 current,
543 pressed: option,
544 pressedIsApplied: isApplied(option),
545 }),
546 );
547 }}
548 />
549 ))}
550 </View>
551 );
552 })}
553 </ScrollView>
554
555 <View className="mx-5 h-px bg-border" />
556
557 <View style={{ paddingBottom: insets.bottom + 12 }}>
558 {descriptorTemplate.map((entry) => {
559 const live = displayedDescriptors.find(
560 (descriptor) => descriptor.label === entry.label,
561 );
562 if ((live?.type ?? entry.type) === "select") {
563 return (
564 <DisclosureRow
565 key={entry.label}
566 label={entry.label}
567 value={live ? getProviderOptionCurrentLabel(live) : undefined}
568 disabled={!live}
569 onPress={() => {
570 if (live) {
571 setSubmenu({ kind: "descriptor", id: live.id });
572 }
573 }}
574 />
575 );
576 }
577 return (
578 <SwitchRow
579 key={entry.label}
580 label={entry.label}
581 value={live?.type === "boolean" ? (live.currentValue ?? false) : false}
582 disabled={!live}
583 onValueChange={(value) => {
584 if (live) {
585 handleOptionChange(live.id, value);
586 }
587 }}
588 />
589 );
590 })}
591 <DisclosureRow
592 label="Runtime"
593 value={
594 RUNTIME_MODE_CHOICES.find((choice) => choice.mode === props.runtimeMode)?.label
595 }
596 onPress={() => setSubmenu({ kind: "runtime" })}
597 />
598 <Pressable
599 accessibilityRole="button"
600 onPress={handleSave}
601 className="mx-4 mt-2 h-12 items-center justify-center rounded-full bg-primary active:opacity-80"
602 >
603 <Text className="text-sm font-t3-bold text-primary-foreground">
604 {pendingModel ? "Save" : "Done"}
605 </Text>
606 </Pressable>
607 </View>
608 </View>
609
610 {/* Submenus stack over the sheet instead of replacing its content,
611 so the main sheet keeps its size while drilling in and out. */}
612 {submenuContent ? (
613 <View className="absolute inset-0 justify-end">
614 <Pressable
615 accessibilityLabel={`Close ${submenuContent.title}`}
616 className="absolute inset-0 bg-backdrop"
617 onPress={() => setSubmenu(null)}
618 />
619 <View className="overflow-hidden rounded-t-[24px] border border-b-0 border-border bg-sheet">
620 <Pressable
621 accessibilityLabel={`Close ${submenuContent.title}`}
622 accessibilityRole="button"
623 onPress={() => setSubmenu(null)}
624 className="items-center pb-1 pt-2.5"
625 >
626 <View className="h-1 w-9 rounded-full bg-subtle-strong" />
627 </Pressable>
628 <Text className="px-5 pb-1.5 text-2xs font-t3-bold uppercase tracking-widest text-foreground-muted">
629 {submenuContent.title}
630 </Text>
631 <ScrollView
632 style={{ maxHeight: windowHeight * 0.5 }}
633 contentContainerStyle={{ paddingBottom: insets.bottom + 12 }}
634 showsVerticalScrollIndicator={false}
635 bounces={false}
636 >
637 {submenuContent.rows.map((row) => (
638 <ChoiceRow
639 key={row.id}
640 label={row.label}
641 selected={row.selected}
642 onPress={row.onPress}
643 />
644 ))}
645 </ScrollView>
646 </View>
647 </View>
648 ) : null}
649 </View>
650 </Modal>
651 );
652}