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