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