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

FirstRunGate.tsx

221 lines8.5 KB

1import { RefreshIcon } from "~/components/ui/refresh-icon";
2import { useAtomValue } from "@effect/atom-react";
3import { useLocation, useNavigate } from "@tanstack/react-router";
4import { Atom } from "effect/reactivity";
5import { useEffect, useState } from "react";
6​
7import {
8 ensureClientSettingsHydrated,
9 useClientSettings,
10 useClientSettingsHydrationStatus,
11} from "../../hooks/useSettings";
12import { completeOnboarding } from "../../onboarding/firstRun";
13import {
14 isFirstRunWorkspaceProvenanceAuthoritative,
15 isFreshFirstRunWorkspace,
16 resolveFirstRunDecision,
17 resolveHostedFirstRunDecision,
18 transitionFirstRunGateState,
19 type FirstRunGateState,
20} from "../../onboarding/firstRun.logic";
21import { useAllEnvironmentShellsBootstrapped, useProjects } from "../../state/entities";
22import { useEnvironments } from "../../state/environments";
23import { environmentProjects } from "../../state/projects";
24import { primaryServerConfigAtom, primaryServerWelcomeAtom } from "../../state/server";
25import { environmentShell } from "../../state/shell";
26import { environmentThreadShells } from "../../state/threads";
27import { Button } from "../ui/button";
28​
29/** Pending blocks all rendering, including EventRouter welcome navigation. */
30​
31const FIRST_RUN_DECISION_TIMEOUT_MS = 4_000;
32​
33const primaryShellLiveAtom = Atom.make((get) => {
34 const serverConfig = get(primaryServerConfigAtom);
35 return (
36 serverConfig !== null &&
37 get(environmentShell.stateValueAtom(serverConfig.environment.environmentId)).status === "live"
38 );
39}).pipe(Atom.withLabel("web-onboarding-primary-shell-live"));
40​
41const workspaceEvidenceLiveAtom = Atom.make((get) => {
42 const environmentIds = new Set([
43 ...get(environmentProjects.projectsAtom).map((project) => project.environmentId),
44 ...get(environmentThreadShells.threadShellsAtom).map((thread) => thread.environmentId),
45 ]);
46​
47 for (const environmentId of environmentIds) {
48 if (get(environmentShell.stateValueAtom(environmentId)).status !== "live") {
49 return false;
50 }
51 }
52​
53 return true;
54}).pipe(Atom.withLabel("web-onboarding-workspace-evidence-live"));
55​
56// Subscribe only to thread count and the sole thread so populated-workspace shell updates cannot rerender the
57// app root.
58const threadCountAtom = Atom.make(
59 (get) => get(environmentThreadShells.threadShellsAtom).length,
60).pipe(Atom.withLabel("web-onboarding-thread-count"));
61​
62const soleThreadAtom = Atom.make((get) => {
63 const threads = get(environmentThreadShells.threadShellsAtom);
64 return threads.length === 1 ? threads[0]! : null;
65}).pipe(Atom.withLabel("web-onboarding-sole-thread"));
66​
67export function FirstRunGate({
68 enabled,
69 hostedStatic,
70 children,
71}: {
72 readonly enabled: boolean;
73 readonly hostedStatic: boolean;
74 readonly children: React.ReactNode;
75}) {
76 const navigate = useNavigate();
77 const pathname = useLocation({ select: (location) => location.pathname });
78 const hydrationStatus = useClientSettingsHydrationStatus();
79 const hydrated = hydrationStatus === "ready";
80 const onboardingCompletedAt = useClientSettings((settings) => settings.onboardingCompletedAt);
81 const bootstrapped = useAllEnvironmentShellsBootstrapped();
82 const { isReady: environmentCatalogReady } = useEnvironments();
83 const projects = useProjects();
84 const threadCount = useAtomValue(threadCountAtom);
85 const soleThread = useAtomValue(soleThreadAtom);
86 const serverConfig = useAtomValue(primaryServerConfigAtom);
87 const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
88 const primaryShellLive = useAtomValue(primaryShellLiveAtom);
89 const workspaceEvidenceLive = useAtomValue(workspaceEvidenceLiveAtom);
90 const [gateState, setGateState] = useState<FirstRunGateState>(() => ({
91 decision:
92 (!enabled && !hostedStatic) || (hydrated && onboardingCompletedAt !== null)
93 ? "app"
94 : "pending",
95 stalled: false,
96 }));
97 const { decision, stalled } = gateState;
98 const settingsReadFailed = hydrationStatus === "failed" || hydrationStatus === "retrying";
99 // The server's sole cwd-bootstrap project/thread still counts as fresh so npx t3 users see onboarding.
100 const serverCwd = serverConfig?.cwd ?? null;
101 const primaryEnvironmentId = serverConfig?.environment.environmentId ?? null;
102 const workspaceFresh =
103 threadCount <= 1 &&
104 isFreshFirstRunWorkspace({
105 primaryEnvironmentId,
106 serverCwd,
107 bootstrapProjectId: serverWelcome?.bootstrapProjectId,
108 bootstrapThreadId: serverWelcome?.bootstrapThreadId,
109 bootstrapProjectCreated: serverWelcome?.bootstrapProjectCreated,
110 bootstrapThreadCreated: serverWelcome?.bootstrapThreadCreated,
111 projects,
112 threads: soleThread === null ? [] : [soleThread],
113 });
114​
115 const { decision: nextDecision, persistCompletion } = hostedStatic
116 ? resolveHostedFirstRunDecision(hydrated)
117 : resolveFirstRunDecision({
118 enabled,
119 hydrated,
120 completed: onboardingCompletedAt !== null,
121 bootstrapped,
122 authoritative: primaryShellLive,
123 workspaceAuthoritative: workspaceEvidenceLive,
124 workspaceProvenanceAuthoritative: isFirstRunWorkspaceProvenanceAuthoritative({
125 welcomeReceived: serverWelcome !== null,
126 bootstrapStatus: serverWelcome?.bootstrapStatus ?? null,
127 }),
128 catalogReady: environmentCatalogReady,
129 serverConfigAvailable: serverConfig !== null,
130 workspaceFresh,
131 projectCount: projects.length,
132 threadCount,
133 });
134​
135 if (hydrated) {
136 const transitioned = transitionFirstRunGateState(gateState, {
137 type: "evidence",
138 decision: nextDecision,
139 });
140 if (transitioned !== gateState) setGateState(transitioned);
141 }
142​
143 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- persists onboarding completion to settings once the gate settles on skipping the wizard
144 useEffect(() => {
145 if (decision === "wizard" || !hydrated) return;
146 if (persistCompletion && onboardingCompletedAt === null) {
147 void completeOnboarding().catch(() => undefined);
148 }
149 }, [decision, hydrated, onboardingCompletedAt, persistCompletion]);
150​
151 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- timer gives up on a pending first-run decision after the timeout
152 useEffect(() => {
153 if (!enabled || decision !== "pending" || !hydrated) return;
154 const timer = window.setTimeout(
155 () => setGateState((state) => transitionFirstRunGateState(state, { type: "timeout" })),
156 FIRST_RUN_DECISION_TIMEOUT_MS,
157 );
158 return () => window.clearTimeout(timer);
159 }, [decision, enabled, hydrated]);
160​
161 // Setup opens by itself only from the home route. A direct link, such as
162 // Settings, opens as asked so setup can never lock a user out of the app.
163 const wizardOwnsRoute = pathname === "/";
164 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- navigates from the home route to /welcome when the gate decides on the wizard
165 useEffect(() => {
166 if (decision === "wizard" && wizardOwnsRoute) {
167 void navigate({ to: "/welcome", replace: true });
168 }
169 }, [decision, navigate, wizardOwnsRoute]);
170​
171 if (settingsReadFailed) {
172 return <FirstRunRecovery reason="settings" retrying={hydrationStatus === "retrying"} />;
173 }
174 if (decision === "wizard" && !wizardOwnsRoute) {
175 return children;
176 }
177 if (decision !== "app") {
178 return stalled ? <FirstRunRecovery reason="connection" /> : null;
179 }
180 return children;
182​
183function FirstRunRecovery({
184 reason,
185 retrying = false,
186}: {
187 readonly reason: "settings" | "connection";
188 readonly retrying?: boolean;
189}) {
190 const settingsReadFailed = reason === "settings";
191 return (
192 <main className="flex h-dvh min-h-0 items-center justify-center bg-background px-6 text-foreground">
193 <div className="flex max-w-sm flex-col items-center text-center">
194 <h1 className="text-lg font-semibold">
195 {settingsReadFailed ? "Could not read settings" : "Still connecting"}
196 </h1>
197 <p className="mt-2 text-sm text-muted-foreground">
198 {settingsReadFailed
199 ? "Your saved settings could not be loaded."
200 : "T3 Code could not confirm this workspace."}
201 </p>
202 <Button
203 className="mt-5"
204 size="sm"
205 variant="outline"
206 disabled={retrying}
207 onClick={() => {
208 if (settingsReadFailed) {
209 void ensureClientSettingsHydrated().catch(() => undefined);
210 } else {
211 window.location.reload();
212 }
213 }}
214 >
215 <RefreshIcon refreshing={retrying} />
216 {settingsReadFailed ? "Retry" : "Reload"}
217 </Button>
218 </div>
219 </main>
220 );