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

SettingsEnvironmentDetailRouteScreen.tsx

433 lines20.0 KB

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