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
34export function ConnectOnboardingDialog() {
35 if (!hasCloudPublicConfig()) return null;
36
37 return <ConfiguredConnectOnboardingDialog />;
38}
39
40type OnboardingStep = "publish" | "devices";
41
42const EMPTY_SESSION_STATE_ATOM = Atom.make(AsyncResult.initial<AuthSessionState>());
43
44function ConfiguredConnectOnboardingDialog() {
45 // Mirrors ManagedRelayAuthProvider: a pending Clerk session must not read as
46 // signed-out, or its later activation would look like a fresh sign-in.
47 const { isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
48 const [optOutState, setOptOutState] = useLocalStorage(
49 CONNECT_ONBOARDING_OPT_OUT_STORAGE_KEY,
50 EMPTY_CONNECT_ONBOARDING_OPT_OUT_STATE,
51 ConnectOnboardingOptOutSchema,
52 );
53
54 const { isReady: environmentsReady } = useEnvironments();
55 const primaryEnvironmentId = usePrimaryEnvironmentId();
56 const primarySessionState = useAtomValue(
57 primaryEnvironmentId === null
58 ? EMPTY_SESSION_STATE_ATOM
59 : environmentSession.sessionStateAtom(primaryEnvironmentId),
60 );
61 const canReadRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope);
62 const canWriteRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope);
63 const canManageRelay = canReadRelay && canWriteRelay;
64 const sessionScopesKnown =
65 primaryEnvironmentId === null ? environmentsReady : primarySessionState._tag !== "Initial";
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 useEffect(() => {
84 if (step === "publish" && sessionScopesKnown && !showPublishStep && !isApplying) {
85 setStep("devices");
86 }
87 }, [isApplying, sessionScopesKnown, showPublishStep, step]);
88
89 const optOutAccounts = optOutState.optOutAccounts;
90
91 useEffect(() => {
92 if (!isLoaded) return;
93 // A loaded-but-incomplete snapshot (signed in, user id not yet populated)
94 // must not be recorded as signed-out — the next render would then look
95 // like a fresh sign-in on a cold load.
96 if (isSignedIn && !userId) return;
97 const previousAccount = observedAccountRef.current;
98 const nextAccount = isSignedIn && userId ? userId : null;
99 observedAccountRef.current = nextAccount;
100 if (previousAccount !== undefined && previousAccount !== nextAccount && nextAccount !== null) {
101 setRequestedAccount(nextAccount);
102 }
103 }, [isLoaded, isSignedIn, userId]);
104
105 // A manageable session implies a primary environment, so when the scopes
106 // allow publishing, wait for the connection target too — otherwise the
107 // wizard could open on the devices step moments before the publish step
108 // becomes available and freeze there.
109 const publishStepDecided = !canManageRelay || controller.linkState.target !== null;
110
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 useEffect(() => {
136 if (openForAccount !== null && (!isSignedIn || userId !== openForAccount)) {
137 setOpenForAccount(null);
138 }
139 if (requestedAccount !== null && (!isSignedIn || userId !== requestedAccount)) {
140 setRequestedAccount(null);
141 }
142 }, [isSignedIn, openForAccount, requestedAccount, userId]);
143
144 const linkStateData = controller.linkState.data;
145 useEffect(() => {
146 if (openForAccount === null || prefilledFromLinkStateRef.current || linkStateData === null) {
147 return;
148 }
149 prefilledFromLinkStateRef.current = true;
150 if (
151 linkStateData.linked &&
152 linkStateData.linkRevoked !== true &&
153 linkStateData.cloudUserId === openForAccount
154 ) {
155 setExposeEnvironment(linkStateData.managedTunnelActive ?? linkStateData.linked);
156 setPublishAgentActivity(linkStateData.publishAgentActivity);
157 }
158 }, [linkStateData, openForAccount]);
159
160 const complete = () => {
161 if (isApplying) return;
162 const account = openForAccount;
163 setOpenForAccount(null);
164 if (account !== null && dontShowAgain) {
165 setOptOutState((state) =>
166 state.optOutAccounts.includes(account)
167 ? state
168 : { optOutAccounts: [...state.optOutAccounts, account] },
169 );
170 }
171 };
172
173 const applyPublishSelection = async () => {
174 if (isApplying) return;
175 if (
176 primaryEnvironmentId === null ||
177 !readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) ||
178 !readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope)
179 ) {
180 setStep("devices");
181 return;
182 }
183 if (linkStateData === null || controller.linkState.error !== null) return;
184 // The wizard only ever enables — with both toggles off there is nothing to
185 // apply, and an existing link must not be torn down from onboarding.
186 if (!exposeEnvironment && !publishAgentActivity) {
187 setStep("devices");
188 return;
189 }
190 setIsApplying(true);
191 const ok = await controller.reconcileCloudState({
192 managedTunnel: exposeEnvironment,
193 publish: publishAgentActivity,
194 });
195 setIsApplying(false);
196 if (!ok) return;
197 toastManager.add({
198 type: "success",
199 title: "T3 Connect enabled",
200 description: exposeEnvironment
201 ? "This environment is available to your other devices through T3 Connect."
202 : "This environment publishes agent activity to your mobile clients.",
203 });
204 setStep("devices");
205 };
206
207 return (
208 <Dialog
209 open={openForAccount !== null}
210 onOpenChange={(open) => {
211 if (!open && !isApplying) complete();
212 }}
213 >
214 <WizardPopup>
215 <WizardHeader
216 title="Set up T3 Connect"
217 description={
218 <>
219 Mesh your devices together — publish this environment and connect the rest, all in one
220 place.
221 </>
222 }
223 >
224 {steps.length > 1 ? (
225 <WizardSteps
226 steps={steps.map((id) => STEP_LABELS[id])}
227 currentStep={steps.indexOf(step)}
228 isStepDisabled={() => isApplying}
229 onStepChange={(index) => {
230 const next = steps[index];
231 if (
232 next === "publish" &&
233 (primaryEnvironmentId === null ||
234 !readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) ||
235 !readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope))
236 )
237 return;
238 if (next) setStep(next);
239 }}
240 />
241 ) : null}
242 </WizardHeader>
243 <WizardPanel>
244 {step === "publish" ? (
245 <PublishStep
246 exposeEnvironment={exposeEnvironment}
247 publishAgentActivity={publishAgentActivity}
248 disabled={isApplying || !canManageRelay || linkStateData === null}
249 operationError={controller.operationError ?? controller.linkState.error}
250 onExposeEnvironmentChange={(enabled) => {
251 if (
252 primaryEnvironmentId !== null &&
253 readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) &&
254 readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope)
255 )
256 setExposeEnvironment(enabled);
257 }}
258 onPublishAgentActivityChange={(enabled) => {
259 if (
260 primaryEnvironmentId !== null &&
261 readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) &&
262 readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope)
263 )
264 setPublishAgentActivity(enabled);
265 }}
266 />
267 ) : (
268 <DevicesStep />
269 )}
270 </WizardPanel>
271 <WizardFooter
272 leading={
273 <label className="flex cursor-pointer items-center gap-2 self-start text-xs text-muted-foreground sm:self-center">
274 <Checkbox
275 checked={dontShowAgain}
276 onCheckedChange={(checked) => setDontShowAgain(checked === true)}
277 />
278 Don't show this again
279 </label>
280 }
281 >
282 {step === "publish" ? (
283 <>
284 <Button variant="ghost" disabled={isApplying} onClick={() => setStep("devices")}>
285 Not now
286 </Button>
287 <Button
288 disabled={isApplying || !canManageRelay || linkStateData === null}
289 onClick={() => void applyPublishSelection()}
290 >
291 {isApplying ? "Enabling…" : "Continue"}
292 </Button>
293 </>
294 ) : (
295 <Button disabled={isApplying} onClick={complete}>
296 Done
297 </Button>
298 )}
299 </WizardFooter>
300 </WizardPopup>
301 </Dialog>
302 );
303}
304
305const STEP_LABELS: Record<OnboardingStep, string> = {
306 publish: "Publish",
307 devices: "Connect devices",
308};
309
310function PublishStep({
311 exposeEnvironment,
312 publishAgentActivity,
313 disabled,
314 operationError,
315 onExposeEnvironmentChange,
316 onPublishAgentActivityChange,
317}: {
318 readonly exposeEnvironment: boolean;
319 readonly publishAgentActivity: boolean;
320 readonly disabled: boolean;
321 readonly operationError: string | null;
322 readonly onExposeEnvironmentChange: (enabled: boolean) => void;
323 readonly onPublishAgentActivityChange: (enabled: boolean) => void;
324}) {
325 return (
326 <div className="space-y-3">
327 <div className="rounded-lg border">
328 <OnboardingToggleRow
329 title="Publish this environment"
330 description="Make this environment available to your other devices through T3 Connect."
331 checked={exposeEnvironment}
332 disabled={disabled}
333 onCheckedChange={onExposeEnvironmentChange}
334 />
335 <OnboardingToggleRow
336 title="Publish agent activity"
337 description="Send activity from this environment to your mobile clients for push notifications and Live Activities."
338 checked={publishAgentActivity}
339 disabled={disabled}
340 onCheckedChange={onPublishAgentActivityChange}
341 />
342 </div>
343 {operationError ? <p className="text-xs text-destructive">{operationError}</p> : null}
344 </div>
345 );
346}
347
348function OnboardingToggleRow({
349 title,
350 description,
351 checked,
352 disabled,
353 onCheckedChange,
354}: {
355 readonly title: string;
356 readonly description: string;
357 readonly checked: boolean;
358 readonly disabled: boolean;
359 readonly onCheckedChange: (enabled: boolean) => void;
360}) {
361 return (
362 <div className="flex items-start justify-between gap-4 border-t border-border/60 px-4 py-3 first:border-t-0">
363 <div className="min-w-0">
364 <p className="text-sm font-medium">{title}</p>
365 <p className="mt-1 text-xs text-muted-foreground">{description}</p>
366 </div>
367 <Switch
368 aria-label={title}
369 checked={checked}
370 disabled={disabled}
371 onCheckedChange={onCheckedChange}
372 />
373 </div>
374 );
375}
376
377function DevicesStep() {
378 const { environments } = useEnvironments();
379 const primaryEnvironment = usePrimaryEnvironment();
380 const savedEnvironments = environments.filter(
381 (environment) => environment.entry.target._tag !== "PrimaryConnectionTarget",
382 );
383
384 return (
385 <div className="overflow-hidden rounded-lg border">
386 <CloudEnvironmentConnectRows
387 primaryEnvironmentId={primaryEnvironment?.environmentId ?? null}
388 savedEnvironments={savedEnvironments}
389 showSavedEnvironments
390 empty={
391 <p className="px-4 py-6 text-center text-sm text-muted-foreground">
392 No other environments are published to your account yet. Publish one from another device
393 and it will show up here.
394 </p>
395 }
396 />
397 </div>
398 );
399}