Open History to see the last commit
1import { useAuth } from "@clerk/react";
2import { findErrorTraceId } from "@t3tools/client-runtime/errors";
3import { EnvironmentId, AuthRelayReadScope, AuthRelayWriteScope } from "@t3tools/contracts";
4import {
5 isAtomCommandInterrupted,
6 settlePromise,
7 squashAtomCommandFailure,
8} from "@t3tools/client-runtime/state/runtime";
9import { useState } from "react";
10
11import { toastManager } from "../components/ui/toast";
12import { relayEnvironmentDiscovery } from "../state/relay";
13import { readEnvironmentScope } from "../state/session";
14import { useAtomCommand } from "../state/use-atom-command";
15import {
16 linkPrimaryEnvironment as linkPrimaryEnvironmentAtom,
17 unlinkPrimaryEnvironment as unlinkPrimaryEnvironmentAtom,
18 updatePrimaryEnvironmentPreferences as updatePrimaryEnvironmentPreferencesAtom,
19} from "./linkEnvironmentAtoms";
20import { readCachedPrimaryCloudLinkState, usePrimaryCloudLinkState } from "./primaryCloudLinkState";
21import { resolveRelayClerkTokenOptions } from "./publicConfig";
22
23export interface CloudLinkDesiredState {
24 readonly managedTunnel: boolean;
25 readonly publish: boolean;
26 /** Omit to leave the webhook-hold setting as it is. */
27 readonly holdWebhooksWhileOffline?: boolean;
28}
29
30/**
31 * Drives the primary environment's T3 Connect link. T3 Connect (managed
32 * tunnel) and agent-activity publishing are independent capabilities backed by
33 * a single relay link, so consumers express the full desired state and
34 * `reconcileCloudState` applies it: unlink when neither is wanted, otherwise
35 * (re)link with the mode the managed-tunnel bit implies and set the publish
36 * preference. Re-linking only happens when the managed-tunnel mode actually
37 * changes, so flipping publish alone is cheap.
38 */
39export function useCloudLinkController() {
40 const { getToken, isSignedIn } = useAuth();
41 const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
42 reportFailure: false,
43 });
44 const linkPrimaryEnvironment = useAtomCommand(linkPrimaryEnvironmentAtom, {
45 reportFailure: false,
46 });
47 const unlinkPrimaryEnvironment = useAtomCommand(unlinkPrimaryEnvironmentAtom, {
48 reportFailure: false,
49 });
50 const updatePrimaryEnvironmentPreferences = useAtomCommand(
51 updatePrimaryEnvironmentPreferencesAtom,
52 { reportFailure: false },
53 );
54 const primaryCloudLinkState = usePrimaryCloudLinkState();
55 const [operationError, setOperationError] = useState<string | null>(null);
56
57 const reportUpdateFailure = (cause: unknown) => {
58 const message = cause instanceof Error ? cause.message : "Could not update T3 Connect access.";
59 const traceId = findErrorTraceId(cause);
60 console.error("[t3-connect] Could not update T3 Connect", { message, traceId, cause });
61 setOperationError(traceId ? `${message} Trace ID: ${traceId}` : message);
62 toastManager.add({
63 type: "error",
64 title: "Could not update T3 Connect",
65 description: message,
66 data: traceId
67 ? {
68 secondaryActionProps: {
69 children: "Copy trace ID",
70 onClick: () => void navigator.clipboard?.writeText(traceId),
71 },
72 }
73 : undefined,
74 });
75 };
76
77 // Older environment servers predate the managedTunnelActive field; for them a
78 // link always implies a managed tunnel, so fall back to `linked`.
79 const managedTunnelActive =
80 primaryCloudLinkState.data?.managedTunnelActive ?? primaryCloudLinkState.data?.linked ?? false;
81 const publishAgentActivity = primaryCloudLinkState.data?.publishAgentActivity ?? false;
82 const holdWebhooksWhileOffline = primaryCloudLinkState.data?.holdWebhooksWhileOffline ?? false;
83 const linked = primaryCloudLinkState.data?.linked ?? false;
84
85 const reconcileCloudState = async (desired: CloudLinkDesiredState): Promise<boolean> => {
86 setOperationError(null);
87 const target = primaryCloudLinkState.target;
88 if (!target) {
89 reportUpdateFailure(new Error("Local environment is not ready yet."));
90 return false;
91 }
92 const environmentId = EnvironmentId.make(target.environmentId);
93 const canManageLink = () => {
94 if (
95 !readEnvironmentScope(environmentId, AuthRelayReadScope) ||
96 !readEnvironmentScope(environmentId, AuthRelayWriteScope)
97 ) {
98 reportUpdateFailure(
99 new Error("This connection needs permission to view and manage T3 Connect settings."),
100 );
101 return false;
102 }
103 return true;
104 };
105 const readLinkState = () => {
106 const state = readCachedPrimaryCloudLinkState(target);
107 if (state === null) {
108 reportUpdateFailure(new Error("Wait until the current T3 Connect settings can be read."));
109 }
110 return state;
111 };
112 if (!canManageLink()) return false;
113 const wantsLink = desired.managedTunnel || desired.publish;
114 if (wantsLink && readLinkState() === null) return false;
115 const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
116 if (!canManageLink()) return false;
117
118 // A failure after this point may follow a partially applied mutation (e.g.
119 // the link succeeded but the preference update did not), so every exit —
120 // success or failure — refreshes the rendered state to whatever the server
121 // actually holds now.
122 if (!wantsLink) {
123 // Unlink works without a relay token — a failed token read must not
124 // leave the user unable to turn T3 Connect off.
125 const unlinkResult = await unlinkPrimaryEnvironment({
126 target,
127 clerkToken: tokenResult._tag === "Success" ? (tokenResult.value ?? null) : null,
128 });
129 if (unlinkResult._tag === "Failure") {
130 if (!isAtomCommandInterrupted(unlinkResult)) {
131 reportUpdateFailure(squashAtomCommandFailure(unlinkResult));
132 }
133 primaryCloudLinkState.refresh();
134 return false;
135 }
136 } else {
137 const currentLinkState = readLinkState();
138 if (currentLinkState === null) return false;
139 if (tokenResult._tag === "Failure") {
140 reportUpdateFailure(squashAtomCommandFailure(tokenResult));
141 return false;
142 }
143 const clerkToken = tokenResult.value;
144 if (!clerkToken) {
145 reportUpdateFailure(new Error("Sign in to T3 Connect before enabling this."));
146 return false;
147 }
148 const currentManagedTunnel = currentLinkState.managedTunnelActive ?? currentLinkState.linked;
149 if (!currentLinkState.linked || currentManagedTunnel !== desired.managedTunnel) {
150 const linkResult = await linkPrimaryEnvironment({
151 target,
152 clerkToken,
153 mode: desired.managedTunnel ? "managed" : "publish_only",
154 });
155 if (linkResult._tag === "Failure") {
156 if (!isAtomCommandInterrupted(linkResult)) {
157 reportUpdateFailure(squashAtomCommandFailure(linkResult));
158 }
159 primaryCloudLinkState.refresh();
160 return false;
161 }
162 }
163 if (!canManageLink() || readLinkState() === null) {
164 primaryCloudLinkState.refresh();
165 return false;
166 }
167 const prefResult = await updatePrimaryEnvironmentPreferences({
168 target,
169 publishAgentActivity: desired.publish,
170 ...(desired.holdWebhooksWhileOffline === undefined
171 ? {}
172 : { holdWebhooksWhileOffline: desired.holdWebhooksWhileOffline }),
173 });
174 if (prefResult._tag === "Failure") {
175 if (!isAtomCommandInterrupted(prefResult)) {
176 reportUpdateFailure(squashAtomCommandFailure(prefResult));
177 }
178 primaryCloudLinkState.refresh();
179 return false;
180 }
181 }
182
183 primaryCloudLinkState.refresh();
184 const refreshResult = await refreshRelayEnvironments();
185 if (refreshResult._tag === "Failure" && !isAtomCommandInterrupted(refreshResult)) {
186 reportUpdateFailure(squashAtomCommandFailure(refreshResult));
187 return false;
188 }
189 return true;
190 };
191
192 return {
193 isSignedIn,
194 linkState: primaryCloudLinkState,
195 linked,
196 managedTunnelActive,
197 publishAgentActivity,
198 holdWebhooksWhileOffline,
199 operationError,
200 reconcileCloudState,
201 };
202}