From 35eff03509024b1d0a2281089b639ab300e7dc3d Mon Sep 17 00:00:00 2001 From: Christophe Vila Date: Sun, 26 Jul 2026 12:29:26 +0200 Subject: [PATCH] docs: add implementation plan for improved first-connection flow --- .../2026-07-26-improve-first-connection.md | 822 ++++++++++++++++++ 1 file changed, 822 insertions(+) create mode 100644 docs/superpowers/plans/2026-07-26-improve-first-connection.md diff --git a/docs/superpowers/plans/2026-07-26-improve-first-connection.md b/docs/superpowers/plans/2026-07-26-improve-first-connection.md new file mode 100644 index 0000000..97ad034 --- /dev/null +++ b/docs/superpowers/plans/2026-07-26-improve-first-connection.md @@ -0,0 +1,822 @@ +# Improve First Connection Page Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Make connecting a Garmin account a mandatory, persisted gate during onboarding (and on every subsequent login until it succeeds), instead of an optional step left to the Profile page. + +**Architecture:** Add a nullable `garmin_connected_at` timestamp to `profile`, set once on the first successful Garmin authentication (`handleAuthLogin`/`handleAuthMFA`). Expose it via `GET /api/session/me`. `LoginGate.tsx` becomes a three-way fork (`!has_profile` → `CreateProfile`, `has_profile && !garmin_connected` → new `ConnectGarmin`, else → `App`), so a user who abandons the connect step re-enters at `ConnectGarmin` on their next login rather than skipping straight into the app. + +**Tech Stack:** Go (`database/sql` via `modernc.org/sqlite`, chi router), React + TypeScript (Vite), no frontend test framework. + +## Global Constraints + +- `internal/store/schema.sql` is edited directly, never migrated (pre-production app, see `CLAUDE.md`). +- Every store/API method touching per-user data takes an explicit `userID` and filters by it. +- Cross-user isolation is tested adversarially (two real users, real IDs), not just checked for non-collision. +- After the `schema.sql` change, regenerate `docs/DATABASE.md` via `go run ./cmd/dumpschema` (from `backend/`). +- `gofmt -l .` must report nothing; `go vet ./...` and `go build ./...` must pass. +- No frontend test suite exists — frontend changes are verified via `npm run build`, `npm run lint`, and a manual browser check. +- This local dev DB predates schema changes made this session (`ON DELETE CASCADE`) but was already fixed up in place. A brand-new nullable column (`garmin_connected_at TEXT`) needs no such fix-up: SQLite's idempotent-skip `applySchema` never re-applies `schema.sql` to an existing DB file, but adding a nullable column to `profile`'s Go-side handling doesn't require the on-disk table to already have it selected correctly... **actually it does** — `GetProfile`'s `SELECT` will fail against the live dev DB once it lists `garmin_connected_at` in `profileColumns`, since that column doesn't exist there yet. Task 1 includes a real `ALTER TABLE` against the live dev DB (safe, additive, no rebuild needed this time) to keep manual testing working. + +--- + +### Task 1: Persist `garmin_connected_at` in the store layer + +**Files:** +- Modify: `backend/internal/store/schema.sql` (add column to the `profile` table) +- Modify: `backend/internal/store/profile.go` (`Profile` struct, `profileColumns`, `GetProfile`, new `MarkGarminConnected`) +- Modify: `backend/internal/store/profile_test.go` (new tests) +- Modify: `backend/internal/store/isolation_test.go` (new adversarial test) +- Modify: `docs/DATABASE.md` (regenerated) +- Modify (real DB, not version-controlled): `backend/geniusrun.db` — additive `ALTER TABLE` + +**Interfaces:** +- Produces: `Profile.GarminConnectedAt *string` (nil until first successful Garmin auth); `func (db *DB) MarkGarminConnected(ctx context.Context, userID int64) error`. + +- [ ] **Step 1: Write the failing tests** + +Add to `backend/internal/store/profile_test.go`: + +```go +func TestMarkGarminConnected_SetsTimestampOnceOnFirstCall(t *testing.T) { + db := openTestDB(t) + ctx := context.Background() + userID, err := db.ProvisionUser(ctx, "test-sub", "Test") + if err != nil { + t.Fatalf("ProvisionUser: %v", err) + } + + before, err := db.GetProfile(ctx, userID) + if err != nil { + t.Fatalf("GetProfile: %v", err) + } + if before.GarminConnectedAt != nil { + t.Fatalf("expected a fresh profile to have nil GarminConnectedAt, got %v", *before.GarminConnectedAt) + } + + if err := db.MarkGarminConnected(ctx, userID); err != nil { + t.Fatalf("MarkGarminConnected: %v", err) + } + afterFirst, err := db.GetProfile(ctx, userID) + if err != nil { + t.Fatalf("GetProfile after first mark: %v", err) + } + if afterFirst.GarminConnectedAt == nil { + t.Fatal("expected GarminConnectedAt to be set after MarkGarminConnected") + } + firstValue := *afterFirst.GarminConnectedAt + + // A second call must not change the recorded first-connection time. + if err := db.MarkGarminConnected(ctx, userID); err != nil { + t.Fatalf("MarkGarminConnected (second call): %v", err) + } + afterSecond, err := db.GetProfile(ctx, userID) + if err != nil { + t.Fatalf("GetProfile after second mark: %v", err) + } + if afterSecond.GarminConnectedAt == nil || *afterSecond.GarminConnectedAt != firstValue { + t.Fatalf("GarminConnectedAt changed on second call: first=%q second=%v", firstValue, afterSecond.GarminConnectedAt) + } +} +``` + +Add to `backend/internal/store/isolation_test.go`: + +```go +// TestIsolation_MarkGarminConnectedNeverLeaksAcrossUsers confirms marking +// one user's Garmin connection never sets another user's flag. +func TestIsolation_MarkGarminConnectedNeverLeaksAcrossUsers(t *testing.T) { + db := openTestDB(t) + ctx := context.Background() + + userA, err := db.ProvisionUser(ctx, "sub-a", "A") + if err != nil { + t.Fatalf("ProvisionUser(a): %v", err) + } + userB, err := db.ProvisionUser(ctx, "sub-b", "B") + if err != nil { + t.Fatalf("ProvisionUser(b): %v", err) + } + + if err := db.MarkGarminConnected(ctx, userA); err != nil { + t.Fatalf("MarkGarminConnected(a): %v", err) + } + + profileB, err := db.GetProfile(ctx, userB) + if err != nil { + t.Fatalf("GetProfile(b): %v", err) + } + if profileB.GarminConnectedAt != nil { + t.Fatal("userA's MarkGarminConnected call leaked into userB's profile") + } +} +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `cd backend && go test ./internal/store/... -run 'TestMarkGarminConnected|TestIsolation_MarkGarminConnected' -v` +Expected: FAIL — `db.MarkGarminConnected undefined` / `Profile has no field GarminConnectedAt`. + +- [ ] **Step 3: Add the column to `schema.sql`** + +In `backend/internal/store/schema.sql`, in the `profile` table (right after `garmin_password`), change: + +```sql + garmin_password TEXT NOT NULL DEFAULT '', + rolling_window_days INTEGER NOT NULL DEFAULT 90, +``` + +to: + +```sql + garmin_password TEXT NOT NULL DEFAULT '', + -- Set once, the first time this user successfully authenticates with + -- Garmin (handleAuthLogin/handleAuthMFA). Null means never connected -- + -- the login gate uses this (not the in-memory auth status, which + -- resets on restart) to decide whether a returning user must + -- reconnect before entering the app. + garmin_connected_at TEXT, + rolling_window_days INTEGER NOT NULL DEFAULT 90, +``` + +- [ ] **Step 4: Update `Profile`, `profileColumns`, and `GetProfile` in `profile.go`** + +Change the struct (add the field right after `GarminPassword`): + +```go + Name string + GarminEmail string + GarminPassword string + // GarminConnectedAt is nil until this user's first successful Garmin + // authentication (see store.MarkGarminConnected) -- the login gate uses + // it, not UpdateProfile, so it's deliberately excluded from + // UpdateProfile's SET clause below and can only ever move from nil to + // set, never reset by a normal profile save. + GarminConnectedAt *string + RollingWindowDays int +``` + +Change `profileColumns`: + +```go +const profileColumns = ` + name, garmin_email, garmin_password, garmin_connected_at, rolling_window_days, backfill_horizon_days, max_heart_rate, resting_heart_rate, + hr_zone1_min_pct, hr_zone1_max_pct, hr_zone2_min_pct, hr_zone2_max_pct, + hr_zone3_min_pct, hr_zone3_max_pct, hr_zone4_min_pct, hr_zone4_max_pct, + hr_zone5_min_pct, hr_zone5_max_pct, + warmup_minutes, cooldown_minutes, + min_representative_pace_sec_per_km, min_representative_time_seconds, + pace_color, heart_rate_color, warmup_color, effort_color, recovery_color, cooldown_color, + main_line_tint_pct, background_darken_pct, target_brighten_pct, + created_at, updated_at +` +``` + +Change `GetProfile`'s `Scan` call (add `&p.GarminConnectedAt` right after `&p.GarminPassword`): + +```go + err := db.QueryRowContext(ctx, `SELECT `+profileColumns+` FROM profile WHERE user_id = ?`, userID).Scan( + &p.Name, &p.GarminEmail, &p.GarminPassword, &p.GarminConnectedAt, &p.RollingWindowDays, &p.BackfillHorizonDays, &p.MaxHeartRate, &p.RestingHeartRate, + &p.HRZone1MinPct, &p.HRZone1MaxPct, &p.HRZone2MinPct, &p.HRZone2MaxPct, + &p.HRZone3MinPct, &p.HRZone3MaxPct, &p.HRZone4MinPct, &p.HRZone4MaxPct, + &p.HRZone5MinPct, &p.HRZone5MaxPct, + &p.WarmupMinutes, &p.CooldownMinutes, + &p.MinRepresentativePaceSecPerKm, &p.MinRepresentativeTimeSeconds, + &p.PaceColor, &p.HeartRateColor, &p.WarmupColor, &p.EffortColor, &p.RecoveryColor, &p.CooldownColor, + &p.MainLineTintPct, &p.BackgroundDarkenPct, &p.TargetBrightenPct, + &p.CreatedAt, &p.UpdatedAt, + ) +``` + +Do **not** touch `UpdateProfile` — `garmin_connected_at` must stay out of its `SET`/args list so a normal Profile-page save can never reset it. + +- [ ] **Step 5: Add `MarkGarminConnected`** + +Append to `backend/internal/store/profile.go`: + +```go + +// MarkGarminConnected records the first time userID successfully +// authenticates with Garmin. A no-op if already set, so it always reflects +// the first connection, not the most recent one. +func (db *DB) MarkGarminConnected(ctx context.Context, userID int64) error { + _, err := db.ExecContext(ctx, `UPDATE profile SET garmin_connected_at = datetime('now') WHERE user_id = ? AND garmin_connected_at IS NULL`, userID) + if err != nil { + return fmt.Errorf("mark garmin connected for user %d: %w", userID, err) + } + return nil +} +``` + +- [ ] **Step 6: Run tests to verify they pass** + +Run: `cd backend && go test ./internal/store/... -run 'TestMarkGarminConnected|TestIsolation_MarkGarminConnected' -v` +Expected: PASS. + +- [ ] **Step 7: Run the full store test suite** + +Run: `cd backend && go test ./internal/store/...` +Expected: PASS. + +- [ ] **Step 8: Regenerate `docs/DATABASE.md`** + +Run: `cd backend && go run ./cmd/dumpschema` +Expected: `docs/DATABASE.md` shows the new `garmin_connected_at` column in `profile`. + +- [ ] **Step 9: Additively update the live local dev DB** + +The real `backend/geniusrun.db` predates this column (schema.sql changes never retrofit an existing DB file — see `applySchema`'s idempotent skip in `db.go`). Unlike the earlier `ON DELETE CASCADE` fix, this is purely additive (a new nullable column), so a plain `ALTER TABLE` is sufficient — no rebuild-and-copy dance needed: + +```bash +sqlite3 backend/geniusrun.db "ALTER TABLE profile ADD COLUMN garmin_connected_at TEXT;" +sqlite3 backend/geniusrun.db "SELECT sql FROM sqlite_master WHERE type='table' AND name='profile';" | grep garmin_connected_at +``` + +Confirm the backend isn't running before touching the file (`ps aux | grep geniusrund`), same care as before. + +- [ ] **Step 10: Commit** + +```bash +git add backend/internal/store/schema.sql backend/internal/store/profile.go backend/internal/store/profile_test.go backend/internal/store/isolation_test.go docs/DATABASE.md +git commit -m "feat(store): persist garmin_connected_at, set once on first successful auth" +``` + +--- + +### Task 2: Wire `MarkGarminConnected` into the auth handlers and expose it via session/me + +**Files:** +- Modify: `backend/internal/api/auth.go` (`recordAuthResult`, both call sites) +- Modify: `backend/internal/api/session.go` (`sessionMeResponse`, `handleSessionMe`) +- Modify: `backend/internal/api/api_test.go` (new tests) +- Modify: `backend/internal/api/isolation_test.go` (new adversarial test) + +**Interfaces:** +- Consumes: `store.DB.MarkGarminConnected(ctx, userID) error` (Task 1); `store.DB.GetProfile(ctx, userID) (store.Profile, error)` (existing). +- Produces: `sessionMeResponse.GarminConnected bool` (JSON `garmin_connected`). + +- [ ] **Step 1: Write the failing tests** + +Append to `backend/internal/api/api_test.go`: + +```go +func TestSessionMe_ReportsGarminConnectedAfterSuccessfulAuth(t *testing.T) { + s, _, _ := newTestServer(t) + router := s.Router() + + rec := doJSON(t, router, http.MethodGet, "/api/session/me", nil) + var before sessionMeResponse + unmarshalBody(t, rec, &before) + if before.GarminConnected { + t.Fatal("expected a fresh account to report garmin_connected=false") + } + + rec = doJSON(t, router, http.MethodPost, "/api/auth/login", nil) // mock.Client defaults to AuthSuccess + if rec.Code != http.StatusOK { + t.Fatalf("auth/login status = %d, body = %s", rec.Code, rec.Body.String()) + } + + rec = doJSON(t, router, http.MethodGet, "/api/session/me", nil) + var after sessionMeResponse + unmarshalBody(t, rec, &after) + if !after.GarminConnected { + t.Fatal("expected garmin_connected=true after a successful auth") + } +} + +func TestSessionMe_GarminConnectedStaysFalseOnMFARequiredOrFailed(t *testing.T) { + s, _, userID := newTestServer(t) + client, err := s.garminFor(context.Background(), userID) + if err != nil { + t.Fatalf("garminFor: %v", err) + } + mockClient, ok := client.(*mock.Client) + if !ok { + t.Fatalf("expected *mock.Client, got %T", client) + } + mockClient.AuthResults = []garmin.AuthResult{{Status: garmin.AuthMFARequired, Message: "MFA required"}} + + router := s.Router() + rec := doJSON(t, router, http.MethodPost, "/api/auth/login", nil) + if rec.Code != http.StatusOK { + t.Fatalf("auth/login status = %d, body = %s", rec.Code, rec.Body.String()) + } + + rec = doJSON(t, router, http.MethodGet, "/api/session/me", nil) + var me sessionMeResponse + unmarshalBody(t, rec, &me) + if me.GarminConnected { + t.Fatal("expected garmin_connected=false after mfa_required") + } +} +``` + +Append to `backend/internal/api/isolation_test.go`: + +```go +// TestIsolation_GarminConnectedNeverLeaksAcrossUsers confirms one user's +// successful Garmin auth never flips garmin_connected for another user. +func TestIsolation_GarminConnectedNeverLeaksAcrossUsers(t *testing.T) { + s, db, _ := newTestServer(t) // provisions "test-user" (userA) + if _, err := db.ProvisionUser(newCtx(), "user-b", "B"); err != nil { + t.Fatalf("ProvisionUser(b): %v", err) + } + + router := s.Router() + rec := doJSON(t, router, http.MethodPost, "/api/auth/login", nil) // as userA + if rec.Code != http.StatusOK { + t.Fatalf("auth/login status = %d, body = %s", rec.Code, rec.Body.String()) + } + + rec = doJSONAs(t, router, "user-b", http.MethodGet, "/api/session/me", nil) + var meB sessionMeResponse + unmarshalBody(t, rec, &meB) + if meB.GarminConnected { + t.Fatal("userA's successful Garmin auth leaked into userB's garmin_connected flag") + } +} +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `cd backend && go test ./internal/api/... -run 'TestSessionMe_ReportsGarminConnected|TestSessionMe_GarminConnectedStaysFalse|TestIsolation_GarminConnected' -v` +Expected: FAIL — `sessionMeResponse` has no field `GarminConnected`. + +- [ ] **Step 3: Update `recordAuthResult` in `auth.go`** + +Change the imports: + +```go +import ( + "context" + "encoding/json" + "log" + "net/http" + + "geniusrun/backend/internal/garmin" +) +``` + +Change `recordAuthResult` and both call sites: + +```go +// recordAuthResult updates the in-memory auth status/message for userID, +// and -- on a successful authentication -- persists that this account has +// connected to Garmin at least once (store.MarkGarminConnected), which is +// what the login gate actually checks (session cookie's in-memory auth +// status resets on every backend restart; this doesn't). +func (s *Server) recordAuthResult(ctx context.Context, userID int64, res garmin.AuthResult) { + s.mu.Lock() + s.userAuthStatus[userID] = res.Status + s.userAuthMessage[userID] = res.Message + s.mu.Unlock() + + if res.Status == garmin.AuthSuccess { + if err := s.DB.MarkGarminConnected(ctx, userID); err != nil { + log.Printf("api: mark garmin connected for user %d: %v", userID, err) + } + } +} +``` + +In `handleAuthLogin`, change `s.recordAuthResult(userID, res)` to `s.recordAuthResult(r.Context(), userID, res)`. +In `handleAuthMFA`, change `s.recordAuthResult(userID, res)` to `s.recordAuthResult(r.Context(), userID, res)`. + +- [ ] **Step 4: Update `sessionMeResponse` and `handleSessionMe` in `session.go`** + +Change: + +```go +type sessionMeResponse struct { + Name string `json:"name"` + Email string `json:"email"` + HasProfile bool `json:"has_profile"` + DisplayName string `json:"display_name,omitempty"` +} +``` + +to: + +```go +type sessionMeResponse struct { + Name string `json:"name"` + Email string `json:"email"` + HasProfile bool `json:"has_profile"` + DisplayName string `json:"display_name,omitempty"` + GarminConnected bool `json:"garmin_connected"` +} +``` + +Change `handleSessionMe`: + +```go +func (s *Server) handleSessionMe(w http.ResponseWriter, r *http.Request) { + claims, ok := auth.ClaimsFromContext(r.Context()) + if !ok { + // Unreachable in practice -- RequireSession already 401s before this + // handler runs -- but fail closed rather than panic if that ever changes. + writeError(w, http.StatusUnauthorized, "not authenticated") + return + } + resp := sessionMeResponse{Name: claims.Name, Email: claims.Email} + if u, found := userFromContext(r.Context()); found { + resp.HasProfile = true + resp.DisplayName = u.DisplayName + profile, err := s.DB.GetProfile(r.Context(), u.ID) + if err != nil { + writeError(w, http.StatusInternalServerError, err.Error()) + return + } + resp.GarminConnected = profile.GarminConnectedAt != nil + } + writeJSON(w, http.StatusOK, resp) +} +``` + +- [ ] **Step 5: Run tests to verify they pass** + +Run: `cd backend && go test ./internal/api/... -run 'TestSessionMe_ReportsGarminConnected|TestSessionMe_GarminConnectedStaysFalse|TestIsolation_GarminConnected' -v` +Expected: PASS. + +- [ ] **Step 6: Run the full backend test suite** + +Run: `cd backend && go build ./... && go vet ./... && gofmt -l . && go test ./...` +Expected: `gofmt -l .` empty; everything else passes. + +- [ ] **Step 7: Commit** + +```bash +git add backend/internal/api/auth.go backend/internal/api/session.go backend/internal/api/api_test.go backend/internal/api/isolation_test.go +git commit -m "feat(api): persist and expose garmin_connected on successful auth" +``` + +--- + +### Task 3: Frontend — three-way login gate and the new ConnectGarmin screen + +**Files:** +- Modify: `frontend/src/types/api.ts` (`SessionInfo`) +- Create: `frontend/src/ConnectGarmin.tsx` +- Modify: `frontend/src/CreateProfile.tsx` (add Log out link) +- Modify: `frontend/src/CreateProfile.css` (one new class, shared with `ConnectGarmin.tsx`) +- Modify: `frontend/src/LoginGate.tsx` (three-way fork) + +**Interfaces:** +- Consumes: `api.getProfile()`, `api.updateProfile(profile)`, `api.login()`, `api.submitMFA(code)` (all existing, unchanged signatures); `SessionInfo.garmin_connected: boolean` (new). +- Produces: `ConnectGarmin({ onConnected: () => void })`, a React component. + +- [ ] **Step 1: Add `garmin_connected` to `SessionInfo`** + +In `frontend/src/types/api.ts`, change: + +```ts +export interface SessionInfo { + name: string; + email: string; + has_profile: boolean; + display_name?: string; +} +``` + +to: + +```ts +export interface SessionInfo { + name: string; + email: string; + has_profile: boolean; + display_name?: string; + garmin_connected: boolean; +} +``` + +- [ ] **Step 2: Add a shared status-message class to `CreateProfile.css`** + +Append to `frontend/src/CreateProfile.css`: + +```css +.create-profile-message { + margin: 0; + color: #9ca3af; +} + +.create-profile-mfa { + display: flex; + flex-direction: column; + gap: 0.75rem; + width: 100%; + max-width: 320px; +} +``` + +- [ ] **Step 3: Create `frontend/src/ConnectGarmin.tsx`** + +```tsx +import { useState } from "react"; +import { api, BASE_URL } from "./api/client"; +import "./CreateProfile.css"; +import type { AuthResponse } from "./types/api"; + +// Shown after CreateProfile (or on any later login, until it succeeds -- +// see LoginGate) since connecting Garmin is mandatory: the account exists +// but this is the last gate before the main app. Deliberately not a reuse +// of GarminConnection.tsx (the Profile page's version), which also renders +// Sync now/Disconnect/Reset all -- none of which make sense here. +export function ConnectGarmin({ onConnected }: { onConnected: () => void }) { + const [email, setEmail] = useState(""); + const [password, setPassword] = useState(""); + const [code, setCode] = useState(""); + const [auth, setAuth] = useState(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + async function connect(e: React.FormEvent) { + e.preventDefault(); + if (!email.trim() || !password) { + setError("Please enter your Garmin email and password."); + return; + } + setBusy(true); + setError(null); + try { + const profile = await api.getProfile(); + await api.updateProfile({ ...profile, GarminEmail: email.trim(), GarminPassword: password }); + setAuth(await api.login()); + } catch (err) { + setError(err instanceof Error ? err.message : "Something went wrong, please try again."); + } finally { + setBusy(false); + } + } + + async function submitMFA() { + if (!code.trim()) return; + setBusy(true); + setError(null); + try { + setAuth(await api.submitMFA(code.trim())); + setCode(""); + } catch (err) { + setError(err instanceof Error ? err.message : "Something went wrong, please try again."); + } finally { + setBusy(false); + } + } + + const status = auth?.status; + + return ( +
+

