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

SettingsEnvironmentDetailRouteScreen.tsx

378 lines17.1 KB

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