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 { useManagedTunnelUsage } from "~/cloud/managedRelayState";
13import { hasCloudPublicConfig } from "~/cloud/publicConfig";
14import { useCloudLinkController } from "~/cloud/useCloudLinkController";
15import { useLocalStorage } from "~/hooks/useLocalStorage";
16import { isHostedStaticApp } from "~/hostedPairing";
17import {
18 useEnvironments,
19 usePrimaryEnvironment,
20 usePrimaryEnvironmentId,
21} from "~/state/environments";
22import { environmentSession, readEnvironmentScope, useEnvironmentScope } from "~/state/session";
23import {
24 type T3ConnectAccountPageUrl,
25 useT3ConnectAccountPage,
26} from "../clerk/T3ConnectAccountPages";
27import { CloudEnvironmentConnectRows } from "./CloudEnvironmentConnectList";
28import { TunnelLimitAlert } from "./TunnelUsage";
29import { Button } from "../ui/button";
30import { Checkbox } from "../ui/checkbox";
31import { Dialog } from "../ui/dialog";
32import { Switch } from "../ui/switch";
33import { toastManager } from "../ui/toast";
34import { WizardSteps, WizardPopup, WizardHeader, WizardPanel, WizardFooter } from "../ui/wizard";
35
36export function ConnectOnboardingDialog() {
37 if (!hasCloudPublicConfig()) return null;
38
39 return <ConfiguredConnectOnboardingDialog />;
40}
41
42type OnboardingStep = "publish" | "devices";
43
44const EMPTY_SESSION_STATE_ATOM = Atom.make(AsyncResult.initial<AuthSessionState>());
45
46function ConfiguredConnectOnboardingDialog() {
47 // Pending Clerk sessions must not look signed out or activation would look like a new sign-in.
48 const { isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
49 const [optOutState, setOptOutState] = useLocalStorage(
50 CONNECT_ONBOARDING_OPT_OUT_STORAGE_KEY,
51 EMPTY_CONNECT_ONBOARDING_OPT_OUT_STATE,
52 ConnectOnboardingOptOutSchema,
53 );
54
55 const { environments, isReady: environmentsReady } = useEnvironments();
56 // The empty hosted home already adds account computers after sign-in.
57 const homeScreenAddsComputers =
58 isHostedStaticApp() && environmentsReady && environments.length === 0;
59 const primaryEnvironmentId = usePrimaryEnvironmentId();
60 const primarySessionState = useAtomValue(
61 primaryEnvironmentId === null
62 ? EMPTY_SESSION_STATE_ATOM
63 : environmentSession.sessionStateAtom(primaryEnvironmentId),
64 );
65 const canReadRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope);
66 const canWriteRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope);
67 const canManageRelay = canReadRelay && canWriteRelay;
68 const sessionScopesKnown =
69 primaryEnvironmentId === null ? environmentsReady : primarySessionState._tag !== "Initial";
70
71 const controller = useCloudLinkController();
72 const accountPage = useT3ConnectAccountPage();
73 const showPublishStep = canManageRelay && controller.linkState.target !== null;
74 const steps: ReadonlyArray<OnboardingStep> = showPublishStep
75 ? ["publish", "devices"]
76 : ["devices"];
77
78 const [requestedAccount, setRequestedAccount] = useState<string | null>(null);
79 const [openForAccount, setOpenForAccount] = useState<string | null>(null);
80 const [step, setStep] = useState<OnboardingStep>("devices");
81 const [exposeEnvironment, setExposeEnvironment] = useState(true);
82 const [publishAgentActivity, setPublishAgentActivity] = useState(true);
83 const [dontShowAgain, setDontShowAgain] = useState(false);
84 const [isApplying, setIsApplying] = useState(false);
85 const [prefilledFromLinkState, setPrefilledFromLinkState] = useState(false);
86 // Start undefined so an existing account never looks like a fresh sign-in.
87 const [observedAccount, setObservedAccount] = useState<string | null | undefined>(undefined);
88
89 if (step === "publish" && sessionScopesKnown && !showPublishStep && !isApplying) {
90 setStep("devices");
91 }
92
93 const optOutAccounts = optOutState.optOutAccounts;
94
95 // A signed-in snapshot without userId is incomplete; recording signed-out would fake a fresh sign-in.
96 if (isLoaded && !(isSignedIn && !userId)) {
97 const nextAccount = isSignedIn && userId ? userId : null;
98 if (nextAccount !== observedAccount) {
99 setObservedAccount(nextAccount);
100 if (observedAccount !== undefined && nextAccount !== null) {
101 setRequestedAccount(nextAccount);
102 }
103 }
104 }
105
106 if (openForAccount !== null && (!isSignedIn || userId !== openForAccount)) {
107 setOpenForAccount(null);
108 }
109 if (requestedAccount !== null && (!isSignedIn || userId !== requestedAccount)) {
110 setRequestedAccount(null);
111 }
112
113 // Wait for the publish target before opening; otherwise the wizard can freeze on devices before publish
114 // becomes available.
115 const publishStepDecided = !canManageRelay || controller.linkState.target !== null;
116
117 if (requestedAccount !== null && openForAccount === null) {
118 if (homeScreenAddsComputers || optOutAccounts.includes(requestedAccount)) {
119 setRequestedAccount(null);
120 } else if (sessionScopesKnown && publishStepDecided) {
121 setRequestedAccount(null);
122 setPrefilledFromLinkState(false);
123 setExposeEnvironment(true);
124 setPublishAgentActivity(true);
125 setDontShowAgain(false);
126 setStep(canManageRelay && controller.linkState.target !== null ? "publish" : "devices");
127 setOpenForAccount(requestedAccount);
128 }
129 }
130
131 const linkStateData = controller.linkState.data;
132 if (openForAccount !== null && !prefilledFromLinkState && linkStateData !== null) {
133 setPrefilledFromLinkState(true);
134 if (
135 linkStateData.linked &&
136 linkStateData.linkRevoked !== true &&
137 linkStateData.cloudUserId === openForAccount
138 ) {
139 setExposeEnvironment(linkStateData.managedTunnelActive ?? linkStateData.linked);
140 setPublishAgentActivity(linkStateData.publishAgentActivity);
141 }
142 }
143
144 const complete = () => {
145 if (isApplying) return;
146 const account = openForAccount;
147 setOpenForAccount(null);
148 if (account !== null && dontShowAgain) {
149 setOptOutState((state) =>
150 state.optOutAccounts.includes(account)
151 ? state
152 : { optOutAccounts: [...state.optOutAccounts, account] },
153 );
154 }
155 };
156
157 const applyPublishSelection = async () => {
158 if (isApplying) return;
159 if (
160 primaryEnvironmentId === null ||
161 !readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) ||
162 !readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope)
163 ) {
164 setStep("devices");
165 return;
166 }
167 if (linkStateData === null || controller.linkState.error !== null) return;
168 // Onboarding only enables links; both toggles off must preserve existing links.
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 const openAccountPage = accountPage.open;
191 // The account page is a Clerk modal, so close this dialog before it opens.
192 const leaveForAccountPage = openAccountPage
193 ? (page: T3ConnectAccountPageUrl) => {
194 complete();
195 openAccountPage(page);
196 }
197 : null;
198
199 return (
200 <Dialog
201 open={openForAccount !== null}
202 onOpenChange={(open) => {
203 if (!open && !isApplying) complete();
204 }}
205 >
206 <WizardPopup>
207 <WizardHeader
208 title="Set up T3 Connect"
209 description={
210 <>
211 Mesh your devices together. Publish this environment and connect the rest, all in one
212 place.
213 </>
214 }
215 >
216 {steps.length > 1 ? (
217 <WizardSteps
218 steps={steps.map((id) => STEP_LABELS[id])}
219 currentStep={steps.indexOf(step)}
220 isStepDisabled={() => isApplying}
221 onStepChange={(index) => {
222 const next = steps[index];
223 if (
224 next === "publish" &&
225 (primaryEnvironmentId === null ||
226 !readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) ||
227 !readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope))
228 )
229 return;
230 if (next) setStep(next);
231 }}
232 />
233 ) : null}
234 </WizardHeader>
235 <WizardPanel>
236 {step === "publish" ? (
237 <PublishStep
238 exposeEnvironment={exposeEnvironment}
239 publishAgentActivity={publishAgentActivity}
240 disabled={isApplying || !canManageRelay || linkStateData === null}
241 operationError={controller.operationError ?? controller.linkState.error}
242 tunnelLimit={controller.tunnelLimit}
243 onOpenAccountPage={leaveForAccountPage}
244 onExposeEnvironmentChange={(enabled) => {
245 if (
246 primaryEnvironmentId !== null &&
247 readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) &&
248 readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope)
249 )
250 setExposeEnvironment(enabled);
251 }}
252 onPublishAgentActivityChange={(enabled) => {
253 if (
254 primaryEnvironmentId !== null &&
255 readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) &&
256 readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope)
257 )
258 setPublishAgentActivity(enabled);
259 }}
260 />
261 ) : (
262 <DevicesStep />
263 )}
264 </WizardPanel>
265 <WizardFooter
266 leading={
267 <label className="flex cursor-pointer items-center gap-2 self-start text-xs text-muted-foreground sm:self-center">
268 <Checkbox
269 checked={dontShowAgain}
270 onCheckedChange={(checked) => setDontShowAgain(checked === true)}
271 />
272 Don't show this again
273 </label>
274 }
275 >
276 {step === "publish" ? (
277 <>
278 <Button variant="ghost" disabled={isApplying} onClick={() => setStep("devices")}>
279 Not now
280 </Button>
281 <Button
282 disabled={isApplying || !canManageRelay || linkStateData === null}
283 onClick={() => void applyPublishSelection()}
284 >
285 {isApplying ? "Enabling…" : "Continue"}
286 </Button>
287 </>
288 ) : (
289 <Button disabled={isApplying} onClick={complete}>
290 Done
291 </Button>
292 )}
293 </WizardFooter>
294 </WizardPopup>
295 {/* Base UI renders Root children while closed, so this keeps the account page mounted. */}
296 {accountPage.portals}
297 </Dialog>
298 );
299}
300
301const STEP_LABELS: Record<OnboardingStep, string> = {
302 publish: "Publish",
303 devices: "Connect devices",
304};
305
306function PublishStep({
307 exposeEnvironment,
308 publishAgentActivity,
309 disabled,
310 operationError,
311 tunnelLimit,
312 onOpenAccountPage,
313 onExposeEnvironmentChange,
314 onPublishAgentActivityChange,
315}: {
316 readonly exposeEnvironment: boolean;
317 readonly publishAgentActivity: boolean;
318 readonly disabled: boolean;
319 readonly operationError: string | null;
320 readonly tunnelLimit: number | null;
321 readonly onOpenAccountPage: ((page: T3ConnectAccountPageUrl) => void) | 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 {tunnelLimit !== null ? (
345 <OnboardingTunnelLimitAlert onOpenAccountPage={onOpenAccountPage} />
346 ) : null}
347 </div>
348 );
349}
350
351function OnboardingTunnelLimitAlert({
352 onOpenAccountPage,
353}: {
354 readonly onOpenAccountPage: ((page: T3ConnectAccountPageUrl) => void) | null;
355}) {
356 const { upgrade } = useManagedTunnelUsage();
357 return (
358 <TunnelLimitAlert
359 upgrade={upgrade}
360 onLinkT3Chat={onOpenAccountPage ? () => onOpenAccountPage("t3-chat") : null}
361 onManageTunnels={onOpenAccountPage ? () => onOpenAccountPage("t3-connect") : null}
362 />
363 );
364}
365
366function OnboardingToggleRow({
367 title,
368 description,
369 checked,
370 disabled,
371 onCheckedChange,
372}: {
373 readonly title: string;
374 readonly description: string;
375 readonly checked: boolean;
376 readonly disabled: boolean;
377 readonly onCheckedChange: (enabled: boolean) => void;
378}) {
379 return (
380 <div className="flex items-start justify-between gap-4 border-t border-border/60 px-4 py-3 first:border-t-0">
381 <div className="min-w-0">
382 <p className="text-sm font-medium">{title}</p>
383 <p className="mt-1 text-xs text-muted-foreground">{description}</p>
384 </div>
385 <Switch
386 aria-label={title}
387 checked={checked}
388 disabled={disabled}
389 onCheckedChange={onCheckedChange}
390 />
391 </div>
392 );
393}
394
395function DevicesStep() {
396 const { environments } = useEnvironments();
397 const primaryEnvironment = usePrimaryEnvironment();
398 const savedEnvironments = environments.filter(
399 (environment) => environment.entry.target._tag !== "PrimaryConnectionTarget",
400 );
401
402 return (
403 <div className="overflow-hidden rounded-lg border">
404 <CloudEnvironmentConnectRows
405 primaryEnvironmentId={primaryEnvironment?.environmentId ?? null}
406 savedEnvironments={savedEnvironments}
407 showSavedEnvironments
408 empty={
409 <p className="px-4 py-6 text-center text-sm text-muted-foreground">
410 No other environments are published to your account yet. Publish one from another device
411 and it will show up here.
412 </p>
413 }
414 />
415 </div>
416 );
417}