TypeScript
feat(mobile): manage environment and provider updates (#13302)
Julius Marminge68fb7f4b8509
diff --git a/.github/workflows/mobile-eas-preview.yml b/.github/workflows/mobile-eas-preview.ymlindex d53602f8f5e..5db69c9befa 100644--- a/.github/workflows/mobile-eas-preview.yml+++ b/.github/workflows/mobile-eas-preview.yml@@ -78,7 +78,19 @@ jobs:working-directory: apps/mobileenv:EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}- run: eas env:pull preview --non-interactive+ run: |+ eas env:pull preview --non-interactive+ # EAS Update disables dotenv loading. Keep the downloaded native config+ # in its process environment so Android build and OTA fingerprints match.+ node --input-type=module <<'NODE'+ import { appendFileSync, readFileSync } from "node:fs";+ import { parseEnv } from "node:util";+ const env = parseEnv(readFileSync(".env.local", "utf8"));+ const googleServicesFile = env.T3CODE_ANDROID_GOOGLE_SERVICES_FILE;+ if (googleServicesFile) {+ appendFileSync(process.env.GITHUB_ENV, `T3CODE_ANDROID_GOOGLE_SERVICES_FILE=${googleServicesFile}\n`);+ }+ NODE- name: Deploy with fingerprint checkif: steps.expo-token.outputs.present == 'true'diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsxindex 524eac86071..7f508f486ce 100644--- a/apps/mobile/src/Stack.tsx+++ b/apps/mobile/src/Stack.tsx@@ -71,6 +71,7 @@ import { SettingsAppearanceRouteScreen } from "./features/settings/SettingsAppeaimport { SettingsClientStorageRouteScreen } from "./features/settings/SettingsClientStorageRouteScreen";import { SettingsDiagnosticsRouteScreen } from "./features/diagnostics/SettingsDiagnosticsRouteScreen";import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen";+import { SettingsEnvironmentDetailRouteScreen } from "./features/settings/SettingsEnvironmentDetailRouteScreen";import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";import {SettingsEnvironmentAgentBehaviorRouteScreen,@@ -193,6 +194,11 @@ const SettingsContentStack = createNativeStackNavigator({title: "Environments",},}),+ SettingsEnvironmentDetail: createNativeStackScreen({+ screen: SettingsEnvironmentDetailRouteScreen,+ linking: "environments/:environmentId",+ options: { title: "Environment" },+ }),SettingsEnvironmentNewThreads: createNativeStackScreen({screen: SettingsEnvironmentNewThreadsRouteScreen,linking: "new-threads",diff --git a/apps/mobile/src/features/connection/CloudEnvironmentRows.tsx b/apps/mobile/src/features/connection/CloudEnvironmentRows.tsxindex 2828392ba8f..d362b78a936 100644--- a/apps/mobile/src/features/connection/CloudEnvironmentRows.tsx+++ b/apps/mobile/src/features/connection/CloudEnvironmentRows.tsx@@ -35,6 +35,7 @@ import { type RelayEnvironmentView, useConnectionController } from "./useConnectinterface CloudEnvironmentRowsProps {readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;+ readonly onOpenEnvironment?: (environmentId: EnvironmentId) => void;readonly onSetEnvironmentEnabled: (environmentId: EnvironmentId, enabled: boolean) => void;/** Long-press on a saved row. The callback owns the confirm. */readonly onRemoveEnvironment: (environmentId: EnvironmentId) => void;@@ -124,26 +125,30 @@ function CloudEnvironmentRowsContent() : null}{hasCloudRows ? (- <View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">- {props.connectedCloudEnvironments.map((environment, index) => (+ <View collapsable={false} className="overflow-hidden rounded-[24px] bg-grouped-card">+ {props.connectedCloudEnvironments.map((environment) => (<ConnectedCloudEnvironmentRowkey={environment.environmentId}environment={environment}descriptor={discoveredDescriptors.get(environment.environmentId)}- borderTop={index !== 0}onSetEnabled={(enabled) =>props.onSetEnvironmentEnabled(environment.environmentId, enabled)}onRemove={() => props.onRemoveEnvironment(environment.environmentId)}+ onOpen={+ props.onOpenEnvironment+ ? () => props.onOpenEnvironment?.(environment.environmentId)+ : undefined+ }errorExpanded={expandedErrorId === environment.environmentId}onToggleError={() => handleToggleCloudError(environment.environmentId)}/>))}- {availableCloudEnvironments.map((environment, index) => (+ {availableCloudEnvironments.map((environment) => (<CloudEnvironmentRowkey={environment.environment.environmentId}environment={environment}- borderTop={props.connectedCloudEnvironments.length > 0 || index !== 0}+ showChevron={props.onOpenEnvironment !== undefined}onConnect={() => handleConnectCloudEnvironment(environment)}errorExpanded={expandedErrorId === environment.environment.environmentId}onToggleError={() => handleToggleCloudError(environment.environment.environmentId)}@@ -151,14 +156,14 @@ function CloudEnvironmentRowsContent())}</View>) : controller.relayDiscovery.isRefreshing ? (- <View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card p-6">+ <View collapsable={false} className="items-center gap-3 rounded-[24px] bg-grouped-card p-6"><ActivityIndicator colorClassName={"accent-icon"} /><Text className="text-center text-sm leading-normal text-foreground-muted">Loading linked cloud environments.</Text></View>) : controller.relayDiscovery.error ? null : (- <View collapsable={false} className="rounded-[24px] bg-card p-5">+ <View collapsable={false} className="rounded-[24px] bg-grouped-card p-5"><Text className="text-sm leading-normal text-foreground-muted">No additional linked cloud environments.</Text>@@ -170,7 +175,7 @@ function CloudEnvironmentRowsContent({discoveryAvailable &&controller.relayDiscovery.error &&!controller.relayDiscovery.isRefreshing ? (- <View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">+ <View collapsable={false} className="gap-3 rounded-[24px] bg-grouped-card p-5"><Text className="text-base font-t3-bold text-foreground">Could not load T3 Connect environments</Text>@@ -202,10 +207,10 @@ function ConnectedCloudEnvironmentRow(props: {readonly environment: ConnectedEnvironmentSummary;/** Discovery's view of the server, for the glyph before the first connection. */readonly descriptor: ExecutionEnvironmentDescriptor | undefined;- readonly borderTop: boolean;readonly errorExpanded: boolean;readonly onSetEnabled: (enabled: boolean) => void;readonly onRemove: () => void;+ readonly onOpen?: (() => void) | undefined;readonly onToggleError: () => void;}) {const serverConfig = useAtomValue(@@ -222,10 +227,13 @@ function ConnectedCloudEnvironmentRow(props: {return (<PressableaccessibilityHint="Long press to remove from this device"+ accessibilityRole={props.onOpen ? "button" : undefined}+ accessibilityLabel={props.onOpen ? `Manage ${props.environment.environmentLabel}` : undefined}+ onPress={props.onOpen}onLongPress={props.onRemove}><CloudEnvironmentRowShell- borderTop={props.borderTop}+ opensDetails={props.onOpen !== undefined}connectionError={enabled || unsupported ? props.environment.connectionError : null}connectionErrorTraceId={enabled ? props.environment.connectionErrorTraceId : null}connectionState={enabled || unsupported ? props.environment.connectionState : "available"}@@ -246,7 +254,7 @@ function ConnectedCloudEnvironmentRow(props: {function CloudEnvironmentRow(props: {readonly environment: RelayEnvironmentView;- readonly borderTop: boolean;+ readonly showChevron: boolean;readonly errorExpanded: boolean;readonly onConnect: () => void;readonly onToggleError: () => void;@@ -260,7 +268,7 @@ function CloudEnvironmentRow(props: {return (<CloudEnvironmentRowShell- borderTop={props.borderTop}+ showChevron={props.showChevron}connectionError={presentation.connectionError}connectionErrorTraceId={presentation.connectionErrorTraceId}connectionState={presentation.connectionState}@@ -285,7 +293,8 @@ function CloudEnvironmentRow(props: {}function CloudEnvironmentRowShell(props: {- readonly borderTop: boolean;+ readonly showChevron?: boolean;+ readonly opensDetails?: boolean;readonly connectionError: string | null;readonly connectionErrorTraceId: string | null;readonly connectionState: EnvironmentConnectionPhase;@@ -340,13 +349,7 @@ function CloudEnvironmentRowShell(props: {[measuredErrorText, props.connectionError],);return (- <View- collapsable={false}- className={cn(- "flex-row items-center gap-3 bg-card px-4 py-3.5",- props.borderTop && "border-t border-border",- )}- >+ <View collapsable={false} className="flex-row items-center gap-3 bg-grouped-card px-4 py-3.5"><View className="min-w-0 flex-1 gap-0.5"><View className="min-w-0 flex-row items-center gap-2"><ConnectionStatusDot state={props.connectionState} pulse={shouldPulse} size={7} />@@ -409,10 +412,16 @@ function CloudEnvironmentRowShell(props: {</StatusContainer></View><ThemedSwitch+ style={{ alignSelf: "center" }}disabled={props.disabled}onValueChange={props.onValueChange}value={props.value}/>+ {props.opensDetails || props.showChevron ? (+ <View style={{ opacity: props.opensDetails ? 1 : 0.4 }}>+ <SymbolView name="chevron.right" size={12} tintColorClassName="accent-icon-subtle" />+ </View>+ ) : null}</View>);}diff --git a/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx b/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsxindex cf90cd42a0a..28b34fdec6d 100644--- a/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx+++ b/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx@@ -35,6 +35,7 @@ function connectionStatusLabel(environment: ConnectedEnvironmentSummary): stringexport function ConnectionEnvironmentRow(props: {readonly environment: ConnectedEnvironmentSummary;readonly expanded: boolean;+ readonly opensDetails?: boolean;readonly onToggle: () => void;readonly onReconnect: (environmentId: EnvironmentId) => void;readonly onRemove: (environmentId: EnvironmentId) => void;@@ -76,19 +77,22 @@ export function ConnectionEnvironmentRow(props: {}, [label, url, props]);return (- <Animated.View layout={LinearTransition.duration(250)} className="bg-card">+ <Animated.View layout={LinearTransition.duration(250)} className="bg-grouped-card"><PressableclassName="flex-row items-center gap-3 px-4 py-3.5 active:opacity-70"+ accessibilityRole="button"+ accessibilityLabel={+ props.opensDetails ? `Manage ${props.environment.environmentLabel}` : undefined+ }onPress={props.onToggle}>- <ConnectionStatusDot- state={enabled || unsupported ? props.environment.connectionState : "available"}- pulse={isRetrying}- size={8}- />-<View className="flex-1 gap-0.5"><View className="flex-row items-center gap-1.5">+ <ConnectionStatusDot+ state={enabled || unsupported ? props.environment.connectionState : "available"}+ pulse={isRetrying}+ size={8}+ /><EnvironmentMachineSymbolkind={resolveEnvironmentMachineKind(serverConfig)}size={14}@@ -101,9 +105,11 @@ export function ConnectionEnvironmentRow(props: {{props.environment.environmentLabel}</Text></View>- <Text className="text-xs text-foreground-muted" numberOfLines={1}>- {props.environment.displayUrl}- </Text>+ {!props.environment.isRelayManaged && props.environment.displayUrl.trim() ? (+ <Text className="text-xs text-foreground-muted" numberOfLines={1}>+ {props.environment.displayUrl}+ </Text>+ ) : null}{statusLabel ? (<TextclassName={cn(@@ -126,12 +132,13 @@ export function ConnectionEnvironmentRow(props: {</View><ThemedSwitch+ style={{ alignSelf: "center" }}disabled={unsupported}onValueChange={(next) => props.onSetEnabled(props.environment.environmentId, next)}value={enabled}/><SymbolView- name="chevron.down"+ name={props.opensDetails ? "chevron.right" : "chevron.down"}size={12}tintColorClassName="accent-icon-subtle"type="monochrome"diff --git a/apps/mobile/src/features/connection/GitHubRoutingSettings.tsx b/apps/mobile/src/features/connection/GitHubRoutingSettings.tsxindex 764a7d1a0d5..3358fa1995d 100644--- a/apps/mobile/src/features/connection/GitHubRoutingSettings.tsx+++ b/apps/mobile/src/features/connection/GitHubRoutingSettings.tsx@@ -43,15 +43,12 @@ export function GitHubRoutingSettings() {return (<View className="mt-5 gap-3"><SettingsSection title="GitHub routing">- {[...catalog.entries.values()].map((entry, index) => {+ {[...catalog.entries.values()].map((entry) => {const environmentId = entry.target.environmentId;const selected = gitHubRoutingPermissionFor(entry, permissions);const disabled = !catalog.isReady || saving || gitHubRoutingConnectionKey(entry) === null;return (- <View- key={environmentId}- className={index === 0 ? undefined : "border-t border-border-subtle"}- >+ <View key={environmentId}><PressableaccessibilityRole="button"accessibilityLabel={`${entry.target.label} GitHub routing`}@@ -83,7 +80,7 @@ export function GitHubRoutingSettings() {accessibilityRole="radio"accessibilityState={{ checked: selected === option.value, disabled }}disabled={disabled}- className="flex-row items-center gap-4 border-t border-border-subtle p-4 disabled:opacity-50"+ className="flex-row items-center gap-4 p-4 disabled:opacity-50"onPress={() => {setSaving(true);void update({ environmentId, permission: option.value }).then((result) => {diff --git a/apps/mobile/src/features/connection/LocalEnvironmentList.tsx b/apps/mobile/src/features/connection/LocalEnvironmentList.tsxindex dca29e092f6..bec038390a9 100644--- a/apps/mobile/src/features/connection/LocalEnvironmentList.tsx+++ b/apps/mobile/src/features/connection/LocalEnvironmentList.tsx@@ -4,7 +4,6 @@ import { View } from "react-native";import { SymbolView } from "../../components/AppSymbol";import { AppText as Text } from "../../components/AppText";-import { cn } from "../../lib/cn";import { ConnectionEnvironmentRow } from "./ConnectionEnvironmentRow";type EnvironmentRowProps = ComponentProps<typeof ConnectionEnvironmentRow>;@@ -15,14 +14,20 @@ export function LocalEnvironmentList({expandedId,onToggle,...rowActions-}: Pick<EnvironmentRowProps, "onReconnect" | "onRemove" | "onSetEnabled" | "onUpdate"> & {+}: Pick<+ EnvironmentRowProps,+ "onReconnect" | "onRemove" | "onSetEnabled" | "onUpdate" | "opensDetails"+> & {readonly environments: ReadonlyArray<EnvironmentRowProps["environment"]>;readonly expandedId: EnvironmentId | null;readonly onToggle: (environmentId: EnvironmentId) => void;}) {if (environments.length === 0) {return (- <View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card px-6 py-8">+ <View+ collapsable={false}+ className="items-center gap-3 rounded-[24px] bg-grouped-card px-6 py-8"+ ><View className="h-12 w-12 items-center justify-center rounded-[16px] bg-subtle"><SymbolViewname="point.3.connected.trianglepath.dotted"@@ -40,13 +45,9 @@ export function LocalEnvironmentList({}return (- <View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">- {environments.map((environment, index) => (- <View- key={environment.environmentId}- collapsable={false}- className={cn(index !== 0 && "border-t border-border")}- >+ <View collapsable={false} className="overflow-hidden rounded-[24px] bg-grouped-card">+ {environments.map((environment) => (+ <View key={environment.environmentId} collapsable={false}><ConnectionEnvironmentRowenvironment={environment}expanded={expandedId === environment.environmentId}diff --git a/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsxnew file mode 100644index 00000000000..be334da900a--- /dev/null+++ b/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx@@ -0,0 +1,341 @@+import { useAtomValue } from "@effect/atom-react";+import type { StaticScreenProps } from "@react-navigation/native";+import type { EnvironmentId, ServerProvider } from "@t3tools/contracts";+import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";+import { AsyncResult } from "effect/unstable/reactivity";+import { useEffect, useRef, useState } from "react";+import { Alert, View } from "react-native";+import { useSafeAreaInsets } from "react-native-safe-area-context";++import { AppText as Text } from "../../components/AppText";+import { ProviderIcon } from "../../components/ProviderIcon";+import { ScreenScrollView } from "../../components/ScreenScrollView";+import { serverEnvironment } from "../../state/server";+import { environmentSession } from "../../state/session";+import { useAtomCommand } from "../../state/use-atom-command";+import { useRemoteConnections } from "../../state/use-remote-environment-registry";+import { ConnectionEnvironmentRow } from "../connection/ConnectionEnvironmentRow";+import { SettingsActionRow } from "./components/SettingsActionRow";+import { SettingsScreen } from "./components/SettingsScreen";+import { SettingsSection } from "./components/SettingsSection";+import {+ canMaintainEnvironment,+ canUpdateEnvironmentProvider,+ findEnvironmentUpdate,+ supportsEnvironmentUpdate,+} from "./environment-maintenance";++export function SettingsEnvironmentDetailRouteScreen({+ route,+}: StaticScreenProps<{+ readonly environmentId: EnvironmentId;+}>) {+ // Key local request state to the host even when navigation reuses this screen.+ return (+ <EnvironmentDetail+ key={route.params.environmentId}+ environmentId={route.params.environmentId}+ />+ );+}++function EnvironmentDetail({ environmentId }: { readonly environmentId: EnvironmentId }) {+ const insets = useSafeAreaInsets();+ const connections = useRemoteConnections();+ const environment = connections.connectedEnvironments.find(+ (entry) => entry.environmentId === environmentId,+ );+ const config = useAtomValue(serverEnvironment.configValueAtom(environmentId));+ const session = useAtomValue(environmentSession.sessionStateValueAtom(environmentId));+ const sessionResult = useAtomValue(environmentSession.sessionStateAtom(environmentId));+ const updateState = useAtomValue(serverEnvironment.updateStateAtom(environmentId));+ const updateServer = useAtomCommand(serverEnvironment.updateServer);+ const updateProvider = useAtomCommand(serverEnvironment.updateProvider);+ const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders);+ const [connectionExpanded, setConnectionExpanded] = useState(false);+ const [pending, setPending] = useState<string | null>(null);+ const pendingRef = useRef(false);+ const [error, setError] = useState<string | null>(null);+ const [notice, setNotice] = useState<string | null>(null);+ const [release, setRelease] = useState<{+ fromVersion: string;+ targetVersion: string | null;+ } | null>(null);+ const checkController = useRef<AbortController | null>(null);+ useEffect(() => () => checkController.current?.abort(), []);++ const connected = environment?.isEnabled === true && environment.connectionState === "connected";+ const allowed =+ !AsyncResult.isFailure(sessionResult) && canMaintainEnvironment(session, connected);+ const running = updateState.status === "running";+ const providerBusy =+ config?.providers.some(+ (provider) =>+ provider.updateState?.status === "running" || provider.updateState?.status === "queued",+ ) ?? false;+ const disabled = !allowed || pending !== null || running || providerBusy;+ const version = config?.environment.serverVersion;+ const checkedRelease = release?.fromVersion === version ? release : null;+ const capabilities = config?.environment.capabilities;++ async function run(label: string, action: () => Promise<void>) {+ if (pendingRef.current) return;+ pendingRef.current = true;+ setPending(label);+ setError(null);+ setNotice(null);+ try {+ await action();+ } catch (cause) {+ setError(+ cause instanceof Error ? cause.message : "The action could not be completed. Try again.",+ );+ } finally {+ pendingRef.current = false;+ setPending(null);+ }+ }++ function requestServerUpdate() {+ const targetVersion = checkedRelease?.targetVersion;+ if (disabled || !targetVersion || !capabilities || !supportsEnvironmentUpdate(capabilities))+ return;+ Alert.alert(+ `Update ${environment?.environmentLabel ?? "environment"}?`,+ `Install T3 Code ${targetVersion}. ${capabilities.serverSelfUpdate === "desktop-managed" ? "The desktop app will close and relaunch." : "The server will restart and reconnect."} Running threads may be interrupted.`,+ [+ { text: "Cancel", style: "cancel" },+ {+ text: "Update",+ onPress: () =>+ void run("server", async () => {+ const result = await updateServer({+ environmentId,+ input: {+ targetVersion,+ ...(capabilities.serverUpdateThreadContinuation &&+ config?.settings.continueThreadsAfterServerUpdate+ ? { continueRunningThreads: true }+ : {}),+ },+ });+ if (AsyncResult.isFailure(result)) throw squashAtomCommandFailure(result);+ setRelease(null);+ setNotice(`Updated to ${result.value.targetVersion}.`);+ }),+ },+ ],+ );+ }++ function requestProviderUpdate(provider: ServerProvider) {+ if (disabled || !canUpdateEnvironmentProvider(provider)) return;+ void run(provider.instanceId, async () => {+ const result = await updateProvider({+ environmentId,+ input: {+ provider: provider.driver,+ instanceId: provider.instanceId,+ },+ });+ if (AsyncResult.isFailure(result)) throw squashAtomCommandFailure(result);+ });+ }++ return (+ <SettingsScreen title={environment?.environmentLabel ?? "Environment"}>+ <ScreenScrollView+ contentInsetAdjustmentBehavior="automatic"+ className="flex-1"+ contentContainerClassName="gap-6 px-5 pt-4"+ contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}+ >+ {!environment ? (+ <Text className="text-base text-foreground-muted">+ This environment is no longer saved on this device.+ </Text>+ ) : (+ <>+ <SettingsSection title="Connection">+ <ConnectionEnvironmentRow+ environment={environment}+ expanded={connectionExpanded}+ onToggle={() => setConnectionExpanded((value) => !value)}+ onReconnect={connections.onReconnectEnvironment}+ onRemove={connections.onRemoveEnvironmentPress}+ onSetEnabled={connections.onSetEnvironmentEnabled}+ onUpdate={connections.onUpdateEnvironment}+ />+ </SettingsSection>+ {!connected ? (+ <Text className="px-2 text-sm text-foreground-muted">+ Connect this environment to manage it.+ </Text>+ ) : !allowed ? (+ <Text className="px-2 text-sm text-foreground-muted">+ {AsyncResult.isFailure(sessionResult)+ ? "Could not verify your permissions. Reconnect to try again."+ : session === null+ ? "Checking permissions…"+ : "This connection does not have permission to manage the environment."}+ </Text>+ ) : null}+ {error ? (+ <Text selectable className="px-2 text-sm text-danger-foreground">+ {error}+ </Text>+ ) : null}+ {notice ? <Text className="px-2 text-sm text-foreground-muted">{notice}</Text> : null}+ {config ? (+ <>+ <SettingsSection title="T3 Code">+ <View className="gap-1 p-4">+ <Text className="text-base text-foreground">Version {version}</Text>+ {running ? (+ <Text className="text-sm text-foreground-muted">+ {updateState.stage === "resuming"+ ? "Restarting and reconnecting…"+ : "Downloading update…"}+ </Text>+ ) : updateState.status === "failed" ? (+ <Text selectable className="text-sm text-danger-foreground">+ {updateState.message}+ </Text>+ ) : null}+ {checkedRelease ? (+ <Text className="text-sm text-foreground-muted">+ {checkedRelease.targetVersion+ ? `Version ${checkedRelease.targetVersion} is available.`+ : "You are up to date."}+ </Text>+ ) : null}+ {!supportsEnvironmentUpdate(config.environment.capabilities) ? (+ <Text className="text-sm text-foreground-muted">+ {capabilities?.serverSelfUpdate === "desktop-managed"+ ? "Update the desktop app on this machine."+ : "Update and restart T3 Code on this machine."}+ </Text>+ ) : null}+ </View>+ <SettingsActionRow+ icon="arrow.clockwise"+ label="Check for updates"+ disabled={disabled}+ loading={pending === "check"}+ onPress={() => {+ if (disabled) return;+ void run("check", async () => {+ const controller = new AbortController();+ checkController.current = controller;+ const timeout = setTimeout(() => controller.abort(), 20_000);+ try {+ const targetVersion = await findEnvironmentUpdate(+ config.environment.serverVersion,+ controller.signal,+ );+ setRelease({+ fromVersion: config.environment.serverVersion,+ targetVersion,+ });+ } finally {+ clearTimeout(timeout);+ checkController.current = null;+ }+ });+ }}+ />+ {checkedRelease?.targetVersion &&+ supportsEnvironmentUpdate(config.environment.capabilities) ? (+ <SettingsActionRow+ icon="arrow.up.circle"+ label={`Update to ${checkedRelease.targetVersion}`}+ disabled={disabled}+ loading={pending === "server" || running}+ onPress={requestServerUpdate}+ />+ ) : null}+ </SettingsSection>+ <SettingsSection title="Providers">+ <SettingsActionRow+ icon="arrow.clockwise"+ label="Refresh providers"+ disabled={disabled}+ loading={pending === "refresh"}+ onPress={() => {+ if (disabled) return;+ void run("refresh", async () => {+ const result = await refreshProviders({ environmentId, input: {} });+ if (AsyncResult.isFailure(result)) throw squashAtomCommandFailure(result);+ setNotice("Provider status refreshed.");+ });+ }}+ />+ {config.providers+ .filter((provider) => provider.enabled)+ .map((provider) => (+ <View key={provider.instanceId}>+ <View className="gap-1 p-4">+ <View className="flex-row items-center gap-2">+ <ProviderIcon provider={provider.driver} size={18} />+ <Text className="min-w-0 flex-1 text-base font-t3-medium text-foreground">+ {provider.displayName ?? provider.driver}+ </Text>+ </View>+ <Text className="text-sm text-foreground-muted">+ {provider.installed+ ? (provider.version ?? "Version unknown")+ : "Not installed"}+ {provider.versionAdvisory?.latestVersion+ ? ` · Latest ${provider.versionAdvisory.latestVersion}`+ : ""}+ </Text>+ {provider.updateState && provider.updateState.status !== "idle" ? (+ <Text+ selectable+ className={+ provider.updateState.status === "failed"+ ? "text-sm text-danger-foreground"+ : "text-sm text-foreground-muted"+ }+ >+ {provider.updateState.message ??+ `Update ${provider.updateState.status}`}+ </Text>+ ) : null}+ {provider.compatibilityAdvisory?.message ? (+ <Text selectable className="text-sm text-foreground-muted">+ {provider.compatibilityAdvisory.message}+ </Text>+ ) : null}+ {provider.unavailableReason || provider.message ? (+ <Text selectable className="text-sm text-foreground-muted">+ {provider.unavailableReason ?? provider.message}+ </Text>+ ) : null}+ {provider.versionAdvisory?.status === "behind_latest" &&+ !provider.versionAdvisory.canUpdate ? (+ <Text className="text-sm text-foreground-muted">+ Update this provider on the environment's machine.+ </Text>+ ) : null}+ </View>+ {canUpdateEnvironmentProvider(provider) ? (+ <SettingsActionRow+ icon="arrow.up.circle"+ label={`Update ${provider.displayName ?? provider.driver}`}+ disabled={disabled}+ loading={pending === provider.instanceId}+ onPress={() => requestProviderUpdate(provider)}+ />+ ) : null}+ </View>+ ))}+ </SettingsSection>+ </>+ ) : null}+ </>+ )}+ </ScreenScrollView>+ </SettingsScreen>+ );+}diff --git a/apps/mobile/src/features/settings/SettingsEnvironmentsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsEnvironmentsRouteScreen.tsxindex 7ca791afec6..003178a03ac 100644--- a/apps/mobile/src/features/settings/SettingsEnvironmentsRouteScreen.tsx+++ b/apps/mobile/src/features/settings/SettingsEnvironmentsRouteScreen.tsx@@ -47,7 +47,6 @@ export function SettingsEnvironmentsRouteScreen() {const connectedCloudEnvironments = SHOWCASE_ENABLED? SHOWCASE_CONNECTED_CLOUD_ENVIRONMENTS: environmentSections.connectedCloudEnvironments;- const [expandedId, setExpandedId] = useState<EnvironmentId | null>(null);const headerIconColor = useUniwindTheme()["--color-icon"];const relaySession = useAtomValue(managedRelaySessionAtom);const refreshRelayEnvironments = useAtomCommand(@@ -68,9 +67,15 @@ export function SettingsEnvironmentsRouteScreen() {}}- const handleToggle = useCallback((environmentId: EnvironmentId) => {- setExpandedId((prev) => (prev === environmentId ? null : environmentId));- }, []);+ const openEnvironment = useCallback(+ (environmentId: EnvironmentId) => {+ navigation.navigate("SettingsSheet", {+ screen: "SettingsContent",+ params: { screen: "SettingsEnvironmentDetail", params: { environmentId } },+ });+ },+ [navigation],+ );const handleUpdateEnvironment = useCallback((environmentId: EnvironmentId,@@ -159,8 +164,9 @@ export function SettingsEnvironmentsRouteScreen() {><LocalEnvironmentListenvironments={localEnvironments}- expandedId={expandedId}- onToggle={handleToggle}+ expandedId={null}+ onToggle={openEnvironment}+ opensDetailsonReconnect={onReconnectEnvironment}onRemove={onRemoveEnvironmentPress}onSetEnabled={onSetEnvironmentEnabled}@@ -172,6 +178,7 @@ export function SettingsEnvironmentsRouteScreen() {user is signed out — the component gates discovery itself. */}<CloudEnvironmentRowsconnectedCloudEnvironments={connectedCloudEnvironments}+ onOpenEnvironment={openEnvironment}onSetEnvironmentEnabled={onSetEnvironmentEnabled}onRemoveEnvironment={onRemoveEnvironmentPress}{...(SHOWCASE_ENABLEDdiff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsxindex 8aff022910d..bc5315bec13 100644--- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx+++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx@@ -1,3 +1,5 @@+import { useNavigation } from "@react-navigation/native";+import { SettingsRow } from "./components/SettingsRow";import { ScreenScrollView as ScrollView } from "../../components/ScreenScrollView";import { SymbolView } from "../../components/AppSymbol";import { AppText as Text } from "../../components/AppText";@@ -133,6 +135,7 @@ export function SettingsEnvironmentMaintenanceRouteScreen() {function ServerSettingsDetail(props: { readonly page: SettingsPage }) {const insets = useSafeAreaInsets();+ const navigation = useNavigation();const { selectedTargets, projectGroups, selectedProjectKey } = useSettingsEnvironmentFilter();const selectedProject = projectGroups.find((group) => group.key === selectedProjectKey);const projectSelected = selectedProjectKey !== null;@@ -397,36 +400,61 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {) : 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">+ <>+ {!projectSelected ? (+ <SettingsSection title="Manage environments">+ {selectedTargets.map((target) => (+ <SettingsRow+ key={target.environmentId}+ icon="server.rack"+ label={target.label}+ value="Server and provider updates"+ onPress={() =>+ navigation.navigate("SettingsSheet", {+ screen: "SettingsContent",+ params: {+ screen: "SettingsEnvironmentDetail",+ params: { environmentId: target.environmentId },+ },+ })+ }+ />+ ))}+ </SettingsSection>+ ) : null}+ <SettingsSection title="Updates"><FanoutSwitchRow- icon="arrow.uturn.forward"- label="Continue after restart"+ icon="arrow.clockwise"+ label="Check provider updates"subtitle={- supportsContinuation- ? "Resume interrupted threads after an update or restart."- : "Update older servers to control restart continuation."- }- value={uniform("continueThreadsAfterServerUpdate")}- disabled={- disabledFor("continueThreadsAfterServerUpdate") || !supportsContinuation+ projectSelected+ ? "Environment-wide setting. Select All projects to change it."+ : "Check installed provider CLIs for newer versions."}- onValueChange={(value) => write({ continueThreadsAfterServerUpdate: value })}+ value={uniform("enableProviderUpdateChecks")}+ disabled={disabledFor("enableProviderUpdateChecks")}+ onValueChange={(value) => write({ enableProviderUpdateChecks: value })}/>- </View>- </SettingsSection>+ <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}</>)}diff --git a/apps/mobile/src/features/settings/components/SettingsSwitchRow.tsx b/apps/mobile/src/features/settings/components/SettingsSwitchRow.tsxindex 49fb98e4997..85cb4764e25 100644--- a/apps/mobile/src/features/settings/components/SettingsSwitchRow.tsx+++ b/apps/mobile/src/features/settings/components/SettingsSwitchRow.tsx@@ -17,6 +17,7 @@ export function SettingsSwitchRow(subtitle={props.subtitle}><ThemedSwitch+ style={{ alignSelf: "center" }}accessibilityLabel={props.label}disabled={props.disabled}onValueChange={props.onValueChange}diff --git a/apps/mobile/src/features/settings/environment-maintenance.test.ts b/apps/mobile/src/features/settings/environment-maintenance.test.tsnew file mode 100644index 00000000000..878f7151189--- /dev/null+++ b/apps/mobile/src/features/settings/environment-maintenance.test.ts@@ -0,0 +1,154 @@+import { AuthOrchestrationOperateScope, ServerProvider } from "@t3tools/contracts";+import * as Schema from "effect/Schema";+import { afterEach, describe, expect, it, vi } from "vite-plus/test";++import {+ canMaintainEnvironment,+ canUpdateEnvironmentProvider,+ findEnvironmentUpdate,+ supportsEnvironmentUpdate,+} from "./environment-maintenance";++const provider = Schema.decodeUnknownSync(ServerProvider)({+ instanceId: "codex-personal",+ driver: "codex",+ enabled: true,+ installed: true,+ version: "1.0.0",+ status: "ready",+ auth: { status: "authenticated" },+ checkedAt: "2026-09-23T00:00:00.000Z",+ models: [],+ versionAdvisory: {+ status: "behind_latest",+ currentVersion: "1.0.0",+ latestVersion: "1.1.0",+ canUpdate: true,+ updateCommand: null,+ checkedAt: null,+ message: null,+ },+});++afterEach(() => vi.unstubAllGlobals());++describe("environment maintenance access", () => {+ it("requires a connected authenticated session with operate permission", () => {+ const session = {+ authenticated: true,+ auth: {+ policy: "remote-reachable" as const,+ bootstrapMethods: [],+ sessionMethods: [],+ sessionCookieName: "session",+ },+ scopes: [AuthOrchestrationOperateScope],+ };+ expect(canMaintainEnvironment(session, true)).toBe(true);+ expect(canMaintainEnvironment(session, false)).toBe(false);+ expect(canMaintainEnvironment({ ...session, authenticated: false }, true)).toBe(false);+ expect(canMaintainEnvironment({ ...session, scopes: [] }, true)).toBe(false);+ const { scopes: _, ...legacy } = session;+ expect(canMaintainEnvironment(legacy, true)).toBe(false);+ expect(canMaintainEnvironment(null, true)).toBe(false);+ });++ it("requires remote desktop update support for desktop hosts", () => {+ expect(supportsEnvironmentUpdate({})).toBe(false);+ expect(supportsEnvironmentUpdate({ serverSelfUpdate: "respawn" })).toBe(true);+ expect(supportsEnvironmentUpdate({ serverSelfUpdate: "desktop-managed" })).toBe(false);+ expect(+ supportsEnvironmentUpdate({ serverSelfUpdate: "desktop-managed", desktopAppUpdate: true }),+ ).toBe(true);+ });++ it("excludes unavailable, manual, busy, and incompatible provider updates", () => {+ expect(canUpdateEnvironmentProvider(provider)).toBe(true);+ expect(canUpdateEnvironmentProvider({ ...provider, installed: false })).toBe(false);+ expect(canUpdateEnvironmentProvider({ ...provider, availability: "unavailable" })).toBe(false);+ expect(canUpdateEnvironmentProvider({ ...provider, versionAdvisory: undefined })).toBe(false);+ for (const latestVersionStatus of ["broken", "unsupported"] as const) {+ expect(+ canUpdateEnvironmentProvider({+ ...provider,+ compatibilityAdvisory: {+ status: "supported",+ latestVersionStatus,+ message: null,+ recommendedVersion: null,+ recommendedRange: null,+ },+ }),+ ).toBe(false);+ }+ for (const status of ["queued", "running"] as const) {+ expect(+ canUpdateEnvironmentProvider({+ ...provider,+ updateState: {+ status,+ startedAt: null,+ finishedAt: null,+ message: null,+ output: null,+ },+ }),+ ).toBe(false);+ }+ expect(+ canUpdateEnvironmentProvider({+ ...provider,+ versionAdvisory: {+ ...provider.versionAdvisory!,+ canUpdate: false,+ },+ }),+ ).toBe(false);+ });+});++describe("environment release checks", () => {+ const signal = new AbortController().signal;++ it("keeps stable hosts on stable releases and ignores drafts", async () => {+ vi.stubGlobal(+ "fetch",+ vi+ .fn()+ .mockImplementation(async () =>+ Response.json([+ { tag_name: "v2.0.0-nightly.20260923.1" },+ { tag_name: "v1.2.0", draft: true },+ { tag_name: "v1.1.0" },+ ]),+ ),+ );+ expect(await findEnvironmentUpdate("1.0.0", signal)).toBe("1.1.0");+ expect(await findEnvironmentUpdate("1.1.0", signal)).toBeNull();+ expect(await findEnvironmentUpdate("1.3.0", signal)).toBeNull();+ });++ it("walks release pages to find the host's channel", async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(+ Response.json(Array.from({ length: 100 }, () => ({ tag_name: "v2.0.0" }))),+ )+ .mockResolvedValueOnce(Response.json([{ tag_name: "v1.0.0-preview.20260923.2" }]));+ vi.stubGlobal("fetch", fetchMock);+ expect(await findEnvironmentUpdate("1.0.0-preview.20260923.1", signal)).toBe(+ "1.0.0-preview.20260923.2",+ );+ expect(fetchMock.mock.calls[1]?.[0]).toContain("page=2");+ expect(fetchMock.mock.calls[1]?.[1]).toEqual({ signal });+ });++ it("reports failed checks instead of claiming the server is current", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(null, { status: 403 })));+ await expect(findEnvironmentUpdate("1.0.0", signal)).rejects.toThrow("403");+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(Response.json([])));+ await expect(findEnvironmentUpdate("1.0.0", signal)).rejects.toThrow("No stable release");+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(Response.json({ error: "invalid" })));+ await expect(findEnvironmentUpdate("1.0.0", signal)).rejects.toThrow();+ });+});diff --git a/apps/mobile/src/features/settings/environment-maintenance.ts b/apps/mobile/src/features/settings/environment-maintenance.tsnew file mode 100644index 00000000000..f441066d717--- /dev/null+++ b/apps/mobile/src/features/settings/environment-maintenance.ts@@ -0,0 +1,68 @@+import {+ AuthOrchestrationOperateScope,+ type AuthSessionState,+ type ExecutionEnvironmentCapabilities,+ type ServerProvider,+} from "@t3tools/contracts";+import {+ cliReleaseChannelOf,+ cliReleaseIndexPageUrl,+ newestCliReleaseVersion,+} from "@t3tools/shared/cliRelease";+import { compareSemverVersions } from "@t3tools/shared/semver";+import * as Schema from "effect/Schema";++export function canMaintainEnvironment(session: AuthSessionState | null, connected: boolean) {+ return (+ connected &&+ session?.authenticated === true &&+ session.scopes?.includes(AuthOrchestrationOperateScope) === true+ );+}++export function supportsEnvironmentUpdate(+ capabilities: Pick<ExecutionEnvironmentCapabilities, "serverSelfUpdate" | "desktopAppUpdate">,+) {+ return (+ capabilities.serverSelfUpdate !== undefined &&+ (capabilities.serverSelfUpdate !== "desktop-managed" || capabilities.desktopAppUpdate === true)+ );+}++export function canUpdateEnvironmentProvider(provider: ServerProvider) {+ const compatibility = provider.compatibilityAdvisory?.latestVersionStatus;+ return (+ provider.installed &&+ provider.availability !== "unavailable" &&+ provider.versionAdvisory?.status === "behind_latest" &&+ provider.versionAdvisory.canUpdate &&+ provider.versionAdvisory.latestVersion !== null &&+ compatibility !== "broken" &&+ compatibility !== "unsupported" &&+ provider.updateState?.status !== "running" &&+ provider.updateState?.status !== "queued"+ );+}++const Releases = Schema.Array(+ Schema.Struct({+ tag_name: Schema.String,+ draft: Schema.optionalKey(Schema.Boolean),+ }),+);+const decodeReleases = Schema.decodeUnknownSync(Releases);++/** Preserve the host's release channel and never offer a downgrade. */+export async function findEnvironmentUpdate(currentVersion: string, signal: AbortSignal) {+ const channel = cliReleaseChannelOf(currentVersion);+ for (let page = 1; ; page++) {+ const response = await fetch(cliReleaseIndexPageUrl(page), { signal });+ if (!response.ok) throw new Error(`Could not check releases (${response.status}). Try again.`);+ const releases = decodeReleases(await response.json());+ const version = newestCliReleaseVersion(releases, channel);+ if (version !== undefined) {+ return compareSemverVersions(version, currentVersion) > 0 ? version : null;+ }+ if (releases.length < 100) throw new Error(`No ${channel} release was found.`);+ }+}diff --git a/docs/user/updating.md b/docs/user/updating.mdindex 25833d3e79e..6909c7b6022 100644--- a/docs/user/updating.md+++ b/docs/user/updating.md@@ -58,6 +58,18 @@ update can roll back to the previous version. If the update still fails:## Mobile updates+To update an environment from your phone, open **Settings → Environments** and+select it. **Check for updates** finds the latest release on that environment's+current release channel. Keep the app open while the environment updates and+reconnects. Hosts that cannot update remotely show instructions for updating on+the machine instead.++The same page lets you refresh provider status and update supported providers.+These controls require a connected environment and permission to operate it.+Provider update checks and restart continuation preferences are in+**Settings → Maintenance**. If provider update checks are disabled, enable them+there before refreshing to find newer versions.+Install App Store or Google Play releases as usual. The mobile app can alsodownload updates in the background and apply them when you next leave the app.It saves drafts and queued messages before restarting. If you keep the app open