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

FirstRunGate.tsx

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