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

SettingsEnvironmentDetailRouteScreen.tsx

373 lines16.9 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 type EnvironmentId,
8 type ServerProvider,
9} from "@t3tools/contracts";
10import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
11import * as Cause from "effect/Cause";
12import * as Exit from "effect/Exit";
13import { AsyncResult } from "effect/reactivity";
14import { useRef, useState } from "react";
15import { View } from "react-native";
16import { useSafeAreaInsets } from "react-native-safe-area-context";
17​
18import { AppText as Text } from "../../components/ui/AppText";
19import { ProviderIcon } from "../../components/ProviderIcon";
20import { ScreenScrollView } from "../../components/ui/ScreenScrollView";
21import { appAtomRegistry } from "../../state/atom-registry";
22import { environmentPresentations } from "../../state/presentation";
23import { serverEnvironment } from "../../state/server";
24import { environmentSession, useEnvironmentScope, readEnvironmentScope } from "../../state/session";
25import { useAtomCommand } from "../../state/use-atom-command";
26import { useRemoteConnections } from "../../state/use-remote-environment-registry";
27import { ConnectionEnvironmentRow } from "../connection/ConnectionEnvironmentRow";
28import { EnvironmentRoutesSection } from "./EnvironmentRoutesSection";
29import { OutdatedServerUpdateSection } from "./OutdatedServerUpdateSection";
30import { SettingsActionRow } from "./components/SettingsActionRow";
31import { SettingsScreen } from "./components/SettingsScreen";
32import { SettingsSection } from "./components/SettingsSection";
33import {
34 canMaintainEnvironment,
35 canUpdateEnvironmentProvider,
36 supportsEnvironmentUpdate,
37} from "./environment-maintenance";
38import { environmentReleaseCheckAtom, releaseCheckValue } from "./environmentUpdateCheck";
39​
40export function SettingsEnvironmentDetailRouteScreen({
41 route,
42}: StaticScreenProps<{
43 readonly environmentId: EnvironmentId;
44}>) {
45 return (
46 <EnvironmentDetail
47 key={route.params.environmentId}
48 environmentId={route.params.environmentId}
49 />
50 );
52​
53function EnvironmentDetail({ environmentId }: { readonly environmentId: EnvironmentId }) {
54 const insets = useSafeAreaInsets();
55 const navigation = useNavigation();
56 const connections = useRemoteConnections();
57 const environment = connections.connectedEnvironments.find(
58 (entry) => entry.environmentId === environmentId,
59 );
60 const config = useAtomValue(serverEnvironment.configValueAtom(environmentId));
61 const session = useAtomValue(environmentSession.sessionStateValueAtom(environmentId));
62 const sessionResult = useAtomValue(environmentSession.sessionStateAtom(environmentId));
63 const updateState = useAtomValue(serverEnvironment.updateStateAtom(environmentId));
64 const outdated =
65 useAtomValue(environmentPresentations.presentationAtom(environmentId))?.entry
66 .serverUpdateRequired === true;
67 const updateServer = useAtomCommand(serverEnvironment.updateServer);
68 const updateProvider = useAtomCommand(serverEnvironment.updateProvider);
69 const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders);
70 const [connectionExpanded, setConnectionExpanded] = useState(false);
71 const [pending, setPending] = useState<string | null>(null);
72 const pendingRef = useRef(false);
73 const [error, setError] = useState<string | null>(null);
74 const [notice, setNotice] = useState<string | null>(null);
75 const [releaseCheck, checkRelease] = useAtom(environmentReleaseCheckAtom(environmentId), {
76 mode: "promiseExit",
77 });
78 const release = releaseCheckValue(releaseCheck);
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 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)
218 ? "Could not verify your permissions. Reconnect to try again."
219 : session === null
220 ? "Checking permissions…"
221 : "This connection does not have permission to manage the environment."}
222 </Text>
223 ) : null}
224 {error ? (
225 <Text selectable className="px-2 text-sm text-danger-foreground">
226 {error}
227 </Text>
228 ) : null}
229 {notice ? <Text className="px-2 text-sm text-foreground-muted">{notice}</Text> : null}
230 {config && !outdated ? (
231 <>
232 <SettingsSection title="T3 Code">
233 <View className="gap-1 p-4">
234 <Text className="text-base text-foreground">Version {version}</Text>
235 {running ? (
236 <Text className="text-sm text-foreground-muted">
237 {updateState.stage === "resuming"
238 ? "Restarting and reconnecting…"
239 : "Downloading update…"}
240 </Text>
241 ) : updateState.status === "failed" ? (
242 <Text selectable className="text-sm text-danger-foreground">
243 {updateState.message}
244 </Text>
245 ) : null}
246 {checkedRelease ? (
247 <Text className="text-sm text-foreground-muted">
248 {checkedRelease.targetVersion
249 ? `Version ${checkedRelease.targetVersion} is available.`
250 : "You are up to date."}
251 </Text>
252 ) : null}
253 {checkedRelease?.targetVersion &&
254 !supportsEnvironmentUpdate(config.environment.capabilities) ? (
255 <Text className="text-sm text-foreground-muted">
256 {capabilities?.serverSelfUpdate === "desktop-managed"
257 ? "Update the desktop app on this machine."
258 : "Update and restart T3 Code on this machine."}
259 </Text>
260 ) : null}
261 </View>
262 <SettingsActionRow
263 icon="arrow.clockwise"
264 label="Check for updates"
265 disabled={disabled}
266 loading={pending === "check"}
267 onPress={() => {
268 if (disabled) return;
269 const fromVersion = config.environment.serverVersion;
270 void run("check", async () => {
271 const exit = await checkRelease(async () => fromVersion);
272 // `run` owns the error message, so a failed lookup rethrows to it.
273 if (Exit.isFailure(exit)) throw Cause.squash(exit.cause);
274 });
275 }}
276 />
277 {checkedRelease?.targetVersion &&
278 supportsEnvironmentUpdate(config.environment.capabilities) ? (
279 <SettingsActionRow
280 icon="arrow.up.circle"
281 label={`Update to ${checkedRelease.targetVersion}`}
282 disabled={disabled}
283 loading={pending === "server" || running}
284 onPress={requestServerUpdate}
285 />
286 ) : null}
287 </SettingsSection>
288 <SettingsSection title="Providers">
289 <SettingsActionRow
290 icon="arrow.clockwise"
291 label="Refresh providers"
292 disabled={busy || !canRead}
293 loading={pending === "refresh"}
294 onPress={() => {
295 if (busy || !canRead) return;
296 void run("refresh", async () => {
297 if (!readEnvironmentScope(environmentId, AuthOrchestrationReadScope))
298 return;
299 const result = await refreshProviders({ environmentId, input: {} });
300 if (AsyncResult.isFailure(result)) throw squashAtomCommandFailure(result);
301 setNotice("Provider status refreshed.");
302 });
303 }}
304 />
305 {config.providers
306 .filter((provider) => provider.enabled)
307 .map((provider) => (
308 <View key={provider.instanceId}>
309 <View className="gap-1 p-4">
310 <View className="flex-row items-center gap-2">
311 <ProviderIcon provider={provider.driver} size={18} />
312 <Text className="min-w-0 flex-1 text-base font-t3-medium text-foreground">
313 {provider.displayName ?? provider.driver}
314 </Text>
315 </View>
316 <Text className="text-sm text-foreground-muted">
317 {provider.installed
318 ? (provider.version ?? "Version unknown")
319 : "Not installed"}
320 {provider.versionAdvisory?.latestVersion
321 ? ` · Latest ${provider.versionAdvisory.latestVersion}`
322 : ""}
323 </Text>
324 {provider.updateState && provider.updateState.status !== "idle" ? (
325 <Text
326 selectable
327 className={
328 provider.updateState.status === "failed"
329 ? "text-sm text-danger-foreground"
330 : "text-sm text-foreground-muted"
331 }
332 >
333 {provider.updateState.message ??
334 `Update ${provider.updateState.status}`}
335 </Text>
336 ) : null}
337 {provider.compatibilityAdvisory?.message ? (
338 <Text selectable className="text-sm text-foreground-muted">
339 {provider.compatibilityAdvisory.message}
340 </Text>
341 ) : null}
342 {provider.unavailableReason || provider.message ? (
343 <Text selectable className="text-sm text-foreground-muted">
344 {provider.unavailableReason ?? provider.message}
345 </Text>
346 ) : null}
347 {provider.versionAdvisory?.status === "behind_latest" &&
348 !provider.versionAdvisory.canUpdate ? (
349 <Text className="text-sm text-foreground-muted">
350 Update this provider on the environment's machine.
351 </Text>
352 ) : null}
353 </View>
354 {canUpdateEnvironmentProvider(provider) ? (
355 <SettingsActionRow
356 icon="arrow.up.circle"
357 label={`Update ${provider.displayName ?? provider.driver}`}
358 disabled={busy || !canManageProviders}
359 loading={pending === provider.instanceId}
360 onPress={() => requestProviderUpdate(provider)}
361 />
362 ) : null}
363 </View>
364 ))}
365 </SettingsSection>
366 </>
367 ) : null}
368 </>
369 )}
370 </ScreenScrollView>
371 </SettingsScreen>
372 );