Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
3import type { EnvironmentId, ServerProvider } from "@t3tools/contracts";
4import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
5import { AsyncResult } from "effect/reactivity";
6import { useEffect, useRef, useState } from "react";
7import { Alert, View } from "react-native";
8import { useSafeAreaInsets } from "react-native-safe-area-context";
9
10import { AppText as Text } from "../../components/AppText";
11import { ProviderIcon } from "../../components/ProviderIcon";
12import { ScreenScrollView } from "../../components/ScreenScrollView";
13import { serverEnvironment } from "../../state/server";
14import { environmentSession } from "../../state/session";
15import { useAtomCommand } from "../../state/use-atom-command";
16import { useRemoteConnections } from "../../state/use-remote-environment-registry";
17import { ConnectionEnvironmentRow } from "../connection/ConnectionEnvironmentRow";
18import { EnvironmentRoutesSection } from "./EnvironmentRoutesSection";
19import { SettingsActionRow } from "./components/SettingsActionRow";
20import { SettingsScreen } from "./components/SettingsScreen";
21import { SettingsSection } from "./components/SettingsSection";
22import {
23 canMaintainEnvironment,
24 canUpdateEnvironmentProvider,
25 findEnvironmentUpdate,
26 supportsEnvironmentUpdate,
27} from "./environment-maintenance";
28
29export function SettingsEnvironmentDetailRouteScreen({
30 route,
31}: StaticScreenProps<{
32 readonly environmentId: EnvironmentId;
33}>) {
34 // Key local request state to the host even when navigation reuses this screen.
35 return (
36 <EnvironmentDetail
37 key={route.params.environmentId}
38 environmentId={route.params.environmentId}
39 />
40 );
41}
42
43function EnvironmentDetail({ environmentId }: { readonly environmentId: EnvironmentId }) {
44 const insets = useSafeAreaInsets();
45 const navigation = useNavigation();
46 const connections = useRemoteConnections();
47 const environment = connections.connectedEnvironments.find(
48 (entry) => entry.environmentId === environmentId,
49 );
50 const config = useAtomValue(serverEnvironment.configValueAtom(environmentId));
51 const session = useAtomValue(environmentSession.sessionStateValueAtom(environmentId));
52 const sessionResult = useAtomValue(environmentSession.sessionStateAtom(environmentId));
53 const updateState = useAtomValue(serverEnvironment.updateStateAtom(environmentId));
54 const updateServer = useAtomCommand(serverEnvironment.updateServer);
55 const updateProvider = useAtomCommand(serverEnvironment.updateProvider);
56 const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders);
57 const [connectionExpanded, setConnectionExpanded] = useState(false);
58 const [pending, setPending] = useState<string | null>(null);
59 const pendingRef = useRef(false);
60 const [error, setError] = useState<string | null>(null);
61 const [notice, setNotice] = useState<string | null>(null);
62 const [release, setRelease] = useState<{
63 fromVersion: string;
64 targetVersion: string | null;
65 } | null>(null);
66 const checkController = useRef<AbortController | null>(null);
67 useEffect(() => () => checkController.current?.abort(), []);
68
69 const connected = environment?.isEnabled === true && environment.connectionState === "connected";
70 const allowed =
71 !AsyncResult.isFailure(sessionResult) && canMaintainEnvironment(session, connected);
72 const running = updateState.status === "running";
73 const providerBusy =
74 config?.providers.some(
75 (provider) =>
76 provider.updateState?.status === "running" || provider.updateState?.status === "queued",
77 ) ?? false;
78 const disabled = !allowed || pending !== null || running || providerBusy;
79 const version = config?.environment.serverVersion;
80 const checkedRelease = release?.fromVersion === version ? release : null;
81 const capabilities = config?.environment.capabilities;
82
83 async function run(label: string, action: () => Promise<void>) {
84 if (pendingRef.current) return;
85 pendingRef.current = true;
86 setPending(label);
87 setError(null);
88 setNotice(null);
89 try {
90 await action();
91 } catch (cause) {
92 setError(
93 cause instanceof Error ? cause.message : "The action could not be completed. Try again.",
94 );
95 } finally {
96 pendingRef.current = false;
97 setPending(null);
98 }
99 }
100
101 function requestServerUpdate() {
102 const targetVersion = checkedRelease?.targetVersion;
103 if (disabled || !targetVersion || !capabilities || !supportsEnvironmentUpdate(capabilities))
104 return;
105 Alert.alert(
106 `Update ${environment?.environmentLabel ?? "environment"}?`,
107 `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.`,
108 [
109 { text: "Cancel", style: "cancel" },
110 {
111 text: "Update",
112 onPress: () =>
113 void run("server", async () => {
114 const result = await updateServer({
115 environmentId,
116 input: {
117 targetVersion,
118 ...(capabilities.serverUpdateThreadContinuation &&
119 config?.settings.continueThreadsAfterServerUpdate
120 ? { continueRunningThreads: true }
121 : {}),
122 },
123 });
124 if (AsyncResult.isFailure(result)) throw squashAtomCommandFailure(result);
125 setRelease(null);
126 setNotice(`Updated to ${result.value.targetVersion}.`);
127 }),
128 },
129 ],
130 );
131 }
132
133 function requestProviderUpdate(provider: ServerProvider) {
134 if (disabled || !canUpdateEnvironmentProvider(provider)) return;
135 void run(provider.instanceId, async () => {
136 const result = await updateProvider({
137 environmentId,
138 input: {
139 provider: provider.driver,
140 instanceId: provider.instanceId,
141 },
142 });
143 if (AsyncResult.isFailure(result)) throw squashAtomCommandFailure(result);
144 });
145 }
146
147 return (
148 <SettingsScreen title={environment?.environmentLabel ?? "Environment"}>
149 <ScreenScrollView
150 contentInsetAdjustmentBehavior="automatic"
151 className="flex-1"
152 contentContainerClassName="gap-6 px-5 pt-4"
153 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
154 >
155 {!environment ? (
156 <Text className="text-base text-foreground-muted">
157 This environment is no longer saved on this device.
158 </Text>
159 ) : (
160 <>
161 <SettingsSection title="Connection">
162 <ConnectionEnvironmentRow
163 environment={environment}
164 expanded={connectionExpanded}
165 onToggle={() => setConnectionExpanded((value) => !value)}
166 onReconnect={connections.onReconnectEnvironment}
167 onRemove={connections.onRemoveEnvironmentPress}
168 onSetEnabled={connections.onSetEnvironmentEnabled}
169 onUpdate={connections.onUpdateEnvironment}
170 />
171 </SettingsSection>
172 <EnvironmentRoutesSection
173 environmentId={environmentId}
174 connected={connected}
175 onAddRoute={() =>
176 navigation.navigate("SettingsSheet", {
177 screen: "SettingsContent",
178 params: {
179 screen: "SettingsEnvironmentNew",
180 params: { routeFor: environmentId },
181 },
182 })
183 }
184 />
185 {!connected ? (
186 <Text className="px-2 text-sm text-foreground-muted">
187 Connect this environment to manage it.
188 </Text>
189 ) : !allowed ? (
190 <Text className="px-2 text-sm text-foreground-muted">
191 {AsyncResult.isFailure(sessionResult)
192 ? "Could not verify your permissions. Reconnect to try again."
193 : session === null
194 ? "Checking permissions…"
195 : "This connection does not have permission to manage the environment."}
196 </Text>
197 ) : null}
198 {error ? (
199 <Text selectable className="px-2 text-sm text-danger-foreground">
200 {error}
201 </Text>
202 ) : null}
203 {notice ? <Text className="px-2 text-sm text-foreground-muted">{notice}</Text> : null}
204 {config ? (
205 <>
206 <SettingsSection title="T3 Code">
207 <View className="gap-1 p-4">
208 <Text className="text-base text-foreground">Version {version}</Text>
209 {running ? (
210 <Text className="text-sm text-foreground-muted">
211 {updateState.stage === "resuming"
212 ? "Restarting and reconnecting…"
213 : "Downloading update…"}
214 </Text>
215 ) : updateState.status === "failed" ? (
216 <Text selectable className="text-sm text-danger-foreground">
217 {updateState.message}
218 </Text>
219 ) : null}
220 {checkedRelease ? (
221 <Text className="text-sm text-foreground-muted">
222 {checkedRelease.targetVersion
223 ? `Version ${checkedRelease.targetVersion} is available.`
224 : "You are up to date."}
225 </Text>
226 ) : null}
227 {!supportsEnvironmentUpdate(config.environment.capabilities) ? (
228 <Text className="text-sm text-foreground-muted">
229 {capabilities?.serverSelfUpdate === "desktop-managed"
230 ? "Update the desktop app on this machine."
231 : "Update and restart T3 Code on this machine."}
232 </Text>
233 ) : null}
234 </View>
235 <SettingsActionRow
236 icon="arrow.clockwise"
237 label="Check for updates"
238 disabled={disabled}
239 loading={pending === "check"}
240 onPress={() => {
241 if (disabled) return;
242 void run("check", async () => {
243 const controller = new AbortController();
244 checkController.current = controller;
245 const timeout = setTimeout(() => controller.abort(), 20_000);
246 try {
247 const targetVersion = await findEnvironmentUpdate(
248 config.environment.serverVersion,
249 controller.signal,
250 );
251 setRelease({
252 fromVersion: config.environment.serverVersion,
253 targetVersion,
254 });
255 } finally {
256 clearTimeout(timeout);
257 checkController.current = null;
258 }
259 });
260 }}
261 />
262 {checkedRelease?.targetVersion &&
263 supportsEnvironmentUpdate(config.environment.capabilities) ? (
264 <SettingsActionRow
265 icon="arrow.up.circle"
266 label={`Update to ${checkedRelease.targetVersion}`}
267 disabled={disabled}
268 loading={pending === "server" || running}
269 onPress={requestServerUpdate}
270 />
271 ) : null}
272 </SettingsSection>
273 <SettingsSection title="Providers">
274 <SettingsActionRow
275 icon="arrow.clockwise"
276 label="Refresh providers"
277 disabled={disabled}
278 loading={pending === "refresh"}
279 onPress={() => {
280 if (disabled) return;
281 void run("refresh", async () => {
282 const result = await refreshProviders({ environmentId, input: {} });
283 if (AsyncResult.isFailure(result)) throw squashAtomCommandFailure(result);
284 setNotice("Provider status refreshed.");
285 });
286 }}
287 />
288 {config.providers
289 .filter((provider) => provider.enabled)
290 .map((provider) => (
291 <View key={provider.instanceId}>
292 <View className="gap-1 p-4">
293 <View className="flex-row items-center gap-2">
294 <ProviderIcon provider={provider.driver} size={18} />
295 <Text className="min-w-0 flex-1 text-base font-t3-medium text-foreground">
296 {provider.displayName ?? provider.driver}
297 </Text>
298 </View>
299 <Text className="text-sm text-foreground-muted">
300 {provider.installed
301 ? (provider.version ?? "Version unknown")
302 : "Not installed"}
303 {provider.versionAdvisory?.latestVersion
304 ? ` · Latest ${provider.versionAdvisory.latestVersion}`
305 : ""}
306 </Text>
307 {provider.updateState && provider.updateState.status !== "idle" ? (
308 <Text
309 selectable
310 className={
311 provider.updateState.status === "failed"
312 ? "text-sm text-danger-foreground"
313 : "text-sm text-foreground-muted"
314 }
315 >
316 {provider.updateState.message ??
317 `Update ${provider.updateState.status}`}
318 </Text>
319 ) : null}
320 {provider.compatibilityAdvisory?.message ? (
321 <Text selectable className="text-sm text-foreground-muted">
322 {provider.compatibilityAdvisory.message}
323 </Text>
324 ) : null}
325 {provider.unavailableReason || provider.message ? (
326 <Text selectable className="text-sm text-foreground-muted">
327 {provider.unavailableReason ?? provider.message}
328 </Text>
329 ) : null}
330 {provider.versionAdvisory?.status === "behind_latest" &&
331 !provider.versionAdvisory.canUpdate ? (
332 <Text className="text-sm text-foreground-muted">
333 Update this provider on the environment's machine.
334 </Text>
335 ) : null}
336 </View>
337 {canUpdateEnvironmentProvider(provider) ? (
338 <SettingsActionRow
339 icon="arrow.up.circle"
340 label={`Update ${provider.displayName ?? provider.driver}`}
341 disabled={disabled}
342 loading={pending === provider.instanceId}
343 onPress={() => requestProviderUpdate(provider)}
344 />
345 ) : null}
346 </View>
347 ))}
348 </SettingsSection>
349 </>
350 ) : null}
351 </>
352 )}
353 </ScreenScrollView>
354 </SettingsScreen>
355 );
356}