TypeScript
feat(mobile): make Settings easier to navigate and scope (#12272)
Julius Marmingec25c3e0ee678
diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsxindex 71efbb11cff..c750e366c1d 100644--- a/apps/mobile/src/Stack.tsx+++ b/apps/mobile/src/Stack.tsx@@ -59,6 +59,12 @@ import { SettingsClientStorageRouteScreen } from "./features/settings/SettingsClimport { SettingsDiagnosticsRouteScreen } from "./features/diagnostics/SettingsDiagnosticsRouteScreen";import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen";import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";+import {+ SettingsEnvironmentAgentBehaviorRouteScreen,+ SettingsEnvironmentMaintenanceRouteScreen,+ SettingsEnvironmentNewThreadsRouteScreen,+ SettingsEnvironmentSourceControlRouteScreen,+} from "./features/settings/SettingsServerControlsRouteScreen";import { SettingsKeyboardRouteScreen } from "./features/settings/SettingsKeyboardRouteScreen";import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";import {@@ -66,9 +72,14 @@ import {SettingsOpenSourceLicensesRouteScreen,} from "./features/settings/SettingsOpenSourceLicensesRouteScreen";import { SettingsProjectGroupingRouteScreen } from "./features/settings/SettingsProjectGroupingRouteScreen";+import { SettingsProjectOverviewRouteScreen } from "./features/settings/SettingsProjectOverviewRouteScreen";import { UsageLimitAccountScreen } from "./features/usage/UsageLimitsPooled";import { UsageRouteScreen } from "./features/usage/UsageRouteScreen";+import { SettingsAboutRouteScreen } from "./features/settings/SettingsAboutRouteScreen";+import { SettingsNotificationsRouteScreen } from "./features/settings/SettingsNotificationsRouteScreen";import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";+import { SettingsThreadsRouteScreen } from "./features/settings/SettingsThreadsRouteScreen";+import { SettingsEnvironmentFilterProvider } from "./features/settings/settings-environment-filter";import { ShowcaseCaptureCoordinator } from "./features/showcase/ShowcaseCaptureCoordinator";import {SettingsLegalDocumentCloseHeaderButton,@@ -168,6 +179,41 @@ const SettingsContentStack = createNativeStackNavigator({title: "Environments",},}),+ SettingsEnvironmentNewThreads: createNativeStackScreen({+ screen: SettingsEnvironmentNewThreadsRouteScreen,+ linking: "new-threads",+ options: { title: "New threads" },+ }),+ SettingsEnvironmentSourceControl: createNativeStackScreen({+ screen: SettingsEnvironmentSourceControlRouteScreen,+ linking: "source-control",+ options: { title: "Source control" },+ }),+ SettingsEnvironmentAgentBehavior: createNativeStackScreen({+ screen: SettingsEnvironmentAgentBehaviorRouteScreen,+ linking: "agent-behavior",+ options: { title: "Agent behavior" },+ }),+ SettingsEnvironmentMaintenance: createNativeStackScreen({+ screen: SettingsEnvironmentMaintenanceRouteScreen,+ linking: "maintenance",+ options: { title: "Maintenance" },+ }),+ SettingsNotifications: createNativeStackScreen({+ screen: SettingsNotificationsRouteScreen,+ linking: "notifications",+ options: { title: "Notifications" },+ }),+ SettingsThreads: createNativeStackScreen({+ screen: SettingsThreadsRouteScreen,+ linking: "thread-preferences",+ options: { title: "Thread behavior" },+ }),+ SettingsAbout: createNativeStackScreen({+ screen: SettingsAboutRouteScreen,+ linking: "about",+ options: { title: "About T3 Code" },+ }),SettingsEnvironmentNew: createNativeStackScreen({screen: ConnectionsNewRouteScreen,linking: "environment-new",@@ -193,9 +239,21 @@ const SettingsContentStack = createNativeStackNavigator({screen: SettingsProjectGroupingRouteScreen,linking: "project-grouping",options: {- title: "Project Grouping",+ title: "Organization",},}),+ SettingsOrganization: createNativeStackScreen({+ screen: SettingsProjectGroupingRouteScreen,+ linking: "organization",+ options: {+ title: "Organization",+ },+ }),+ SettingsProjectOverview: createNativeStackScreen({+ screen: SettingsProjectOverviewRouteScreen,+ linking: "project",+ options: { title: "Project overview" },+ }),SettingsKeyboard: createNativeStackScreen({screen: SettingsKeyboardRouteScreen,linking: "keyboard",@@ -257,6 +315,9 @@ const SettingsSheetStack = createNativeStackNavigator({SettingsContent: createNativeStackScreen({screen: SettingsContentStack,linking: "",+ layout: ({ children }) => (+ <SettingsEnvironmentFilterProvider>{children}</SettingsEnvironmentFilterProvider>+ ),}),SettingsAuth: createNativeStackScreen({screen: SettingsAuthRouteScreen,@@ -632,7 +693,7 @@ export const RootStack = createNativeStackNavigator({? { presentation: "card" as const }: {...FORM_SHEET_PRESENTATION_OPTIONS,- sheetAllowedDetents: [0.7, 0.92],+ sheetAllowedDetents: [0.92],sheetGrabberVisible: true,}),},diff --git a/apps/mobile/src/features/settings/SettingsAboutRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsAboutRouteScreen.tsxnew file mode 100644index 00000000000..bbb70b236be--- /dev/null+++ b/apps/mobile/src/features/settings/SettingsAboutRouteScreen.tsx@@ -0,0 +1,149 @@+import { ScreenScrollView as ScrollView } from "../../components/ScreenScrollView";+import Constants from "expo-constants";+import { useCallback, useEffect, useRef, useState } from "react";+import { Alert, Pressable, View } from "react-native";+import { useSafeAreaInsets } from "react-native-safe-area-context";++import { AppText as Text } from "../../components/AppText";+import { SymbolView } from "../../components/AppSymbol";+import {+ type AppUpdateCheckState,+ isAppUpdateCheckAvailable,+ registerHiddenUpdateTap,+ runAppUpdateCheck,+} from "../updates/app-updates";+import { SettingsRow } from "./components/SettingsRow";+import { SettingsSection } from "./components/SettingsSection";+import { SettingsScreen } from "./components/SettingsScreen";++export function SettingsAboutRouteScreen() {+ const insets = useSafeAreaInsets();++ return (+ <SettingsScreen title="About T3 Code">+ <ScrollView+ contentInsetAdjustmentBehavior="automatic"+ showsVerticalScrollIndicator={false}+ className="flex-1"+ contentContainerClassName="gap-6 px-5 pt-4"+ contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}+ >+ <AppSettingsSection />+ </ScrollView>+ </SettingsScreen>+ );+}++function AppSettingsSection() {+ const [updateState, setUpdateState] = useState<AppUpdateCheckState>("idle");+ const updateInFlight = useRef(false);+ const hiddenUpdateTapCount = useRef(0);++ const version = Constants.expoConfig?.version ?? "0.0.0";+ // Fall back to "production" to match resolveAppVariant in app.config.ts, so a+ // missing variant never mislabels a production build as development.+ const variant = (Constants.expoConfig?.extra?.appVariant as string | undefined) ?? "production";+ const variantLabel = variant === "production" ? "" : capitalize(variant);+ const versionLabel = variantLabel ? `${version} · ${variantLabel}` : version;+ const updateCheckAvailable = isAppUpdateCheckAvailable();+ const busy =+ updateState === "checking" || updateState === "downloading" || updateState === "restarting";++ // "Up to date" is a transient acknowledgement, not a state worth persisting —+ // return the version row to its normal, deliberately quiet state.+ useEffect(() => {+ if (updateState !== "current") return;+ const timer = setTimeout(() => setUpdateState("idle"), 3000);+ return () => clearTimeout(timer);+ }, [updateState]);++ const checkForUpdate = useCallback(async () => {+ // `disabled={busy}` only takes effect on the next render, so two taps in the+ // same frame would both get through. The ref closes that window.+ if (updateInFlight.current) return;+ updateInFlight.current = true;+ try {+ // The user asked for this restart by tapping the version row, so it may+ // apply immediately instead of prompting.+ await runAppUpdateCheck({+ applyMode: "immediate",+ onFailure: (message) => Alert.alert("Update failed", message),+ onStateChange: setUpdateState,+ });+ } finally {+ updateInFlight.current = false;+ }+ }, []);++ const handleVersionPress = useCallback(() => {+ if (!updateCheckAvailable || updateInFlight.current) return;+ const tap = registerHiddenUpdateTap(hiddenUpdateTapCount.current);+ hiddenUpdateTapCount.current = tap.nextCount;+ if (tap.shouldCheck) {+ void checkForUpdate();+ }+ }, [checkForUpdate, updateCheckAvailable]);++ const statusLabel =+ updateState === "checking"+ ? "Checking…"+ : updateState === "downloading"+ ? "Downloading…"+ : // "ready" appears only when this check joined an in-flight background-mode+ // check; that download installs at the next backgrounding.+ updateState === "ready"+ ? "Update ready"+ : updateState === "restarting"+ ? "Restarting…"+ : updateState === "current"+ ? "Up to date"+ : null;++ const versionRow = (+ <View className="flex-row items-center gap-4 p-4">+ <SymbolView+ name="info.circle"+ size={22}+ tintColorClassName="accent-icon"+ type="monochrome"+ weight="regular"+ />+ <Text className="flex-1 text-lg text-foreground">Version</Text>+ <View className="items-end">+ <Text className="text-lg text-foreground-muted">{versionLabel}</Text>+ {statusLabel ? (+ <Text className="text-xs text-foreground-muted/70">{statusLabel}</Text>+ ) : null}+ </View>+ </View>+ );++ return (+ <SettingsSection title="App">+ <SettingsRow icon="internaldrive" label="Client Storage" target="SettingsClientStorage" />+ <SettingsRow icon="stethoscope" label="Diagnostics" target="SettingsDiagnostics" />+ <SettingsRow+ icon="doc.on.doc"+ label="Open source licenses"+ target="SettingsOpenSourceLicenses"+ />+ <SettingsRow icon="doc.text" label="Legal" fullScreenTarget="SettingsLegal" />+ {updateCheckAvailable ? (+ <Pressable+ accessibilityLabel={`Version ${versionLabel}`}+ accessibilityRole="text"+ disabled={busy}+ onPress={handleVersionPress}+ >+ {versionRow}+ </Pressable>+ ) : (+ versionRow+ )}+ </SettingsSection>+ );+}++function capitalize(value: string): string {+ return value.length > 0 ? value.charAt(0).toUpperCase() + value.slice(1) : value;+}diff --git a/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsxnew file mode 100644index 00000000000..8809c429c82--- /dev/null+++ b/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx@@ -0,0 +1,499 @@+import { ScreenScrollView as ScrollView } from "../../components/ScreenScrollView";+import { useAuth } from "@clerk/expo";+import { useAtomSet, useAtomValue } from "@effect/atom-react";+import * as Notifications from "expo-notifications";+import { useNavigation } from "@react-navigation/native";+import * as Effect from "effect/Effect";+import { AsyncResult } from "effect/unstable/reactivity";+import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";+import { Alert, AppState, Linking, Platform } from "react-native";+import { useSafeAreaInsets } from "react-native-safe-area-context";++import { AppText as Text } from "../../components/AppText";+import {+ isAtomCommandInterrupted,+ reportAtomCommandResult,+ settleAsyncResult,+ settlePromise,+ squashAtomCommandFailure,+} from "@t3tools/client-runtime/state/runtime";+import { supportsAgentAwarenessPush } from "../agent-awareness/capabilities";+import {+ openAndroidLiveUpdateSettings,+ supportsAndroidLiveUpdateSettings,+} from "../agent-awareness/androidNotifications";+import { setLiveActivityUpdatesEnabled } from "../agent-awareness/liveActivityPreferences";+import { requestAgentNotificationPermission } from "../agent-awareness/notificationPermissions";+import {+ getAgentAwarenessRegistrationStatus,+ refreshAgentAwarenessRegistration,+ subscribeAgentAwarenessRegistrationStatus,+} from "../agent-awareness/remoteRegistration";+import { refreshManagedRelayEnvironments } from "../cloud/managedRelayState";+import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/publicConfig";+import { runtime } from "../../lib/runtime";+import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";+import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";+import { SettingsRow } from "./components/SettingsRow";+import { SettingsSection } from "./components/SettingsSection";+import { SettingsSwitchRow } from "./components/SettingsSwitchRow";+import { SettingsScreen } from "./components/SettingsScreen";+import { resolveAgentAwarenessPlatformPresentation } from "./SettingsRouteScreen.logic";++type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";+type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";++// Reflects whether the relay actually accepted this device's registration.+// The notification and Live Activity switches are gated on this so they can+// never read as enabled when the device cannot receive anything (e.g. the+// registration request timed out).+function useDeviceRegistered(): boolean {+ const status = useSyncExternalStore(+ subscribeAgentAwarenessRegistrationStatus,+ getAgentAwarenessRegistrationStatus,+ () => "unknown" as const,+ );+ return status === "registered";+}++export function SettingsNotificationsRouteScreen() {+ if (!hasCloudPublicConfig()) {+ return (+ <SettingsScreen title="Notifications">+ <ScrollView+ contentInsetAdjustmentBehavior="automatic"+ contentContainerClassName="px-5 pt-4"+ >+ <Text className="text-base text-foreground-muted">+ Notifications require T3 Connect in this app build.+ </Text>+ </ScrollView>+ </SettingsScreen>+ );+ }++ return <ConfiguredSettingsNotificationsRouteScreen />;+}++function ConfiguredSettingsNotificationsRouteScreen() {+ const preferencesResult = useAtomValue(mobilePreferencesAtom);+ const savePreferences = useAtomSet(updateMobilePreferencesAtom);+ const agentAwarenessPushAvailable = supportsAgentAwarenessPush();+ const agentAwarenessPlatform = resolveAgentAwarenessPlatformPresentation(Platform.OS);+ const agentAwarenessSubtitle =+ Platform.OS === "android" && !agentAwarenessPushAvailable+ ? "Install a newer app build to enable notifications"+ : agentAwarenessPlatform.subtitle;+ const insets = useSafeAreaInsets();+ const navigation = useNavigation();+ const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });+ const { savedConnectionsById } = useSavedRemoteConnections();+ const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");+ const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");+ const liveActivityWriteInFlight = useRef(false);+ const deviceRegistered = useDeviceRegistered();+ const liveActivitiesPreferenceEnabled = AsyncResult.isSuccess(preferencesResult)+ ? preferencesResult.value.liveActivitiesEnabled !== false+ : true;+ const canClearLiveActivitiesPreference =+ AsyncResult.isSuccess(preferencesResult) &&+ preferencesResult.value.liveActivitiesEnabled !== false;++ const connections = useMemo(() => Object.values(savedConnectionsById), [savedConnectionsById]);+ const environmentCount = connections.length;++ const refreshNotifications = useCallback(async () => {+ if (Platform.OS !== "ios" && Platform.OS !== "android") {+ setNotificationStatus("unsupported");+ return;+ }+ const result = await settlePromise(() => Notifications.getPermissionsAsync());+ if (result._tag === "Failure") {+ reportAtomCommandResult(result, { label: "notification permission refresh" });+ setNotificationStatus("disabled");+ return;+ }+ setNotificationStatus(result.value.granted ? "enabled" : "disabled");+ }, []);++ useEffect(() => {+ void refreshNotifications();+ const subscription = AppState.addEventListener("change", (state) => {+ if (state === "active") void refreshNotifications();+ });+ return () => subscription.remove();+ }, [refreshNotifications]);++ useEffect(() => {+ if (!isLoaded) {+ setLiveActivityStatus("checking");+ return;+ }+ if (!isSignedIn) {+ setLiveActivityStatus("signed-out");+ return;+ }+ if (!AsyncResult.isSuccess(preferencesResult)) {+ if (AsyncResult.isFailure(preferencesResult)) {+ reportAtomCommandResult(preferencesResult, { label: "live activity preference load" });+ setLiveActivityStatus("enabled");+ } else {+ setLiveActivityStatus("checking");+ }+ return;+ }+ setLiveActivityStatus(+ preferencesResult.value.liveActivitiesEnabled === false ? "disabled" : "enabled",+ );+ }, [isLoaded, isSignedIn, preferencesResult]);++ const requestNotifications = useCallback(async () => {+ const result = await settleAsyncResult(() =>+ runtime.runPromiseExit(+ requestAgentNotificationPermission.pipe(+ Effect.tap((permission) =>+ permission.type === "granted" ? refreshAgentAwarenessRegistration() : Effect.void,+ ),+ ),+ ),+ );+ if (result._tag === "Failure") {+ if (!isAtomCommandInterrupted(result)) {+ const error = squashAtomCommandFailure(result);+ Alert.alert(+ "Notifications unavailable",+ error instanceof Error ? error.message : "Could not request notification permission.",+ );+ }+ return;+ }+ if (result.value.type === "granted") {+ setNotificationStatus("enabled");+ // Permission alone is not enough: the switch stays off until the relay+ // registration succeeds, so tell the user the truth about which happened.+ if (getAgentAwarenessRegistrationStatus() === "registered") {+ Alert.alert("Notifications enabled", "Agent notifications are enabled for this device.");+ } else {+ Alert.alert(+ "Couldn't finish enabling notifications",+ "Notification access was granted, but this device could not be registered with T3 Connect. Notifications will start once registration succeeds.",+ );+ }+ return;+ }+ if (result.value.type === "unsupported") {+ setNotificationStatus("unsupported");+ Alert.alert(+ "Notifications unavailable",+ "Agent notifications are unavailable on this platform.",+ );+ return;+ }+ setNotificationStatus("disabled");+ if (result.value.canAskAgain) {+ Alert.alert("Notifications disabled", "Notifications were not enabled.");+ return;+ }+ Alert.alert(+ "Notifications disabled",+ "Notifications were denied for this app. Open Settings to enable them.",+ [+ { text: "Cancel", style: "cancel" },+ { text: "Open Settings", onPress: () => void Linking.openSettings() },+ ],+ );+ }, []);++ const promptSignIn = useCallback(() => {+ Alert.alert(+ "Sign in to T3 Connect",+ "Live Activity updates require T3 Connect so relay can deliver updates to this device.",+ [+ { text: "Cancel", style: "cancel" },+ {+ text: "Continue",+ onPress: () => navigation.navigate("SettingsSheet", { screen: "SettingsAuth" }),+ },+ ],+ );+ }, [navigation]);++ const linkEnvironments = useCallback(async () => {+ if (!isSignedIn) {+ promptSignIn();+ return;+ }++ setLiveActivityStatus("linking");+ if (Platform.OS === "android") {+ const permission = await settleAsyncResult(() =>+ runtime.runPromiseExit(requestAgentNotificationPermission),+ );+ if (permission._tag === "Failure") {+ setLiveActivityStatus("disabled");+ const error = squashAtomCommandFailure(permission);+ Alert.alert(+ "Ongoing activity unavailable",+ error instanceof Error ? error.message : "Could not enable agent notifications.",+ );+ return;+ }+ if (permission.value.type !== "granted") {+ setLiveActivityStatus("disabled");+ Alert.alert(+ "Notification permission needed",+ "Enable notifications in system Settings to show ongoing agent activity.",+ [+ { text: "Cancel", style: "cancel" },+ { text: "Open Settings", onPress: () => void Linking.openSettings() },+ ],+ );+ return;+ }+ setNotificationStatus("enabled");+ }+ const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));+ if (tokenResult._tag === "Failure") {+ setLiveActivityStatus("disabled");+ const error = squashAtomCommandFailure(tokenResult);+ Alert.alert(+ Platform.OS === "android" ? "Ongoing activity unavailable" : "Live Activities unavailable",+ error instanceof Error ? error.message : "Could not enable agent activity updates.",+ );+ return;+ }+ if (!tokenResult.value) {+ promptSignIn();+ setLiveActivityStatus("signed-out");+ return;+ }++ const updateResult = await settleAsyncResult(() =>+ runtime.runPromiseExit(+ setLiveActivityUpdatesEnabled({+ enabled: true,+ previousEnabled: liveActivitiesPreferenceEnabled,+ clerkToken: tokenResult.value,+ connections,+ }),+ ),+ );+ if (updateResult._tag === "Failure") {+ setLiveActivityStatus("disabled");+ if (!isAtomCommandInterrupted(updateResult)) {+ const error = squashAtomCommandFailure(updateResult);+ Alert.alert(+ Platform.OS === "android"+ ? "Ongoing activity unavailable"+ : "Live Activities unavailable",+ error instanceof Error ? error.message : "Could not enable agent activity updates.",+ );+ }+ return;+ }++ savePreferences({ liveActivitiesEnabled: true });+ refreshManagedRelayEnvironments();+ setLiveActivityStatus("enabled");+ // The environment link can succeed while this device's own registration+ // (the push-to-start token the relay needs) has not — don't claim Live+ // Activities are live until the device is actually registered.+ if (getAgentAwarenessRegistrationStatus() === "registered") {+ Alert.alert(+ Platform.OS === "android" ? "Ongoing activity enabled" : "Live Activities enabled",+ environmentCount > 0+ ? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for agent activity updates.`+ : "Agent activity updates are enabled. Add an environment to start receiving updates.",+ );+ } else {+ Alert.alert(+ "Couldn't finish enabling activity updates",+ "This device could not be registered with T3 Connect, so activity updates won't appear yet. They'll start once registration succeeds.",+ );+ }+ }, [+ connections,+ environmentCount,+ getToken,+ isSignedIn,+ liveActivitiesPreferenceEnabled,+ promptSignIn,+ savePreferences,+ ]);++ const handleDeviceNotificationsChange = useCallback(+ (enabled: boolean) => {+ if (enabled) {+ if (!isSignedIn) {+ promptSignIn();+ return;+ }+ void requestNotifications();+ return;+ }++ Alert.alert(+ "Disable notifications",+ "Open system Settings to disable notifications for T3 Code.",+ [+ { text: "Cancel", style: "cancel" },+ { text: "Open Settings", onPress: () => void Linking.openSettings() },+ ],+ );+ },+ [isSignedIn, promptSignIn, requestNotifications],+ );++ const handleLiveActivitiesChange = useCallback(+ (enabled: boolean) => {+ if (liveActivityWriteInFlight.current) return;+ if (!enabled) {+ liveActivityWriteInFlight.current = true;+ setLiveActivityStatus("linking");+ void (async () => {+ try {+ let token: string | null = null;+ if (isSignedIn) {+ const tokenResult = await settlePromise(() =>+ getToken(resolveRelayClerkTokenOptions()),+ );+ if (tokenResult._tag === "Failure") {+ setLiveActivityStatus("enabled");+ reportAtomCommandResult(tokenResult, {+ label: "live activity disable token lookup",+ });+ return;+ }+ token = tokenResult.value;+ }++ const updateResult = await settleAsyncResult(() =>+ runtime.runPromiseExit(+ setLiveActivityUpdatesEnabled({+ enabled: false,+ previousEnabled: liveActivitiesPreferenceEnabled,+ clerkToken: token,+ connections,+ }),+ ),+ );+ if (updateResult._tag === "Failure") {+ setLiveActivityStatus(isSignedIn ? "enabled" : "signed-out");+ reportAtomCommandResult(updateResult, {+ label: "live activity disable",+ });+ return;+ }+ savePreferences({ liveActivitiesEnabled: false });+ refreshManagedRelayEnvironments();+ setLiveActivityStatus("disabled");+ } finally {+ liveActivityWriteInFlight.current = false;+ }+ })();+ return;+ }++ if (!isSignedIn) {+ promptSignIn();+ return;+ }++ liveActivityWriteInFlight.current = true;+ void linkEnvironments().finally(() => {+ liveActivityWriteInFlight.current = false;+ });+ },+ [+ connections,+ getToken,+ isSignedIn,+ linkEnvironments,+ liveActivitiesPreferenceEnabled,+ promptSignIn,+ savePreferences,+ ],+ );++ return (+ <SettingsScreen title="Notifications">+ <ScrollView+ contentInsetAdjustmentBehavior="automatic"+ showsVerticalScrollIndicator={false}+ className="flex-1"+ contentContainerClassName="gap-6 px-5 pt-4"+ contentContainerStyle={{+ paddingBottom: Math.max(insets.bottom, 18) + 18,+ }}+ >+ <SettingsSection title="Agent activity">+ <SettingsSwitchRow+ icon="bell.badge"+ label="Device Notifications"+ disabled={+ !agentAwarenessPlatform.supported ||+ !agentAwarenessPushAvailable ||+ notificationStatus === "checking" ||+ notificationStatus === "unsupported"+ }+ subtitle={agentAwarenessSubtitle}+ // Only reads as on when this device is actually registered with the+ // relay; otherwise notifications cannot be delivered regardless of+ // the local iOS permission.+ value={+ agentAwarenessPushAvailable && notificationStatus === "enabled" && deviceRegistered+ }+ onValueChange={handleDeviceNotificationsChange}+ />+ <SettingsSwitchRow+ disabled={+ !agentAwarenessPlatform.supported ||+ !agentAwarenessPushAvailable ||+ !isLoaded ||+ liveActivityStatus === "checking" ||+ liveActivityStatus === "linking"+ }+ icon="bolt.circle"+ label={+ Platform.OS === "android"+ ? supportsAndroidLiveUpdateSettings()+ ? "Agent Live Updates"+ : "Ongoing Agent Activity"+ : "Live Activity Updates"+ }+ subtitle={agentAwarenessSubtitle}+ // Same gate: a saved preference is meaningless until the device+ // registration the relay needs to push updates has succeeded.+ value={+ agentAwarenessPushAvailable &&+ (liveActivityStatus === "enabled" || liveActivityStatus === "linking") &&+ deviceRegistered+ }+ onValueChange={handleLiveActivitiesChange}+ />+ {liveActivityStatus === "signed-out" && canClearLiveActivitiesPreference ? (+ <SettingsRow+ icon="bolt.circle"+ label="Turn off Live Activity preference"+ onPress={() => handleLiveActivitiesChange(false)}+ />+ ) : null}+ {supportsAndroidLiveUpdateSettings() ? (+ <SettingsRow+ icon="bolt.circle"+ label="Live Update Settings"+ onPress={() => {+ void openAndroidLiveUpdateSettings().catch(() => {+ Alert.alert(+ "Couldn't open Settings",+ "Open Android Settings, select T3 Code, then enable Live Updates in Notifications.",+ );+ });+ }}+ />+ ) : null}+ </SettingsSection>+ </ScrollView>+ </SettingsScreen>+ );+}diff --git a/apps/mobile/src/features/settings/SettingsProjectGroupingRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsProjectGroupingRouteScreen.tsxindex 5eb815098aa..fb17ed64edc 100644--- a/apps/mobile/src/features/settings/SettingsProjectGroupingRouteScreen.tsx+++ b/apps/mobile/src/features/settings/SettingsProjectGroupingRouteScreen.tsx@@ -47,7 +47,7 @@ export function SettingsProjectGroupingRouteScreen() {: null;return (- <SettingsScreen title="Project Grouping">+ <SettingsScreen title="Organization"><ScrollViewcontentInsetAdjustmentBehavior="automatic"showsVerticalScrollIndicator={false}@@ -55,7 +55,7 @@ export function SettingsProjectGroupingRouteScreen() {contentContainerClassName="gap-3 px-5 pt-4"contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}>- <SettingsSection title="Default grouping">+ <SettingsSection title="Project grouping">{GROUPING_OPTIONS.map((option, index) => (<Pressablekey={option.mode}diff --git a/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsxnew file mode 100644index 00000000000..8c260e871a0--- /dev/null+++ b/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx@@ -0,0 +1,174 @@+import { ScreenScrollView as ScrollView } from "../../components/ScreenScrollView";+import { AppText as Text, AppTextInput } from "../../components/AppText";+import { ProjectFavicon } from "../../components/ProjectFavicon";+import { deriveProjectGroupLabel } from "@t3tools/client-runtime/state/project-grouping";+import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";+import { useState } from "react";+import { Platform, Pressable, View } from "react-native";+import { useSafeAreaInsets } from "react-native-safe-area-context";++import { projectEnvironment } from "../../state/projects";+import { useAtomCommand } from "../../state/use-atom-command";+import { SettingsScreen } from "./components/SettingsScreen";+import { SettingsSection } from "./components/SettingsSection";+import {+ AndroidSettingsEnvironmentFilter,+ SettingsEnvironmentFilterHeader,+} from "./components/SettingsEnvironmentFilterHeader";+import { useSettingsEnvironmentFilter, type SettingsTarget } from "./settings-environment-filter";++export function SettingsProjectOverviewRouteScreen() {+ const insets = useSafeAreaInsets();+ const { selectedTargets, projectGroups, selectedProjectKey } = useSettingsEnvironmentFilter();+ const group = projectGroups.find((entry) => entry.key === selectedProjectKey);+ const selectedEnvironmentIds = new Set(selectedTargets.map((entry) => entry.environmentId));+ const members =+ group?.members+ .map((entry) => entry.project)+ .filter((project) => selectedEnvironmentIds.has(project.environmentId)) ?? [];++ return (+ <>+ <SettingsEnvironmentFilterHeader />+ <SettingsScreen title="Project overview" trailing={<AndroidSettingsEnvironmentFilter />}>+ <ScrollView+ contentInsetAdjustmentBehavior="automatic"+ showsVerticalScrollIndicator={false}+ className="flex-1"+ contentContainerClassName="gap-6 px-5 pt-4"+ contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}+ >+ {members.length === 0 ? (+ <Text className="px-2 text-base text-foreground-muted">+ This project has no checkout on the selected connected environments. Change the filter+ above.+ </Text>+ ) : (+ <ProjectOverviewContent+ key={`${selectedProjectKey}:${members.map((member) => member.id).join(",")}`}+ members={members}+ environments={selectedTargets}+ />+ )}+ </ScrollView>+ </SettingsScreen>+ </>+ );+}++function ProjectOverviewContent(props: {+ readonly members: readonly EnvironmentProject[];+ readonly environments: readonly SettingsTarget[];+}) {+ const representative = props.members[0]!;+ const displayName = deriveProjectGroupLabel({ representative, members: props.members });+ const [draftName, setDraftName] = useState<string | null>(null);+ const [isSaving, setIsSaving] = useState(false);+ const updateProject = useAtomCommand(projectEnvironment.update, {+ label: "project name update",+ reportFailure: true,+ });+ const nextName = (draftName ?? displayName).trim();+ const canSave = !isSaving && nextName.length > 0 && nextName !== displayName;++ const saveName = () => {+ if (!canSave) return;+ setIsSaving(true);+ void (async () => {+ try {+ const results = await Promise.all(+ props.members.map((member) =>+ updateProject({+ environmentId: member.environmentId,+ input: { projectId: member.id, title: nextName },+ }),+ ),+ );+ if (results.every((result) => result._tag !== "Failure")) setDraftName(null);+ } finally {+ setIsSaving(false);+ }+ })();+ };++ return (+ <>+ <View className="flex-row items-center gap-4 px-2">+ <ProjectFavicon+ environmentId={representative.environmentId}+ projectTitle={displayName}+ workspaceRoot={representative.workspaceRoot}+ faviconPath={representative.faviconPath}+ size={48}+ />+ <View className="min-w-0 flex-1">+ <Text className="text-xl font-t3-semibold text-foreground" numberOfLines={2}>+ {displayName}+ </Text>+ <Text className="text-sm text-foreground-muted">+ {props.members.length === 1 ? "1 checkout" : `${props.members.length} checkouts`}+ </Text>+ </View>+ </View>++ <SettingsSection title="Project">+ <View className="gap-3 p-4">+ <Text className="text-sm font-t3-medium text-foreground-muted">Name</Text>+ <View className="flex-row items-center gap-3">+ <AppTextInput+ accessibilityLabel="Project name"+ className="min-h-11 min-w-0 flex-1 rounded-xl border-continuous bg-card px-3 text-base text-foreground"+ value={draftName ?? displayName}+ onChangeText={setDraftName}+ onSubmitEditing={saveName}+ returnKeyType="done"+ editable={!isSaving}+ />+ {canSave ? (+ <Pressable+ accessibilityRole="button"+ accessibilityLabel="Save project name"+ onPress={saveName}+ className="rounded-full bg-subtle-strong px-4 py-2 active:opacity-70"+ >+ <Text className="text-sm font-t3-medium text-foreground">Save</Text>+ </Pressable>+ ) : null}+ </View>+ </View>+ </SettingsSection>++ <SettingsSection title="Checkouts">+ {props.members.map((member, index) => {+ const environment = props.environments.find(+ (entry) => entry.environmentId === member.environmentId,+ );+ return (+ <View+ key={`${member.environmentId}:${member.id}`}+ className={index === 0 ? "gap-1 p-4" : "gap-1 border-t border-border-subtle p-4"}+ >+ <Text+ className={+ Platform.OS === "android"+ ? "text-base text-foreground"+ : "text-lg text-foreground"+ }+ >+ {environment?.label ?? "Environment"}+ </Text>+ {environment?.displayUrl ? (+ <Text className="text-sm leading-normal text-foreground-muted">+ {environment.displayUrl}+ </Text>+ ) : null}+ <Text className="text-sm leading-normal text-foreground-muted" selectable>+ {member.workspaceRoot}+ </Text>+ </View>+ );+ })}+ </SettingsSection>+ </>+ );+}diff --git a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsRouteScreen.tsxindex d32dcb3e682..c8a3b92abed 100644--- a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx+++ b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx@@ -1,83 +1,23 @@-import { AutoSettleDaysField } from "./components/AutoSettleDaysField";import { ScreenScrollView as ScrollView } from "../../components/ScreenScrollView";import { useAuth, useUser } from "@clerk/expo";-import { useAtomSet, useAtomValue } from "@effect/atom-react";-import Constants from "expo-constants";-import * as Notifications from "expo-notifications";import { useNavigation } from "@react-navigation/native";-import { NativeStackScreenOptions } from "../../native/StackHeader";-import { SymbolView } from "../../components/AppSymbol";-import * as Effect from "effect/Effect";-import { AsyncResult } from "effect/unstable/reactivity";-import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";-import { Alert, Linking, Platform, Pressable, View } from "react-native";+import { Platform, View } from "react-native";+import { deriveProjectGroupLabel } from "@t3tools/client-runtime/state/project-grouping";import { useSafeAreaInsets } from "react-native-safe-area-context";-import {- isAtomCommandInterrupted,- reportAtomCommandResult,- settleAsyncResult,- settlePromise,- squashAtomCommandFailure,-} from "@t3tools/client-runtime/state/runtime";-import { AppText as Text } from "../../components/AppText";-import { supportsAgentAwarenessPush } from "../agent-awareness/capabilities";-import {- openAndroidLiveUpdateSettings,- supportsAndroidLiveUpdateSettings,-} from "../agent-awareness/androidNotifications";-import { setLiveActivityUpdatesEnabled } from "../agent-awareness/liveActivityPreferences";-import { requestAgentNotificationPermission } from "../agent-awareness/notificationPermissions";-import {- getAgentAwarenessRegistrationStatus,- refreshAgentAwarenessRegistration,- subscribeAgentAwarenessRegistrationStatus,-} from "../agent-awareness/remoteRegistration";-import { refreshManagedRelayEnvironments } from "../cloud/managedRelayState";-import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/publicConfig";-import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";+import { hasCloudPublicConfig } from "../cloud/publicConfig";import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";-import { runtime } from "../../lib/runtime";-import { cn } from "../../lib/cn";-import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";-import { serverEnvironment } from "../../state/server";-import { useAtomCommand } from "../../state/use-atom-command";-import { useEnvironments } from "../../state/environments";-import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";-import { supportsSharedSettingsSync } from "@t3tools/client-runtime/state/shared-settings";-import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";-import {- type AppUpdateCheckState,- isAppUpdateCheckAvailable,- registerHiddenUpdateTap,- runAppUpdateCheck,-} from "../updates/app-updates";import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";import { SettingsRow } from "./components/SettingsRow";import { SettingsSection } from "./components/SettingsSection";-import { SettingsSwitchRow } from "./components/SettingsSwitchRow";import { SettingsScreen } from "./components/SettingsScreen";-import { resolveAgentAwarenessPlatformPresentation } from "./SettingsRouteScreen.logic";-import { planAutoSettleSettingsSync, type AutoSettleSettings } from "./autoSettleSettingsSync";--type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";-type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";--// Reflects whether the relay actually accepted this device's registration.-// The notification and Live Activity switches are gated on this so they can-// never read as enabled when the device cannot receive anything (e.g. the-// registration request timed out).-function useDeviceRegistered(): boolean {- const status = useSyncExternalStore(- subscribeAgentAwarenessRegistrationStatus,- getAgentAwarenessRegistrationStatus,- () => "unknown" as const,- );- return status === "registered";-}+import {+ AndroidSettingsEnvironmentFilter,+ SettingsEnvironmentFilterHeader,+} from "./components/SettingsEnvironmentFilterHeader";+import { useSettingsEnvironmentFilter } from "./settings-environment-filter";export function SettingsRouteScreen() {- const navigation = useNavigation();const content = hasCloudPublicConfig() ? (<ConfiguredSettingsRouteScreen />) : (@@ -87,27 +27,11 @@ export function SettingsRouteScreen() {return (<><WorkspaceSidebarToolbar />- {Platform.OS !== "android" ? (- <NativeStackScreenOptions- options={{- unstable_headerRightItems:- Platform.OS === "ios"- ? () => [- withNativeGlassHeaderItem({- accessibilityLabel: "Close settings",- icon: { name: "xmark", type: "sfSymbol" } as const,- identifier: "settings-close",- label: "",- onPress: () => navigation.goBack(),- type: "button",- }),- ]- : undefined,- }}- />- ) : null}+ <SettingsEnvironmentFilterHeader closeSettings />{Platform.OS === "android" ? (- <SettingsScreen title="Settings">{content}</SettingsScreen>+ <SettingsScreen title="Settings" trailing={<AndroidSettingsEnvironmentFilter />}>+ {content}+ </SettingsScreen>) : (content)}@@ -115,10 +39,17 @@ export function SettingsRouteScreen() {);}-function LocalSettingsRouteScreen() {+function ConfiguredSettingsRouteScreen() {const insets = useSafeAreaInsets();+ const navigation = useNavigation();+ const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });+ const { user } = useUser();const { savedConnectionsById } = useSavedRemoteConnections();- const environmentCount = Object.keys(savedConnectionsById).length;+ const accountLabel = !isLoaded+ ? "Checking"+ : !isSignedIn+ ? "Sign in"+ : (user?.primaryEmailAddress?.emailAddress ?? "Signed in");return (<View collapsable={false} className="flex-1 bg-sheet">@@ -126,368 +57,37 @@ function LocalSettingsRouteScreen() {contentInsetAdjustmentBehavior="automatic"showsVerticalScrollIndicator={false}className="flex-1"- contentContainerClassName="gap-6 px-5 pt-4"- contentContainerStyle={{- paddingBottom: Math.max(insets.bottom, 18) + 18,- }}+ contentContainerClassName="gap-4 px-5 pt-4"+ contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}>- <SettingsSection title="Configuration">+ <SettingsSection title="Connections">+ <SettingsRow+ icon="person.crop.circle"+ label="T3 Account"+ value={accountLabel}+ disabled={!isLoaded}+ onPress={() => navigation.navigate("SettingsSheet", { screen: "SettingsAuth" })}+ /><SettingsRowicon="desktopcomputer"label="Environments"- value={`${environmentCount}`}+ value={`${Object.keys(savedConnectionsById).length}`}valuePosition="trailing"target="SettingsEnvironments"/>+ <SettingsRow icon="bell.badge" label="Notifications" target="SettingsNotifications" /></SettingsSection>- <GeneralSettingsSection />-- <SettingsSection title="Appearance">- <SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />- </SettingsSection>-- <LegacySettingsSection />-- <ArchivedThreadsSettingsSection />-- <AppSettingsSection />+ <SettingsIndexSections /></ScrollView></View>);}-function ConfiguredSettingsRouteScreen() {- const preferencesResult = useAtomValue(mobilePreferencesAtom);- const savePreferences = useAtomSet(updateMobilePreferencesAtom);- const agentAwarenessPushAvailable = supportsAgentAwarenessPush();- const agentAwarenessPlatform = resolveAgentAwarenessPlatformPresentation(Platform.OS);- const agentAwarenessSubtitle =- Platform.OS === "android" && !agentAwarenessPushAvailable- ? "Install a newer app build to enable notifications"- : agentAwarenessPlatform.subtitle;+function LocalSettingsRouteScreen() {const insets = useSafeAreaInsets();- const navigation = useNavigation();- const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });- const { user } = useUser();const { savedConnectionsById } = useSavedRemoteConnections();- const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");- const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");- const deviceRegistered = useDeviceRegistered();- const liveActivitiesPreferenceEnabled = AsyncResult.isSuccess(preferencesResult)- ? preferencesResult.value.liveActivitiesEnabled !== false- : true;-- const connections = useMemo(() => Object.values(savedConnectionsById), [savedConnectionsById]);- const environmentCount = connections.length;- const accountLabel = useMemo(() => {- if (!isLoaded) return "Checking";- if (!isSignedIn) return "Sign in";- return user?.primaryEmailAddress?.emailAddress ?? "Signed in";- }, [isLoaded, isSignedIn, user?.primaryEmailAddress?.emailAddress]);-- const refreshNotifications = useCallback(async () => {- if (Platform.OS !== "ios" && Platform.OS !== "android") {- setNotificationStatus("unsupported");- return;- }- const result = await settlePromise(() => Notifications.getPermissionsAsync());- if (result._tag === "Failure") {- reportAtomCommandResult(result, { label: "notification permission refresh" });- setNotificationStatus("disabled");- return;- }- setNotificationStatus(result.value.granted ? "enabled" : "disabled");- }, []);-- useEffect(() => {- void refreshNotifications();- }, [refreshNotifications]);-- useEffect(() => {- if (!isLoaded) {- setLiveActivityStatus("checking");- return;- }- if (!isSignedIn) {- setLiveActivityStatus("signed-out");- return;- }- if (!AsyncResult.isSuccess(preferencesResult)) {- if (AsyncResult.isFailure(preferencesResult)) {- reportAtomCommandResult(preferencesResult, { label: "live activity preference load" });- setLiveActivityStatus("enabled");- } else {- setLiveActivityStatus("checking");- }- return;- }- setLiveActivityStatus(- preferencesResult.value.liveActivitiesEnabled === false ? "disabled" : "enabled",- );- }, [isLoaded, isSignedIn, preferencesResult]);-- const requestNotifications = useCallback(async () => {- const result = await settleAsyncResult(() =>- runtime.runPromiseExit(- requestAgentNotificationPermission.pipe(- Effect.tap((permission) =>- permission.type === "granted" ? refreshAgentAwarenessRegistration() : Effect.void,- ),- ),- ),- );- if (result._tag === "Failure") {- if (!isAtomCommandInterrupted(result)) {- const error = squashAtomCommandFailure(result);- Alert.alert(- "Notifications unavailable",- error instanceof Error ? error.message : "Could not request notification permission.",- );- }- return;- }- if (result.value.type === "granted") {- setNotificationStatus("enabled");- // Permission alone is not enough: the switch stays off until the relay- // registration succeeds, so tell the user the truth about which happened.- if (getAgentAwarenessRegistrationStatus() === "registered") {- Alert.alert("Notifications enabled", "Agent notifications are enabled for this device.");- } else {- Alert.alert(- "Couldn't finish enabling notifications",- "Notification access was granted, but this device could not be registered with T3 Connect. Notifications will start once registration succeeds.",- );- }- return;- }- if (result.value.type === "unsupported") {- setNotificationStatus("unsupported");- Alert.alert(- "Notifications unavailable",- "Agent notifications are unavailable on this platform.",- );- return;- }- setNotificationStatus("disabled");- if (result.value.canAskAgain) {- Alert.alert("Notifications disabled", "Notifications were not enabled.");- return;- }- Alert.alert(- "Notifications disabled",- "Notifications were denied for this app. Open Settings to enable them.",- [- { text: "Cancel", style: "cancel" },- { text: "Open Settings", onPress: () => void Linking.openSettings() },- ],- );- }, []);-- const promptSignIn = useCallback(() => {- Alert.alert(- "Sign in to T3 Connect",- "Live Activity updates require T3 Connect so relay can deliver updates to this device.",- [- { text: "Cancel", style: "cancel" },- {- text: "Continue",- onPress: () => navigation.navigate("SettingsSheet", { screen: "SettingsAuth" }),- },- ],- );- }, [navigation]);-- const linkEnvironments = useCallback(async () => {- if (!isSignedIn) {- promptSignIn();- return;- }-- setLiveActivityStatus("linking");- if (Platform.OS === "android") {- const permission = await settleAsyncResult(() =>- runtime.runPromiseExit(requestAgentNotificationPermission),- );- if (permission._tag === "Failure") {- setLiveActivityStatus("disabled");- const error = squashAtomCommandFailure(permission);- Alert.alert(- "Ongoing activity unavailable",- error instanceof Error ? error.message : "Could not enable agent notifications.",- );- return;- }- if (permission.value.type !== "granted") {- setLiveActivityStatus("disabled");- Alert.alert(- "Notification permission needed",- "Enable notifications in system Settings to show ongoing agent activity.",- [- { text: "Cancel", style: "cancel" },- { text: "Open Settings", onPress: () => void Linking.openSettings() },- ],- );- return;- }- setNotificationStatus("enabled");- }- const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));- if (tokenResult._tag === "Failure") {- setLiveActivityStatus("disabled");- const error = squashAtomCommandFailure(tokenResult);- Alert.alert(- Platform.OS === "android" ? "Ongoing activity unavailable" : "Live Activities unavailable",- error instanceof Error ? error.message : "Could not enable agent activity updates.",- );- return;- }- if (!tokenResult.value) {- promptSignIn();- setLiveActivityStatus("signed-out");- return;- }-- const updateResult = await settleAsyncResult(() =>- runtime.runPromiseExit(- setLiveActivityUpdatesEnabled({- enabled: true,- previousEnabled: liveActivitiesPreferenceEnabled,- clerkToken: tokenResult.value,- connections,- }),- ),- );- if (updateResult._tag === "Failure") {- setLiveActivityStatus("disabled");- if (!isAtomCommandInterrupted(updateResult)) {- const error = squashAtomCommandFailure(updateResult);- Alert.alert(- Platform.OS === "android"- ? "Ongoing activity unavailable"- : "Live Activities unavailable",- error instanceof Error ? error.message : "Could not enable agent activity updates.",- );- }- return;- }-- savePreferences({ liveActivitiesEnabled: true });- refreshManagedRelayEnvironments();- setLiveActivityStatus("enabled");- // The environment link can succeed while this device's own registration- // (the push-to-start token the relay needs) has not — don't claim Live- // Activities are live until the device is actually registered.- if (getAgentAwarenessRegistrationStatus() === "registered") {- Alert.alert(- Platform.OS === "android" ? "Ongoing activity enabled" : "Live Activities enabled",- environmentCount > 0- ? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for agent activity updates.`- : "Agent activity updates are enabled. Add an environment to start receiving updates.",- );- } else {- Alert.alert(- "Couldn't finish enabling activity updates",- "This device could not be registered with T3 Connect, so activity updates won't appear yet. They'll start once registration succeeds.",- );- }- }, [- connections,- environmentCount,- getToken,- isSignedIn,- liveActivitiesPreferenceEnabled,- promptSignIn,- savePreferences,- ]);-- const handleDeviceNotificationsChange = useCallback(- (enabled: boolean) => {- if (enabled) {- if (!isSignedIn) {- promptSignIn();- return;- }- void requestNotifications();- return;- }-- Alert.alert(- "Disable notifications",- "Open system Settings to disable notifications for T3 Code.",- [- { text: "Cancel", style: "cancel" },- { text: "Open Settings", onPress: () => void Linking.openSettings() },- ],- );- },- [isSignedIn, promptSignIn, requestNotifications],- );-- const handleLiveActivitiesChange = useCallback(- (enabled: boolean) => {- if (!enabled) {- setLiveActivityStatus("disabled");- void (async () => {- let token: string | null = null;- if (isSignedIn) {- const tokenResult = await settlePromise(() =>- getToken(resolveRelayClerkTokenOptions()),- );- if (tokenResult._tag === "Failure") {- reportAtomCommandResult(tokenResult, {- label: "live activity disable token lookup",- });- return;- }- token = tokenResult.value;- }-- const updateResult = await settleAsyncResult(() =>- runtime.runPromiseExit(- setLiveActivityUpdatesEnabled({- enabled: false,- previousEnabled: liveActivitiesPreferenceEnabled,- clerkToken: token,- connections,- }),- ),- );- if (updateResult._tag === "Failure") {- setLiveActivityStatus("enabled");- reportAtomCommandResult(updateResult, {- label: "live activity disable",- });- return;- }- savePreferences({ liveActivitiesEnabled: false });- refreshManagedRelayEnvironments();- })();- return;- }-- if (!isSignedIn) {- promptSignIn();- return;- }-- void linkEnvironments();- },- [- connections,- getToken,- isSignedIn,- linkEnvironments,- liveActivitiesPreferenceEnabled,- promptSignIn,- savePreferences,- ],- );-- const openAccount = useCallback(() => {- if (!isLoaded) return;- navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });- }, [isLoaded, navigation]);+ const environmentCount = Object.keys(savedConnectionsById).length;return (<View collapsable={false} className="flex-1 bg-sheet">@@ -495,26 +95,12 @@ function ConfiguredSettingsRouteScreen() {contentInsetAdjustmentBehavior="automatic"showsVerticalScrollIndicator={false}className="flex-1"- contentContainerClassName="gap-6 px-5 pt-4"+ contentContainerClassName="gap-4 px-5 pt-4"contentContainerStyle={{paddingBottom: Math.max(insets.bottom, 18) + 18,}}>- <View className="gap-3">- <SettingsSection title="Account">- <SettingsRow- icon="person.crop.circle"- label="T3 Account"- value={accountLabel}- onPress={openAccount}- />- </SettingsSection>- <Text className="px-2 text-sm text-foreground-muted">- T3 Code works locally without signing in. Cloud features are optional.- </Text>- </View>-- <SettingsSection title="Configuration">+ <SettingsSection title="Connections"><SettingsRowicon="desktopcomputer"label="Environments"@@ -522,353 +108,85 @@ function ConfiguredSettingsRouteScreen() {valuePosition="trailing"target="SettingsEnvironments"/>- <SettingsSwitchRow- icon="bell.badge"- label="Device Notifications"- disabled={- !agentAwarenessPlatform.supported ||- !agentAwarenessPushAvailable ||- notificationStatus === "checking" ||- notificationStatus === "unsupported"- }- subtitle={agentAwarenessSubtitle}- // Only reads as on when this device is actually registered with the- // relay; otherwise notifications cannot be delivered regardless of- // the local iOS permission.- value={- agentAwarenessPushAvailable && notificationStatus === "enabled" && deviceRegistered- }- onValueChange={handleDeviceNotificationsChange}- />- <SettingsSwitchRow- disabled={- !agentAwarenessPlatform.supported ||- !agentAwarenessPushAvailable ||- !isLoaded ||- liveActivityStatus === "checking" ||- liveActivityStatus === "linking"- }- icon="bolt.circle"- label={- Platform.OS === "android"- ? supportsAndroidLiveUpdateSettings()- ? "Agent Live Updates"- : "Ongoing Agent Activity"- : "Live Activity Updates"- }- subtitle={agentAwarenessSubtitle}- // Same gate: a saved preference is meaningless until the device- // registration the relay needs to push updates has succeeded.- value={- agentAwarenessPushAvailable &&- (liveActivityStatus === "enabled" || liveActivityStatus === "linking") &&- deviceRegistered- }- onValueChange={handleLiveActivitiesChange}- />- {supportsAndroidLiveUpdateSettings() ? (- <SettingsRow- icon="bolt.circle"- label="Live Update Settings"- onPress={() => {- void openAndroidLiveUpdateSettings().catch(() => {- Alert.alert(- "Couldn't open Settings",- "Open Android Settings, select T3 Code, then enable Live Updates in Notifications.",- );- });- }}- />- ) : null}</SettingsSection>- <GeneralSettingsSection />-- <SettingsSection title="Appearance">- <SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />- </SettingsSection>-- <LegacySettingsSection />-- <ArchivedThreadsSettingsSection />-- <AppSettingsSection />+ <SettingsIndexSections /></ScrollView></View>);}-function GeneralSettingsSection() {- return (- <SettingsSection title="General">- <SettingsRow icon="folder" label="Project Grouping" target="SettingsProjectGrouping" />- {Platform.OS === "ios" ? (- <SettingsRow icon="keyboard" label="Keyboard" target="SettingsKeyboard" />- ) : null}- <AutoSettleSettingsRows />- <SettingsRow icon="chart.bar.xaxis" label="Usage" target="SettingsUsage" />- </SettingsSection>- );-}--const AUTO_SETTLE_DEFAULT_DAYS = DEFAULT_SERVER_SETTINGS.sidebarAutoSettleAfterDays ?? 3;--/**- * Mobile edits auto-settle defaults across connected, capable environments.- * The first target supplies the displayed values. Applying them leaves each- * environment's other defaults and overrides intact.- */-function AutoSettleSettingsRows() {- const { environments } = useEnvironments();- const [pendingWrites, setPendingWrites] = useState(0);- const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {- label: "server settings update",- reportFailure: true,- });-- const syncTargets = environments.filter(supportsSharedSettingsSync);- const reference = syncTargets[0] ?? null;- const referenceSettings = reference?.serverConfig?.settings ?? null;-- if (reference === null || referenceSettings === null) {- return null;- }-- const writeToAll = (patch: Partial<AutoSettleSettings>) => {- setPendingWrites((count) => count + 1);- void Promise.allSettled(- syncTargets.map((environment) =>- updateSettings({ environmentId: environment.environmentId, input: { patch } }),- ),- ).finally(() => setPendingWrites((count) => count - 1));- };-- const { patch: autoSettlePatch, mismatches } = planAutoSettleSettingsSync(- { environmentId: reference.environmentId, settings: referenceSettings },- syncTargets.map((environment) => ({- environmentId: environment.environmentId,- label: environment.label,- settings: environment.serverConfig?.settings ?? null,- })),- );-- const afterDays = referenceSettings.sidebarAutoSettleAfterDays;-+function SettingsIndexSections() {+ const { selectedTargets, projectGroups, selectedProjectKey } = useSettingsEnvironmentFilter();+ const noServerTargets = selectedTargets.length === 0;+ const selectedProject = projectGroups.find((group) => group.key === selectedProjectKey);+ const scopedProjectMembers =+ selectedProject?.members+ .map((member) => member.project)+ .filter((project) =>+ selectedTargets.some((target) => target.environmentId === project.environmentId),+ ) ?? [];+ const projectLabel =+ scopedProjectMembers.length > 0+ ? deriveProjectGroupLabel({+ representative: scopedProjectMembers[0]!,+ members: scopedProjectMembers,+ })+ : (selectedProject?.label ?? "Unavailable project");return (<>- <SettingsSwitchRow- icon="arrow.triangle.branch"- label="Auto-settle merged threads"- value={referenceSettings.sidebarAutoSettleOnMerge}- onValueChange={(value) => writeToAll({ sidebarAutoSettleOnMerge: value })}- />- <SettingsSwitchRow- icon="clock"- label="Auto-settle inactive threads"- value={afterDays !== null}- onValueChange={(value) =>- writeToAll({ sidebarAutoSettleAfterDays: value ? AUTO_SETTLE_DEFAULT_DAYS : null })- }- />- {afterDays !== null ? (- <View- className={cn(- "flex-row items-center gap-4 px-4",- Platform.OS === "android" ? "min-h-14 py-3" : "py-4",- )}- >- <View style={{ width: Platform.OS === "android" ? 24 : 22 }} />- <Text- className={cn(- "flex-1 text-foreground",- Platform.OS === "android" ? "text-base" : "text-lg",- )}- >- Inactive days- </Text>- <AutoSettleDaysField- value={afterDays}- onValueChange={(value) => writeToAll({ sidebarAutoSettleAfterDays: value })}- />- </View>- ) : null}- {pendingWrites === 0 && mismatches.length > 0 ? (- <View className="flex-row items-center gap-4 border-t border-border-subtle p-4">- <View className="min-w-0 flex-1">- <Text className="text-lg text-foreground">Auto-settle defaults differ</Text>- <Text className="text-sm text-foreground-muted">- {mismatches.map((mismatch) => mismatch.label).join(", ")}- </Text>- </View>- <Pressable- accessibilityRole="button"- onPress={() => writeToAll(autoSettlePatch)}- className="rounded-full bg-subtle px-4 py-2 active:opacity-70"- >- <Text className="text-base font-t3-medium text-foreground">- Apply auto-settle defaults- </Text>- </Pressable>- </View>- ) : null}- </>- );-}+ <SettingsSection title="Interface">+ <SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />+ {Platform.OS === "ios" ? (+ <SettingsRow icon="keyboard" label="Keyboard" target="SettingsKeyboard" />+ ) : null}+ </SettingsSection>-/**- * Device-local legacy toggles. Mobile has no client-settings sync, so this is- * the counterpart of web's Settings → General → Legacy features backed by- * mobile preferences.- */-function LegacySettingsSection() {- const savePreferences = useAtomSet(updateMobilePreferencesAtom);- const preferences = useAtomValue(mobilePreferencesAtom);- const threadListV2Enabled = useThreadListV2Enabled();- const planModeEnabled =- AsyncResult.isSuccess(preferences) && preferences.value.planModeEnabled === true;+ <SettingsSection title="Projects & threads">+ {selectedProjectKey !== null ? (+ <SettingsRow+ icon="folder"+ label="Overview"+ value={projectLabel}+ target="SettingsProjectOverview"+ />+ ) : null}+ <SettingsRow icon="folder" label="Organization" target="SettingsOrganization" />+ <SettingsRow icon="text.bubble" label="Thread behavior" target="SettingsThreads" />+ <SettingsRow icon="archivebox" label="Archived Threads" target="SettingsArchive" />+ </SettingsSection>- return (- <View className="gap-3">- <SettingsSection title="Legacy">- <SettingsSwitchRow- icon="sidebar.left"- label="Legacy Thread List"- value={!threadListV2Enabled}- onValueChange={(value) => savePreferences({ legacyThreadListEnabled: value })}+ <SettingsSection title="Server settings">+ <SettingsRow+ icon="text.bubble"+ label="New threads"+ target="SettingsEnvironmentNewThreads"+ disabled={noServerTargets}+ />+ <SettingsRow+ icon="arrow.triangle.branch"+ label="Source control"+ target="SettingsEnvironmentSourceControl"+ disabled={noServerTargets}/>- <SettingsSwitchRow- icon="hammer"- label="Plan Mode"- value={planModeEnabled}- onValueChange={(value) => savePreferences({ planModeEnabled: value })}+ <SettingsRow+ icon="text.alignleft"+ label="Agent behavior"+ target="SettingsEnvironmentAgentBehavior"+ disabled={noServerTargets}+ />+ <SettingsRow+ icon="arrow.clockwise"+ label="Maintenance"+ target="SettingsEnvironmentMaintenance"+ disabled={noServerTargets}/></SettingsSection>- <Text className="px-2 text-sm text-foreground-muted">- Opt into retired interfaces kept for compatibility. Plan Mode restores the Build/Plan- control; otherwise every task runs in Build mode.- </Text>- </View>- );-}--function AppSettingsSection() {- const [updateState, setUpdateState] = useState<AppUpdateCheckState>("idle");- const updateInFlight = useRef(false);- const hiddenUpdateTapCount = useRef(0);- const version = Constants.expoConfig?.version ?? "0.0.0";- // Fall back to "production" to match resolveAppVariant in app.config.ts, so a- // missing variant never mislabels a production build as development.- const variant = (Constants.expoConfig?.extra?.appVariant as string | undefined) ?? "production";- const variantLabel = variant === "production" ? "" : capitalize(variant);- const versionLabel = variantLabel ? `${version} · ${variantLabel}` : version;- const updateCheckAvailable = isAppUpdateCheckAvailable();- const busy =- updateState === "checking" || updateState === "downloading" || updateState === "restarting";-- // "Up to date" is a transient acknowledgement, not a state worth persisting —- // return the version row to its normal, deliberately quiet state.- useEffect(() => {- if (updateState !== "current") return;- const timer = setTimeout(() => setUpdateState("idle"), 3000);- return () => clearTimeout(timer);- }, [updateState]);-- const checkForUpdate = useCallback(async () => {- // `disabled={busy}` only takes effect on the next render, so two taps in the- // same frame would both get through. The ref closes that window.- if (updateInFlight.current) return;- updateInFlight.current = true;- try {- // The user asked for this restart by tapping the version row, so it may- // apply immediately instead of prompting.- await runAppUpdateCheck({- applyMode: "immediate",- onFailure: (message) => Alert.alert("Update failed", message),- onStateChange: setUpdateState,- });- } finally {- updateInFlight.current = false;- }- }, []);-- const handleVersionPress = useCallback(() => {- if (!updateCheckAvailable || updateInFlight.current) return;- const tap = registerHiddenUpdateTap(hiddenUpdateTapCount.current);- hiddenUpdateTapCount.current = tap.nextCount;- if (tap.shouldCheck) {- void checkForUpdate();- }- }, [checkForUpdate, updateCheckAvailable]);-- const statusLabel =- updateState === "checking"- ? "Checking…"- : updateState === "downloading"- ? "Downloading…"- : // "ready" appears only when this check joined an in-flight background-mode- // check; that download installs at the next backgrounding.- updateState === "ready"- ? "Update ready"- : updateState === "restarting"- ? "Restarting…"- : updateState === "current"- ? "Up to date"- : null;-- const versionRow = (- <View className="flex-row items-center gap-4 p-4">- <SymbolView- name="info.circle"- size={22}- tintColorClassName="accent-icon"- type="monochrome"- weight="regular"- />- <Text className="flex-1 text-lg text-foreground">Version</Text>- <View className="items-end">- <Text className="text-lg text-foreground-muted">{versionLabel}</Text>- {statusLabel ? (- <Text className="text-xs text-foreground-muted/70">{statusLabel}</Text>- ) : null}- </View>- </View>- );-- return (- <SettingsSection title="App">- <SettingsRow icon="internaldrive" label="Client Storage" target="SettingsClientStorage" />- <SettingsRow icon="stethoscope" label="Diagnostics" target="SettingsDiagnostics" />- <SettingsRow- icon="doc.on.doc"- label="Open source licenses"- target="SettingsOpenSourceLicenses"- />- <SettingsRow icon="doc.text" label="Legal" fullScreenTarget="SettingsLegal" />- {updateCheckAvailable ? (- <Pressable- accessibilityLabel={`Version ${versionLabel}`}- accessibilityRole="text"- disabled={busy}- onPress={handleVersionPress}- >- {versionRow}- </Pressable>- ) : (- versionRow- )}- </SettingsSection>- );-}--function capitalize(value: string): string {- return value.length > 0 ? value.charAt(0).toUpperCase() + value.slice(1) : value;-}--function ArchivedThreadsSettingsSection() {- return (- <SettingsSection title="Threads">- <SettingsRow icon="archivebox" label="Archived Threads" target="SettingsArchive" />- </SettingsSection>+ <SettingsSection title="App">+ <SettingsRow icon="chart.bar.xaxis" label="Usage" target="SettingsUsage" />+ <SettingsRow icon="info.circle" label="About T3 Code" target="SettingsAbout" />+ </SettingsSection>+ </>);}diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsxnew file mode 100644index 00000000000..6e7cef0de93--- /dev/null+++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx@@ -0,0 +1,474 @@+import { ScreenScrollView as ScrollView } from "../../components/ScreenScrollView";+import { SymbolView } from "../../components/AppSymbol";+import { AppText as Text } from "../../components/AppText";+import {+ type ResponseStreamingMode,+ type ServerSettings,+ type ServerSettingsPatch,+ type ThreadEnvMode,+ PROJECT_SCOPED_SERVER_SETTING_KEYS,+ type ProjectScopedServerSettingKey,+} from "@t3tools/contracts";+import { useRef, useState, type ComponentProps } from "react";+import { Alert, Platform, Pressable, View } from "react-native";+import { useSafeAreaInsets } from "react-native-safe-area-context";++import { RUNTIME_MODE_CHOICES } from "../threads/thread-settings-options";+import { serverEnvironment } from "../../state/server";+import { useAtomCommand } from "../../state/use-atom-command";+import { SettingsScreen } from "./components/SettingsScreen";+import {+ AndroidSettingsEnvironmentFilter,+ SettingsEnvironmentFilterHeader,+} from "./components/SettingsEnvironmentFilterHeader";+import { SettingsSection } from "./components/SettingsSection";+import { SettingsSwitchRow } from "./components/SettingsSwitchRow";+import { SettingsProjectOverridesSection } from "./components/SettingsProjectOverridesSection";+import { useSettingsEnvironmentFilter } from "./settings-environment-filter";+import {+ planMobileScopedSettingsClear,+ planMobileScopedSettingsPatch,+ resolveMobileSettingsTargets,+ type ScopedMobileSettingsTarget,+} from "./settings-scoped-server";++type SettingsPage = "new-threads" | "source-control" | "agent-behavior" | "maintenance";++const PAGE_TITLES: Record<SettingsPage, string> = {+ "new-threads": "New threads",+ "source-control": "Source control",+ "agent-behavior": "Agent behavior",+ maintenance: "Maintenance",+};++const PAGE_PROJECT_KEYS: Record<SettingsPage, readonly ProjectScopedServerSettingKey[]> = {+ "new-threads": ["defaultThreadEnvMode", "defaultRuntimeMode"],+ "source-control": ["defaultAutoPull", "newWorktreesStartFromOrigin"],+ "agent-behavior": ["responseStreamingMode", "enableAgentBrowserAccess"],+ maintenance: ["continueThreadsAfterServerUpdate"],+};++const WORKSPACE_CHOICES: ReadonlyArray<{+ readonly mode: ThreadEnvMode;+ readonly label: string;+ readonly description: string;+}> = [+ {+ mode: "local",+ label: "Current checkout",+ description: "Start new threads in the existing workspace.",+ },+ {+ mode: "worktree",+ label: "New worktree",+ description: "Give each new thread a separate checkout.",+ },+];++const STREAMING_CHOICES: ReadonlyArray<{+ readonly mode: ResponseStreamingMode;+ readonly label: string;+ readonly description: string;+}> = [+ {+ mode: "turn",+ label: "After the turn",+ description: "Show the answer when the agent finishes.",+ },+ {+ mode: "paragraph",+ label: "Finished paragraphs",+ description: "Show each paragraph or code block as it completes.",+ },+ {+ mode: "token",+ label: "Token by token (legacy)",+ description: "Repaint for every token; this can be slower.",+ },+];++export function SettingsEnvironmentNewThreadsRouteScreen() {+ return <ServerSettingsDetail page="new-threads" />;+}++export function SettingsEnvironmentSourceControlRouteScreen() {+ return <ServerSettingsDetail page="source-control" />;+}++export function SettingsEnvironmentAgentBehaviorRouteScreen() {+ return <ServerSettingsDetail page="agent-behavior" />;+}++export function SettingsEnvironmentMaintenanceRouteScreen() {+ return <ServerSettingsDetail page="maintenance" />;+}++function ServerSettingsDetail(props: { readonly page: SettingsPage }) {+ const insets = useSafeAreaInsets();+ const { selectedTargets, projectGroups, selectedProjectKey } = useSettingsEnvironmentFilter();+ const selectedProject = projectGroups.find((group) => group.key === selectedProjectKey);+ const projectSelected = selectedProjectKey !== null;+ const targets = resolveMobileSettingsTargets(+ selectedTargets,+ projectSelected ? (selectedProject?.members.map((member) => member.project) ?? []) : null,+ );+ const [pendingWrites, setPendingWrites] = useState(0);+ const writeInFlight = useRef(false);+ const [pendingTargets, setPendingTargets] = useState<+ readonly ScopedMobileSettingsTarget[] | null+ >(null);+ const displayTargets = pendingWrites > 0 && pendingTargets !== null ? pendingTargets : targets;+ const hasConnectedSelection = targets.length > 0;+ const reference = displayTargets[0] ?? null;+ const uniform = <K extends keyof ServerSettings>(key: K): ServerSettings[K] | null => {+ if (reference === null) return null;+ const value = reference.settings[key];+ return displayTargets.every((entry) => entry.settings[key] === value) ? value : null;+ };+ const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {+ label: "environment settings update",+ reportFailure: true,+ });+ const write = (patch: ServerSettingsPatch) => {+ if (writeInFlight.current || !hasConnectedSelection) return;+ const writes = planMobileScopedSettingsPatch(targets, projectSelected, patch);+ if (writes.length === 0) return;+ writeInFlight.current = true;+ setPendingTargets(targets);+ setPendingWrites((count) => count + 1);+ void Promise.allSettled(+ writes.map((entry) =>+ updateSettings({ environmentId: entry.environmentId, input: { patch: entry.patch } }),+ ),+ ).finally(() => {+ writeInFlight.current = false;+ setPendingTargets(null);+ setPendingWrites((count) => count - 1);+ });+ };+ const clearProjectOverrides = () => {+ if (writeInFlight.current) return;+ const writes = planMobileScopedSettingsClear(targets, PAGE_PROJECT_KEYS[props.page]);+ if (writes.length === 0) return;+ writeInFlight.current = true;+ setPendingTargets(targets);+ setPendingWrites((count) => count + 1);+ void Promise.allSettled(+ writes.map((entry) =>+ updateSettings({ environmentId: entry.environmentId, input: { patch: entry.patch } }),+ ),+ ).finally(() => {+ writeInFlight.current = false;+ setPendingTargets(null);+ setPendingWrites((count) => count - 1);+ });+ };+ const supportsProjectOverrides = targets.every(+ (target) =>+ target.environment.serverConfig.environment.capabilities.projectSettingsOverrides === true,+ );+ const disabled =+ pendingWrites > 0 || !hasConnectedSelection || (projectSelected && !supportsProjectOverrides);+ const supportsContinuation = targets.every(+ (target) =>+ target.environment.serverConfig.environment.capabilities.threadRestartContinuation === true,+ );+ const disabledFor = (key: string) =>+ disabled ||+ (projectSelected &&+ !PROJECT_SCOPED_SERVER_SETTING_KEYS.includes(+ key as (typeof PROJECT_SCOPED_SERVER_SETTING_KEYS)[number],+ ));++ return (+ <>+ <SettingsEnvironmentFilterHeader />+ <SettingsScreen+ title={PAGE_TITLES[props.page]}+ trailing={<AndroidSettingsEnvironmentFilter />}+ >+ <ScrollView+ contentInsetAdjustmentBehavior="automatic"+ showsVerticalScrollIndicator={false}+ className="flex-1"+ contentContainerClassName="gap-6 px-5 pt-4"+ contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}+ >+ {!hasConnectedSelection || reference === null ? (+ <Text className="px-2 text-base text-foreground-muted">+ {projectSelected+ ? "Select a project with a checkout on a connected environment."+ : "Use the filter above to select a connected environment."}+ </Text>+ ) : (+ <>+ {projectSelected ? (+ <SettingsProjectOverridesSection+ projectLabel={selectedProject?.label ?? "Unavailable project"}+ hasOverrides={targets.some((target) =>+ PAGE_PROJECT_KEYS[props.page].some((key) => target.sources[key] === "project"),+ )}+ supportsOverrides={supportsProjectOverrides}+ pending={pendingWrites > 0}+ onClear={clearProjectOverrides}+ />+ ) : null}+ {props.page === "new-threads" ? (+ <>+ <SettingsSection+ title="Default workspace"+ trailing={+ pendingWrites === 0 && uniform("defaultThreadEnvMode") === null ? (+ <MixedValuesLabel projectSelected={projectSelected} />+ ) : null+ }+ >+ {WORKSPACE_CHOICES.map((choice, index) => (+ <ChoiceRow+ key={choice.mode}+ label={choice.label}+ description={choice.description}+ selected={uniform("defaultThreadEnvMode") === choice.mode}+ separated={index > 0}+ disabled={disabledFor("defaultThreadEnvMode")}+ onPress={() => write({ defaultThreadEnvMode: choice.mode })}+ />+ ))}+ </SettingsSection>+ <SettingsSection+ title="Default permissions"+ trailing={+ pendingWrites === 0 && uniform("defaultRuntimeMode") === null ? (+ <MixedValuesLabel projectSelected={projectSelected} />+ ) : null+ }+ >+ {RUNTIME_MODE_CHOICES.map((choice, index) => (+ <ChoiceRow+ key={choice.mode}+ label={choice.label}+ description={choice.description}+ selected={uniform("defaultRuntimeMode") === choice.mode}+ separated={index > 0}+ disabled={disabledFor("defaultRuntimeMode")}+ onPress={() => write({ defaultRuntimeMode: choice.mode })}+ />+ ))}+ </SettingsSection>+ </>+ ) : null}++ {props.page === "source-control" ? (+ <>+ <SettingsSection title="Default branch">+ <FanoutSwitchRow+ icon="arrow.down.circle"+ label="Automatically pull"+ subtitle="Keep the default branch current when there are no local changes."+ value={uniform("defaultAutoPull")}+ disabled={disabledFor("defaultAutoPull")}+ onValueChange={(value) => write({ defaultAutoPull: value })}+ />+ </SettingsSection>+ <SettingsSection title="Worktrees">+ <FanoutSwitchRow+ icon="arrow.triangle.branch"+ label="Start from origin"+ subtitle="Base new worktrees on the remote branch."+ value={uniform("newWorktreesStartFromOrigin")}+ disabled={disabledFor("newWorktreesStartFromOrigin")}+ onValueChange={(value) => write({ newWorktreesStartFromOrigin: value })}+ />+ </SettingsSection>+ </>+ ) : null}++ {props.page === "agent-behavior" ? (+ <>+ <SettingsSection+ title="Response streaming"+ trailing={+ pendingWrites === 0 && uniform("responseStreamingMode") === null ? (+ <MixedValuesLabel projectSelected={projectSelected} />+ ) : null+ }+ >+ {STREAMING_CHOICES.map((choice, index) => (+ <ChoiceRow+ key={choice.mode}+ label={choice.label}+ description={choice.description}+ selected={uniform("responseStreamingMode") === choice.mode}+ separated={index > 0}+ disabled={disabledFor("responseStreamingMode")}+ onPress={() => {+ if (choice.mode !== "token") {+ write({ responseStreamingMode: choice.mode });+ return;+ }+ Alert.alert(+ "Use legacy token streaming?",+ "Repainting every token can make the app slower.",+ [+ { text: "Cancel", style: "cancel" },+ {+ text: "Use token streaming",+ onPress: () => write({ responseStreamingMode: "token" }),+ },+ ],+ );+ }}+ />+ ))}+ </SettingsSection>+ <SettingsSection title="Preview browser">+ <FanoutSwitchRow+ icon="globe"+ label="Agent browser access"+ subtitle="Allow agents to use the in-app preview browser."+ value={uniform("enableAgentBrowserAccess")}+ disabled={disabledFor("enableAgentBrowserAccess")}+ onValueChange={(value) => write({ enableAgentBrowserAccess: value })}+ />+ </SettingsSection>+ </>+ ) : null}++ {props.page === "maintenance" ? (+ <SettingsSection title="Updates">+ <FanoutSwitchRow+ icon="arrow.clockwise"+ label="Check provider updates"+ subtitle={+ projectSelected+ ? "Environment-wide setting. Select All projects to change it."+ : "Check installed provider CLIs for newer versions."+ }+ value={uniform("enableProviderUpdateChecks")}+ disabled={disabledFor("enableProviderUpdateChecks")}+ onValueChange={(value) => write({ enableProviderUpdateChecks: value })}+ />+ <View className="border-t border-border-subtle">+ <FanoutSwitchRow+ icon="arrow.uturn.forward"+ label="Continue after restart"+ subtitle={+ supportsContinuation+ ? "Resume interrupted threads after an update or restart."+ : "Update older servers to control restart continuation."+ }+ value={uniform("continueThreadsAfterServerUpdate")}+ disabled={+ disabledFor("continueThreadsAfterServerUpdate") || !supportsContinuation+ }+ onValueChange={(value) => write({ continueThreadsAfterServerUpdate: value })}+ />+ </View>+ </SettingsSection>+ ) : null}+ </>+ )}+ </ScrollView>+ </SettingsScreen>+ </>+ );+}++function ChoiceRow(props: {+ readonly label: string;+ readonly description: string;+ readonly selected: boolean;+ readonly separated: boolean;+ readonly disabled: boolean;+ readonly onPress: () => void;+}) {+ return (+ <Pressable+ accessibilityRole="radio"+ accessibilityState={{ checked: props.selected, disabled: props.disabled }}+ className={+ props.separated+ ? "flex-row items-center gap-4 border-t border-border-subtle p-4 active:opacity-70"+ : "flex-row items-center gap-4 p-4 active:opacity-70"+ }+ disabled={props.disabled}+ onPress={props.onPress}+ >+ <View className="min-w-0 flex-1 gap-1">+ <Text+ className={+ Platform.OS === "android" ? "text-base text-foreground" : "text-lg text-foreground"+ }+ >+ {props.label}+ </Text>+ <Text className="text-sm leading-normal text-foreground-muted">{props.description}</Text>+ </View>+ {props.selected ? (+ <SymbolView+ name="checkmark"+ size={18}+ tintColorClassName="accent-icon"+ type="monochrome"+ weight="semibold"+ />+ ) : null}+ </Pressable>+ );+}++function MixedValuesLabel(props: { readonly projectSelected: boolean }) {+ return (+ <Text+ accessibilityLabel={+ props.projectSelected+ ? "Selected project checkouts use different values"+ : "Selected environments use different values"+ }+ className="px-2 text-sm text-foreground-muted android:px-4"+ >+ Mixed+ </Text>+ );+}++function FanoutSwitchRow(props: {+ readonly icon: ComponentProps<typeof SymbolView>["name"];+ readonly label: string;+ readonly subtitle: string;+ readonly value: boolean | null;+ readonly disabled: boolean;+ readonly onValueChange: (value: boolean) => void;+}) {+ if (props.value !== null) {+ return (+ <SettingsSwitchRow+ icon={props.icon}+ label={props.label}+ subtitle={props.subtitle}+ value={props.value}+ disabled={props.disabled}+ onValueChange={props.onValueChange}+ />+ );+ }++ return (+ <View className="flex-row items-center gap-4 p-4">+ <SymbolView name={props.icon} size={22} tintColorClassName="accent-icon" />+ <View className="min-w-0 flex-1 gap-1">+ <Text className="text-lg text-foreground">{props.label}</Text>+ <Text className="text-sm text-foreground-muted">{props.subtitle}</Text>+ </View>+ <Pressable+ accessibilityLabel={`Set ${props.label} on for selected environments`}+ accessibilityRole="button"+ disabled={props.disabled}+ className="rounded-full bg-subtle px-3 py-2 active:opacity-70 disabled:opacity-40"+ onPress={() => props.onValueChange(true)}+ >+ <Text className="text-sm font-t3-medium text-foreground">Mixed · Set on</Text>+ </Pressable>+ </View>+ );+}diff --git a/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsxnew file mode 100644index 00000000000..bd8ec325215--- /dev/null+++ b/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx@@ -0,0 +1,266 @@+import { AutoSettleDaysField } from "./components/AutoSettleDaysField";+import { ScreenScrollView as ScrollView } from "../../components/ScreenScrollView";+import { useAtomSet, useAtomValue } from "@effect/atom-react";+import { AsyncResult } from "effect/unstable/reactivity";+import { useRef, useState } from "react";+import { Platform, Pressable, View } from "react-native";+import { useSafeAreaInsets } from "react-native-safe-area-context";++import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";+import { supportsSharedSettingsSync } from "@t3tools/client-runtime/state/shared-settings";+import { AppText as Text } from "../../components/AppText";+import { cn } from "../../lib/cn";+import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";+import { serverEnvironment } from "../../state/server";+import { useAtomCommand } from "../../state/use-atom-command";+import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";+import { SettingsSection } from "./components/SettingsSection";+import { SettingsProjectOverridesSection } from "./components/SettingsProjectOverridesSection";+import { SettingsSwitchRow } from "./components/SettingsSwitchRow";+import { SettingsScreen } from "./components/SettingsScreen";+import {+ AndroidSettingsEnvironmentFilter,+ SettingsEnvironmentFilterHeader,+} from "./components/SettingsEnvironmentFilterHeader";+import { planAutoSettleSettingsSync, type AutoSettleSettings } from "./autoSettleSettingsSync";+import { useSettingsEnvironmentFilter } from "./settings-environment-filter";+import {+ planMobileScopedSettingsClear,+ planMobileScopedSettingsPatch,+ resolveMobileSettingsTargets,+ type ScopedMobileSettingsTarget,+} from "./settings-scoped-server";++export function SettingsThreadsRouteScreen() {+ const insets = useSafeAreaInsets();++ return (+ <>+ <SettingsEnvironmentFilterHeader />+ <SettingsScreen title="Thread behavior" trailing={<AndroidSettingsEnvironmentFilter />}>+ <ScrollView+ contentInsetAdjustmentBehavior="automatic"+ showsVerticalScrollIndicator={false}+ className="flex-1"+ contentContainerClassName="gap-6 px-5 pt-4"+ contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}+ >+ <AutoSettleSettingsRows />+ <LegacySettingsSection />+ </ScrollView>+ </SettingsScreen>+ </>+ );+}++const AUTO_SETTLE_DEFAULT_DAYS = DEFAULT_SERVER_SETTINGS.sidebarAutoSettleAfterDays ?? 3;++/**+ * Mobile edits auto-settle defaults across selected capable targets.+ */+function AutoSettleSettingsRows() {+ const { selectedTargets, projectGroups, selectedProjectKey } = useSettingsEnvironmentFilter();+ const selectedProject = projectGroups.find((group) => group.key === selectedProjectKey);+ const projectSelected = selectedProjectKey !== null;+ const [pendingWrites, setPendingWrites] = useState(0);+ const writeInFlight = useRef(false);+ const [pendingTargets, setPendingTargets] = useState<+ readonly ScopedMobileSettingsTarget[] | null+ >(null);+ const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {+ label: "server settings update",+ reportFailure: true,+ });++ const syncEnvironments = selectedTargets.filter(supportsSharedSettingsSync);+ const syncTargets = resolveMobileSettingsTargets(+ syncEnvironments,+ projectSelected ? (selectedProject?.members.map((member) => member.project) ?? []) : null,+ );+ const displayTargets =+ pendingWrites > 0 && pendingTargets !== null ? pendingTargets : syncTargets;+ const reference = displayTargets[0] ?? null;+ const referenceSettings = reference?.settings ?? null;++ if (reference === null || referenceSettings === null) {+ return null;+ }++ const writeToAll = (patch: Partial<AutoSettleSettings>) => {+ if (writeInFlight.current) return;+ const writes = planMobileScopedSettingsPatch(syncTargets, projectSelected, patch);+ if (writes.length === 0) return;+ writeInFlight.current = true;+ setPendingTargets(syncTargets);+ setPendingWrites((count) => count + 1);+ void Promise.allSettled(+ writes.map((entry) =>+ updateSettings({ environmentId: entry.environmentId, input: { patch: entry.patch } }),+ ),+ ).finally(() => {+ writeInFlight.current = false;+ setPendingTargets(null);+ setPendingWrites((count) => count - 1);+ });+ };++ const { patch: autoSettlePatch, mismatches } = planAutoSettleSettingsSync(+ {+ environmentId: reference.environment.environmentId,+ projectId: reference.projectId,+ settings: referenceSettings,+ },+ displayTargets.map((target) => ({+ environmentId: target.environment.environmentId,+ projectId: target.projectId,+ label: target.environment.label,+ settings: target.settings,+ })),+ );++ const supportsProjectOverrides = syncTargets.every(+ (target) =>+ target.environment.serverConfig.environment.capabilities.projectSettingsOverrides === true,+ );+ const disabled = pendingWrites > 0 || (projectSelected && !supportsProjectOverrides);+ const hasProjectOverrides =+ projectSelected &&+ syncTargets.some(+ (target) =>+ target.sources.sidebarAutoSettleOnMerge === "project" ||+ target.sources.sidebarAutoSettleAfterDays === "project",+ );+ const clearProjectOverrides = () => {+ if (writeInFlight.current) return;+ const writes = planMobileScopedSettingsClear(syncTargets, [+ "sidebarAutoSettleOnMerge",+ "sidebarAutoSettleAfterDays",+ ]);+ if (writes.length === 0) return;+ writeInFlight.current = true;+ setPendingTargets(syncTargets);+ setPendingWrites((count) => count + 1);+ void Promise.allSettled(+ writes.map((entry) =>+ updateSettings({ environmentId: entry.environmentId, input: { patch: entry.patch } }),+ ),+ ).finally(() => {+ writeInFlight.current = false;+ setPendingTargets(null);+ setPendingWrites((count) => count - 1);+ });+ };++ const afterDays = referenceSettings.sidebarAutoSettleAfterDays;++ return (+ <View className="gap-6">+ {projectSelected ? (+ <SettingsProjectOverridesSection+ projectLabel={selectedProject?.label ?? "Unavailable project"}+ hasOverrides={hasProjectOverrides}+ supportsOverrides={supportsProjectOverrides}+ pending={pendingWrites > 0}+ onClear={clearProjectOverrides}+ />+ ) : null}+ <SettingsSection title="Auto-settle">+ <SettingsSwitchRow+ icon="arrow.triangle.branch"+ label="Auto-settle merged threads"+ value={referenceSettings.sidebarAutoSettleOnMerge}+ disabled={disabled}+ onValueChange={(value) => writeToAll({ sidebarAutoSettleOnMerge: value })}+ />+ <SettingsSwitchRow+ icon="clock"+ label="Auto-settle inactive threads"+ value={afterDays !== null}+ disabled={disabled}+ onValueChange={(value) =>+ writeToAll({ sidebarAutoSettleAfterDays: value ? AUTO_SETTLE_DEFAULT_DAYS : null })+ }+ />+ {afterDays !== null ? (+ <View+ className={cn(+ "flex-row items-center gap-4 px-4",+ Platform.OS === "android" ? "min-h-14 py-3" : "py-4",+ )}+ >+ <View style={{ width: Platform.OS === "android" ? 24 : 22 }} />+ <Text+ className={cn(+ "flex-1 text-foreground",+ Platform.OS === "android" ? "text-base" : "text-lg",+ )}+ >+ Inactive days+ </Text>+ <AutoSettleDaysField+ value={afterDays}+ disabled={disabled}+ onValueChange={(value) => writeToAll({ sidebarAutoSettleAfterDays: value })}+ />+ </View>+ ) : null}+ </SettingsSection>+ {pendingWrites === 0 && mismatches.length > 0 ? (+ <SettingsSection title="Across environments">+ <View className="gap-3 p-4">+ <Text className="text-base text-foreground">Auto-settle defaults differ</Text>+ <Text className="text-sm text-foreground-muted">+ {mismatches.map((mismatch) => mismatch.label).join(", ")}+ </Text>+ <Pressable+ accessibilityRole="button"+ disabled={disabled}+ onPress={() => writeToAll(autoSettlePatch)}+ className="self-start rounded-full bg-subtle px-4 py-2 active:opacity-70"+ >+ <Text className="text-sm font-t3-medium text-foreground">+ Apply auto-settle defaults+ </Text>+ </Pressable>+ </View>+ </SettingsSection>+ ) : null}+ </View>+ );+}++/**+ * Device-local legacy toggles. Mobile has no client-settings sync, so this is+ * the counterpart of web's Settings → General → Legacy features backed by+ * mobile preferences.+ */+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">+ <SettingsSection title="Legacy">+ <SettingsSwitchRow+ icon="sidebar.left"+ label="Legacy Thread List"+ 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">+ 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/settings/autoSettleSettingsSync.test.ts b/apps/mobile/src/features/settings/autoSettleSettingsSync.test.tsindex ec550725adc..996ebbd4979 100644--- a/apps/mobile/src/features/settings/autoSettleSettingsSync.test.ts+++ b/apps/mobile/src/features/settings/autoSettleSettingsSync.test.ts@@ -1,4 +1,4 @@-import { DEFAULT_SERVER_SETTINGS, EnvironmentId } from "@t3tools/contracts";+import { DEFAULT_SERVER_SETTINGS, EnvironmentId, ProjectId } from "@t3tools/contracts";import { describe, expect, it } from "vite-plus/test";import { planAutoSettleSettingsSync } from "./autoSettleSettingsSync";@@ -75,4 +75,18 @@ describe("auto-settle settings sync", () => {expect(plan.mismatches).toEqual([]);});++ it("notices different project checkouts on the same environment", () => {+ const projectReference = { ...reference, projectId: ProjectId.make("one") };+ const otherCheckout = {+ environmentId: reference.environmentId,+ projectId: ProjectId.make("two"),+ label: "Other checkout",+ settings: { ...reference.settings, sidebarAutoSettleAfterDays: null },+ };++ expect(planAutoSettleSettingsSync(projectReference, [otherCheckout]).mismatches).toEqual([+ otherCheckout,+ ]);+ });});diff --git a/apps/mobile/src/features/settings/autoSettleSettingsSync.ts b/apps/mobile/src/features/settings/autoSettleSettingsSync.tsindex 6addfa381fd..bbaaaa23d5b 100644--- a/apps/mobile/src/features/settings/autoSettleSettingsSync.ts+++ b/apps/mobile/src/features/settings/autoSettleSettingsSync.ts@@ -1,4 +1,4 @@-import type { EnvironmentId, ServerSettings } from "@t3tools/contracts";+import type { EnvironmentId, ProjectId, ServerSettings } from "@t3tools/contracts";export type AutoSettleSettings = Pick<ServerSettings,@@ -7,13 +7,18 @@ export type AutoSettleSettings = Pick<interface AutoSettleSyncTarget {readonly environmentId: EnvironmentId;+ readonly projectId?: ProjectId | null;readonly label: string;readonly settings: AutoSettleSettings | null;}/** Receives connected, capable targets. Applying these defaults must preserve other settings. */export function planAutoSettleSettingsSync(- reference: { readonly environmentId: EnvironmentId; readonly settings: AutoSettleSettings },+ reference: {+ readonly environmentId: EnvironmentId;+ readonly projectId?: ProjectId | null;+ readonly settings: AutoSettleSettings;+ },targets: readonly AutoSettleSyncTarget[],) {const patch: AutoSettleSettings = {@@ -22,7 +27,8 @@ export function planAutoSettleSettingsSync(};const mismatches = targets.filter((target) =>- target.environmentId !== reference.environmentId &&+ (target.environmentId !== reference.environmentId ||+ target.projectId !== reference.projectId) &&target.settings !== null &&(target.settings.sidebarAutoSettleAfterDays !== patch.sidebarAutoSettleAfterDays ||target.settings.sidebarAutoSettleOnMerge !== patch.sidebarAutoSettleOnMerge),diff --git a/apps/mobile/src/features/settings/components/AutoSettleDaysField.android.tsx b/apps/mobile/src/features/settings/components/AutoSettleDaysField.android.tsxindex bc9ccafecf7..572812880ad 100644--- a/apps/mobile/src/features/settings/components/AutoSettleDaysField.android.tsx+++ b/apps/mobile/src/features/settings/components/AutoSettleDaysField.android.tsx@@ -10,6 +10,7 @@ import type { AutoSettleDaysFieldProps } from "./AutoSettleDaysField";export function AutoSettleDaysField(props: AutoSettleDaysFieldProps) {const adjust = (amount: number) => {+ if (props.disabled) return;const next = Math.max(MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,Math.min(MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS, props.value + amount),@@ -28,7 +29,7 @@ export function AutoSettleDaysField(props: AutoSettleDaysFieldProps) {<MaterialIconButtonicon="minus"accessibilityLabel="Decrease days before auto-settle"- disabled={props.value <= MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS}+ disabled={props.disabled || props.value <= MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS}onPress={() => adjust(-1)}/><AppText@@ -42,7 +43,7 @@ export function AutoSettleDaysField(props: AutoSettleDaysFieldProps) {<MaterialIconButtonicon="plus"accessibilityLabel="Increase days before auto-settle"- disabled={props.value >= MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS}+ disabled={props.disabled || props.value >= MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS}onPress={() => adjust(1)}/></View>diff --git a/apps/mobile/src/features/settings/components/AutoSettleDaysField.ios.tsx b/apps/mobile/src/features/settings/components/AutoSettleDaysField.ios.tsxindex 19a8998084c..2c77aa55571 100644--- a/apps/mobile/src/features/settings/components/AutoSettleDaysField.ios.tsx+++ b/apps/mobile/src/features/settings/components/AutoSettleDaysField.ios.tsx@@ -2,6 +2,7 @@ import { Button, Host, HStack, Picker, Popover, Text, VStack } from "@expo/ui/swimport {accessibilityLabel,buttonStyle,+ disabled,font,foregroundStyle,frame,@@ -34,11 +35,13 @@ export function AutoSettleDaysField(props: AutoSettleDaysFieldProps) {<Popover.Trigger><ButtononPress={() => {+ if (props.disabled) return;setDraft(props.value);setOpen(true);}}modifiers={[buttonStyle("bordered"),+ disabled(props.disabled),accessibilityLabel(`Days before auto-settle: ${props.value}`),frame({ minWidth: 64, minHeight: 44 }),foregroundStyle(colors["--color-primary"]),@@ -81,7 +84,7 @@ export function AutoSettleDaysField(props: AutoSettleDaysFieldProps) {label="Done"onPress={() => {setOpen(false);- if (draft !== props.value) props.onValueChange(draft);+ if (!props.disabled && draft !== props.value) props.onValueChange(draft);}}modifiers={[foregroundStyle(colors["--color-primary"])]}/>diff --git a/apps/mobile/src/features/settings/components/AutoSettleDaysField.tsx b/apps/mobile/src/features/settings/components/AutoSettleDaysField.tsxindex 096cbaa4f2f..ddbca55b643 100644--- a/apps/mobile/src/features/settings/components/AutoSettleDaysField.tsx+++ b/apps/mobile/src/features/settings/components/AutoSettleDaysField.tsx@@ -9,11 +9,16 @@ import { AppTextInput } from "../../../components/AppText";export interface AutoSettleDaysFieldProps {readonly value: number;readonly onValueChange: (value: number) => void;+ readonly disabled?: boolean;}export function AutoSettleDaysField(props: AutoSettleDaysFieldProps) {const [draft, setDraft] = useState<string | null>(null);const commit = () => {+ if (props.disabled) {+ setDraft(null);+ return;+ }const text = (draft ?? "").trim();setDraft(null);// Validate the whole input; decimals and trailing text must not become whole days.@@ -37,6 +42,7 @@ export function AutoSettleDaysField(props: AutoSettleDaysFieldProps) {onBlur={commit}onSubmitEditing={commit}accessibilityLabel="Days before auto-settle"+ editable={!props.disabled}/>);}diff --git a/apps/mobile/src/features/settings/components/SettingsEnvironmentFilterHeader.tsx b/apps/mobile/src/features/settings/components/SettingsEnvironmentFilterHeader.tsxnew file mode 100644index 00000000000..2c87f0c7182--- /dev/null+++ b/apps/mobile/src/features/settings/components/SettingsEnvironmentFilterHeader.tsx@@ -0,0 +1,187 @@+import { useNavigation } from "@react-navigation/native";+import { Platform, Pressable } from "react-native";++import { ControlPillMenu } from "../../../components/ControlPill";+import { SymbolView } from "../../../components/AppSymbol";+import { NativeStackScreenOptions } from "../../../native/StackHeader";+import { withNativeGlassHeaderItem } from "../../layout/native-glass-header-items";+import { useSettingsEnvironmentFilter } from "../settings-environment-filter";++export function SettingsEnvironmentFilterHeader(props: { readonly closeSettings?: boolean }) {+ const navigation = useNavigation();+ const {+ availableTargets,+ selectedTargets,+ selectedIds,+ selectAll,+ toggleEnvironment,+ selectableProjectGroups,+ selectedProjectKey,+ selectProject,+ } = useSettingsEnvironmentFilter();+ if (Platform.OS !== "ios") return null;++ const filterIcon =+ selectedIds === null && selectedProjectKey === null+ ? "line.3.horizontal.decrease"+ : "line.3.horizontal.decrease.circle.fill";+ const filterVersion = JSON.stringify({+ selection: selectedIds === null ? null : [...selectedIds].sort(),+ targets: availableTargets.map((entry) => [entry.environmentId, entry.label, entry.displayUrl]),+ project: selectedProjectKey,+ projects: selectableProjectGroups.map((group) => [group.key, group.label]),+ });++ return (+ <NativeStackScreenOptions+ optionsVersion={filterVersion}+ options={{+ unstable_headerRightItems: () => [+ withNativeGlassHeaderItem({+ accessibilityLabel: "Filter settings environments and projects",+ icon: { name: filterIcon, type: "sfSymbol" },+ label: "",+ type: "menu",+ menu: {+ title: "Settings scope",+ items: [+ {+ type: "submenu",+ label:+ selectedIds === null+ ? "All environments"+ : `${selectedTargets.length} environments`,+ items: [+ {+ type: "action",+ label: "All connected environments",+ state: selectedIds === null ? "on" : undefined,+ onPress: selectAll,+ },+ ...availableTargets.map((entry) => ({+ type: "action" as const,+ label: entry.label,+ description: entry.displayUrl ?? undefined,+ state:+ selectedIds === null || selectedIds.has(entry.environmentId)+ ? ("on" as const)+ : undefined,+ onPress: () => toggleEnvironment(entry.environmentId),+ })),+ ],+ },+ {+ type: "submenu",+ label:+ selectableProjectGroups.find((group) => group.key === selectedProjectKey)+ ?.label ??+ (selectedProjectKey === null ? "All projects" : "Unavailable project"),+ items: [+ {+ type: "action",+ label: "All projects",+ state: selectedProjectKey === null ? "on" : undefined,+ onPress: () => selectProject(null),+ },+ ...selectableProjectGroups.map((group) => ({+ type: "action" as const,+ label: group.label,+ state: selectedProjectKey === group.key ? ("on" as const) : undefined,+ onPress: () => selectProject(group.key),+ })),+ ],+ },+ ],+ },+ }),+ ...(props.closeSettings+ ? [+ withNativeGlassHeaderItem({+ accessibilityLabel: "Close settings",+ icon: { name: "xmark", type: "sfSymbol" },+ identifier: "settings-close",+ label: "",+ onPress: () => navigation.goBack(),+ type: "button",+ }),+ ]+ : []),+ ],+ }}+ />+ );+}++export function AndroidSettingsEnvironmentFilter() {+ const {+ availableTargets,+ selectedIds,+ selectAll,+ toggleEnvironment,+ selectableProjectGroups,+ selectedProjectKey,+ selectProject,+ } = useSettingsEnvironmentFilter();+ const filterIcon =+ selectedIds === null && selectedProjectKey === null+ ? "line.3.horizontal.decrease"+ : "line.3.horizontal.decrease.circle.fill";++ return (+ <ControlPillMenu+ accessible+ accessibilityRole="button"+ accessibilityLabel="Filter settings environments and projects"+ title="Settings scope"+ actions={[+ {+ id: "all",+ title: "All connected environments",+ state: selectedIds === null ? ("on" as const) : ("off" as const),+ },+ ...availableTargets.map((entry) => ({+ id: `environment:${entry.environmentId}`,+ title: `Environment · ${entry.label}`,+ subtitle: entry.displayUrl ?? undefined,+ state:+ selectedIds === null || selectedIds.has(entry.environmentId)+ ? ("on" as const)+ : ("off" as const),+ })),+ {+ id: "project:all",+ title: "All projects",+ state: selectedProjectKey === null ? ("on" as const) : ("off" as const),+ },+ ...selectableProjectGroups.map((group) => ({+ id: `project:${group.key}`,+ title: `Project · ${group.label}`,+ state: selectedProjectKey === group.key ? ("on" as const) : ("off" as const),+ })),+ ]}+ onPressAction={({ nativeEvent }) => {+ if (nativeEvent.event === "all") selectAll();+ else if (nativeEvent.event === "project:all") selectProject(null);+ else if (nativeEvent.event.startsWith("project:")) {+ const group = selectableProjectGroups.find(+ (entry) => `project:${entry.key}` === nativeEvent.event,+ );+ if (group) selectProject(group.key);+ } else {+ const target = availableTargets.find(+ (entry) => `environment:${entry.environmentId}` === nativeEvent.event,+ );+ if (target) toggleEnvironment(target.environmentId);+ }+ }}+ >+ <Pressable+ accessibilityRole="button"+ accessibilityLabel="Filter settings environments and projects"+ className="size-11 items-center justify-center rounded-full"+ >+ <SymbolView name={filterIcon} size={22} tintColorClassName="accent-icon" />+ </Pressable>+ </ControlPillMenu>+ );+}diff --git a/apps/mobile/src/features/settings/components/SettingsProjectOverridesSection.tsx b/apps/mobile/src/features/settings/components/SettingsProjectOverridesSection.tsxnew file mode 100644index 00000000000..c364e09e36e--- /dev/null+++ b/apps/mobile/src/features/settings/components/SettingsProjectOverridesSection.tsx@@ -0,0 +1,37 @@+import { Pressable, View } from "react-native";++import { AppText as Text } from "../../../components/AppText";+import { SettingsSection } from "./SettingsSection";++export function SettingsProjectOverridesSection(props: {+ readonly projectLabel: string;+ readonly hasOverrides: boolean;+ readonly supportsOverrides: boolean;+ readonly pending: boolean;+ readonly onClear: () => void;+}) {+ return (+ <SettingsSection title="Project">+ <View className="min-h-16 flex-row items-center gap-3 px-4 py-3">+ <Text className="min-w-0 flex-1 text-base text-foreground" numberOfLines={2}>+ {props.projectLabel}+ </Text>+ {!props.pending && props.supportsOverrides && props.hasOverrides ? (+ <Pressable+ accessibilityRole="button"+ accessibilityLabel="Use environment defaults"+ onPress={props.onClear}+ className="px-2 py-2 active:opacity-70"+ >+ <Text className="text-sm font-t3-medium text-primary">Use defaults</Text>+ </Pressable>+ ) : null}+ </View>+ {!props.supportsOverrides ? (+ <Text className="px-4 pb-3 text-sm text-foreground-muted">+ Update the selected environments to edit project overrides.+ </Text>+ ) : null}+ </SettingsSection>+ );+}diff --git a/apps/mobile/src/features/settings/components/SettingsSection.tsx b/apps/mobile/src/features/settings/components/SettingsSection.tsxindex 9dbdc166154..954a2b435a3 100644--- a/apps/mobile/src/features/settings/components/SettingsSection.tsx+++ b/apps/mobile/src/features/settings/components/SettingsSection.tsx@@ -5,6 +5,7 @@ import { AppText as Text } from "../../../components/AppText";export function SettingsSection(props: {readonly title?: string;+ readonly trailing?: ReactNode;readonly children: ReactNode;/** Force the grouped card background; Android otherwise lists options flat. */readonly card?: boolean;@@ -12,15 +13,18 @@ export function SettingsSection(props: {return (<View className="gap-2">{props.title ? (- <Text- className={- Platform.OS === "android"- ? "px-4 text-sm font-t3-medium text-primary"- : "px-2 text-sm font-t3-medium text-foreground-muted"- }- >- {props.title}- </Text>+ <View className="flex-row items-center justify-between gap-3">+ <Text+ className={+ Platform.OS === "android"+ ? "px-4 text-sm font-t3-medium text-primary"+ : "px-2 text-sm font-t3-medium text-foreground-muted"+ }+ >+ {props.title}+ </Text>+ {props.trailing}+ </View>) : null}<ViewclassName={diff --git a/apps/mobile/src/features/settings/components/settings-sheet-targets.ts b/apps/mobile/src/features/settings/components/settings-sheet-targets.tsindex 2ac985a1149..5c8d7384b4c 100644--- a/apps/mobile/src/features/settings/components/settings-sheet-targets.ts+++ b/apps/mobile/src/features/settings/components/settings-sheet-targets.ts@@ -1,7 +1,16 @@export type SettingsSheetTarget =| "SettingsEnvironments"+ | "SettingsNotifications"+ | "SettingsThreads"+ | "SettingsAbout"| "SettingsArchive"| "SettingsAppearance"+ | "SettingsOrganization"+ | "SettingsProjectOverview"+ | "SettingsEnvironmentNewThreads"+ | "SettingsEnvironmentSourceControl"+ | "SettingsEnvironmentAgentBehavior"+ | "SettingsEnvironmentMaintenance"| "SettingsKeyboard"| "SettingsProjectGrouping"| "SettingsClientStorage"diff --git a/apps/mobile/src/features/settings/settings-environment-filter.logic.ts b/apps/mobile/src/features/settings/settings-environment-filter.logic.tsnew file mode 100644index 00000000000..7e349c7eb50--- /dev/null+++ b/apps/mobile/src/features/settings/settings-environment-filter.logic.ts@@ -0,0 +1,15 @@+import type { EnvironmentId } from "@t3tools/contracts";++export function toggleSettingsEnvironment(+ selected: ReadonlySet<EnvironmentId> | null,+ available: readonly { readonly environmentId: EnvironmentId }[],+ toggledId: EnvironmentId,+): ReadonlySet<EnvironmentId> | null {+ const ids = available.map((entry) => entry.environmentId);+ const next = new Set(ids.filter((id) => selected === null || selected.has(id)));+ if (ids.includes(toggledId)) {+ if (next.has(toggledId)) next.delete(toggledId);+ else next.add(toggledId);+ }+ return ids.every((id) => next.has(id)) ? null : next;+}diff --git a/apps/mobile/src/features/settings/settings-environment-filter.test.ts b/apps/mobile/src/features/settings/settings-environment-filter.test.tsnew file mode 100644index 00000000000..3cc2c4227bf--- /dev/null+++ b/apps/mobile/src/features/settings/settings-environment-filter.test.ts@@ -0,0 +1,30 @@+import type { EnvironmentId } from "@t3tools/contracts";+import { describe, expect, it } from "vite-plus/test";++import { toggleSettingsEnvironment } from "./settings-environment-filter.logic";++const first = "first" as EnvironmentId;+const second = "second" as EnvironmentId;+const connected = [{ environmentId: first }, { environmentId: second }];++describe("settings environment filter", () => {+ it("starts with all connected environments and can narrow to either or neither", () => {+ const withoutFirst = toggleSettingsEnvironment(null, connected, first);+ expect([...withoutFirst!]).toEqual([second]);++ const none = toggleSettingsEnvironment(withoutFirst, connected, second);+ expect([...none!]).toEqual([]);++ const onlyFirst = toggleSettingsEnvironment(none, connected, first);+ expect([...onlyFirst!]).toEqual([first]);++ expect(toggleSettingsEnvironment(onlyFirst, connected, second)).toBeNull();+ });++ it("drops environments that are no longer connected when the selection changes", () => {+ const onlyFirst = new Set([first]);+ expect(toggleSettingsEnvironment(onlyFirst, [{ environmentId: second }], first)).toEqual(+ new Set(),+ );+ });+});diff --git a/apps/mobile/src/features/settings/settings-environment-filter.tsx b/apps/mobile/src/features/settings/settings-environment-filter.tsxnew file mode 100644index 00000000000..e82991262d1--- /dev/null+++ b/apps/mobile/src/features/settings/settings-environment-filter.tsx@@ -0,0 +1,100 @@+import type { EnvironmentId } from "@t3tools/contracts";+import { buildProjectGroups } from "@t3tools/client-runtime/state/project-grouping";+import { createContext, useContext, useMemo, useState, type ReactNode } from "react";++import { useEnvironments, type EnvironmentPresentation } from "../../state/environments";+import { useProjects } from "../../state/entities";+import { useMobileProjectGroupingSettings } from "../../state/project-grouping";+import { toggleSettingsEnvironment } from "./settings-environment-filter.logic";++export type SettingsTarget = EnvironmentPresentation & {+ readonly serverConfig: NonNullable<EnvironmentPresentation["serverConfig"]>;+};++function connectedSettingsTargets(environments: readonly EnvironmentPresentation[]) {+ return environments.filter(+ (entry): entry is SettingsTarget =>+ entry.connection.phase === "connected" && entry.serverConfig !== null,+ );+}++const SettingsEnvironmentFilterContext = createContext<{+ readonly availableTargets: readonly SettingsTarget[];+ readonly selectedTargets: readonly SettingsTarget[];+ readonly selectedIds: ReadonlySet<EnvironmentId> | null;+ readonly projectGroups: ReturnType<typeof buildProjectGroups>;+ readonly selectableProjectGroups: ReturnType<typeof buildProjectGroups>;+ readonly selectedProjectKey: string | null;+ readonly selectProject: (projectKey: string | null) => void;+ readonly selectAll: () => void;+ readonly toggleEnvironment: (environmentId: EnvironmentId) => void;+} | null>(null);++export function SettingsEnvironmentFilterProvider(props: { readonly children: ReactNode }) {+ const { environments } = useEnvironments();+ const projects = useProjects();+ const groupingSettings = useMobileProjectGroupingSettings();+ const groupingMode = groupingSettings.sidebarProjectGroupingMode;+ const [selectedIds, setSelectedIds] = useState<ReadonlySet<EnvironmentId> | null>(null);+ const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);+ const projectGroups = useMemo(+ () =>+ buildProjectGroups({+ projects,+ settings: { sidebarProjectGroupingMode: groupingMode, sidebarProjectGroupingOverrides: {} },+ }),+ [projects, groupingMode],+ );+ const availableTargets = useMemo(() => connectedSettingsTargets(environments), [environments]);+ const selectedTargets = useMemo(+ () =>+ availableTargets.filter(+ (entry) => selectedIds === null || selectedIds.has(entry.environmentId),+ ),+ [availableTargets, selectedIds],+ );+ const selectableProjectGroups = useMemo(+ () =>+ projectGroups.filter((group) =>+ group.members.some((member) =>+ selectedTargets.some((target) => target.environmentId === member.project.environmentId),+ ),+ ),+ [projectGroups, selectedTargets],+ );+ const value = useMemo(+ () => ({+ availableTargets,+ selectedTargets,+ selectedIds,+ projectGroups,+ selectableProjectGroups,+ selectedProjectKey,+ selectProject: setSelectedProjectKey,+ selectAll: () => setSelectedIds(null),+ toggleEnvironment: (environmentId: EnvironmentId) =>+ setSelectedIds((current) =>+ toggleSettingsEnvironment(current, availableTargets, environmentId),+ ),+ }),+ [+ availableTargets,+ selectedTargets,+ selectedIds,+ projectGroups,+ selectableProjectGroups,+ selectedProjectKey,+ ],+ );+ return (+ <SettingsEnvironmentFilterContext value={value}>+ {props.children}+ </SettingsEnvironmentFilterContext>+ );+}++export function useSettingsEnvironmentFilter() {+ const filter = useContext(SettingsEnvironmentFilterContext);+ if (filter === null) throw new Error("Settings environment filter provider is missing.");+ return filter;+}diff --git a/apps/mobile/src/features/settings/settings-scoped-server.test.ts b/apps/mobile/src/features/settings/settings-scoped-server.test.tsnew file mode 100644index 00000000000..dd589cd2038--- /dev/null+++ b/apps/mobile/src/features/settings/settings-scoped-server.test.ts@@ -0,0 +1,94 @@+import {+ DEFAULT_SERVER_SETTINGS,+ type EnvironmentId,+ type ProjectId,+ type ServerSettings,+} from "@t3tools/contracts";+import { describe, expect, it } from "vite-plus/test";++import type { SettingsTarget } from "./settings-environment-filter";+import {+ planMobileScopedSettingsClear,+ planMobileScopedSettingsPatch,+ resolveMobileSettingsTargets,+} from "./settings-scoped-server";++const firstId = "first" as EnvironmentId;+const secondId = "second" as EnvironmentId;+const firstProject = "first-project" as ProjectId;+const secondProject = "second-project" as ProjectId;++function environment(environmentId: EnvironmentId, settings: ServerSettings): SettingsTarget {+ return {+ environmentId,+ serverConfig: {+ settings,+ environment: { capabilities: { projectSettingsOverrides: true } },+ },+ } as SettingsTarget;+}++describe("mobile project settings scope", () => {+ it("edits each checkout's own override without changing either environment default", () => {+ const firstSettings: ServerSettings = {+ ...DEFAULT_SERVER_SETTINGS,+ responseStreamingMode: "paragraph",+ projectSettingsOverrides: { [firstProject]: { defaultAutoPull: true } },+ };+ const secondSettings: ServerSettings = {+ ...DEFAULT_SERVER_SETTINGS,+ responseStreamingMode: "token",+ projectSettingsOverrides: {},+ };+ const targets = resolveMobileSettingsTargets(+ [environment(firstId, firstSettings), environment(secondId, secondSettings)],+ [+ { environmentId: firstId, id: firstProject },+ { environmentId: secondId, id: secondProject },+ ],+ );++ const writes = planMobileScopedSettingsPatch(targets, true, {+ responseStreamingMode: "turn",+ });+ expect(writes).toEqual([+ {+ environmentId: firstId,+ patch: {+ projectSettingsOverrides: {+ [firstProject]: { defaultAutoPull: true, responseStreamingMode: "turn" },+ },+ },+ },+ {+ environmentId: secondId,+ patch: { projectSettingsOverrides: { [secondProject]: { responseStreamingMode: "turn" } } },+ },+ ]);+ expect(firstSettings.responseStreamingMode).toBe("paragraph");+ expect(secondSettings.responseStreamingMode).toBe("token");+ });++ it("resets only the selected page's override and rejects environment-wide writes", () => {+ const settings: ServerSettings = {+ ...DEFAULT_SERVER_SETTINGS,+ projectSettingsOverrides: {+ [firstProject]: { defaultAutoPull: true, responseStreamingMode: "turn" },+ },+ };+ const targets = resolveMobileSettingsTargets(+ [environment(firstId, settings)],+ [{ environmentId: firstId, id: firstProject }],+ );++ expect(planMobileScopedSettingsClear(targets, ["responseStreamingMode"])).toEqual([+ {+ environmentId: firstId,+ patch: { projectSettingsOverrides: { [firstProject]: { defaultAutoPull: true } } },+ },+ ]);+ expect(+ planMobileScopedSettingsPatch(targets, true, { enableProviderUpdateChecks: false }),+ ).toEqual([]);+ });+});diff --git a/apps/mobile/src/features/settings/settings-scoped-server.ts b/apps/mobile/src/features/settings/settings-scoped-server.tsnew file mode 100644index 00000000000..53cc44a7ee1--- /dev/null+++ b/apps/mobile/src/features/settings/settings-scoped-server.ts@@ -0,0 +1,106 @@+import {+ PROJECT_SCOPED_SERVER_SETTING_KEYS,+ type EnvironmentId,+ type ProjectId,+ type ProjectScopedServerSettingKey,+ type ServerSettings,+ type ServerSettingsPatch,+} from "@t3tools/contracts";+import {+ clearProjectSettingsOverrides,+ resolveProjectSettings,+} from "@t3tools/shared/projectSettings";++import type { SettingsTarget } from "./settings-environment-filter";++export interface ScopedMobileSettingsTarget {+ readonly environment: SettingsTarget;+ readonly projectId: ProjectId | null;+ readonly settings: ServerSettings;+ readonly sources: ReturnType<typeof resolveProjectSettings>["sources"];+}++export function resolveMobileSettingsTargets(+ environments: readonly SettingsTarget[],+ members: readonly { readonly environmentId: EnvironmentId; readonly id: ProjectId }[] | null,+): readonly ScopedMobileSettingsTarget[] {+ if (members === null) {+ return environments.map((environment) => ({+ environment,+ projectId: null,+ ...resolveProjectSettings(environment.serverConfig.settings, null),+ }));+ }+ const byId = new Map(environments.map((environment) => [environment.environmentId, environment]));+ return members.flatMap((member) => {+ const environment = byId.get(member.environmentId);+ if (!environment) return [];+ return [+ {+ environment,+ projectId: member.id,+ ...resolveProjectSettings(environment.serverConfig.settings, member.id),+ },+ ];+ });+}++export function planMobileScopedSettingsPatch(+ targets: readonly ScopedMobileSettingsTarget[],+ projectSelected: boolean,+ patch: ServerSettingsPatch,+) {+ if (!projectSelected) {+ return targets.map((target) => ({ environmentId: target.environment.environmentId, patch }));+ }+ const keys = Object.keys(patch);+ if (+ keys.some(+ (key) => !PROJECT_SCOPED_SERVER_SETTING_KEYS.includes(key as ProjectScopedServerSettingKey),+ )+ )+ return [];+ const writes = new Map<EnvironmentId, Record<string, unknown>>();+ for (const target of targets) {+ if (+ target.projectId === null ||+ target.environment.serverConfig.environment.capabilities.projectSettingsOverrides !== true+ )+ continue;+ const current =+ target.environment.serverConfig.settings.projectSettingsOverrides[target.projectId] ?? {};+ const next = { ...current, ...patch };+ const overrides = writes.get(target.environment.environmentId) ?? {};+ overrides[target.projectId] = next;+ writes.set(target.environment.environmentId, overrides);+ }+ return [...writes].map(([environmentId, projectSettingsOverrides]) => ({+ environmentId,+ patch: { projectSettingsOverrides } as ServerSettingsPatch,+ }));+}++export function planMobileScopedSettingsClear(+ targets: readonly ScopedMobileSettingsTarget[],+ keys: readonly ProjectScopedServerSettingKey[],+) {+ const writes = new Map<EnvironmentId, Record<string, unknown>>();+ for (const target of targets) {+ if (+ target.projectId === null ||+ target.environment.serverConfig.environment.capabilities.projectSettingsOverrides !== true+ )+ continue;+ const overrides = writes.get(target.environment.environmentId) ?? {};+ overrides[target.projectId] = clearProjectSettingsOverrides(+ target.environment.serverConfig.settings,+ target.projectId,+ keys,+ );+ writes.set(target.environment.environmentId, overrides);+ }+ return [...writes].map(([environmentId, projectSettingsOverrides]) => ({+ environmentId,+ patch: { projectSettingsOverrides } as ServerSettingsPatch,+ }));+}diff --git a/docs/user/appearance.md b/docs/user/appearance.mdindex fc7842903e0..ff9c2746bf8 100644--- a/docs/user/appearance.md+++ b/docs/user/appearance.md@@ -1,8 +1,9 @@# Appearance and themes-Open **Settings → Appearance** to choose a theme and follow the system appearance or stay in light-or dark mode. To use different themes for light and dark mode, select the corresponding preview-within each theme. Appearance preferences are saved separately on each device or browser.+On web and desktop, open **Settings → Appearance** to choose a theme and follow the system+appearance or stay in light or dark mode. To use different themes for light and dark mode, select+the corresponding preview within each theme. Appearance preferences are saved separately on each+device or browser.On web and desktop, use **Change theme** in the command palette to select a theme without leaving chat.Press **Cmd+Option+A** on macOS or **Ctrl+Alt+A** on Windows/Linux to open the theme picker directly.@@ -10,8 +11,8 @@ Use **Change appearance** in the command palette to choose System, Light, or Darthe theme. **Cmd+Option+Shift+A** on macOS or **Ctrl+Alt+Shift+A** on Windows/Linux cycles throughthose modes. Customize these shortcuts under **Settings → Keybindings**.-Mobile has its own themes and text, code, and terminal preferences. It does not follow environment-themes or defaults.+On mobile, open **Settings → Appearance**. Mobile has its own themes and text,+code, and terminal preferences. It does not follow environment themes or defaults.On Android 12 or newer, choose the **Material You** theme in Appearance to use colors fromyour wallpaper. Selecting another theme replaces those colors. Like other themes, Material Youdiff --git a/docs/user/mobile-notifications.md b/docs/user/mobile-notifications.mdindex 3a8d61d1cb7..9c5e30ef760 100644--- a/docs/user/mobile-notifications.md+++ b/docs/user/mobile-notifications.md@@ -1,6 +1,6 @@# Mobile notifications-Sign in to T3 Connect, link your environments, and enable **Device Notifications** in Settings to receive alerts when an agent finishes, fails, needs approval, or asks for input. Tap a notification to open its thread. Your environment must have agent activity publishing enabled.+Sign in to T3 Connect, link your environments, and enable **Device Notifications** in **Settings → Notifications** to receive alerts when an agent finishes, fails, needs approval, or asks for input. Tap a notification to open its thread. Your environment must have agent activity publishing enabled.Enable **Ongoing Agent Activity** on Android or **Live Activity Updates** on iOS to follow work without opening the app. Finished results remain visible for up to 15 minutes. You can dismiss an Android activity card without disabling alerts; turn off ongoing activity in Settings to stop future cards.diff --git a/docs/user/open-source-licenses.md b/docs/user/open-source-licenses.mdindex 2c99bc46fb1..bc1854aba5d 100644--- a/docs/user/open-source-licenses.md+++ b/docs/user/open-source-licenses.md@@ -5,7 +5,7 @@ notices:- On web and desktop, open **Settings → General**, find **Open source licenses** under **About**,and select **View licenses**.-- On mobile, open **Settings → App → Open source licenses**.+- On mobile, open **Settings → About T3 Code → Open source licenses**.The page lists the version when available, license identifier, and the parts of T3 Code that includeor use the item. This also covers optional device tools that T3 Code installs on demand instead ofdiff --git a/docs/user/project-settings.md b/docs/user/project-settings.mdindex f250e223f59..0d5d7e66b1f 100644--- a/docs/user/project-settings.md+++ b/docs/user/project-settings.md@@ -1,6 +1,6 @@# Settings and project overrides-The Settings breadcrumb ends with the environment and project a change applies to. They start+On web and desktop, the Settings breadcrumb ends with the environment and project a change applies to. They startat **All environments** and **All projects** and stay selected as you move between categories orsearch for a setting.@@ -26,6 +26,17 @@ again.Providers and diagnostics are per machine: they show one environment at a time, the primaryone until you pick another. Every other setting fans out to the selection.+On mobile, open **Settings** and use the filter in its header to choose connected environments+and a project. The filter stays available in server-setting pages. With **All projects** selected,+the **Server settings** categories and auto-settle controls in **Thread behavior** edit the+selected environments' defaults. Choosing a project edits its overrides on the selected+environments. Use **Use defaults** in a page to remove that page's project overrides.+Open **Settings → Projects & threads → Overview** to rename the project across its selected+connected checkouts and see where those checkouts live.+Settings that are environment-wide stay read-only while a project is selected. When selected+targets disagree, a control shows **Mixed** until you choose one value. Appearance, keyboard,+and other phone-only settings ignore the filter.+## Defaults and inheritanceGeneral contains the model and workspace for new threads. Integrations controls agent browser@@ -83,6 +94,7 @@ from the icon palette, derived from the saved project name. For example, `NebulaIn Source Control, enable **Automatically pull** to keep the default-branch checkout up to datewith its configured upstream. Choose an environment to set the default or a project to override it.+On mobile, use **Settings → Source control** to change selected environment defaults or project overrides.T3 Code only pulls when it can fast-forward and the checkout has no changed files, untracked files,or local commits. It skips checkouts on another branch or without an upstream. If a checkout hasdiff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.mdindex ee79d6e94fb..650954d7a58 100644--- a/docs/user/thread-sidebar.md+++ b/docs/user/thread-sidebar.md@@ -93,9 +93,9 @@ prevent automatic settlement. An open pull request does not prevent inactivitysettlement, but an old closed or merged pull request does not settle work youresumed after it closed.-Change these rules in **Settings → General**. They continue to run when your apps-are closed. On web and desktop, choose an environment at the top to change only-its rules, or **All environments** to update connected environments together.+Change these rules in **Settings → General** on web and desktop, or **Settings → Thread behavior** on mobile.+They continue to run when your apps are closed. On web and desktop, choose an environment at the+top to change only its rules, or **All environments** to update connected environments together.Mixed values show where the selected environments disagree. Mobile applies theserules to connected environments that support shared settings. Offline environmentsand older servers keep their previous values. Changing a rule does not reopen