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