The best way to control Claude Code, Codex and more from any computer or phone

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