Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ConnectOnboardingDialog.tsx

468 lines17.3 KB

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