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