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

SettingsEnvironmentDetailRouteScreen.tsx

383 lines17.0 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 { 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 try {
100 await action();
101 } catch (cause) {
102 setError(
103 cause instanceof Error ? cause.message : "The action could not be completed. Try again.",
104 );
105 } finally {
106 pendingRef.current = false;
107 setPending(null);
108 }
109 }
110​
111 function requestServerUpdate() {
112 const targetVersion = checkedRelease?.targetVersion;
113 if (disabled || !targetVersion || !capabilities || !supportsEnvironmentUpdate(capabilities))
114 return;
115 Dialog.alert(
116 `Update ${environment?.environmentLabel ?? "environment"}?`,
117 `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.`,
118 [
119 { text: "Cancel", style: "cancel" },
120 {
121 text: "Update",
122 onPress: () =>
123 void run("server", async () => {
124 if (
125 AsyncResult.isFailure(
126 appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId)),
127 ) ||
128 !canMaintainEnvironment(
129 appAtomRegistry.get(environmentSession.sessionStateValueAtom(environmentId)),
130 connected,
131 )
132 )
133 return;
134 const result = await updateServer({
135 environmentId,
136 input: {
137 targetVersion,
138 ...(capabilities.serverUpdateThreadContinuation &&
139 config?.settings.continueThreadsAfterServerUpdate
140 ? { continueRunningThreads: true }
141 : {}),
142 },
143 });
144 if (AsyncResult.isFailure(result)) throw squashAtomCommandFailure(result);
145 setRelease(null);
146 setNotice(`Updated to ${result.value.targetVersion}.`);
147 }),
148 },
149 ],
150 );
151 }
152​
153 function requestProviderUpdate(provider: ServerProvider) {
154 if (
155 busy ||
156 !readEnvironmentScope(environmentId, AuthProvidersManageScope) ||
157 !canUpdateEnvironmentProvider(provider)
158 )
159 return;
160 void run(provider.instanceId, async () => {
161 const result = await updateProvider({
162 environmentId,
163 input: {
164 provider: provider.driver,
165 instanceId: provider.instanceId,
166 },
167 });
168 if (AsyncResult.isFailure(result)) throw squashAtomCommandFailure(result);
169 });
170 }
171​
172 return (
173 <SettingsScreen title={environment?.environmentLabel ?? "Environment"}>
174 <ScreenScrollView
175 contentInsetAdjustmentBehavior="automatic"
176 className="flex-1"
177 contentContainerClassName="gap-6 px-5 pt-4"
178 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
179 >
180 {!environment ? (
181 <Text className="text-base text-foreground-muted">
182 This environment is no longer saved on this device.
183 </Text>
184 ) : (
185 <>
186 <SettingsSection title="Connection">
187 <ConnectionEnvironmentRow
188 environment={environment}
189 expanded={connectionExpanded}
190 onToggle={() => setConnectionExpanded((value) => !value)}
191 onReconnect={connections.onReconnectEnvironment}
192 onRemove={connections.onRemoveEnvironmentPress}
193 onSetEnabled={connections.onSetEnvironmentEnabled}
194 onUpdate={connections.onUpdateEnvironment}
195 />
196 </SettingsSection>
197 <EnvironmentRoutesSection
198 environmentId={environmentId}
199 connected={connected}
200 onAddRoute={() =>
201 navigation.navigate("SettingsSheet", {
202 screen: "SettingsContent",
203 params: {
204 screen: "SettingsEnvironmentNew",
205 params: { routeFor: environmentId },
206 },
207 })
208 }
209 />
210 {!connected ? (
211 <Text className="px-2 text-sm text-foreground-muted">
212 Connect this environment to manage it.
213 </Text>
214 ) : !allowed ? (
215 <Text className="px-2 text-sm text-foreground-muted">
216 {AsyncResult.isFailure(sessionResult)
217 ? "Could not verify your permissions. Reconnect to try again."
218 : session === null
219 ? "Checking permissions…"
220 : "This connection does not have permission to manage the environment."}
221 </Text>
222 ) : null}
223 {error ? (
224 <Text selectable className="px-2 text-sm text-danger-foreground">
225 {error}
226 </Text>
227 ) : null}
228 {notice ? <Text className="px-2 text-sm text-foreground-muted">{notice}</Text> : null}
229 {config ? (
230 <>
231 <SettingsSection title="T3 Code">
232 <View className="gap-1 p-4">
233 <Text className="text-base text-foreground">Version {version}</Text>
234 {running ? (
235 <Text className="text-sm text-foreground-muted">
236 {updateState.stage === "resuming"
237 ? "Restarting and reconnecting…"
238 : "Downloading update…"}
239 </Text>
240 ) : updateState.status === "failed" ? (
241 <Text selectable className="text-sm text-danger-foreground">
242 {updateState.message}
243 </Text>
244 ) : null}
245 {checkedRelease ? (
246 <Text className="text-sm text-foreground-muted">
247 {checkedRelease.targetVersion
248 ? `Version ${checkedRelease.targetVersion} is available.`
249 : "You are up to date."}
250 </Text>
251 ) : null}
252 {!supportsEnvironmentUpdate(config.environment.capabilities) ? (
253 <Text className="text-sm text-foreground-muted">
254 {capabilities?.serverSelfUpdate === "desktop-managed"
255 ? "Update the desktop app on this machine."
256 : "Update and restart T3 Code on this machine."}
257 </Text>
258 ) : null}
259 </View>
260 <SettingsActionRow
261 icon="arrow.clockwise"
262 label="Check for updates"
263 disabled={disabled}
264 loading={pending === "check"}
265 onPress={() => {
266 if (disabled) return;
267 void run("check", async () => {
268 const controller = new AbortController();
269 checkController.current = controller;
270 const timeout = setTimeout(() => controller.abort(), 20_000);
271 try {
272 const targetVersion = await findEnvironmentUpdate(
273 config.environment.serverVersion,
274 controller.signal,
275 );
276 setRelease({
277 fromVersion: config.environment.serverVersion,
278 targetVersion,
279 });
280 } finally {
281 clearTimeout(timeout);
282 checkController.current = null;
283 }
284 });
285 }}
286 />
287 {checkedRelease?.targetVersion &&
288 supportsEnvironmentUpdate(config.environment.capabilities) ? (
289 <SettingsActionRow
290 icon="arrow.up.circle"
291 label={`Update to ${checkedRelease.targetVersion}`}
292 disabled={disabled}
293 loading={pending === "server" || running}
294 onPress={requestServerUpdate}
295 />
296 ) : null}
297 </SettingsSection>
298 <SettingsSection title="Providers">
299 <SettingsActionRow
300 icon="arrow.clockwise"
301 label="Refresh providers"
302 disabled={busy || !canRead}
303 loading={pending === "refresh"}
304 onPress={() => {
305 if (busy || !canRead) return;
306 void run("refresh", async () => {
307 if (!readEnvironmentScope(environmentId, AuthOrchestrationReadScope))
308 return;
309 const result = await refreshProviders({ environmentId, input: {} });
310 if (AsyncResult.isFailure(result)) throw squashAtomCommandFailure(result);
311 setNotice("Provider status refreshed.");
312 });
313 }}
314 />
315 {config.providers
316 .filter((provider) => provider.enabled)
317 .map((provider) => (
318 <View key={provider.instanceId}>
319 <View className="gap-1 p-4">
320 <View className="flex-row items-center gap-2">
321 <ProviderIcon provider={provider.driver} size={18} />
322 <Text className="min-w-0 flex-1 text-base font-t3-medium text-foreground">
323 {provider.displayName ?? provider.driver}
324 </Text>
325 </View>
326 <Text className="text-sm text-foreground-muted">
327 {provider.installed
328 ? (provider.version ?? "Version unknown")
329 : "Not installed"}
330 {provider.versionAdvisory?.latestVersion
331 ? ` · Latest ${provider.versionAdvisory.latestVersion}`
332 : ""}
333 </Text>
334 {provider.updateState && provider.updateState.status !== "idle" ? (
335 <Text
336 selectable
337 className={
338 provider.updateState.status === "failed"
339 ? "text-sm text-danger-foreground"
340 : "text-sm text-foreground-muted"
341 }
342 >
343 {provider.updateState.message ??
344 `Update ${provider.updateState.status}`}
345 </Text>
346 ) : null}
347 {provider.compatibilityAdvisory?.message ? (
348 <Text selectable className="text-sm text-foreground-muted">
349 {provider.compatibilityAdvisory.message}
350 </Text>
351 ) : null}
352 {provider.unavailableReason || provider.message ? (
353 <Text selectable className="text-sm text-foreground-muted">
354 {provider.unavailableReason ?? provider.message}
355 </Text>
356 ) : null}
357 {provider.versionAdvisory?.status === "behind_latest" &&
358 !provider.versionAdvisory.canUpdate ? (
359 <Text className="text-sm text-foreground-muted">
360 Update this provider on the environment's machine.
361 </Text>
362 ) : null}
363 </View>
364 {canUpdateEnvironmentProvider(provider) ? (
365 <SettingsActionRow
366 icon="arrow.up.circle"
367 label={`Update ${provider.displayName ?? provider.driver}`}
368 disabled={busy || !canManageProviders}
369 loading={pending === provider.instanceId}
370 onPress={() => requestProviderUpdate(provider)}
371 />
372 ) : null}
373 </View>
374 ))}
375 </SettingsSection>
376 </>
377 ) : null}
378 </>
379 )}
380 </ScreenScrollView>
381 </SettingsScreen>
382 );