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