Open History to see the last commit
1import { useAuth } from "@clerk/react";
2import { AuthAdministrativeScopes, AuthRelayWriteScope } from "@t3tools/contracts";
3import { useEffect, useRef, useState } from "react";
4
5import {
6 CONNECT_ONBOARDING_OPT_OUT_STORAGE_KEY,
7 ConnectOnboardingOptOutSchema,
8 EMPTY_CONNECT_ONBOARDING_OPT_OUT_STATE,
9} from "~/cloud/connectOnboarding";
10import { hasCloudPublicConfig } from "~/cloud/publicConfig";
11import { useCloudLinkController } from "~/cloud/useCloudLinkController";
12import { usePrimarySessionState } from "~/environments/primary";
13import { useLocalStorage } from "~/hooks/useLocalStorage";
14import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";
15import { CloudEnvironmentConnectRows } from "./CloudEnvironmentConnectList";
16import { Button } from "../ui/button";
17import { Checkbox } from "../ui/checkbox";
18import {
19 Dialog,
20 DialogDescription,
21 DialogFooter,
22 DialogHeader,
23 DialogPanel,
24 DialogPopup,
25 DialogTitle,
26} from "../ui/dialog";
27import { Switch } from "../ui/switch";
28import { toastManager } from "../ui/toast";
29import { WizardSteps } from "../ui/wizard-steps";
30
31/**
32 * Post-sign-in onboarding wizard for T3 Connect. Opens on every in-session
33 * sign-in — sign-out removes the connected relay environments, so each new
34 * session starts with no devices to reach. It first prompts to publish this
35 * environment (managed tunnel + agent activity, both defaulting on) when the
36 * current session is authorized to manage the relay link, then lists the
37 * account's T3 Connect environments so every device can be connected right
38 * away. A cold load with a restored session does not count as a sign-in.
39 */
40export function ConnectOnboardingDialog() {
41 if (!hasCloudPublicConfig()) return null;
42
43 return <ConfiguredConnectOnboardingDialog />;
44}
45
46type OnboardingStep = "publish" | "devices";
47
48function ConfiguredConnectOnboardingDialog() {
49 // Mirrors ManagedRelayAuthProvider: a pending Clerk session must not read as
50 // signed-out, or its later activation would look like a fresh sign-in.
51 const { isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
52 const [optOutState, setOptOutState] = useLocalStorage(
53 CONNECT_ONBOARDING_OPT_OUT_STORAGE_KEY,
54 EMPTY_CONNECT_ONBOARDING_OPT_OUT_STATE,
55 ConnectOnboardingOptOutSchema,
56 );
57
58 const desktopBridge = window.desktopBridge;
59 const primarySessionState = usePrimarySessionState();
60 const currentSessionScopes = desktopBridge
61 ? AuthAdministrativeScopes
62 : primarySessionState.data?.authenticated
63 ? (primarySessionState.data.scopes ?? null)
64 : null;
65 const canManageRelay = currentSessionScopes?.includes(AuthRelayWriteScope) ?? false;
66 // The publish step is only offered when we know the answer; opening the
67 // wizard before the session state resolves would let the step set change
68 // mid-flight. A failed session read still opens the wizard — it just means
69 // no publish step.
70 const sessionScopesKnown =
71 Boolean(desktopBridge) ||
72 primarySessionState.data !== null ||
73 primarySessionState.error !== null;
74
75 const controller = useCloudLinkController();
76 const showPublishStep = canManageRelay && controller.linkState.target !== null;
77 const steps: ReadonlyArray<OnboardingStep> = showPublishStep
78 ? ["publish", "devices"]
79 : ["devices"];
80
81 const [requestedAccount, setRequestedAccount] = useState<string | null>(null);
82 const [openForAccount, setOpenForAccount] = useState<string | null>(null);
83 const [step, setStep] = useState<OnboardingStep>("devices");
84 const [exposeEnvironment, setExposeEnvironment] = useState(true);
85 const [publishAgentActivity, setPublishAgentActivity] = useState(true);
86 const [dontShowAgain, setDontShowAgain] = useState(false);
87 const [isApplying, setIsApplying] = useState(false);
88 const prefilledFromLinkStateRef = useRef(false);
89 const observedAccountRef = useRef<string | null | undefined>(undefined);
90
91 const optOutAccounts = optOutState.optOutAccounts;
92
93 // Every sign-in or account switch that completes during this session
94 // requests the wizard — account transitions clear the connected relay
95 // environments, so each new session starts with no devices to reach. A cold
96 // load observes undefined → account and must not re-prompt.
97 useEffect(() => {
98 if (!isLoaded) return;
99 // A loaded-but-incomplete snapshot (signed in, user id not yet populated)
100 // must not be recorded as signed-out — the next render would then look
101 // like a fresh sign-in on a cold load.
102 if (isSignedIn && !userId) return;
103 const previousAccount = observedAccountRef.current;
104 const nextAccount = isSignedIn && userId ? userId : null;
105 observedAccountRef.current = nextAccount;
106 if (previousAccount !== undefined && previousAccount !== nextAccount && nextAccount !== null) {
107 setRequestedAccount(nextAccount);
108 }
109 }, [isLoaded, isSignedIn, userId]);
110
111 // A manageable session implies a primary environment, so when the scopes
112 // allow publishing, wait for the connection target too — otherwise the
113 // wizard could open on the devices step moments before the publish step
114 // becomes available and freeze there.
115 const publishStepDecided = !canManageRelay || controller.linkState.target !== null;
116
117 // Open once the session scopes resolve so the step set is stable. Accounts
118 // that chose "Don't show this again" are skipped.
119 useEffect(() => {
120 if (requestedAccount === null || openForAccount !== null) return;
121 if (optOutAccounts.includes(requestedAccount)) {
122 setRequestedAccount(null);
123 return;
124 }
125 if (!sessionScopesKnown || !publishStepDecided) return;
126 setRequestedAccount(null);
127 prefilledFromLinkStateRef.current = false;
128 setExposeEnvironment(true);
129 setPublishAgentActivity(true);
130 setDontShowAgain(false);
131 setStep(canManageRelay && controller.linkState.target !== null ? "publish" : "devices");
132 setOpenForAccount(requestedAccount);
133 }, [
134 canManageRelay,
135 controller.linkState.target,
136 openForAccount,
137 optOutAccounts,
138 publishStepDecided,
139 requestedAccount,
140 sessionScopesKnown,
141 ]);
142
143 // Signing out (or switching accounts) mid-wizard invalidates everything the
144 // wizard would do — close it and let the sign-in trigger re-evaluate.
145 useEffect(() => {
146 if (openForAccount !== null && (!isSignedIn || userId !== openForAccount)) {
147 setOpenForAccount(null);
148 }
149 if (requestedAccount !== null && (!isSignedIn || userId !== requestedAccount)) {
150 setRequestedAccount(null);
151 }
152 }, [isSignedIn, openForAccount, requestedAccount, userId]);
153
154 // Toggles default on, but an environment that is already linked should show
155 // its actual configuration instead of silently proposing to rewrite it.
156 // Only when the link belongs to the account being onboarded, though — after
157 // an account switch the cached link state can still describe the previous
158 // account's setup.
159 const linkStateData = controller.linkState.data;
160 useEffect(() => {
161 if (openForAccount === null || prefilledFromLinkStateRef.current || linkStateData === null) {
162 return;
163 }
164 prefilledFromLinkStateRef.current = true;
165 if (linkStateData.linked && linkStateData.cloudUserId === openForAccount) {
166 setExposeEnvironment(linkStateData.managedTunnelActive ?? linkStateData.linked);
167 setPublishAgentActivity(linkStateData.publishAgentActivity);
168 }
169 }, [linkStateData, openForAccount]);
170
171 const complete = () => {
172 // Keep the wizard up while a link request is in flight so its outcome
173 // (and any failure) stays visible.
174 if (isApplying) return;
175 const account = openForAccount;
176 setOpenForAccount(null);
177 if (account !== null && dontShowAgain) {
178 setOptOutState((state) =>
179 state.optOutAccounts.includes(account)
180 ? state
181 : { optOutAccounts: [...state.optOutAccounts, account] },
182 );
183 }
184 };
185
186 const applyPublishSelection = async () => {
187 // The wizard only ever enables — with both toggles off there is nothing to
188 // apply, and an existing link must not be torn down from onboarding.
189 if (!exposeEnvironment && !publishAgentActivity) {
190 setStep("devices");
191 return;
192 }
193 setIsApplying(true);
194 const ok = await controller.reconcileCloudState({
195 managedTunnel: exposeEnvironment,
196 publish: publishAgentActivity,
197 });
198 setIsApplying(false);
199 if (!ok) return;
200 toastManager.add({
201 type: "success",
202 title: "T3 Connect enabled",
203 description: exposeEnvironment
204 ? "This environment is available to your other devices through T3 Connect."
205 : "This environment publishes agent activity to your mobile clients.",
206 });
207 setStep("devices");
208 };
209
210 return (
211 <Dialog
212 open={openForAccount !== null}
213 onOpenChange={(open) => {
214 // Keep the dialog up while a link request is in flight so its outcome
215 // (and any failure) stays visible.
216 if (!open && !isApplying) complete();
217 }}
218 >
219 <DialogPopup className="max-w-xl">
220 <DialogHeader>
221 <DialogTitle>Set up T3 Connect</DialogTitle>
222 <DialogDescription>
223 Mesh your devices together — publish this environment and connect the rest, all in one
224 place.
225 </DialogDescription>
226 {steps.length > 1 ? (
227 <WizardSteps
228 steps={steps.map((id) => ({ id, label: STEP_LABELS[id] }))}
229 currentStep={step}
230 disabled={isApplying}
231 onStepSelect={setStep}
232 />
233 ) : null}
234 </DialogHeader>
235 <DialogPanel>
236 {step === "publish" ? (
237 <PublishStep
238 exposeEnvironment={exposeEnvironment}
239 publishAgentActivity={publishAgentActivity}
240 disabled={isApplying}
241 operationError={controller.operationError}
242 onExposeEnvironmentChange={setExposeEnvironment}
243 onPublishAgentActivityChange={setPublishAgentActivity}
244 />
245 ) : (
246 <DevicesStep />
247 )}
248 </DialogPanel>
249 <DialogFooter variant="bare" className="sm:justify-between">
250 <label className="flex cursor-pointer items-center gap-2 self-start text-xs text-muted-foreground sm:self-center">
251 <Checkbox
252 checked={dontShowAgain}
253 onCheckedChange={(checked) => setDontShowAgain(checked === true)}
254 />
255 Don't show this again
256 </label>
257 <div className="flex flex-col-reverse gap-2 sm:flex-row">
258 {step === "publish" ? (
259 <>
260 <Button variant="ghost" disabled={isApplying} onClick={() => setStep("devices")}>
261 Not now
262 </Button>
263 <Button
264 disabled={
265 isApplying || (controller.linkState.isPending && linkStateData === null)
266 }
267 onClick={() => void applyPublishSelection()}
268 >
269 {isApplying ? "Enabling…" : "Continue"}
270 </Button>
271 </>
272 ) : (
273 <Button disabled={isApplying} onClick={complete}>
274 Done
275 </Button>
276 )}
277 </div>
278 </DialogFooter>
279 </DialogPopup>
280 </Dialog>
281 );
282}
283
284const STEP_LABELS: Record<OnboardingStep, string> = {
285 publish: "Publish",
286 devices: "Connect devices",
287};
288
289function PublishStep({
290 exposeEnvironment,
291 publishAgentActivity,
292 disabled,
293 operationError,
294 onExposeEnvironmentChange,
295 onPublishAgentActivityChange,
296}: {
297 readonly exposeEnvironment: boolean;
298 readonly publishAgentActivity: boolean;
299 readonly disabled: boolean;
300 readonly operationError: string | null;
301 readonly onExposeEnvironmentChange: (enabled: boolean) => void;
302 readonly onPublishAgentActivityChange: (enabled: boolean) => void;
303}) {
304 return (
305 <div className="space-y-3">
306 <div className="rounded-lg border">
307 <OnboardingToggleRow
308 title="Publish this environment"
309 description="Make this environment available to your other devices through T3 Connect."
310 checked={exposeEnvironment}
311 disabled={disabled}
312 onCheckedChange={onExposeEnvironmentChange}
313 />
314 <OnboardingToggleRow
315 title="Publish agent activity"
316 description="Send activity from this environment to your mobile clients for push notifications and Live Activities."
317 checked={publishAgentActivity}
318 disabled={disabled}
319 onCheckedChange={onPublishAgentActivityChange}
320 />
321 </div>
322 {operationError ? <p className="text-xs text-destructive">{operationError}</p> : null}
323 </div>
324 );
325}
326
327function OnboardingToggleRow({
328 title,
329 description,
330 checked,
331 disabled,
332 onCheckedChange,
333}: {
334 readonly title: string;
335 readonly description: string;
336 readonly checked: boolean;
337 readonly disabled: boolean;
338 readonly onCheckedChange: (enabled: boolean) => void;
339}) {
340 return (
341 <div className="flex items-start justify-between gap-4 border-t border-border/60 px-4 py-3 first:border-t-0">
342 <div className="min-w-0">
343 <p className="text-sm font-medium">{title}</p>
344 <p className="mt-1 text-xs text-muted-foreground">{description}</p>
345 </div>
346 <Switch
347 aria-label={title}
348 checked={checked}
349 disabled={disabled}
350 onCheckedChange={onCheckedChange}
351 />
352 </div>
353 );
354}
355
356function DevicesStep() {
357 const { environments } = useEnvironments();
358 const primaryEnvironment = usePrimaryEnvironment();
359 const savedEnvironments = environments.filter(
360 (environment) => environment.entry.target._tag !== "PrimaryConnectionTarget",
361 );
362
363 return (
364 <div className="overflow-hidden rounded-lg border">
365 <CloudEnvironmentConnectRows
366 primaryEnvironmentId={primaryEnvironment?.environmentId ?? null}
367 savedEnvironments={savedEnvironments}
368 showSavedEnvironments
369 empty={
370 <p className="px-4 py-6 text-center text-sm text-muted-foreground">
371 No other environments are published to your account yet. Publish one from another device
372 and it will show up here.
373 </p>
374 }
375 />
376 </div>
377 );
378}