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