Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SettingsEnvironmentDetailRouteScreen.tsx

398 lines18.2 KB

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