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