🧞‍♀️ Connect your Garmin account

+

geniusrun needs your Garmin credentials to sync your activities.

+ + {status !== "authenticated" && status !== "mfa_required" && ( +
+ setEmail(e.target.value)} + disabled={busy} + autoFocus + /> + setPassword(e.target.value)} + disabled={busy} + /> + +
+ )} + + {status === "mfa_required" && ( +
+ setCode(e.target.value)} + onKeyDown={(e) => e.key === "Enter" && submitMFA()} + disabled={busy} + autoFocus + /> + +
+ )} + + {status === "authenticated" && ( + <> +

Connected to Garmin.

+ + + )} + + {auth?.message && status !== "authenticated" &&

{auth.message}

} + {error &&

{error}

} + +
+ +
+
+ ); +} +``` + +- [ ] **Step 4: Add a Log out link to `CreateProfile.tsx`** + +Change: + +```tsx + {error &&

{error}

} + + + + ); +} +``` + +to: + +```tsx + {error &&

{error}

} + + +
+ +
+ + ); +} +``` + +And change the import line at the top of `CreateProfile.tsx`: + +```tsx +import { api } from "./api/client"; +``` + +to: + +```tsx +import { api, BASE_URL } from "./api/client"; +``` + +- [ ] **Step 5: Wire the three-way fork into `LoginGate.tsx`** + +Change the imports: + +```tsx +import { useEffect, useState } from "react"; +import { api, BASE_URL } from "./api/client"; +import "./LoginGate.css"; +import App from "./App"; +import { CreateProfile } from "./CreateProfile"; +import type { SessionInfo } from "./types/api"; +``` + +to: + +```tsx +import { useEffect, useState } from "react"; +import { api, BASE_URL } from "./api/client"; +import "./LoginGate.css"; +import App from "./App"; +import { ConnectGarmin } from "./ConnectGarmin"; +import { CreateProfile } from "./CreateProfile"; +import type { SessionInfo } from "./types/api"; +``` + +Change the final part of the component body: + +```tsx + if (!session!.has_profile) { + return ( + setSession((s) => (s ? { ...s, has_profile: true, display_name: displayName } : s))} + /> + ); + } + + return ; +} +``` + +to: + +```tsx + if (!session!.has_profile) { + return ( + setSession((s) => (s ? { ...s, has_profile: true, display_name: displayName } : s))} + /> + ); + } + + // Connecting Garmin is mandatory, re-checked on every login (not just + // right after signup) -- see docs/superpowers/specs/2026-07-26-improve-first-connection-design.md + // for why this can't be a purely in-session check. + if (!session!.garmin_connected) { + return setSession((s) => (s ? { ...s, garmin_connected: true } : s))} />; + } + + return ; +} +``` + +Also update the doc comment above the `LoginGate` function (currently describes only a two-way fork) -- change: + +```tsx +// Wraps App: on mount, asks the backend whether this browser already has a +// valid session (GET /api/session/me). geniusrun has no anonymous view, so +// this is the first fork -- "show the login screen" vs "show the app." A +// second fork, once authenticated, is whether the session's account has a +// provisioned profile yet (session.has_profile) -- a brand-new OIDC login +// sees CreateProfile instead of App until it submits one. +``` + +to: + +```tsx +// Wraps App: on mount, asks the backend whether this browser already has a +// valid session (GET /api/session/me). geniusrun has no anonymous view, so +// this is the first fork -- "show the login screen" vs "show the app." A +// second fork, once authenticated, is whether the session's account has a +// provisioned profile yet (session.has_profile) -- a brand-new OIDC login +// sees CreateProfile instead of App until it submits one. A third fork, +// once provisioned, is whether Garmin has ever been successfully connected +// (session.garmin_connected) -- mandatory, and re-checked on every login, +// not just immediately after signup. +``` + +- [ ] **Step 6: Build and lint** + +Run: `cd frontend && npm run build && npm run lint` +Expected: build succeeds; lint reports no new warnings beyond the 3 pre-existing `PaceField.tsx` ones. + +- [ ] **Step 7: Manual browser verification** + +With the backend (`cd backend && ./start.sh`) and frontend (`cd frontend && ./start.sh`) running: +1. Delete your profile (or use a fresh OIDC account) so you land on `CreateProfile`. +2. Submit a display name — confirm you're immediately routed to `ConnectGarmin`, not the main app. +3. Try an obviously wrong Garmin password — confirm the error shows and the form stays editable. +4. Enter correct credentials (resolve MFA if prompted) — confirm "Connected to Garmin." appears with a "Continue to geniusrun" button, and clicking it lands in the main app. +5. Log out, log back in with the same account — confirm you land straight in the app (not back through `ConnectGarmin`), proving `garmin_connected_at` persisted. +6. On the `ConnectGarmin` screen specifically, confirm the "Log out" link works. + +- [ ] **Step 8: Commit** + +```bash +git add frontend/src/types/api.ts frontend/src/ConnectGarmin.tsx frontend/src/CreateProfile.tsx frontend/src/CreateProfile.css frontend/src/LoginGate.tsx +git commit -m "feat(onboarding): add mandatory ConnectGarmin gate to first login" +``` + +--- + +### Task 4: Final verification + +**Files:** none (verification + cleanup only) + +- [ ] **Step 1: Full backend check** + +Run: `cd backend && gofmt -l . && go vet ./... && go build ./... && go test ./...` +Expected: `gofmt -l .` empty; everything else passes. + +- [ ] **Step 2: Full frontend check** + +Run: `cd frontend && npm run build && npm run lint` +Expected: both succeed, no new lint warnings. + +- [ ] **Step 3: Confirm `docs/DATABASE.md` is current** + +Run: `cd backend && go run ./cmd/dumpschema && git status --short docs/DATABASE.md` +Expected: no output from `git status` (already committed in Task 1, unchanged since). + +- [ ] **Step 4: Update `docs/IDEAS.md`** + +Remove the now-implemented line from the Backlog section: + +``` +- improve first connection page: in CreateProfile.tsx, in addition to the display name, we should directly ask garmin login/password and manage MFA from there, so the synchronization experience in profile page will be easier later on +``` + +- [ ] **Step 5: Commit** + +```bash +git add docs/IDEAS.md +git commit -m "docs: remove improve-first-connection-page from IDEAS backlog (implemented)" +```