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.
Nest mobile task settings in bottom sheets (#6224)
Julius Marminge85389b9883a2
diff --git a/.agents/skills/test-t3-mobile/SKILL.md b/.agents/skills/test-t3-mobile/SKILL.mdindex 98c1c3b20..fbcd52e69 100644--- a/.agents/skills/test-t3-mobile/SKILL.md+++ b/.agents/skills/test-t3-mobile/SKILL.md@@ -125,31 +125,29 @@ Do not start, stop, erase, or reconfigure an emulator owned by another task. Tra## Pair each client once-Issue a fresh credential against the running backend's exact base directory:+Use the bundled helper from the repository root. It issues a fresh credential against the running backend's exact base directory, opens the existing Add Environment route with the credential in an encoded query parameter, and asks that route to connect once:```bash-T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \- --base-dir <base-dir> \- --base-url <mobile-origin> \- --ttl 15m \- --label agent-mobile-<short-device-id>+.agents/skills/test-t3-mobile/scripts/pair-client.sh \+ ios <simulator-udid> <server-port> <base-dir>++.agents/skills/test-t3-mobile/scripts/pair-client.sh \+ android <emulator-serial> <server-port> <base-dir>```-In PowerShell, set `$env:T3CODE_PORT = "<server-port>"` first and run the `node ... auth pairing create` command without the leading assignment.+Run only the command for the selected platform. The helper uses `http://127.0.0.1:<server-port>` for iOS and `http://10.0.2.2:<server-port>` for Android. Pass a fifth argument only when testing a non-development URL scheme.-If the visible Add Environment action is not exposed as a semantic target, open the app's registered route instead of guessing coordinates:+The helper opens this registered route:-```bash-xcrun simctl openurl <simulator-udid> 't3code-dev://connections/new'-adb -s <emulator-serial> shell am start -W \- -a android.intent.action.VIEW \- -d 't3code-dev://connections/new' \- com.t3tools.t3code.dev+```text+t3code-dev://connections/new?pairingUrl=<encoded-pairing-url>&autoConnect=1```-Run only the command for the selected platform.+The Add Environment route owns the behavior: `pairingUrl` prefills its normal host and token inputs, while `autoConnect=1` submits once in development builds and returns to Home after success. Without `autoConnect`, the same route only prefills the form for manual inspection.++Do not enter pairing hosts or tokens through simulator keyboard automation. Xcode's semantic typer sends HID-style key events through the simulator's active keyboard state, which can corrupt uppercase tokens and punctuation even when the host Mac uses a U.S. input source. The one-shot route is the deterministic pairing path. Use the visible form only as a fallback, and paste credentials rather than typing them character by character.-In T3 Code Dev, open Add Environment and enter the complete `<mobile-origin>` and newly printed `Token`. Verify the expected seeded projects appear before exercising the affected flow.+Verify the expected seeded projects appear before exercising the affected flow.Pairing credentials are secret, short-lived, and single-use. Create a different credential for every simulator, emulator, physical device, or browser. If an attempt fails, issue a new credential rather than retrying the old one. Do not expose tokens in screenshots, commits, or final responses.@@ -183,6 +181,8 @@ Keep local verification focused. Do not turn this workflow into a full repositor- **Old UI or an old error appears:** verify Metro's worktree, variant, URL, and port before diagnosing the app.- **The environment remains empty:** verify the platform-specific HTTP origin, use a fresh token, and confirm project seeding used the identical base directory.- **A second client cannot pair:** pairing tokens are single-use; issue another token.+- **The pairing form opens but does not connect:** confirm the deep link uses the existing `connections/new` route, includes `autoConnect=1`, and carries a freshly minted encoded `pairingUrl`.+- **Pairing text changes case or punctuation:** do not retry semantic typing. Use `scripts/pair-client.sh`; the simulator keyboard layout and HID input path are not reliable for credentials.- **iOS semantic actions fail:** set explicit XcodeBuildMCP defaults and refresh with `snapshot_ui`.- **Android cannot reach Metro:** verify `adb reverse` for the exact Metro port and relaunch the development-client URL.- **Android cannot reach the backend:** use `10.0.2.2`, not `127.0.0.1`, for the Android Emulator.diff --git a/.agents/skills/test-t3-mobile/scripts/pair-client.sh b/.agents/skills/test-t3-mobile/scripts/pair-client.shnew file mode 100755index 000000000..9caa06072--- /dev/null+++ b/.agents/skills/test-t3-mobile/scripts/pair-client.sh@@ -0,0 +1,72 @@+#!/usr/bin/env bash++set -euo pipefail++usage() {+ echo "Usage: $0 <ios|android> <device-id> <server-port> <base-dir> [url-scheme]" >&2+ exit 2+}++[[ $# -ge 4 && $# -le 5 ]] || usage++platform="$1"+device_id="$2"+server_port="$3"+base_dir="$4"+url_scheme="${5:-t3code-dev}"++case "$platform" in+ ios)+ mobile_origin="http://127.0.0.1:${server_port}"+ ;;+ android)+ mobile_origin="http://10.0.2.2:${server_port}"+ ;;+ *)+ usage+ ;;+esac++repo_root="$(git rev-parse --show-toplevel)"+cd "$repo_root"++if ! pairing_output="$({+ T3CODE_PORT="$server_port" node apps/server/src/bin.ts auth pairing create \+ --base-dir "$base_dir" \+ --base-url "$mobile_origin" \+ --ttl 15m \+ --label "agent-mobile-${device_id:0:8}"+} 2>&1)"; then+ echo "Could not mint a mobile pairing credential." >&2+ exit 1+fi++pairing_url="$(printf '%s\n' "$pairing_output" | sed -n 's/^Pair URL: //p' | tail -n 1)"+if [[ -z "$pairing_url" ]]; then+ echo "Could not parse the mobile pairing URL." >&2+ exit 1+fi++deep_link="$(PAIRING_URL="$pairing_url" URL_SCHEME="$url_scheme" node - <<'NODE'+const query = new URLSearchParams({+ pairingUrl: process.env.PAIRING_URL,+ autoConnect: "1",+});+process.stdout.write(`${process.env.URL_SCHEME}://connections/new?${query}`);+NODE+)"++case "$platform" in+ ios)+ xcrun simctl openurl "$device_id" "$deep_link"+ ;;+ android)+ # adb shell re-joins its arguments and evaluates them through the device+ # shell, so the deep link's `?`/`&` must be quoted once more for that shell.+ adb -s "$device_id" shell \+ "am start -W -a android.intent.action.VIEW -d '$deep_link' com.t3tools.t3code.dev" \+ >/dev/null+ ;;+esac++echo "Opened the existing Add Environment route with a fresh pairing credential."diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsxindex 93bb61655..20bba1f60 100644--- a/apps/mobile/src/Stack.tsx+++ b/apps/mobile/src/Stack.tsx@@ -11,7 +11,7 @@ import {type NativeStackNavigationOptions,} from "@react-navigation/native-stack";import { useEffect, useRef } from "react";-import { DynamicColorIOS, Platform, Pressable, ScrollView, StyleSheet } from "react-native";+import { Platform, Pressable, ScrollView, StyleSheet } from "react-native";import { useResolveClassNames } from "uniwind";import { AppText as Text } from "./components/AppText";@@ -39,6 +39,15 @@ import { AddProjectLocalRoute } from "./features/projects/AddProjectLocalRoute";import { AddProjectRepositoryRoute } from "./features/projects/AddProjectRepositoryRoute";import { AddProjectSourceRoute } from "./features/projects/AddProjectSourceRoute";import { NewTaskDraftRouteScreen } from "./features/threads/NewTaskDraftRouteScreen";+import {+ NewTaskBranchPickerRouteScreen,+ NewTaskEnvironmentPickerRouteScreen,+} from "./features/threads/NewTaskContextPickerScreens";+import {+ ExistingThreadSettingsRouteProvider,+ ExistingThreadSettingsRouteScreen,+ NewTaskThreadSettingsRouteScreen,+} from "./features/threads/ThreadSettingsSheet";import { NewTaskFlowProvider } from "./features/threads/new-task-flow-provider";import { NewTaskRouteScreen } from "./features/threads/NewTaskRouteScreen";import { SettingsAppearanceRouteScreen } from "./features/settings/SettingsAppearanceRouteScreen";@@ -62,17 +71,15 @@ import {} from "./features/sharing/incoming-share-presentation";import { NATIVE_LIQUID_GLASS_SUPPORTED } from "./native/native-glass";import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader";+import {+ FORM_SHEET_PRESENTATION_OPTIONS,+ NATIVE_SHEET_SURFACE_COLOR,+ NATIVE_SHEET_SURFACE_CONTENT_STYLE,+} from "./native/sheet-surface";import { useThreadOutboxDrain } from "./state/use-thread-outbox-drain";const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);-// Matches --color-sheet in global.css (light/dark). DynamicColorIOS lets the header-// background stay STATIC config while still adapting to appearance changes.-const SHEET_BACKGROUND_COLOR =- Platform.OS === "ios"- ? DynamicColorIOS({ light: "rgba(242, 242, 247, 0.98)", dark: "rgba(14, 14, 14, 0.98)" })- : undefined;-type AppScreenOptions = NativeStackNavigationOptions & {readonly unstable_navigationItemStyle?: "editor";};@@ -91,8 +98,8 @@ const GLASS_HEADER_OPTIONS: AppScreenOptions = {headerShown: true,headerStyle: NATIVE_LIQUID_GLASS_SUPPORTED? { backgroundColor: "transparent" }- : SHEET_BACKGROUND_COLOR !== undefined- ? { backgroundColor: SHEET_BACKGROUND_COLOR as unknown as string }+ : NATIVE_SHEET_SURFACE_COLOR !== undefined+ ? { backgroundColor: NATIVE_SHEET_SURFACE_COLOR as unknown as string }: undefined,headerTitleStyle: { fontSize: 18, fontWeight: "800" },headerTransparent: NATIVE_LIQUID_GLASS_SUPPORTED,@@ -109,10 +116,10 @@ const SOLID_HEADER_OPTIONS: AppScreenOptions = {headerShadowVisible: false,headerShown: true,headerStyle:- SHEET_BACKGROUND_COLOR !== undefined+ NATIVE_SHEET_SURFACE_COLOR !== undefined? // native-stack types this as `string`, but the native side accepts any// ColorValue including DynamicColorIOS.- { backgroundColor: SHEET_BACKGROUND_COLOR as unknown as string }+ { backgroundColor: NATIVE_SHEET_SURFACE_COLOR as unknown as string }: undefined,headerTitleStyle: { fontSize: 18, fontWeight: "800" },headerTransparent: false,@@ -125,6 +132,14 @@ const SHEET_SOLID_HEADER_OPTIONS: AppScreenOptions = {unstable_navigationItemStyle: undefined,};+// A native glass header for a sheet screen whose primary child is a scroll+// view. The centered sheet title stays stable while UIKit supplies scroll-edge+// fading from that child.+const SHEET_GLASS_HEADER_OPTIONS: AppScreenOptions = {+ ...GLASS_HEADER_OPTIONS,+ unstable_navigationItemStyle: undefined,+};+const LEGAL_DOCUMENT_HEADER_OPTIONS: AppScreenOptions = {...SHEET_SOLID_HEADER_OPTIONS,headerBackVisible: false,@@ -238,9 +253,16 @@ const THREAD_LINKING_PREFIX = "threads/:environmentId/:threadId";const NewTaskSheetStack = createNativeStackNavigator({initialRouteName: "NewTask",screenOptions: {- ...GLASS_HEADER_OPTIONS,- // Sheets read better with the iOS-default centered title (no editor style).- unstable_navigationItemStyle: undefined,+ ...SHEET_GLASS_HEADER_OPTIONS,+ // The form-sheet host owns the one opaque adaptive surface. Child screens+ // and the navigation bar stay transparent over it, avoiding visible color+ // slabs as view controllers move horizontally.+ contentStyle: Platform.OS === "ios" ? { backgroundColor: "transparent" } : undefined,+ // UIKit's default push adds a dimming shadow and independently transitions+ // the navigation bar. Both read as mismatched sheet backgrounds here.+ // simple_push retains native push/pop gestures without either artifact.+ animation: Platform.OS === "ios" ? "simple_push" : undefined,+ animationDuration: Platform.OS === "ios" ? 350 : undefined,},screens: {NewTask: createNativeStackScreen({@@ -253,9 +275,39 @@ const NewTaskSheetStack = createNativeStackNavigator({NewTaskDraft: createNativeStackScreen({screen: NewTaskDraftRouteScreen,linking: "draft",- // The draft composer has no scroll view for glass to sample; a solid- // header also lays the content out below the bar (no manual inset).- options: SHEET_SOLID_HEADER_OPTIONS,+ options: {+ headerBackVisible: false,+ title: "",+ },+ }),+ NewTaskEnvironment: createNativeStackScreen({+ screen: NewTaskEnvironmentPickerRouteScreen,+ linking: "draft/environment",+ options: {+ title: "Environment",+ },+ }),+ NewTaskBranch: createNativeStackScreen({+ screen: NewTaskBranchPickerRouteScreen,+ linking: "draft/branch",+ options: {+ title: "Branch",+ },+ }),+ ThreadSettings: createNativeStackScreen({+ screen: NewTaskThreadSettingsRouteScreen,+ linking: "draft/settings",+ options: {+ gestureEnabled: true,+ headerShown: false,+ ...(Platform.OS === "android"+ ? { presentation: "card" as const }+ : {+ ...FORM_SHEET_PRESENTATION_OPTIONS,+ sheetAllowedDetents: [1],+ sheetGrabberVisible: true,+ }),+ },}),AddProject: createNativeStackScreen({screen: AddProjectSourceRoute,@@ -294,6 +346,7 @@ const WORKSPACE_OVERLAY_ROUTES = new Set(["SettingsLegal","SettingsSheet","ThreadReviewComment",+ "ThreadSettingsSheet",]);/**@@ -356,9 +409,11 @@ function RootStackLayout(props: {<HardwareKeyboardCommandProvider pathname={pathname}><ThreadOutboxDrainWorker /><ShowcaseCaptureCoordinator pathname={pathname} />- <AdaptiveWorkspaceLayout pathname={workspacePathname}>- {props.children}- </AdaptiveWorkspaceLayout>+ <ExistingThreadSettingsRouteProvider>+ <AdaptiveWorkspaceLayout pathname={workspacePathname}>+ {props.children}+ </AdaptiveWorkspaceLayout>+ </ExistingThreadSettingsRouteProvider></HardwareKeyboardCommandProvider>);}@@ -440,7 +495,9 @@ export const RootStack = createNativeStackNavigator({options: {// Android cannot host the keyboard-driven comment composer inside a// formSheet; use a full-screen modal there instead.- presentation: Platform.OS === "android" ? "fullScreenModal" : "formSheet",+ ...(Platform.OS === "android"+ ? { presentation: "fullScreenModal" as const }+ : FORM_SHEET_PRESENTATION_OPTIONS),sheetAllowedDetents: Platform.OS === "android" ? undefined : [0.55, 0.92],sheetGrabberVisible: Platform.OS !== "android",},@@ -450,10 +507,7 @@ export const RootStack = createNativeStackNavigator({linking: `${THREAD_LINKING_PREFIX}/files`,options: {...GLASS_HEADER_OPTIONS,- contentStyle:- SHEET_BACKGROUND_COLOR !== undefined- ? { backgroundColor: SHEET_BACKGROUND_COLOR }- : undefined,+ contentStyle: NATIVE_SHEET_SURFACE_CONTENT_STYLE,title: "Files",},}),@@ -462,11 +516,25 @@ export const RootStack = createNativeStackNavigator({linking: `${THREAD_LINKING_PREFIX}/files/:path*`,options: SOLID_HEADER_OPTIONS,}),+ ThreadSettingsSheet: createNativeStackScreen({+ screen: ExistingThreadSettingsRouteScreen,+ options: {+ gestureEnabled: true,+ headerShown: false,+ ...(Platform.OS === "android"+ ? { presentation: "card" as const }+ : {+ ...FORM_SHEET_PRESENTATION_OPTIONS,+ sheetAllowedDetents: [1],+ sheetGrabberVisible: true,+ }),+ },+ }),GitOverview: createNativeStackScreen({screen: GitOverviewSheet,linking: `${THREAD_LINKING_PREFIX}/git`,options: {- presentation: "formSheet",+ ...FORM_SHEET_PRESENTATION_OPTIONS,sheetAllowedDetents: [0.55, 0.92],sheetGrabberVisible: true,},@@ -475,7 +543,7 @@ export const RootStack = createNativeStackNavigator({screen: GitCommitSheet,linking: `${THREAD_LINKING_PREFIX}/git/commit`,options: {- presentation: "formSheet",+ ...FORM_SHEET_PRESENTATION_OPTIONS,sheetAllowedDetents: [0.55, 0.92],sheetGrabberVisible: true,},@@ -484,7 +552,7 @@ export const RootStack = createNativeStackNavigator({screen: GitBranchesSheet,linking: `${THREAD_LINKING_PREFIX}/git/branches`,options: {- presentation: "formSheet",+ ...FORM_SHEET_PRESENTATION_OPTIONS,sheetAllowedDetents: [0.55, 0.92],sheetGrabberVisible: true,},@@ -493,7 +561,7 @@ export const RootStack = createNativeStackNavigator({screen: GitConfirmSheet,linking: `${THREAD_LINKING_PREFIX}/git-confirm`,options: {- presentation: "formSheet",+ ...FORM_SHEET_PRESENTATION_OPTIONS,sheetAllowedDetents: [0.45, 0.7],sheetGrabberVisible: true,},@@ -509,7 +577,7 @@ export const RootStack = createNativeStackNavigator({...(Platform.OS === "android"? { presentation: "card" as const }: {- presentation: "formSheet" as const,+ ...FORM_SHEET_PRESENTATION_OPTIONS,sheetAllowedDetents: [0.7, 0.92],sheetGrabberVisible: true,}),@@ -532,7 +600,7 @@ export const RootStack = createNativeStackNavigator({...(Platform.OS === "android" ? { headerShown: false } : SHEET_SOLID_HEADER_OPTIONS),title: "Set up T3 Connect",gestureEnabled: true,- presentation: "formSheet",+ ...FORM_SHEET_PRESENTATION_OPTIONS,sheetAllowedDetents: [0.6, 0.95],sheetGrabberVisible: true,},@@ -547,7 +615,7 @@ export const RootStack = createNativeStackNavigator({...(Platform.OS === "android"? { presentation: "card" as const, headerShown: false }: {- presentation: "formSheet" as const,+ ...FORM_SHEET_PRESENTATION_OPTIONS,sheetAllowedDetents: [0.55, 0.7],sheetGrabberVisible: true,}),@@ -557,7 +625,7 @@ export const RootStack = createNativeStackNavigator({screen: ConnectionsNewRouteScreen,linking: "connections/new",options: {- presentation: "formSheet",+ ...FORM_SHEET_PRESENTATION_OPTIONS,sheetAllowedDetents: [0.55, 0.7],sheetGrabberVisible: true,},@@ -577,7 +645,7 @@ export const RootStack = createNativeStackNavigator({...(Platform.OS === "android"? { presentation: "card" as const }: {- presentation: "formSheet" as const,+ ...FORM_SHEET_PRESENTATION_OPTIONS,sheetAllowedDetents: [0.92],sheetGrabberVisible: true,}),diff --git a/apps/mobile/src/components/ComposerToolbarTrigger.tsx b/apps/mobile/src/components/ComposerToolbar.tsxsimilarity index 77%rename from apps/mobile/src/components/ComposerToolbarTrigger.tsxrename to apps/mobile/src/components/ComposerToolbar.tsxindex 201876249..de2cca1f6 100644--- a/apps/mobile/src/components/ComposerToolbarTrigger.tsx+++ b/apps/mobile/src/components/ComposerToolbar.tsx@@ -17,11 +17,73 @@ import { cn } from "../lib/cn";import { AppText as Text } from "./AppText";import { SymbolView } from "./AppSymbol";-export const COMPOSER_TOOLBAR_CONTROL_HEIGHT = 44;-export const COMPOSER_TOOLBAR_GAP = 8;-export const COMPOSER_TOOLBAR_FADE_WIDTH = 18;+const COMPOSER_TOOLBAR_GAP = 8;+const COMPOSER_TOOLBAR_FADE_WIDTH = 18;const COMPOSER_TOOLBAR_SCROLL_EPSILON = 4;+/**+ * Quiet inline composer control used inside cards and their context rows.+ * Unlike ComposerToolbarButton, this does not draw another pill inside the+ * composer surface, so model and workspace controls read as part of the card.+ */+export function ComposerInlineControl(props: {+ readonly accessibilityHint?: string;+ readonly accessibilityLabel?: string;+ readonly disabled?: boolean;+ readonly emphasized?: boolean;+ readonly icon?: ComponentProps<typeof SymbolView>["name"];+ readonly iconNode?: ReactNode;+ readonly label: string;+ readonly maxWidth?: number;+ readonly onPress?: () => void;+ readonly selected?: boolean;+ readonly static?: boolean;+ readonly chevronDirection?: "down" | "right";+ readonly showChevron?: boolean;+}) {+ const iconColor = useThemeColor(+ props.emphasized || props.selected ? "--color-icon" : "--color-icon-muted",+ );++ return (+ <Pressable+ accessibilityLabel={props.accessibilityLabel ?? props.label}+ accessibilityHint={props.accessibilityHint}+ accessibilityRole={props.static ? undefined : "button"}+ accessibilityState={+ props.static ? undefined : { disabled: props.disabled, selected: props.selected }+ }+ className="h-11 flex-row items-center gap-2 rounded-xl px-2 active:bg-subtle"+ disabled={props.disabled || props.static}+ onPress={props.onPress}+ style={{ maxWidth: props.maxWidth ?? 190, opacity: props.disabled ? 0.45 : 1 }}+ >+ {props.iconNode ? (+ <View className="size-4 shrink-0 items-center justify-center">{props.iconNode}</View>+ ) : props.icon ? (+ <SymbolView name={props.icon} size={16} tintColor={iconColor} type="monochrome" />+ ) : null}+ <Text+ className={cn(+ "shrink text-sm font-t3-medium",+ props.emphasized || props.selected ? "text-foreground" : "text-foreground-muted",+ )}+ numberOfLines={1}+ >+ {props.label}+ </Text>+ {props.showChevron === false ? null : (+ <SymbolView+ name={props.chevronDirection === "right" ? "chevron.right" : "chevron.down"}+ size={10}+ tintColor={iconColor}+ type="monochrome"+ />+ )}+ </Pressable>+ );+}+export function ComposerToolbarRow(props: {readonly children: ReactNode;readonly paddingBottom?: number;@@ -247,5 +309,3 @@ export function ComposerToolbarButton(props: {</Pressable>);}--export const ComposerToolbarTrigger = ComposerToolbarButton;diff --git a/apps/mobile/src/components/GlassSurface.tsx b/apps/mobile/src/components/GlassSurface.tsxindex f34bd4e28..f0b1f863f 100644--- a/apps/mobile/src/components/GlassSurface.tsx+++ b/apps/mobile/src/components/GlassSurface.tsx@@ -5,16 +5,19 @@ import {useColorScheme,View,type ColorValue,+ type StyleProp,type ViewProps,type ViewStyle,} from "react-native";import { useThemeColor } from "../lib/useThemeColor";-export interface GlassSurfaceProps extends Omit<ViewProps, "className"> {+interface GlassSurfaceProps extends Omit<ViewProps, "className"> {readonly children: ReactNode;readonly glassEffectStyle?: "clear" | "regular" | "none";readonly tintColor?: ColorValue;readonly chrome?: "default" | "none";+ /** Styling used only when native Liquid Glass is unavailable. */+ readonly fallbackStyle?: StyleProp<ViewStyle>;}export function GlassSurface({@@ -22,6 +25,7 @@ export function GlassSurface({glassEffectStyle = "regular",chrome = "default",tintColor,+ fallbackStyle,style,...props}: GlassSurfaceProps) {@@ -67,7 +71,7 @@ export function GlassSurface({}return (- <View {...props} style={[surfaceStyle, style]}>+ <View {...props} style={[surfaceStyle, fallbackStyle, style]}>{children}</View>);diff --git a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsxindex de3799ac8..37d53cbd8 100644--- a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx+++ b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx@@ -2,7 +2,7 @@ import { CameraView, useCameraPermissions } from "expo-camera";import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";import { AsyncResult } from "effect/unstable/reactivity";-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import { Alert, Platform, ScrollView, View } from "react-native";import { useSafeAreaInsets } from "react-native-safe-area-context";import { useThemeColor } from "../../lib/useThemeColor";@@ -11,12 +11,13 @@ import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";import { ErrorBanner } from "../../components/ErrorBanner";import { ConnectionSheetButton } from "./ConnectionSheetButton";-import { extractPairingUrlFromQrPayload } from "./pairing";+import { buildPairingUrl, extractPairingUrlFromQrPayload, parsePairingUrl } from "./pairing";import { useRemoteConnections } from "../../state/use-remote-environment-registry";-import { buildPairingUrl, parsePairingUrl } from "./pairing";type ConnectionsNewRouteParams = {readonly mode?: string;+ readonly pairingUrl?: string;+ readonly autoConnect?: string;};export function ConnectionsNewRouteScreen({@@ -30,6 +31,13 @@ export function ConnectionsNewRouteScreen({} = useRemoteConnections();const navigation = useNavigation();const params = route.params ?? {};+ // Deep-link prefill exists for development automation only. A production+ // link must not arrive with attacker-chosen host and token already filled.+ const routePairingUrl = __DEV__ ? (params.pairingUrl?.trim() ?? "") : "";+ const shouldAutoConnect =+ __DEV__ &&+ routePairingUrl.length > 0 &&+ (params.autoConnect === "1" || params.autoConnect === "true");const insets = useSafeAreaInsets();const [hostInput, setHostInput] = useState("");const [codeInput, setCodeInput] = useState("");@@ -37,6 +45,7 @@ export function ConnectionsNewRouteScreen({const [showScanner, setShowScanner] = useState(params.mode === "scan_qr");const [cameraPermission, requestCameraPermission] = useCameraPermissions();const [scannerLocked, setScannerLocked] = useState(false);+ const attemptedAutoConnectRef = useRef<string | null>(null);const headerIconColor = useThemeColor("--color-icon");@@ -48,6 +57,16 @@ export function ConnectionsNewRouteScreen({setCodeInput(code);}, [connectionPairingUrl]);+ useEffect(() => {+ if (routePairingUrl.length === 0) {+ return;+ }++ const { host, code } = parsePairingUrl(routePairingUrl);+ setHostInput(host);+ setCodeInput(code);+ }, [routePairingUrl]);+useEffect(() => {if (pairingConnectionError) {setIsSubmitting(false);@@ -116,22 +135,38 @@ export function ConnectionsNewRouteScreen({[onChangeConnectionPairingUrl, scannerLocked],);+ const connectAndClose = useCallback(+ async (pairingUrl: string, replaceWithHome: boolean) => {+ setIsSubmitting(true);+ onChangeConnectionPairingUrl(pairingUrl);+ try {+ const result = await onConnectPress(pairingUrl);+ if (AsyncResult.isSuccess(result)) {+ if (replaceWithHome || !navigation.canGoBack()) {+ navigation.dispatch(StackActions.replace("Home"));+ } else {+ navigation.goBack();+ }+ }+ } finally {+ setIsSubmitting(false);+ }+ },+ [navigation, onChangeConnectionPairingUrl, onConnectPress],+ );+const handleSubmit = useCallback(async () => {- setIsSubmitting(true);+ await connectAndClose(buildPairingUrl(hostInput, codeInput), false);+ }, [codeInput, connectAndClose, hostInput]);- const pairingUrl = buildPairingUrl(hostInput, codeInput);- onChangeConnectionPairingUrl(pairingUrl);- const result = await onConnectPress(pairingUrl);- if (AsyncResult.isSuccess(result)) {- if (navigation.canGoBack()) {- navigation.goBack();- } else {- navigation.dispatch(StackActions.replace("Home"));- }- } else {- setIsSubmitting(false);+ useEffect(() => {+ if (!shouldAutoConnect || attemptedAutoConnectRef.current === routePairingUrl) {+ return;}- }, [codeInput, hostInput, onChangeConnectionPairingUrl, onConnectPress, navigation]);++ attemptedAutoConnectRef.current = routePairingUrl;+ void connectAndClose(routePairingUrl, true);+ }, [connectAndClose, routePairingUrl, shouldAutoConnect]);return (<View collapsable={false} className="flex-1 bg-sheet">diff --git a/apps/mobile/src/features/home/HomeHeader.tsx b/apps/mobile/src/features/home/HomeHeader.tsxindex f3d33934a..e7ce41cb4 100644--- a/apps/mobile/src/features/home/HomeHeader.tsx+++ b/apps/mobile/src/features/home/HomeHeader.tsx@@ -356,6 +356,7 @@ function IosHomeHeader(props: HomeHeaderProps) {onSearchTextChange: props.onSearchQueryChange,placeholder: "Search",searchTextChangeId: "home-search-text",+ showsSearchDismissButton: true,}),],}diff --git a/apps/mobile/src/features/layout/native-mail-search-toolbar.ts b/apps/mobile/src/features/layout/native-mail-search-toolbar.tsindex 8770d96b1..34d5570e6 100644--- a/apps/mobile/src/features/layout/native-mail-search-toolbar.ts+++ b/apps/mobile/src/features/layout/native-mail-search-toolbar.ts@@ -11,6 +11,9 @@ import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";*/export const NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED = NATIVE_LIQUID_GLASS_SUPPORTED;+/** Clearance for scroll content that must come to rest above the floating toolbar. */+export const NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET = 56;+type NativeMailSearchToolbarInput = Omit<HeaderBarButtonMailSearchToolbarItem,"type" | "useFallbackSearchField"diff --git a/apps/mobile/src/features/projects/AddProjectScreen.tsx b/apps/mobile/src/features/projects/AddProjectScreen.tsxindex 39e6bda3c..747a919a0 100644--- a/apps/mobile/src/features/projects/AddProjectScreen.tsx+++ b/apps/mobile/src/features/projects/AddProjectScreen.tsx@@ -27,7 +27,7 @@ import {inferProjectTitleFromPath,} from "@t3tools/client-runtime/state/projects";import { CommandId, type EnvironmentId, ProjectId } from "@t3tools/contracts";-import { StackActions, useNavigation } from "@react-navigation/native";+import { CommonActions, StackActions, useNavigation } from "@react-navigation/native";import { SymbolView } from "../../components/AppSymbol";import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native";@@ -402,13 +402,12 @@ function SourceControlRow(props: {icon={icon}isFirst={props.isFirst}onPress={() =>- navigation.navigate("NewTaskSheet", {- screen: "AddProjectRepository",- params: {+ navigation.dispatch(+ StackActions.push("AddProjectRepository", {environmentId: props.selectedEnvironmentId,source: props.source,- },- })+ }),+ )}/>);@@ -498,12 +497,11 @@ export function AddProjectSourceScreen() {}isFirstonPress={() =>- navigation.navigate("NewTaskSheet", {- screen: "AddProjectLocal",- params: {+ navigation.dispatch(+ StackActions.push("AddProjectLocal", {environmentId: selectedEnvironment.environmentId,- },- })+ }),+ )}/>{(["url", ...sortAddProjectProviderSources(readiness)] as AddProjectRemoteSource[]).map(@@ -547,10 +545,18 @@ function useCreateProject(environment: EnvironmentOption | null) {if (existing) {Alert.alert("Project already exists", existing.title);navigation.dispatch(- StackActions.replace("NewTaskDraft", {- environmentId: existing.environmentId,- projectId: existing.id,- title: existing.title,+ CommonActions.reset({+ index: 0,+ routes: [+ {+ name: "NewTaskDraft",+ params: {+ environmentId: existing.environmentId,+ projectId: existing.id,+ title: existing.title,+ },+ },+ ],}),);return;@@ -571,10 +577,18 @@ function useCreateProject(environment: EnvironmentOption | null) {return result;}navigation.dispatch(- StackActions.replace("NewTaskDraft", {- environmentId: environment.environmentId,- projectId,- title: inferProjectTitleFromPath(workspaceRoot),+ CommonActions.reset({+ index: 0,+ routes: [+ {+ name: "NewTaskDraft",+ params: {+ environmentId: environment.environmentId,+ projectId,+ title: inferProjectTitleFromPath(workspaceRoot),+ },+ },+ ],}),);return result;@@ -612,15 +626,14 @@ export function AddProjectRepositoryScreen(props: {const provider = addProjectRemoteSourceProvider(source);if (!provider) {const remoteUrl = repositoryInput.trim();- navigation.navigate("NewTaskSheet", {- screen: "AddProjectDestination",- params: {+ navigation.dispatch(+ StackActions.push("AddProjectDestination", {environmentId: environment.environmentId,source,remoteUrl,repositoryTitle: remoteUrl,- },- });+ }),+ );setIsSubmitting(false);return;}@@ -636,15 +649,14 @@ export function AddProjectRepositoryScreen(props: {setError(errorMessage(Cause.squash(result.cause)));} else {const repository = result.value;- navigation.navigate("NewTaskSheet", {- screen: "AddProjectDestination",- params: {+ navigation.dispatch(+ StackActions.push("AddProjectDestination", {environmentId: environment.environmentId,source,remoteUrl: repository.sshUrl,repositoryTitle: repository.nameWithOwner,- },- });+ }),+ );}setIsSubmitting(false);}, [environment, isSubmitting, lookupRepositoryQuery, repositoryInput, navigation, source]);diff --git a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsRouteScreen.tsxindex c718558a2..84a5634e5 100644--- a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx+++ b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx@@ -549,7 +549,10 @@ function GeneralSettingsSection() {*/function LegacySettingsSection() {const savePreferences = useAtomSet(updateMobilePreferencesAtom);+ const preferences = useAtomValue(mobilePreferencesAtom);const threadListV2Enabled = useThreadListV2Enabled();+ const planModeEnabled =+ AsyncResult.isSuccess(preferences) && preferences.value.planModeEnabled === true;return (<View className="gap-3">@@ -560,10 +563,16 @@ function LegacySettingsSection() {value={!threadListV2Enabled}onValueChange={(value) => savePreferences({ legacyThreadListEnabled: value })}/>+ <SettingsSwitchRow+ icon="hammer"+ label="Plan Mode"+ value={planModeEnabled}+ onValueChange={(value) => savePreferences({ planModeEnabled: value })}+ /></SettingsSection><Text className="px-2 text-sm text-foreground-muted">- Brings back the original grouped thread list. The default list is flat, in creation order:- active work renders as cards; settled threads collapse to compact rows.+ Opt into retired interfaces kept for compatibility. Plan Mode restores the Build/Plan+ control; otherwise every task runs in Build mode.</Text></View>);diff --git a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsxindex cb281bf4a..a80d90d82 100644--- a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx+++ b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx@@ -18,7 +18,7 @@ import {ComposerToolbarButton,ComposerToolbarRow,ComposerToolbarScroller,-} from "../../components/ComposerToolbarTrigger";+} from "../../components/ComposerToolbar";import { ControlPillMenu } from "../../components/ControlPill";import { EmptyState } from "../../components/EmptyState";import { GlassSurface } from "../../components/GlassSurface";diff --git a/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx b/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsxnew file mode 100644index 000000000..68bf0d05c--- /dev/null+++ b/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx@@ -0,0 +1,473 @@+import type { VcsRef } from "@t3tools/client-runtime/state/vcs";+import { LegendList } from "@legendapp/list/react-native";+import {+ isAtomCommandInterrupted,+ squashAtomCommandFailure,+} from "@t3tools/client-runtime/state/runtime";+import * as Haptics from "expo-haptics";+import { useNavigation } from "@react-navigation/native";+import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import {+ ActivityIndicator,+ Alert,+ Platform,+ Pressable,+ ScrollView,+ Switch,+ TextInput,+ View,+} from "react-native";+import { useSafeAreaInsets } from "react-native-safe-area-context";++import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";+import { SymbolView } from "../../components/AppSymbol";+import { AppText as Text } from "../../components/AppText";+import { cn } from "../../lib/cn";+import { useFontFamily } from "../../lib/useFontFamily";+import { useThemeColor } from "../../lib/useThemeColor";+import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";+import { useAtomCommand } from "../../state/use-atom-command";+import { vcsEnvironment } from "../../state/vcs";+import {+ createNativeMailSearchToolbarItem,+ NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET,+ NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED,+} from "../layout/native-mail-search-toolbar";+import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";+import { shouldCheckoutNewTaskBranch } from "./new-task-context-presentation";++function SelectionRow(props: {+ readonly icon?: "arrow.triangle.branch" | "desktopcomputer";+ readonly onPress: () => void;+ readonly disabled?: boolean;+ readonly selected: boolean;+ readonly isLast?: boolean;+ readonly subtitle?: string;+ readonly title: string;+}) {+ const iconColor = useThemeColor("--color-icon-muted");+ const checkmarkColor = useThemeColor("--color-icon");++ return (+ <Pressable+ accessibilityLabel={[props.title, props.subtitle].filter(Boolean).join(", ")}+ accessibilityRole="radio"+ accessibilityState={{ checked: props.selected }}+ className={cn(+ "min-h-14 flex-row items-center gap-3 bg-card px-4 py-3 active:bg-subtle",+ !props.isLast && "border-b border-border-subtle",+ )}+ disabled={props.disabled}+ onPress={props.onPress}+ style={{ opacity: props.disabled ? 0.45 : 1 }}+ >+ {props.icon ? (+ <SymbolView name={props.icon} size={17} tintColor={iconColor} type="monochrome" />+ ) : null}+ <View className="min-w-0 flex-1 gap-0.5">+ <Text className="text-base font-t3-medium text-foreground" numberOfLines={1}>+ {props.title}+ </Text>+ {props.subtitle ? (+ <Text className="text-xs text-foreground-muted" numberOfLines={1}>+ {props.subtitle}+ </Text>+ ) : null}+ </View>+ {props.selected ? (+ <SymbolView+ name="checkmark"+ size={16}+ tintColor={checkmarkColor}+ type="monochrome"+ weight="semibold"+ />+ ) : null}+ </Pressable>+ );+}++function ToggleRow(props: {+ readonly title: string;+ readonly value: boolean;+ readonly onValueChange: (value: boolean) => void;+}) {+ return (+ <View className="min-h-14 flex-row items-center gap-3 bg-card px-4 py-3">+ <Text className="min-w-0 flex-1 text-base font-t3-medium text-foreground" numberOfLines={1}>+ {props.title}+ </Text>+ <Switch+ accessibilityLabel={props.title}+ onValueChange={props.onValueChange}+ value={props.value}+ />+ </View>+ );+}++function BranchSelectionRow(props: {+ readonly badge: string | null;+ readonly branch: VcsRef;+ readonly disabled: boolean;+ readonly isFirst: boolean;+ readonly isLast: boolean;+ readonly onSelect: (branch: VcsRef) => void;+ readonly selected: boolean;+}) {+ const onPress = useCallback(() => props.onSelect(props.branch), [props.branch, props.onSelect]);++ return (+ <View+ className={cn(+ props.isFirst && "overflow-hidden rounded-t-2xl",+ props.isLast && "overflow-hidden rounded-b-2xl",+ )}+ >+ <SelectionRow+ icon="arrow.triangle.branch"+ disabled={props.disabled}+ isLast={props.isLast}+ onPress={onPress}+ selected={props.selected}+ subtitle={props.badge ? props.badge.toUpperCase() : undefined}+ title={props.branch.name}+ />+ </View>+ );+}++function PickerSurface(props: { readonly children: ReactNode }) {+ return <View className="overflow-hidden rounded-2xl bg-card">{props.children}</View>;+}++export function NewTaskEnvironmentPickerRouteScreen() {+ const flow = useNewTaskFlow();+ const navigation = useNavigation();+ const insets = useSafeAreaInsets();++ return (+ <View className="flex-1 bg-sheet" collapsable={false}>+ <NativeStackScreenOptions+ options={{+ headerShown: Platform.OS !== "android",+ title: "Environment",+ }}+ />+ {Platform.OS === "android" ? (+ <AndroidScreenHeader title="Environment" onBack={() => navigation.goBack()} />+ ) : null}+ <ScrollView+ contentInsetAdjustmentBehavior="automatic"+ contentContainerStyle={{+ paddingBottom: Math.max(insets.bottom, 16) + 16,+ paddingHorizontal: 16,+ paddingTop: 16,+ }}+ showsVerticalScrollIndicator={false}+ >+ <PickerSurface>+ {flow.environments.map((environment, index) => (+ <SelectionRow+ key={String(environment.environmentId)}+ icon="desktopcomputer"+ isLast={index === flow.environments.length - 1}+ onPress={() => {+ void Haptics.selectionAsync();+ flow.selectEnvironment(environment.environmentId);+ navigation.goBack();+ }}+ selected={flow.selectedEnvironmentId === environment.environmentId}+ title={environment.environmentLabel}+ />+ ))}+ </PickerSurface>+ </ScrollView>+ </View>+ );+}++export function NewTaskBranchPickerRouteScreen() {+ const flow = useNewTaskFlow();+ const navigation = useNavigation();+ const insets = useSafeAreaInsets();+ const placeholderColor = useThemeColor("--color-placeholder");+ const foregroundColor = useThemeColor("--color-foreground");+ const fontFamily = useFontFamily("regular");+ const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });+ const [switchingBranchName, setSwitchingBranchName] = useState<string | null>(null);+ const selectingBranchNameRef = useRef<string | null>(null);+ const allowSelectionNavigationRef = useRef(false);+ const mountedRef = useRef(true);+ const screenTitle = flow.workspaceMode === "worktree" ? "Base branch" : "Branch";+ const usesNativeMailSearchToolbar = Platform.OS === "ios" && NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED;+ const selectedBranchName =+ flow.selectedBranchName ??+ flow.availableBranches.find((branch) => branch.current)?.name ??+ flow.availableBranches.find((branch) => branch.isDefault)?.name ??+ null;+ const branchListContentStyle = useMemo(+ () => ({+ paddingBottom: usesNativeMailSearchToolbar+ ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET + 16+ : Platform.OS === "ios"+ ? 16+ : Math.max(insets.bottom, 16) + 16,+ paddingHorizontal: 16,+ paddingTop: 12,+ }),+ [insets.bottom, usesNativeMailSearchToolbar],+ );++ useEffect(() => {+ mountedRef.current = true;+ return () => {+ mountedRef.current = false;+ flow.setBranchQuery("");+ };+ }, [flow.setBranchQuery]);++ useEffect(+ () =>+ navigation.addListener("beforeRemove", (event) => {+ if (selectingBranchNameRef.current !== null && !allowSelectionNavigationRef.current) {+ event.preventDefault();+ }+ }),+ [navigation],+ );++ const selectBranch = useCallback(+ async (branch: VcsRef) => {+ if (selectingBranchNameRef.current !== null) {+ return;+ }+ selectingBranchNameRef.current = branch.name;+ void Haptics.selectionAsync();++ try {+ let selectedBranch = branch;+ const needsCheckout = shouldCheckoutNewTaskBranch({+ branchIsCurrent: branch.current,+ branchWorktreePath: branch.worktreePath,+ workspaceMode: flow.workspaceMode,+ });+ if (needsCheckout && flow.selectedProject) {+ setSwitchingBranchName(branch.name);+ const result = await switchRef({+ environmentId: flow.selectedProject.environmentId,+ input: {+ cwd: flow.selectedProject.workspaceRoot,+ refName: branch.name,+ },+ });+ if (result._tag === "Failure") {+ if (mountedRef.current && navigation.isFocused() && !isAtomCommandInterrupted(result)) {+ const error = squashAtomCommandFailure(result);+ Alert.alert(+ "Could not switch branch",+ error instanceof Error ? error.message : "The branch could not be checked out.",+ );+ }+ return;+ }+ selectedBranch = {+ ...branch,+ current: true,+ isRemote: false,+ name: result.value.refName ?? branch.name,+ };+ }++ // The checkout has already changed the repository. Persist the matching+ // draft selection even if the native sheet was dismissed while the+ // command was in flight; only visible-screen work is focus-gated below.+ flow.selectBranch(selectedBranch);+ if (!mountedRef.current || !navigation.isFocused()) {+ return;+ }+ flow.setBranchQuery("");+ allowSelectionNavigationRef.current = true;+ navigation.goBack();+ } finally {+ selectingBranchNameRef.current = null;+ allowSelectionNavigationRef.current = false;+ if (mountedRef.current) {+ setSwitchingBranchName(null);+ }+ }+ },+ [+ flow.selectBranch,+ flow.selectedProject,+ flow.setBranchQuery,+ flow.workspaceMode,+ navigation,+ switchRef,+ ],+ );++ const renderBranch = useCallback(+ ({ item, index }: { readonly item: VcsRef; readonly index: number }) => (+ <BranchSelectionRow+ badge={branchBadgeLabel({ branch: item, project: flow.selectedProject })}+ branch={item}+ disabled={switchingBranchName !== null}+ isFirst={index === 0}+ isLast={index === flow.filteredBranches.length - 1}+ onSelect={selectBranch}+ selected={selectedBranchName === item.name}+ />+ ),+ [+ flow.filteredBranches.length,+ flow.selectedProject,+ selectBranch,+ selectedBranchName,+ switchingBranchName,+ ],+ );++ const branchListHeader =+ flow.workspaceMode === "worktree" ? (+ <View className="mb-3 overflow-hidden rounded-2xl">+ <ToggleRow+ onValueChange={flow.setStartFromOrigin}+ title="Start from origin"+ value={flow.startFromOrigin}+ />+ </View>+ ) : null;++ const branchContent =+ flow.filteredBranches.length === 0 ? (+ <ScrollView+ className="flex-1 bg-sheet"+ contentInsetAdjustmentBehavior="automatic"+ contentContainerStyle={{ flexGrow: 1, paddingHorizontal: 16, paddingTop: 12 }}+ scrollEnabled={false}+ showsVerticalScrollIndicator={false}+ >+ {branchListHeader}+ <View+ className="flex-1 items-center justify-center gap-3 px-4"+ style={{+ marginBottom: usesNativeMailSearchToolbar+ ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET+ : 0,+ }}+ >+ {flow.branchesLoading ? <ActivityIndicator /> : null}+ <Text className="text-center text-sm text-foreground-muted">+ {flow.branchesLoading+ ? "Loading branches…"+ : flow.branchesError+ ? flow.branchesError+ : flow.branchQuery+ ? "No matching branches"+ : "No branches available"}+ </Text>+ {!flow.branchesLoading && flow.branchesError ? (+ <Pressable+ accessibilityRole="button"+ className="rounded-full bg-card px-4 py-2 active:opacity-70"+ onPress={flow.loadBranches}+ >+ <Text className="text-sm font-t3-medium text-foreground">Try again</Text>+ </Pressable>+ ) : null}+ </View>+ </ScrollView>+ ) : (+ <LegendList+ alwaysBounceVertical={false}+ automaticallyAdjustsScrollIndicatorInsets+ automaticallyAdjustKeyboardInsets={Platform.OS === "ios"}+ className="flex-1 bg-sheet"+ contentInsetAdjustmentBehavior="automatic"+ contentContainerStyle={branchListContentStyle}+ data={flow.filteredBranches}+ keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}+ keyboardShouldPersistTaps="handled"+ keyExtractor={(branch) =>+ `${branch.remoteName ?? "local"}:${branch.name}:${branch.worktreePath ?? ""}`+ }+ ListHeaderComponent={branchListHeader}+ ListFooterComponent={+ flow.branchesFetchingNextPage ? (+ <View className="items-center py-4">+ <ActivityIndicator />+ </View>+ ) : null+ }+ onEndReached={flow.hasMoreBranches ? flow.loadMoreBranches : undefined}+ onEndReachedThreshold={0.35}+ renderItem={renderBranch}+ showsVerticalScrollIndicator={false}+ />+ );++ if (Platform.OS === "android") {+ return (+ <View className="flex-1 bg-sheet" collapsable={false}>+ <NativeStackScreenOptions options={{ headerShown: false }} />+ <AndroidScreenHeader title={screenTitle} onBack={() => navigation.goBack()} />+ <View className="px-4 pb-2 pt-3">+ <TextInput+ autoCapitalize="none"+ autoCorrect={false}+ className="h-11 rounded-xl bg-card px-4 text-base text-foreground"+ onChangeText={flow.setBranchQuery}+ placeholder="Find a branch"+ placeholderTextColor={placeholderColor}+ style={{ color: foregroundColor, fontFamily }}+ value={flow.branchQuery}+ />+ </View>+ {branchContent}+ </View>+ );+ }++ return (+ <>+ <NativeStackScreenOptions+ options={{+ headerShown: true,+ title: screenTitle,+ unstable_headerToolbarItems: usesNativeMailSearchToolbar+ ? () => [+ createNativeMailSearchToolbarItem({+ onSearchTextChange: flow.setBranchQuery,+ placeholder: "Find a branch",+ searchTextChangeId: "new-task-branch-search-text",+ showsSearchDismissButton: true,+ }),+ ]+ : undefined,+ headerSearchBarOptions: usesNativeMailSearchToolbar+ ? undefined+ : {+ allowToolbarIntegration: true,+ autoCapitalize: "none",+ hideNavigationBar: false,+ obscureBackground: false,+ placeholder: "Find a branch",+ onChangeText: (event) => {+ flow.setBranchQuery(event.nativeEvent.text);+ },+ onCancelButtonPress: () => {+ flow.setBranchQuery("");+ },+ },+ }}+ />+ {usesNativeMailSearchToolbar ? null : (+ <NativeHeaderToolbar placement="bottom">+ <NativeHeaderToolbar.SearchBarSlot />+ </NativeHeaderToolbar>+ )}+ {branchContent}+ </>+ );+}diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsxindex 1ece23ca0..87b12ad22 100644--- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx+++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx@@ -1,9 +1,14 @@-import { NativeStackScreenOptions } from "../../native/StackHeader";-import { StackActions, useNavigation, usePreventRemove } from "@react-navigation/native";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { Alert, InteractionManager, Platform, View, useColorScheme } from "react-native";+import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";import {- KeyboardAvoidingView,+ StackActions,+ useFocusEffect,+ useNavigation,+ usePreventRemove,+} from "@react-navigation/native";+import { useCallback, useEffect, useRef, useState } from "react";+import { Alert, Platform, Pressable, ScrollView, View, useColorScheme } from "react-native";+import {+ KeyboardController,KeyboardStickyView,useKeyboardState,} from "react-native-keyboard-controller";@@ -11,7 +16,6 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";import { useThemeColor } from "../../lib/useThemeColor";import { useFontFamily } from "../../lib/useFontFamily";-import { EnvironmentId } from "@t3tools/contracts";import {isAtomCommandInterrupted,squashAtomCommandFailure,@@ -19,22 +23,24 @@ import {import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";import {+ ComposerInlineControl,ComposerToolbarButton,ComposerToolbarRow,ComposerToolbarScroller,- ComposerToolbarTrigger,-} from "../../components/ComposerToolbarTrigger";+} from "../../components/ComposerToolbar";import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";-import { ControlPill, ControlPillMenu } from "../../components/ControlPill";import { ProviderIcon } from "../../components/ProviderIcon";+import { SymbolView } from "../../components/AppSymbol";+import { AppText as Text } from "../../components/AppText";import { ComposerSurface } from "./ThreadComposer";-import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet";-import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation";+import {+ useThreadSettingsSheetPresentation,+ type NavigationWithFinishTransitioning,+} from "./use-thread-settings-sheet-presentation";import { makeTurnCommandMetadata } from "../../lib/commandMetadata";import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";-import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";import {clearComposerDraftContent,@@ -49,21 +55,33 @@ import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";-import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";+import { useNewTaskFlow } from "./new-task-flow-provider";import { useCreateProjectThread } from "./use-project-actions";import { resolveDraftProjectSelection } from "./new-task-project-selection";+import {+ resolveNewTaskBranchLabel,+ resolveNewTaskWorkspaceLabel,+} from "./new-task-context-presentation";import { useIncomingShare } from "../sharing/IncomingShareProvider";-function formatWorkspaceLabel(input: {- readonly workspaceMode: string;- readonly currentBranchName: string | null;- readonly selectedBranchName: string | null;-}): string {- const branchName = input.selectedBranchName ?? input.currentBranchName;- if (input.workspaceMode === "worktree") {- return branchName ? `New worktree · ${branchName}` : "New worktree";+function NewTaskWorkspaceIcon(props: {+ readonly workspaceMode: "local" | "worktree";+ readonly worktreePath: string | null;+}) {+ const iconColor = useThemeColor("--color-icon-muted");++ if (props.workspaceMode === "local" && props.worktreePath === null) {+ return <SymbolView name="folder" size={16} tintColor={iconColor} type="monochrome" />;}- return branchName ? `Current · ${branchName}` : "Current checkout";++ return (+ <View className="size-4">+ <SymbolView name="folder" size={16} tintColor={iconColor} type="monochrome" />+ <View className="absolute -right-1 -bottom-1">+ <SymbolView name="arrow.triangle.branch" size={9} tintColor={iconColor} type="monochrome" />+ </View>+ </View>+ );}export function NewTaskDraftScreen(props: {@@ -90,7 +108,8 @@ export function NewTaskDraftScreen(props: {const insets = useSafeAreaInsets();const colorScheme = useColorScheme();const isKeyboardVisible = useKeyboardState((state) => state.isVisible);- const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);+ const controlsBottomPadding = Math.max(insets.bottom, 10);+ const keyboardOpenedOffset = Math.max(0, controlsBottomPadding - 8);const { projectScopes, selectedProject, selectedProjectKey, setProject } = flow;const { connectedEnvironments } = useRemoteConnectionStatus();const selectedEnvironmentServerConfig = useEnvironmentServerConfig(@@ -108,6 +127,49 @@ export function NewTaskDraftScreen(props: {editorRef: promptInputRef,isEditorFocused: isComposerFocused,});+ useEffect(() => {+ if (Platform.OS !== "ios") {+ return;+ }++ navigation.getParent()?.setOptions({ gestureEnabled: !isKeyboardVisible });+ }, [isKeyboardVisible, navigation]);+ useEffect(() => {+ return () => {+ if (Platform.OS === "ios") {+ navigation.getParent()?.setOptions({ gestureEnabled: true });+ }+ };+ }, [navigation]);+ const settingsRoutePresentedRef = useRef(false);+ useEffect(() => {+ if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {+ return;+ }++ settingsRoutePresentedRef.current = true;+ navigation.dispatch(StackActions.push("ThreadSettings"));+ }, [navigation, settingsSheetPresentation.isVisible]);+ useFocusEffect(+ useCallback(() => {+ if (!settingsRoutePresentedRef.current) {+ return;+ }++ settingsRoutePresentedRef.current = false;+ settingsSheetPresentation.onDismissed();+ }, [settingsSheetPresentation.onDismissed]),+ );+ useEffect(+ () =>+ // UIKit's completion callback for the sheet dismissal, surfaced by the+ // native-stack patch. This is when the queued keyboard restore runs.+ (navigation as unknown as NavigationWithFinishTransitioning).addListener(+ "finishTransitioning",+ settingsSheetPresentation.onStackTransitionsFinished,+ ),+ [navigation, settingsSheetPresentation.onStackTransitionsFinished],+ );const [importingShareKey, setImportingShareKey] = useState<string | null>(null);const [isCancellingShareImport, setIsCancellingShareImport] = useState(false);const [cancelledIncomingShareId, setCancelledIncomingShareId] = useState<string | null>(null);@@ -227,9 +289,9 @@ export function NewTaskDraftScreen(props: {}, [props.pendingTaskId, cancelEditingPendingTask]);const foregroundColor = useThemeColor("--color-foreground");+ const projectUnderlineColor = useThemeColor("--color-foreground-muted");const regularFontFamily = useFontFamily("regular");const bodyText = useScaledTextRole("body");- const headlineText = useScaledTextRole("headline");const sheetFadeOpaque = colorScheme === "dark" ? "rgba(14,14,14,0.98)" : "rgba(242,242,247,0.98)";const sheetFadeTransparent = colorScheme === "dark" ? "rgba(14,14,14,0)" : "rgba(242,242,247,0)";@@ -315,7 +377,7 @@ export function NewTaskDraftScreen(props: {return;}loadedBranchesProjectKeyRef.current = projectKey;- void flow.loadBranches();+ flow.loadBranches();}, [flow.loadBranches, selectedProject]);useEffect(() => {@@ -517,121 +579,6 @@ export function NewTaskDraftScreen(props: {shareImportAttempt,]);- useEffect(() => {- // Android starts with the collapsed composer pill (like an open thread)- // and only expands/focuses when tapped.- if (!selectedProject || Platform.OS === "android") {- return;- }-- let focusFrame: ReturnType<typeof requestAnimationFrame> | null = null;- const interaction = InteractionManager.runAfterInteractions(() => {- 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 () => {- interaction.cancel();- if (focusFrame !== null) {- cancelAnimationFrame(focusFrame);- }- };- }, [- selectedProject,- settingsSheetPresentation.isActiveRef,- settingsSheetPresentation.restoreFocusAfterSave,- ]);-- const environmentMenuActions = useMemo(- () =>- flow.environments.map((environment) => ({- id: `environment:${environment.environmentId}`,- title: environment.environmentLabel,- attributes: isIncomingShareTransferPending ? { disabled: true } : undefined,- state:- flow.selectedEnvironmentId === environment.environmentId ? ("on" as const) : undefined,- })),- [flow.environments, flow.selectedEnvironmentId, isIncomingShareTransferPending],- );-- const providerOptionDescriptors = useMemo(- () =>- resolveProviderOptionDescriptors({- capabilities: flow.selectedModelOption?.capabilities,- selections: flow.selectedModel?.options,- }),- [flow.selectedModel?.options, flow.selectedModelOption?.capabilities],- );-- const workspaceMenuActions = useMemo(() => {- const branchActions =- flow.availableBranches.length === 0- ? [- {- id: "workspace:branch:none",- title: flow.branchesLoading ? "Loading branches…" : "No branches available",- attributes: { disabled: true },- },- ]- : flow.availableBranches.slice(0, 12).map((branch) => {- const badge = branchBadgeLabel({- branch,- project: flow.selectedProject,- });-- return {- id: `workspace:branch:${branch.name}`,- title: branch.name,- subtitle: badge ? badge.toUpperCase() : undefined,- state: flow.selectedBranchName === branch.name ? ("on" as const) : undefined,- };- });-- return [- {- id: "workspace:mode",- title: "Mode",- subtitle: flow.workspaceMode === "local" ? "Current checkout" : "New worktree",- subactions: (["local", "worktree"] as const).map((value) => ({- id: `workspace:mode:${value}`,- title: value === "local" ? "Current checkout" : "New worktree",- state: flow.workspaceMode === value ? ("on" as const) : undefined,- })),- },- {- id: "workspace:branch",- title: "Branch",- subtitle: flow.selectedBranchName ?? "Choose branch",- subactions: branchActions,- },- ...(flow.workspaceMode === "worktree"- ? [- {- id: "workspace:start-from-origin",- title: "Start from origin",- subtitle: "Base the worktree on the latest origin branch",- image: "arrow.triangle.pull",- state: flow.startFromOrigin ? ("on" as const) : undefined,- },- ]- : []),- ];- }, [- flow.availableBranches,- flow.branchesLoading,- flow.selectedBranchName,- flow.selectedProject,- flow.startFromOrigin,- flow.workspaceMode,- ]);-const selectedEnvironmentLabel =flow.environments.find((environment) => environment.environmentId === flow.selectedEnvironmentId,@@ -640,50 +587,17 @@ export function NewTaskDraftScreen(props: {flow.availableBranches.find((branch) => branch.current)?.name ??flow.availableBranches.find((branch) => branch.isDefault)?.name ??null;- const settingsSummaryLabel = threadSettingsSummaryLabel({- modelLabel: flow.selectedModelOption?.label ?? "Model",- optionDescriptors: providerOptionDescriptors,- runtimeMode: flow.runtimeMode,- interactionMode: flow.interactionMode,+ const selectedBranchName = flow.selectedBranchName ?? currentBranchName;+ const selectedBranchLabel = resolveNewTaskBranchLabel({+ branchName: selectedBranchName,+ startFromOrigin: flow.startFromOrigin,+ workspaceMode: flow.workspaceMode,});- const workspaceLabel = useMemo(- () =>- formatWorkspaceLabel({- currentBranchName,- selectedBranchName: flow.selectedBranchName,- workspaceMode: flow.workspaceMode,- }),- [currentBranchName, flow.selectedBranchName, flow.workspaceMode],- );- function handleEnvironmentMenuAction(event: string) {- if (isIncomingShareTransferPending || !event.startsWith("environment:")) {- return;- }- flow.selectEnvironment(EnvironmentId.make(event.slice("environment:".length)));- }-- function handleWorkspaceMenuAction(event: string) {- if (isIncomingShareTransferPending) {- return;- }- if (event.startsWith("workspace:mode:")) {- flow.setWorkspaceMode(- event.slice("workspace:mode:".length) as Parameters<typeof flow.setWorkspaceMode>[0],- );- return;- }- if (event === "workspace:start-from-origin") {- flow.setStartFromOrigin(!flow.startFromOrigin);- return;- }- if (event.startsWith("workspace:branch:")) {- const branchName = event.slice("workspace:branch:".length);- const branch = flow.availableBranches.find((candidate) => candidate.name === branchName);- if (branch) {- flow.selectBranch(branch);- }- }- }+ const workspaceLabel = resolveNewTaskWorkspaceLabel({+ workspaceMode: flow.workspaceMode,+ worktreePath: flow.selectedWorktreePath,+ });+ const showBranchLoading = flow.branchesLoading && flow.availableBranches.length === 0;async function handlePickImages(): Promise<void> {if (isIncomingShareTransferPending) {@@ -733,7 +647,9 @@ export function NewTaskDraftScreen(props: {draft.workspaceSelection?.worktreePath ?? flow.selectedWorktreePath;const startFromOrigin = draft.workspaceSelection?.startFromOrigin ?? flow.startFromOrigin;const runtimeMode = draft.runtimeMode ?? flow.runtimeMode;- const interactionMode = draft.interactionMode ?? flow.interactionMode;+ const interactionMode = flow.planModeEnabled+ ? (draft.interactionMode ?? flow.interactionMode)+ : "default";const initialMessageText = draft.text.trim();if (@@ -851,7 +767,7 @@ export function NewTaskDraftScreen(props: {if (!selectedProject) {return (- <View className="flex-1 bg-sheet">+ <View className="flex-1 bg-sheet" collapsable={false}>{Platform.OS === "android" ? (<><NativeStackScreenOptions options={{ headerShown: false }} />@@ -866,11 +782,6 @@ export function NewTaskDraftScreen(props: {const isAndroid = Platform.OS === "android";const isDarkMode = colorScheme === "dark";- // Android expansion follows native editor focus so relayout cannot race- // the touch gesture that opens the keyboard.- // 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) &&@@ -882,235 +793,279 @@ export function NewTaskDraftScreen(props: {const promptEditor = (<ComposerEditorref={promptInputRef}- // Native autoFocus fires becomeFirstResponder in didMoveToWindow, which- // forces the iOS keyboard bring-up during the formSheet present- // animation and stalls it. The runAfterInteractions effect above focuses- // the editor once the transition settles instead.+ // The context-first screen intentionally opens with the keyboard closed.+ // Focusing is a user action, so presenting the form sheet has one motion.autoFocus={false}editable={!isIncomingShareTransferPending}multiline- scrollEnabled={isExpanded}+ scrollEnabledvalue={flow.prompt}skills={flow.selectedProviderSkills}onChangeText={flow.setPrompt}onFocus={() => setIsComposerFocused(true)}onBlur={() => setIsComposerFocused(false)}onPasteImages={(uris) => void handleNativePasteImages(uris)}- placeholder={`Describe a coding task in ${selectedProject.title}`}- // Same collapsed centering as ThreadComposer: native vertical gravity- // in a pill-height box.- singleLineCentered={!isExpanded}- contentInsetVertical={isAndroid ? 0 : undefined}- style={- isAndroid- ? isExpanded- ? { minHeight: 80, maxHeight: 160, paddingHorizontal: 4, paddingVertical: 4 }- : { height: 36 }- : { flex: 1, minHeight: 0 }- }- textStyle={- isAndroid- ? { ...bodyText, color: foregroundColor, fontFamily: regularFontFamily }- : headlineText- }+ placeholder="Ask anything…"+ singleLineCentered={false}+ contentInsetVertical={0}+ style={{+ minHeight: 72,+ maxHeight: 160,+ paddingHorizontal: 4,+ paddingVertical: 4,+ }}+ textStyle={{ ...bodyText, color: foregroundColor, fontFamily: regularFontFamily }}/>);- const toolbarPills = (- <>- <ComposerToolbarButton- icon="plus"- onPress={() => void handlePickImages()}- showChevron={false}- disabled={isIncomingShareTransferPending}- />- <ComposerToolbarTrigger- accessibilityLabel="Thread settings"+ const closeNewTask = () => {+ void KeyboardController.dismiss({ animated: true });+ const parentNavigation = navigation.getParent();+ if (parentNavigation) {+ parentNavigation.goBack();+ return;+ }+ navigation.goBack();+ };+ const chooseProject = () => {+ if (isIncomingShareTransferPending) {+ return;+ }+ promptInputRef.current?.blur();+ void KeyboardController.dismiss({ animated: true });+ navigation.dispatch(StackActions.push("NewTask", { incomingShareId: props.incomingShareId }));+ };+ const openContextPicker = (routeName: "NewTaskBranch" | "NewTaskEnvironment") => {+ if (isIncomingShareTransferPending) {+ return;+ }+ promptInputRef.current?.blur();+ void KeyboardController.dismiss({ animated: true });+ navigation.dispatch(StackActions.push(routeName));+ };++ const hero = (+ <View className="items-center gap-6 px-6" testID="new-task-hero">+ <View className="w-full items-center gap-1.5">+ <Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">+ What should we build+ </Text>+ <View className="max-w-full flex-row items-center justify-center">+ <Text className="text-2xl font-t3-medium tracking-tight text-foreground">in </Text>+ <Pressable+ accessibilityHint="Opens the project picker"+ accessibilityLabel={`Change project from ${selectedProject.title}`}+ accessibilityRole="button"+ disabled={isIncomingShareTransferPending}+ onPress={chooseProject}+ className="min-w-0 max-w-[250px] active:opacity-65"+ style={{+ borderBottomColor: projectUnderlineColor,+ borderBottomWidth: 1,+ }}+ >+ <Text+ className="text-2xl font-t3-medium tracking-tight text-foreground"+ numberOfLines={1}+ >+ {selectedProject.title}+ </Text>+ </Pressable>+ <Text className="text-2xl font-t3-medium tracking-tight text-foreground">?</Text>+ </View>+ </View>++ <ComposerInlineControl+ accessibilityLabel={`Environment: ${selectedEnvironmentLabel}`}+ chevronDirection="right"disabled={isIncomingShareTransferPending}- iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />}- label={settingsSummaryLabel}- maxWidth={320}- onPress={settingsSheetPresentation.open}+ icon="desktopcomputer"+ label={`on ${selectedEnvironmentLabel}`}+ maxWidth={260}+ onPress={+ flow.environments.length > 1 ? () => openContextPicker("NewTaskEnvironment") : undefined+ }+ showChevron={flow.environments.length > 1}+ static={flow.environments.length <= 1}/>- <ControlPillMenu- actions={environmentMenuActions}- onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}- >- <ComposerToolbarTrigger- accessibilityLabel="Environment"- disabled={isIncomingShareTransferPending}- icon="desktopcomputer"- label={selectedEnvironmentLabel}- />- </ControlPillMenu>- <ControlPillMenu- actions={workspaceMenuActions}- onPressAction={({ nativeEvent }) => handleWorkspaceMenuAction(nativeEvent.event)}+ </View>+ );+ const heroViewport = (+ <View className="flex-1" collapsable={false}>+ <ScrollView+ alwaysBounceVertical={isKeyboardVisible}+ className="flex-1"+ contentInsetAdjustmentBehavior="never"+ contentContainerClassName="grow items-center pb-[236px] pt-12 ios:pt-[72px]"+ keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}+ keyboardShouldPersistTaps="handled"+ showsVerticalScrollIndicator={false}+ style={{ flex: 1 }}+ testID="new-task-hero-scroll">- <ComposerToolbarTrigger- accessibilityLabel="Workspace"- disabled={isIncomingShareTransferPending}- icon="point.topleft.down.curvedto.point.bottomright.up"- label={workspaceLabel}- />- </ControlPillMenu>- </>+ {hero}+ </ScrollView>+ </View>);- 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 workspaceControls = (+ <View className="flex-row items-center gap-1 px-2">+ <ComposerInlineControl+ accessibilityHint={`Switches to ${flow.workspaceMode === "local" ? "a new worktree" : "the current checkout"}`}+ accessibilityLabel={workspaceLabel}+ disabled={isIncomingShareTransferPending}+ iconNode={+ <NewTaskWorkspaceIcon+ workspaceMode={flow.workspaceMode}+ worktreePath={flow.selectedWorktreePath}+ />+ }+ label={workspaceLabel}+ maxWidth={flow.workspaceMode === "local" ? 220 : 148}+ onPress={() => flow.setWorkspaceMode(flow.workspaceMode === "local" ? "worktree" : "local")}+ showChevron={false}+ />++ <ComposerInlineControl+ accessibilityLabel={`${flow.workspaceMode === "worktree" ? "Base branch" : "Branch"}: ${selectedBranchLabel}`}+ chevronDirection="right"+ disabled={isIncomingShareTransferPending}+ icon="arrow.triangle.branch"+ label={showBranchLoading ? "Loading branches…" : selectedBranchLabel}+ maxWidth={190}+ onPress={() => openContextPicker("NewTaskBranch")}+ />+ </View>);- const startButton = (- <ComposerToolbarButton- accessibilityLabel={- flow.submitting ? "Starting task" : environmentConnected ? "Start task" : "Queue task"- }- icon={environmentConnected ? "arrow.up" : "tray.and.arrow.up"}- onPress={() => void handleStart()}- variant="primary"- showChevron={false}- disabled={!canStart}- />+ const composerDock = (+ <View className="bg-sheet px-4 pt-1" style={{ paddingBottom: controlsBottomPadding }}>+ <View className="pb-1">{workspaceControls}</View>++ <ComposerSurface+ animateLayout={false}+ isDarkMode={isDarkMode}+ style={{+ borderRadius: 26,+ minHeight: 140,+ overflow: "hidden",+ paddingBottom: 6,+ paddingHorizontal: 14,+ paddingTop: 14,+ }}+ >+ {flow.attachments.length > 0 ? (+ <View className="pb-2.5">+ <ComposerAttachmentStrip+ attachments={flow.attachments}+ imageBorderRadius={16}+ imageSize={72}+ onRemove={isIncomingShareTransferPending ? () => undefined : flow.removeAttachment}+ />+ </View>+ ) : null}++ {promptEditor}++ <ComposerToolbarRow paddingBottom={0} paddingHorizontal={0} paddingTop={4}>+ <ComposerToolbarScroller+ fadeOpaque={sheetFadeOpaque}+ fadeTransparent={sheetFadeTransparent}+ contentPaddingRight={8}+ >+ <ComposerToolbarButton+ accessibilityLabel="Add attachment"+ disabled={isIncomingShareTransferPending}+ icon="plus"+ onPress={() => void handlePickImages()}+ showChevron={false}+ />+ <ComposerInlineControl+ accessibilityLabel="Model and reasoning settings"+ disabled={isIncomingShareTransferPending}+ emphasized+ iconNode={+ <ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />+ }+ label={flow.selectedModelOption?.label ?? "Choose model"}+ maxWidth={152}+ onPress={settingsSheetPresentation.open}+ />+ {flow.planModeEnabled ? (+ <ComposerInlineControl+ accessibilityHint={`Switches to ${flow.interactionMode === "plan" ? "Build" : "Plan"} mode`}+ accessibilityLabel={`Interaction mode: ${flow.interactionMode === "plan" ? "Plan" : "Build"}`}+ disabled={isIncomingShareTransferPending}+ emphasized+ icon={+ flow.interactionMode === "plan"+ ? { ios: "list.bullet.clipboard", android: "auto_awesome" }+ : { ios: "hammer", android: "construction" }+ }+ label={flow.interactionMode === "plan" ? "Plan" : "Build"}+ onPress={() =>+ flow.setInteractionMode(flow.interactionMode === "plan" ? "default" : "plan")+ }+ showChevron={false}+ />+ ) : null}+ </ComposerToolbarScroller>+ <ComposerToolbarButton+ accessibilityLabel={+ flow.submitting ? "Starting task" : environmentConnected ? "Start task" : "Queue task"+ }+ disabled={!canStart}+ icon={environmentConnected ? "arrow.up" : "tray.and.arrow.up"}+ onPress={() => void handleStart()}+ showChevron={false}+ variant="primary"+ />+ </ComposerToolbarRow>+ </ComposerSurface>+ </View>);if (isAndroid) {- // The draft is a thread that doesn't exist yet, so it mirrors the thread- // page: in-screen header, empty feed canvas above, and the same floating- // composer chrome as ThreadComposer (collapsed pill → expanded card).- //- // Composer positioning mirrors ThreadDetailScreen's floating overlay- // (KeyboardStickyView, absolute bottom overlay) rather than- // KeyboardAvoidingView's automaticOffset+padding: automaticOffset- // resolves the composer's on-screen frame via a native- // viewPositionInWindow measurement, which this app's Android- // edge-to-edge setup (KeyboardProvider's native content-view margin- // handling neutralizes windowSoftInputMode="adjustResize" while active)- // makes unreliable — the composer stayed under the keyboard instead of- // translating above it. KeyboardStickyView sticks directly to the- // animated keyboard height instead, sidestepping that measurement.return (- <View className="flex-1 bg-screen">+ <View className="flex-1 bg-sheet" collapsable={false}><NativeStackScreenOptions options={{ headerShown: false }} />- <AndroidScreenHeader title="New Thread" onBack={() => navigation.goBack()} />-- <View className="flex-1" />+ <AndroidScreenHeader title="New task" onBack={closeNewTask} />+ {heroViewport}<KeyboardStickyView- enabled={isKeyboardVisible}style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}- offset={{ closed: 0, opened: 0 }}+ offset={{ closed: 0, opened: keyboardOpenedOffset }}>- <View- className="px-4 pt-2"- style={{- paddingBottom: controlsBottomPadding,- experimental_backgroundImage: isDarkMode- ? "linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0.85) 40%, rgba(0,0,0,0.95) 100%)"- : "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.85) 40%, rgba(255,255,255,0.95) 100%)",- }}- >- <ComposerSurface- isDarkMode={isDarkMode}- style={- isExpanded- ? {- borderRadius: 20,- overflow: "hidden",- paddingHorizontal: 14,- paddingVertical: 12,- }- : {- borderRadius: 999,- overflow: "hidden",- flexDirection: "row",- alignItems: "center",- paddingLeft: 18,- paddingRight: 5,- paddingVertical: 5,- }- }- >- {isExpanded && flow.attachments.length > 0 ? (- <View className="pb-2.5">- <ComposerAttachmentStrip- attachments={flow.attachments}- onRemove={- isIncomingShareTransferPending ? () => undefined : flow.removeAttachment- }- />- </View>- ) : null}- <View className={isExpanded ? undefined : "min-w-0 flex-1"}>{promptEditor}</View>- {!isExpanded ? (- <ControlPill- icon="arrow.up"- variant="primary"- disabled={!canStart}- onPress={() => void handleStart()}- />- ) : null}- </ComposerSurface>-- {isExpanded ? (- <ComposerToolbarRow paddingBottom={8} paddingHorizontal={0} paddingTop={8}>- <ComposerToolbarScroller- fadeOpaque={isDarkMode ? "rgba(0,0,0,0.95)" : "rgba(255,255,255,0.95)"}- fadeTransparent={isDarkMode ? "rgba(0,0,0,0)" : "rgba(255,255,255,0)"}- >- {toolbarPills}- </ComposerToolbarScroller>- {startButton}- </ComposerToolbarRow>- ) : null}- </View>+ {composerDock}</KeyboardStickyView>- {settingsSheet}</View>);}return (- <View className="flex-1 bg-sheet">- <NativeStackScreenOptions options={{ title: selectedProject.title }} />-- <KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">- <View className="min-h-0 flex-1 px-5 pt-2">{promptEditor}</View>+ <View className="flex-1 bg-sheet" collapsable={false}>+ <NativeStackScreenOptions+ options={{+ headerBackVisible: false,+ headerShadowVisible: false,+ title: "",+ }}+ />+ <NativeHeaderToolbar placement="left">+ <NativeHeaderToolbar.Button+ accessibilityLabel="Cancel new task"+ label="Cancel"+ onPress={closeNewTask}+ />+ </NativeHeaderToolbar>- <View className="border-t border-border" style={{ paddingBottom: controlsBottomPadding }}>- {flow.attachments.length > 0 ? (- <View className="px-4 pt-3">- <ComposerAttachmentStrip- attachments={flow.attachments}- onRemove={isIncomingShareTransferPending ? () => undefined : flow.removeAttachment}- imageSize={88}- imageBorderRadius={20}- />- </View>- ) : null}- <ComposerToolbarRow paddingBottom={controlsBottomPadding} paddingHorizontal={6}>- <ComposerToolbarScroller- fadeOpaque={sheetFadeOpaque}- fadeTransparent={sheetFadeTransparent}- >- {toolbarPills}- </ComposerToolbarScroller>- {startButton}- </ComposerToolbarRow>- </View>- </KeyboardAvoidingView>- {settingsSheet}+ {heroViewport}+ <KeyboardStickyView+ style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}+ offset={{ closed: 0, opened: keyboardOpenedOffset }}+ >+ {composerDock}+ </KeyboardStickyView></View>);}diff --git a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsxindex 7f4a68c08..94304448e 100644--- a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx+++ b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx@@ -1,8 +1,13 @@import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";-import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";+import {+ StackActions,+ useIsFocused,+ useNavigation,+ type StaticScreenProps,+} from "@react-navigation/native";import { SymbolView } from "../../components/AppSymbol";import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";-import { useEffect, useRef, useState } from "react";+import { useEffect, useRef } from "react";import { ActivityIndicator, Alert, Platform, Pressable, ScrollView, View } from "react-native";import { useSafeAreaInsets } from "react-native-safe-area-context";import { useThemeColor } from "../../lib/useThemeColor";@@ -14,10 +19,10 @@ import { ProjectFavicon } from "../../components/ProjectFavicon";import { useProjects } from "../../state/entities";import type { WorkspaceState } from "../../state/workspaceModel";import { useWorkspaceState } from "../../state/workspace";-import { scopedProjectKey } from "../../lib/scopedEntities";import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";import { useIncomingShare } from "../sharing/IncomingShareProvider";import { useNewTaskFlow } from "./new-task-flow-provider";+import { getProjectScopeSelectionTarget } from "./new-task-project-selection";type NewTaskRouteParams = {readonly incomingShareId?: string | string[];@@ -80,7 +85,7 @@ function deriveProjectEmptyState(catalogState: WorkspaceState): {export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParams | undefined>) {const projects = useProjects();- const { projectScopes } = useNewTaskFlow();+ const { projectScopes, selectedEnvironmentId, setProject } = useNewTaskFlow();const { state: catalogState } = useWorkspaceState();const navigation = useNavigation();const isFocused = useIsFocused();@@ -88,7 +93,6 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParaconst insets = useSafeAreaInsets();const chevronColor = useThemeColor("--color-chevron");const accentColor = useThemeColor("--color-icon-muted");- const [expandedGroupKeys, setExpandedGroupKeys] = useState<ReadonlySet<string>>(() => new Set());const { getShare, releaseShareReservation } = useIncomingShare();const routeShareId = Array.isArray(route.params?.incomingShareId)? route.params.incomingShareId[0]@@ -126,27 +130,22 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParareturn;}}- navigation.navigate("NewTaskSheet", {- screen: "NewTaskDraft",- params: {+ const state = navigation.getState();+ const previousRoute = state?.routes[state.index - 1];+ if (previousRoute?.name === "NewTaskDraft") {+ setProject(project);+ navigation.goBack();+ return;+ }++ navigation.dispatch(+ StackActions.push("NewTaskDraft", {environmentId: project.environmentId,projectId: project.id,title: project.title,incomingShareId: incomingShare?.id,- },- });- }-- function toggleGroup(groupKey: string): void {- setExpandedGroupKeys((current) => {- const next = new Set(current);- if (next.has(groupKey)) {- next.delete(groupKey);- } else {- next.add(groupKey);- }- return next;- });+ }),+ );}useEffect(() => {@@ -169,15 +168,14 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParareturn;}resumedDestinationKeyRef.current = destinationKey;- navigation.navigate("NewTaskSheet", {- screen: "NewTaskDraft",- params: {+ navigation.dispatch(+ StackActions.push("NewTaskDraft", {environmentId: reservedDestinationProject.environmentId,projectId: reservedDestinationProject.id,title: reservedDestinationProject.title,incomingShareId: incomingShare.id,- },- });+ }),+ );}, [incomingShare, isFocused, navigation, reservedDestinationProject]);return (@@ -196,7 +194,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara{accessibilityLabel: "Add project",icon: "plus",- onPress: () => navigation.navigate("NewTaskSheet", { screen: "AddProject" }),+ onPress: () => navigation.dispatch(StackActions.push("AddProject")),},]: []@@ -223,7 +221,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara{catalogState.hasReadyEnvironment ? (<NativeHeaderToolbar.Buttonicon="plus"- onPress={() => navigation.navigate("NewTaskSheet", { screen: "AddProject" })}+ onPress={() => navigation.dispatch(StackActions.push("AddProject"))}separateBackground/>) : null}@@ -263,7 +261,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara) : (<PressableclassName="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"- onPress={() => navigation.navigate("NewTaskSheet", { screen: "AddProject" })}+ onPress={() => navigation.dispatch(StackActions.push("AddProject"))}><Text className="text-sm font-t3-bold text-primary-foreground">Add new project@@ -275,22 +273,15 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">{projectScopes.map((scope, scopeIndex) => {const hasMultipleProjects = scope.projects.length > 1;- const expanded = expandedGroupKeys.has(scope.key);- const singleProject = hasMultipleProjects ? null : scope.projects[0];+ const selectionTarget = getProjectScopeSelectionTarget(scope, selectedEnvironmentId);return (<Viewkey={scope.key}className={cn(scopeIndex > 0 && "border-t border-border-subtle")}><Pressable- disabled={singleProject !== null && reservedDestinationProject !== null}- onPress={() => {- if (singleProject) {- void selectProject(singleProject);- } else {- toggleGroup(scope.key);- }- }}+ disabled={reservedDestinationProject !== null}+ onPress={() => void selectProject(selectionTarget)}className="flex-row items-center gap-3 bg-card px-4 py-3.5"><View className="h-7 w-7 items-center justify-center">@@ -311,52 +302,16 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara>{hasMultipleProjects? `${scope.projects.length} workspaces`- : singleProject?.workspaceRoot}+ : selectionTarget.workspaceRoot}</Text></View><SymbolView- name={hasMultipleProjects && expanded ? "chevron.down" : "chevron.right"}+ name="chevron.right"size={14}tintColor={chevronColor}type="monochrome"/></Pressable>- {hasMultipleProjects && expanded- ? scope.projects.map((project) => (- <Pressable- key={scopedProjectKey(project.environmentId, project.id)}- disabled={reservedDestinationProject !== null}- onPress={() => void selectProject(project)}- className="flex-row items-center gap-3 border-t border-border-subtle bg-card py-3 pr-4 pl-10"- >- <ProjectFavicon- environmentId={project.environmentId}- faviconPath={project.faviconPath}- size={18}- projectTitle={project.title}- workspaceRoot={project.workspaceRoot}- />- <View className="min-w-0 flex-1">- <Text className="text-sm font-t3-bold text-foreground">- {project.title}- </Text>- <Text- className="text-xs text-foreground-muted"- ellipsizeMode="middle"- numberOfLines={1}- >- {project.workspaceRoot}- </Text>- </View>- <SymbolView- name="chevron.right"- size={14}- tintColor={chevronColor}- type="monochrome"- />- </Pressable>- ))- : null}</View>);})}diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsxindex 6ce42aeb1..3fba0a351 100644--- a/apps/mobile/src/features/threads/ThreadComposer.tsx+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx@@ -1,4 +1,3 @@-import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";import type {EnvironmentId,MessageId,@@ -14,7 +13,7 @@ import {serializeComposerFileLink,type ComposerTrigger,} from "@t3tools/shared/composerTrigger";-import * as Haptics from "expo-haptics";+import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";import type { ReactNode } from "react";import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";import {@@ -41,18 +40,19 @@ import { scopedThreadKey } from "../../lib/scopedEntities";import { AppText as Text } from "../../components/AppText";import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";+import { GlassSurface } from "../../components/GlassSurface";import {ComposerEditor,type ComposerEditorHandle,type ComposerEditorSelection,} from "../../components/ComposerEditor";import {+ ComposerInlineControl,ComposerToolbarButton,ComposerToolbarRow,ComposerToolbarScroller,- ComposerToolbarTrigger,-} from "../../components/ComposerToolbarTrigger";-import { ControlPill, ControlPillMenu } from "../../components/ControlPill";+} from "../../components/ComposerToolbar";+import { ControlPill } from "../../components/ControlPill";import { ProviderIcon } from "../../components/ProviderIcon";import type { DraftComposerImageAttachment } from "../../lib/composerImages";import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";@@ -63,15 +63,17 @@ import {normalizeSearchQuery,scoreQueryMatch,} from "@t3tools/shared/searchRanking";-import {- applyProviderOptionSelection,- resolveProviderOptionDescriptors,-} from "../../lib/providerOptions";+import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";import { useComposerPathSearch } from "../../state/use-composer-path-search";import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";-import { buildThreadSettingsMenu } from "./thread-settings-menu";-import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet";-import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation";+import {+ type ExistingThreadSettingsRouteSession,+ useExistingThreadSettingsRoutePresentation,+} from "./ThreadSettingsSheet";+import {+ useThreadSettingsSheetPresentation,+ type NavigationWithFinishTransitioning,+} from "./use-thread-settings-sheet-presentation";/*** Height of the collapsed composer (pill + vertical padding, excluding safe-area inset).@@ -83,7 +85,7 @@ export const COMPOSER_COLLAPSED_CHROME = 60;* Height of the expanded composer (card + toolbar + vertical padding, excluding safe-area inset).* Used by the parent to compute the larger feed bottom inset when the composer is focused.*/-export const COMPOSER_EXPANDED_CHROME = 174;+export const COMPOSER_EXPANDED_CHROME = 156;export interface ThreadComposerProps {readonly draftMessage: string;@@ -123,8 +125,8 @@ export interface ThreadComposerProps {}/**- * The pill / card container — renders as LiquidGlassView on supported- * iOS 26+ devices (progressive blur, native morph), opaque View otherwise.+ * The pill / card container — renders with Expo's native GlassView on supported+ * iOS 26+ devices and keeps the existing opaque fallback elsewhere.* Exported so NewTaskDraftScreen can render the same composer chrome.*/// One timing for every piece of the expanded↔compact morph so the surface,@@ -140,6 +142,8 @@ export function ComposerSurface(props: {readonly children: ReactNode;readonly style: ViewStyle;readonly isDarkMode: boolean;+ /** Existing thread composers morph between pill and card layouts. */+ readonly animateLayout?: boolean;}) {// Drop shadow lives on a wrapper: `overflow: "hidden"` on the surface itself// (needed to clip content to the pill shape) would clip the shadow on iOS.@@ -152,35 +156,26 @@ export function ComposerSurface(props: {elevation: 10,};- if (isLiquidGlassSupported) {- return (- <Animated.View layout={COMPOSER_LAYOUT_TRANSITION} style={shadowStyle}>- <LiquidGlassView- effect="regular"- interactive- colorScheme={props.isDarkMode ? "dark" : "light"}- style={props.style}- >- {props.children}- </LiquidGlassView>- </Animated.View>- );- }-return (- <Animated.View layout={COMPOSER_LAYOUT_TRANSITION} style={shadowStyle}>- <View- style={[- props.style,- {- backgroundColor: props.isDarkMode ? "rgba(44,44,46,0.96)" : "rgba(255,255,255,0.96)",- borderWidth: 1,- borderColor: props.isDarkMode ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.06)",- },- ]}+ <Animated.View+ layout={props.animateLayout === false ? undefined : COMPOSER_LAYOUT_TRANSITION}+ style={shadowStyle}+ >+ <GlassSurface+ chrome="none"+ fallbackStyle={{+ backgroundColor: props.isDarkMode ? "rgba(44,44,46,0.96)" : "rgba(255,255,255,0.96)",+ borderWidth: 1,+ borderColor: props.isDarkMode ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.06)",+ }}+ glassEffectStyle="regular"+ // The composer is a passive material containing interactive controls.+ // Expo GlassView defaults to non-interactive and both layouts share it.+ tintColor="transparent"+ style={props.style}>{props.children}- </View>+ </GlassSurface></Animated.View>);}@@ -271,6 +266,7 @@ const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill(});export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) {+ const navigation = useNavigation();const isDarkMode = useColorScheme() === "dark";const foregroundColor = useThemeColor("--color-foreground");const bodyText = useScaledTextRole("body");@@ -281,14 +277,16 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposereditorRef: inputRef,isEditorFocused: isFocused,});+ const settingsRoutePresentation = useExistingThreadSettingsRoutePresentation();+ const settingsRoutePresentedRef = useRef(false);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;- // Opening and closing count as active so the composer stays expanded while- // focus moves between its native editor and the settings modal.+ // Opening and presentation count as active so the composer stays expanded+ // while focus moves between its native editor and the settings picker.const isExpanded = isFocused || settingsSheetPresentation.isActive;const canSend = hasContent;@@ -334,7 +332,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer: "Send";const currentModelSelection = props.selectedThread.modelSelection;const currentRuntimeMode = props.selectedThread.runtimeMode;- const currentInteractionMode = props.selectedThread.interactionMode ?? "default";const connectionStatus = composerConnectionStatus({connectionError: props.connectionError,connectionState: props.connectionState,@@ -626,67 +623,71 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer}),[currentModelOption?.capabilities, currentModelSelection.options],);- const settingsSummaryLabel = threadSettingsSummaryLabel({- modelLabel: currentModelOption?.label ?? currentModelSelection.model,- optionDescriptors: providerOptionDescriptors,- runtimeMode: currentRuntimeMode,- interactionMode: currentInteractionMode,- });-- // iOS gets a native menu on the trigger pill: the everyday adjustments- // apply without resigning the keyboard, while "All Settings…" (and the- // Android trigger) still route through the sheet, which must dismiss it.- const settingsMenu = useMemo(- () =>- Platform.OS === "ios"- ? buildThreadSettingsMenu({- providerGroups: threadProviderGroups,- selectedModel: currentModelSelection,- optionDescriptors: providerOptionDescriptors,- runtimeMode: currentRuntimeMode,- })- : null,- [threadProviderGroups, currentModelSelection, providerOptionDescriptors, currentRuntimeMode],- );-- const onUpdateModelSelection = props.onUpdateModelSelection;- const onUpdateRuntimeMode = props.onUpdateRuntimeMode;- const handleSettingsMenuAction = useCallback(- (eventId: string) => {- const event = settingsMenu?.events.get(eventId);- if (!event) {- return;- }- switch (event.type) {- case "select-model":- void Haptics.selectionAsync();- onUpdateModelSelection(event.option.selection);- return;- case "set-option": {- const options = applyProviderOptionSelection(providerOptionDescriptors, {- id: event.optionId,- value: event.value,- });- if (options) {- void Haptics.selectionAsync();- onUpdateModelSelection({ ...currentModelSelection, options });- }- return;- }- case "set-runtime":- void Haptics.selectionAsync();- onUpdateRuntimeMode(event.mode);- return;- }- },+ const settingsOwnerId = scopedThreadKey(props.environmentId, props.selectedThread.id);+ const settingsRouteSession = useMemo<ExistingThreadSettingsRouteSession>(+ () => ({+ ownerId: settingsOwnerId,+ providerGroups: threadProviderGroups,+ selectedModel: currentModelSelection,+ onSelectModel: (option) => props.onUpdateModelSelection(option.selection),+ optionDescriptors: providerOptionDescriptors,+ onUpdateOptionSelections: (options) =>+ props.onUpdateModelSelection({ ...currentModelSelection, options }),+ runtimeMode: currentRuntimeMode,+ onUpdateRuntimeMode: props.onUpdateRuntimeMode,+ }),[currentModelSelection,- onUpdateModelSelection,- onUpdateRuntimeMode,+ currentRuntimeMode,+ props.onUpdateModelSelection,+ props.onUpdateRuntimeMode,providerOptionDescriptors,- settingsMenu,+ settingsOwnerId,+ threadProviderGroups,],);+ const openSettings = useCallback(() => {+ settingsRoutePresentation.present(settingsRouteSession);+ settingsSheetPresentation.open();+ }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.open]);++ useEffect(() => {+ if (settingsSheetPresentation.isActive) {+ settingsRoutePresentation.present(settingsRouteSession);+ }+ }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.isActive]);++ useEffect(() => {+ if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {+ return;+ }++ settingsRoutePresentedRef.current = true;+ navigation.dispatch(StackActions.push("ThreadSettingsSheet"));+ }, [navigation, settingsSheetPresentation.isVisible]);++ useFocusEffect(+ useCallback(() => {+ if (!settingsRoutePresentedRef.current) {+ return;+ }++ settingsRoutePresentedRef.current = false;+ settingsSheetPresentation.onDismissed();+ settingsRoutePresentation.clear(settingsOwnerId);+ }, [settingsOwnerId, settingsRoutePresentation.clear, settingsSheetPresentation.onDismissed]),+ );++ useEffect(+ () =>+ // UIKit's completion callback for the sheet dismissal, surfaced by the+ // native-stack patch. This is when the queued keyboard restore runs.+ (navigation as unknown as NavigationWithFinishTransitioning).addListener(+ "finishTransitioning",+ settingsSheetPresentation.onStackTransitionsFinished,+ ),+ [navigation, settingsSheetPresentation.onStackTransitionsFinished],+ );return (<Animated.View@@ -739,10 +740,12 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerstyle={isExpanded? {- borderRadius: 20,+ borderRadius: 26,+ minHeight: 140,overflow: "hidden" as const,+ paddingBottom: 6,paddingHorizontal: 14,- paddingVertical: 12,+ paddingTop: 14,}: {borderRadius: 999,@@ -792,7 +795,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerstyle={isExpanded? {- minHeight: 80,+ minHeight: 72,maxHeight: 160,paddingHorizontal: 4,paddingVertical: 4,@@ -841,15 +844,12 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer)}</Animated.View>) : null}- </ComposerSurface>-- {isExpanded ? (- // Toolbar row — matches draft page layout (expanded only)- <Animated.View entering={FadeIn.duration(160)} exiting={FadeOut.duration(120)}>- <ComposerToolbarRow paddingBottom={8} paddingHorizontal={0} paddingTop={8}>+ {isExpanded ? (+ <ComposerToolbarRow paddingBottom={0} paddingHorizontal={0} paddingTop={4}><ComposerToolbarScrollerfadeOpaque={toolbarFadeOpaque}fadeTransparent={toolbarFadeTransparent}+ contentPaddingRight={8}><ComposerToolbarButtonaccessibilityLabel="Add attachment"@@ -857,31 +857,16 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposeronPress={() => void props.onPickDraftImages()}showChevron={false}/>- {settingsMenu ? (- <ControlPillMenu- actions={settingsMenu.actions}- onPressAction={({ nativeEvent }) => handleSettingsMenuAction(nativeEvent.event)}- >- <ComposerToolbarTrigger- accessibilityLabel="Thread settings"- iconNode={- <ProviderIcon provider={currentModelOption?.providerDriver} size={16} />- }- label={settingsSummaryLabel}- maxWidth={320}- />- </ControlPillMenu>- ) : (- <ComposerToolbarTrigger- accessibilityLabel="Thread settings"- iconNode={- <ProviderIcon provider={currentModelOption?.providerDriver} size={16} />- }- label={settingsSummaryLabel}- maxWidth={320}- onPress={settingsSheetPresentation.open}- />- )}+ <ComposerInlineControl+ accessibilityLabel="Model and reasoning settings"+ emphasized+ iconNode={+ <ProviderIcon provider={currentModelOption?.providerDriver} size={16} />+ }+ label={currentModelOption?.label ?? currentModelSelection.model}+ maxWidth={152}+ onPress={openSettings}+ />{showStopAction ? (<ComposerToolbarButtonaccessibilityLabel="Stop"@@ -901,8 +886,8 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposershowChevron={false}/></ComposerToolbarRow>- </Animated.View>- ) : null}+ ) : null}+ </ComposerSurface>{/* Queue count */}{props.queueCount > 0 ? (@@ -915,21 +900,6 @@ 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.tsxindex f87a41e0e..637b7b5ee 100644--- a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx+++ b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx@@ -1,92 +1,113 @@import type {ModelSelection,- ProviderInteractionMode,ProviderOptionDescriptor,ProviderOptionSelection,RuntimeMode,} from "@t3tools/contracts";+import type { LegendListRenderItemProps } from "@legendapp/list/react-native";+import { AnimatedLegendList } from "@legendapp/list/reanimated";+import { HeaderHeightContext } from "@react-navigation/elements";import {getProviderOptionCurrentLabel,getProviderOptionCurrentValue,getProviderOptionDescriptors,} from "@t3tools/shared/model";+import { useNavigation, useRoute, type RouteProp } from "@react-navigation/native";+import {+ createNativeStackNavigator,+ type NativeStackNavigationProp,+} from "@react-navigation/native-stack";import * as Haptics from "expo-haptics";-import { useCallback, useEffect, useRef, useState } from "react";import {- Modal,- Platform,- Pressable,- ScrollView,- Switch,- useWindowDimensions,- View,-} from "react-native";+ createContext,+ use,+ useCallback,+ useEffect,+ useMemo,+ useState,+ type ReactNode,+} from "react";+import { Platform, Pressable, ScrollView, Switch, TextInput, View } from "react-native";+import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";import { useSafeAreaInsets } from "react-native-safe-area-context";import { SymbolView } from "../../components/AppSymbol";import { AppText as Text } from "../../components/AppText";+import { AndroidSheetHeader } from "../../components/AndroidScreenHeader";import { ProviderIcon } from "../../components/ProviderIcon";import { cn } from "../../lib/cn";import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";-import { applyProviderOptionSelection, providerOptionValueLabels } from "../../lib/providerOptions";+import { applyProviderOptionSelection } from "../../lib/providerOptions";+import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";import { useThemeColor } from "../../lib/useThemeColor";-import { RUNTIME_MODE_CHOICES, selectableChoices } from "./thread-settings-menu";-import { pendingModelAfterPress } from "./thread-settings-sheet-state";-import type { ThreadSettingsSheetCloseReason } from "./use-thread-settings-sheet-presentation";+import {+ NativeHeaderToolbar,+ NativeStackScreenOptions,+ nativeHeaderScrollEdgeEffects,+} from "../../native/StackHeader";+import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";+import {+ NATIVE_SHEET_SURFACE_COLOR,+ NATIVE_SHEET_SURFACE_CONTENT_STYLE,+} from "../../native/sheet-surface";+import { useNewTaskFlow } from "./new-task-flow-provider";+import {+ createNativeMailSearchToolbarItem,+ NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET,+ NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED,+} from "../layout/native-mail-search-toolbar";+import { RUNTIME_MODE_CHOICES, selectableChoices } from "./thread-settings-options";+import {+ modelMatchesCatalogQuery,+ pendingModelAfterPress,+ providerSectionIsCollapsed,+} from "./thread-settings-sheet-state";/**- * 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.+ * Everyday harnesses start expanded; every other provider (OpenRouter catalogs+ * and friends) starts folded so a 300-model catalog cannot bury the list. All+ * provider headers remain user-collapsible.*/const PRIMARY_PROVIDER_DRIVERS: ReadonlySet<string> = new Set(["claudeAgent", "codex"]);-/**- * Compact "Fable 5 · Max · Auto" style summary for the composer trigger pill,- * covering model, provider options, runtime mode, and plan mode in one label.+ * Keep measured row changes stable, but let catalog mutations use the list's+ * native bounds so a filtered catalog that underflows returns to the top.*/-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(" · ");-}-+const THREAD_SETTINGS_MAINTAIN_VISIBLE_CONTENT_POSITION = {+ data: false,+ size: true,+} as const;+const THREAD_SETTINGS_CATALOG_LAYOUT_TRANSITION = LinearTransition.duration(180);+const THREAD_SETTINGS_CATALOG_ENTER_TRANSITION = FadeIn.duration(140);+const THREAD_SETTINGS_CATALOG_EXIT_TRANSITION = FadeOut.duration(120);+const THREAD_SETTINGS_OPTIONS_LAYOUT_TRANSITION = LinearTransition.duration(180);+const THREAD_SETTINGS_OPTION_ENTER_TRANSITION = FadeIn.duration(140);+const THREAD_SETTINGS_OPTION_EXIT_TRANSITION = FadeOut.duration(100);+const THREAD_SETTINGS_HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(+ Platform.OS,+ Platform.Version,+);function ModelRow(props: {readonly option: ModelOption;readonly selected: boolean;readonly onPress: () => void;+ readonly isFirst: boolean;+ readonly isLast: boolean;}) {- const primaryFg = useThemeColor("--color-primary-foreground");+ const checkmarkColor = useThemeColor("--color-icon");return (<Pressable- accessibilityRole="button"- accessibilityState={{ selected: props.selected }}+ accessibilityLabel={props.option.label}+ accessibilityRole="radio"+ accessibilityState={{ checked: 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",+ "mx-4 min-h-11 flex-row items-center gap-2 bg-card px-4 py-2 active:bg-subtle",+ props.isFirst && "rounded-t-2xl",+ props.isLast ? "rounded-b-2xl" : "border-b border-border-subtle",)}>- <Text- className={cn(- "shrink text-sm font-t3-medium",- props.selected ? "text-primary-foreground" : "text-foreground",- )}- numberOfLines={1}- >+ <Text className="min-w-0 shrink text-base font-t3-medium text-foreground" numberOfLines={1}>{props.option.label}</Text>{props.option.isDefault ? (@@ -101,17 +122,19 @@ function ModelRow(props: {) : null}<View className="flex-1" />{props.selected ? (- <SymbolView name="checkmark" size={14} tintColor={primaryFg} type="monochrome" />+ <SymbolView+ name="checkmark"+ size={16}+ tintColor={checkmarkColor}+ type="monochrome"+ weight="semibold"+ />) : 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.- */+/** Provider catalog header with its harness logo and disclosure state. */function ProviderHeader(props: {readonly driver: string | undefined;readonly label: string;@@ -121,24 +144,10 @@ function ProviderHeader(props: {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",- )}- >+ const content = (+ <><ProviderIcon provider={props.driver} size={15} />- <Text className="text-2xs font-t3-bold uppercase tracking-widest text-foreground-muted">- {props.label}- </Text>+ <Text className="text-sm font-t3-medium text-foreground-muted">{props.label}</Text>{props.collapsible ? (<><View className="flex-1" />@@ -149,13 +158,33 @@ function ProviderHeader(props: {) : null}<SymbolViewname={props.collapsed ? "chevron.down" : "chevron.up"}- size={11}+ size={12}tintColor={iconSubtle}type="monochrome"/></>) : null}- </Pressable>+ </>+ );++ if (props.collapsible) {+ return (+ <Pressable+ accessibilityLabel={`${props.label}, ${props.modelCount} models`}+ accessibilityRole="button"+ accessibilityState={{ expanded: !props.collapsed }}+ className="mx-4 mt-1 min-h-11 flex-row items-center gap-2 rounded-xl px-1 pt-2 active:opacity-60"+ onPress={props.onToggle}+ >+ {content}+ </Pressable>+ );+ }++ return (+ <View accessibilityRole="header" className="mx-4 min-h-9 flex-row items-center gap-2 px-1 pt-1">+ {content}+ </View>);}@@ -163,18 +192,17 @@ function ProviderHeader(props: {function DisclosureRow(props: {readonly label: string;readonly value: string | undefined;- readonly disabled?: boolean;readonly onPress: () => void;+ readonly isLast?: boolean;}) {const iconSubtle = useThemeColor("--color-icon-subtle");return (<PressableaccessibilityRole="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",+ "min-h-11 flex-row items-center gap-2 bg-card px-4 py-2 active:bg-subtle",+ !props.isLast && "border-b border-border-subtle",)}><Text className="text-sm font-t3-medium text-foreground">{props.label}</Text>@@ -192,31 +220,37 @@ function DisclosureRow(props: {/** Single option inside a submenu panel. */function ChoiceRow(props: {readonly label: string;+ readonly description?: string;readonly selected: boolean;readonly onPress: () => void;+ readonly isLast: boolean;}) {- const primaryFg = useThemeColor("--color-primary-foreground");+ const checkmarkColor = useThemeColor("--color-icon");return (<Pressable- accessibilityRole="button"- accessibilityState={{ selected: props.selected }}+ accessibilityLabel={props.description ? `${props.label}. ${props.description}` : props.label}+ accessibilityRole="radio"+ accessibilityState={{ checked: 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",+ "min-h-14 flex-row items-center gap-3 bg-card px-4 py-3 active:bg-subtle",+ !props.isLast && "border-b border-border-subtle",)}>- <Text- className={cn(- "shrink text-sm font-t3-medium",- props.selected ? "text-primary-foreground" : "text-foreground",- )}- >- {props.label}- </Text>- <View className="flex-1" />+ <View className="min-w-0 flex-1 gap-0.5">+ <Text className="text-base font-t3-medium text-foreground">{props.label}</Text>+ {props.description ? (+ <Text className="text-sm leading-5 text-foreground-muted">{props.description}</Text>+ ) : null}+ </View>{props.selected ? (- <SymbolView name="checkmark" size={14} tintColor={primaryFg} type="monochrome" />+ <SymbolView+ name="checkmark"+ size={16}+ tintColor={checkmarkColor}+ type="monochrome"+ weight="semibold"+ />) : null}</Pressable>);@@ -225,60 +259,31 @@ function ChoiceRow(props: {function SwitchRow(props: {readonly label: string;readonly value: boolean;- readonly disabled?: boolean;readonly onValueChange: (value: boolean) => void;+ readonly isLast?: boolean;}) {- const activeTrack = String(useThemeColor("--color-switch-active"));- const track = String(useThemeColor("--color-secondary-border"));return (<ViewclassName={cn(- "flex-row items-center justify-between px-5 py-2.5",- props.disabled && "opacity-40",+ "min-h-11 flex-row items-center justify-between bg-card px-4 py-1",+ !props.isLast && "border-b border-border-subtle",)}><Text className="text-sm font-t3-medium text-foreground">{props.label}</Text><Switch- disabled={props.disabled}- ios_backgroundColor={track}+ accessibilityLabel={props.label}onValueChange={props.onValueChange}- trackColor={{ false: track, true: activeTrack }}value={props.value}/></View>);}-type SubmenuPage =+type ThreadSettingsSubmenuPage =| { 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;+type ThreadSettingsSessionProps = {readonly providerGroups: ReadonlyArray<ProviderGroup>;readonly selectedModel: ModelSelection | null;readonly onSelectModel: (option: ModelOption) => void;@@ -286,367 +291,949 @@ export function ThreadSettingsSheet(props: {readonly onUpdateOptionSelections: (selections: ReadonlyArray<ProviderOptionSelection>) => void;readonly runtimeMode: RuntimeMode;readonly onUpdateRuntimeMode: (mode: RuntimeMode) => void;-}) {- const insets = useSafeAreaInsets();- const { height: windowHeight } = useWindowDimensions();+};++export type ExistingThreadSettingsRouteSession = ThreadSettingsSessionProps & {+ readonly ownerId: string;+};++type ExistingThreadSettingsRouteContextValue = {+ readonly session: ExistingThreadSettingsRouteSession | null;+ readonly present: (session: ExistingThreadSettingsRouteSession) => void;+ readonly clear: (ownerId: string) => void;+};++const ExistingThreadSettingsRouteContext =+ createContext<ExistingThreadSettingsRouteContextValue | null>(null);++/** Bridges the active thread's settings state into the root native sheet route. */+export function ExistingThreadSettingsRouteProvider(props: { readonly children: ReactNode }) {+ const [session, setSession] = useState<ExistingThreadSettingsRouteSession | null>(null);+ const present = useCallback((nextSession: ExistingThreadSettingsRouteSession) => {+ setSession(nextSession);+ }, []);+ const clear = useCallback((ownerId: string) => {+ setSession((current) => (current?.ownerId === ownerId ? null : current));+ }, []);+ const value = useMemo(() => ({ session, present, clear }), [clear, present, session]);++ return (+ <ExistingThreadSettingsRouteContext.Provider value={value}>+ {props.children}+ </ExistingThreadSettingsRouteContext.Provider>+ );+}++export function useExistingThreadSettingsRoutePresentation() {+ const value = use(ExistingThreadSettingsRouteContext);+ if (!value) {+ throw new Error(+ "useExistingThreadSettingsRoutePresentation must be used inside ExistingThreadSettingsRouteProvider.",+ );+ }+ return value;+}++type ThreadSettingsSessionValue = {+ readonly providerGroups: ReadonlyArray<ProviderGroup>;+ readonly runtimeMode: RuntimeMode;+ readonly onUpdateRuntimeMode: (mode: RuntimeMode) => void;+ readonly displayedDescriptors: ReadonlyArray<ProviderOptionDescriptor>;+ readonly providerExpansionOverrides: ReadonlySet<string>;+ readonly hasLegacyModels: boolean;+ readonly pendingModel: ModelOption | null;+ readonly providerFilter: string | null;+ readonly searchQuery: string;+ readonly showLegacy: boolean;+ readonly applyOptionChange: (id: string, value: string | boolean) => void;+ readonly commitPendingModel: () => void;+ readonly isApplied: (option: ModelOption) => boolean;+ readonly isDisplayed: (option: ModelOption) => boolean;+ readonly pressModel: (option: ModelOption) => void;+ readonly setProviderFilter: (providerKey: string | null) => void;+ readonly setSearchQuery: (query: string) => void;+ readonly setShowLegacy: (showLegacy: boolean) => void;+ readonly toggleProvider: (providerKey: string) => void;+};++const ThreadSettingsSessionContext = createContext<ThreadSettingsSessionValue | null>(null);++/** Owns the staged model and option state for one picker presentation. */+function ThreadSettingsSessionProvider(+ props: ThreadSettingsSessionProps & { readonly children: ReactNode },+) {const [showLegacyToggle, setShowLegacyToggle] = useState(false);- const [expandedProviders, setExpandedProviders] = useState<ReadonlySet<string>>(() => new Set());+ const [providerFilter, setProviderFilter] = useState<string | null>(null);+ const [searchQuery, setSearchQuery] = useState("");+ const [providerExpansionOverrides, setProviderExpansionOverrides] = 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;+ const isApplied = useCallback(+ (option: ModelOption) =>+ option.selection.instanceId === props.selectedModel?.instanceId &&+ option.selection.model === props.selectedModel.model,+ [props.selectedModel],+ );// The list highlights the staged pick; Save turns it into the applied one.- const isDisplayed = (option: ModelOption) =>- pendingModel ? option.key === pendingModel.key : isApplied(option);+ const isDisplayed = useCallback(+ (option: ModelOption) => (pendingModel ? option.key === pendingModel.key : isApplied(option)),+ [isApplied, pendingModel],+ );// 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 displayedDescriptors = useMemo(+ () =>+ pendingModel+ ? pendingModel.capabilities+ ? getProviderOptionDescriptors({+ caps: pendingModel.capabilities,+ selections: pendingModel.selection.options,+ })+ : []+ : props.optionDescriptors,+ [pendingModel, props.optionDescriptors],+ );- const handleSave = () => {+ const hasLegacyModels = useMemo(+ () => props.providerGroups.some((group) => group.models.some((model) => model.isLegacy)),+ [props.providerGroups],+ );+ const commitPendingModel = useCallback(() => {if (pendingModel) {void Haptics.selectionAsync();props.onSelectModel(pendingModel);}- props.onClose("save");- };+ }, [pendingModel, props.onSelectModel]);- 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 applyOptionChange = useCallback(+ (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);+ }+ },+ [displayedDescriptors, pendingModel, props.onUpdateOptionSelections],+ );- const toggleProvider = (providerKey: string) => {- setExpandedProviders((current) => {+ const toggleProvider = useCallback((providerKey: string) => {+ setProviderExpansionOverrides((current) => {const next = new Set(current);if (!next.delete(providerKey)) {next.add(providerKey);}return next;});- };+ }, []);++ const pressModel = useCallback(+ (option: ModelOption) => {+ void Haptics.selectionAsync();+ setPendingModel((current) =>+ pendingModelAfterPress({+ current,+ pressed: option,+ pressedIsApplied: isApplied(option),+ }),+ );+ },+ [isApplied],+ );++ const value = useMemo<ThreadSettingsSessionValue>(+ () => ({+ providerGroups: props.providerGroups,+ runtimeMode: props.runtimeMode,+ onUpdateRuntimeMode: props.onUpdateRuntimeMode,+ displayedDescriptors,+ providerExpansionOverrides,+ hasLegacyModels,+ pendingModel,+ providerFilter,+ searchQuery,+ showLegacy: showLegacyToggle,+ applyOptionChange,+ commitPendingModel,+ isApplied,+ isDisplayed,+ pressModel,+ setProviderFilter,+ setSearchQuery,+ setShowLegacy: setShowLegacyToggle,+ toggleProvider,+ }),+ [+ applyOptionChange,+ commitPendingModel,+ displayedDescriptors,+ providerExpansionOverrides,+ hasLegacyModels,+ isApplied,+ isDisplayed,+ pendingModel,+ pressModel,+ providerFilter,+ props.onUpdateRuntimeMode,+ props.providerGroups,+ props.runtimeMode,+ searchQuery,+ showLegacyToggle,+ toggleProvider,+ ],+ );++ return (+ <ThreadSettingsSessionContext.Provider value={value}>+ {props.children}+ </ThreadSettingsSessionContext.Provider>+ );+}++function useThreadSettingsSession() {+ const value = use(ThreadSettingsSessionContext);+ if (!value) {+ throw new Error("useThreadSettingsSession must be used inside ThreadSettingsSessionProvider.");+ }+ return value;+}++type ThreadSettingsProviderCatalog = {+ readonly key: string;+ readonly driver: string | undefined;+ readonly label: string;+ readonly collapsible: boolean;+ readonly collapsed: boolean;+ readonly modelCount: number;+ readonly models: ReadonlyArray<ModelOption>;+};++type ThreadSettingsCatalogItem =+ | {+ readonly kind: "provider";+ readonly key: string;+ readonly provider: ThreadSettingsProviderCatalog;+ }+ | {+ readonly kind: "model";+ readonly key: string;+ readonly option: ModelOption;+ readonly isFirst: boolean;+ readonly isLast: boolean;+ }+ | {+ readonly kind: "empty";+ readonly key: "empty";+ }+ | {+ readonly kind: "options";+ readonly key: "options";+ };++function ThreadSettingsModelListRow(props: {+ readonly option: ModelOption;+ readonly isFirst: boolean;+ readonly isLast: boolean;+}) {+ const session = useThreadSettingsSession();+ const onPress = useCallback(+ () => session.pressModel(props.option),+ [props.option, session.pressModel],+ );++ return (+ <ModelRow+ isFirst={props.isFirst}+ isLast={props.isLast}+ onPress={onPress}+ option={props.option}+ selected={session.isDisplayed(props.option)}+ />+ );+}++function ThreadSettingsProviderListHeader(props: {+ readonly provider: ThreadSettingsProviderCatalog;+}) {+ const session = useThreadSettingsSession();+ const onToggle = useCallback(+ () => session.toggleProvider(props.provider.key),+ [props.provider.key, session.toggleProvider],+ );++ return (+ <ProviderHeader+ collapsible={props.provider.collapsible}+ collapsed={props.provider.collapsed}+ driver={props.provider.driver}+ label={props.provider.label}+ modelCount={props.provider.modelCount}+ onToggle={onToggle}+ />+ );+}++function useThreadSettingsCatalogItems(+ session: ThreadSettingsSessionValue,+): ReadonlyArray<ThreadSettingsCatalogItem> {+ return useMemo(+ () =>+ session.providerGroups.flatMap((group) => {+ if (session.providerFilter !== null && group.providerKey !== session.providerFilter) {+ return [];+ }+ const driver = group.models[0]?.providerDriver;+ const catalogModels = session.showLegacy+ ? group.models+ : group.models.filter((model) => !model.isLegacy || session.isDisplayed(model));+ const visibleModels = catalogModels.filter((model) =>+ modelMatchesCatalogQuery({+ model,+ providerLabel: group.providerLabel,+ query: session.searchQuery,+ }),+ );+ if (visibleModels.length === 0) {+ return [];+ }+ const isPrimary = driver !== undefined && PRIMARY_PROVIDER_DRIVERS.has(driver);+ // Staging a model must not change disclosure state. The applied model+ // stays stable for the lifetime of this picker (Save closes it), so it+ // is safe to use as the initial selected-provider default.+ const containsAppliedSelection = group.models.some(session.isApplied);+ const isNarrowed = session.providerFilter !== null || session.searchQuery.trim().length > 0;+ const collapsible = !isNarrowed;+ const collapsed = providerSectionIsCollapsed({+ defaultExpanded: isPrimary || containsAppliedSelection,+ hasExpansionOverride: session.providerExpansionOverrides.has(group.providerKey),+ isNarrowed,+ });+ const provider: ThreadSettingsProviderCatalog = {+ key: group.providerKey,+ driver,+ label: group.providerLabel,+ collapsible,+ collapsed,+ modelCount: visibleModels.length,+ models: collapsed ? [] : visibleModels,+ };+ return [+ {+ kind: "provider" as const,+ key: `provider:${group.providerKey}`,+ provider,+ },+ ...provider.models.map((option, index) => ({+ kind: "model" as const,+ key: `model:${option.key}`,+ option,+ isFirst: index === 0,+ isLast: index === provider.models.length - 1,+ })),+ ];+ }),+ [+ session.isApplied,+ session.isDisplayed,+ session.providerExpansionOverrides,+ session.providerFilter,+ session.providerGroups,+ session.searchQuery,+ session.showLegacy,+ ],+ );+}++function ThreadSettingsOptionsItem(props: {+ readonly animationsReady: boolean;+ readonly onOpenSubmenu: (submenu: ThreadSettingsSubmenuPage) => void;+}) {+ const insets = useSafeAreaInsets();+ const session = useThreadSettingsSession();+ const bottomToolbarInset =+ Platform.OS === "ios" && NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED+ ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET+ : 0;++ return (+ <View style={{ paddingBottom: insets.bottom + bottomToolbarInset + 12 }}>+ <Text className="px-5 pb-2 pt-2 text-sm font-t3-medium text-foreground-muted">Options</Text>+ <Animated.View+ className="mx-4 overflow-hidden rounded-2xl bg-card"+ layout={THREAD_SETTINGS_OPTIONS_LAYOUT_TRANSITION}+ >+ {session.displayedDescriptors.map((descriptor) => {+ if (descriptor.type === "select") {+ return (+ <Animated.View+ key={descriptor.id}+ entering={+ props.animationsReady ? THREAD_SETTINGS_OPTION_ENTER_TRANSITION : undefined+ }+ exiting={props.animationsReady ? THREAD_SETTINGS_OPTION_EXIT_TRANSITION : undefined}+ layout={THREAD_SETTINGS_OPTIONS_LAYOUT_TRANSITION}+ >+ <DisclosureRow+ label={descriptor.label}+ value={getProviderOptionCurrentLabel(descriptor)}+ onPress={() => props.onOpenSubmenu({ kind: "descriptor", id: descriptor.id })}+ />+ </Animated.View>+ );+ }+ return (+ <Animated.View+ key={descriptor.id}+ entering={props.animationsReady ? THREAD_SETTINGS_OPTION_ENTER_TRANSITION : undefined}+ exiting={props.animationsReady ? THREAD_SETTINGS_OPTION_EXIT_TRANSITION : undefined}+ layout={THREAD_SETTINGS_OPTIONS_LAYOUT_TRANSITION}+ >+ <SwitchRow+ label={descriptor.label}+ value={descriptor.currentValue ?? false}+ onValueChange={(value) => session.applyOptionChange(descriptor.id, value)}+ />+ </Animated.View>+ );+ })}+ <Animated.View layout={THREAD_SETTINGS_OPTIONS_LAYOUT_TRANSITION}>+ <DisclosureRow+ isLast+ label="Runtime"+ value={+ RUNTIME_MODE_CHOICES.find((choice) => choice.mode === session.runtimeMode)?.label+ }+ onPress={() => props.onOpenSubmenu({ kind: "runtime" })}+ />+ </Animated.View>+ </Animated.View>++ {Platform.OS !== "ios" && session.hasLegacyModels ? (+ <>+ <Text className="px-5 pb-2 pt-7 text-sm font-t3-medium text-foreground-muted">+ Catalog+ </Text>+ <View className="mx-4 overflow-hidden rounded-2xl bg-card">+ <SwitchRow+ isLast+ label="Legacy models"+ onValueChange={session.setShowLegacy}+ value={session.showLegacy}+ />+ </View>+ </>+ ) : null}+ </View>+ );+}++/** One native scroll owner for the model catalog and its related settings. */+function ThreadSettingsMainContent(props: {+ readonly onOpenSubmenu: (submenu: ThreadSettingsSubmenuPage) => void;+}) {+ const session = useThreadSettingsSession();+ const catalogItems = useThreadSettingsCatalogItems(session);+ const [animationsReady, setAnimationsReady] = useState(false);+ const nativeHeaderHeight = use(HeaderHeightContext) ?? 0;+ const hasActiveCatalogFilter =+ session.providerFilter !== null || session.searchQuery.trim().length > 0;+ const usesTransparentNativeHeader = Platform.OS === "ios" && NATIVE_LIQUID_GLASS_SUPPORTED;+ const listItems = useMemo<ReadonlyArray<ThreadSettingsCatalogItem>>(+ () => [+ ...(catalogItems.length === 0 && hasActiveCatalogFilter+ ? ([{ kind: "empty", key: "empty" }] as const)+ : catalogItems),+ { kind: "options", key: "options" },+ ],+ [catalogItems, hasActiveCatalogFilter],+ );+ const renderCatalogItem = useCallback(+ (itemProps: LegendListRenderItemProps<ThreadSettingsCatalogItem>) => {+ const item = itemProps.item;+ let content: ReactNode;++ if (item.kind === "provider") {+ content = <ThreadSettingsProviderListHeader provider={item.provider} />;+ } else if (item.kind === "model") {+ content = (+ <ThreadSettingsModelListRow+ isFirst={item.isFirst}+ isLast={item.isLast}+ option={item.option}+ />+ );+ } else if (item.kind === "empty") {+ content = (+ <View className="items-center px-8 py-14">+ <Text className="text-center text-sm text-foreground-muted">No matching models</Text>+ </View>+ );+ } else {+ content = (+ <ThreadSettingsOptionsItem+ animationsReady={animationsReady}+ onOpenSubmenu={props.onOpenSubmenu}+ />+ );+ }++ return (+ <Animated.View+ key={item.key}+ entering={animationsReady ? THREAD_SETTINGS_CATALOG_ENTER_TRANSITION : undefined}+ exiting={animationsReady ? THREAD_SETTINGS_CATALOG_EXIT_TRANSITION : undefined}+ >+ {content}+ </Animated.View>+ );+ },+ [animationsReady, props.onOpenSubmenu],+ );++ return (+ <AnimatedLegendList+ automaticallyAdjustsScrollIndicatorInsets+ className="flex-1 bg-sheet"+ contentContainerStyle={{ paddingTop: 4 }}+ contentInsetAdjustmentBehavior={usesTransparentNativeHeader ? "never" : "automatic"}+ data={listItems}+ estimatedItemSize={48}+ extraData={animationsReady}+ getItemType={(item) => item.kind}+ itemLayoutAnimation={THREAD_SETTINGS_CATALOG_LAYOUT_TRANSITION}+ keyExtractor={(item) => item.key}+ keyboardDismissMode="on-drag"+ keyboardShouldPersistTaps="handled"+ maintainVisibleContentPosition={THREAD_SETTINGS_MAINTAIN_VISIBLE_CONTENT_POSITION}+ ListHeaderComponent={+ <>+ {usesTransparentNativeHeader ? <View style={{ height: nativeHeaderHeight }} /> : null}+ {Platform.OS === "android" ? (+ <View className="px-4 pb-2 pt-3">+ <TextInput+ accessibilityLabel="Find a model"+ autoCapitalize="none"+ autoCorrect={false}+ className="h-11 rounded-xl bg-card px-4 text-base text-foreground"+ onChangeText={session.setSearchQuery}+ placeholder="Find a model"+ placeholderTextColorClassName="accent-placeholder"+ value={session.searchQuery}+ />+ </View>+ ) : null}+ </>+ }+ recycleItems+ onLoad={() => setAnimationsReady(true)}+ renderItem={renderCatalogItem}+ showsVerticalScrollIndicator={false}+ />+ );+}++/** Compact choice page pushed by the picker navigator. */+function ThreadSettingsChoiceContent(props: {+ readonly submenu: ThreadSettingsSubmenuPage;+ readonly onSelected: () => void;+}) {+ const insets = useSafeAreaInsets();+ const session = useThreadSettingsSession();+ const descriptorId = props.submenu.kind === "descriptor" ? props.submenu.id : null;const activeDescriptor =- submenu?.kind === "descriptor"- ? displayedDescriptors.find(- (descriptor) => descriptor.type === "select" && descriptor.id === submenu.id,+ descriptorId !== null+ ? session.displayedDescriptors.find(+ (descriptor) => descriptor.type === "select" && descriptor.id === descriptorId,): undefined;const submenuContent =- submenu?.kind === "runtime"+ props.submenu.kind === "runtime"? {- title: "Runtime",rows: RUNTIME_MODE_CHOICES.map((choice) => ({id: choice.mode,label: choice.label,- selected: choice.mode === props.runtimeMode,+ description: choice.description,+ selected: choice.mode === session.runtimeMode,onPress: () => {void Haptics.selectionAsync();- props.onUpdateRuntimeMode(choice.mode);- setSubmenu(null);+ session.onUpdateRuntimeMode(choice.mode);+ props.onSelected();},})),}: activeDescriptor?.type === "select"? {- title: activeDescriptor.label,rows: selectableChoices(activeDescriptor).map((choice) => ({id: choice.id,label: choice.label,+ description: undefined,selected: choice.id === getProviderOptionCurrentValue(activeDescriptor),onPress: () => {void Haptics.selectionAsync();- handleOptionChange(activeDescriptor.id, choice.id);- setSubmenu(null);+ session.applyOptionChange(activeDescriptor.id, choice.id);+ props.onSelected();},})),}: null;+ if (!submenuContent) {+ return <View className="flex-1 bg-sheet" />;+ }+return (- <Modal- transparent- statusBarTranslucent- navigationBarTranslucent- animationType={Platform.OS === "ios" ? "fade" : "none"}- visible={props.visible}- onDismiss={notifyDismissed}- onRequestClose={submenuContent ? () => setSubmenu(null) : () => props.onClose("dismiss")}+ <ScrollView+ className="flex-1 bg-sheet"+ contentContainerStyle={{+ paddingBottom: insets.bottom + 12,+ paddingHorizontal: 16,+ paddingTop: 16,+ }}+ contentInsetAdjustmentBehavior="automatic"+ showsVerticalScrollIndicator={false}>- <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-2xl bg-card">+ {submenuContent.rows.map((row, index) => (+ <ChoiceRow+ key={row.id}+ description={row.description}+ isLast={index === submenuContent.rows.length - 1}+ label={row.label}+ selected={row.selected}+ onPress={row.onPress}+ />+ ))}+ </View>+ </ScrollView>+ );+}++type ThreadSettingsPickerStackParams = {+ ThreadSettingsModels: undefined;+ ThreadSettingsChoice: ThreadSettingsSubmenuPage & { readonly title: string };+};++type ThreadSettingsPickerPresentation = {+ readonly onClose: () => void;+};++const ThreadSettingsPickerStack = createNativeStackNavigator<ThreadSettingsPickerStackParams>();+const ThreadSettingsPickerPresentationContext =+ createContext<ThreadSettingsPickerPresentation | null>(null);++function useThreadSettingsPickerPresentation() {+ const value = use(ThreadSettingsPickerPresentationContext);+ if (!value) {+ throw new Error(+ "useThreadSettingsPickerPresentation must be used inside ThreadSettingsPickerNavigator.",+ );+ }+ return value;+}++function ThreadSettingsModelsScreen() {+ const session = useThreadSettingsSession();+ const presentation = useThreadSettingsPickerPresentation();+ const navigation = useNavigation<NativeStackNavigationProp<ThreadSettingsPickerStackParams>>();+ const usesNativeMailSearchToolbar = Platform.OS === "ios" && NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED;+ const hasCustomCatalogFilter = session.providerFilter !== null || session.showLegacy;+ const commitAndClose = useCallback(() => {+ session.commitPendingModel();+ presentation.onClose();+ }, [presentation, session]);+ const filterMenu = useMemo(+ () => ({+ title: "Model filters",+ items: [+ {+ type: "submenu" as const,+ title: "Provider",+ items: [+ {+ type: "action" as const,+ title: "All providers",+ state: session.providerFilter === null ? ("on" as const) : ("off" as const),+ onPress: () => session.setProviderFilter(null),+ },+ ...session.providerGroups.map((group) => ({+ type: "action" as const,+ title: group.providerLabel,+ state:+ session.providerFilter === group.providerKey ? ("on" as const) : ("off" as const),+ onPress: () => session.setProviderFilter(group.providerKey),+ })),+ ],+ },+ ...(session.hasLegacyModels+ ? [+ {+ type: "action" as const,+ title: "Show legacy models",+ state: session.showLegacy ? ("on" as const) : ("off" as const),+ onPress: () => session.setShowLegacy(!session.showLegacy),+ },+ ]+ : []),+ ],+ }),+ [session],+ );++ return (+ <>+ {Platform.OS === "android" ? (+ <AndroidSheetHeader+ actions={[+ {+ accessibilityLabel: session.pendingModel ? "Save thread settings" : "Done",+ icon: "checkmark",+ onPress: commitAndClose,+ },+ ]}+ onBack={presentation.onClose}+ title="Thread settings"/>- <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}+ ) : null}+ <NativeStackScreenOptions+ optionsVersion={[+ session.providerFilter,+ session.providerGroups.map((group) => group.providerKey),+ session.showLegacy,+ ]}+ options={{+ unstable_headerToolbarItems: usesNativeMailSearchToolbar+ ? () => [+ createNativeMailSearchToolbarItem({+ filterButtonId: "thread-settings-model-filter",+ filterMenu,+ filterSystemImageName: hasCustomCatalogFilter+ ? "line.3.horizontal.decrease.circle.fill"+ : "line.3.horizontal.decrease",+ onSearchTextChange: session.setSearchQuery,+ placeholder: "Find a model",+ searchTextChangeId: "thread-settings-model-search-text",+ showsSearchDismissButton: true,+ }),+ ]+ : undefined,+ headerShown: Platform.OS !== "android",+ headerSearchBarOptions:+ Platform.OS === "ios" && !usesNativeMailSearchToolbar+ ? {+ autoCapitalize: "none",+ hideNavigationBar: false,+ obscureBackground: false,+ onCancelButtonPress: () => session.setSearchQuery(""),+ onChangeText: (event) => session.setSearchQuery(event.nativeEvent.text),+ placeholder: "Find a model",+ }+ : undefined,+ }}+ />+ <ThreadSettingsMainContent+ onOpenSubmenu={(submenu) => {+ const title =+ submenu.kind === "runtime"+ ? "Runtime"+ : (session.displayedDescriptors.find(+ (descriptor) => descriptor.type === "select" && descriptor.id === submenu.id,+ )?.label ?? "Option");+ navigation.navigate("ThreadSettingsChoice", { ...submenu, title });+ }}+ />+ <NativeHeaderToolbar placement="left">+ <NativeHeaderToolbar.Button+ accessibilityLabel="Cancel thread settings"+ label="Cancel"+ onPress={presentation.onClose}+ />+ </NativeHeaderToolbar>+ <NativeHeaderToolbar placement="right">+ <NativeHeaderToolbar.Button+ accessibilityLabel={session.pendingModel ? "Save thread settings" : "Done"}+ label={session.pendingModel ? "Save" : "Done"}+ onPress={commitAndClose}+ />+ </NativeHeaderToolbar>+ {Platform.OS === "ios" && !usesNativeMailSearchToolbar ? (+ <NativeHeaderToolbar placement="bottom">+ <NativeHeaderToolbar.Menu+ accessibilityLabel="Filter models"+ icon={+ hasCustomCatalogFilter+ ? "line.3.horizontal.decrease.circle.fill"+ : "line.3.horizontal.decrease.circle"+ }+ separateBackground+ title="Model filters">- {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"+ <NativeHeaderToolbar.Menu title="Provider">+ <NativeHeaderToolbar.Label>Provider</NativeHeaderToolbar.Label>+ <NativeHeaderToolbar.MenuAction+ isOn={session.providerFilter === null}+ onPress={() => session.setProviderFilter(null)}>- <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}+ All providers+ </NativeHeaderToolbar.MenuAction>+ {session.providerGroups.map((group) => (+ <NativeHeaderToolbar.MenuAction+ key={group.providerKey}+ isOn={session.providerFilter === group.providerKey}+ onPress={() => session.setProviderFilter(group.providerKey)}+ >+ {group.providerLabel}+ </NativeHeaderToolbar.MenuAction>+ ))}+ </NativeHeaderToolbar.Menu>+ {session.hasLegacyModels ? (+ <NativeHeaderToolbar.MenuAction+ isOn={session.showLegacy}+ onPress={() => session.setShowLegacy(!session.showLegacy)}>- {submenuContent.rows.map((row) => (- <ChoiceRow- key={row.id}- label={row.label}- selected={row.selected}- onPress={row.onPress}- />- ))}- </ScrollView>- </View>- </View>- ) : null}- </View>- </Modal>+ Show legacy models+ </NativeHeaderToolbar.MenuAction>+ ) : null}+ </NativeHeaderToolbar.Menu>+ </NativeHeaderToolbar>+ ) : null}+ </>+ );+}++function ThreadSettingsChoiceScreen() {+ const navigation = useNavigation<NativeStackNavigationProp<ThreadSettingsPickerStackParams>>();+ const route = useRoute<RouteProp<ThreadSettingsPickerStackParams, "ThreadSettingsChoice">>();++ return (+ <>+ <NativeStackScreenOptions options={{ headerShown: Platform.OS !== "android" }} />+ {Platform.OS === "android" ? (+ <AndroidSheetHeader title={route.params.title} onBack={() => navigation.goBack()} />+ ) : null}+ <ThreadSettingsChoiceContent submenu={route.params} onSelected={() => navigation.goBack()} />+ </>+ );+}++function ThreadSettingsPickerNavigator(props: ThreadSettingsPickerPresentation) {+ const sheetBackground = String(useThemeColor("--color-sheet"));+ const foreground = String(useThemeColor("--color-foreground"));+ const nativeSheetBackground = NATIVE_SHEET_SURFACE_COLOR ?? sheetBackground;+ const presentation = useMemo(+ () => ({+ onClose: props.onClose,+ }),+ [props.onClose],+ );++ return (+ <ThreadSettingsPickerPresentationContext.Provider value={presentation}>+ <ThreadSettingsPickerStack.Navigator+ initialRouteName="ThreadSettingsModels"+ screenOptions={{+ animation: "slide_from_right",+ contentStyle: NATIVE_SHEET_SURFACE_CONTENT_STYLE ?? {+ backgroundColor: nativeSheetBackground,+ },+ gestureEnabled: true,+ headerBackButtonDisplayMode: "minimal",+ headerBackTitle: "",+ headerShadowVisible: false,+ headerStyle: {+ backgroundColor: (NATIVE_LIQUID_GLASS_SUPPORTED+ ? "transparent"+ : nativeSheetBackground) as unknown as string,+ },+ headerTransparent: NATIVE_LIQUID_GLASS_SUPPORTED,+ headerTintColor: foreground,+ headerTitleStyle: { fontSize: 17, fontWeight: "700" },+ scrollEdgeEffects: NATIVE_LIQUID_GLASS_SUPPORTED+ ? THREAD_SETTINGS_HEADER_SCROLL_EDGE_EFFECTS+ : undefined,+ }}+ >+ <ThreadSettingsPickerStack.Screen+ name="ThreadSettingsModels"+ component={ThreadSettingsModelsScreen}+ options={{ headerBackVisible: false, title: "Thread settings" }}+ />+ <ThreadSettingsPickerStack.Screen+ name="ThreadSettingsChoice"+ component={ThreadSettingsChoiceScreen}+ options={({ route }) => ({ title: route.params.title })}+ />+ </ThreadSettingsPickerStack.Navigator>+ </ThreadSettingsPickerPresentationContext.Provider>+ );+}++/** Existing-thread model picker hosted by the root RNS form-sheet route. */+export function ExistingThreadSettingsRouteScreen() {+ const navigation = useNavigation<NativeStackNavigationProp<Record<string, object | undefined>>>();+ const presentation = useExistingThreadSettingsRoutePresentation();+ const session = presentation.session;++ useEffect(() => {+ if (session) {+ return;+ }++ navigation.goBack();+ }, [navigation, session]);++ if (!session) {+ return <View className="flex-1 bg-sheet" />;+ }++ const { ownerId: _ownerId, ...settings } = session;++ return (+ <ThreadSettingsSessionProvider {...settings}>+ <ThreadSettingsPickerNavigator onClose={() => navigation.goBack()} />+ </ThreadSettingsSessionProvider>+ );+}++/**+ * Native stack hosted by the New Task navigator's form-sheet route. Keeping+ * the sheet presentation in RNS gives UIKit ownership of nested dismissal,+ * while Reasoning and Runtime remain regular pushes inside this navigator.+ */+export function NewTaskThreadSettingsRouteScreen() {+ const flow = useNewTaskFlow();+ const navigation = useNavigation<NativeStackNavigationProp<Record<string, object | undefined>>>();+ const optionDescriptors = useMemo(+ () =>+ resolveProviderOptionDescriptors({+ capabilities: flow.selectedModelOption?.capabilities,+ selections: flow.selectedModel?.options,+ }),+ [flow.selectedModel?.options, flow.selectedModelOption?.capabilities],+ );++ return (+ <ThreadSettingsSessionProvider+ providerGroups={flow.providerGroups}+ selectedModel={flow.selectedModel}+ onSelectModel={(option) => flow.setSelectedModelKey(option.key, option.selection.options)}+ optionDescriptors={optionDescriptors}+ onUpdateOptionSelections={flow.setSelectedModelOptions}+ runtimeMode={flow.runtimeMode}+ onUpdateRuntimeMode={flow.setRuntimeMode}+ >+ <ThreadSettingsPickerNavigator onClose={() => navigation.goBack()} />+ </ThreadSettingsSessionProvider>);}diff --git a/apps/mobile/src/features/threads/legacy-plan-mode.test.ts b/apps/mobile/src/features/threads/legacy-plan-mode.test.tsnew file mode 100644index 000000000..e55631885--- /dev/null+++ b/apps/mobile/src/features/threads/legacy-plan-mode.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from "@effect/vitest";++import { resolvePendingTaskInteractionMode } from "./legacy-plan-mode";++describe("resolvePendingTaskInteractionMode", () => {+ it("preserves a queued plan task while the preference is still loading", () => {+ expect(+ resolvePendingTaskInteractionMode({+ preferenceLoaded: false,+ planModeEnabled: false,+ draftInteractionMode: "plan",+ queuedInteractionMode: "plan",+ }),+ ).toBe("plan");+ });++ it("forces build mode once the disabled preference has loaded", () => {+ expect(+ resolvePendingTaskInteractionMode({+ preferenceLoaded: true,+ planModeEnabled: false,+ draftInteractionMode: "plan",+ queuedInteractionMode: "plan",+ }),+ ).toBe("default");+ });++ it("keeps a fresh draft in build mode while the preference is loading", () => {+ expect(+ resolvePendingTaskInteractionMode({+ preferenceLoaded: false,+ planModeEnabled: false,+ draftInteractionMode: "plan",+ queuedInteractionMode: undefined,+ }),+ ).toBe("default");+ });++ it("honors the draft's mode when the plan preference is enabled", () => {+ expect(+ resolvePendingTaskInteractionMode({+ preferenceLoaded: true,+ planModeEnabled: true,+ draftInteractionMode: "plan",+ queuedInteractionMode: undefined,+ }),+ ).toBe("plan");+ expect(+ resolvePendingTaskInteractionMode({+ preferenceLoaded: true,+ planModeEnabled: true,+ draftInteractionMode: undefined,+ queuedInteractionMode: "plan",+ }),+ ).toBe("default");+ });+});diff --git a/apps/mobile/src/features/threads/legacy-plan-mode.ts b/apps/mobile/src/features/threads/legacy-plan-mode.tsnew file mode 100644index 000000000..e7122125f--- /dev/null+++ b/apps/mobile/src/features/threads/legacy-plan-mode.ts@@ -0,0 +1,29 @@+import {+ DEFAULT_PROVIDER_INTERACTION_MODE,+ type ProviderInteractionMode,+} from "@t3tools/contracts";++export function resolveLegacyPlanModeEnabled(input: {+ readonly loaded: boolean;+ readonly preference: boolean | undefined;+}): boolean {+ return input.loaded && input.preference === true;+}++export function resolvePendingTaskInteractionMode(input: {+ readonly preferenceLoaded: boolean;+ readonly planModeEnabled: boolean;+ readonly draftInteractionMode: ProviderInteractionMode | undefined;+ readonly queuedInteractionMode: ProviderInteractionMode | undefined;+}): ProviderInteractionMode {+ if (input.planModeEnabled) {+ return input.draftInteractionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;+ }+ if (!input.preferenceLoaded) {+ // Only an existing queued task may retain its previous mode while the+ // preference is unknown. A fresh draft still defaults to Build so a stale+ // persisted Plan selection cannot bypass a disabled preference at launch.+ return input.queuedInteractionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;+ }+ return DEFAULT_PROVIDER_INTERACTION_MODE;+}diff --git a/apps/mobile/src/features/threads/new-task-context-presentation.test.ts b/apps/mobile/src/features/threads/new-task-context-presentation.test.tsnew file mode 100644index 000000000..3c81d8231--- /dev/null+++ b/apps/mobile/src/features/threads/new-task-context-presentation.test.ts@@ -0,0 +1,128 @@+import { describe, expect, it } from "vite-plus/test";++import {+ resolveNewTaskBranchWorktreePath,+ resolveNewTaskBranchLabel,+ resolveNewTaskLocalWorkspaceSelection,+} from "./new-task-context-presentation";++describe("resolveNewTaskLocalWorkspaceSelection", () => {+ it("waits for refs instead of carrying a worktree base into Current checkout", () => {+ expect(+ resolveNewTaskLocalWorkspaceSelection({+ branches: [],+ projectCwd: "/repo",+ }),+ ).toEqual({+ branch: null,+ worktreePath: null,+ awaitsCurrentBranch: true,+ });+ });++ it("adopts the checkout's current branch once refs load", () => {+ expect(+ resolveNewTaskLocalWorkspaceSelection({+ branches: [+ { name: "feature/worktree-base", current: false, worktreePath: "/worktree" },+ { name: "main", current: true, worktreePath: "/repo" },+ ],+ projectCwd: "/repo",+ }),+ ).toEqual({+ branch: "main",+ worktreePath: null,+ awaitsCurrentBranch: false,+ });+ });++ it("carries the worktree path when the current branch lives in another worktree", () => {+ expect(+ resolveNewTaskLocalWorkspaceSelection({+ branches: [+ { name: "feature/split", current: true, worktreePath: "/repo/.t3/worktrees/split" },+ { name: "main", current: false, worktreePath: "/repo" },+ ],+ projectCwd: "/repo",+ }),+ ).toEqual({+ branch: "feature/split",+ worktreePath: "/repo/.t3/worktrees/split",+ awaitsCurrentBranch: false,+ });+ });+});++describe("resolveNewTaskBranchWorktreePath", () => {+ it("moves Current checkout to the selected existing worktree", () => {+ expect(+ resolveNewTaskBranchWorktreePath({+ workspaceMode: "local",+ projectCwd: "/repo",+ branchWorktreePath: "/repo/.t3/worktrees/feature",+ }),+ ).toBe("/repo/.t3/worktrees/feature");+ });++ it("keeps the project checkout represented by a null override", () => {+ expect(+ resolveNewTaskBranchWorktreePath({+ workspaceMode: "local",+ projectCwd: "/repo",+ branchWorktreePath: "/repo",+ }),+ ).toBeNull();+ });++ it("does not reuse an existing worktree while creating a new one", () => {+ expect(+ resolveNewTaskBranchWorktreePath({+ workspaceMode: "worktree",+ projectCwd: "/repo",+ branchWorktreePath: "/repo/.t3/worktrees/feature",+ }),+ ).toBeNull();+ });+});++describe("resolveNewTaskBranchLabel", () => {+ it("shows the checked-out branch without a base-ref prefix", () => {+ expect(+ resolveNewTaskBranchLabel({+ branchName: "feature/mobile",+ startFromOrigin: true,+ workspaceMode: "local",+ }),+ ).toBe("feature/mobile");+ });++ it("labels a local worktree base with From", () => {+ expect(+ resolveNewTaskBranchLabel({+ branchName: "main",+ startFromOrigin: false,+ workspaceMode: "worktree",+ }),+ ).toBe("From main");+ });++ it("labels a remote worktree base with From origin", () => {+ expect(+ resolveNewTaskBranchLabel({+ branchName: "main",+ startFromOrigin: true,+ workspaceMode: "worktree",+ }),+ ).toBe("From origin/main");+ });++ it("prompts when no branch is available", () => {+ expect(+ resolveNewTaskBranchLabel({+ branchName: null,+ startFromOrigin: true,+ workspaceMode: "worktree",+ }),+ ).toBe("Choose branch");+ });+});diff --git a/apps/mobile/src/features/threads/new-task-context-presentation.ts b/apps/mobile/src/features/threads/new-task-context-presentation.tsnew file mode 100644index 000000000..99eee3ea4--- /dev/null+++ b/apps/mobile/src/features/threads/new-task-context-presentation.ts@@ -0,0 +1,83 @@+type WorkspaceMode = "local" | "worktree";++export function resolveNewTaskWorkspaceLabel(input: {+ readonly workspaceMode: WorkspaceMode;+ readonly worktreePath: string | null;+}): "Current checkout" | "Current worktree" | "New worktree" {+ if (input.workspaceMode === "worktree") {+ return "New worktree";+ }+ return input.worktreePath ? "Current worktree" : "Current checkout";+}++export function resolveNewTaskBranchWorktreePath(input: {+ readonly workspaceMode: WorkspaceMode;+ readonly projectCwd: string;+ readonly branchWorktreePath: string | null | undefined;+}): string | null {+ if (+ input.workspaceMode === "worktree" ||+ !input.branchWorktreePath ||+ input.branchWorktreePath === input.projectCwd+ ) {+ return null;+ }+ return input.branchWorktreePath;+}++export function resolveNewTaskLocalWorkspaceSelection(input: {+ readonly branches: ReadonlyArray<{+ readonly name: string;+ readonly current: boolean;+ readonly worktreePath?: string | null;+ }>;+ readonly projectCwd: string;+}): {+ readonly branch: string | null;+ readonly worktreePath: string | null;+ readonly awaitsCurrentBranch: boolean;+} {+ const currentBranch = input.branches.find((branch) => branch.current) ?? null;+ if (!currentBranch) {+ return {+ branch: null,+ worktreePath: null,+ awaitsCurrentBranch: true,+ };+ }++ return {+ branch: currentBranch.name,+ worktreePath: resolveNewTaskBranchWorktreePath({+ workspaceMode: "local",+ projectCwd: input.projectCwd,+ branchWorktreePath: currentBranch.worktreePath,+ }),+ awaitsCurrentBranch: false,+ };+}++export function resolveNewTaskBranchLabel(input: {+ readonly branchName: string | null;+ readonly startFromOrigin: boolean;+ readonly workspaceMode: WorkspaceMode;+}): string {+ if (!input.branchName) {+ return "Choose branch";+ }++ if (input.workspaceMode === "local") {+ return input.branchName;+ }++ const baseRef = input.startFromOrigin ? `origin/${input.branchName}` : input.branchName;+ return `From ${baseRef}`;+}++export function shouldCheckoutNewTaskBranch(input: {+ readonly branchIsCurrent: boolean;+ readonly branchWorktreePath: string | null | undefined;+ readonly workspaceMode: WorkspaceMode;+}): boolean {+ return input.workspaceMode === "local" && !input.branchIsCurrent && !input.branchWorktreePath;+}diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsxindex 7d79e9ece..44056ead3 100644--- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx+++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx@@ -42,6 +42,7 @@ import { useEnvironmentQuery } from "../../state/query";import {appendComposerDraftAttachments,clearComposerDraft,+ copyComposerDraftContentIfEmpty,getComposerDraftSnapshot,isComposerDraftEmpty,removeComposerDraftAttachment,@@ -50,7 +51,7 @@ import {updateComposerDraftSettings,useComposerDraft,} from "../../state/use-composer-drafts";-import { useBranches } from "../../state/queries";+import { useDebouncedValue, usePaginatedBranches } from "../../state/queries";import {flattenQueuedThreadMessages,threadOutboxManager,@@ -74,10 +75,16 @@ import {type HomeProjectScope,} from "../home/homeThreadList";import { useMobileProjectGroupingSettings } from "../../state/project-grouping";+import { resolvePendingTaskInteractionMode } from "./legacy-plan-mode";+import { useLegacyPlanModeState } from "./use-legacy-plan-mode-enabled";+import {+ resolveNewTaskBranchWorktreePath,+ resolveNewTaskLocalWorkspaceSelection,+} from "./new-task-context-presentation";type WorkspaceMode = "local" | "worktree";-const EMPTY_BRANCH_REFS: ReadonlyArray<VcsRef> = [];+const BRANCH_SEARCH_DEBOUNCE_MS = 150;function pendingTaskDraftKey(messageId: string): string {return `pending-task:${messageId}`;@@ -96,14 +103,6 @@ function findQueuedPendingTask(messageId: string): QueuedThreadMessage | null {return message?.creation !== undefined ? message : null;}-function normalizeSelectedWorktreePath(project: EnvironmentProject, branch: VcsRef): string | null {- if (!branch.worktreePath) {- return null;- }-- return branch.worktreePath === project.workspaceRoot ? null : branch.worktreePath;-}-export function branchBadgeLabel(input: {readonly branch: VcsRef;readonly project: EnvironmentProject | null;@@ -117,9 +116,6 @@ export function branchBadgeLabel(input: {if (input.branch.isDefault) {return "default";}- if (input.branch.isRemote) {- return "remote";- }return null;}@@ -139,9 +135,13 @@ type NewTaskFlowContextValue = {readonly submitting: boolean;readonly branchQuery: string;readonly branchesLoading: boolean;+ readonly branchesError: string | null;+ readonly branchesFetchingNextPage: boolean;+ readonly hasMoreBranches: boolean;readonly availableBranches: ReadonlyArray<VcsRef>;readonly runtimeMode: RuntimeMode;readonly interactionMode: ProviderInteractionMode;+ readonly planModeEnabled: boolean;readonly expandedProvider: string | null;readonly environments: ReadonlyArray<{readonly environmentId: EnvironmentId;@@ -175,7 +175,8 @@ type NewTaskFlowContextValue = {readonly clearAttachments: () => void;readonly setSubmitting: (value: boolean) => void;readonly setBranchQuery: (value: string) => void;- readonly loadBranches: () => Promise<void>;+ readonly loadBranches: () => void;+ readonly loadMoreBranches: () => void;readonly setRuntimeMode: (value: RuntimeMode) => void;readonly setInteractionMode: (value: ProviderInteractionMode) => void;readonly setSelectedModelOptions: (@@ -191,6 +192,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {const threads = useThreadShells();const { savedConnectionsById } = useSavedRemoteConnections();const groupingSettings = useMobileProjectGroupingSettings();+ const { enabled: planModeEnabled, loaded: planModePreferenceLoaded } = useLegacyPlanModeState();const projectScopes = useMemo(() =>sortHomeProjectScopes({@@ -219,6 +221,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {const [branchQuery, setBranchQuery] = useState("");const [expandedProvider, setExpandedProvider] = useState<string | null>(null);const [editingPendingTask, setEditingPendingTask] = useState<QueuedThreadMessage | null>(null);+ const pendingLocalBranchSyncDraftKeysRef = useRef(new Set<string>());// Mirrors `editingPendingTask` synchronously so the unmount flush cannot act// on a task whose editing session already ended this render.const editingPendingTaskRef = useRef<QueuedThreadMessage | null>(null);@@ -229,6 +232,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {setSubmitting(false);setBranchQuery("");setExpandedProvider(null);+ pendingLocalBranchSyncDraftKeysRef.current.clear();const editing = editingPendingTaskRef.current;editingPendingTaskRef.current = null;setEditingPendingTask(null);@@ -395,7 +399,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {selectedEnvironmentServerConfig?.settings.newWorktreesStartFromOrigin ??true;const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;- const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;+ const interactionMode = planModeEnabled+ ? (selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE)+ : DEFAULT_PROVIDER_INTERACTION_MODE;// Stored selections only count while their provider is usable on the// server; otherwise the server's default model wins instead of silently@@ -521,18 +527,24 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {}replaceComposerDraftAttachments(selectedProjectDraftKey, []);}, [selectedProjectDraftKey]);+ const debouncedBranchQuery = useDebouncedValue(branchQuery, BRANCH_SEARCH_DEBOUNCE_MS);const branchTarget = useMemo(() => ({environmentId: selectedProject?.environmentId ?? null,// `|| null` also skips the stand-in project's empty workspaceRoot.cwd: selectedProject?.workspaceRoot || null,- query: null,+ query: debouncedBranchQuery,}),- [selectedProject?.environmentId, selectedProject?.workspaceRoot],+ [debouncedBranchQuery, selectedProject?.environmentId, selectedProject?.workspaceRoot],);- const branchState = useBranches(branchTarget);- const branchesLoading = branchState.isPending;- const allBranchRefs = branchState.data?.refs ?? EMPTY_BRANCH_REFS;+ const branchState = usePaginatedBranches(branchTarget);+ const branchSearchIsDebouncing = branchQuery.trim() !== debouncedBranchQuery.trim();+ const branchesLoading =+ branchSearchIsDebouncing || (branchState.isPending && branchState.data === null);+ const branchesFetchingNextPage = branchState.isFetchingNextPage;+ const hasMoreBranches =+ branchState.data?.nextCursor !== null && branchState.data?.nextCursor !== undefined;+ const allBranchRefs = branchState.refs;const availableBranches = useMemo(() =>pipe(@@ -554,11 +566,21 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {);}, [availableBranches, branchQuery]);- const setProject = useCallback((project: EnvironmentProject) => {- const nextProjectKey = scopedProjectKey(project.environmentId, project.id);- setSelectedEnvironmentId(project.environmentId);- setSelectedProjectKey(nextProjectKey);- }, []);+ const setProject = useCallback(+ (project: EnvironmentProject) => {+ const nextProjectKey = scopedProjectKey(project.environmentId, project.id);+ const nextDraftKey = `new-task:${nextProjectKey}`;+ if (+ selectedProjectDraftKey?.startsWith("new-task:") &&+ selectedProjectDraftKey !== nextDraftKey+ ) {+ void copyComposerDraftContentIfEmpty(selectedProjectDraftKey, nextDraftKey);+ }+ setSelectedEnvironmentId(project.environmentId);+ setSelectedProjectKey(nextProjectKey);+ },+ [selectedProjectDraftKey],+ );const selectEnvironment = useCallback((environmentId: EnvironmentId) => {@@ -596,28 +618,86 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {if (!selectedProjectDraftKey) {return;}+ if (!selectedProject) {+ return;+ }+ const localSelection = resolveNewTaskLocalWorkspaceSelection({+ branches: availableBranches,+ projectCwd: selectedProject.workspaceRoot,+ });+ if (mode === "local" && localSelection.awaitsCurrentBranch) {+ pendingLocalBranchSyncDraftKeysRef.current.add(selectedProjectDraftKey);+ } else {+ pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);+ }updateComposerDraftSettings(selectedProjectDraftKey, {workspaceSelection: {mode,- branch: selectedBranchName,- worktreePath: selectedWorktreePath,+ branch: mode === "local" ? localSelection.branch : selectedBranchName,+ worktreePath: mode === "local" ? localSelection.worktreePath : selectedWorktreePath,...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),},});},- [draftStartFromOrigin, selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],+ [+ availableBranches,+ draftStartFromOrigin,+ selectedBranchName,+ selectedProject,+ selectedProjectDraftKey,+ selectedWorktreePath,+ ],);+ useEffect(() => {+ if (+ workspaceMode !== "local" ||+ !selectedProject ||+ !selectedProjectDraftKey ||+ !pendingLocalBranchSyncDraftKeysRef.current.has(selectedProjectDraftKey)+ ) {+ return;+ }+ const localSelection = resolveNewTaskLocalWorkspaceSelection({+ branches: availableBranches,+ projectCwd: selectedProject.workspaceRoot,+ });+ if (localSelection.awaitsCurrentBranch) {+ return;+ }++ pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);+ updateComposerDraftSettings(selectedProjectDraftKey, {+ workspaceSelection: {+ mode: "local",+ branch: localSelection.branch,+ worktreePath: localSelection.worktreePath,+ ...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),+ },+ });+ }, [+ availableBranches,+ draftStartFromOrigin,+ selectedProject,+ selectedProjectDraftKey,+ workspaceMode,+ ]);+const selectBranch = useCallback((branch: VcsRef) => {if (!selectedProject || !selectedProjectDraftKey) {return;}+ pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);updateComposerDraftSettings(selectedProjectDraftKey, {workspaceSelection: {mode: workspaceMode,branch: branch.name,- worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),+ worktreePath: resolveNewTaskBranchWorktreePath({+ workspaceMode,+ projectCwd: selectedProject.workspaceRoot,+ branchWorktreePath: branch.worktreePath,+ }),...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),},});@@ -643,7 +723,8 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {);const refreshBranches = branchState.refresh;- const loadBranches = useCallback(async () => {+ const loadMoreBranches = branchState.loadNext;+ const loadBranches = useCallback(() => {if (!selectedProject) {return;}@@ -767,7 +848,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {attachments: draft.attachments,modelSelection: draftModelSelection,runtimeMode: draft.runtimeMode ?? DEFAULT_RUNTIME_MODE,- interactionMode: draft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE,+ interactionMode: resolvePendingTaskInteractionMode({+ preferenceLoaded: planModePreferenceLoaded,+ planModeEnabled,+ draftInteractionMode: draft.interactionMode,+ queuedInteractionMode: editingPendingTask?.interactionMode,+ }),creation: {projectId: selectedProject.id,...(projectTitle !== undefined ? { projectTitle } : {}),@@ -792,6 +878,8 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {selectedModel,selectedProject,selectedProjectDraftKey,+ planModeEnabled,+ planModePreferenceLoaded,startFromOrigin,workspaceMode,],@@ -904,9 +992,13 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {submitting,branchQuery,branchesLoading,+ branchesError: branchState.error,+ branchesFetchingNextPage,+ hasMoreBranches,availableBranches,runtimeMode,interactionMode,+ planModeEnabled,expandedProvider,environments,selectedProject,@@ -935,6 +1027,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {setSubmitting,setBranchQuery,loadBranches,+ loadMoreBranches,setRuntimeMode,setInteractionMode,setSelectedModelOptions,@@ -946,6 +1039,8 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {beginEditingPendingTask,branchQuery,branchesLoading,+ branchState.error,+ branchesFetchingNextPage,buildPendingTaskMessage,cancelEditingPendingTask,editingPendingTask,@@ -954,7 +1049,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {filteredBranches,finishEditingPendingTask,interactionMode,+ planModeEnabled,loadBranches,+ loadMoreBranches,projectScopes,modelOptions,prompt,@@ -963,6 +1060,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {reset,runtimeMode,selectedBranchName,+ hasMoreBranches,selectedEnvironmentId,selectedModel,selectedModelKey,diff --git a/apps/mobile/src/features/threads/new-task-project-selection.test.ts b/apps/mobile/src/features/threads/new-task-project-selection.test.tsindex d8ed12bcc..7068a95d5 100644--- a/apps/mobile/src/features/threads/new-task-project-selection.test.ts+++ b/apps/mobile/src/features/threads/new-task-project-selection.test.ts@@ -5,12 +5,13 @@ import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";import type { HomeProjectScope } from "../home/homeThreadList";import {getOnlySelectableProject,+ getProjectScopeSelectionTarget,resolveDraftProjectSelection,} from "./new-task-project-selection";-function makeProject(id: string): EnvironmentProject {+function makeProject(id: string, environmentId = "environment"): EnvironmentProject {return {- environmentId: EnvironmentId.make("environment"),+ environmentId: EnvironmentId.make(environmentId),id: ProjectId.make(id),title: id,workspaceRoot: `/work/${id}`,@@ -41,9 +42,25 @@ describe("getOnlySelectableProject", () => {expect(getOnlySelectableProject([makeScope([project])])).toBe(project);});- it("does not auto-select a representative when one group has multiple clones", () => {+ it("selects the representative when one logical project has multiple workspaces", () => {const projects = [makeProject("t3code"), makeProject("t3code-2"), makeProject("t3code-3")];- expect(getOnlySelectableProject([makeScope(projects)])).toBeNull();+ expect(getOnlySelectableProject([makeScope(projects)])).toBe(projects[0]);+ });+});++describe("getProjectScopeSelectionTarget", () => {+ it("keeps the current environment when it hosts the selected logical project", () => {+ const projects = [makeProject("t3code-mac", "mac"), makeProject("t3code-server", "server")];+ expect(getProjectScopeSelectionTarget(makeScope(projects), EnvironmentId.make("server"))).toBe(+ projects[1],+ );+ });++ it("falls back to the representative when the current environment does not host the project", () => {+ const projects = [makeProject("t3code-mac", "mac"), makeProject("t3code-server", "server")];+ expect(getProjectScopeSelectionTarget(makeScope(projects), EnvironmentId.make("other"))).toBe(+ projects[0],+ );});});@@ -63,10 +80,11 @@ describe("resolveDraftProjectSelection", () => {});});- it("opens the picker for multiple physical projects in one logical group", () => {+ it("selects one logical project even when it has multiple physical workspaces", () => {const projects = [makeProject("t3code"), makeProject("t3code-2"), makeProject("t3code-3")];expect(resolveDraftProjectSelection(null, projects, [makeScope(projects)])).toEqual({- kind: "pick",+ kind: "select",+ project: projects[0],});});diff --git a/apps/mobile/src/features/threads/new-task-project-selection.ts b/apps/mobile/src/features/threads/new-task-project-selection.tsindex 29ae3cf4f..7be899d62 100644--- a/apps/mobile/src/features/threads/new-task-project-selection.ts+++ b/apps/mobile/src/features/threads/new-task-project-selection.ts@@ -1,18 +1,29 @@import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";+import type { EnvironmentId } from "@t3tools/contracts";import { scopedProjectKey } from "../../lib/scopedEntities";import type { HomeProjectScope } from "../home/homeThreadList";-export type DraftProjectSelectionResolution =+type DraftProjectSelectionResolution =| { readonly kind: "preserve" }| { readonly kind: "select"; readonly project: EnvironmentProject }| { readonly kind: "pick" };+export function getProjectScopeSelectionTarget(+ scope: HomeProjectScope,+ preferredEnvironmentId: EnvironmentId | null,+): EnvironmentProject {+ return (+ scope.projects.find((project) => project.environmentId === preferredEnvironmentId) ??+ scope.representative+ );+}+export function getOnlySelectableProject(projectScopes: ReadonlyArray<HomeProjectScope>,): EnvironmentProject | null {const onlyScope = projectScopes.length === 1 ? projectScopes[0] : null;- return onlyScope?.projects.length === 1 ? (onlyScope.projects[0] ?? null) : null;+ return onlyScope?.representative ?? null;}export function resolveDraftProjectSelection(diff --git a/apps/mobile/src/features/threads/thread-settings-menu.test.ts b/apps/mobile/src/features/threads/thread-settings-menu.test.tsdeleted file mode 100644index 078be2df1..000000000--- a/apps/mobile/src/features/threads/thread-settings-menu.test.ts+++ /dev/null@@ -1,284 +0,0 @@-import { describe, expect, it } from "vite-plus/test";--import { ProviderInstanceId, type ProviderOptionDescriptor } from "@t3tools/contracts";--import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";-import { buildThreadSettingsMenu, type ThreadSettingsMenuEvent } from "./thread-settings-menu";--function modelOption(- model: string,- overrides: Partial<Pick<ModelOption, "isDefault" | "isLegacy" | "providerKey">> = {},-): ModelOption {- const providerKey = overrides.providerKey ?? "codex";- return {- key: `${providerKey}:${model}`,- label: model,- subtitle: providerKey,- providerKey,- providerLabel: providerKey === "codex" ? "Codex" : "Claude",- providerDriver: providerKey === "codex" ? "codex" : "claudeAgent",- isDefault: overrides.isDefault ?? false,- isLegacy: overrides.isLegacy ?? false,- capabilities: null,- selection: {- instanceId: ProviderInstanceId.make(providerKey),- model,- options: [],- },- };-}--function group(models: ReadonlyArray<ModelOption>): ProviderGroup {- const first = models[0];- if (!first) {- throw new Error("group requires at least one model");- }- return {- providerKey: first.providerKey,- providerLabel: first.providerLabel,- models,- };-}--const effortDescriptor: ProviderOptionDescriptor = {- id: "effort",- label: "Reasoning",- type: "select",- options: [- { id: "low", label: "Low" },- { id: "medium", label: "Medium", isDefault: true },- { id: "high", label: "High" },- { id: "ultrathink", label: "Ultrathink" },- { id: "ultracode", label: "Ultracode" },- ],- currentValue: "high",- promptInjectedValues: ["ultrathink"],-};--const fastModeDescriptor: ProviderOptionDescriptor = {- id: "fastMode",- label: "Fast mode",- type: "boolean",- currentValue: false,-};--function baseInput() {- const models = [- modelOption("gpt-current", { isDefault: true }),- modelOption("gpt-next"),- modelOption("gpt-old", { isLegacy: true }),- ];- return {- providerGroups: [group(models)],- selectedModel: models[0]?.selection ?? null,- optionDescriptors: [effortDescriptor, fastModeDescriptor],- runtimeMode: "auto",- } as const;-}--function eventFor(menu: ReturnType<typeof buildThreadSettingsMenu>, id: string | undefined) {- return id === undefined ? undefined : menu.events.get(id);-}--describe("buildThreadSettingsMenu", () => {- it("orders the top level as model, options, runtime", () => {- const menu = buildThreadSettingsMenu(baseInput());-- expect(menu.actions.map((action) => action.title)).toEqual([- "Model",- "Reasoning",- "Fast mode",- "Runtime",- ]);- });-- it("summarizes the current choice on each submenu row", () => {- const menu = buildThreadSettingsMenu(baseInput());-- expect(menu.actions.find((action) => action.title === "Model")?.subtitle).toBe("gpt-current");- expect(menu.actions.find((action) => action.title === "Reasoning")?.subtitle).toBe("High");- expect(menu.actions.find((action) => action.title === "Runtime")?.subtitle).toBe("Auto");- });-- it("checkmarks the selected model and resolves selection events", () => {- const menu = buildThreadSettingsMenu(baseInput());-- const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];- const current = modelItems.find((action) => action.title === "gpt-current");- expect(current?.state).toBe("on");- expect(current?.subtitle).toBe("Default");- expect(modelItems.find((action) => action.title === "gpt-next")?.state).toBe("off");-- const event = eventFor(menu, modelItems.find((action) => action.title === "gpt-next")?.id);- expect(event?.type).toBe("select-model");- expect(event?.type === "select-model" ? event.option.selection.model : null).toBe("gpt-next");- });-- it("folds unselected legacy models behind a nested submenu", () => {- const menu = buildThreadSettingsMenu(baseInput());-- const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];- expect(modelItems.map((action) => action.title)).toEqual([- "gpt-current",- "gpt-next",- "Legacy Models",- ]);- expect(- modelItems- .find((action) => action.title === "Legacy Models")- ?.subactions?.map((action) => action.title),- ).toEqual(["gpt-old"]);- });-- it("keeps a selected legacy model in the main list", () => {- const input = baseInput();- const legacy = input.providerGroups[0]?.models.find((model) => model.isLegacy);- const menu = buildThreadSettingsMenu({- ...input,- selectedModel: legacy?.selection ?? null,- });-- const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];- expect(modelItems.map((action) => action.title)).toEqual([- "gpt-current",- "gpt-next",- "gpt-old",- ]);- expect(modelItems.find((action) => action.title === "gpt-old")?.state).toBe("on");- });-- it("hides prompt-injected and workflow-trigger efforts but still summarizes them", () => {- const menu = buildThreadSettingsMenu({- ...baseInput(),- optionDescriptors: [{ ...effortDescriptor, currentValue: "ultracode" }],- });-- const reasoning = menu.actions.find((action) => action.title === "Reasoning");- expect(reasoning?.subactions?.map((action) => action.title)).toEqual(["Low", "Medium", "High"]);- // The hidden value stays visible as the current summary; it just can't be- // picked from the phone.- expect(reasoning?.subtitle).toBe("Ultracode");- expect(reasoning?.subactions?.every((action) => action.state === "off")).toBe(true);- });-- it("resolves select-option and runtime events with checkmarked current values", () => {- const menu = buildThreadSettingsMenu(baseInput());-- const reasoningItems =- menu.actions.find((action) => action.title === "Reasoning")?.subactions ?? [];- expect(reasoningItems.find((action) => action.title === "High")?.state).toBe("on");- expect(eventFor(menu, reasoningItems.find((action) => action.title === "Low")?.id)).toEqual({- type: "set-option",- optionId: "effort",- value: "low",- });-- const runtimeItems =- menu.actions.find((action) => action.title === "Runtime")?.subactions ?? [];- expect(runtimeItems.find((action) => action.title === "Auto")?.state).toBe("on");- expect(- eventFor(menu, runtimeItems.find((action) => action.title === "Full access")?.id),- ).toEqual({ type: "set-runtime", mode: "full-access" });- });-- it("toggles boolean options with the inverted current value", () => {- const menu = buildThreadSettingsMenu(baseInput());-- const fastMode = menu.actions.find((action) => action.title === "Fast mode");- expect(fastMode?.state).toBe("off");- expect(fastMode?.subactions).toBeUndefined();- expect(eventFor(menu, fastMode?.id)).toEqual({- type: "set-option",- optionId: "fastMode",- value: true,- });-- const enabled = buildThreadSettingsMenu({- ...baseInput(),- optionDescriptors: [{ ...fastModeDescriptor, currentValue: true }],- });- const enabledRow = enabled.actions.find((action) => action.title === "Fast mode");- expect(enabledRow?.state).toBe("on");- expect(eventFor(enabled, enabledRow?.id)).toEqual({- type: "set-option",- optionId: "fastMode",- value: false,- });- });-- it("keeps the menu presented only for top-level toggles", () => {- const menu = buildThreadSettingsMenu(baseInput());-- // Root-level boolean toggles refresh in place with clean chrome, so they- // keep the menu presented.- expect(- menu.actions.find((action) => action.title === "Fast mode")?.attributes?.keepsMenuPresented,- ).toBe(true);-- // Picks inside nested submenus close the menu: staying presented leaves- // the submenu on screen with an expanded-submenu header, and the- // bottom-anchored collapse back out drops by the levels' height delta.- const expected = undefined;- const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];- const reasoningItems =- menu.actions.find((action) => action.title === "Reasoning")?.subactions ?? [];- const runtimeItems =- menu.actions.find((action) => action.title === "Runtime")?.subactions ?? [];- const nestedPicks = [...modelItems, ...reasoningItems, ...runtimeItems].filter(- (action) => action.subactions === undefined,- );- expect(nestedPicks.length).toBeGreaterThan(0);- expect(nestedPicks.every((action) => action.attributes?.keepsMenuPresented === expected)).toBe(- true,- );- });-- it("sections models by provider only when multiple groups are offered", () => {- const codexModels = [modelOption("gpt-current", { isDefault: true })];- const claudeModels = [modelOption("fable-5", { providerKey: "claude" })];- const menu = buildThreadSettingsMenu({- providerGroups: [group(codexModels), group(claudeModels)],- selectedModel: codexModels[0]?.selection ?? null,- optionDescriptors: [],- runtimeMode: "auto",- });-- const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];- expect(- modelItems.map((action) => ({ title: action.title, inline: action.displayInline ?? false })),- ).toEqual([- { title: "Codex", inline: true },- { title: "Claude", inline: true },- ]);- const claudeSection = modelItems.find((action) => action.title === "Claude");- expect(claudeSection?.subactions?.map((action) => action.title)).toEqual(["fable-5"]);- });-- const eventTypes = (menu: ReturnType<typeof buildThreadSettingsMenu>) => {- const types = new Set<ThreadSettingsMenuEvent["type"]>();- for (const event of menu.events.values()) {- types.add(event.type);- }- return types;- };-- it("registers an event for every leaf action id", () => {- const menu = buildThreadSettingsMenu(baseInput());- const leafIds: string[] = [];- const collect = (items: ReadonlyArray<{ id?: string; subactions?: unknown[] }>) => {- for (const item of items) {- if (Array.isArray(item.subactions) && item.subactions.length > 0) {- collect(item.subactions as ReadonlyArray<{ id?: string; subactions?: unknown[] }>);- } else if (item.id !== undefined) {- leafIds.push(item.id);- }- }- };- collect(menu.actions);-- for (const id of leafIds) {- expect(menu.events.get(id), `missing event for ${id}`).toBeDefined();- }- expect(eventTypes(menu)).toEqual(new Set(["select-model", "set-option", "set-runtime"]));- });-});diff --git a/apps/mobile/src/features/threads/thread-settings-menu.ts b/apps/mobile/src/features/threads/thread-settings-menu.tsdeleted file mode 100644index 31b1c021c..000000000--- a/apps/mobile/src/features/threads/thread-settings-menu.ts+++ /dev/null@@ -1,202 +0,0 @@-import type { MenuAction } from "@react-native-menu/menu";-import type { ModelSelection, ProviderOptionDescriptor, RuntimeMode } from "@t3tools/contracts";-import {- getProviderOptionCurrentLabel,- getProviderOptionCurrentValue,-} from "@t3tools/shared/model";--import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";--/**- * 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.- */-export const HIDDEN_EFFORT_OPTION_IDS: ReadonlySet<string> = new Set(["ultracode"]);--export 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" },-];--export 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),- );-}--export type ThreadSettingsMenuEvent =- | { readonly type: "select-model"; readonly option: ModelOption }- | { readonly type: "set-option"; readonly optionId: string; readonly value: string | boolean }- | { readonly type: "set-runtime"; readonly mode: RuntimeMode };--export type ThreadSettingsMenu = {- readonly actions: MenuAction[];- /** Menu action id → the change it applies, for the onPressAction dispatch. */- readonly events: ReadonlyMap<string, ThreadSettingsMenuEvent>;-};--/**- * Native menu replacement for the thread settings sheet (model, select and- * boolean provider options, runtime mode). The menu presents from the- * composer pill without resigning the keyboard, so adjusting settings never- * bounces focus. A thread is bound to one harness, so the menu covers the- * sheet's full surface for existing threads; the sheet remains the Android- * and new-task-draft surface.- *- * Selections apply immediately — the sheet's stage-then-Save flow only exists- * because the sheet batches a model change with its option edits.- */-export function buildThreadSettingsMenu(input: {- readonly providerGroups: ReadonlyArray<ProviderGroup>;- readonly selectedModel: ModelSelection | null;- readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;- readonly runtimeMode: RuntimeMode;-}): ThreadSettingsMenu {- const events = new Map<string, ThreadSettingsMenuEvent>();- const actions: MenuAction[] = [];-- const isSelected = (option: ModelOption) =>- option.selection.instanceId === input.selectedModel?.instanceId &&- option.selection.model === input.selectedModel.model;-- // Only top-level leaves (boolean toggles) keep the menu presented (iOS- // 16+): the root refreshes in place with clean chrome. Picks inside nested- // submenus close the menu — keeping the submenu presented renders an- // expanded-submenu header with no way to pop back to the root, and the- // bottom-anchored collapse back out travels the levels' height difference.- const keepPresented = { keepsMenuPresented: true } as const;-- const modelAction = (option: ModelOption, id: string): MenuAction => {- events.set(id, { type: "select-model", option });- return {- id,- title: option.label,- ...(option.isDefault ? { subtitle: "Default" } : {}),- state: isSelected(option) ? "on" : "off",- };- };-- const modelItems: MenuAction[] = [];- const legacyItems: MenuAction[] = [];- let selectedModelLabel: string | undefined;- input.providerGroups.forEach((group, groupIndex) => {- const groupItems: MenuAction[] = [];- group.models.forEach((option, modelIndex) => {- if (isSelected(option)) {- selectedModelLabel = option.label;- }- const id = `model:${groupIndex}:${modelIndex}`;- // A highlighted legacy model stays in the main list (mirroring the- // sheet) so the checkmark isn't hidden behind the Legacy fold.- if (option.isLegacy && !isSelected(option)) {- legacyItems.push(modelAction(option, id));- } else {- groupItems.push(modelAction(option, id));- }- });- if (groupItems.length === 0) {- return;- }- // A thread is bound to one harness, so provider sections only appear for- // multi-group callers (the new-task draft, if it ever adopts the menu).- if (input.providerGroups.length > 1) {- modelItems.push({- id: `model-group:${groupIndex}`,- title: group.providerLabel,- displayInline: true,- subactions: groupItems,- });- } else {- modelItems.push(...groupItems);- }- });- if (legacyItems.length > 0) {- modelItems.push({- id: "legacy-models",- title: "Legacy Models",- subactions: legacyItems,- });- }- if (modelItems.length > 0) {- actions.push({- id: "model",- title: "Model",- ...(selectedModelLabel === undefined- ? input.selectedModel- ? { subtitle: input.selectedModel.model }- : {}- : { subtitle: selectedModelLabel }),- subactions: modelItems,- });- }-- for (const descriptor of input.optionDescriptors) {- if (descriptor.type === "boolean") {- const id = `option:${descriptor.id}`;- events.set(id, {- type: "set-option",- optionId: descriptor.id,- value: !(descriptor.currentValue ?? false),- });- actions.push({- id,- title: descriptor.label,- state: descriptor.currentValue ? "on" : "off",- attributes: keepPresented,- });- continue;- }- const currentValue = getProviderOptionCurrentValue(descriptor);- const choices = selectableChoices(descriptor).map((choice): MenuAction => {- const id = `option:${descriptor.id}:${choice.id}`;- events.set(id, { type: "set-option", optionId: descriptor.id, value: choice.id });- return {- id,- title: choice.label,- state: choice.id === currentValue ? "on" : "off",- };- });- if (choices.length === 0) {- continue;- }- const currentLabel = getProviderOptionCurrentLabel(descriptor);- actions.push({- id: `option:${descriptor.id}`,- title: descriptor.label,- ...(currentLabel === undefined ? {} : { subtitle: currentLabel }),- subactions: choices,- });- }-- const runtimeLabel = RUNTIME_MODE_CHOICES.find(- (choice) => choice.mode === input.runtimeMode,- )?.label;- actions.push({- id: "runtime",- title: "Runtime",- ...(runtimeLabel === undefined ? {} : { subtitle: runtimeLabel }),- subactions: RUNTIME_MODE_CHOICES.map((choice): MenuAction => {- const id = `runtime:${choice.mode}`;- events.set(id, { type: "set-runtime", mode: choice.mode });- return {- id,- title: choice.label,- state: choice.mode === input.runtimeMode ? "on" : "off",- };- }),- });-- return { actions, events };-}diff --git a/apps/mobile/src/features/threads/thread-settings-options.test.ts b/apps/mobile/src/features/threads/thread-settings-options.test.tsnew file mode 100644index 000000000..041f8b9de--- /dev/null+++ b/apps/mobile/src/features/threads/thread-settings-options.test.ts@@ -0,0 +1,29 @@+import type { ProviderOptionDescriptor } from "@t3tools/contracts";+import { describe, expect, it } from "vite-plus/test";++import { selectableChoices } from "./thread-settings-options";++const effortDescriptor: Extract<ProviderOptionDescriptor, { type: "select" }> = {+ id: "effort",+ label: "Reasoning",+ type: "select",+ options: [+ { id: "low", label: "Low" },+ { id: "medium", label: "Medium", isDefault: true },+ { id: "high", label: "High" },+ { id: "ultrathink", label: "Ultrathink" },+ { id: "ultracode", label: "Ultracode" },+ ],+ currentValue: "high",+ promptInjectedValues: ["ultrathink"],+};++describe("selectableChoices", () => {+ it("hides prompt-injected and workflow-trigger choices, keeping declared order", () => {+ expect(selectableChoices(effortDescriptor).map((choice) => choice.id)).toEqual([+ "low",+ "medium",+ "high",+ ]);+ });+});diff --git a/apps/mobile/src/features/threads/thread-settings-options.ts b/apps/mobile/src/features/threads/thread-settings-options.tsnew file mode 100644index 000000000..b678154f8--- /dev/null+++ b/apps/mobile/src/features/threads/thread-settings-options.ts@@ -0,0 +1,46 @@+import type { ProviderOptionDescriptor, RuntimeMode } from "@t3tools/contracts";++/**+ * 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"]);++export const RUNTIME_MODE_CHOICES: ReadonlyArray<{+ readonly mode: RuntimeMode;+ readonly label: string;+ readonly description: string;+}> = [+ {+ mode: "approval-required",+ label: "Supervised",+ description: "Ask before commands and file changes.",+ },+ {+ mode: "auto-accept-edits",+ label: "Auto-accept edits",+ description: "Auto-approve edits, ask before other actions.",+ },+ {+ mode: "auto",+ label: "Auto",+ description: "Supported providers approve routine actions; others still ask.",+ },+ {+ mode: "full-access",+ label: "Full access",+ description: "Allow commands and edits without prompts.",+ },+];++export 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),+ );+}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.tsindex 1264c75cd..2e8fee985 100644--- a/apps/mobile/src/features/threads/thread-settings-sheet-state.test.ts+++ b/apps/mobile/src/features/threads/thread-settings-sheet-state.test.ts@@ -3,7 +3,7 @@ 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";+import { modelMatchesCatalogQuery, pendingModelAfterPress } from "./thread-settings-sheet-state";function modelOption(model: string,@@ -28,6 +28,26 @@ function modelOption(}describe("thread settings sheet state", () => {+ it("matches visible model and provider terms", () => {+ const model = modelOption("gpt-next");++ expect(modelMatchesCatalogQuery({ model, providerLabel: "Codex", query: "NEXT" })).toBe(true);+ expect(modelMatchesCatalogQuery({ model, providerLabel: "Codex", query: "codex" })).toBe(true);+ expect(modelMatchesCatalogQuery({ model, providerLabel: "Codex", query: "claude" })).toBe(+ false,+ );+ });++ it("treats whitespace-only catalog searches as empty", () => {+ expect(+ modelMatchesCatalogQuery({+ model: modelOption("gpt-next"),+ providerLabel: "Codex",+ query: " ",+ }),+ ).toBe(true);+ });+it("clears staging when the applied model is pressed", () => {expect(pendingModelAfterPress({diff --git a/apps/mobile/src/features/threads/thread-settings-sheet-state.ts b/apps/mobile/src/features/threads/thread-settings-sheet-state.tsindex f0540dc5a..1e417b925 100644--- a/apps/mobile/src/features/threads/thread-settings-sheet-state.ts+++ b/apps/mobile/src/features/threads/thread-settings-sheet-state.ts@@ -1,5 +1,24 @@import type { ModelOption } from "../../lib/modelOptions";+/** Match the terms a user can actually see or recognize in the model picker. */+export function modelMatchesCatalogQuery(input: {+ readonly model: ModelOption;+ readonly providerLabel: string;+ readonly query: string;+}): boolean {+ const query = input.query.trim().toLocaleLowerCase();+ if (query.length === 0) {+ return true;+ }++ return [+ input.model.label,+ input.model.subtitle,+ input.model.selection.model,+ input.providerLabel,+ ].some((value) => value.toLocaleLowerCase().includes(query));+}+/** Preserve staged provider options when the highlighted model is tapped again. */export function pendingModelAfterPress(input: {readonly current: ModelOption | null;@@ -11,3 +30,18 @@ export function pendingModelAfterPress(input: {}return input.current?.key === input.pressed.key ? input.current : input.pressed;}++/**+ * Primary and selected providers start open; all other catalogs start closed.+ * A user's disclosure tap inverts that default until the picker is dismissed.+ */+export function providerSectionIsCollapsed(input: {+ readonly defaultExpanded: boolean;+ readonly hasExpansionOverride: boolean;+ readonly isNarrowed: boolean;+}): boolean {+ if (input.isNarrowed) {+ return false;+ }+ return input.defaultExpanded ? input.hasExpansionOverride : !input.hasExpansionOverride;+}diff --git a/apps/mobile/src/features/threads/use-legacy-plan-mode-enabled.ts b/apps/mobile/src/features/threads/use-legacy-plan-mode-enabled.tsnew file mode 100644index 000000000..25ec4ff0e--- /dev/null+++ b/apps/mobile/src/features/threads/use-legacy-plan-mode-enabled.ts@@ -0,0 +1,26 @@+import { useAtomValue } from "@effect/atom-react";+import { AsyncResult } from "effect/unstable/reactivity";++import { mobilePreferencesAtom } from "../../state/preferences";+import { resolveLegacyPlanModeEnabled } from "./legacy-plan-mode";++/**+ * Mobile preferences are device-local, matching the desktop client setting.+ * Keep the legacy composer mode hidden until the preference has loaded and is+ * explicitly enabled.+ */+export function useLegacyPlanModeEnabled(): boolean {+ return useLegacyPlanModeState().enabled;+}++export function useLegacyPlanModeState(): { readonly enabled: boolean; readonly loaded: boolean } {+ const preferences = useAtomValue(mobilePreferencesAtom);+ const loaded = AsyncResult.isSuccess(preferences);+ return {+ enabled: resolveLegacyPlanModeEnabled({+ loaded,+ preference: loaded ? preferences.value.planModeEnabled : undefined,+ }),+ loaded,+ };+}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.tsindex 3cc2ed184..b5b4914ad 100644--- a/apps/mobile/src/features/threads/use-thread-settings-sheet-presentation.ts+++ b/apps/mobile/src/features/threads/use-thread-settings-sheet-presentation.ts@@ -3,14 +3,46 @@ import { KeyboardController } from "react-native-keyboard-controller";import type { ComposerEditorHandle } from "../../components/ComposerEditor";-export type ThreadSettingsSheetCloseReason = "save" | "dismiss";+type PresentationPhase = "closed" | "opening" | "visible";-type PresentationPhase = "closed" | "opening" | "visible" | "closing";+/**+ * The navigator-level UIKit completion event added by the repo's+ * `@react-navigation/native-stack` patch; absent from upstream event maps.+ */+export type NavigationWithFinishTransitioning = {+ readonly addListener: (type: "finishTransitioning", callback: () => void) => () => void;+};++/**+ * How long after the dismissal's state change the keyboard starts rising, so+ * its ~250ms show overlaps the tail of the sheet's ~500ms travel the way+ * UIKit apps choreograph it. This is aesthetics, not correctness: without+ * keepFocus-style inputView overrides a show started mid-dismissal completes+ * cleanly, so a slower device merely gets more overlap — no failure mode.+ * The navigator's `finishTransitioning` event (UIKit's real completion+ * callback, surfaced by the repo's native-stack patch) additionally bounds+ * the restore at the true landing moment should this timer ever lag it.+ */+const SHEET_DISMISSAL_KEYBOARD_OVERLAP_MS = 300;++/**+ * A JS-initiated dismissal pops state before its animation runs; a+ * gesture-driven one animates natively first and pops afterwards, with the+ * navigator's completion event landing a few dozen milliseconds before the+ * pop. A completion this fresh at pop time therefore means the sheet is+ * already gone and the keyboard should return immediately. The two orderings+ * are separated by the sheet's full ~500ms travel, so this window is a+ * classification with wide margin, not an animation race.+ */+const NATIVE_DISMISSAL_ECHO_WINDOW_MS = 150;/**- * 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.+ * Keeps the custom native composer and the settings sheet from owning focus at+ * the same time. Opening resigns the editor cleanly; a dismissal re-focuses it+ * once the sheet has fully landed. A plain blur/focus pair costs one keyboard+ * animation each way — keepFocus-style inputView overrides are avoided because+ * removing them forces UIKit to reload input views, replaying the keyboard's+ * show as a visible collapse/re-open.*/export function useThreadSettingsSheetPresentation(input: {readonly editorRef: RefObject<ComposerEditorHandle | null>;@@ -19,18 +51,36 @@ export function useThreadSettingsSheetPresentation(input: {const [phase, setPhase] = useState<PresentationPhase>("closed");const isActiveRef = useRef(false);const isMountedRef = useRef(true);+ const isEditorFocusedRef = useRef(input.isEditorFocused);const openingIdRef = useRef(0);- const restoreFocusOnSaveRef = useRef(false);- const shouldRestoreAfterDismissRef = useRef(false);+ const focusRestoreIdRef = useRef(0);+ const restoreFocusAfterDismissRef = useRef(false);+ const restorePendingRef = useRef(false);+ const lastStackTransitionFinishedAtRef = useRef(0);+ const dismissRestoreTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const clearDismissRestoreTimer = useCallback(() => {+ if (dismissRestoreTimerRef.current !== null) {+ clearTimeout(dismissRestoreTimerRef.current);+ dismissRestoreTimerRef.current = null;+ }+ }, []);- useEffect(- () => () => {+ useEffect(() => {+ isEditorFocusedRef.current = input.isEditorFocused;+ }, [input.isEditorFocused]);++ useEffect(() => {+ // React Strict Mode and Fast Refresh both run an effect cleanup/setup+ // cycle without recreating refs. Re-arm the mounted guard on every setup.+ isMountedRef.current = true;+ return () => {isMountedRef.current = false;isActiveRef.current = false;openingIdRef.current += 1;- },- [],- );+ focusRestoreIdRef.current += 1;+ clearDismissRestoreTimer();+ };+ }, [clearDismissRestoreTimer]);const open = useCallback(() => {if (isActiveRef.current) {@@ -38,61 +88,107 @@ export function useThreadSettingsSheetPresentation(input: {}isActiveRef.current = true;- restoreFocusOnSaveRef.current = input.isEditorFocused || KeyboardController.isVisible();- shouldRestoreAfterDismissRef.current = false;+ focusRestoreIdRef.current += 1;+ clearDismissRestoreTimer();+ restorePendingRef.current = false;+ restoreFocusAfterDismissRef.current = input.isEditorFocused || KeyboardController.isVisible();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.+ // Start the keyboard transition before the custom native editor resigns+ // first responder, then present the sheet on the next frame. The sheet and+ // keyboard animate together instead of serializing two native transitions.+ void KeyboardController.dismiss({ animated: true });input.editorRef.current?.blur();- void KeyboardController.dismiss().then(() => {++ requestAnimationFrame(() => {if (!isMountedRef.current || !isActiveRef.current || openingIdRef.current !== openingId) {return;}setPhase("visible");});- }, [input.editorRef, input.isEditorFocused]);+ }, [clearDismissRestoreTimer, input.editorRef, input.isEditorFocused]);++ const restoreEditorFocus = useCallback(() => {+ const focusRestoreId = focusRestoreIdRef.current + 1;+ focusRestoreIdRef.current = focusRestoreId;+ let attemptsRemaining = 20;++ // Restoration runs after the dismissal transition, so the first attempt+ // normally succeeds; the retries are insurance against UIKit briefly+ // refusing first-responder status right at the transition boundary.+ const restoreFocus = () => {+ if (+ !isMountedRef.current ||+ focusRestoreIdRef.current !== focusRestoreId ||+ isEditorFocusedRef.current ||+ attemptsRemaining <= 0+ ) {+ return;+ }- const close = useCallback((reason: ThreadSettingsSheetCloseReason) => {- if (!isActiveRef.current) {+ attemptsRemaining -= 1;+ input.editorRef.current?.focus();+ setTimeout(restoreFocus, 50);+ };+ requestAnimationFrame(restoreFocus);+ }, [input.editorRef]);++ /** Runs the queued restore once — whichever completion signal arrives first. */+ const runPendingDismissalRestore = useCallback(() => {+ if (!restorePendingRef.current) {return;}+ restorePendingRef.current = false;+ clearDismissRestoreTimer();+ // A reopened sheet owns focus again; drop the stale restore request.+ if (!isMountedRef.current || isActiveRef.current) {+ return;+ }+ restoreEditorFocus();+ }, [clearDismissRestoreTimer, restoreEditorFocus]);- openingIdRef.current += 1;- shouldRestoreAfterDismissRef.current = reason === "save" && restoreFocusOnSaveRef.current;- setPhase("closing");- }, []);-+ /**+ * Marks the sheet closed and queues the keyboard's return for the moment+ * the dismissal transition actually completes: the sheet slides away over a+ * resting composer, then the keyboard lifts it in one continuous motion.+ */const onDismissed = useCallback(() => {- const shouldRestoreFocus = shouldRestoreAfterDismissRef.current;- shouldRestoreAfterDismissRef.current = false;- restoreFocusOnSaveRef.current = false;isActiveRef.current = false;setPhase("closed");- if (shouldRestoreFocus) {- input.editorRef.current?.focus();+ if (!restoreFocusAfterDismissRef.current) {+ return;}- }, [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;+ restoreFocusAfterDismissRef.current = false;+ restorePendingRef.current = true;+ clearDismissRestoreTimer();+ if (Date.now() - lastStackTransitionFinishedAtRef.current <= NATIVE_DISMISSAL_ECHO_WINDOW_MS) {+ // A stack transition finished just before this pop reached JS: the pop+ // is the state echo of a gesture-driven dismissal whose animation has+ // already completed. The sheet is gone — bring the keyboard back now.+ runPendingDismissalRestore();+ return;}- }, []);+ dismissRestoreTimerRef.current = setTimeout(() => {+ dismissRestoreTimerRef.current = null;+ runPendingDismissalRestore();+ }, SHEET_DISMISSAL_KEYBOARD_OVERLAP_MS);+ }, [clearDismissRestoreTimer, runPendingDismissalRestore]);++ /** Wire to the navigator's `finishTransitioning` event. */+ const onStackTransitionsFinished = useCallback(() => {+ lastStackTransitionFinishedAtRef.current = Date.now();+ runPendingDismissalRestore();+ }, [runPendingDismissalRestore]);return {isActive: phase !== "closed",- isActiveRef,isVisible: phase === "visible",open,- close,onDismissed,- restoreFocusAfterSave,+ onStackTransitionsFinished,} as const;}diff --git a/apps/mobile/src/native/native-glass.ts b/apps/mobile/src/native/native-glass.tsindex 40b28076d..18f221940 100644--- a/apps/mobile/src/native/native-glass.ts+++ b/apps/mobile/src/native/native-glass.ts@@ -1,9 +1,9 @@-import { isLiquidGlassSupported } from "@callstack/liquid-glass";+import { isGlassEffectAPIAvailable } from "expo-glass-effect";import { Platform } from "react-native";import { supportsNativeLiquidGlass } from "../lib/native-glass-capability";export const NATIVE_LIQUID_GLASS_SUPPORTED = supportsNativeLiquidGlass(Platform.OS,- isLiquidGlassSupported,+ isGlassEffectAPIAvailable(),);diff --git a/apps/mobile/src/native/sheet-surface.ts b/apps/mobile/src/native/sheet-surface.tsnew file mode 100644index 000000000..eb2e8a8d1--- /dev/null+++ b/apps/mobile/src/native/sheet-surface.ts@@ -0,0 +1,28 @@+import { DynamicColorIOS, Platform, type ColorValue, type ViewStyle } from "react-native";++/**+ * One opaque surface for content rendered inside a native form sheet.+ *+ * UIKit owns the outer sheet material and rounded corners. The presented route+ * owns this surface so nested navigators never expose a differently colored+ * native container while their screens move.+ */+export const NATIVE_SHEET_SURFACE_COLOR: ColorValue | undefined =+ Platform.OS === "ios" ? DynamicColorIOS({ light: "#f2f2f7", dark: "#0e0e0e" }) : undefined;++export const NATIVE_SHEET_SURFACE_CONTENT_STYLE: ViewStyle | undefined =+ NATIVE_SHEET_SURFACE_COLOR === undefined+ ? undefined+ : { backgroundColor: NATIVE_SHEET_SURFACE_COLOR };++/**+ * Paint the adaptive background on the presented screen itself. Nested stacks+ * can stay transparent over this single surface, so a push never exposes an+ * unpainted form-sheet host behind the moving child view controllers.+ */+export const FORM_SHEET_PRESENTATION_OPTIONS = {+ presentation: "formSheet" as const,+ ...(NATIVE_SHEET_SURFACE_CONTENT_STYLE === undefined+ ? null+ : { contentStyle: NATIVE_SHEET_SURFACE_CONTENT_STYLE }),+};diff --git a/apps/mobile/src/persistence/mobile-preferences.ts b/apps/mobile/src/persistence/mobile-preferences.tsindex b504fb190..1da9c9f7a 100644--- a/apps/mobile/src/persistence/mobile-preferences.ts+++ b/apps/mobile/src/persistence/mobile-preferences.ts@@ -35,6 +35,8 @@ export interface Preferences {* default flat list — see `resolveThreadListV2Enabled`.*/readonly legacyThreadListEnabled?: boolean;+ /** Device-local counterpart of desktop's `planModeEnabled` legacy flag. */+ readonly planModeEnabled?: boolean;}export class MobilePreferencesLoadError extends Schema.TaggedErrorClass<MobilePreferencesLoadError>()(@@ -88,6 +90,7 @@ function sanitizePreferences(parsed: Preferences): Preferences {projectGroupingMode?: SidebarProjectGroupingMode;autoSettleOnMerge?: boolean;legacyThreadListEnabled?: boolean;+ planModeEnabled?: boolean;} = {};if (typeof parsed.liveActivitiesEnabled === "boolean") {@@ -130,6 +133,9 @@ function sanitizePreferences(parsed: Preferences): Preferences {if (typeof parsed.legacyThreadListEnabled === "boolean") {preferences.legacyThreadListEnabled = parsed.legacyThreadListEnabled;}+ if (typeof parsed.planModeEnabled === "boolean") {+ preferences.planModeEnabled = parsed.planModeEnabled;+ }return preferences;}diff --git a/apps/mobile/src/state/queries.ts b/apps/mobile/src/state/queries.tsindex b02b190db..0c0da1f84 100644--- a/apps/mobile/src/state/queries.ts+++ b/apps/mobile/src/state/queries.ts@@ -1,14 +1,23 @@-import type { EnvironmentId, OrchestrationThread, ThreadId } from "@t3tools/contracts";+import type { VcsRefTarget } from "@t3tools/client-runtime/state/vcs";+import type {+ EnvironmentId,+ OrchestrationThread,+ ThreadId,+ VcsListRefsResult,+ VcsRef,+} from "@t3tools/contracts";import {createThreadSearchResultsAtomFamily,makeThreadSearchKey,type EnvironmentThreadSearchMatch,} from "@t3tools/client-runtime/state/thread-search";import { useAtomValue } from "@effect/atom-react";+import * as Cause from "effect/Cause";import * as Option from "effect/Option";-import { Atom } from "effect/unstable/reactivity";-import { useEffect, useMemo, useState } from "react";+import { AsyncResult, Atom } from "effect/unstable/reactivity";+import { useCallback, useEffect, useMemo, useState } from "react";+import { appAtomRegistry } from "./atom-registry";import { orchestrationEnvironment } from "./orchestration";import { projectEnvironment } from "./projects";import { useEnvironmentQuery } from "./query";@@ -24,6 +33,8 @@ const COMPOSER_PATH_SEARCH_DEBOUNCE_MS = 200;const COMPOSER_PATH_SEARCH_LIMIT = 20;const THREAD_SEARCH_DEBOUNCE_MS = 200;const VCS_REF_LIST_LIMIT = 100;+const EMPTY_REFS: ReadonlyArray<VcsRef> = [];+const INITIAL_BRANCH_CURSORS = [undefined] as const;const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray<EnvironmentThreadSearchMatch> = Object.freeze([]);const EMPTY_THREAD_SEARCH_ATOM = Atom.make({matches: EMPTY_THREAD_SEARCH_MATCHES,@@ -52,7 +63,7 @@ export interface ComposerPathSearchTarget {readonly query: string | null;}-function useDebouncedValue<A>(value: A, delayMs: number): A {+export function useDebouncedValue<A>(value: A, delayMs: number): A {const [debounced, setDebounced] = useState(value);useEffect(() => {@@ -125,6 +136,113 @@ export function useBranches(input: {);}+export function usePaginatedBranches(target: VcsRefTarget) {+ const query = target.query?.trim() ?? "";+ const targetKey =+ target.environmentId !== null && target.cwd !== null+ ? JSON.stringify([target.environmentId, target.cwd, query])+ : null;+ const [pagination, setPagination] = useState<{+ readonly targetKey: string | null;+ readonly cursors: ReadonlyArray<number | undefined>;+ }>({+ targetKey,+ cursors: INITIAL_BRANCH_CURSORS,+ });+ const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS;+ const pageAtoms = useMemo(+ () =>+ target.environmentId !== null && target.cwd !== null+ ? cursors.map((cursor) =>+ vcsEnvironment.listRefs({+ environmentId: target.environmentId!,+ input: {+ cwd: target.cwd!,+ ...(query.length > 0 ? { query } : {}),+ ...(cursor === undefined ? {} : { cursor }),+ limit: VCS_REF_LIST_LIMIT,+ },+ }),+ )+ : [],+ [cursors, query, target.cwd, target.environmentId],+ );+ const pagesAtom = useMemo(+ () =>+ Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(+ Atom.withLabel(`mobile:vcs-ref-pages:${targetKey ?? "empty"}`),+ ),+ [pageAtoms, targetKey],+ );+ const results = useAtomValue(pagesAtom);+ const values = results.flatMap((result) => {+ const value = Option.getOrNull(AsyncResult.value(result));+ return value === null ? [] : [value];+ });+ const refs = new Map<string, VcsRef>();+ for (const value of values) {+ for (const ref of value.refs) {+ refs.set(ref.name, ref);+ }+ }+ const first = values[0] ?? null;+ const last = values.at(-1) ?? null;+ const data: VcsListRefsResult | null =+ first === null || last === null+ ? null+ : {+ refs: [...refs.values()],+ isRepo: first.isRepo,+ hasPrimaryRemote: first.hasPrimaryRemote,+ nextCursor: last.nextCursor,+ totalCount: Math.max(...values.map((value) => value.totalCount)),+ };+ const lastResult = results.at(-1);+ const isFetchingNextPage =+ results.length > 1 &&+ lastResult?.waiting === true &&+ Option.isNone(AsyncResult.value(lastResult));+ const failed = results.find((result) => result._tag === "Failure");+ const error =+ failed?._tag === "Failure"+ ? (() => {+ const cause = Cause.squash(failed.cause);+ return cause instanceof Error && cause.message.trim().length > 0+ ? cause.message+ : "Failed to load refs.";+ })()+ : null;+ const refresh = useCallback(() => {+ const firstPage = pageAtoms[0];+ setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS });+ if (firstPage !== undefined) {+ appAtomRegistry.refresh(firstPage);+ }+ }, [pageAtoms, targetKey]);+ const loadNext = useCallback(() => {+ if (targetKey === null || data?.nextCursor === null || data?.nextCursor === undefined) {+ return;+ }+ setPagination((current) => {+ const currentCursors =+ current.targetKey === targetKey ? current.cursors : INITIAL_BRANCH_CURSORS;+ return currentCursors.includes(data.nextCursor!)+ ? { targetKey, cursors: currentCursors }+ : { targetKey, cursors: [...currentCursors, data.nextCursor!] };+ });+ }, [data?.nextCursor, targetKey]);++ return {+ data,+ refs: data?.refs ?? EMPTY_REFS,+ error,+ isPending: results.some((result) => result.waiting),+ isFetchingNextPage,+ refresh,+ loadNext,+ };+}+export function useComposerPathSearch(target: ComposerPathSearchTarget) {const normalizedTarget = useMemo(() => ({diff --git a/apps/mobile/src/state/use-composer-drafts.test.ts b/apps/mobile/src/state/use-composer-drafts.test.tsindex fed97e81e..ae03141a8 100644--- a/apps/mobile/src/state/use-composer-drafts.test.ts+++ b/apps/mobile/src/state/use-composer-drafts.test.ts@@ -1,10 +1,57 @@import { afterEach, describe, expect, it } from "@effect/vitest";import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";+import { vi } from "vite-plus/test";++const composerDraftFileMocks = vi.hoisted(() => {+ let document = "";+ let releaseRead: (() => void) | null = null;+ let readBarrier = Promise.resolve();++ return {+ blockRead() {+ readBarrier = new Promise<void>((resolve) => {+ releaseRead = resolve;+ });+ },+ releaseRead() {+ releaseRead?.();+ releaseRead = null;+ },+ setDocument(value: unknown) {+ document = JSON.stringify(value);+ },+ Directory: class {+ create() {}+ },+ File: class {+ exists = true;++ create() {}++ async text() {+ await readBarrier;+ return document;+ }++ write(value: string) {+ document = value;+ }+ },+ };+});++vi.mock("expo-file-system", () => ({+ Directory: composerDraftFileMocks.Directory,+ File: composerDraftFileMocks.File,+ Paths: { document: "/documents" },+}));import { appAtomRegistry } from "./atom-registry";import {clearComposerDraftContentState,composerDraftsAtom,+ copyComposerDraftContentIfEmpty,+ copyComposerDraftContentState,decodePersistedComposerDrafts,type ComposerDraft,getComposerDraftSnapshot,@@ -165,6 +212,53 @@ describe("mobile composer drafts", () => {expect(getComposerDraftSnapshot(draftKey)).toEqual(selectedDraft);});+ it("carries unfinished content to a newly selected project without overwriting its settings", () => {+ const sourceKey = "new-task:environment-1:project-1";+ const targetKey = "new-task:environment-1:project-2";+ const source: ComposerDraft = {+ text: "Keep this task",+ attachments: [],+ importedShareIds: ["share-1"],+ workspaceSelection: {+ mode: "worktree",+ branch: "feature/source",+ worktreePath: null,+ },+ };+ const target: ComposerDraft = {+ text: "",+ attachments: [],+ runtimeMode: "approval-required",+ };++ expect(+ copyComposerDraftContentState(+ { [sourceKey]: source, [targetKey]: target },+ sourceKey,+ targetKey,+ ),+ ).toEqual({+ [sourceKey]: source,+ [targetKey]: {+ ...target,+ text: source.text,+ attachments: source.attachments,+ importedShareIds: source.importedShareIds,+ },+ });+ });++ it("does not overwrite unfinished content already stored for the selected project", () => {+ const sourceKey = "new-task:environment-1:project-1";+ const targetKey = "new-task:environment-1:project-2";+ const drafts: Record<string, ComposerDraft> = {+ [sourceKey]: { text: "Source task", attachments: [] },+ [targetKey]: { text: "Target task", attachments: [] },+ };++ expect(copyComposerDraftContentState(drafts, sourceKey, targetKey)).toBe(drafts);+ });+it("merges shared content into a project draft without duplicating retries", () => {const draftKey = "new-task:environment-1:project-1";const sharedAttachment = {@@ -268,4 +362,35 @@ describe("mobile composer drafts", () => {[`new-task:${retainedEnvironmentId}:project-local`]: DRAFT,});});++ it("waits for persisted drafts before copying content between projects", async () => {+ const sourceKey = "new-task:environment-1:project-1";+ const targetKey = "new-task:environment-1:project-2";+ const unrelatedKey = "environment-1:thread-1";+ const source = { text: "Current task", attachments: [] } satisfies ComposerDraft;+ const target = { text: "Persisted target", attachments: [] } satisfies ComposerDraft;+ const unrelated = { text: "Keep me", attachments: [] } satisfies ComposerDraft;++ composerDraftFileMocks.setDocument({+ schemaVersion: 1,+ drafts: {+ [targetKey]: target,+ [unrelatedKey]: unrelated,+ },+ });+ composerDraftFileMocks.blockRead();+ appAtomRegistry.set(composerDraftsAtom, { [sourceKey]: source });++ const copy = copyComposerDraftContentIfEmpty(sourceKey, targetKey);+ expect(appAtomRegistry.get(composerDraftsAtom)).toEqual({ [sourceKey]: source });++ composerDraftFileMocks.releaseRead();+ await copy;++ expect(appAtomRegistry.get(composerDraftsAtom)).toEqual({+ [sourceKey]: source,+ [targetKey]: target,+ [unrelatedKey]: unrelated,+ });+ });});diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.tsindex 24fa547e2..e9f8cde3c 100644--- a/apps/mobile/src/state/use-composer-drafts.ts+++ b/apps/mobile/src/state/use-composer-drafts.ts@@ -253,7 +253,11 @@ export function ensureComposerDraftsLoaded(): void {function updateComposerDrafts(update: (current: Record<string, ComposerDraft>) => Record<string, ComposerDraft>,): void {- const next = update(appAtomRegistry.get(composerDraftsAtom));+ const current = appAtomRegistry.get(composerDraftsAtom);+ const next = update(current);+ if (next === current) {+ return;+ }appAtomRegistry.set(composerDraftsAtom, next);schedulePersistComposerDrafts(next);}@@ -412,6 +416,51 @@ export function restoreComposerDraftSnapshotState(return next;}+export function copyComposerDraftContentState(+ current: Record<string, ComposerDraft>,+ sourceDraftKey: string,+ targetDraftKey: string,+): Record<string, ComposerDraft> {+ if (sourceDraftKey === targetDraftKey) {+ return current;+ }+ const source = normalizeDraft(current[sourceDraftKey]);+ const target = normalizeDraft(current[targetDraftKey]);+ const sourceHasContent =+ source.text.length > 0 ||+ source.attachments.length > 0 ||+ (source.importedShareIds?.length ?? 0) > 0;+ const targetHasContent =+ target.text.length > 0 ||+ target.attachments.length > 0 ||+ (target.importedShareIds?.length ?? 0) > 0;+ if (!sourceHasContent || targetHasContent) {+ return current;+ }+ return {+ ...current,+ [targetDraftKey]: {+ ...target,+ text: source.text,+ attachments: source.attachments,+ ...(source.importedShareIds ? { importedShareIds: source.importedShareIds } : {}),+ },+ };+}++export async function copyComposerDraftContentIfEmpty(+ sourceDraftKey: string,+ targetDraftKey: string,+): Promise<void> {+ ensureComposerDraftsLoaded();+ if (loadPromise !== null) {+ await loadPromise;+ }+ updateComposerDrafts((current) =>+ copyComposerDraftContentState(current, sourceDraftKey, targetDraftKey),+ );+}+function mergeComposerDraftText(existing: string, incoming: string): string {if (incoming.length === 0) {return existing;diff --git a/docs/user/permission-modes.md b/docs/user/permission-modes.mdindex cb69e45b5..0648bafc8 100644--- a/docs/user/permission-modes.md+++ b/docs/user/permission-modes.md@@ -44,5 +44,4 @@ with prompting enabled and a restricted workspace while **Full access** disableslabels above describe what you get; the exact per-provider translation is internal and maychange.-Mobile offers the same four modes. It labels the first one **Approve actions** rather than-**Supervised**.+Mobile offers the same four modes with the same labels and descriptions.diff --git a/patches/@react-navigation%[email protected] b/patches/@react-navigation%[email protected]index 1ec4d9785..e92ae4975 100644--- a/patches/@react-navigation%[email protected]+++ b/patches/@react-navigation%[email protected]@@ -100,3 +100,25 @@ index 0b75c70b4e0d233ee3b5faaf9cfbc40d4f8ed494..eb174e3fde91a7783f132b3fb16b0117-//# sourceMappingURL=useHeaderConfigProps.js.map\ No newline at end of file+//# sourceMappingURL=useHeaderConfigProps.js.map+diff --git a/lib/module/views/NativeStackView.native.js b/lib/module/views/NativeStackView.native.js+index c342e90..5d3e440 100644+--- a/lib/module/views/NativeStackView.native.js++++ b/lib/module/views/NativeStackView.native.js+@@ -370,6 +370,17 @@ export function NativeStackView({+ return /*#__PURE__*/_jsx(SafeAreaProviderCompat, {+ children: /*#__PURE__*/_jsx(ScreenStack, {+ style: styles.container,++ onFinishTransitioning: () => {++ // Surface UIKit's transition-completion callback to every route of++ // this navigator. Unlike transitionEnd, this also fires when a modal++ // finishes dismissing — where the presenting screen below receives no++ // appearance callbacks — and for a gesture-driven dismissal it fires++ // before the state pop, while the modal route is still the focused++ // one, so the event must not be targeted at a single route.++ navigation.emit({++ type: 'finishTransitioning'++ });++ },+ children: state.routes.concat(state.preloadedRoutes).map((route, index) => {+ const descriptor = descriptors[route.key] ?? preloadedDescriptors[route.key];+ const isFocused = state.index === index;diff --git a/patches/[email protected] b/patches/[email protected]index 605366ff1..dc65d13b9 100644--- a/patches/[email protected]+++ b/patches/[email protected]@@ -226,7 +226,7 @@ index 5970e3e3a624b9498b8dedfc16831df03a274d0c..5ebff085788d813f1139eb6f9129fb21// appearance does not apply to the tvOS so we need to use lagacy customization#if TARGET_OS_TV-@@ -637,10 +675,384 @@ + (void)updateViewController:(UIViewController *)vc+@@ -637,10 +675,458 @@ + (void)updateViewController:(UIViewController *)vc// This assignment should be done after `navitem.titleView = ...` assignment (iOS 16.0 bug).// See: https://github.com/software-mansion/react-native-screens/issues/1570 (comments)navitem.title = config.title;@@ -391,40 +391,6 @@ index 5970e3e3a624b9498b8dedfc16831df03a274d0c..5ebff085788d813f1139eb6f9129fb21+ ]];+ [chromeHostView bringSubviewToFront:toolbarHost];+-+ void (^configureKeyboardTracking)(UITextField *) = ^(UITextField *textField) {-+ BOOL isEditing = textField.isFirstResponder;-+ keyboardAvoidConstraint.priority =-+ isEditing ? UILayoutPriorityDefaultHigh : UILayoutPriorityDefaultLow;-+ restingBottomConstraint.priority =-+ isEditing ? UILayoutPriorityDefaultLow : UILayoutPriorityDefaultHigh;-+-+ __weak NSLayoutConstraint *weakKeyboardAvoidConstraint = keyboardAvoidConstraint;-+ __weak NSLayoutConstraint *weakRestingBottomConstraint = restingBottomConstraint;-+ __weak UIView *weakChromeHostView = chromeHostView;-+ NSString *beginActionIdentifier = @"org.react-native-screens.mail-search-toolbar.keyboard-begin";-+ NSString *endActionIdentifier = @"org.react-native-screens.mail-search-toolbar.keyboard-end";-+ [textField removeActionForIdentifier:beginActionIdentifier forControlEvents:UIControlEventEditingDidBegin];-+ [textField removeActionForIdentifier:endActionIdentifier forControlEvents:UIControlEventEditingDidEnd];-+ [textField addAction:[UIAction actionWithTitle:@""-+ image:nil-+ identifier:beginActionIdentifier-+ handler:^(__kindof UIAction *_Nonnull action) {-+ weakRestingBottomConstraint.priority = UILayoutPriorityDefaultLow;-+ weakKeyboardAvoidConstraint.priority = UILayoutPriorityDefaultHigh;-+ [weakChromeHostView setNeedsLayout];-+ }]-+ forControlEvents:UIControlEventEditingDidBegin];-+ [textField addAction:[UIAction actionWithTitle:@""-+ image:nil-+ identifier:endActionIdentifier-+ handler:^(__kindof UIAction *_Nonnull action) {-+ weakKeyboardAvoidConstraint.priority = UILayoutPriorityDefaultLow;-+ weakRestingBottomConstraint.priority = UILayoutPriorityDefaultHigh;-+ [weakChromeHostView setNeedsLayout];-+ }]-+ forControlEvents:UIControlEventEditingDidEnd];-+ };-++ UIGlassEffect *glassEffect = [UIGlassEffect effectWithStyle:UIGlassEffectStyleRegular];+ glassEffect.interactive = YES;+ UIVisualEffectView *glassView = [[UIVisualEffectView alloc] initWithEffect:glassEffect];@@ -438,9 +404,13 @@ index 5970e3e3a624b9498b8dedfc16831df03a274d0c..5ebff085788d813f1139eb6f9129fb21+ mailSearchToolbarConfig[@"composeButtonId"] != nil || mailSearchToolbarConfig[@"composeMenu"] != nil;+ CGFloat glassLeadingInset = hasFilterButton ? sideButtonReserve : 0.0;+ CGFloat glassTrailingInset = hasComposeButton ? -sideButtonReserve : 0.0;++ NSLayoutConstraint *glassLeadingConstraint =++ [glassView.leadingAnchor constraintEqualToAnchor:toolbarHost.leadingAnchor constant:glassLeadingInset];++ NSLayoutConstraint *glassTrailingConstraint =++ [glassView.trailingAnchor constraintEqualToAnchor:toolbarHost.trailingAnchor constant:glassTrailingInset];+ [NSLayoutConstraint activateConstraints:@[-+ [glassView.leadingAnchor constraintEqualToAnchor:toolbarHost.leadingAnchor constant:glassLeadingInset],-+ [glassView.trailingAnchor constraintEqualToAnchor:toolbarHost.trailingAnchor constant:glassTrailingInset],++ glassLeadingConstraint,++ glassTrailingConstraint,+ [glassView.centerYAnchor constraintEqualToAnchor:toolbarHost.centerYAnchor],+ [glassView.heightAnchor constraintEqualToConstant:toolbarHeight],+ ]];@@ -490,6 +460,7 @@ index 5970e3e3a624b9498b8dedfc16831df03a274d0c..5ebff085788d813f1139eb6f9129fb21+ UISearchBar *searchBar =+ !useFallbackSearchField && navitem.searchController != nil ? navitem.searchController.searchBar : nil;+ NSString *placeholder = mailSearchToolbarConfig[@"placeholder"];++ UITextField *resolvedSearchTextField = nil;+ if (searchBar != nil) {+ if (placeholder != nil) {+ searchBar.placeholder = placeholder;@@ -506,7 +477,7 @@ index 5970e3e3a624b9498b8dedfc16831df03a274d0c..5ebff085788d813f1139eb6f9129fb21+ searchBar.searchTextField.adjustsFontForContentSizeCategory = YES;+ searchBar.searchTextField.textColor = UIColor.labelColor;+ searchBar.searchTextField.tintColor = UIColor.labelColor;-+ configureKeyboardTracking(searchBar.searchTextField);++ resolvedSearchTextField = searchBar.searchTextField;+ if (placeholder != nil) {+ searchBar.searchTextField.attributedPlaceholder =+ [[NSAttributedString alloc] initWithString:placeholder attributes:placeholderAttributes];@@ -539,7 +510,7 @@ index 5970e3e3a624b9498b8dedfc16831df03a274d0c..5ebff085788d813f1139eb6f9129fb21+ searchField.adjustsFontForContentSizeCategory = YES;+ searchField.textColor = UIColor.labelColor;+ searchField.tintColor = UIColor.labelColor;-+ configureKeyboardTracking(searchField);++ resolvedSearchTextField = searchField;+ searchField.translatesAutoresizingMaskIntoConstraints = NO;+ [glassView.contentView addSubview:searchField];+ [NSLayoutConstraint activateConstraints:@[@@ -550,8 +521,9 @@ index 5970e3e3a624b9498b8dedfc16831df03a274d0c..5ebff085788d813f1139eb6f9129fb21+ ]];+ }+++ UIButton *filterButton = nil;+ if (hasFilterButton) {-+ UIButton *filterButton = makeGlassButton(++ filterButton = makeGlassButton(+ mailSearchToolbarConfig[@"filterSystemImageName"] ?: @"line.3.horizontal.decrease",+ mailSearchToolbarConfig[@"filterButtonId"],+ mailSearchToolbarConfig[@"filterMenu"]);@@ -565,8 +537,9 @@ index 5970e3e3a624b9498b8dedfc16831df03a274d0c..5ebff085788d813f1139eb6f9129fb21+ ]];+ }+++ UIButton *composeButton = nil;+ if (hasComposeButton) {-+ UIButton *composeButton = makeGlassButton(++ composeButton = makeGlassButton(+ mailSearchToolbarConfig[@"composeSystemImageName"] ?: @"square.and.pencil",+ mailSearchToolbarConfig[@"composeButtonId"],+ mailSearchToolbarConfig[@"composeMenu"]);@@ -579,6 +552,107 @@ index 5970e3e3a624b9498b8dedfc16831df03a274d0c..5ebff085788d813f1139eb6f9129fb21+ [composeButton.heightAnchor constraintEqualToConstant:buttonSize],+ ]];+ }++++ BOOL showsSearchDismissButton =++ [mailSearchToolbarConfig[@"showsSearchDismissButton"] boolValue] && resolvedSearchTextField != nil;++ UIButton *searchDismissButton = nil;++ if (showsSearchDismissButton) {++ searchDismissButton = makeGlassButton(@"xmark", nil, nil);++ searchDismissButton.accessibilityLabel = @"Dismiss search keyboard";++ searchDismissButton.alpha = 0.0;++ searchDismissButton.hidden = YES;++ searchDismissButton.translatesAutoresizingMaskIntoConstraints = NO;++ [toolbarHost addSubview:searchDismissButton];++ [NSLayoutConstraint activateConstraints:@[++ [searchDismissButton.trailingAnchor constraintEqualToAnchor:toolbarHost.trailingAnchor],++ [searchDismissButton.centerYAnchor constraintEqualToAnchor:toolbarHost.centerYAnchor],++ [searchDismissButton.widthAnchor constraintEqualToConstant:buttonSize],++ [searchDismissButton.heightAnchor constraintEqualToConstant:buttonSize],++ ]];++ __weak UITextField *weakSearchTextField = resolvedSearchTextField;++ [searchDismissButton++ addAction:[UIAction actionWithHandler:^(__kindof UIAction *_Nonnull action) {++ [weakSearchTextField resignFirstResponder];++ }]++ forControlEvents:UIControlEventTouchUpInside];++ }++++ __weak UIButton *weakFilterButton = filterButton;++ __weak UIButton *weakComposeButton = composeButton;++ __weak UIButton *weakSearchDismissButton = searchDismissButton;++ __weak NSLayoutConstraint *weakGlassLeadingConstraint = glassLeadingConstraint;++ __weak NSLayoutConstraint *weakGlassTrailingConstraint = glassTrailingConstraint;++ __weak NSLayoutConstraint *weakKeyboardAvoidConstraint = keyboardAvoidConstraint;++ __weak NSLayoutConstraint *weakRestingBottomConstraint = restingBottomConstraint;++ __weak UIView *weakToolbarHost = toolbarHost;++ __weak UITextField *weakSearchTextField = resolvedSearchTextField;++ void (^setSearchEditingAppearance)(BOOL, BOOL) = ^(BOOL isEditing, BOOL animated) {++ weakKeyboardAvoidConstraint.priority =++ isEditing ? UILayoutPriorityDefaultHigh : UILayoutPriorityDefaultLow;++ weakRestingBottomConstraint.priority =++ isEditing ? UILayoutPriorityDefaultLow : UILayoutPriorityDefaultHigh;++++ if (showsSearchDismissButton) {++ if (isEditing) {++ weakSearchDismissButton.hidden = NO;++ } else {++ weakFilterButton.hidden = NO;++ weakComposeButton.hidden = NO;++ }++ weakGlassLeadingConstraint.constant = isEditing ? 0.0 : glassLeadingInset;++ weakGlassTrailingConstraint.constant = isEditing ? -sideButtonReserve : glassTrailingInset;++++ void (^changes)(void) = ^{++ weakFilterButton.alpha = isEditing ? 0.0 : 1.0;++ weakComposeButton.alpha = isEditing ? 0.0 : 1.0;++ weakSearchDismissButton.alpha = isEditing ? 1.0 : 0.0;++ [weakToolbarHost layoutIfNeeded];++ };++ void (^completion)(BOOL) = ^(BOOL finished) {++ if (!finished || weakSearchTextField.isFirstResponder != isEditing) {++ return;++ }++ weakFilterButton.hidden = isEditing;++ weakComposeButton.hidden = isEditing;++ weakSearchDismissButton.hidden = !isEditing;++ };++ if (animated) {++ [UIView animateWithDuration:0.2++ delay:0.0++ options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseInOut++ animations:changes++ completion:completion];++ } else {++ changes();++ completion(YES);++ }++ }++ [weakToolbarHost setNeedsLayout];++ };++++ setSearchEditingAppearance(resolvedSearchTextField.isFirstResponder, NO);++ NSString *beginActionIdentifier = @"org.react-native-screens.mail-search-toolbar.keyboard-begin";++ NSString *endActionIdentifier = @"org.react-native-screens.mail-search-toolbar.keyboard-end";++ [resolvedSearchTextField removeActionForIdentifier:beginActionIdentifier++ forControlEvents:UIControlEventEditingDidBegin];++ [resolvedSearchTextField removeActionForIdentifier:endActionIdentifier++ forControlEvents:UIControlEventEditingDidEnd];++ [resolvedSearchTextField++ addAction:[UIAction actionWithTitle:@""++ image:nil++ identifier:beginActionIdentifier++ handler:^(__kindof UIAction *_Nonnull action) {++ setSearchEditingAppearance(YES, YES);++ }]++ forControlEvents:UIControlEventEditingDidBegin];++ [resolvedSearchTextField++ addAction:[UIAction actionWithTitle:@""++ image:nil++ identifier:endActionIdentifier++ handler:^(__kindof UIAction *_Nonnull action) {++ setSearchEditingAppearance(NO, YES);++ }]++ forControlEvents:UIControlEventEditingDidEnd];+ }+#endif+ }@@ -615,7 +689,7 @@ index 5970e3e3a624b9498b8dedfc16831df03a274d0c..5ebff085788d813f1139eb6f9129fb21// Setting navigation bar visibility is split to mitigate iOS 26 bug with bar button items// (setting nav bar visibility should be done after `navitem.*BarButtonItems`).-@@ -773,6 +1185,7 @@ - (void)applySemanticContentAttributeIfNeededToNavCtrl:(UINavigationController *+@@ -773,6 +1259,7 @@ - (void)applySemanticContentAttributeIfNeededToNavCtrl:(UINavigationController *- (NSArray<UIBarButtonItem *> *)barButtonItemsFromConfigs:(NSArray<NSDictionary<NSString *, id> *> *)dictswithCurrentItems:(NSArray<UIBarButtonItem *> *)currentItems@@ -623,7 +697,7 @@ index 5970e3e3a624b9498b8dedfc16831df03a274d0c..5ebff085788d813f1139eb6f9129fb21{if (dicts.count == 0) {return currentItems;-@@ -781,7 +1194,197 @@ - (void)applySemanticContentAttributeIfNeededToNavCtrl:(UINavigationController *+@@ -781,7 +1268,197 @@ - (void)applySemanticContentAttributeIfNeededToNavCtrl:(UINavigationController *[items addObjectsFromArray:currentItems];for (NSUInteger i = 0; i < dicts.count; i++) {NSDictionary *dict = dicts[i];@@ -822,7 +896,7 @@ index 5970e3e3a624b9498b8dedfc16831df03a274d0c..5ebff085788d813f1139eb6f9129fb21RNSBarButtonItem *item = [[RNSBarButtonItem alloc] initWithConfig:dictaction:^(NSString *buttonId) {auto eventEmitter = std::static_pointer_cast<const facebook::react::RNSScreenStackHeaderConfigEventEmitter>(-@@ -803,19 +1406,23 @@ - (void)applySemanticContentAttributeIfNeededToNavCtrl:(UINavigationController *+@@ -803,19 +1480,23 @@ - (void)applySemanticContentAttributeIfNeededToNavCtrl:(UINavigationController *}imageLoader:_imageLoader];NSNumber *index = dict[@"index"];@@ -852,7 +926,7 @@ index 5970e3e3a624b9498b8dedfc16831df03a274d0c..5ebff085788d813f1139eb6f9129fb21[items insertObject:item atIndex:index.integerValue];} else {[items addObject:item];-@@ -825,6 +1432,47 @@ - (void)applySemanticContentAttributeIfNeededToNavCtrl:(UINavigationController *+@@ -825,6 +1506,47 @@ - (void)applySemanticContentAttributeIfNeededToNavCtrl:(UINavigationController *return items;}@@ -900,7 +974,7 @@ index 5970e3e3a624b9498b8dedfc16831df03a274d0c..5ebff085788d813f1139eb6f9129fb21RNS_IGNORE_SUPER_CALL_BEGIN- (void)insertReactSubview:(RNSScreenStackHeaderSubview *)subview atIndex:(NSInteger)atIndex{-@@ -1013,6 +1661,8 @@ - (void)updateProps:(react::Props::Shared const &)props oldProps:(react::Props::+@@ -1013,6 +1735,8 @@ - (void)updateProps:(react::Props::Shared const &)props oldProps:(react::Props::}_title = RCTNSStringFromStringNilIfEmpty(newScreenProps.title);@@ -909,7 +983,7 @@ index 5970e3e3a624b9498b8dedfc16831df03a274d0c..5ebff085788d813f1139eb6f9129fb21if (newScreenProps.titleFontFamily != oldScreenProps.titleFontFamily) {_titleFontFamily = RCTNSStringFromStringNilIfEmpty(newScreenProps.titleFontFamily);}-@@ -1038,6 +1688,7 @@ - (void)updateProps:(react::Props::Shared const &)props oldProps:(react::Props::+@@ -1038,6 +1762,7 @@ - (void)updateProps:(react::Props::Shared const &)props oldProps:(react::Props::_disableBackButtonMenu = newScreenProps.disableBackButtonMenu;_backButtonDisplayMode =[RNSConvert UINavigationItemBackButtonDisplayModeFromCppEquivalent:newScreenProps.backButtonDisplayMode];@@ -917,7 +991,7 @@ index 5970e3e3a624b9498b8dedfc16831df03a274d0c..5ebff085788d813f1139eb6f9129fb21if (newScreenProps.userInterfaceStyle != oldScreenProps.userInterfaceStyle) {_userInterfaceStyle = [RNSConvert UIUserInterfaceStyleFromCppEquivalent:newScreenProps.userInterfaceStyle];-@@ -1084,6 +1735,30 @@ - (void)updateProps:(react::Props::Shared const &)props oldProps:(react::Props::+@@ -1084,6 +1809,30 @@ - (void)updateProps:(react::Props::Shared const &)props oldProps:(react::Props::_headerRightBarButtonItems = array;}@@ -1313,7 +1387,7 @@ index 3b384e03891e38e936f370372a682d73440e7ec2..861ffed850e90f27916c427853b503db/*** The tint color to apply to the item.*-@@ -1145,8 +1193,37 @@ export interface HeaderBarButtonItemWithMenu extends SharedHeaderBarButtonItem {+@@ -1145,8 +1193,38 @@ export interface HeaderBarButtonItemWithMenu extends SharedHeaderBarButtonItem {export interface HeaderBarButtonItemSpacing {type: 'spacing';spacing: number;@@ -1344,6 +1418,7 @@ index 3b384e03891e38e936f370372a682d73440e7ec2..861ffed850e90f27916c427853b503db+ onSearchTextChange?: ((text: string) => void) | undefined;+ placeholder?: string | undefined;+ searchTextChangeId?: string | undefined;++ showsSearchDismissButton?: boolean | undefined;+ useFallbackSearchField?: boolean | undefined;+ width?: number | undefined;}@@ -1653,7 +1728,7 @@ index 76a83f3acb6fd3f0af7f027798848b7124100286..9e4499f076f9988e3266df4be7201e13/*** The tint color to apply to the item.*-@@ -1279,11 +1327,46 @@ export interface HeaderBarButtonItemWithMenu extends SharedHeaderBarButtonItem {+@@ -1279,11 +1327,47 @@ export interface HeaderBarButtonItemWithMenu extends SharedHeaderBarButtonItem {export interface HeaderBarButtonItemSpacing {type: 'spacing';spacing: number;@@ -1687,6 +1762,7 @@ index 76a83f3acb6fd3f0af7f027798848b7124100286..9e4499f076f9988e3266df4be7201e13+ onSearchTextChange?: ((text: string) => void) | undefined;+ placeholder?: string | undefined;+ searchTextChangeId?: string | undefined;++ showsSearchDismissButton?: boolean | undefined;+ useFallbackSearchField?: boolean | undefined;+ width?: number | undefined;}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 9abd0dc45..7eab1715c 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -80,13 +80,13 @@ patchedDependencies:'@pierre/[email protected]': 7ef7cb0cbabb17c15cdb137554068b36f15f6f5265e73fb51452aa3380db91aa'@react-native-menu/[email protected]': c7f66d121c726ade4f5c4e1aed11a691e5711d244c544084e289ac26132a0045'@react-native/[email protected]': c1b594a16e682d621b6a960926f8ce13fc92edfb397884cfe7fcb0518996a784- '@react-navigation/[email protected]': c7fc101b78d434904425e5a24c22fb0042298dec6f807250486e784f3c717273+ '@react-navigation/[email protected]': 0365b727005b3a830af80ccbd0b637666cc0338d33ddcb7a25b6de51a21ea027[email protected]: af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6[email protected]: 9170f8074ae4e35a0a086e756c8f815794fd3abe51eac67ca3ba02804225ec1f[email protected]: 808eb26f9e57cf4945efd3985af4d9c764da6f91f4c9764433cc868602bbf4d3[email protected]: 20be72c84d74253acdcfefbc6defe36dc396944f1a44cab2bdd0e3cd572ae008[email protected]: 825622aae63a8fb5b904f3c77908a0e216261d727ea171709f2c0b6088422675- [email protected]: 25ba61e9bbb54a203ff374b9ca8ce6761ea4970742c748e1bcf8d2500bf3f92e+ [email protected]: 59bfd7b84af01708b6e581c4ccdd5ecf05f8b205383802d66b64ed7ea7bb2199importers:@@ -237,7 +237,7 @@ importers:version: 7.3.4([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])'@react-navigation/native-stack':specifier: 7.17.6- version: 7.17.6(patch_hash=c7fc101b78d434904425e5a24c22fb0042298dec6f807250486e784f3c717273)(0f4ac5b153e229af40627cf59223263d)+ version: 7.17.6(patch_hash=0365b727005b3a830af80ccbd0b637666cc0338d33ddcb7a25b6de51a21ea027)(7ffd26361d0ffb9781446d1519df37be)'@shikijs/core':specifier: 4.2.0version: 4.2.0@@ -402,7 +402,7 @@ importers:version: 5.7.0([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])react-native-screens:specifier: 4.25.2- version: 4.25.2(patch_hash=25ba61e9bbb54a203ff374b9ca8ce6761ea4970742c748e1bcf8d2500bf3f92e)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ version: 4.25.2(patch_hash=59bfd7b84af01708b6e581c4ccdd5ecf05f8b205383802d66b64ed7ea7bb2199)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])react-native-shiki-engine:specifier: ^0.3.12version: 0.3.12([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])@@ -12275,7 +12275,7 @@ snapshots:ws: 8.21.0([email protected])([email protected])zod: 3.25.76optionalDependencies:- expo-router: 56.2.11(c60e26523d4e8ab19ca3d2f562bb6cb8)+ expo-router: 56.2.11(e1497a99e5bc5be76c1cdb733671f865)react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- '@expo/dom-webview'@@ -12351,7 +12351,7 @@ snapshots:ws: 8.21.0([email protected])([email protected])zod: 3.25.76optionalDependencies:- expo-router: 56.2.11(db5c693a26481047569df6781f34db9f)+ expo-router: 56.2.11(80beea6a31a5d2003a696c1401258797)react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- '@expo/dom-webview'@@ -12691,7 +12691,7 @@ snapshots:react: 19.2.3optionalDependencies:'@expo/metro-runtime': 56.0.15(@expo/[email protected])([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])- expo-router: 56.2.11(c60e26523d4e8ab19ca3d2f562bb6cb8)+ expo-router: 56.2.11(e1497a99e5bc5be76c1cdb733671f865)react-dom: 19.2.3([email protected])transitivePeerDependencies:- supports-color@@ -12706,7 +12706,7 @@ snapshots:react: 19.2.6optionalDependencies:'@expo/metro-runtime': 56.0.15(@expo/[email protected])([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])- expo-router: 56.2.11(db5c693a26481047569df6781f34db9f)+ expo-router: 56.2.11(80beea6a31a5d2003a696c1401258797)react-dom: 19.2.6([email protected])transitivePeerDependencies:- supports-color@@ -14291,7 +14291,7 @@ snapshots:optionalDependencies:'@react-native-masked-view/masked-view': 0.3.2([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])- '@react-navigation/[email protected](patch_hash=c7fc101b78d434904425e5a24c22fb0042298dec6f807250486e784f3c717273)(0f4ac5b153e229af40627cf59223263d)':+ '@react-navigation/[email protected](patch_hash=0365b727005b3a830af80ccbd0b637666cc0338d33ddcb7a25b6de51a21ea027)(7ffd26361d0ffb9781446d1519df37be)':dependencies:'@react-navigation/elements': 2.9.26(c6a2ad0e2c930f8e3896e77c3ba11bc4)'@react-navigation/native': 7.3.4([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])@@ -14299,7 +14299,7 @@ snapshots:react: 19.2.3react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])react-native-safe-area-context: 5.7.0([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])- react-native-screens: 4.25.2(patch_hash=25ba61e9bbb54a203ff374b9ca8ce6761ea4970742c748e1bcf8d2500bf3f92e)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ react-native-screens: 4.25.2(patch_hash=59bfd7b84af01708b6e581c4ccdd5ecf05f8b205383802d66b64ed7ea7bb2199)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])sf-symbols-typescript: 2.2.0warn-once: 0.1.1transitivePeerDependencies:@@ -17080,47 +17080,47 @@ snapshots:- supports-color- typescript- [email protected](c60e26523d4e8ab19ca3d2f562bb6cb8):+ [email protected](80beea6a31a5d2003a696c1401258797):dependencies:- '@expo/log-box': 56.0.13(@expo/[email protected])([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])- '@expo/metro-runtime': 56.0.15(@expo/[email protected])([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ '@expo/log-box': 56.0.13(@expo/[email protected])([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ '@expo/metro-runtime': 56.0.15(@expo/[email protected])([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])'@expo/schema-utils': 56.0.1- '@expo/ui': 56.0.18(3cdc0dde9f93166d952f1e1bd0cb25c0)- '@radix-ui/react-slot': 1.2.4(@types/[email protected])([email protected])- '@radix-ui/react-tabs': 1.1.13(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@react-native-masked-view/masked-view': 0.3.2([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ '@expo/ui': 56.0.18(32843e0c0883df8bccfa0b8323659df5)+ '@radix-ui/react-slot': 1.2.4(@types/[email protected])([email protected])+ '@radix-ui/react-tabs': 1.1.13(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ '@react-native-masked-view/masked-view': 0.3.2([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])'@testing-library/jest-dom': 6.9.1'@testing-library/user-event': 14.6.1(@testing-library/[email protected])client-only: 0.0.1color: 4.2.3debug: 4.4.3escape-string-regexp: 4.0.0- expo: 56.0.12(8895228379997a2a064f9644cda56ed0)- expo-constants: 56.0.18([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))- expo-glass-effect: 56.0.4([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])- expo-linking: 56.0.14([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ expo: 56.0.12(deb8cbf3e0f411b34ba85a995c9982ba)+ expo-constants: 56.0.18([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))+ expo-glass-effect: 56.0.4([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ expo-linking: 56.0.14([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])expo-server: 56.0.5- expo-symbols: 56.0.6([email protected])([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ expo-symbols: 56.0.6([email protected])([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])fast-deep-equal: 3.1.3invariant: 2.2.4nanoid: 3.3.12query-string: 7.1.3- react: 19.2.3+ react: 19.2.6react-fast-compare: 3.2.2react-is: 19.2.7- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])- react-native-drawer-layout: 4.2.4(05364bd849de538917a7364cc7dee3f5)- react-native-safe-area-context: 5.7.0([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])- react-native-screens: 4.25.2(patch_hash=25ba61e9bbb54a203ff374b9ca8ce6761ea4970742c748e1bcf8d2500bf3f92e)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])+ react-native-drawer-layout: 4.2.4(de9b2f2dc96a3557fdc0df187a8417ee)+ react-native-safe-area-context: 5.7.0([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ react-native-screens: 4.25.2(patch_hash=59bfd7b84af01708b6e581c4ccdd5ecf05f8b205383802d66b64ed7ea7bb2199)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])server-only: 0.0.1sf-symbols-typescript: 2.2.0shallowequal: 1.1.0standard-navigation: 0.0.5- vaul: 1.1.2(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ vaul: 1.1.2(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])optionalDependencies:- react-dom: 19.2.3([email protected])- react-native-gesture-handler: 2.31.2(patch_hash=808eb26f9e57cf4945efd3985af4d9c764da6f91f4c9764433cc868602bbf4d3)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])- react-native-reanimated: 4.3.1([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ react-dom: 19.2.6([email protected])+ react-native-gesture-handler: 2.31.2(patch_hash=808eb26f9e57cf4945efd3985af4d9c764da6f91f4c9764433cc868602bbf4d3)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ react-native-reanimated: 4.3.1([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])transitivePeerDependencies:- '@babel/core'- '@testing-library/dom'@@ -17131,47 +17131,47 @@ snapshots:- supports-coloroptional: true- [email protected](db5c693a26481047569df6781f34db9f):+ [email protected](e1497a99e5bc5be76c1cdb733671f865):dependencies:- '@expo/log-box': 56.0.13(@expo/[email protected])([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])- '@expo/metro-runtime': 56.0.15(@expo/[email protected])([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ '@expo/log-box': 56.0.13(@expo/[email protected])([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ '@expo/metro-runtime': 56.0.15(@expo/[email protected])([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])'@expo/schema-utils': 56.0.1- '@expo/ui': 56.0.18(32843e0c0883df8bccfa0b8323659df5)- '@radix-ui/react-slot': 1.2.4(@types/[email protected])([email protected])- '@radix-ui/react-tabs': 1.1.13(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@react-native-masked-view/masked-view': 0.3.2([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ '@expo/ui': 56.0.18(3cdc0dde9f93166d952f1e1bd0cb25c0)+ '@radix-ui/react-slot': 1.2.4(@types/[email protected])([email protected])+ '@radix-ui/react-tabs': 1.1.13(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ '@react-native-masked-view/masked-view': 0.3.2([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])'@testing-library/jest-dom': 6.9.1'@testing-library/user-event': 14.6.1(@testing-library/[email protected])client-only: 0.0.1color: 4.2.3debug: 4.4.3escape-string-regexp: 4.0.0- expo: 56.0.12(deb8cbf3e0f411b34ba85a995c9982ba)- expo-constants: 56.0.18([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))- expo-glass-effect: 56.0.4([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])- expo-linking: 56.0.14([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ expo: 56.0.12(8895228379997a2a064f9644cda56ed0)+ expo-constants: 56.0.18([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))+ expo-glass-effect: 56.0.4([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ expo-linking: 56.0.14([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])expo-server: 56.0.5- expo-symbols: 56.0.6([email protected])([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ expo-symbols: 56.0.6([email protected])([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])fast-deep-equal: 3.1.3invariant: 2.2.4nanoid: 3.3.12query-string: 7.1.3- react: 19.2.6+ react: 19.2.3react-fast-compare: 3.2.2react-is: 19.2.7- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])- react-native-drawer-layout: 4.2.4(de9b2f2dc96a3557fdc0df187a8417ee)- react-native-safe-area-context: 5.7.0([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])- react-native-screens: 4.25.2(patch_hash=25ba61e9bbb54a203ff374b9ca8ce6761ea4970742c748e1bcf8d2500bf3f92e)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])+ react-native-drawer-layout: 4.2.4(05364bd849de538917a7364cc7dee3f5)+ react-native-safe-area-context: 5.7.0([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ react-native-screens: 4.25.2(patch_hash=59bfd7b84af01708b6e581c4ccdd5ecf05f8b205383802d66b64ed7ea7bb2199)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])server-only: 0.0.1sf-symbols-typescript: 2.2.0shallowequal: 1.1.0standard-navigation: 0.0.5- vaul: 1.1.2(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ vaul: 1.1.2(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])optionalDependencies:- react-dom: 19.2.6([email protected])- react-native-gesture-handler: 2.31.2(patch_hash=808eb26f9e57cf4945efd3985af4d9c764da6f91f4c9764433cc868602bbf4d3)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])- react-native-reanimated: 4.3.1([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ react-dom: 19.2.3([email protected])+ react-native-gesture-handler: 2.31.2(patch_hash=808eb26f9e57cf4945efd3985af4d9c764da6f91f4c9764433cc868602bbf4d3)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])+ react-native-reanimated: 4.3.1([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])transitivePeerDependencies:- '@babel/core'- '@testing-library/dom'@@ -19977,14 +19977,14 @@ snapshots:react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])optional: true- [email protected](patch_hash=25ba61e9bbb54a203ff374b9ca8ce6761ea4970742c748e1bcf8d2500bf3f92e)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]):+ [email protected](patch_hash=59bfd7b84af01708b6e581c4ccdd5ecf05f8b205383802d66b64ed7ea7bb2199)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]):dependencies:react: 19.2.3react-freeze: 1.0.4([email protected])react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])warn-once: 0.1.1- [email protected](patch_hash=25ba61e9bbb54a203ff374b9ca8ce6761ea4970742c748e1bcf8d2500bf3f92e)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]):+ [email protected](patch_hash=59bfd7b84af01708b6e581c4ccdd5ecf05f8b205383802d66b64ed7ea7bb2199)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]):dependencies:react: 19.2.6react-freeze: 1.0.4([email protected])