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

SettingsEnvironmentDetailRouteScreen.tsx

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