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

FirstRunGate.tsx

244 lines9.2 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/unstable/reactivity";
5import { useEffect, useLayoutEffect, useState } from "react";
6​
7import {
8 ensureClientSettingsHydrated,
9 useClientSettings,
10 useClientSettingsHydrationStatus,
11} from "../../hooks/useSettings";
12import { mountOnboardingTheme } from "../../hooks/useTheme";
13import { useCompleteOnboarding } from "../../onboarding/firstRun";
14import {
15 isFirstRunWorkspaceProvenanceAuthoritative,
16 isFreshFirstRunWorkspace,
17 resolveFirstRunDecision,
18 resolveHostedFirstRunDecision,
19 transitionFirstRunGateState,
20 type FirstRunGateState,
21} from "../../onboarding/firstRun.logic";
22import {
23 useAllEnvironmentShellsBootstrapped,
24 useProjects,
25 useThreadShells,
26} from "../../state/entities";
27import { useEnvironments } from "../../state/environments";
28import { environmentProjects } from "../../state/projects";
29import { primaryServerConfigAtom, primaryServerWelcomeAtom } from "../../state/server";
30import { environmentShell } from "../../state/shell";
31import { environmentThreadShells } from "../../state/threads";
32import { Button } from "../ui/button";
33​
34/**
35 * Holds back authenticated and hosted app trees until the first-run decision
36 * is known, so a fresh install never flashes the main screen before the wizard.
37 * Nothing renders while pending — no shell, no EventRouter (whose welcome
38 * payload would otherwise navigate into a thread), no dialogs.
39 *
40 * Decision order: a set `onboardingCompletedAt` resolves to the app as soon as
41 * settings hydrate (the common case, no server round-trip). A `null` flag also
42 * covers installs that predate the field, so it alone is not enough — the gate
43 * waits for environment shells to bootstrap and inspects the workspace.
44 * Hosted mode instead checks its saved environment catalog. A timeout shows
45 * recovery for an unreachable primary server without mounting the app tree.
46 */
47​
48const FIRST_RUN_DECISION_TIMEOUT_MS = 4_000;
49​
50const primaryShellLiveAtom = Atom.make((get) => {
51 const serverConfig = get(primaryServerConfigAtom);
52 return (
53 serverConfig !== null &&
54 get(environmentShell.stateValueAtom(serverConfig.environment.environmentId)).status === "live"
55 );
56}).pipe(Atom.withLabel("web-onboarding-primary-shell-live"));
57​
58const workspaceEvidenceLiveAtom = Atom.make((get) => {
59 const environmentIds = new Set([
60 ...get(environmentProjects.projectsAtom).map((project) => project.environmentId),
61 ...get(environmentThreadShells.threadShellsAtom).map((thread) => thread.environmentId),
62 ]);
63​
64 for (const environmentId of environmentIds) {
65 if (get(environmentShell.stateValueAtom(environmentId)).status !== "live") {
66 return false;
67 }
68 }
69​
70 return true;
71}).pipe(Atom.withLabel("web-onboarding-workspace-evidence-live"));
72​
73export function FirstRunGate({
74 enabled,
75 hostedStatic,
76 children,
77}: {
78 readonly enabled: boolean;
79 readonly hostedStatic: boolean;
80 readonly children: React.ReactNode;
81}) {
82 const navigate = useNavigate();
83 const pathname = useLocation({ select: (location) => location.pathname });
84 const hydrationStatus = useClientSettingsHydrationStatus();
85 const hydrated = hydrationStatus === "ready";
86 const completeOnboarding = useCompleteOnboarding();
87 const onboardingCompletedAt = useClientSettings((settings) => settings.onboardingCompletedAt);
88 const bootstrapped = useAllEnvironmentShellsBootstrapped();
89 const { environments, isReady: environmentCatalogReady } = useEnvironments();
90 const projects = useProjects();
91 const threads = useThreadShells();
92 const serverConfig = useAtomValue(primaryServerConfigAtom);
93 const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
94 const primaryShellLive = useAtomValue(primaryShellLiveAtom);
95 const workspaceEvidenceLive = useAtomValue(workspaceEvidenceLiveAtom);
96 // Within a session settings stay hydrated, so remounts (e.g. returning from
97 // the wizard) resolve synchronously instead of blanking a frame.
98 const [gateState, setGateState] = useState<FirstRunGateState>(() => ({
99 decision:
100 (!enabled && !hostedStatic) || (hydrated && onboardingCompletedAt !== null)
101 ? "app"
102 : "pending",
103 stalled: false,
104 }));
105 const { decision, stalled } = gateState;
106 const settingsReadFailed = hydrationStatus === "failed" || hydrationStatus === "retrying";
107 const ownsOnboardingTheme = settingsReadFailed || stalled || decision === "wizard";
108​
109 useLayoutEffect(() => {
110 if (!ownsOnboardingTheme) return;
111 return mountOnboardingTheme();
112 }, [ownsOnboardingTheme]);
113​
114 // A workspace still counts as fresh when its only content is the server's
115 // own cwd auto-bootstrap: web mode creates a project + thread from cwd at
116 // startup (`autoBootstrapProjectFromCwd` defaults on there), so "no
117 // projects at all" would mean `npx t3` users never see the wizard. Any
118 // other project, more than one thread, or state in a non-primary
119 // environment is real user state — the aggregate hooks span every
120 // environment, and a saved remote's project must never read as "the
121 // bootstrap project" just because its root string matches the primary cwd.
122 const serverCwd = serverConfig?.cwd ?? null;
123 const primaryEnvironmentId = serverConfig?.environment.environmentId ?? null;
124 const workspaceFresh = isFreshFirstRunWorkspace({
125 primaryEnvironmentId,
126 serverCwd,
127 bootstrapProjectId: serverWelcome?.bootstrapProjectId,
128 bootstrapThreadId: serverWelcome?.bootstrapThreadId,
129 bootstrapProjectCreated: serverWelcome?.bootstrapProjectCreated,
130 bootstrapThreadCreated: serverWelcome?.bootstrapThreadCreated,
131 projects,
132 threads,
133 });
134​
135 const { decision: nextDecision, persistCompletion } = hostedStatic
136 ? resolveHostedFirstRunDecision({
137 hydrated,
138 completed: onboardingCompletedAt !== null,
139 catalogReady: environmentCatalogReady,
140 environmentCount: environments.length,
141 })
142 : resolveFirstRunDecision({
143 enabled,
144 hydrated,
145 completed: onboardingCompletedAt !== null,
146 bootstrapped,
147 authoritative: primaryShellLive,
148 workspaceAuthoritative: workspaceEvidenceLive,
149 workspaceProvenanceAuthoritative: isFirstRunWorkspaceProvenanceAuthoritative({
150 welcomeReceived: serverWelcome !== null,
151 bootstrapStatus: serverWelcome?.bootstrapStatus ?? null,
152 }),
153 catalogReady: environmentCatalogReady,
154 serverConfigAvailable: serverConfig !== null,
155 workspaceFresh,
156 projectCount: projects.length,
157 threadCount: threads.length,
158 });
159​
160 useEffect(() => {
161 if (decision === "wizard" || !hydrated) return;
162​
163 if (persistCompletion && onboardingCompletedAt === null) {
164 void completeOnboarding().catch(() => undefined);
165 }
166​
167 setGateState((state) =>
168 transitionFirstRunGateState(state, { type: "evidence", decision: nextDecision }),
169 );
170 }, [
171 completeOnboarding,
172 decision,
173 hydrated,
174 nextDecision,
175 onboardingCompletedAt,
176 persistCompletion,
177 ]);
178​
179 // A stalled server read gets a recovery screen, but never mounts the app.
180 // The timer starts after settings hydrate so slow local hydration does not
181 // show a false connection failure.
182 useEffect(() => {
183 if (!enabled || decision !== "pending" || !hydrated) return;
184 const timer = window.setTimeout(
185 () => setGateState((state) => transitionFirstRunGateState(state, { type: "timeout" })),
186 FIRST_RUN_DECISION_TIMEOUT_MS,
187 );
188 return () => window.clearTimeout(timer);
189 }, [decision, enabled, hydrated]);
190​
191 useEffect(() => {
192 if (decision === "wizard" && pathname !== "/welcome") {
193 void navigate({ to: "/welcome", replace: true });
194 }
195 }, [decision, navigate, pathname]);
196​
197 if (settingsReadFailed) {
198 return <FirstRunRecovery reason="settings" retrying={hydrationStatus === "retrying"} />;
199 }
200 if (decision !== "app") {
201 return stalled ? <FirstRunRecovery reason="connection" /> : null;
202 }
203 return children;
205​
206function FirstRunRecovery({
207 reason,
208 retrying = false,
209}: {
210 readonly reason: "settings" | "connection";
211 readonly retrying?: boolean;
212}) {
213 const settingsReadFailed = reason === "settings";
214 return (
215 <main className="flex h-dvh min-h-0 items-center justify-center bg-background px-6 text-foreground">
216 <div className="flex max-w-sm flex-col items-center text-center">
217 <h1 className="text-lg font-semibold">
218 {settingsReadFailed ? "Could not read settings" : "Still connecting"}
219 </h1>
220 <p className="mt-2 text-sm text-muted-foreground">
221 {settingsReadFailed
222 ? "Your saved settings could not be loaded."
223 : "T3 Code could not confirm this workspace."}
224 </p>
225 <Button
226 className="mt-5"
227 size="sm"
228 variant="outline"
229 disabled={retrying}
230 onClick={() => {
231 if (settingsReadFailed) {
232 void ensureClientSettingsHydrated().catch(() => undefined);
233 } else {
234 window.location.reload();
235 }
236 }}
237 >
238 <RefreshIcon refreshing={retrying} />
239 {settingsReadFailed ? "Retry" : "Reload"}
240 </Button>
241 </div>
242 </main>
243 );