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

FirstRunGate.tsx

226 lines8.4 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 { isLocalEnvironmentDisabled } from "../../localEnvironment";
13import { completeOnboarding } from "../../onboarding/firstRun";
14import {
15 isFirstRunWorkspaceProvenanceAuthoritative,
16 isFreshFirstRunWorkspace,
17 resolveFirstRunDecision,
18 resolveHostedFirstRunDecision,
19 transitionFirstRunGateState,
20 type FirstRunGateState,
21} from "../../onboarding/firstRun.logic";
22import { useAllEnvironmentShellsBootstrapped, useProjects } from "../../state/entities";
23import { useEnvironments } from "../../state/environments";
24import { environmentProjects } from "../../state/projects";
25import { primaryServerConfigAtom, primaryServerWelcomeAtom } from "../../state/server";
26import { environmentShell } from "../../state/shell";
27import { environmentThreadShells } from "../../state/threads";
28import { Button } from "../ui/button";
29​
30/**
31 * Nothing renders while pending — no shell, no EventRouter (whose welcome
32 * payload would otherwise navigate into a thread), no dialogs.
33 */
34​
35const FIRST_RUN_DECISION_TIMEOUT_MS = 4_000;
36​
37const primaryShellLiveAtom = Atom.make((get) => {
38 const serverConfig = get(primaryServerConfigAtom);
39 return (
40 serverConfig !== null &&
41 get(environmentShell.stateValueAtom(serverConfig.environment.environmentId)).status === "live"
42 );
43}).pipe(Atom.withLabel("web-onboarding-primary-shell-live"));
44​
45const workspaceEvidenceLiveAtom = Atom.make((get) => {
46 const environmentIds = new Set([
47 ...get(environmentProjects.projectsAtom).map((project) => project.environmentId),
48 ...get(environmentThreadShells.threadShellsAtom).map((thread) => thread.environmentId),
49 ]);
50​
51 for (const environmentId of environmentIds) {
52 if (get(environmentShell.stateValueAtom(environmentId)).status !== "live") {
53 return false;
54 }
55 }
56​
57 return true;
58}).pipe(Atom.withLabel("web-onboarding-workspace-evidence-live"));
59​
60// The gate only needs how many threads exist and, while there is at most one,
61// that thread; a shell update of any thread in a populated workspace must not
62// re-render the app root.
63const threadCountAtom = Atom.make(
64 (get) => get(environmentThreadShells.threadShellsAtom).length,
65).pipe(Atom.withLabel("web-onboarding-thread-count"));
66​
67const soleThreadAtom = Atom.make((get) => {
68 const threads = get(environmentThreadShells.threadShellsAtom);
69 return threads.length === 1 ? threads[0]! : null;
70}).pipe(Atom.withLabel("web-onboarding-sole-thread"));
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 onboardingCompletedAt = useClientSettings((settings) => settings.onboardingCompletedAt);
86 const bootstrapped = useAllEnvironmentShellsBootstrapped();
87 const { environments, isReady: environmentCatalogReady } = useEnvironments();
88 const projects = useProjects();
89 const threadCount = useAtomValue(threadCountAtom);
90 const soleThread = useAtomValue(soleThreadAtom);
91 const serverConfig = useAtomValue(primaryServerConfigAtom);
92 const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
93 const primaryShellLive = useAtomValue(primaryShellLiveAtom);
94 const workspaceEvidenceLive = useAtomValue(workspaceEvidenceLiveAtom);
95 const [gateState, setGateState] = useState<FirstRunGateState>(() => ({
96 decision:
97 (!enabled && !hostedStatic) || (hydrated && onboardingCompletedAt !== null)
98 ? "app"
99 : "pending",
100 stalled: false,
101 }));
102 const { decision, stalled } = gateState;
103 const settingsReadFailed = hydrationStatus === "failed" || hydrationStatus === "retrying";
104 // A workspace still counts as fresh when its only content is the server's own
105 // cwd auto-bootstrap: web mode creates a project + thread from cwd at startup
106 // (`autoBootstrapProjectFromCwd` defaults on there), so "no projects at all"
107 // would mean `npx t3` users never see the wizard.
108 const serverCwd = serverConfig?.cwd ?? null;
109 const primaryEnvironmentId = serverConfig?.environment.environmentId ?? null;
110 const workspaceFresh =
111 threadCount <= 1 &&
112 isFreshFirstRunWorkspace({
113 primaryEnvironmentId,
114 serverCwd,
115 bootstrapProjectId: serverWelcome?.bootstrapProjectId,
116 bootstrapThreadId: serverWelcome?.bootstrapThreadId,
117 bootstrapProjectCreated: serverWelcome?.bootstrapProjectCreated,
118 bootstrapThreadCreated: serverWelcome?.bootstrapThreadCreated,
119 projects,
120 threads: soleThread === null ? [] : [soleThread],
121 });
122​
123 const { decision: nextDecision, persistCompletion } = hostedStatic
124 ? resolveHostedFirstRunDecision({
125 localEnvironmentDisabled: isLocalEnvironmentDisabled(),
126 hydrated,
127 completed: onboardingCompletedAt !== null,
128 catalogReady: environmentCatalogReady,
129 environmentCount: environments.length,
130 })
131 : resolveFirstRunDecision({
132 enabled,
133 hydrated,
134 completed: onboardingCompletedAt !== null,
135 bootstrapped,
136 authoritative: primaryShellLive,
137 workspaceAuthoritative: workspaceEvidenceLive,
138 workspaceProvenanceAuthoritative: isFirstRunWorkspaceProvenanceAuthoritative({
139 welcomeReceived: serverWelcome !== null,
140 bootstrapStatus: serverWelcome?.bootstrapStatus ?? null,
141 }),
142 catalogReady: environmentCatalogReady,
143 serverConfigAvailable: serverConfig !== null,
144 workspaceFresh,
145 projectCount: projects.length,
146 threadCount,
147 });
148​
149 if (decision !== "wizard" && hydrated) {
150 const transitioned = transitionFirstRunGateState(gateState, {
151 type: "evidence",
152 decision: nextDecision,
153 });
154 if (transitioned !== gateState) setGateState(transitioned);
155 }
156​
157 useEffect(() => {
158 if (decision === "wizard" || !hydrated) return;
159 if (persistCompletion && onboardingCompletedAt === null) {
160 void completeOnboarding().catch(() => undefined);
161 }
162 }, [decision, hydrated, onboardingCompletedAt, persistCompletion]);
163​
164 useEffect(() => {
165 if (!enabled || decision !== "pending" || !hydrated) return;
166 const timer = window.setTimeout(
167 () => setGateState((state) => transitionFirstRunGateState(state, { type: "timeout" })),
168 FIRST_RUN_DECISION_TIMEOUT_MS,
169 );
170 return () => window.clearTimeout(timer);
171 }, [decision, enabled, hydrated]);
172​
173 useEffect(() => {
174 if (decision === "wizard" && pathname !== "/welcome") {
175 void navigate({ to: "/welcome", replace: true });
176 }
177 }, [decision, navigate, pathname]);
178​
179 if (settingsReadFailed) {
180 return <FirstRunRecovery reason="settings" retrying={hydrationStatus === "retrying"} />;
181 }
182 if (decision !== "app") {
183 return stalled ? <FirstRunRecovery reason="connection" /> : null;
184 }
185 return children;
187​
188function FirstRunRecovery({
189 reason,
190 retrying = false,
191}: {
192 readonly reason: "settings" | "connection";
193 readonly retrying?: boolean;
194}) {
195 const settingsReadFailed = reason === "settings";
196 return (
197 <main className="flex h-dvh min-h-0 items-center justify-center bg-background px-6 text-foreground">
198 <div className="flex max-w-sm flex-col items-center text-center">
199 <h1 className="text-lg font-semibold">
200 {settingsReadFailed ? "Could not read settings" : "Still connecting"}
201 </h1>
202 <p className="mt-2 text-sm text-muted-foreground">
203 {settingsReadFailed
204 ? "Your saved settings could not be loaded."
205 : "T3 Code could not confirm this workspace."}
206 </p>
207 <Button
208 className="mt-5"
209 size="sm"
210 variant="outline"
211 disabled={retrying}
212 onClick={() => {
213 if (settingsReadFailed) {
214 void ensureClientSettingsHydrated().catch(() => undefined);
215 } else {
216 window.location.reload();
217 }
218 }}
219 >
220 <RefreshIcon refreshing={retrying} />
221 {settingsReadFailed ? "Retry" : "Reload"}
222 </Button>
223 </div>
224 </main>
225 );