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

FirstRunGate.tsx

218 lines8.1 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 useEffect(() => {
144 if (decision === "wizard" || !hydrated) return;
145 if (persistCompletion && onboardingCompletedAt === null) {
146 void completeOnboarding().catch(() => undefined);
147 }
148 }, [decision, hydrated, onboardingCompletedAt, persistCompletion]);
149​
150 useEffect(() => {
151 if (!enabled || decision !== "pending" || !hydrated) return;
152 const timer = window.setTimeout(
153 () => setGateState((state) => transitionFirstRunGateState(state, { type: "timeout" })),
154 FIRST_RUN_DECISION_TIMEOUT_MS,
155 );
156 return () => window.clearTimeout(timer);
157 }, [decision, enabled, hydrated]);
158​
159 // Setup opens by itself only from the home route. A direct link, such as
160 // Settings, opens as asked so setup can never lock a user out of the app.
161 const wizardOwnsRoute = pathname === "/";
162 useEffect(() => {
163 if (decision === "wizard" && wizardOwnsRoute) {
164 void navigate({ to: "/welcome", replace: true });
165 }
166 }, [decision, navigate, wizardOwnsRoute]);
167​
168 if (settingsReadFailed) {
169 return <FirstRunRecovery reason="settings" retrying={hydrationStatus === "retrying"} />;
170 }
171 if (decision === "wizard" && !wizardOwnsRoute) {
172 return children;
173 }
174 if (decision !== "app") {
175 return stalled ? <FirstRunRecovery reason="connection" /> : null;
176 }
177 return children;
179​
180function FirstRunRecovery({
181 reason,
182 retrying = false,
183}: {
184 readonly reason: "settings" | "connection";
185 readonly retrying?: boolean;
186}) {
187 const settingsReadFailed = reason === "settings";
188 return (
189 <main className="flex h-dvh min-h-0 items-center justify-center bg-background px-6 text-foreground">
190 <div className="flex max-w-sm flex-col items-center text-center">
191 <h1 className="text-lg font-semibold">
192 {settingsReadFailed ? "Could not read settings" : "Still connecting"}
193 </h1>
194 <p className="mt-2 text-sm text-muted-foreground">
195 {settingsReadFailed
196 ? "Your saved settings could not be loaded."
197 : "T3 Code could not confirm this workspace."}
198 </p>
199 <Button
200 className="mt-5"
201 size="sm"
202 variant="outline"
203 disabled={retrying}
204 onClick={() => {
205 if (settingsReadFailed) {
206 void ensureClientSettingsHydrated().catch(() => undefined);
207 } else {
208 window.location.reload();
209 }
210 }}
211 >
212 <RefreshIcon refreshing={retrying} />
213 {settingsReadFailed ? "Retry" : "Reload"}
214 </Button>
215 </div>
216 </main>
217 );