The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { useAtomValue } from "@effect/atom-react"; |
| 2 | import { useAuth } from "@clerk/react"; |
| 3 | import { findErrorTraceId, thrownErrorMessage } from "@t3tools/client-runtime/errors"; |
| 4 | import { AuthRelayReadScope, AuthRelayWriteScope, type EnvironmentId } from "@t3tools/contracts"; |
| 5 | import { ManagedRelay } from "@t3tools/client-runtime/relay"; |
| 6 | import { |
| 7 | isAtomCommandInterrupted, |
| 8 | settlePromise, |
| 9 | squashAtomCommandFailure, |
| 10 | } from "@t3tools/client-runtime/state/runtime"; |
| 11 | import * as Schema from "effect/Schema"; |
| 12 | import { useState } from "react"; |
| 13 | import { msg } from "gt-react"; |
| 14 | |
| 15 | import { toastManager } from "../components/ui/toast"; |
| 16 | import { m } from "../i18n/messages"; |
| 17 | import { stackedThreadToast } from "../components/ui/toastHelpers"; |
| 18 | import { relayFailureReason } from "./relayFailureReason"; |
| 19 | import { relayEnvironmentDiscovery } from "../state/relay"; |
| 20 | import { |
| 21 | readEnvironmentCanConfigureRelay, |
| 22 | readEnvironmentScope, |
| 23 | useEnvironmentCanConfigureRelay, |
| 24 | } from "../state/session"; |
| 25 | import { useAtomCommand } from "../state/use-atom-command"; |
| 26 | import { isCloudEnvironmentLinkError } from "./linkEnvironment"; |
| 27 | import { refreshManagedTunnelUsage } from "./managedRelayState"; |
| 28 | import { |
| 29 | linkEnvironment as linkEnvironmentAtom, |
| 30 | unlinkEnvironment as unlinkEnvironmentAtom, |
| 31 | updateEnvironmentPreferences as updateEnvironmentPreferencesAtom, |
| 32 | } from "./linkEnvironmentAtoms"; |
| 33 | import { readCachedCloudLinkState, useCloudLinkState } from "./cloudLinkState"; |
| 34 | import { resolveRelayClerkTokenOptions } from "./publicConfig"; |
| 35 | import { cloudChangeReplacesLink, isManagedTunnelActive } from "./t3ConnectState"; |
| 36 | |
| 37 | export interface CloudLinkDesiredState { |
| 38 | readonly managedTunnel: boolean; |
| 39 | readonly publish: boolean; |
| 40 | readonly holdWebhooksWhileOffline?: boolean; |
| 41 | } |
| 42 | |
| 43 | const isManagedRelayRequestFailedError = Schema.is(ManagedRelay.ManagedRelayRequestFailedError); |
| 44 | const isManagedRelayClientError = Schema.is(ManagedRelay.ManagedRelayClientError); |
| 45 | |
| 46 | /** The account's tunnel cap when the relay refused a new tunnel for being at it. */ |
| 47 | function tunnelLimitFromLinkFailure(cause: unknown): number | null { |
| 48 | if (!isCloudEnvironmentLinkError(cause)) return null; |
| 49 | const relayCause = cause.cause; |
| 50 | if (!isManagedRelayRequestFailedError(relayCause)) return null; |
| 51 | return relayCause.relayError?._tag === "RelayEnvironmentLinkLimitExceededError" |
| 52 | ? relayCause.relayError.maxTunnels |
| 53 | : null; |
| 54 | } |
| 55 | |
| 56 | export function useCloudLinkController(environmentId: EnvironmentId | null) { |
| 57 | const { getToken, isSignedIn } = useAuth(); |
| 58 | const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, { |
| 59 | reportFailure: false, |
| 60 | }); |
| 61 | const linkEnvironment = useAtomCommand(linkEnvironmentAtom, { |
| 62 | reportFailure: false, |
| 63 | }); |
| 64 | const unlinkEnvironment = useAtomCommand(unlinkEnvironmentAtom, { |
| 65 | reportFailure: false, |
| 66 | }); |
| 67 | const updateEnvironmentPreferences = useAtomCommand(updateEnvironmentPreferencesAtom, { |
| 68 | reportFailure: false, |
| 69 | }); |
| 70 | const cloudLinkState = useCloudLinkState(environmentId); |
| 71 | const relayEnvironments = useAtomValue(relayEnvironmentDiscovery.stateValueAtom).environments; |
| 72 | const relayProviderKind = environmentId |
| 73 | ? relayEnvironments.get(environmentId)?.environment.endpoint.providerKind |
| 74 | : undefined; |
| 75 | const [operationError, setOperationError] = useState<string | null>(null); |
| 76 | const [tunnelLimit, setTunnelLimit] = useState<number | null>(null); |
| 77 | |
| 78 | const reportUpdateFailure = (cause: unknown, reason?: string) => { |
| 79 | const message = thrownErrorMessage(cause, m) ?? m(msg("Could not update T3 Connect access.")); |
| 80 | const traceId = findErrorTraceId(cause); |
| 81 | console.error("[t3-connect] Could not update T3 Connect", { message, traceId, cause }); |
| 82 | setOperationError( |
| 83 | traceId ? m(msg("{message} Trace ID: {traceId}", { message, traceId })) : message, |
| 84 | ); |
| 85 | toastManager.add( |
| 86 | stackedThreadToast({ |
| 87 | type: "error", |
| 88 | title: m(msg("Could not update T3 Connect")), |
| 89 | description: reason ?? relayFailureReason(cause) ?? message, |
| 90 | ...(traceId |
| 91 | ? { |
| 92 | actionProps: { |
| 93 | children: m(msg("Copy trace ID")), |
| 94 | onClick: () => void navigator.clipboard?.writeText(traceId), |
| 95 | }, |
| 96 | actionVariant: "outline", |
| 97 | } |
| 98 | : {}), |
| 99 | data: { hideCopyButton: true }, |
| 100 | }), |
| 101 | ); |
| 102 | }; |
| 103 | |
| 104 | const linkData = cloudLinkState.data; |
| 105 | const linkRevoked = linkData?.linkRevoked ?? false; |
| 106 | const managedTunnelActive = linkData ? isManagedTunnelActive(linkData, relayProviderKind) : false; |
| 107 | const managedTunnelOutOfSync = |
| 108 | linkData !== null && !managedTunnelActive && isManagedTunnelActive(linkData, undefined); |
| 109 | const publishAgentActivity = cloudLinkState.data?.publishAgentActivity ?? false; |
| 110 | const holdWebhooksWhileOffline = cloudLinkState.data?.holdWebhooksWhileOffline ?? false; |
| 111 | const linked = !linkRevoked && (cloudLinkState.data?.linked ?? false); |
| 112 | const canConfigureRelay = useEnvironmentCanConfigureRelay(environmentId); |
| 113 | const needsRelayConfiguration = (desired: CloudLinkDesiredState) => |
| 114 | !canConfigureRelay && |
| 115 | linkData !== null && |
| 116 | cloudChangeReplacesLink(linkData, relayProviderKind, desired); |
| 117 | |
| 118 | const reconcileCloudState = async (desired: CloudLinkDesiredState): Promise<boolean> => { |
| 119 | setOperationError(null); |
| 120 | setTunnelLimit(null); |
| 121 | const target = cloudLinkState.target; |
| 122 | if (!target) { |
| 123 | reportUpdateFailure(new Error(m(msg("Choose an environment first.")))); |
| 124 | return false; |
| 125 | } |
| 126 | const environmentId = target.environmentId; |
| 127 | const canManageLink = () => { |
| 128 | if ( |
| 129 | !readEnvironmentScope(environmentId, AuthRelayReadScope) || |
| 130 | !readEnvironmentScope(environmentId, AuthRelayWriteScope) |
| 131 | ) { |
| 132 | reportUpdateFailure( |
| 133 | new Error( |
| 134 | m(msg("This connection needs permission to view and manage T3 Connect settings.")), |
| 135 | ), |
| 136 | ); |
| 137 | return false; |
| 138 | } |
| 139 | return true; |
| 140 | }; |
| 141 | const readLinkState = () => { |
| 142 | const state = readCachedCloudLinkState(target); |
| 143 | if (state === null) { |
| 144 | reportUpdateFailure( |
| 145 | new Error(m(msg("Wait until the current T3 Connect settings can be read."))), |
| 146 | ); |
| 147 | } |
| 148 | return state; |
| 149 | }; |
| 150 | if (!canManageLink()) return false; |
| 151 | const wantsLink = desired.managedTunnel || desired.publish; |
| 152 | if (wantsLink && readLinkState() === null) return false; |
| 153 | const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions())); |
| 154 | if (!canManageLink()) return false; |
| 155 | |
| 156 | // A failed mutation may have partially applied, so refresh server state on every exit. |
| 157 | if (!wantsLink) { |
| 158 | // Unlink needs no relay token; failed token reads must still allow it. |
| 159 | const unlinkResult = await unlinkEnvironment({ |
| 160 | target, |
| 161 | clerkToken: tokenResult._tag === "Success" ? (tokenResult.value ?? null) : null, |
| 162 | }); |
| 163 | refreshManagedTunnelUsage(); |
| 164 | if (unlinkResult._tag === "Failure") { |
| 165 | if (!isAtomCommandInterrupted(unlinkResult)) { |
| 166 | const cause = squashAtomCommandFailure(unlinkResult); |
| 167 | // Only the relay delete fails with a relay error, and it runs after the local unlink. |
| 168 | const relayKeptLink = |
| 169 | isCloudEnvironmentLinkError(cause) && isManagedRelayClientError(cause.cause); |
| 170 | reportUpdateFailure( |
| 171 | cause, |
| 172 | relayKeptLink |
| 173 | ? m(msg("Disconnected here, but T3 Connect still lists it. Remove it in Account.")) |
| 174 | : undefined, |
| 175 | ); |
| 176 | } |
| 177 | cloudLinkState.refresh(); |
| 178 | await refreshRelayEnvironments(); |
| 179 | return false; |
| 180 | } |
| 181 | } else { |
| 182 | const currentLinkState = readLinkState(); |
| 183 | if (currentLinkState === null) return false; |
| 184 | if (tokenResult._tag === "Failure") { |
| 185 | reportUpdateFailure(squashAtomCommandFailure(tokenResult)); |
| 186 | return false; |
| 187 | } |
| 188 | const clerkToken = tokenResult.value; |
| 189 | if (!clerkToken) { |
| 190 | reportUpdateFailure(new Error(m(msg("Sign in to T3 Connect before enabling this.")))); |
| 191 | return false; |
| 192 | } |
| 193 | if (cloudChangeReplacesLink(currentLinkState, relayProviderKind, desired)) { |
| 194 | if (!readEnvironmentCanConfigureRelay(environmentId)) { |
| 195 | reportUpdateFailure( |
| 196 | new Error( |
| 197 | m( |
| 198 | msg( |
| 199 | "This connection needs the relay configuration permission to configure T3 Connect.", |
| 200 | ), |
| 201 | ), |
| 202 | ), |
| 203 | ); |
| 204 | return false; |
| 205 | } |
| 206 | const linkResult = await linkEnvironment({ |
| 207 | target, |
| 208 | clerkToken, |
| 209 | mode: desired.managedTunnel ? "managed" : "publish_only", |
| 210 | }); |
| 211 | // Any link attempt can change the account's tunnel count. |
| 212 | refreshManagedTunnelUsage(); |
| 213 | if (linkResult._tag === "Failure") { |
| 214 | if (!isAtomCommandInterrupted(linkResult)) { |
| 215 | const cause = squashAtomCommandFailure(linkResult); |
| 216 | // The caller shows an upgrade prompt instead of an error. |
| 217 | const limit = tunnelLimitFromLinkFailure(cause); |
| 218 | if (limit === null) reportUpdateFailure(cause); |
| 219 | else setTunnelLimit(limit); |
| 220 | } |
| 221 | cloudLinkState.refresh(); |
| 222 | return false; |
| 223 | } |
| 224 | } |
| 225 | if (!canManageLink() || readLinkState() === null) { |
| 226 | cloudLinkState.refresh(); |
| 227 | return false; |
| 228 | } |
| 229 | const prefResult = await updateEnvironmentPreferences({ |
| 230 | target, |
| 231 | publishAgentActivity: desired.publish, |
| 232 | ...(desired.holdWebhooksWhileOffline === undefined |
| 233 | ? {} |
| 234 | : { holdWebhooksWhileOffline: desired.holdWebhooksWhileOffline }), |
| 235 | }); |
| 236 | if (prefResult._tag === "Failure") { |
| 237 | if (!isAtomCommandInterrupted(prefResult)) { |
| 238 | reportUpdateFailure(squashAtomCommandFailure(prefResult)); |
| 239 | } |
| 240 | cloudLinkState.refresh(); |
| 241 | return false; |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | cloudLinkState.refresh(); |
| 246 | const refreshResult = await refreshRelayEnvironments(); |
| 247 | if (refreshResult._tag === "Failure" && !isAtomCommandInterrupted(refreshResult)) { |
| 248 | reportUpdateFailure(squashAtomCommandFailure(refreshResult)); |
| 249 | return false; |
| 250 | } |
| 251 | return true; |
| 252 | }; |
| 253 | |
| 254 | return { |
| 255 | isSignedIn, |
| 256 | linkState: cloudLinkState, |
| 257 | linked, |
| 258 | linkRevoked, |
| 259 | managedTunnelActive, |
| 260 | managedTunnelOutOfSync, |
| 261 | publishAgentActivity, |
| 262 | holdWebhooksWhileOffline, |
| 263 | operationError, |
| 264 | tunnelLimit, |
| 265 | needsRelayConfiguration, |
| 266 | reconcileCloudState, |
| 267 | }; |
| 268 | } |