Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
feat(mobile): one sheet for model and thread settings (#5625)
Theo Browne30164cb1ba8e
diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsxindex 6b121d851..bf2dfa8f4 100644--- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx+++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx@@ -25,15 +25,12 @@ import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStriimport { ControlPill, ControlPillMenu } from "../../components/ControlPill";import { ProviderIcon } from "../../components/ProviderIcon";import { ComposerSurface } from "./ThreadComposer";+import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet";+import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation";import { makeTurnCommandMetadata } from "../../lib/commandMetadata";import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";-import {- applyProviderOptionMenuEvent,- buildProviderOptionMenuActions,- providerOptionsConfigurationLabel,- resolveProviderOptionDescriptors,-} from "../../lib/providerOptions";+import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";import {clearComposerDraftContent,@@ -43,7 +40,7 @@ import {type ComposerDraft,} from "../../state/use-composer-drafts";import { useEnvironmentServerConfig, useProjects } from "../../state/entities";-import { buildModelMenuActions, resolveSelectableModelSelection } from "../../lib/modelOptions";+import { resolveSelectableModelSelection } from "../../lib/modelOptions";import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";@@ -103,6 +100,10 @@ export function NewTaskDraftScreen(props: {const promptInputRef = useRef<ComposerEditorHandle>(null);const loadedBranchesProjectKeyRef = useRef<string | null>(null);const [isComposerFocused, setIsComposerFocused] = useState(false);+ const settingsSheetPresentation = useThreadSettingsSheetPresentation({+ editorRef: promptInputRef,+ isEditorFocused: isComposerFocused,+ });const [importingShareKey, setImportingShareKey] = useState<string | null>(null);const [isCancellingShareImport, setIsCancellingShareImport] = useState(false);const [cancelledIncomingShareId, setCancelledIncomingShareId] = useState<string | null>(null);@@ -521,7 +522,15 @@ export function NewTaskDraftScreen(props: {let focusFrame: ReturnType<typeof requestAnimationFrame> | null = null;const interaction = InteractionManager.runAfterInteractions(() => {- focusFrame = requestAnimationFrame(() => promptInputRef.current?.focus());+ focusFrame = requestAnimationFrame(() => {+ // The delayed focus can land after the settings sheet opened, which+ // would pop the keyboard underneath its modal.+ if (!settingsSheetPresentation.isActiveRef.current) {+ promptInputRef.current?.focus();+ } else {+ settingsSheetPresentation.restoreFocusAfterSave();+ }+ });});return () => {@@ -530,7 +539,11 @@ export function NewTaskDraftScreen(props: {cancelAnimationFrame(focusFrame);}};- }, [selectedProject]);+ }, [+ selectedProject,+ settingsSheetPresentation.isActiveRef,+ settingsSheetPresentation.restoreFocusAfterSave,+ ]);const environmentMenuActions = useMemo(() =>@@ -544,10 +557,6 @@ export function NewTaskDraftScreen(props: {[flow.environments, flow.selectedEnvironmentId, isIncomingShareTransferPending],);- const modelMenuActions = useMemo(- () => buildModelMenuActions(flow.providerGroups, flow.selectedModel),- [flow.providerGroups, flow.selectedModel],- );const providerOptionDescriptors = useMemo(() =>resolveProviderOptionDescriptors({@@ -557,54 +566,6 @@ export function NewTaskDraftScreen(props: {[flow.selectedModel?.options, flow.selectedModelOption?.capabilities],);- const optionsMenuActions = useMemo(- () => [- ...buildProviderOptionMenuActions(providerOptionDescriptors),- {- id: "options-runtime",- title: "Runtime",- subtitle:- flow.runtimeMode === "approval-required"- ? "Approve actions"- : flow.runtimeMode === "auto-accept-edits"- ? "Auto-accept edits"- : flow.runtimeMode === "auto"- ? "Auto"- : "Full access",- subactions: [- { id: "options:runtime:approval-required", title: "Approve actions" },- { id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },- { id: "options:runtime:auto", title: "Auto" },- { id: "options:runtime:full-access", title: "Full access" },- ].map((option) => {- const value = option.id.replace("options:runtime:", "");- return {- id: option.id,- title: option.title,- state: flow.runtimeMode === value ? ("on" as const) : undefined,- };- }),- },- {- id: "options-interaction",- title: "Interaction",- subtitle: flow.interactionMode === "plan" ? "Plan" : "Default",- subactions: [- { id: "options:interaction:default", title: "Default" },- { id: "options:interaction:plan", title: "Plan" },- ].map((option) => {- const value = option.id.replace("options:interaction:", "");- return {- id: option.id,- title: option.title,- state: flow.interactionMode === value ? ("on" as const) : undefined,- };- }),- },- ],- [flow.interactionMode, flow.runtimeMode, providerOptionDescriptors],- );-const workspaceMenuActions = useMemo(() => {const branchActions =flow.availableBranches.length === 0@@ -675,10 +636,12 @@ export function NewTaskDraftScreen(props: {flow.availableBranches.find((branch) => branch.current)?.name ??flow.availableBranches.find((branch) => branch.isDefault)?.name ??null;- const configurationLabel = useMemo(- () => providerOptionsConfigurationLabel(providerOptionDescriptors),- [providerOptionDescriptors],- );+ const settingsSummaryLabel = threadSettingsSummaryLabel({+ modelLabel: flow.selectedModelOption?.label ?? "Model",+ optionDescriptors: providerOptionDescriptors,+ runtimeMode: flow.runtimeMode,+ interactionMode: flow.interactionMode,+ });const workspaceLabel = useMemo(() =>formatWorkspaceLabel({@@ -688,13 +651,6 @@ export function NewTaskDraftScreen(props: {}),[currentBranchName, flow.selectedBranchName, flow.workspaceMode],);- function handleModelMenuAction(event: string) {- if (isIncomingShareTransferPending || !event.startsWith("model:")) {- return;- }- flow.setSelectedModelKey(event.slice("model:".length));- }-function handleEnvironmentMenuAction(event: string) {if (isIncomingShareTransferPending || !event.startsWith("environment:")) {return;@@ -702,28 +658,6 @@ export function NewTaskDraftScreen(props: {flow.selectEnvironment(EnvironmentId.make(event.slice("environment:".length)));}- function handleOptionsMenuAction(event: string) {- if (isIncomingShareTransferPending) {- return;- }- const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);- if (providerOptions) {- flow.setSelectedModelOptions(providerOptions);- return;- }- if (event.startsWith("options:runtime:")) {- flow.setRuntimeMode(- event.slice("options:runtime:".length) as Parameters<typeof flow.setRuntimeMode>[0],- );- return;- }- if (event.startsWith("options:interaction:")) {- flow.setInteractionMode(- event.slice("options:interaction:".length) as Parameters<typeof flow.setInteractionMode>[0],- );- }- }-function handleWorkspaceMenuAction(event: string) {if (isIncomingShareTransferPending) {return;@@ -930,7 +864,9 @@ export function NewTaskDraftScreen(props: {const isDarkMode = colorScheme === "dark";// Android expansion follows native editor focus so relayout cannot race// the touch gesture that opens the keyboard.- const isExpanded = !isAndroid || isComposerFocused;+ // The settings sheet dismisses the keyboard, so its flag keeps the Android+ // draft composer expanded through the blur (mirrors ThreadComposer).+ const isExpanded = !isAndroid || isComposerFocused || settingsSheetPresentation.isActive;const canStart =Boolean(flow.selectedProject) &&Boolean(flow.selectedModel) &&@@ -984,28 +920,14 @@ export function NewTaskDraftScreen(props: {showChevron={false}disabled={isIncomingShareTransferPending}/>- <ControlPillMenu- actions={modelMenuActions}- onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}- >- <ComposerToolbarTrigger- accessibilityLabel="Model"- disabled={isIncomingShareTransferPending}- iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />}- label={flow.selectedModelOption?.label ?? "Model"}- />- </ControlPillMenu>- <ControlPillMenu- actions={optionsMenuActions}- onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}- >- <ComposerToolbarTrigger- accessibilityLabel="Configuration"- disabled={isIncomingShareTransferPending}- icon="slider.horizontal.3"- label={configurationLabel}- />- </ControlPillMenu>+ <ComposerToolbarTrigger+ accessibilityLabel="Thread settings"+ disabled={isIncomingShareTransferPending}+ iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />}+ label={settingsSummaryLabel}+ maxWidth={320}+ onPress={settingsSheetPresentation.open}+ /><ControlPillMenuactions={environmentMenuActions}onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}@@ -1031,6 +953,21 @@ export function NewTaskDraftScreen(props: {</>);+ const settingsSheet = (+ <ThreadSettingsSheet+ visible={settingsSheetPresentation.isVisible}+ onClose={settingsSheetPresentation.close}+ onDismissed={settingsSheetPresentation.onDismissed}+ providerGroups={flow.providerGroups}+ selectedModel={flow.selectedModel}+ onSelectModel={(option) => flow.setSelectedModelKey(option.key, option.selection.options)}+ optionDescriptors={providerOptionDescriptors}+ onUpdateOptionSelections={flow.setSelectedModelOptions}+ runtimeMode={flow.runtimeMode}+ onUpdateRuntimeMode={flow.setRuntimeMode}+ />+ );+const startButton = (<ComposerToolbarButtonaccessibilityLabel={@@ -1120,6 +1057,7 @@ export function NewTaskDraftScreen(props: {) : null}</View></KeyboardAvoidingView>+ {settingsSheet}</View>);}@@ -1153,6 +1091,7 @@ export function NewTaskDraftScreen(props: {</ComposerToolbarRow></View></KeyboardAvoidingView>+ {settingsSheet}</View>);}diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsxindex 1b026964c..c846dca28 100644--- a/apps/mobile/src/features/threads/ThreadComposer.tsx+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx@@ -51,10 +51,10 @@ import {ComposerToolbarScroller,ComposerToolbarTrigger,} from "../../components/ComposerToolbarTrigger";-import { ControlPill, ControlPillMenu } from "../../components/ControlPill";+import { ControlPill } from "../../components/ControlPill";import { ProviderIcon } from "../../components/ProviderIcon";import type { DraftComposerImageAttachment } from "../../lib/composerImages";-import { buildModelMenuActions, buildModelOptions, groupByProvider } from "../../lib/modelOptions";+import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";import type { RemoteClientConnectionState } from "../../lib/connection";import {@@ -62,14 +62,11 @@ import {normalizeSearchQuery,scoreQueryMatch,} from "@t3tools/shared/searchRanking";-import {- applyProviderOptionMenuEvent,- buildProviderOptionMenuActions,- providerOptionsConfigurationLabel,- resolveProviderOptionDescriptors,-} from "../../lib/providerOptions";+import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";import { useComposerPathSearch } from "../../state/use-composer-path-search";import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";+import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet";+import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation";/*** Height of the collapsed composer (pill + vertical padding, excluding safe-area inset).@@ -273,15 +270,28 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerconst fallbackInputRef = useRef<ComposerEditorHandle>(null);const inputRef = props.editorRef ?? fallbackInputRef;const [isFocused, setIsFocused] = useState(false);+ const settingsSheetPresentation = useThreadSettingsSheetPresentation({+ editorRef: inputRef,+ isEditorFocused: isFocused,+ });const wasExpandedBeforePreviewRef = useRef(false);const inFlightThreadIdsRef = useRef(new Set<string>());const { onExpandedChange } = props;const [previewImageUri, setPreviewImageUri] = useState<string | null>(null);const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;- const isExpanded = isFocused;+ // Opening and closing count as active so the composer stays expanded while+ // focus moves between its native editor and the settings modal.+ const isExpanded = isFocused || settingsSheetPresentation.isActive;const canSend = hasContent;+ // Notify the parent from the derived value, not focus events: the parent+ // sizes the feed inset from this, and blur-during-sheet would otherwise+ // report collapsed while the composer still renders expanded.+ useEffect(() => {+ onExpandedChange?.(isExpanded);+ }, [isExpanded, onExpandedChange]);+const onPressImage = useCallback((uri: string) => {wasExpandedBeforePreviewRef.current = isFocused;@@ -299,13 +309,11 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerconst handleFocus = useCallback(() => {setIsFocused(true);- onExpandedChange?.(true);- }, [onExpandedChange]);+ }, []);const handleBlur = useCallback(() => {setIsFocused(false);- onExpandedChange?.(false);- }, [onExpandedChange]);+ }, []);const showStopAction =props.selectedThread.session?.status === "running" ||props.selectedThread.session?.status === "starting";@@ -588,6 +596,12 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer[props.serverConfig, currentModelSelection],);const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);+ // An existing thread is bound to its harness: sessions can't move between+ // provider instances, so the picker only offers the thread's own group.+ const threadProviderGroups = useMemo(+ () => providerGroups.filter((group) => group.providerKey === currentModelSelection.instanceId),+ [providerGroups, currentModelSelection.instanceId],+ );const currentModelOption =modelOptions.find((option) =>@@ -602,95 +616,12 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer}),[currentModelOption?.capabilities, currentModelSelection.options],);- const configurationLabel = useMemo(- () => providerOptionsConfigurationLabel(providerOptionDescriptors),- [providerOptionDescriptors],- );- const modelMenuActions = useMemo(- () => buildModelMenuActions(providerGroups, currentModelSelection),- [providerGroups, currentModelSelection],- );-- // ── Options menu ─────────────────────────────────────────- const optionsMenuActions = useMemo(- () => [- ...buildProviderOptionMenuActions(providerOptionDescriptors),- {- id: "options-runtime",- title: "Runtime",- subtitle:- currentRuntimeMode === "approval-required"- ? "Approve actions"- : currentRuntimeMode === "auto-accept-edits"- ? "Auto-accept edits"- : currentRuntimeMode === "auto"- ? "Auto"- : "Full access",- subactions: [- { id: "options:runtime:approval-required", title: "Approve actions" },- { id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },- { id: "options:runtime:auto", title: "Auto" },- { id: "options:runtime:full-access", title: "Full access" },- ].map((option) => {- const value = option.id.replace("options:runtime:", "");- return {- id: option.id,- title: option.title,- state: currentRuntimeMode === value ? ("on" as const) : undefined,- };- }),- },- {- id: "options-interaction",- title: "Interaction",- subtitle: currentInteractionMode === "plan" ? "Plan" : "Default",- subactions: [- { id: "options:interaction:default", title: "Default" },- { id: "options:interaction:plan", title: "Plan" },- ].map((option) => {- const value = option.id.replace("options:interaction:", "");- return {- id: option.id,- title: option.title,- state: currentInteractionMode === value ? ("on" as const) : undefined,- };- }),- },- ],- [currentInteractionMode, currentRuntimeMode, providerOptionDescriptors],- );-- // ── Menu handlers ────────────────────────────────────────- function handleModelMenuAction(event: string) {- if (!event.startsWith("model:")) {- return;- }- const modelKey = event.slice("model:".length);- const option = modelOptions.find((o) => o.key === modelKey);- if (option) {- props.onUpdateModelSelection(option.selection);- }- }-- function handleOptionsMenuAction(event: string) {- const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);- if (providerOptions) {- props.onUpdateModelSelection({- ...currentModelSelection,- options: providerOptions,- });- return;- }- if (event.startsWith("options:runtime:")) {- const runtimeMode = event.slice("options:runtime:".length) as RuntimeMode;- props.onUpdateRuntimeMode(runtimeMode);- return;- }- if (event.startsWith("options:interaction:")) {- const interactionMode = event.slice("options:interaction:".length) as ProviderInteractionMode;- props.onUpdateInteractionMode(interactionMode);- }- }+ const settingsSummaryLabel = threadSettingsSummaryLabel({+ modelLabel: currentModelOption?.label ?? currentModelSelection.model,+ optionDescriptors: providerOptionDescriptors,+ runtimeMode: currentRuntimeMode,+ interactionMode: currentInteractionMode,+ });return (<Animated.View@@ -861,28 +792,15 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposeronPress={() => void props.onPickDraftImages()}showChevron={false}/>- <ControlPillMenu- actions={modelMenuActions}- onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}- >- <ComposerToolbarTrigger- accessibilityLabel="Model"- iconNode={- <ProviderIcon provider={currentModelOption?.providerDriver} size={16} />- }- label={currentModelOption?.label ?? currentModelSelection.model}- />- </ControlPillMenu>- <ControlPillMenu- actions={optionsMenuActions}- onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}- >- <ComposerToolbarTrigger- accessibilityLabel="Configuration"- icon="slider.horizontal.3"- label={configurationLabel}- />- </ControlPillMenu>+ <ComposerToolbarTrigger+ accessibilityLabel="Thread settings"+ iconNode={+ <ProviderIcon provider={currentModelOption?.providerDriver} size={16} />+ }+ label={settingsSummaryLabel}+ maxWidth={320}+ onPress={settingsSheetPresentation.open}+ />{showStopAction ? (<ComposerToolbarButtonaccessibilityLabel="Stop"@@ -916,6 +834,21 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer) : null}</Animated.View>+ <ThreadSettingsSheet+ visible={settingsSheetPresentation.isVisible}+ onClose={settingsSheetPresentation.close}+ onDismissed={settingsSheetPresentation.onDismissed}+ providerGroups={threadProviderGroups}+ selectedModel={currentModelSelection}+ onSelectModel={(option) => props.onUpdateModelSelection(option.selection)}+ optionDescriptors={providerOptionDescriptors}+ onUpdateOptionSelections={(options) =>+ props.onUpdateModelSelection({ ...currentModelSelection, options })+ }+ runtimeMode={currentRuntimeMode}+ onUpdateRuntimeMode={props.onUpdateRuntimeMode}+ />+<ImageViewingimages={previewImageUri ? [{ uri: previewImageUri }] : []}imageIndex={0}diff --git a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsxnew file mode 100644index 000000000..9c27e6f01--- /dev/null+++ b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx@@ -0,0 +1,678 @@+import type {+ ModelSelection,+ ProviderInteractionMode,+ ProviderOptionDescriptor,+ ProviderOptionSelection,+ RuntimeMode,+} from "@t3tools/contracts";+import {+ getProviderOptionCurrentLabel,+ getProviderOptionCurrentValue,+ getProviderOptionDescriptors,+} from "@t3tools/shared/model";+import * as Haptics from "expo-haptics";+import { useCallback, useEffect, useRef, useState } from "react";+import {+ Modal,+ Platform,+ Pressable,+ ScrollView,+ Switch,+ useWindowDimensions,+ View,+} from "react-native";+import { useSafeAreaInsets } from "react-native-safe-area-context";++import { SymbolView } from "../../components/AppSymbol";+import { AppText as Text } from "../../components/AppText";+import { ProviderIcon } from "../../components/ProviderIcon";+import { cn } from "../../lib/cn";+import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";+import { applyProviderOptionSelection, providerOptionValueLabels } from "../../lib/providerOptions";+import { useThemeColor } from "../../lib/useThemeColor";+import { pendingModelAfterPress } from "./thread-settings-sheet-state";+import type { ThreadSettingsSheetCloseReason } from "./use-thread-settings-sheet-presentation";++/**+ * The everyday harnesses stay expanded; every other provider (OpenRouter+ * catalogs and friends) folds behind its header so a 300-model catalog can't+ * bury the list.+ */+const PRIMARY_PROVIDER_DRIVERS: ReadonlySet<string> = new Set(["claudeAgent", "codex"]);++/**+ * Desktop-oriented effort keywords that don't belong in the phone picker.+ * Prompt-injected values (ultrathink and friends) are filtered from the+ * descriptor metadata; ultracode is a real option but a workflow trigger, not+ * a reasoning level. A value set elsewhere still displays, it just isn't+ * offered.+ */+const HIDDEN_EFFORT_OPTION_IDS: ReadonlySet<string> = new Set(["ultracode"]);++const RUNTIME_MODE_CHOICES: ReadonlyArray<{+ readonly mode: RuntimeMode;+ readonly label: string;+ readonly shortLabel: string;+}> = [+ { mode: "approval-required", label: "Approve actions", shortLabel: "Approve" },+ { mode: "auto-accept-edits", label: "Auto-accept edits", shortLabel: "Edits" },+ { mode: "auto", label: "Auto", shortLabel: "Auto" },+ { mode: "full-access", label: "Full access", shortLabel: "Full" },+];++/**+ * Compact "Fable 5 · Max · Auto" style summary for the composer trigger pill,+ * covering model, provider options, runtime mode, and plan mode in one label.+ */+export function threadSettingsSummaryLabel(input: {+ readonly modelLabel: string;+ readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;+ readonly runtimeMode: RuntimeMode;+ readonly interactionMode: ProviderInteractionMode;+}): string {+ const runtime = RUNTIME_MODE_CHOICES.find((choice) => choice.mode === input.runtimeMode);+ return [+ input.modelLabel,+ ...providerOptionValueLabels(input.optionDescriptors),+ ...(runtime ? [runtime.shortLabel] : []),+ ...(input.interactionMode === "plan" ? ["Plan"] : []),+ ].join(" · ");+}++function selectableChoices(descriptor: Extract<ProviderOptionDescriptor, { type: "select" }>) {+ const injected = new Set(descriptor.promptInjectedValues ?? []);+ return descriptor.options.filter(+ (option) => !injected.has(option.id) && !HIDDEN_EFFORT_OPTION_IDS.has(option.id),+ );+}++function ModelRow(props: {+ readonly option: ModelOption;+ readonly selected: boolean;+ readonly onPress: () => void;+}) {+ const primaryFg = useThemeColor("--color-primary-foreground");+ return (+ <Pressable+ accessibilityRole="button"+ accessibilityState={{ selected: props.selected }}+ onPress={props.onPress}+ // Selected rows get the same primary treatment as the submenu rows.+ // Subtle backgrounds (bg-subtle-strong) get overridden by the OS+ // selection chrome on iOS 26, so use the explicit high-contrast style+ // everywhere instead.+ className={cn(+ "mx-2.5 flex-row items-center gap-2 rounded-xl px-3 py-3.5 active:opacity-70",+ props.selected ? "bg-primary" : "bg-transparent",+ )}+ >+ <Text+ className={cn(+ "shrink text-sm font-t3-medium",+ props.selected ? "text-primary-foreground" : "text-foreground",+ )}+ numberOfLines={1}+ >+ {props.option.label}+ </Text>+ {props.option.isDefault ? (+ <View className="rounded-md bg-subtle-strong px-1.5 py-0.5">+ <Text className="text-3xs font-t3-bold text-foreground-muted">Default</Text>+ </View>+ ) : null}+ {props.option.isLegacy ? (+ <View className="rounded-md bg-subtle px-1.5 py-0.5">+ <Text className="text-3xs font-t3-bold text-foreground-muted">Legacy</Text>+ </View>+ ) : null}+ <View className="flex-1" />+ {props.selected ? (+ <SymbolView name="checkmark" size={14} tintColor={primaryFg} type="monochrome" />+ ) : null}+ </Pressable>+ );+}++/**+ * Provider section header with the harness logo. Secondary providers render+ * as a tappable fold (count + chevron while collapsed); primary providers+ * and the group holding the current selection are static headers.+ */+function ProviderHeader(props: {+ readonly driver: string | undefined;+ readonly label: string;+ readonly collapsible: boolean;+ readonly collapsed: boolean;+ readonly modelCount: number;+ readonly onToggle: () => void;+}) {+ const iconSubtle = useThemeColor("--color-icon-subtle");+ return (+ <Pressable+ accessibilityRole={props.collapsible ? "button" : "header"}+ accessibilityState={props.collapsible ? { expanded: !props.collapsed } : undefined}+ accessibilityLabel={+ props.collapsible ? `${props.label}, ${props.modelCount} models` : props.label+ }+ disabled={!props.collapsible}+ onPress={props.onToggle}+ className={cn(+ "mx-2.5 flex-row items-center gap-2 rounded-xl px-3",+ props.collapsible ? "py-3.5 active:opacity-70" : "pb-2 pt-4",+ )}+ >+ <ProviderIcon provider={props.driver} size={15} />+ <Text className="text-2xs font-t3-bold uppercase tracking-widest text-foreground-muted">+ {props.label}+ </Text>+ {props.collapsible ? (+ <>+ <View className="flex-1" />+ {props.collapsed ? (+ <Text className="text-2xs font-t3-medium text-foreground-muted">+ {props.modelCount}+ </Text>+ ) : null}+ <SymbolView+ name={props.collapsed ? "chevron.down" : "chevron.up"}+ size={11}+ tintColor={iconSubtle}+ type="monochrome"+ />+ </>+ ) : null}+ </Pressable>+ );+}++/** Compact row that opens a single-choice submenu panel. */+function DisclosureRow(props: {+ readonly label: string;+ readonly value: string | undefined;+ readonly disabled?: boolean;+ readonly onPress: () => void;+}) {+ const iconSubtle = useThemeColor("--color-icon-subtle");+ return (+ <Pressable+ accessibilityRole="button"+ disabled={props.disabled}+ onPress={props.onPress}+ className={cn(+ "flex-row items-center gap-2 px-5 py-3 active:opacity-70",+ props.disabled && "opacity-40",+ )}+ >+ <Text className="text-sm font-t3-medium text-foreground">{props.label}</Text>+ <View className="flex-1" />+ {props.value ? (+ <Text className="text-sm text-foreground-muted" numberOfLines={1}>+ {props.value}+ </Text>+ ) : null}+ <SymbolView name="chevron.right" size={12} tintColor={iconSubtle} type="monochrome" />+ </Pressable>+ );+}++/** Single option inside a submenu panel. */+function ChoiceRow(props: {+ readonly label: string;+ readonly selected: boolean;+ readonly onPress: () => void;+}) {+ const primaryFg = useThemeColor("--color-primary-foreground");+ return (+ <Pressable+ accessibilityRole="button"+ accessibilityState={{ selected: props.selected }}+ onPress={props.onPress}+ className={cn(+ "mx-2.5 flex-row items-center rounded-xl px-3 py-3.5 active:opacity-70",+ props.selected ? "bg-primary" : "bg-transparent",+ )}+ >+ <Text+ className={cn(+ "shrink text-sm font-t3-medium",+ props.selected ? "text-primary-foreground" : "text-foreground",+ )}+ >+ {props.label}+ </Text>+ <View className="flex-1" />+ {props.selected ? (+ <SymbolView name="checkmark" size={14} tintColor={primaryFg} type="monochrome" />+ ) : null}+ </Pressable>+ );+}++function SwitchRow(props: {+ readonly label: string;+ readonly value: boolean;+ readonly disabled?: boolean;+ readonly onValueChange: (value: boolean) => void;+}) {+ const activeTrack = String(useThemeColor("--color-switch-active"));+ const track = String(useThemeColor("--color-secondary-border"));+ return (+ <View+ className={cn(+ "flex-row items-center justify-between px-5 py-2.5",+ props.disabled && "opacity-40",+ )}+ >+ <Text className="text-sm font-t3-medium text-foreground">{props.label}</Text>+ <Switch+ disabled={props.disabled}+ ios_backgroundColor={track}+ onValueChange={props.onValueChange}+ trackColor={{ false: track, true: activeTrack }}+ value={props.value}+ />+ </View>+ );+}++type SubmenuPage =+ | { readonly kind: "descriptor"; readonly id: string }+ | { readonly kind: "runtime" };++/**+ * Unified thread settings: the sheet is the provider-grouped model list+ * (primary harnesses expanded, other providers folded, legacy behind the+ * top-right pill) with a Save button, plus compact disclosure rows whose+ * single-choice submenus stack in a small panel over the sheet so it never+ * changes size. Model changes stage until Save — while staged, the settings+ * rows edit the staged model's options and Save applies everything together.+ *+ * Callers control which harnesses are offered via providerGroups: an+ * existing thread must pass only its own provider's group, since a session+ * can't switch harness mid-thread.+ *+ * Rendered through an RN Modal (not the root OverlayPortal) so it also+ * presents above natively-presented form sheets like the new-task draft.+ * Callers must dismiss the keyboard when opening — the iOS keyboard window+ * would otherwise cover the lower half of the sheet.+ */+export function ThreadSettingsSheet(props: {+ readonly visible: boolean;+ /**+ * "save" = the Save/Done button (the user is finished configuring);+ * "dismiss" = backdrop, grabber, or system back. Hosts only restore the+ * keyboard for "save" so a stray tap outside a control never pops it.+ */+ readonly onClose: (reason: ThreadSettingsSheetCloseReason) => void;+ readonly onDismissed: () => void;+ readonly providerGroups: ReadonlyArray<ProviderGroup>;+ readonly selectedModel: ModelSelection | null;+ readonly onSelectModel: (option: ModelOption) => void;+ readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;+ readonly onUpdateOptionSelections: (selections: ReadonlyArray<ProviderOptionSelection>) => void;+ readonly runtimeMode: RuntimeMode;+ readonly onUpdateRuntimeMode: (mode: RuntimeMode) => void;+}) {+ const insets = useSafeAreaInsets();+ const { height: windowHeight } = useWindowDimensions();+ const [showLegacyToggle, setShowLegacyToggle] = useState(false);+ const [expandedProviders, setExpandedProviders] = useState<ReadonlySet<string>>(() => new Set());+ const [pendingModel, setPendingModel] = useState<ModelOption | null>(null);+ const [submenu, setSubmenu] = useState<SubmenuPage | null>(null);+ const wasPresentedRef = useRef(false);+ const notifyDismissed = useCallback(() => {+ if (!wasPresentedRef.current) {+ return;+ }+ wasPresentedRef.current = false;+ props.onDismissed();+ }, [props.onDismissed]);++ // Every open starts fresh: no staged model, no submenu, legacy hidden,+ // secondary providers folded. The sheet stays mounted between opens, so+ // state would otherwise stick around.+ useEffect(() => {+ if (props.visible) {+ wasPresentedRef.current = true;+ setShowLegacyToggle(false);+ setExpandedProviders(new Set());+ setPendingModel(null);+ setSubmenu(null);+ } else if (Platform.OS === "android" && wasPresentedRef.current) {+ // React Native only emits Modal.onDismiss on iOS. Android uses no exit+ // animation below, so the post-commit effect is its dismissal boundary.+ notifyDismissed();+ }+ }, [notifyDismissed, props.visible]);++ const isApplied = (option: ModelOption) =>+ option.selection.instanceId === props.selectedModel?.instanceId &&+ option.selection.model === props.selectedModel.model;+ // The list highlights the staged pick; Save turns it into the applied one.+ const isDisplayed = (option: ModelOption) =>+ pendingModel ? option.key === pendingModel.key : isApplied(option);++ // While a model is staged, the settings rows describe and edit the staged+ // model's options (kept on its pending selection); Save applies model and+ // options together. Otherwise they edit the applied selection directly.+ const displayedDescriptors = pendingModel+ ? pendingModel.capabilities+ ? getProviderOptionDescriptors({+ caps: pendingModel.capabilities,+ selections: pendingModel.selection.options,+ })+ : []+ : props.optionDescriptors;++ const hasLegacyModels = props.providerGroups.some((group) =>+ group.models.some((model) => model.isLegacy),+ );+ // Legacy stays hidden unless the pill is toggled this open; a highlighted+ // legacy model is exempted from the filter instead of forcing the whole+ // legacy list visible.+ const showLegacy = showLegacyToggle;++ // Stable settings rows: the union of descriptors across the primary+ // harnesses' current models (plus whatever the displayed model advertises)+ // always renders, with unsupported rows disabled instead of vanishing when+ // the selection changes. Keyed by label, not id — Claude and Codex use+ // different ids for the same "Reasoning" concept.+ const descriptorTemplate = (() => {+ const seen = new Map<string, { type: "select" | "boolean" }>();+ for (const group of props.providerGroups) {+ const driver = group.models[0]?.providerDriver;+ if (driver === undefined || !PRIMARY_PROVIDER_DRIVERS.has(driver)) {+ continue;+ }+ for (const model of group.models) {+ if (model.isLegacy) {+ continue;+ }+ for (const descriptor of model.capabilities?.optionDescriptors ?? []) {+ if (!seen.has(descriptor.label)) {+ seen.set(descriptor.label, { type: descriptor.type });+ }+ }+ }+ }+ for (const descriptor of displayedDescriptors) {+ if (!seen.has(descriptor.label)) {+ seen.set(descriptor.label, { type: descriptor.type });+ }+ }+ return [...seen.entries()].map(([label, entry]) => ({ label, ...entry }));+ })();++ const handleSave = () => {+ if (pendingModel) {+ void Haptics.selectionAsync();+ props.onSelectModel(pendingModel);+ }+ props.onClose("save");+ };++ const handleOptionChange = (id: string, value: string | boolean) => {+ const next = applyProviderOptionSelection(displayedDescriptors, { id, value });+ if (!next) {+ return;+ }+ if (pendingModel) {+ setPendingModel({+ ...pendingModel,+ selection: { ...pendingModel.selection, options: next },+ });+ } else {+ props.onUpdateOptionSelections(next);+ }+ };++ const toggleProvider = (providerKey: string) => {+ setExpandedProviders((current) => {+ const next = new Set(current);+ if (!next.delete(providerKey)) {+ next.add(providerKey);+ }+ return next;+ });+ };++ const activeDescriptor =+ submenu?.kind === "descriptor"+ ? displayedDescriptors.find(+ (descriptor) => descriptor.type === "select" && descriptor.id === submenu.id,+ )+ : undefined;++ const submenuContent =+ submenu?.kind === "runtime"+ ? {+ title: "Runtime",+ rows: RUNTIME_MODE_CHOICES.map((choice) => ({+ id: choice.mode,+ label: choice.label,+ selected: choice.mode === props.runtimeMode,+ onPress: () => {+ void Haptics.selectionAsync();+ props.onUpdateRuntimeMode(choice.mode);+ setSubmenu(null);+ },+ })),+ }+ : activeDescriptor?.type === "select"+ ? {+ title: activeDescriptor.label,+ rows: selectableChoices(activeDescriptor).map((choice) => ({+ id: choice.id,+ label: choice.label,+ selected: choice.id === getProviderOptionCurrentValue(activeDescriptor),+ onPress: () => {+ void Haptics.selectionAsync();+ handleOptionChange(activeDescriptor.id, choice.id);+ setSubmenu(null);+ },+ })),+ }+ : null;++ return (+ <Modal+ transparent+ statusBarTranslucent+ navigationBarTranslucent+ animationType={Platform.OS === "ios" ? "fade" : "none"}+ visible={props.visible}+ onDismiss={notifyDismissed}+ onRequestClose={submenuContent ? () => setSubmenu(null) : () => props.onClose("dismiss")}+ >+ <View className="flex-1 justify-end">+ <Pressable+ accessibilityLabel="Close thread settings"+ className="absolute inset-0 bg-backdrop"+ onPress={() => props.onClose("dismiss")}+ />+ <View+ className="overflow-hidden rounded-t-[24px] border border-b-0 border-border bg-sheet"+ style={{ maxHeight: windowHeight * 0.85 }}+ >+ {/* The grabber doubles as the accessible close control: the dim+ backdrop above a tall sheet is a sliver, and VoiceOver can't+ reach it at all. */}+ <Pressable+ accessibilityLabel="Close thread settings"+ accessibilityRole="button"+ onPress={() => props.onClose("dismiss")}+ className="items-center pb-1 pt-2.5"+ >+ <View className="h-1 w-9 rounded-full bg-subtle-strong" />+ </Pressable>+ {hasLegacyModels ? (+ <View className="flex-row justify-end px-4 pb-1.5">+ <Pressable+ accessibilityRole="button"+ accessibilityState={{ selected: showLegacy }}+ hitSlop={8}+ onPress={() => {+ void Haptics.selectionAsync();+ setShowLegacyToggle(!showLegacy);+ }}+ className="rounded-full border border-border bg-subtle px-3 py-1.5 active:opacity-70"+ >+ <Text className="text-2xs font-t3-medium text-foreground-muted">+ {showLegacy ? "Hide legacy models" : "Show legacy models"}+ </Text>+ </Pressable>+ </View>+ ) : null}+ {/* Only the model list scrolls. Provider catalogs can run to+ hundreds of models (OpenRouter), so the rows below stay pinned+ and reachable instead of living at the end of that scroll. */}+ <ScrollView+ style={{ flexShrink: 1 }}+ contentContainerStyle={{ paddingBottom: 8 }}+ showsVerticalScrollIndicator={false}+ >+ {props.providerGroups.map((group) => {+ const driver = group.models[0]?.providerDriver;+ const isPrimary = driver !== undefined && PRIMARY_PROVIDER_DRIVERS.has(driver);+ const visibleModels = showLegacy+ ? group.models+ : group.models.filter((model) => !model.isLegacy || isDisplayed(model));+ if (visibleModels.length === 0) {+ return null;+ }+ const containsSelection = group.models.some(isDisplayed);+ const collapsible = !isPrimary && !containsSelection;+ const collapsed = collapsible && !expandedProviders.has(group.providerKey);+ return (+ <View key={group.providerKey}>+ <ProviderHeader+ driver={driver}+ label={group.providerLabel}+ collapsible={collapsible}+ collapsed={collapsed}+ modelCount={visibleModels.length}+ onToggle={() => toggleProvider(group.providerKey)}+ />+ {collapsed+ ? null+ : visibleModels.map((option) => (+ <ModelRow+ key={option.key}+ option={option}+ selected={isDisplayed(option)}+ onPress={() => {+ void Haptics.selectionAsync();+ // Re-tapping the applied model cancels staging.+ setPendingModel((current) =>+ pendingModelAfterPress({+ current,+ pressed: option,+ pressedIsApplied: isApplied(option),+ }),+ );+ }}+ />+ ))}+ </View>+ );+ })}+ </ScrollView>++ <View className="mx-5 h-px bg-border" />++ <View style={{ paddingBottom: insets.bottom + 12 }}>+ {descriptorTemplate.map((entry) => {+ const live = displayedDescriptors.find(+ (descriptor) => descriptor.label === entry.label,+ );+ if ((live?.type ?? entry.type) === "select") {+ return (+ <DisclosureRow+ key={entry.label}+ label={entry.label}+ value={live ? getProviderOptionCurrentLabel(live) : undefined}+ disabled={!live}+ onPress={() => {+ if (live) {+ setSubmenu({ kind: "descriptor", id: live.id });+ }+ }}+ />+ );+ }+ return (+ <SwitchRow+ key={entry.label}+ label={entry.label}+ value={live?.type === "boolean" ? (live.currentValue ?? false) : false}+ disabled={!live}+ onValueChange={(value) => {+ if (live) {+ handleOptionChange(live.id, value);+ }+ }}+ />+ );+ })}+ <DisclosureRow+ label="Runtime"+ value={+ RUNTIME_MODE_CHOICES.find((choice) => choice.mode === props.runtimeMode)?.label+ }+ onPress={() => setSubmenu({ kind: "runtime" })}+ />+ <Pressable+ accessibilityRole="button"+ onPress={handleSave}+ className="mx-4 mt-2 h-12 items-center justify-center rounded-full bg-primary active:opacity-80"+ >+ <Text className="text-sm font-t3-bold text-primary-foreground">+ {pendingModel ? "Save" : "Done"}+ </Text>+ </Pressable>+ </View>+ </View>++ {/* Submenus stack over the sheet instead of replacing its content,+ so the main sheet keeps its size while drilling in and out. */}+ {submenuContent ? (+ <View className="absolute inset-0 justify-end">+ <Pressable+ accessibilityLabel={`Close ${submenuContent.title}`}+ className="absolute inset-0 bg-backdrop"+ onPress={() => setSubmenu(null)}+ />+ <View className="overflow-hidden rounded-t-[24px] border border-b-0 border-border bg-sheet">+ <Pressable+ accessibilityLabel={`Close ${submenuContent.title}`}+ accessibilityRole="button"+ onPress={() => setSubmenu(null)}+ className="items-center pb-1 pt-2.5"+ >+ <View className="h-1 w-9 rounded-full bg-subtle-strong" />+ </Pressable>+ <Text className="px-5 pb-1.5 text-2xs font-t3-bold uppercase tracking-widest text-foreground-muted">+ {submenuContent.title}+ </Text>+ <ScrollView+ style={{ maxHeight: windowHeight * 0.5 }}+ contentContainerStyle={{ paddingBottom: insets.bottom + 12 }}+ showsVerticalScrollIndicator={false}+ bounces={false}+ >+ {submenuContent.rows.map((row) => (+ <ChoiceRow+ key={row.id}+ label={row.label}+ selected={row.selected}+ onPress={row.onPress}+ />+ ))}+ </ScrollView>+ </View>+ </View>+ ) : null}+ </View>+ </Modal>+ );+}diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsxindex 18bacd125..e3170eef0 100644--- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx+++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx@@ -25,6 +25,7 @@ import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";import {buildModelOptions,groupByProvider,+ resolveDefaultableModelSelection,resolveSelectableModelSelection,} from "../../lib/modelOptions";import { scopedProjectKey } from "../../lib/scopedEntities";@@ -147,7 +148,10 @@ type NewTaskFlowContextValue = {readonly reset: () => void;readonly setProject: (project: EnvironmentProject) => void;readonly selectEnvironment: (environmentId: EnvironmentId) => void;- readonly setSelectedModelKey: (key: string | null) => void;+ readonly setSelectedModelKey: (+ key: string | null,+ options?: ReadonlyArray<ProviderOptionSelection>,+ ) => void;readonly setWorkspaceMode: (mode: WorkspaceMode) => void;readonly selectBranch: (branch: VcsRef) => void;readonly setStartFromOrigin: (value: boolean) => void;@@ -359,14 +363,16 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;- // Stored selections (draft and project default) only count while their- // provider is usable on the server; otherwise the server's default model- // wins instead of silently targeting a disabled provider.+ // Stored selections only count while their provider is usable on the+ // server; otherwise the server's default model wins instead of silently+ // targeting a disabled provider. The draft selection is an explicit pick+ // and passes through as-is; the project default (last used, possibly from+ // desktop) is implicit and additionally never resolves to a legacy model.const draftModelSelection = resolveSelectableModelSelection(selectedEnvironmentServerConfig,selectedProjectDraft.modelSelection ?? null,);- const projectDefaultModelSelection = resolveSelectableModelSelection(+ const projectDefaultModelSelection = resolveDefaultableModelSelection(selectedEnvironmentServerConfig,selectedProject?.defaultModelSelection ?? null,);@@ -404,7 +410,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {[selectedEnvironmentServerConfig, selectedModel?.instanceId],);const setSelectedModelKey = useCallback(- (key: string | null) => {+ // Options ride along in the same write: a follow-up setSelectedModelOptions+ // call would rebuild the selection from the stale pre-switch model.+ (key: string | null, options?: ReadonlyArray<ProviderOptionSelection>) => {if (!key || !selectedProjectDraftKey) {return;}@@ -413,7 +421,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {return;}updateComposerDraftSettings(selectedProjectDraftKey, {- modelSelection: option.selection,+ modelSelection: options ? { ...option.selection, options } : option.selection,});},[modelOptions, selectedProjectDraftKey],diff --git a/apps/mobile/src/features/threads/thread-settings-sheet-state.test.ts b/apps/mobile/src/features/threads/thread-settings-sheet-state.test.tsnew file mode 100644index 000000000..1264c75cd--- /dev/null+++ b/apps/mobile/src/features/threads/thread-settings-sheet-state.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from "vite-plus/test";++import { ProviderInstanceId, type ProviderOptionSelection } from "@t3tools/contracts";++import type { ModelOption } from "../../lib/modelOptions";+import { pendingModelAfterPress } from "./thread-settings-sheet-state";++function modelOption(+ model: string,+ options: ReadonlyArray<ProviderOptionSelection> = [],+): ModelOption {+ return {+ key: `codex:${model}`,+ label: model,+ subtitle: "Codex",+ providerKey: "codex",+ providerLabel: "Codex",+ providerDriver: "codex",+ isDefault: false,+ isLegacy: false,+ capabilities: null,+ selection: {+ instanceId: ProviderInstanceId.make("codex"),+ model,+ options,+ },+ };+}++describe("thread settings sheet state", () => {+ it("clears staging when the applied model is pressed", () => {+ expect(+ pendingModelAfterPress({+ current: modelOption("gpt-next"),+ pressed: modelOption("gpt-current"),+ pressedIsApplied: true,+ }),+ ).toBeNull();+ });++ it("preserves staged options when the highlighted model is pressed again", () => {+ const pending = modelOption("gpt-next", [{ id: "effort", value: "high" }]);++ expect(+ pendingModelAfterPress({+ current: pending,+ pressed: modelOption("gpt-next"),+ pressedIsApplied: false,+ }),+ ).toBe(pending);+ });++ it("stages a different model", () => {+ const pressed = modelOption("gpt-other");++ expect(+ pendingModelAfterPress({+ current: modelOption("gpt-next"),+ pressed,+ pressedIsApplied: false,+ }),+ ).toBe(pressed);+ });+});diff --git a/apps/mobile/src/features/threads/thread-settings-sheet-state.ts b/apps/mobile/src/features/threads/thread-settings-sheet-state.tsnew file mode 100644index 000000000..f0540dc5a--- /dev/null+++ b/apps/mobile/src/features/threads/thread-settings-sheet-state.ts@@ -0,0 +1,13 @@+import type { ModelOption } from "../../lib/modelOptions";++/** Preserve staged provider options when the highlighted model is tapped again. */+export function pendingModelAfterPress(input: {+ readonly current: ModelOption | null;+ readonly pressed: ModelOption;+ readonly pressedIsApplied: boolean;+}): ModelOption | null {+ if (input.pressedIsApplied) {+ return null;+ }+ return input.current?.key === input.pressed.key ? input.current : input.pressed;+}diff --git a/apps/mobile/src/features/threads/use-thread-settings-sheet-presentation.ts b/apps/mobile/src/features/threads/use-thread-settings-sheet-presentation.tsnew file mode 100644index 000000000..3cc2ed184--- /dev/null+++ b/apps/mobile/src/features/threads/use-thread-settings-sheet-presentation.ts@@ -0,0 +1,98 @@+import { useCallback, useEffect, useRef, useState, type RefObject } from "react";+import { KeyboardController } from "react-native-keyboard-controller";++import type { ComposerEditorHandle } from "../../components/ComposerEditor";++export type ThreadSettingsSheetCloseReason = "save" | "dismiss";++type PresentationPhase = "closed" | "opening" | "visible" | "closing";++/**+ * Keeps the custom native composer and the settings modal from owning focus at+ * the same time. Opening waits for the keyboard dismissal to finish, while+ * focus restoration waits for the modal's dismissal callback.+ */+export function useThreadSettingsSheetPresentation(input: {+ readonly editorRef: RefObject<ComposerEditorHandle | null>;+ readonly isEditorFocused: boolean;+}) {+ const [phase, setPhase] = useState<PresentationPhase>("closed");+ const isActiveRef = useRef(false);+ const isMountedRef = useRef(true);+ const openingIdRef = useRef(0);+ const restoreFocusOnSaveRef = useRef(false);+ const shouldRestoreAfterDismissRef = useRef(false);++ useEffect(+ () => () => {+ isMountedRef.current = false;+ isActiveRef.current = false;+ openingIdRef.current += 1;+ },+ [],+ );++ const open = useCallback(() => {+ if (isActiveRef.current) {+ return;+ }++ isActiveRef.current = true;+ restoreFocusOnSaveRef.current = input.isEditorFocused || KeyboardController.isVisible();+ shouldRestoreAfterDismissRef.current = false;+ setPhase("opening");++ const openingId = openingIdRef.current + 1;+ openingIdRef.current = openingId;++ // Keyboard.dismiss() only tracks React Native TextInputs. The composer is+ // a custom native text view, so explicitly resign its first responder too.+ input.editorRef.current?.blur();+ void KeyboardController.dismiss().then(() => {+ if (!isMountedRef.current || !isActiveRef.current || openingIdRef.current !== openingId) {+ return;+ }+ setPhase("visible");+ });+ }, [input.editorRef, input.isEditorFocused]);++ const close = useCallback((reason: ThreadSettingsSheetCloseReason) => {+ if (!isActiveRef.current) {+ return;+ }++ openingIdRef.current += 1;+ shouldRestoreAfterDismissRef.current = reason === "save" && restoreFocusOnSaveRef.current;+ setPhase("closing");+ }, []);++ const onDismissed = useCallback(() => {+ const shouldRestoreFocus = shouldRestoreAfterDismissRef.current;+ shouldRestoreAfterDismissRef.current = false;+ restoreFocusOnSaveRef.current = false;+ isActiveRef.current = false;+ setPhase("closed");++ if (shouldRestoreFocus) {+ input.editorRef.current?.focus();+ }+ }, [input.editorRef]);++ // The new-task screen can have an autofocus queued before the sheet opens.+ // Preserve that intent for Save without allowing it to focus under the modal.+ const restoreFocusAfterSave = useCallback(() => {+ if (isActiveRef.current) {+ restoreFocusOnSaveRef.current = true;+ }+ }, []);++ return {+ isActive: phase !== "closed",+ isActiveRef,+ isVisible: phase === "visible",+ open,+ close,+ onDismissed,+ restoreFocusAfterSave,+ } as const;+}diff --git a/apps/mobile/src/lib/modelOptions.test.ts b/apps/mobile/src/lib/modelOptions.test.tsindex 2ec8566b4..8a9dabbe0 100644--- a/apps/mobile/src/lib/modelOptions.test.ts+++ b/apps/mobile/src/lib/modelOptions.test.ts@@ -3,14 +3,14 @@ import { describe, expect, it } from "vite-plus/test";import { ProviderInstanceId, type ServerConfig } from "@t3tools/contracts";import {- buildModelMenuActions,buildModelOptions,groupByProvider,+ resolveDefaultableModelSelection,resolveSelectableModelSelection,} from "./modelOptions";describe("mobile model options", () => {- it("folds legacy models into a provider-scoped menu", () => {+ it("groups models by provider and flags legacy entries", () => {const config = {providers: [{@@ -39,51 +39,14 @@ describe("mobile model options", () => {],} as unknown as ServerConfig;- const actions = buildModelMenuActions(groupByProvider(buildModelOptions(config, null)), null);-- expect(actions).toMatchObject([- {- title: "Codex",- subactions: [{ id: "model:codex:gpt-5.6-sol", title: "GPT-5.6 Sol" }],- },+ expect(groupByProvider(buildModelOptions(config, null))).toMatchObject([{- id: "legacy-models:codex",- title: "Codex legacy models",- subactions: [{ id: "model:codex:gpt-5.4", title: "GPT-5.4" }],- },- ]);- });-- it("omits an empty provider menu when every model is legacy", () => {- const config = {- providers: [- {- instanceId: "codex",- driver: "codex",- displayName: "Codex",- enabled: true,- installed: true,- auth: { status: "authenticated" },- models: [- {- slug: "gpt-5.4",- name: "GPT-5.4",- isCustom: false,- isLegacy: true,- capabilities: null,- },- ],- },- ],- } as unknown as ServerConfig;-- expect(- buildModelMenuActions(groupByProvider(buildModelOptions(config, null)), null),- ).toMatchObject([- {- id: "legacy-models:codex",- title: "Codex legacy models",- subactions: [{ id: "model:codex:gpt-5.4" }],+ providerKey: "codex",+ providerLabel: "Codex",+ models: [+ { key: "codex:gpt-5.6-sol", label: "GPT-5.6 Sol", isLegacy: false },+ { key: "codex:gpt-5.4", label: "GPT-5.4", isLegacy: true },+ ],},]);});@@ -174,4 +137,38 @@ describe("mobile model options", () => {// No config (environment offline) — nothing to validate against.expect(resolveSelectableModelSelection(null, disabled)).toBe(disabled);});++ it("keeps legacy models out of implicit defaults", () => {+ const config = {+ providers: [+ {+ instanceId: "codex",+ driver: "codex",+ displayName: "Codex",+ enabled: true,+ installed: true,+ auth: { status: "authenticated" },+ models: [+ { slug: "gpt-5.6-sol", name: "GPT-5.6 Sol", isCustom: false, capabilities: null },+ {+ slug: "gpt-5.4",+ name: "GPT-5.4",+ isCustom: false,+ isLegacy: true,+ capabilities: null,+ },+ ],+ },+ ],+ } as unknown as ServerConfig;++ const current = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-sol" };+ const legacy = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" };++ expect(resolveDefaultableModelSelection(config, current)).toBe(current);+ // A legacy last-used selection falls through to the provider default.+ expect(resolveDefaultableModelSelection(config, legacy)).toBeNull();+ // Offline: nothing to validate against, selection passes through.+ expect(resolveDefaultableModelSelection(null, legacy)).toBe(legacy);+ });});diff --git a/apps/mobile/src/lib/modelOptions.ts b/apps/mobile/src/lib/modelOptions.tsindex 951b74f7d..cb7a8c419 100644--- a/apps/mobile/src/lib/modelOptions.ts+++ b/apps/mobile/src/lib/modelOptions.ts@@ -3,7 +3,6 @@ import type {ModelSelection,ServerConfig as T3ServerConfig,} from "@t3tools/contracts";-import type { MenuAction } from "@react-native-menu/menu";import {buildProviderOptionSelectionsFromDescriptors,getProviderOptionDescriptors,@@ -85,6 +84,26 @@ export function resolveSelectableModelSelection(: null;}+/**+ * Like resolveSelectableModelSelection, but additionally rejects legacy+ * models. Used for implicit defaults (stored draft, project last-used): a+ * new thread should never quietly start on a legacy model, so those fall+ * through to the provider's default instead. Explicit picks in the settings+ * sheet are unaffected.+ */+export function resolveDefaultableModelSelection(+ config: T3ServerConfig | null | undefined,+ selection: ModelSelection | null,+): ModelSelection | null {+ const usable = resolveSelectableModelSelection(config, selection);+ if (!usable || !config) {+ return usable;+ }+ const provider = config.providers.find((candidate) => candidate.instanceId === usable.instanceId);+ const model = provider?.models.find((candidate) => candidate.slug === usable.model);+ return model?.isLegacy === true ? null : usable;+}+export function buildModelOptions(config: T3ServerConfig | null | undefined,fallbackModelSelection: ModelSelection | null,@@ -168,53 +187,3 @@ export function groupByProvider(options: ReadonlyArray<ModelOption>): ReadonlyArmodels: group.models,}));}--function modelMenuAction(option: ModelOption, selectedModel: ModelSelection | null): MenuAction {- return {- id: `model:${option.key}`,- title: option.label,- state:- option.selection.instanceId === selectedModel?.instanceId &&- option.selection.model === selectedModel.model- ? "on"- : undefined,- };-}--export function buildModelMenuActions(- groups: ReadonlyArray<ProviderGroup>,- selectedModel: ModelSelection | null,-): MenuAction[] {- return groups.flatMap((group) => {- const currentModels = group.models.filter((model) => !model.isLegacy);- const legacyModels = group.models.filter((model) => model.isLegacy);- const selected = group.models.find(- (model) =>- model.selection.instanceId === selectedModel?.instanceId &&- model.selection.model === selectedModel.model,- );-- return [- ...(currentModels.length > 0- ? [- {- id: `provider:${group.providerKey}`,- title: group.providerLabel,- subtitle: selected && !selected.isLegacy ? selected.label : undefined,- subactions: currentModels.map((option) => modelMenuAction(option, selectedModel)),- },- ]- : []),- ...(legacyModels.length > 0- ? [- {- id: `legacy-models:${group.providerKey}`,- title: `${group.providerLabel} legacy models`,- subtitle: selected?.isLegacy ? selected.label : undefined,- subactions: legacyModels.map((option) => modelMenuAction(option, selectedModel)),- },- ]- : []),- ];- });-}diff --git a/apps/mobile/src/lib/providerOptions.test.ts b/apps/mobile/src/lib/providerOptions.test.tsindex d7f99a3da..d87df6baa 100644--- a/apps/mobile/src/lib/providerOptions.test.ts+++ b/apps/mobile/src/lib/providerOptions.test.ts@@ -3,9 +3,8 @@ import { describe, expect, it } from "vite-plus/test";import type { ModelCapabilities } from "@t3tools/contracts";import {- applyProviderOptionMenuEvent,- buildProviderOptionMenuActions,- providerOptionsConfigurationLabel,+ applyProviderOptionSelection,+ providerOptionValueLabels,resolveProviderOptionDescriptors,} from "./providerOptions";@@ -35,31 +34,13 @@ const CODEX_CAPABILITIES: ModelCapabilities = {};describe("mobile provider options", () => {- it("renders the option descriptors advertised by the selected model", () => {+ it("summarizes the option values currently in effect", () => {const descriptors = resolveProviderOptionDescriptors({capabilities: CODEX_CAPABILITIES,selections: undefined,});- expect(buildProviderOptionMenuActions(descriptors)).toMatchObject([- {- title: "Reasoning",- subtitle: "Medium",- subactions: [- { title: "Medium (default)", state: "on" },- { title: "High", state: undefined },- ],- },- {- title: "Service Tier",- subtitle: "Standard",- subactions: [- { title: "Standard (default)", state: "on" },- { title: "Fast", state: undefined },- ],- },- ]);- expect(providerOptionsConfigurationLabel(descriptors)).toBe("Medium · Standard");+ expect(providerOptionValueLabels(descriptors)).toEqual(["Medium", "Standard"]);});it("updates generic select options without knowing provider-specific ids", () => {@@ -67,14 +48,18 @@ describe("mobile provider options", () => {capabilities: CODEX_CAPABILITIES,selections: undefined,});- const actions = buildProviderOptionMenuActions(descriptors);- const fastEvent = actions[1]?.subactions?.[1]?.id;- expect(fastEvent).toBeDefined();- expect(applyProviderOptionMenuEvent(descriptors, fastEvent!)).toEqual([+ expect(+ applyProviderOptionSelection(descriptors, { id: "serviceTier", value: "priority" }),+ ).toEqual([{ id: "reasoningEffort", value: "medium" },{ id: "serviceTier", value: "priority" },]);+ // Choices the model doesn't advertise are rejected, not stored.+ expect(+ applyProviderOptionSelection(descriptors, { id: "serviceTier", value: "turbo" }),+ ).toBeNull();+ expect(applyProviderOptionSelection(descriptors, { id: "unknown", value: "high" })).toBeNull();});it("treats an unspecified boolean capability as off", () => {@@ -85,16 +70,9 @@ describe("mobile provider options", () => {selections: undefined,});- expect(buildProviderOptionMenuActions(descriptors)).toMatchObject([- {- title: "Fast Mode",- subtitle: "Off",- subactions: [- { title: "Off", state: "on" },- { title: "On", state: undefined },- ],- },+ expect(providerOptionValueLabels(descriptors)).toEqual([]);+ expect(applyProviderOptionSelection(descriptors, { id: "fastMode", value: true })).toEqual([+ { id: "fastMode", value: true },]);- expect(providerOptionsConfigurationLabel(descriptors)).toBe("Configuration");});});diff --git a/apps/mobile/src/lib/providerOptions.ts b/apps/mobile/src/lib/providerOptions.tsindex ae1954989..593f5a374 100644--- a/apps/mobile/src/lib/providerOptions.ts+++ b/apps/mobile/src/lib/providerOptions.ts@@ -3,48 +3,12 @@ import type {ProviderOptionDescriptor,ProviderOptionSelection,} from "@t3tools/contracts";-import type { MenuAction } from "@react-native-menu/menu";import {buildProviderOptionSelectionsFromDescriptors,getProviderOptionCurrentLabel,- getProviderOptionCurrentValue,getProviderOptionDescriptors,} from "@t3tools/shared/model";-const PROVIDER_OPTION_EVENT_PREFIX = "provider-option:";--function providerOptionEvent(id: string, value: string | boolean): string {- return `${PROVIDER_OPTION_EVENT_PREFIX}${encodeURIComponent(JSON.stringify({ id, value }))}`;-}--function parseProviderOptionEvent(- event: string,-): { readonly id: string; readonly value: string | boolean } | null {- if (!event.startsWith(PROVIDER_OPTION_EVENT_PREFIX)) {- return null;- }-- try {- const parsed: unknown = JSON.parse(- decodeURIComponent(event.slice(PROVIDER_OPTION_EVENT_PREFIX.length)),- );- if (- typeof parsed === "object" &&- parsed !== null &&- "id" in parsed &&- typeof parsed.id === "string" &&- "value" in parsed &&- (typeof parsed.value === "string" || typeof parsed.value === "boolean")- ) {- return { id: parsed.id, value: parsed.value };- }- } catch {- return null;- }-- return null;-}-export function resolveProviderOptionDescriptors(input: {readonly capabilities: ModelCapabilities | null | undefined;readonly selections: ReadonlyArray<ProviderOptionSelection> | null | undefined;@@ -58,72 +22,41 @@ export function resolveProviderOptionDescriptors(input: {});}-export function buildProviderOptionMenuActions(- descriptors: ReadonlyArray<ProviderOptionDescriptor>,-): ReadonlyArray<MenuAction> {- return descriptors.map((descriptor) => {- const currentValue =- descriptor.type === "boolean"- ? (descriptor.currentValue ?? false)- : getProviderOptionCurrentValue(descriptor);- const choices =- descriptor.type === "select"- ? descriptor.options.map((option) => ({- id: providerOptionEvent(descriptor.id, option.id),- title: `${option.label}${option.isDefault ? " (default)" : ""}`,- state: currentValue === option.id ? ("on" as const) : undefined,- }))- : ([false, true] as const).map((value) => ({- id: providerOptionEvent(descriptor.id, value),- title: value ? "On" : "Off",- state: currentValue === value ? ("on" as const) : undefined,- }));-- return {- id: `provider-option-menu:${descriptor.id}`,- title: descriptor.label,- subtitle:- descriptor.type === "boolean"- ? currentValue- ? "On"- : "Off"- : getProviderOptionCurrentLabel(descriptor),- subactions: choices,- };- });-}--export function providerOptionsConfigurationLabel(+/**+ * Labels for the option values currently in effect (select values plus+ * enabled booleans), used to summarize the thread configuration in the+ * composer trigger pill.+ */+export function providerOptionValueLabels(descriptors: ReadonlyArray<ProviderOptionDescriptor>,-): string {- const labels = descriptors.flatMap((descriptor) => {+): ReadonlyArray<string> {+ return descriptors.flatMap((descriptor) => {if (descriptor.type === "boolean") {return descriptor.currentValue ? [descriptor.label] : [];}const label = getProviderOptionCurrentLabel(descriptor);return label ? [label] : [];});- return labels.length > 0 ? labels.join(" · ") : "Configuration";}-export function applyProviderOptionMenuEvent(+/**+ * Applies one option change (by descriptor id) and returns the full selection+ * list to store on the model selection, or null when the change doesn't match+ * an advertised descriptor / choice.+ */+export function applyProviderOptionSelection(descriptors: ReadonlyArray<ProviderOptionDescriptor>,- event: string,+ change: ProviderOptionSelection,): ReadonlyArray<ProviderOptionSelection> | null {- const selection = parseProviderOptionEvent(event);- if (!selection) {- return null;- }-- const descriptor = descriptors.find((candidate) => candidate.id === selection.id);+ const descriptor = descriptors.find((candidate) => candidate.id === change.id);if (!descriptor) {return null;}if (- (descriptor.type === "boolean" && typeof selection.value !== "boolean") ||+ (descriptor.type === "boolean" && typeof change.value !== "boolean") ||(descriptor.type === "select" &&- (typeof selection.value !== "string" ||- !descriptor.options.some((option) => option.id === selection.value)))+ (typeof change.value !== "string" ||+ !descriptor.options.some((option) => option.id === change.value)))) {return null;}@@ -132,7 +65,7 @@ export function applyProviderOptionMenuEvent(candidate.id === descriptor.id? {...candidate,- currentValue: selection.value,+ currentValue: change.value,}: candidate,) as ReadonlyArray<ProviderOptionDescriptor>;