Open History to see the last commit
1import { useAuth } from "@clerk/react";
2import { useAtomValue } from "@effect/atom-react";
3import { AuthRelayReadScope, AuthRelayWriteScope, type AuthSessionState } from "@t3tools/contracts";
4import { AsyncResult, Atom } from "effect/reactivity";
5import { useState } from "react";
6
7import {
8 CONNECT_ONBOARDING_OPT_OUT_STORAGE_KEY,
9 ConnectOnboardingOptOutSchema,
10 EMPTY_CONNECT_ONBOARDING_OPT_OUT_STATE,
11} from "~/cloud/connectOnboarding";
12import { hasCloudPublicConfig } from "~/cloud/publicConfig";
13import { useCloudLinkController } from "~/cloud/useCloudLinkController";
14import { useLocalStorage } from "~/hooks/useLocalStorage";
15import {
16 useEnvironments,
17 usePrimaryEnvironment,
18 usePrimaryEnvironmentId,
19} from "~/state/environments";
20import { environmentSession, readEnvironmentScope, useEnvironmentScope } from "~/state/session";
21import { CloudEnvironmentConnectRows } from "./CloudEnvironmentConnectList";
22import { Button } from "../ui/button";
23import { Checkbox } from "../ui/checkbox";
24import { Dialog } from "../ui/dialog";
25import { Switch } from "../ui/switch";
26import { toastManager } from "../ui/toast";
27import { WizardSteps, WizardPopup, WizardHeader, WizardPanel, WizardFooter } from "../ui/wizard";
28
29export function ConnectOnboardingDialog() {
30 if (!hasCloudPublicConfig()) return null;
31
32 return <ConfiguredConnectOnboardingDialog />;
33}
34
35type OnboardingStep = "publish" | "devices";
36
37const EMPTY_SESSION_STATE_ATOM = Atom.make(AsyncResult.initial<AuthSessionState>());
38
39function ConfiguredConnectOnboardingDialog() {
40 // Mirrors ManagedRelayAuthProvider: a pending Clerk session must not read as
41 // signed-out, or its later activation would look like a fresh sign-in.
42 const { isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
43 const [optOutState, setOptOutState] = useLocalStorage(
44 CONNECT_ONBOARDING_OPT_OUT_STORAGE_KEY,
45 EMPTY_CONNECT_ONBOARDING_OPT_OUT_STATE,
46 ConnectOnboardingOptOutSchema,
47 );
48
49 const { isReady: environmentsReady } = useEnvironments();
50 const primaryEnvironmentId = usePrimaryEnvironmentId();
51 const primarySessionState = useAtomValue(
52 primaryEnvironmentId === null
53 ? EMPTY_SESSION_STATE_ATOM
54 : environmentSession.sessionStateAtom(primaryEnvironmentId),
55 );
56 const canReadRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope);
57 const canWriteRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope);
58 const canManageRelay = canReadRelay && canWriteRelay;
59 const sessionScopesKnown =
60 primaryEnvironmentId === null ? environmentsReady : primarySessionState._tag !== "Initial";
61
62 const controller = useCloudLinkController();
63 const showPublishStep = canManageRelay && controller.linkState.target !== null;
64 const steps: ReadonlyArray<OnboardingStep> = showPublishStep
65 ? ["publish", "devices"]
66 : ["devices"];
67
68 const [requestedAccount, setRequestedAccount] = useState<string | null>(null);
69 const [openForAccount, setOpenForAccount] = useState<string | null>(null);
70 const [step, setStep] = useState<OnboardingStep>("devices");
71 const [exposeEnvironment, setExposeEnvironment] = useState(true);
72 const [publishAgentActivity, setPublishAgentActivity] = useState(true);
73 const [dontShowAgain, setDontShowAgain] = useState(false);
74 const [isApplying, setIsApplying] = useState(false);
75 const [prefilledFromLinkState, setPrefilledFromLinkState] = useState(false);
76 // undefined until auth first settles, so the account already signed in at load
77 // never reads as a fresh sign-in.
78 const [observedAccount, setObservedAccount] = useState<string | null | undefined>(undefined);
79
80 if (step === "publish" && sessionScopesKnown && !showPublishStep && !isApplying) {
81 setStep("devices");
82 }
83
84 const optOutAccounts = optOutState.optOutAccounts;
85
86 // A loaded-but-incomplete snapshot (signed in, user id not yet populated)
87 // must not be recorded as signed-out — the next render would then look
88 // like a fresh sign-in on a cold load.
89 if (isLoaded && !(isSignedIn && !userId)) {
90 const nextAccount = isSignedIn && userId ? userId : null;
91 if (nextAccount !== observedAccount) {
92 setObservedAccount(nextAccount);
93 if (observedAccount !== undefined && nextAccount !== null) {
94 setRequestedAccount(nextAccount);
95 }
96 }
97 }
98
99 if (openForAccount !== null && (!isSignedIn || userId !== openForAccount)) {
100 setOpenForAccount(null);
101 }
102 if (requestedAccount !== null && (!isSignedIn || userId !== requestedAccount)) {
103 setRequestedAccount(null);
104 }
105
106 // A manageable session implies a primary environment, so when the scopes
107 // allow publishing, wait for the connection target too — otherwise the
108 // wizard could open on the devices step moments before the publish step
109 // becomes available and freeze there.
110 const publishStepDecided = !canManageRelay || controller.linkState.target !== null;
111
112 if (requestedAccount !== null && openForAccount === null) {
113 if (optOutAccounts.includes(requestedAccount)) {
114 setRequestedAccount(null);
115 } else if (sessionScopesKnown && publishStepDecided) {
116 setRequestedAccount(null);
117 setPrefilledFromLinkState(false);
118 setExposeEnvironment(true);
119 setPublishAgentActivity(true);
120 setDontShowAgain(false);
121 setStep(canManageRelay && controller.linkState.target !== null ? "publish" : "devices");
122 setOpenForAccount(requestedAccount);
123 }
124 }
125
126 const linkStateData = controller.linkState.data;
127 if (openForAccount !== null && !prefilledFromLinkState && linkStateData !== null) {
128 setPrefilledFromLinkState(true);
129 if (
130 linkStateData.linked &&
131 linkStateData.linkRevoked !== true &&
132 linkStateData.cloudUserId === openForAccount
133 ) {
134 setExposeEnvironment(linkStateData.managedTunnelActive ?? linkStateData.linked);
135 setPublishAgentActivity(linkStateData.publishAgentActivity);
136 }
137 }
138
139 const complete = () => {
140 if (isApplying) return;
141 const account = openForAccount;
142 setOpenForAccount(null);
143 if (account !== null && dontShowAgain) {
144 setOptOutState((state) =>
145 state.optOutAccounts.includes(account)
146 ? state
147 : { optOutAccounts: [...state.optOutAccounts, account] },
148 );
149 }
150 };
151
152 const applyPublishSelection = async () => {
153 if (isApplying) return;
154 if (
155 primaryEnvironmentId === null ||
156 !readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) ||
157 !readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope)
158 ) {
159 setStep("devices");
160 return;
161 }
162 if (linkStateData === null || controller.linkState.error !== null) return;
163 // The wizard only ever enables — with both toggles off there is nothing to
164 // apply, and an existing link must not be torn down from onboarding.
165 if (!exposeEnvironment && !publishAgentActivity) {
166 setStep("devices");
167 return;
168 }
169 setIsApplying(true);
170 const ok = await controller.reconcileCloudState({
171 managedTunnel: exposeEnvironment,
172 publish: publishAgentActivity,
173 });
174 setIsApplying(false);
175 if (!ok) return;
176 toastManager.add({
177 type: "success",
178 title: "T3 Connect enabled",
179 description: exposeEnvironment
180 ? "This environment is available to your other devices through T3 Connect."
181 : "This environment publishes agent activity to your mobile clients.",
182 });
183 setStep("devices");
184 };
185
186 return (
187 <Dialog
188 open={openForAccount !== null}
189 onOpenChange={(open) => {
190 if (!open && !isApplying) complete();
191 }}
192 >
193 <WizardPopup>
194 <WizardHeader
195 title="Set up T3 Connect"
196 description={
197 <>
198 Mesh your devices together — publish this environment and connect the rest, all in one
199 place.
200 </>
201 }
202 >
203 {steps.length > 1 ? (
204 <WizardSteps
205 steps={steps.map((id) => STEP_LABELS[id])}
206 currentStep={steps.indexOf(step)}
207 isStepDisabled={() => isApplying}
208 onStepChange={(index) => {
209 const next = steps[index];
210 if (
211 next === "publish" &&
212 (primaryEnvironmentId === null ||
213 !readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) ||
214 !readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope))
215 )
216 return;
217 if (next) setStep(next);
218 }}
219 />
220 ) : null}
221 </WizardHeader>
222 <WizardPanel>
223 {step === "publish" ? (
224 <PublishStep
225 exposeEnvironment={exposeEnvironment}
226 publishAgentActivity={publishAgentActivity}
227 disabled={isApplying || !canManageRelay || linkStateData === null}
228 operationError={controller.operationError ?? controller.linkState.error}
229 onExposeEnvironmentChange={(enabled) => {
230 if (
231 primaryEnvironmentId !== null &&
232 readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) &&
233 readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope)
234 )
235 setExposeEnvironment(enabled);
236 }}
237 onPublishAgentActivityChange={(enabled) => {
238 if (
239 primaryEnvironmentId !== null &&
240 readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) &&
241 readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope)
242 )
243 setPublishAgentActivity(enabled);
244 }}
245 />
246 ) : (
247 <DevicesStep />
248 )}
249 </WizardPanel>
250 <WizardFooter
251 leading={
252 <label className="flex cursor-pointer items-center gap-2 self-start text-xs text-muted-foreground sm:self-center">
253 <Checkbox
254 checked={dontShowAgain}
255 onCheckedChange={(checked) => setDontShowAgain(checked === true)}
256 />
257 Don't show this again
258 </label>
259 }
260 >
261 {step === "publish" ? (
262 <>
263 <Button variant="ghost" disabled={isApplying} onClick={() => setStep("devices")}>
264 Not now
265 </Button>
266 <Button
267 disabled={isApplying || !canManageRelay || linkStateData === null}
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 </WizardFooter>
279 </WizardPopup>
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}