carlos / platform Public

Analytics on-ramp Task 2: Turn on analytics on the Analytics tab

With analytics off, the tab says what is counted and gives an owner one
button that saves through the existing app door and comes back to the tab
(back=analytics, a token the door maps to a path; success and refusal
both return there). A member sees a line that an owner can turn it on.
Off with nothing counted hides the tables, chart and range picker;
numbers counted earlier still show.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev af832617ddd32b977e5afe9cae553e6b20563a61 parent d8ff93e
7 files changed, +241 −26
  • internal/console/analytics_onramp_test.go +157 −0
  • internal/console/analyticsview.go +53 −2
  • internal/console/apianalytics_test.go +1 −1
  • internal/console/appnav_test.go +3 −1
  • internal/console/approved_analytics_onramp_copy_test.go +3 −1
  • internal/console/appsettings_sections_test.go +2 −15
  • internal/console/templates/app_analytics.html +22 −6
diff --git a/internal/console/analytics_onramp_test.go b/internal/console/analytics_onramp_test.go
new file mode 100644
index 000000000..b4f6c30fb
--- /dev/null
+++ b/internal/console/analytics_onramp_test.go
@@ -0,0 +1,157 @@
+package console
+
+// The analytics on-ramp (docs/superpowers/plans/2026-10-26-analytics-onramp.md):
+// the Analytics tab's off state with its Turn on analytics button, the Create
+// an app form's checkbox, and new accounts starting with analytics on.
+
+import (
+ "context"
+ "net/http"
+ "net/url"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/telemetry"
+)
+
+// The off state's own words (copy deck AN-C01 to AN-C04).
+const (
+ onrampOffLead = "<strong>Analytics is off for this app.</strong>"
+ onrampOffWhat = "When analytics is on, the edge counts HTML page views and daily visitors. No JavaScript, no cookie, no stored IP."
+ onrampTurnOn = "Turn on analytics"
+ onrampMemberOff = "An account owner can turn on analytics."
+)
+
+// onrampDataMarkers are the tab's data sections: the summary table, the
+// top-keys tables' empty rows, and the terminal hint under them.
+var onrampDataMarkers = []string{"<th>Page views</th>", "Nothing yet.", "<h3>Top pages", "carlos analytics --app titogo"}
+
+func TestAnalyticsTabOffStateOwner(t *testing.T) {
+ fx, _ := instanceFixture(t, "code-onramp-tab-owner")
+ fx.setUser("paul@keymail.dev")
+ c := newBrowser(t)
+ signUp(t, fx, c, "code-onramp-tab-owner-browser")
+
+ status, _, body := get(t, c, fx.u("/apps/titogo/analytics"))
+ if status != http.StatusOK {
+ t.Fatalf("GET analytics = %d", status)
+ }
+ for _, want := range []string{onrampOffLead, onrampOffWhat, onrampTurnOn,
+ `action="/a/` + fx.sqid + `/apps/titogo/analytics/setting"`,
+ `name="count" value="edge"`, `name="back" value="analytics"`} {
+ if !strings.Contains(body, want) {
+ t.Errorf("off state (owner) missing %q", want)
+ }
+ }
+ // It no longer sends the owner to Settings (AN-C05), and an app that
+ // never counted shows no empty tables, chart or range picker.
+ for _, gone := range []string{"settings/errors-analytics", "Turn it on for this app in", onrampMemberOff,
+ `role="img" aria-label="Page views"`, `<form method="get" class="toolbar">`} {
+ if strings.Contains(body, gone) {
+ t.Errorf("off state (owner) still shows %q", gone)
+ }
+ }
+ for _, gone := range onrampDataMarkers {
+ if strings.Contains(body, gone) {
+ t.Errorf("off state with nothing counted shows the data section %q", gone)
+ }
+ }
+
+ // The button saves through the existing door and comes back to the tab.
+ form := url.Values{"csrf": {sessionToken(t, fx, c)}, "count": {"edge"}, "back": {"analytics"}}
+ status, loc, _ := postForm(t, c, fx.u("/apps/titogo/analytics/setting"), form)
+ if want := fx.path("/apps/titogo/analytics"); status != http.StatusSeeOther || loc != want {
+ t.Fatalf("Turn on analytics = %d -> %q, want 303 to %q", status, loc, want)
+ }
+ res, err := telemetry.Resolve(context.Background(), fx.rel, fx.sqid, "titogo")
+ if err != nil || res.Count != telemetry.CountEdge || res.CountFrom != "app" || res.DoorFrom != "default" {
+ t.Fatalf("after Turn on analytics: %+v %v, want count edge from the app and the door untouched", res, err)
+ }
+ _, _, body = get(t, c, fx.ts.URL+loc)
+ if !strings.Contains(body, analyticsTurnedOnFlash) {
+ t.Errorf("the tab does not show %q after turning on", analyticsTurnedOnFlash)
+ }
+ // On: the off state goes and the data sections show, empty or not.
+ if strings.Contains(body, onrampOffLead) || strings.Contains(body, onrampTurnOn) {
+ t.Error("the off state still shows after turning on")
+ }
+ for _, want := range append([]string{`<form method="get" class="toolbar">`}, onrampDataMarkers...) {
+ if !strings.Contains(body, want) {
+ t.Errorf("on: the tab is missing the data section %q", want)
+ }
+ }
+
+ // A refusal comes back to the tab too, with its message.
+ form = url.Values{"csrf": {sessionToken(t, fx, c)}, "count": {"bogus"}, "back": {"analytics"}}
+ status, loc, _ = postForm(t, c, fx.u("/apps/titogo/analytics/setting"), form)
+ if want := fx.path("/apps/titogo/analytics"); status != http.StatusSeeOther || loc != want {
+ t.Fatalf("refused Turn on = %d -> %q, want 303 to %q", status, loc, want)
+ }
+ if _, _, body = get(t, c, fx.ts.URL+loc); !strings.Contains(body, "Choose edge or off for counting.") {
+ t.Error("the tab does not show the refusal")
+ }
+
+ // back is a token, not a URL: anything else is the settings section.
+ form = url.Values{"csrf": {sessionToken(t, fx, c)}, "count": {"edge"}, "back": {"https://example.com/"}}
+ status, loc, _ = postForm(t, c, fx.u("/apps/titogo/analytics/setting"), form)
+ if want := fx.path("/apps/titogo/settings/errors-analytics"); status != http.StatusSeeOther || loc != want {
+ t.Fatalf("unknown back = %d -> %q, want 303 to %q", status, loc, want)
+ }
+}
+
+func TestAnalyticsTabOffStateMember(t *testing.T) {
+ fx, _ := instanceFixture(t, "code-onramp-tab-member")
+ fx.setUser("alice@keymail.dev")
+ m := newBrowser(t)
+ signUp(t, fx, m, "code-onramp-tab-member-browser")
+
+ status, _, body := get(t, m, fx.u("/apps/titogo/analytics"))
+ if status != http.StatusOK {
+ t.Fatalf("GET analytics = %d", status)
+ }
+ for _, want := range []string{onrampOffLead, onrampOffWhat, onrampMemberOff} {
+ if !strings.Contains(body, want) {
+ t.Errorf("off state (member) missing %q", want)
+ }
+ }
+ for _, gone := range []string{onrampTurnOn, "/analytics/setting", "settings/errors-analytics"} {
+ if strings.Contains(body, gone) {
+ t.Errorf("off state (member) shows %q", gone)
+ }
+ }
+ // The door itself is unchanged for a member: the owner gate's 404, even
+ // with the tab's back token.
+ form := url.Values{"csrf": {sessionToken(t, fx, m)}, "count": {"edge"}, "back": {"analytics"}}
+ if status, loc, _ := postForm(t, m, fx.u("/apps/titogo/analytics/setting"), form); status != http.StatusNotFound || loc != "" {
+ t.Fatalf("member Turn on = %d -> %q, want the owner gate's 404", status, loc)
+ }
+ if res, _ := telemetry.Resolve(context.Background(), fx.rel, fx.sqid, "titogo"); res.Count != telemetry.CountOff {
+ t.Fatalf("a member turned analytics on: %+v", res)
+ }
+}
+
+// Analytics off but counted earlier: the numbers stay, under the off state.
+func TestAnalyticsTabOffStateKeepsCountedData(t *testing.T) {
+ fx, _ := instanceFixture(t, "code-onramp-tab-data")
+ seedAnalytics(t, fx, seedTime())
+ fx.setUser("paul@keymail.dev")
+ c := newBrowser(t)
+ signUp(t, fx, c, "code-onramp-tab-data-browser")
+ _, _, body := get(t, c, fx.u("/apps/titogo/analytics"))
+ for _, want := range []string{onrampOffLead, onrampTurnOn, "<th>Page views</th>", "/pricing", `aria-label="Page views"`} {
+ if !strings.Contains(body, want) {
+ t.Errorf("off with counted data: missing %q", want)
+ }
+ }
+}
+
+func TestAnalyticsWindowHasData(t *testing.T) {
+ if (analyticsWindow{}).HasData() {
+ t.Error("an empty window has data")
+ }
+ var w analyticsWindow
+ w.Sum.Events = map[string]int64{"signup": 1}
+ if !w.HasData() {
+ t.Error("a window holding only a named event has no data")
+ }
+}
diff --git a/internal/console/analyticsview.go b/internal/console/analyticsview.go
index 0718060a0..c7b1a143c 100644
--- a/internal/console/analyticsview.go
+++ b/internal/console/analyticsview.go
@@ -64,6 +64,23 @@ func analyticsFormValues(r *http.Request) (count, door, bad string) {
return count, door, ""
}
+// The two places besides the settings pages an analytics switch may send the
+// browser back to (the "back" form field): the app's Analytics tab, and the
+// Create an app form. Anything else is the settings page, as before.
+const (
+ analyticsBackTab = "analytics"
+ analyticsBackNewApp = "new-app"
+)
+
+// The on-ramp's flashes (copy deck 2026-10-26-analytics-onramp-copy.md,
+// AN-C06, AN-C19, AN-C20): said where the button was pressed, in words
+// rather than the settings vocabulary.
+const (
+ analyticsTurnedOnFlash = "Analytics is on for this app. Page views appear here as they are counted."
+ analyticsAccountDefaultOnFlash = "Analytics is now on for every app in this account without its own setting."
+ analyticsAccountDefaultOffFlash = "Analytics is now off for every app in this account without its own setting."
+)
+
// analyticsFlash is what the owner is told after a save: what is now true,
// named, rather than "saved".
func analyticsFlash(count, door, scope string) string {
@@ -97,6 +114,13 @@ func (s *Server) handleAppAnalyticsSetting(w http.ResponseWriter, r *http.Reques
}
count, door, bad := analyticsFormValues(r)
back := appSettingsURL(acct.Sqid, app, "errors-analytics")
+ // The Analytics tab's Turn on analytics button names the tab as where to
+ // come back to, on success and refusal alike. A token, never a URL: the
+ // door picks the path, so no form can send the browser anywhere else.
+ fromTab := r.FormValue("back") == analyticsBackTab
+ if fromTab {
+ back = "/a/" + url.PathEscape(acct.Sqid) + "/apps/" + url.PathEscape(app) + "/analytics"
+ }
// The setting lives in the deployment bucket, so a console without one
// has nowhere to put it — refused before the write rather than panicking
// inside it, exactly as the errors level is.
@@ -122,7 +146,11 @@ func (s *Server) handleAppAnalyticsSetting(w http.ResponseWriter, r *http.Reques
// Box-consumed: the edge starts or stops counting on the next pass, so
// the serial moves rather than leaving it to the hourly floor.
s.bumpSerial(r.Context())
- s.setFlash(w, "ok", analyticsFlash(count, door, "for this app"))
+ flash := analyticsFlash(count, door, "for this app")
+ if fromTab && count == telemetry.CountEdge && door == "" {
+ flash = analyticsTurnedOnFlash
+ }
+ s.setFlash(w, "ok", flash)
http.Redirect(w, r, back, http.StatusSeeOther)
}
@@ -143,6 +171,12 @@ func (s *Server) handleAccountAnalyticsSetting(w http.ResponseWriter, r *http.Re
}
count, door, bad := analyticsFormValues(r)
back := "/a/" + url.PathEscape(acct.Sqid) + "/settings"
+ // The Create an app form's Make this the account default button comes
+ // back to that form, by token for the reason the app door gives.
+ fromNewApp := r.FormValue("back") == analyticsBackNewApp
+ if fromNewApp {
+ back = "/a/" + url.PathEscape(acct.Sqid) + "/apps/new"
+ }
if s.cfg.Releases == nil {
s.setFlash(w, "err", "No deployment bucket on this host, so this setting cannot be stored.")
http.Redirect(w, r, back, http.StatusSeeOther)
@@ -165,7 +199,14 @@ func (s *Server) handleAccountAnalyticsSetting(w http.ResponseWriter, r *http.Re
// the reason handleAccountErrorLevel spells out.
s.audit(acct, accountAuditSubject, addr, "analytics-setting", "set the account's "+analyticsAudit(count, door))
s.bumpSerial(r.Context())
- s.setFlash(w, "ok", analyticsFlash(count, door, "for every app without its own setting"))
+ flash := analyticsFlash(count, door, "for every app without its own setting")
+ if fromNewApp && door == "" {
+ flash = analyticsAccountDefaultOffFlash
+ if count == telemetry.CountEdge {
+ flash = analyticsAccountDefaultOnFlash
+ }
+ }
+ s.setFlash(w, "ok", flash)
http.Redirect(w, r, back, http.StatusSeeOther)
}
@@ -200,6 +241,16 @@ type analyticsWindow struct {
ChartMax int64
}
+// HasData reports whether the window holds anything counted. With analytics
+// off the tab hides its tables and chart unless it does: numbers collected
+// while it was on stay visible, and an app that never counted shows only the
+// switch rather than empty tables.
+func (w analyticsWindow) HasData() bool {
+ s := w.Sum
+ return s.PV > 0 || s.Bots > 0 || s.Bytes > 0 || s.Visitors > 0 ||
+ len(s.Pages) > 0 || len(s.Referers) > 0 || len(s.Events) > 0 || len(s.Countries) > 0
+}
+
// chartBar is one plotted column: the reading, and the rectangle that draws
// it. The geometry is computed here rather than in the template because a
// template cannot divide, and because the scaling is the part worth testing.
diff --git a/internal/console/apianalytics_test.go b/internal/console/apianalytics_test.go
index 119e8ecfa..de501fd3a 100644
--- a/internal/console/apianalytics_test.go
+++ b/internal/console/apianalytics_test.go
@@ -167,7 +167,7 @@ func TestAppAnalyticsPage(t *testing.T) {
t.Fatalf("%d %s", status, body)
}
// Off: the switch and the reading, and the numbers that exist already.
- for _, want := range []string{"Analytics is off for this app", "no JavaScript, no cookie", "/pricing", "news.ycombinator.com", "signup", "<svg"} {
+ for _, want := range []string{"Analytics is off for this app", "No JavaScript, no cookie", "/pricing", "news.ycombinator.com", "signup", "<svg"} {
if !strings.Contains(body, want) {
t.Errorf("page missing %q", want)
}
diff --git a/internal/console/appnav_test.go b/internal/console/appnav_test.go
index 0362480f1..5da00e6ee 100644
--- a/internal/console/appnav_test.go
+++ b/internal/console/appnav_test.go
@@ -208,7 +208,9 @@ func TestRunningLeftoversNameTheTab(t *testing.T) {
func TestLogsToolbar(t *testing.T) {
fx := newConsoleFixture(t)
c := signInPaul(t, fx)
- for _, tab := range []string{"logs", "errors", "availability", "analytics"} {
+ // Analytics is off for kass and nothing is counted, so its tab hides the
+ // range picker on today (the on-ramp's off state); any other range keeps it.
+ for _, tab := range []string{"logs", "errors", "availability", "analytics?range=7d"} {
status, _, body := get(t, c, fx.u("/apps/kass/"+tab))
if status != 200 {
t.Fatalf("GET /apps/kass/%s = %d", tab, status)
diff --git a/internal/console/approved_analytics_onramp_copy_test.go b/internal/console/approved_analytics_onramp_copy_test.go
index 315cef078..c26aa8fc1 100644
--- a/internal/console/approved_analytics_onramp_copy_test.go
+++ b/internal/console/approved_analytics_onramp_copy_test.go
@@ -19,7 +19,9 @@ const onrampCopyDeckPath = "../../docs/superpowers/plans/2026-10-26-analytics-on
// carry. The task that writes a row's text adds its id here in the same
// commit, once the row is approved. From then on a "gate" row's new text must
// be in its file, and any other row's named test must exist.
-var onrampCopyBuilt = map[string]bool{}
+var onrampCopyBuilt = map[string]bool{
+ "AN-C01": true, "AN-C02": true, "AN-C03": true, "AN-C04": true, "AN-C05": true, "AN-C06": true,
+}
// onrampCopyTestFiles are the test sources a non-gate row's test may live in:
// this package's, and the root package's for the CLI rows.
diff --git a/internal/console/appsettings_sections_test.go b/internal/console/appsettings_sections_test.go
index 2d72bb064..379259139 100644
--- a/internal/console/appsettings_sections_test.go
+++ b/internal/console/appsettings_sections_test.go
@@ -160,21 +160,8 @@ func TestTelemetryHintsLinkTheSection(t *testing.T) {
t.Errorf("Errors tab hint does not link the Errors and analytics section:\n%s", errs)
}
- _, _, an := get(t, c, fx.u("/apps/titogo/analytics"))
- i := strings.Index(an, "Turn it on for this app in ")
- if i < 0 {
- t.Fatalf("Analytics tab (off) has no hint:\n%s", an)
- }
- hint, _, _ := strings.Cut(an[i:], "</p>")
- for _, want := range []string{section + ">Settings, under Errors and analytics</a>",
- "or for the whole account in the account's <a href=", `/settings">Settings</a>.`} {
- if !strings.Contains(hint, want) {
- t.Errorf("Analytics tab hint missing %q: %s", want, hint)
- }
- }
- if strings.Contains(hint, `/apps/titogo/settings">`) {
- t.Errorf("Analytics tab hint still links the app's General settings: %s", hint)
- }
+ // The Analytics tab's off state no longer points at Settings: it carries
+ // its own Turn on analytics button (TestAnalyticsTabOffStateOwner).
}
func TestAppSettingsURL(t *testing.T) {
diff --git a/internal/console/templates/app_analytics.html b/internal/console/templates/app_analytics.html
index 8a1fc3628..54eaeea12 100644
--- a/internal/console/templates/app_analytics.html
+++ b/internal/console/templates/app_analytics.html
@@ -5,13 +5,26 @@
<h2 class="visually-hidden">Analytics</h2>
{{if .AnalyticsErr}}<p class="banner error">{{.AnalyticsErr}}</p>{{end}}
-{{if not .AnalyticsWin.On}}
-<p><strong>Analytics is off for this app</strong> (from the {{.AnalyticsWin.Setting.CountFrom}}).
-When on, the edge counts HTML page views and daily visitors as it serves them: no JavaScript, no cookie,
-no stored IP. A visitor is a salted hash that changes every day.
-Turn it on for this app in <a href="{{.Nav}}/apps/{{.AppName}}/settings/errors-analytics">Settings, under Errors and analytics</a>,
-or for the whole account in the account's <a href="{{.Nav}}/settings">Settings</a>.</p>
+{{/* A failed read resolves to the defaults, which say "off": offering the
+ switch then would be a guess, so the error stands alone. */}}
+{{if and (not .AnalyticsErr) (not .AnalyticsWin.On)}}
+<p><strong>Analytics is off for this app.</strong>
+When analytics is on, the edge counts HTML page views and daily visitors. No JavaScript, no cookie, no stored IP.</p>
+{{if .IsOwner}}
+<form method="post" action="{{.Base}}/apps/{{.AppName}}/analytics/setting">
+ <input type="hidden" name="csrf" value="{{.CSRF}}">
+ <input type="hidden" name="count" value="edge">
+ <input type="hidden" name="back" value="analytics">
+ <button type="submit">Turn on analytics</button>
+</form>
+{{else}}
+<p class="small">An account owner can turn on analytics.</p>
+{{end}}
{{end}}
+{{/* Off with nothing counted in the window: no empty tables, chart or
+ "Nothing yet" rows. Numbers counted while it was on still show, and a
+ range other than today keeps its picker so older days stay reachable. */}}
+{{if or .AnalyticsWin.On .AnalyticsWin.HasData (ne .AnalyticsRange "today")}}
<form method="get" class="toolbar">
<label>range
<select name="range">
@@ -22,6 +35,8 @@ or for the whole account in the account's <a href="{{.Nav}}/settings">Settings</
</label>
<button type="submit" class="btn-sm">Update</button>
</form>
+{{end}}
+{{if or .AnalyticsWin.On .AnalyticsWin.HasData}}
{{with .AnalyticsWin}}
<div class="tablewrap"><table>
<tr><th>Page views</th><th>Visitors{{if ne $.AnalyticsRange "today"}} (daily visitors, summed){{end}}</th><th>Bytes served</th><th>Bots excluded</th><th>Dropped</th></tr>
@@ -45,5 +60,6 @@ or for the whole account in the account's <a href="{{.Nav}}/settings">Settings</
{{range geoAttributions .Sum.GeoSources}}<p class="small"><a href="{{.URL}}">{{.Text}}</a></p>{{end}}
{{end}}
<p class="small">Times are UTC. The same view from a terminal: <code>carlos analytics --app {{.AppName}} --range {{.AnalyticsRange}}</code>.</p>
+{{end}}
{{template "bottom" .}}{{end}}
{{define "kvtable"}}{{if .}}<div class="tablewrap"><table>{{range sortedKV .}}<tr><td>{{.Key}}</td><td>{{.Value}}</td></tr>{{end}}</table></div>{{else}}<p class="small">Nothing yet.</p>{{end}}{{end}}