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