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