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