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