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