Open History to see the last commit
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 { useCompleteOnboarding } 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 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 threadCount = useAtomValue(threadCountAtom);
91 const soleThread = useAtomValue(soleThreadAtom);
92 const serverConfig = useAtomValue(primaryServerConfigAtom);
93 const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
94 const primaryShellLive = useAtomValue(primaryShellLiveAtom);
95 const workspaceEvidenceLive = useAtomValue(workspaceEvidenceLiveAtom);
96 const [gateState, setGateState] = useState<FirstRunGateState>(() => ({
97 decision:
98 (!enabled && !hostedStatic) || (hydrated && onboardingCompletedAt !== null)
99 ? "app"
100 : "pending",
101 stalled: false,
102 }));
103 const { decision, stalled } = gateState;
104 const settingsReadFailed = hydrationStatus === "failed" || hydrationStatus === "retrying";
105 // A workspace still counts as fresh when its only content is the server's own
106 // cwd auto-bootstrap: web mode creates a project + thread from cwd at startup
107 // (`autoBootstrapProjectFromCwd` defaults on there), so "no projects at all"
108 // would mean `npx t3` users never see the wizard.
109 const serverCwd = serverConfig?.cwd ?? null;
110 const primaryEnvironmentId = serverConfig?.environment.environmentId ?? null;
111 const workspaceFresh =
112 threadCount <= 1 &&
113 isFreshFirstRunWorkspace({
114 primaryEnvironmentId,
115 serverCwd,
116 bootstrapProjectId: serverWelcome?.bootstrapProjectId,
117 bootstrapThreadId: serverWelcome?.bootstrapThreadId,
118 bootstrapProjectCreated: serverWelcome?.bootstrapProjectCreated,
119 bootstrapThreadCreated: serverWelcome?.bootstrapThreadCreated,
120 projects,
121 threads: soleThread === null ? [] : [soleThread],
122 });
123
124 const { decision: nextDecision, persistCompletion } = hostedStatic
125 ? resolveHostedFirstRunDecision({
126 localEnvironmentDisabled: isLocalEnvironmentDisabled(),
127 hydrated,
128 completed: onboardingCompletedAt !== null,
129 catalogReady: environmentCatalogReady,
130 environmentCount: environments.length,
131 })
132 : resolveFirstRunDecision({
133 enabled,
134 hydrated,
135 completed: onboardingCompletedAt !== null,
136 bootstrapped,
137 authoritative: primaryShellLive,
138 workspaceAuthoritative: workspaceEvidenceLive,
139 workspaceProvenanceAuthoritative: isFirstRunWorkspaceProvenanceAuthoritative({
140 welcomeReceived: serverWelcome !== null,
141 bootstrapStatus: serverWelcome?.bootstrapStatus ?? null,
142 }),
143 catalogReady: environmentCatalogReady,
144 serverConfigAvailable: serverConfig !== null,
145 workspaceFresh,
146 projectCount: projects.length,
147 threadCount,
148 });
149
150 if (decision !== "wizard" && hydrated) {
151 const transitioned = transitionFirstRunGateState(gateState, {
152 type: "evidence",
153 decision: nextDecision,
154 });
155 if (transitioned !== gateState) setGateState(transitioned);
156 }
157
158 useEffect(() => {
159 if (decision === "wizard" || !hydrated) return;
160 if (persistCompletion && onboardingCompletedAt === null) {
161 void completeOnboarding().catch(() => undefined);
162 }
163 }, [completeOnboarding, decision, hydrated, onboardingCompletedAt, persistCompletion]);
164
165 useEffect(() => {
166 if (!enabled || decision !== "pending" || !hydrated) return;
167 const timer = window.setTimeout(
168 () => setGateState((state) => transitionFirstRunGateState(state, { type: "timeout" })),
169 FIRST_RUN_DECISION_TIMEOUT_MS,
170 );
171 return () => window.clearTimeout(timer);
172 }, [decision, enabled, hydrated]);
173
174 useEffect(() => {
175 if (decision === "wizard" && pathname !== "/welcome") {
176 void navigate({ to: "/welcome", replace: true });
177 }
178 }, [decision, navigate, pathname]);
179
180 if (settingsReadFailed) {
181 return <FirstRunRecovery reason="settings" retrying={hydrationStatus === "retrying"} />;
182 }
183 if (decision !== "app") {
184 return stalled ? <FirstRunRecovery reason="connection" /> : null;
185 }
186 return children;
187}
188
189function FirstRunRecovery({
190 reason,
191 retrying = false,
192}: {
193 readonly reason: "settings" | "connection";
194 readonly retrying?: boolean;
195}) {
196 const settingsReadFailed = reason === "settings";
197 return (
198 <main className="flex h-dvh min-h-0 items-center justify-center bg-background px-6 text-foreground">
199 <div className="flex max-w-sm flex-col items-center text-center">
200 <h1 className="text-lg font-semibold">
201 {settingsReadFailed ? "Could not read settings" : "Still connecting"}
202 </h1>
203 <p className="mt-2 text-sm text-muted-foreground">
204 {settingsReadFailed
205 ? "Your saved settings could not be loaded."
206 : "T3 Code could not confirm this workspace."}
207 </p>
208 <Button
209 className="mt-5"
210 size="sm"
211 variant="outline"
212 disabled={retrying}
213 onClick={() => {
214 if (settingsReadFailed) {
215 void ensureClientSettingsHydrated().catch(() => undefined);
216 } else {
217 window.location.reload();
218 }
219 }}
220 >
221 <RefreshIcon refreshing={retrying} />
222 {settingsReadFailed ? "Retry" : "Reload"}
223 </Button>
224 </div>
225 </main>
226 );
227}