The best way to control Claude Code, Codex and more from any computer or phone

main
ts 247 lines 9.13 KB
Raw
1 import * as Dialog from "../components/ui/Dialog";
2 import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
3 import { useAtomValue } from "@effect/atom-react";
4 import { useNavigation } from "@react-navigation/native";
5 import { Discovery } from "@t3tools/client-runtime/relay";
6 import type { EnvironmentId } from "@t3tools/contracts";
7 import * as Cause from "effect/Cause";
8 import { msg } from "gt-react-native";
9 import { AsyncResult, Atom } from "effect/reactivity";
10 import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
11
12 import { hasCloudPublicConfig } from "../features/cloud/publicConfig";
13 import { m } from "../i18n/messages";
14 import { useConnectionController } from "../features/connection/useConnectionController";
15 import { useRetryEnvironment } from "../features/connection/useRetryEnvironment";
16 import { environmentPresentations } from "./presentation";
17 import { useWorkspaceConnectionState, useWorkspaceEnvironments } from "./workspace";
18 import type { SavedRemoteConnection } from "../lib/connection";
19 import { appAtomRegistry } from "./atom-registry";
20 import type { ConnectedEnvironmentSummary, EnvironmentRuntimeState } from "./remote-runtime-types";
21 import { environmentSession } from "./session";
22 import { environmentCatalog } from "../connection/catalog";
23 import { createRemoteEnvironmentProjectionAtoms } from "./remote-environment-projections";
24 import { serverEnvironment } from "./server";
25 import { relayEnvironmentDiscovery } from "./relay";
26 import { connectPairingUrl as connectPairingUrlCommand } from "../connection/onboarding";
27
28 const RELAY_REMOVAL_ACCOUNT_NOTE: Record<Discovery.RelayEnvironmentRegistration, string> = {
29 registered: msg(
30 "It stays on your {connect} account and keeps its host space. Deregister it under {account} → {connect} to free it.",
31 { connect: "T3 Connect", account: "T3 Account" },
32 ),
33 unregistered: msg("It's no longer on your {connect} account.", { connect: "T3 Connect" }),
34 unknown: msg(
35 "This doesn't change your {connect} account. To deregister it there, use {account} → {connect}.",
36 { connect: "T3 Connect", account: "T3 Account" },
37 ),
38 };
39
40 const connectionPairingUrlAtom = Atom.make("").pipe(
41 Atom.keepAlive,
42 Atom.withLabel("mobile:connection-pairing-url"),
43 );
44
45 const pendingConnectionErrorAtom = Atom.make<string | null>(null).pipe(
46 Atom.keepAlive,
47 Atom.withLabel("mobile:pending-connection-error"),
48 );
49
50 export function setPendingConnectionError(message: string | null): void {
51 appAtomRegistry.set(pendingConnectionErrorAtom, message);
52 }
53
54 export interface PairingOutcome {
55 readonly ok: boolean;
56 /** Shown beside the pairing form; null when the failure got its own dialog. */
57 readonly error: string | null;
58 }
59
60 /** Pairs with the environment behind a pairing link and saves it. */
61 export async function pairEnvironment(
62 pairingUrl: string,
63 expectedEnvironmentId?: EnvironmentId,
64 ): Promise<PairingOutcome> {
65 const result = await runAtomCommand(
66 appAtomRegistry,
67 connectPairingUrlCommand,
68 { pairingUrl, ...(expectedEnvironmentId === undefined ? {} : { expectedEnvironmentId }) },
69 { reportFailure: false },
70 );
71 if (AsyncResult.isSuccess(result)) {
72 appAtomRegistry.set(connectionPairingUrlAtom, "");
73 return { ok: true, error: null };
74 }
75 const error = Cause.squash(result.cause);
76 const message = errorDisplayMessage(error, m) ?? m(msg("Failed to pair with the environment."));
77 if (
78 error !== null &&
79 typeof error === "object" &&
80 "reason" in error &&
81 error.reason === "unsupported"
82 ) {
83 Dialog.alert(m(msg("Client not supported")), message);
84 return { ok: false, error: null };
85 }
86 return { ok: false, error: message };
87 }
88
89 const remoteEnvironmentProjections = createRemoteEnvironmentProjectionAtoms({
90 presentationAtom: environmentPresentations.presentationAtom,
91 preparedConnectionAtom: environmentSession.preparedConnectionValueAtom,
92 serverConfigAtom: serverEnvironment.configValueAtom,
93 });
94
95 export const environmentConnectedAtom = Atom.family((environmentId: EnvironmentId) =>
96 Atom.make(
97 (get) =>
98 get(remoteEnvironmentProjections.runtimeStateAtom(environmentId))?.connectionState ===
99 "connected",
100 ).pipe(Atom.withLabel(`mobile:environment-connected:${environmentId}`)),
101 );
102
103 const EMPTY_SAVED_CONNECTION_ATOM = Atom.make<SavedRemoteConnection | null>(null).pipe(
104 Atom.withLabel("mobile:saved-connection:empty"),
105 );
106
107 const EMPTY_RUNTIME_STATE_ATOM = Atom.make<EnvironmentRuntimeState | null>(null).pipe(
108 Atom.withLabel("mobile:environment-runtime-state:empty"),
109 );
110
111 export const savedConnectionsByIdAtom = Atom.make((get) => {
112 const catalog = get(environmentCatalog.catalogValueAtom);
113 return Object.fromEntries(
114 [...catalog.entries.keys()].flatMap((environmentId) => {
115 const connection = get(remoteEnvironmentProjections.savedConnectionAtom(environmentId));
116 return connection === null ? [] : [[environmentId, connection]];
117 }),
118 ) as Record<EnvironmentId, SavedRemoteConnection>;
119 }).pipe(Atom.withLabel("mobile:saved-connections-by-id"));
120
121 export function useSavedRemoteConnections() {
122 const catalog = useAtomValue(environmentCatalog.catalogValueAtom);
123 const savedConnectionsById = useAtomValue(savedConnectionsByIdAtom);
124
125 return {
126 isLoadingSavedConnection: !catalog.isReady,
127 savedConnectionsById,
128 };
129 }
130
131 export function useSavedRemoteConnection(
132 environmentId: EnvironmentId | null,
133 ): SavedRemoteConnection | null {
134 return useAtomValue(
135 environmentId === null
136 ? EMPTY_SAVED_CONNECTION_ATOM
137 : remoteEnvironmentProjections.savedConnectionAtom(environmentId),
138 );
139 }
140
141 export function useRemoteEnvironmentRuntime(
142 environmentId: EnvironmentId | null,
143 ): EnvironmentRuntimeState | null {
144 return useAtomValue(
145 environmentId === null
146 ? EMPTY_RUNTIME_STATE_ATOM
147 : remoteEnvironmentProjections.runtimeStateAtom(environmentId),
148 );
149 }
150
151 export function useRemoteConnectionStatus() {
152 const state = useWorkspaceConnectionState();
153 const connectedEnvironments: ReadonlyArray<ConnectedEnvironmentSummary> =
154 useWorkspaceEnvironments();
155 const pendingConnectionError = useAtomValue(pendingConnectionErrorAtom);
156
157 return {
158 connectedEnvironments,
159 connectionState: state.connectionState,
160 connectionError: pendingConnectionError ?? state.connectionError,
161 };
162 }
163
164 export function useRemoteConnections() {
165 const controller = useConnectionController();
166 const navigation = useNavigation();
167 const connectionPairingUrl = useAtomValue(connectionPairingUrlAtom);
168 const { connectedEnvironments, connectionError, connectionState } = useRemoteConnectionStatus();
169
170 const onChangeConnectionPairingUrl = (pairingUrl: string) => {
171 appAtomRegistry.set(connectionPairingUrlAtom, pairingUrl);
172 };
173
174 const onConnectPress = (pairingUrl?: string, expectedEnvironmentId?: EnvironmentId) =>
175 pairEnvironment(pairingUrl ?? connectionPairingUrl, expectedEnvironmentId);
176
177 const onReconnectEnvironment = useRetryEnvironment();
178 const onSetEnvironmentEnabled = (environmentId: EnvironmentId, enabled: boolean) =>
179 controller.setEnvironmentEnabled(environmentId, enabled);
180 const onUpdateEnvironment = (
181 environmentId: EnvironmentId,
182 updates: { readonly label: string; readonly displayUrl: string },
183 ) => controller.updateEnvironment(environmentId, updates);
184
185 const onRemoveEnvironmentPress = (environmentId: EnvironmentId) => {
186 const environment = connectedEnvironments.find(
187 (candidate) => candidate.environmentId === environmentId,
188 );
189 if (!environment) {
190 return;
191 }
192 const remove = {
193 text: m(msg("Remove")),
194 style: "destructive",
195 onPress: () => {
196 void controller.removeEnvironment(environmentId);
197 },
198 } as const;
199 if (environment.isRelayManaged) {
200 const registration = Discovery.relayEnvironmentRegistration(
201 appAtomRegistry.get(relayEnvironmentDiscovery.stateValueAtom),
202 environmentId,
203 );
204 const openAccount = {
205 text: m(msg("Open {account}", { account: "T3 Account" })),
206 onPress: () => navigation.navigate("SettingsAuth"),
207 };
208 const cancel = { text: m(msg("Cancel")), style: "cancel" } as const;
209 Dialog.alert(
210 m(msg("Remove from this device?")),
211 `${m(
212 msg("Forget {name} and its cached threads on this device.", {
213 name: environment.environmentLabel,
214 }),
215 )}\n\n${m(RELAY_REMOVAL_ACCOUNT_NOTE[registration])}`,
216 registration === "unregistered" || !hasCloudPublicConfig()
217 ? [cancel, remove]
218 : [cancel, openAccount, remove],
219 );
220 return;
221 }
222 Dialog.alert(
223 m(msg("Remove from this device?")),
224 m(
225 msg(
226 "Forget {name} and its cached threads on this device. Switch it off instead to keep it saved.",
227 { name: environment.environmentLabel },
228 ),
229 ),
230 [{ text: m(msg("Cancel")), style: "cancel" }, remove],
231 );
232 };
233
234 return {
235 connectionPairingUrl,
236 connectionState,
237 connectionError,
238 connectedEnvironments,
239 connectedEnvironmentCount: connectedEnvironments.length,
240 onChangeConnectionPairingUrl,
241 onConnectPress,
242 onReconnectEnvironment,
243 onSetEnvironmentEnabled,
244 onUpdateEnvironment,
245 onRemoveEnvironmentPress,
246 };
247 }