analytics-onramp
Squashed from analytics-onramp into main.
31 files changed,
+1,436
−39
analytics_cmd.go+2 −1apimode.go+18 −1apps.go+61 −3apps_analytics_test.go+98 −0docs/site/cli.md+6 −1docs/superpowers/notes/census-proposal-analytics-onramp.md+19 −0docs/superpowers/plans/2026-10-26-analytics-onramp-copy.md+85 −0docs/superpowers/plans/2026-10-26-analytics-onramp.md+24 −0docs/superpowers/plans/LUNA-COPY-BRIEF-ANALYTICS-ONRAMP-C42.md+24 −0docs/superpowers/plans/LUNA-COPY-BRIEF-ANALYTICS-ONRAMP.md+64 −0docs/superpowers/plans/LUNA-COPY-REVIEW-ANALYTICS-ONRAMP.md+22 −0docs/superpowers/reviews/CODEX-REVIEW-BRIEF-analytics-onramp.md+40 −0internal/console/analytics_onramp_test.go+500 −0internal/console/analyticsonramp.go+131 −0internal/console/analyticsview.go+53 −2internal/console/apianalytics_test.go+1 −1internal/console/apicli.go+35 −0internal/console/appnav_test.go+3 −1internal/console/approved_analytics_onramp_copy_test.go+127 −0internal/console/appsettings_sections_test.go+2 −15internal/console/regionpicker_test.go+12 −1internal/console/server.go+42 −2internal/console/templates/account_settings.html+2 −2internal/console/templates/app_analytics.html+20 −6internal/console/templates/app_new.html+22 −0internal/console/templates/app_settings.html+2 −2internal/console/testdata/perf-budgets.txt+1 −0internal/provision/testdata/plan14-root-reads-analytics-onramp.tsv+6 −0internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/telemetry/telemetry.go+7 −1internal/telemetry/telemetry_test.go+6 −0
CI passed — run details
diff --git a/analytics_cmd.go b/analytics_cmd.go| index 490277f7c..71a4c1bff 100644 |
| --- a/analytics_cmd.go |
| +++ b/analytics_cmd.go |
| @@ -15,7 +15,8 @@ import ( |
| const analyticsUsage = `usage: carlos analytics --app <a> [flags] |
| Page views, daily visitors, bytes served, top pages, top referers and named |
| -events, counted at the edge. Off until you turn it on. |
| +events, counted at the edge. New accounts start with analytics on. Existing |
| +accounts keep their current setting. |
| --range is today, 7d or 30d; multi-day visitor totals are daily visitors |
| summed. The same view is the Analytics tab on the app's dashboard. |
diff --git a/apimode.go b/apimode.go| index ec88725d0..e4bbfc5c9 100644 |
| --- a/apimode.go |
| +++ b/apimode.go |
| @@ -1052,6 +1052,13 @@ type apiCreateAppResult struct { |
| // RegionLabel is the stored region's label, "London (UK)" (region |
| // labels spec §4); "" from an older console. |
| RegionLabel string `json:"region_label"` |
| + |
| + // Analytics is what the new app's counting resolves to after the |
| + // create, "edge" or "off", and AnalyticsFrom where that comes from |
| + // ("app", "account" or "default"). Both "" from an older console, which |
| + // also ignores a requested choice; runAppsCreate checks the echo. |
| + Analytics string `json:"analytics"` |
| + AnalyticsFrom string `json:"analytics_from"` |
| } |
| // createApp claims one app name through the console — the API door onto the |
| @@ -1082,6 +1089,15 @@ type apiCreateAppResult struct { |
| // (validBuildProbe, apps.go), same "a shape the server is certain to |
| // refuse should cost nothing" principle as place. |
| func (s *apiSession) createApp(ctx context.Context, a apiAcct, app, place string, controlPlane bool, buildProbe, region, timezone string) (apiCreateAppResult, error) { |
| + return s.createAppAnalytics(ctx, a, app, place, controlPlane, buildProbe, region, timezone, "") |
| +} |
| + |
| +// createAppAnalytics is createApp with the new app's analytics choice: |
| +// "" follows the account, "edge" or "off" asks for that (`carlos apps create |
| +// --analytics/--no-analytics`). Only an owner may ask for something other |
| +// than the account's default; the console refuses anyone else before the |
| +// name is claimed. |
| +func (s *apiSession) createAppAnalytics(ctx context.Context, a apiAcct, app, place string, controlPlane bool, buildProbe, region, timezone, analytics string) (apiCreateAppResult, error) { |
| in := struct { |
| Name string `json:"name"` |
| Place string `json:"place,omitempty"` |
| @@ -1089,7 +1105,8 @@ func (s *apiSession) createApp(ctx context.Context, a apiAcct, app, place string |
| BuildProbe string `json:"build_probe,omitempty"` |
| Region string `json:"region,omitempty"` |
| Timezone string `json:"timezone,omitempty"` |
| - }{app, place, controlPlane, buildProbe, region, timezone} |
| + Analytics string `json:"analytics,omitempty"` |
| + }{app, place, controlPlane, buildProbe, region, timezone, analytics} |
| status, body, err := s.postJSON(ctx, apiPath(a, "new", ""), in) |
| if err != nil { |
| return apiCreateAppResult{}, err |
diff --git a/apps.go b/apps.go| index 9e4831726..f2412ddf0 100644 |
| --- a/apps.go |
| +++ b/apps.go |
| @@ -520,6 +520,8 @@ func runAppsCreate(args []string) { |
| "stamps from the route row and which therefore lies until the process restarts; "+ |
| `the build must appear as a whole whitespace-delimited word in the body, e.g. "ok abc1234"`) |
| region := fs.String("region", "", flagRegionAppsCreate) |
| + analyticsOn := fs.Bool("analytics", false, "turn analytics on for the new app (default: follow the account)") |
| + analyticsOff := fs.Bool("no-analytics", false, "turn analytics off for the new app (default: follow the account)") |
| // Not accountFlags: that helper also registers --registry for direct-mode |
| // resolution, and this verb never resolves locally — the console resolves |
| // the account against the caller's own memberships. |
| @@ -530,7 +532,12 @@ func runAppsCreate(args []string) { |
| fs.Parse(args) |
| if strings.TrimSpace(*app) == "" { |
| log.Fatal("usage: carlos apps create --app <name> [--place fleet/<f>] [--control-plane] " + |
| - "[--build-probe /path] [--region <code>] [--account <sqid|name>] [--account-id <sqid>] [--console <origin>]") |
| + "[--build-probe /path] [--region <code>] [--analytics | --no-analytics] " + |
| + "[--account <sqid|name>] [--account-id <sqid>] [--console <origin>]") |
| + } |
| + analytics, err := analyticsChoice(*analyticsOn, *analyticsOff) |
| + if err != nil { |
| + log.Fatalf("apps create: %v", err) |
| } |
| // Client-side gates before the server's: the create limiter charges |
| // ATTEMPTS, so a name — or a place or build-probe value — the server is |
| @@ -567,8 +574,8 @@ func runAppsCreate(args []string) { |
| printUsing(stdout, sess) |
| acct := resolvedAccount(sess, acctRaw, acctIDRaw) |
| region2 := strings.TrimSpace(*region) |
| - res, err := sess.createApp(context.Background(), acct, strings.TrimSpace(*app), place2, *controlPlane, probe2, |
| - region2, detectTimezone()) |
| + res, err := sess.createAppAnalytics(context.Background(), acct, strings.TrimSpace(*app), place2, *controlPlane, probe2, |
| + region2, detectTimezone(), analytics) |
| if err != nil { |
| log.Fatalf("apps create: %v", err) |
| } |
| @@ -610,6 +617,57 @@ func runAppsCreate(args []string) { |
| } |
| fmt.Fprintf(stdout, " build probe: %s\n", res.BuildProbe) |
| } |
| + // The same "what actually stuck" check for --analytics/--no-analytics: |
| + // the console echoes what the app now resolves to, and an older console |
| + // echoes nothing at all. |
| + if err := analyticsMismatchErr(res.App, analytics, res.Analytics); err != nil { |
| + log.Fatalf("apps create: %v", err) |
| + } |
| + if line := analyticsLine(res); line != "" { |
| + fmt.Fprintf(stdout, " %s\n", line) |
| + } |
| +} |
| + |
| +// analyticsChoice maps --analytics and --no-analytics onto the create |
| +// request's "analytics" value: "" (neither: follow the account), "edge" or |
| +// "off". Both at once is refused before any call. |
| +func analyticsChoice(on, off bool) (string, error) { |
| + switch { |
| + case on && off: |
| + return "", errors.New("choose --analytics or --no-analytics, not both") |
| + case on: |
| + return "edge", nil |
| + case off: |
| + return "off", nil |
| + } |
| + return "", nil |
| +} |
| + |
| +// analyticsLine is the create output's analytics line, from the console's |
| +// echo: "" from a console too old to echo it. |
| +func analyticsLine(res apiCreateAppResult) string { |
| + if res.Analytics == "" { |
| + return "" |
| + } |
| + state := "off" |
| + if res.Analytics == "edge" { |
| + state = "on" |
| + } |
| + if res.AnalyticsFrom == "app" { |
| + return "analytics: " + state + ", set for this app" |
| + } |
| + return "analytics: " + state + ", following the account" |
| +} |
| + |
| +// analyticsMismatchErr compares the analytics choice asked for with what |
| +// the console echoed, the way placementMismatchErr does for --place. No |
| +// choice asked for is never a mismatch. |
| +func analyticsMismatchErr(app, requested, echoed string) error { |
| + if requested == "" || requested == echoed { |
| + return nil |
| + } |
| + return fmt.Errorf("the app %s was created, but the console did not confirm its analytics setting. "+ |
| + "Set it with: carlos analytics --app %s --set-count %s", app, app, requested) |
| } |
| // placementMismatchErr compares what --place asked for (requested) against |
diff --git a/apps_analytics_test.go b/apps_analytics_test.go| new file mode 100644 |
| index 000000000..a83ff0896 |
| --- /dev/null |
| +++ b/apps_analytics_test.go |
| @@ -0,0 +1,98 @@ |
| +package main |
| + |
| +// `carlos apps create --analytics/--no-analytics` (analytics on-ramp plan, |
| +// docs/superpowers/plans/2026-10-26-analytics-onramp.md, item 4): the flags |
| +// map onto the create API's "analytics" field, and the output reports what |
| +// the console echoed rather than what was asked for. |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestAppsCreateAnalyticsFlagsMapToTheAPI(t *testing.T) { |
| + for _, tc := range []struct { |
| + on, off bool |
| + want string // the request's "analytics" value; "-" = key absent |
| + bad bool |
| + }{ |
| + {false, false, "-", false}, |
| + {true, false, "edge", false}, |
| + {false, true, "off", false}, |
| + {true, true, "", true}, |
| + } { |
| + choice, err := analyticsChoice(tc.on, tc.off) |
| + if tc.bad { |
| + if err == nil || err.Error() != "choose --analytics or --no-analytics, not both" { |
| + t.Errorf("both flags: err = %v, want the both-flags refusal", err) |
| + } |
| + continue |
| + } |
| + if err != nil { |
| + t.Fatalf("analyticsChoice(%v, %v) = %v", tc.on, tc.off, err) |
| + } |
| + var got map[string]any |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + json.NewDecoder(r.Body).Decode(&got) |
| + json.NewEncoder(w).Encode(map[string]any{"account": "acct", "app": "app", |
| + "analytics": "edge", "analytics_from": "app"}) |
| + })) |
| + res, err := newTestSession(ts.URL).createAppAnalytics(context.Background(), apiAcct{Seg: "acct"}, "app", "", false, "", "", "", choice) |
| + ts.Close() |
| + if err != nil { |
| + t.Fatalf("createAppAnalytics: %v", err) |
| + } |
| + v, present := got["analytics"] |
| + if tc.want == "-" { |
| + if present { |
| + t.Errorf("no flag sent analytics=%v; want the key absent so the app follows the account", v) |
| + } |
| + } else if v != tc.want { |
| + t.Errorf("flags on=%v off=%v sent analytics=%v, want %q", tc.on, tc.off, v, tc.want) |
| + } |
| + if res.Analytics != "edge" || res.AnalyticsFrom != "app" { |
| + t.Errorf("result = %+v, want the console's echo", res) |
| + } |
| + } |
| +} |
| + |
| +func TestAppsCreateAnalyticsLine(t *testing.T) { |
| + for _, tc := range []struct { |
| + res apiCreateAppResult |
| + want string |
| + }{ |
| + {apiCreateAppResult{Analytics: "edge", AnalyticsFrom: "app"}, "analytics: on, set for this app"}, |
| + {apiCreateAppResult{Analytics: "off", AnalyticsFrom: "app"}, "analytics: off, set for this app"}, |
| + {apiCreateAppResult{Analytics: "edge", AnalyticsFrom: "account"}, "analytics: on, following the account"}, |
| + {apiCreateAppResult{Analytics: "off", AnalyticsFrom: "default"}, "analytics: off, following the account"}, |
| + {apiCreateAppResult{}, ""}, // an older console echoes nothing |
| + } { |
| + if got := analyticsLine(tc.res); got != tc.want { |
| + t.Errorf("analyticsLine(%+v) = %q, want %q", tc.res, got, tc.want) |
| + } |
| + } |
| +} |
| + |
| +func TestAppsCreateAnalyticsMismatch(t *testing.T) { |
| + for _, tc := range []struct{ requested, echoed string }{{"", ""}, {"", "edge"}, {"edge", "edge"}, {"off", "off"}} { |
| + if err := analyticsMismatchErr("shop", tc.requested, tc.echoed); err != nil { |
| + t.Errorf("requested %q, echoed %q: %v, want no error", tc.requested, tc.echoed, err) |
| + } |
| + } |
| + // An older console echoes "", and a failed write echoes the account's. |
| + for _, echoed := range []string{"", "off"} { |
| + err := analyticsMismatchErr("shop", "edge", echoed) |
| + const want = "the app shop was created, but the console did not confirm its analytics setting. " + |
| + "Set it with: carlos analytics --app shop --set-count edge" |
| + if err == nil || err.Error() != want { |
| + t.Errorf("echoed %q: err = %v, want %q", echoed, err, want) |
| + } |
| + } |
| + if err := analyticsMismatchErr("shop", "off", "edge"); err == nil || !strings.HasSuffix(err.Error(), "--set-count off") { |
| + t.Errorf("off not confirmed: %v", err) |
| + } |
| +} |
diff --git a/docs/site/cli.md b/docs/site/cli.md| index 8d5ffd699..021ef3264 100644 |
| --- a/docs/site/cli.md |
| +++ b/docs/site/cli.md |
| @@ -127,6 +127,10 @@ prints one line saying which and why: |
| carlos apps create --app hello --region uk |
| ``` |
| +`--analytics` or `--no-analytics` turns analytics on or off for the new app. |
| +Without either, the app follows the account's setting. Only an owner can |
| +choose differently from the account. |
| + |
| A name is also refused when its platform apex, `<app>.<account>.<apps |
| domain>`, is already taken: by another app's instance, even one in the Trash, |
| or by any route there at all. The new app would otherwise never get an address |
| @@ -1425,7 +1429,8 @@ Records the edge filed before causes were recorded are grouped under |
| Page views, daily visitors, bytes served, top pages, top referers and named |
| events, counted at the edge as it serves your app: no JavaScript, no cookie, |
| -no stored IP. Off until you turn it on, for one app or for the whole account. |
| +no stored IP. New accounts start with analytics on. Turn it on or off for one |
| +app or for the whole account. |
| ```sh |
| carlos analytics --app hello --set-count edge |
diff --git a/docs/superpowers/notes/census-proposal-analytics-onramp.md b/docs/superpowers/notes/census-proposal-analytics-onramp.md| new file mode 100644 |
| index 000000000..dd3ca7ba0 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-analytics-onramp.md |
| @@ -0,0 +1,19 @@ |
| +# Census approval: analytics-onramp |
| + |
| +Ruling `census-ruling-analytics-onramp`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/telemetry/telemetry.go` `Resolve` | body | unchanged (2) | An empty app name now returns the account setting alone instead of reading apps/<sqid>//telemetry.json; same object family (the account telemetry object), no new root read. | |
| + |
| +Envelopes re-pinned: `.`, `internal/telemetry`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Escalate if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. An escalation goes to the census owner as a decision. |
| + |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `internal/telemetry/telemetry.go` `Resolve`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=PROPOSED-s3-change-index;identity=unchanged (the console and the agent);basis=the fold over the defaults moved into Fold, which the agent's switch pass calls over cached settings; the same two telemetry.Read calls, offsets moved |
| + |
| +Seal: `deeddee1bf22a18562acda97cc34c6d73ee0dff1825100c73fa0be4c6a3f3e7b` → `f5afdacd495705841fcc8441eaefe0efb9db7056de281bb06d1714960a5575b7`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-analytics-onramp.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/plans/2026-10-26-analytics-onramp-copy.md b/docs/superpowers/plans/2026-10-26-analytics-onramp-copy.md| new file mode 100644 |
| index 000000000..011eae691 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-10-26-analytics-onramp-copy.md |
| @@ -0,0 +1,85 @@ |
| +# Analytics on-ramp: copy deck |
| + |
| +Every new or changed user-facing string of the analytics on-ramp plan |
| +(`2026-10-26-analytics-onramp.md`). The gate is |
| +`internal/console/approved_analytics_onramp_copy_test.go` |
| +(`TestAnalyticsOnrampCopyDeckIsApprovedAndApplied`). |
| + |
| +Approved 2026-10-26 by delegation: Luna pass, round 1 |
| +(LUNA-COPY-REVIEW-ANALYTICS-ONRAMP.md, brief LUNA-COPY-BRIEF-ANALYTICS-ONRAMP.md). |
| +Luna changed 7 rows (AN-C02, C04, C06, C15, C21, C22, C40), flagged none, and |
| +left 21 alone. A round with nothing flagged ends the review (AGENTS.md, |
| +stopping rule 1). The text below is Luna's, verbatim. |
| + |
| +AN-C42 was added after round 1 and reviewed alone |
| +(LUNA-COPY-BRIEF-ANALYTICS-ONRAMP-C42.md, answer appended to the review |
| +file): Luna added one sentence, flagged nothing. |
| + |
| +The rules (the same as the console navigation deck, |
| +`2026-10-25-console-ux-nav-copy.md`): |
| + |
| +- One table, columns `| id | where | old | new | checked by | status |`. A row |
| + is one line. |
| +- `where` is a path relative to `internal/console/`, then a short location |
| + note in parentheses. The gate searches the file named by the first token. |
| +- `new` is the approved text, used verbatim by the task that writes it. It is |
| + `(removed)` for a string that goes. |
| +- `checked by` is `gate` (a plain string the gate finds literally in the |
| + file, once the owning task lists its id in `onrampCopyBuilt`) or the name of |
| + the owning task's test, which the gate only checks exists. |
| +- `status` is `pending`, then `approved` or `removed`. No pending row may |
| + reach code or a template. |
| +- No em dashes in `new`. A full stop and a new sentence instead. |
| +- Human text only. Error fragments, diagnostics, JSON keys and URLs are not |
| + rows. |
| +- Placeholders: `<app>` an app's name, `<state>` the word on or off, |
| + `<count>` the word edge or off. `<a>` marks where a link starts and ends. |
| +- Strings that stay as they are are not rows: the Analytics tab's tables, |
| + chart and range toolbar, and the settings forms' own labels. |
| + |
| +What the strings are for: |
| + |
| +- The Analytics tab, when analytics is off for the app, stops pointing at |
| + Settings. It says what is counted and, for an owner, offers one button that |
| + turns analytics on for this app and comes back to the tab. A member sees a |
| + line saying an owner can turn it on. The empty tables and chart are hidden |
| + while it is off. |
| +- The Create an app form gets a checkbox, ticked when the account's default |
| + is on. Choosing differently from the account gives the new app its own |
| + setting. An owner also gets a button that makes the current choice the |
| + account default, which covers every app in the account without its own |
| + setting. A member sees the checkbox but cannot change it. |
| +- New accounts start with analytics on. Existing accounts are unchanged. |
| +- `carlos apps create` gains `--analytics` and `--no-analytics`. |
| + |
| +| id | where | old | new | checked by | status | |
| +|---|---|---|---|---|---| |
| +| AN-C01 | templates/app_analytics.html (analytics off, first sentence, bold) | Analytics is off for this app (from the account). | Analytics is off for this app. | gate | approved | |
| +| AN-C02 | templates/app_analytics.html (analytics off, what is counted) | 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. | When analytics is on, the edge counts HTML page views and daily visitors. No JavaScript, no cookie, no stored IP. | gate | approved | |
| +| AN-C03 | templates/app_analytics.html (analytics off, owner's button) | (new) | Turn on analytics | gate | approved | |
| +| AN-C04 | templates/app_analytics.html (analytics off, what a member sees instead of the button) | (new) | An account owner can turn on analytics. | gate | approved | |
| +| AN-C05 | templates/app_analytics.html (analytics off, the pointer to Settings; was NAV-C44) | Turn it on for this app in `<a>`Settings, under Errors and analytics`</a>`, or for the whole account in the account's `<a>`Settings`</a>`. | (removed) | TestAnalyticsTabOffStateOwner | removed | |
| +| AN-C06 | analyticsview.go (flash on the Analytics tab after Turn on analytics) | (new) | Analytics is on for this app. Page views appear here as they are counted. | gate | approved | |
| +| AN-C10 | templates/app_new.html (checkbox label) | (new) | Count page views and visitors with analytics | gate | approved | |
| +| AN-C11 | templates/app_new.html (under the checkbox) | (new) | No JavaScript, no cookie, no stored IP. | gate | approved | |
| +| AN-C12 | templates/app_new.html (under the checkbox, the account's default is on) | (new) | This account's default is on. | gate | approved | |
| +| AN-C13 | templates/app_new.html (under the checkbox, the account's default is off) | (new) | This account's default is off. | gate | approved | |
| +| AN-C14 | templates/app_new.html (owner's button under the checkbox) | (new) | Make this the account default | gate | approved | |
| +| AN-C15 | templates/app_new.html (owner's note beside the button) | (new) | The account default also applies to every existing app without its own setting. | gate | approved | |
| +| AN-C16 | templates/app_new.html (member's note; the checkbox is shown but cannot be changed) | (new) | Only an owner can change this. | gate | approved | |
| +| AN-C17 | analyticsonramp.go (flash: a member's form chose differently from the account default) | (new) | Only an owner can change analytics for a new app. Nothing was created. | gate | approved | |
| +| AN-C18 | analyticsonramp.go (flash: the app was created but its analytics setting failed to save) | (new) | Created app `<app>`, but its analytics setting could not be saved. Set it in Settings, under Errors and analytics. | TestNewAppAnalyticsWriteFailureSaysSo | approved | |
| +| AN-C19 | analyticsview.go (flash on the create form after Make this the account default, on) | (new) | Analytics is now on for every app in this account without its own setting. | gate | approved | |
| +| AN-C20 | analyticsview.go (flash on the create form after Make this the account default, off) | (new) | Analytics is now off for every app in this account without its own setting. | gate | approved | |
| +| AN-C21 | templates/account_settings.html (Analytics, last sentence of the help) | Whether that needs consent where your visitors are is your call, which is why it is off until you turn it on. | Whether that needs consent where your visitors are is your call. New accounts start with analytics on. | gate | approved | |
| +| AN-C22 | templates/app_settings.html (Errors and analytics, last sentence of the Analytics help) | Whether that needs consent where your visitors are is your call, which is why it is off until you turn it on. | Whether that needs consent where your visitors are is your call. New accounts start with analytics on. | gate | approved | |
| +| AN-C30 | ../../apps.go (`carlos apps create` flag help, `--analytics`) | (new) | turn analytics on for the new app (default: follow the account) | gate | approved | |
| +| AN-C31 | ../../apps.go (`carlos apps create` flag help, `--no-analytics`) | (new) | turn analytics off for the new app (default: follow the account) | gate | approved | |
| +| AN-C32 | ../../apps.go (`carlos apps create` output, the app has its own setting) | (new) | analytics: `<state>`, set for this app | TestAppsCreateAnalyticsLine | approved | |
| +| AN-C33 | ../../apps.go (`carlos apps create` output, the app follows the account) | (new) | analytics: `<state>`, following the account | TestAppsCreateAnalyticsLine | approved | |
| +| AN-C34 | ../../apps.go (`carlos apps create` error, the console did not confirm the choice) | (new) | the app `<app>` was created, but the console did not confirm its analytics setting. Set it with: carlos analytics --app `<app>` --set-count `<count>` | TestAppsCreateAnalyticsMismatch | approved | |
| +| AN-C35 | ../../apps.go (`carlos apps create` error, both flags given) | (new) | choose --analytics or --no-analytics, not both | gate | approved | |
| +| AN-C36 | analyticsonramp.go (`carlos apps create` refusal printed to a member) | (new) | only an owner can choose analytics for a new app. Leave out --analytics and --no-analytics to follow the account | gate | approved | |
| +| AN-C40 | ../../docs/site/cli.md (carlos analytics, first paragraph) | Off until you turn it on, for one app or for the whole account. | New accounts start with analytics on. Turn it on or off for one app or for the whole account. | gate | approved | |
| +| AN-C41 | ../../docs/site/cli.md (carlos apps, after the `--region` example) | (new) | `--analytics` or `--no-analytics` turns analytics on or off for the new app. Without either, the app follows the account's setting. Only an owner can choose differently from the account. | gate | approved | |
| +| AN-C42 | ../../analytics_cmd.go (`carlos analytics --help`, first paragraph; found after round 1, reviewed alone in a second Luna pass) | Off until you turn it on. | New accounts start with analytics on. Existing accounts keep their current setting. | gate | approved | |
diff --git a/docs/superpowers/plans/2026-10-26-analytics-onramp.md b/docs/superpowers/plans/2026-10-26-analytics-onramp.md| new file mode 100644 |
| index 000000000..030fd7648 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-10-26-analytics-onramp.md |
| @@ -0,0 +1,24 @@ |
| +# Analytics on-ramp |
| + |
| +Paul, 2026-10-26, approved in chat ("Yes, go ahead"): |
| + |
| +1. The Analytics tab, when analytics is off, stops pointing at Settings. It shows one short line on what is counted (no JavaScript, no cookie, no stored IP, HTML page views only) and, for owners, a **Turn on analytics** button that saves the app's analytics setting through the existing POST door and redirects back to the Analytics tab. Members see a line saying an owner can turn it on. The empty table, chart and "Nothing yet" sections are hidden while it is off. |
| +2. Create app (console form at `/a/{sqid}/apps/new`) gets an analytics checkbox, ticked from the account's effective default. Choosing differently from the account default gives the new app its own setting; matching it writes nothing (the app follows the account). Under the checkbox, owners get a link/control to make the current choice the account default (the existing account-level analytics setting). |
| +3. New accounts default to analytics **on** (write the account-level setting on at account creation). Existing accounts are unchanged. |
| +4. CLI: `carlos apps create` gains `--analytics` / `--no-analytics` (no flag = follow the account default), through the existing create API. |
| + |
| +## Constraints |
| + |
| +- Reuse the existing settings doors and storage (`telemetry` package: account key, app key, Fold/Resolve; `analyticsview.go` POST handlers). No new storage format. |
| +- Gate order unchanged; only owners can change analytics (as today: `role != RoleOwner` refusal in the setting handlers). The create-app path writes the app's setting only for a user allowed to create apps; check whether non-owners can create apps and, if they can, whether they may set analytics: refuse up front rather than silently ignore. |
| +- The console's per-app frame cache and perf walk exist on main after console-perf-quick-wins merges; this branch is cut from main before that merge, so keep changes to the analytics template, create-app form/handler, account creation and CLI create, and expect a later merge. |
| +- Every new or changed user-facing string is listed in `docs/superpowers/plans/2026-10-26-analytics-onramp-copy.md` and reviewed by a Luna pass (`codex exec -m gpt-5.6-luna`, house rules: no em dashes, plain, short, human text only) before templates/CLI carry it. |
| +- Targeted tests with `-run` only; gofmt, vet, darwin and windows builds; commit trailer `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`; no tenant names. |
| +- Census: run `make census-card` at the end; decisions go to Paul. |
| + |
| +## Tasks |
| + |
| +1. Copy record + Luna pass. |
| +2. Analytics tab off-state with the Turn on button (owner) / member line; POST redirects back to the tab (`back` parameter or equivalent) on success and refusal; tests for owner, member, and that the page shows data sections only when on. |
| +3. Create app checkbox + account-default link; new-account default on; CLI flags; tests (form default follows account; differing choice writes app setting; matching writes nothing; new account starts on; CLI flags map to the API). |
| +4. Final gate + census card. |
diff --git a/docs/superpowers/plans/LUNA-COPY-BRIEF-ANALYTICS-ONRAMP-C42.md b/docs/superpowers/plans/LUNA-COPY-BRIEF-ANALYTICS-ONRAMP-C42.md| new file mode 100644 |
| index 000000000..48d25e139 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/LUNA-COPY-BRIEF-ANALYTICS-ONRAMP-C42.md |
| @@ -0,0 +1,24 @@ |
| +# Copy review brief: analytics on-ramp, AN-C42 alone (delegated by Paul, 2026-10-26) |
| + |
| +Paul delegated copy review for plan copy to you. You are the copy editor; your |
| +edit will be applied as approved copy. This is a one-row pass: the rest of the |
| +deck was reviewed in round 1 (`LUNA-COPY-REVIEW-ANALYTICS-ONRAMP.md`). |
| + |
| +Read `docs/superpowers/plans/LUNA-COPY-BRIEF-ANALYTICS-ONRAMP.md` for what the |
| +change is and the house rules; all of them bind here. Then read row AN-C42 in |
| +`docs/superpowers/plans/2026-10-26-analytics-onramp-copy.md`, and the text |
| +around it in `analytics_cmd.go` (`analyticsUsage`, the `carlos analytics |
| +--help` text). |
| + |
| +AN-C42 replaces "Off until you turn it on." in that help text, which is no |
| +longer true now that new accounts start with analytics on. The drafted text is |
| +AN-C40's approved first sentence. It must stay true for existing accounts too |
| +(they keep whatever they had, which for most is off). It may say how to turn |
| +analytics on or off with this command (`--set-count edge` or `--set-count off`) |
| +if that helps; keep the flag exactly. |
| + |
| +## Output |
| + |
| +1. If you change it: a one-row table `ID | current | new | why`. If not, the |
| + line "AN-C42: KEEP". |
| +2. Flags: `AN-C42 | problem`, or "Flagged rows: none." |
diff --git a/docs/superpowers/plans/LUNA-COPY-BRIEF-ANALYTICS-ONRAMP.md b/docs/superpowers/plans/LUNA-COPY-BRIEF-ANALYTICS-ONRAMP.md| new file mode 100644 |
| index 000000000..ed517c86d |
| --- /dev/null |
| +++ b/docs/superpowers/plans/LUNA-COPY-BRIEF-ANALYTICS-ONRAMP.md |
| @@ -0,0 +1,64 @@ |
| +# Copy review brief: analytics on-ramp deck (delegated by Paul, 2026-10-26) |
| + |
| +Paul delegated copy review for plan copy to you. You are the copy editor; your |
| +edits will be applied as approved copy. This is round 1 of at most three; a |
| +round with no fact problem ends the review. |
| + |
| +Read `docs/superpowers/plans/2026-10-26-analytics-onramp-copy.md` (28 rows, |
| +ids AN-C01 to AN-C41, with gaps). The `new` column is yours to change. The |
| +ids, `where` and `checked by` columns are fixed. The deck's own "What the |
| +strings are for" section says what each group of strings does. The plan is |
| +`docs/superpowers/plans/2026-10-26-analytics-onramp.md`. |
| + |
| +## What the change is |
| + |
| +CARLOS is a hosting platform. Its console is the web app people use to manage |
| +their apps; `carlos` is its command line. Analytics counts page views at the |
| +edge (the server in front of the app), with no JavaScript, no cookie and no |
| +stored IP. Until now it was off unless an owner turned it on in Settings. |
| + |
| +- The app's Analytics tab, when analytics is off, gets a one-click |
| + "Turn on analytics" button for owners. Members (non-owners) see a line |
| + saying an owner can turn it on. |
| +- The Create an app form gets an analytics checkbox, ticked from the |
| + account's default. Owners can also make their choice the account default. |
| + The account default applies to every app without its own setting, existing |
| + apps included, so the note beside that button must say so. |
| +- New accounts start with analytics on. Existing accounts keep what they had. |
| + Two settings pages and the CLI docs said "off until you turn it on", which |
| + is no longer true for new accounts. |
| +- `carlos apps create` gets `--analytics` and `--no-analytics`. |
| + |
| +## House rules (Paul's, all binding) |
| + |
| +- No em dashes, ever. Use a full stop and a new sentence. The `old` column may |
| + hold old text; do not copy its punctuation, and do not edit `old`. |
| +- Plain words. No jargon a reader would not know. Short. Say what to do next. |
| +- Neutral names only (shop, example.com). Never a tenant's name. |
| +- Human text only. If a string is not human text (a log line, a route |
| + pattern, a header name, a JSON key, an error fragment), flag it rather than |
| + edit it. |
| +- Keep every placeholder exactly (`<app>`, `<state>`, `<count>`), every `<a>` |
| + and `</a>` boundary where it is, and every command and flag exactly |
| + (`carlos analytics --app <app> --set-count <count>`, `--analytics`, |
| + `--no-analytics`). |
| +- CLI flag help (AN-C30, AN-C31) and CLI errors (AN-C34 to AN-C36) start with |
| + a lower-case letter, as Go's flag and error conventions want. Page text |
| + starts with a capital. |
| +- Button labels (AN-C03, AN-C14) stay short verb phrases. |
| +- Do not change meaning or the facts a string states. If a fact looks wrong or |
| + conflicts with another row, flag it, do not rewrite it. In particular the |
| + facts in AN-C15 (the account default covers existing apps without their own |
| + setting), AN-C17 (nothing was created) and AN-C21/AN-C22/AN-C40 (new |
| + accounts start with it on) are true and must stay. |
| +- A row whose `new` is `(removed)` is a string that goes. Leave it alone. |
| + |
| +## Output |
| + |
| +Markdown, in this shape: |
| + |
| +1. A table of changes only: `ID | current | new | why` (a few words in why). |
| + Leave unchanged rows out. "current" is the deck's `new` text. |
| +2. A list of flagged rows: `id | problem` (fact conflict, not human text, |
| + placeholder unclear), or "Flagged rows: none." |
| +3. One line of counts: how many rows you changed, flagged and left alone. |
diff --git a/docs/superpowers/plans/LUNA-COPY-REVIEW-ANALYTICS-ONRAMP.md b/docs/superpowers/plans/LUNA-COPY-REVIEW-ANALYTICS-ONRAMP.md| new file mode 100644 |
| index 000000000..f0a28cd2b |
| --- /dev/null |
| +++ b/docs/superpowers/plans/LUNA-COPY-REVIEW-ANALYTICS-ONRAMP.md |
| @@ -0,0 +1,22 @@ |
| +| ID | current | new | why | |
| +|---|---|---|---| |
| +| AN-C02 | When it is on, the edge counts HTML page views and daily visitors. No JavaScript, no cookie, no stored IP. | When analytics is on, the edge counts HTML page views and daily visitors. No JavaScript, no cookie, no stored IP. | Clearer subject | |
| +| AN-C04 | An owner of this account can turn it on. | An account owner can turn on analytics. | Clearer and shorter | |
| +| AN-C06 | Analytics is on for this app. Page views show here as they are counted. | Analytics is on for this app. Page views appear here as they are counted. | More natural wording | |
| +| AN-C15 | The account default also covers every existing app without its own setting. | The account default also applies to every existing app without its own setting. | Plainer wording | |
| +| AN-C21 | Whether that needs consent where your visitors are is your call. New accounts start with it on. | Whether that needs consent where your visitors are is your call. New accounts start with analytics on. | Removes unclear “it” | |
| +| AN-C22 | Whether that needs consent where your visitors are is your call. New accounts start with it on. | Whether that needs consent where your visitors are is your call. New accounts start with analytics on. | Removes unclear “it” | |
| +| AN-C40 | New accounts start with it on. Turn it on or off for one app or for the whole account. | New accounts start with analytics on. Turn it on or off for one app or for the whole account. | Removes unclear “it” | |
| + |
| +Flagged rows: none. |
| + |
| +7 rows changed, 0 flagged, 21 left alone. |
| +## Fix round: AN-C42 alone (brief: LUNA-COPY-BRIEF-ANALYTICS-ONRAMP-C42.md) |
| + |
| +| ID | current | new | why | |
| +|---|---|---|---| |
| +| AN-C42 | New accounts start with analytics on. | New accounts start with analytics on. Existing accounts keep their current setting. | Clarifies the existing-account behavior. | |
| + |
| +Flagged rows: none. |
| + |
| +Changed: 1; flagged: 0; left alone: 0. |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-analytics-onramp.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-analytics-onramp.md| new file mode 100644 |
| index 000000000..85b83d5ee |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-analytics-onramp.md |
| @@ -0,0 +1,40 @@ |
| +# Review brief: branch analytics-onramp, round 1 of 3 |
| + |
| +Repo carlos/platform, branch `analytics-onramp`, commit 9f626eaf (full sha in the reviewer's prompt). |
| +Under review: the diff `origin/main...9f626eaf` (the branch merged origin/main at c0631f46). |
| +Authorities: the plan `docs/superpowers/plans/2026-10-26-analytics-onramp.md` (Paul approved the four items in chat, 2026-10-26); AGENTS.md on main (Stopping rules; census section, C2). |
| + |
| +You are an independent reviewer. Read the plan, then the code, and check every claim against the code. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- Paul, 2026-10-26: Analytics tab off-state with a Turn on button for owners; Create app asks about analytics, defaulting from the account; a way to make the choice the account default; new accounts start with analytics on (existing accounts unchanged); `carlos apps create --analytics/--no-analytics`. |
| +- Builder rulings already accepted by the controller: members can create apps but cannot set analytics (checkbox disabled; a hand-sent different choice is refused before the name is claimed, browser and CLI); only the console's account creation starts analytics on; counted numbers still show when analytics is off; Create app makes one S3 read for the checkbox default (`calls 1` record). |
| +- Copy is Luna-approved; do not review wording except for factual errors. |
| + |
| +## What to check |
| + |
| +1. Authorization: only owners change analytics (app or account); gate order unchanged on the new/changed doors; refusals happen before any write (including the app-name claim on create). |
| +2. The create flow: the checkbox default equals the account's effective setting; a matching choice writes nothing; a differing choice writes the app setting; a failure to write the setting after create leaves the app and tells the user. |
| +3. `telemetry.Resolve` with an empty app name returns the account setting alone and every caller still gets the right answer (account settings page, analytics view, analytics POST handlers, create). |
| +4. New accounts default on, existing accounts unchanged; CLI flags map to the API (no flag = follow the account). |
| +5. The per-app frame cache (internal/console/appframe.go) is still cleared by the create and analytics doors. |
| +6. Census (AGENTS.md on main): answer APPROVE or ESCALATE for the `Resolve` body unit and the `.` and `internal/telemetry` envelope re-pins on `docs/superpowers/notes/census-proposal-analytics-onramp.md` (card question: does any root read now open/run/query/follow a path or input a tenant, app or box agent can create, write or name?). You decide every class. |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. |
| +- **P3**: clarity or polish. Goes on a follow-up list; never a reason for another round. |
| + |
| +A P1 states its failure scenario and the evidence (file:line). Do not raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3. Each gives the section, the problem, the evidence (file:line, verified), the failure scenario, a concrete fix and the invariant or trust boundary it breaks. Then the census verdict lines. End with exactly one verdict: |
| + |
| +- **READY**: no P1 and no P2. |
| +- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another round. |
| +- **NOT READY**: one or more P1s, listed. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites. |
diff --git a/internal/console/analytics_onramp_test.go b/internal/console/analytics_onramp_test.go| new file mode 100644 |
| index 000000000..523e17858 |
| --- /dev/null |
| +++ b/internal/console/analytics_onramp_test.go |
| @@ -0,0 +1,500 @@ |
| +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" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| + "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 or chart (the range picker stays). |
| + for _, gone := range []string{"settings/errors-analytics", "Turn it on for this app in", onrampMemberOff, |
| + `role="img" aria-label="Page views"`} { |
| + 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. |
| +// Counted yesterday, switched off, nothing today: the default tab still has |
| +// the range picker, and the wider window shows the counts. |
| +func TestAnalyticsTabOffStateKeepsRangePickerForOlderData(t *testing.T) { |
| + fx, _ := instanceFixture(t, "code-onramp-tab-older") |
| + seedAnalytics(t, fx, seedTime().Add(-24*time.Hour)) |
| + fx.setUser("paul@keymail.dev") |
| + c := newBrowser(t) |
| + signUp(t, fx, c, "code-onramp-tab-older-browser") |
| + _, _, body := get(t, c, fx.u("/apps/titogo/analytics")) |
| + for _, want := range []string{onrampOffLead, onrampTurnOn, `<form method="get" class="toolbar">`, `<option value="7d">`} { |
| + if !strings.Contains(body, want) { |
| + t.Errorf("off, data only before today: default tab missing %q", want) |
| + } |
| + } |
| + for _, gone := range onrampDataMarkers { |
| + if strings.Contains(body, gone) { |
| + t.Errorf("off, nothing today: default tab shows the data section %q", gone) |
| + } |
| + } |
| + _, _, body = get(t, c, fx.u("/apps/titogo/analytics?range=7d")) |
| + for _, want := range []string{onrampOffLead, `<form method="get" class="toolbar">`, `<option value="7d" selected>`, |
| + "<th>Page views</th>", "<td>5</td>", "/pricing"} { |
| + if !strings.Contains(body, want) { |
| + t.Errorf("?range=7d with older data: missing %q", want) |
| + } |
| + } |
| +} |
| + |
| +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") |
| + } |
| +} |
| + |
| +// setAccountAnalytics writes the fixture account's analytics default. |
| +func setAccountAnalytics(t *testing.T, fx *consoleFixture, count string) { |
| + t.Helper() |
| + if err := telemetry.Update(context.Background(), fx.rel, telemetry.AccountKey(fx.sqid), func(st *telemetry.Settings) { |
| + mergeAnalytics(st, count, "") |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// appAnalyticsObject reports whether the app has its own telemetry object. |
| +func appAnalyticsObject(t *testing.T, fx *consoleFixture, app string) bool { |
| + t.Helper() |
| + st, etag, err := telemetry.Read(context.Background(), fx.rel, telemetry.AppKey(fx.sqid, app)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return etag != "" || st.Analytics != nil |
| +} |
| + |
| +const ( |
| + onrampCheckbox = `<input type="checkbox" name="count" value="edge"` |
| + onrampHiddenOff = `<input type="hidden" name="count" value="off">` |
| + onrampMakeDefault = "Make this the account default" |
| + onrampDefaultOn = "This account's default is on." |
| + onrampDefaultOff = "This account's default is off." |
| + onrampOnlyOwnerNote = "Only an owner can change this." |
| +) |
| + |
| +func TestNewAppFormAnalyticsFollowsAccount(t *testing.T) { |
| + fx, _ := instanceFixture(t, "code-onramp-form") |
| + fx.setUser("paul@keymail.dev") |
| + c := newBrowser(t) |
| + signUp(t, fx, c, "code-onramp-form-owner") |
| + |
| + checkbox := func(body string) string { |
| + at := strings.Index(body, onrampCheckbox) |
| + if at < 0 { |
| + t.Fatalf("the create form has no analytics checkbox:\n%s", body) |
| + } |
| + tag, _, _ := strings.Cut(body[at:], ">") |
| + return tag |
| + } |
| + // No account setting: the built-in default, off, and the box unticked. |
| + _, _, body := get(t, c, fx.u("/apps/new")) |
| + if tag := checkbox(body); strings.Contains(tag, "checked") || strings.Contains(tag, "disabled") { |
| + t.Errorf("default off: owner's checkbox = %s, want unticked and enabled", tag) |
| + } |
| + for _, want := range []string{onrampDefaultOff, onrampHiddenOff, onrampMakeDefault, |
| + `formaction="/a/` + fx.sqid + `/analytics/setting"`, `name="back" value="new-app"`, |
| + "The account default also applies to every existing app without its own setting."} { |
| + if !strings.Contains(body, want) { |
| + t.Errorf("owner's create form missing %q", want) |
| + } |
| + } |
| + // Enter in the name field presses the first submit button: Create app. |
| + if strings.Index(body, ">Create app</button>") > strings.Index(body, onrampMakeDefault) { |
| + t.Error("Make this the account default comes before Create app, so Enter would press it") |
| + } |
| + |
| + setAccountAnalytics(t, fx, telemetry.CountEdge) |
| + _, _, body = get(t, c, fx.u("/apps/new")) |
| + if tag := checkbox(body); !strings.Contains(tag, "checked") { |
| + t.Errorf("default on: owner's checkbox = %s, want ticked", tag) |
| + } |
| + if !strings.Contains(body, onrampDefaultOn) { |
| + t.Errorf("default on: form missing %q", onrampDefaultOn) |
| + } |
| + |
| + // A member sees the account's choice and cannot change it. |
| + fx.setUser("alice@keymail.dev") |
| + m := newBrowser(t) |
| + signUp(t, fx, m, "code-onramp-form-member") |
| + _, _, body = get(t, m, fx.u("/apps/new")) |
| + if tag := checkbox(body); !strings.Contains(tag, "checked") || !strings.Contains(tag, "disabled") { |
| + t.Errorf("member's checkbox = %s, want ticked and disabled", tag) |
| + } |
| + if !strings.Contains(body, onrampOnlyOwnerNote) { |
| + t.Errorf("member's form missing %q", onrampOnlyOwnerNote) |
| + } |
| + for _, gone := range []string{onrampHiddenOff, onrampMakeDefault, "formaction="} { |
| + if strings.Contains(body, gone) { |
| + t.Errorf("member's form shows %q", gone) |
| + } |
| + } |
| +} |
| + |
| +func TestNewAppAnalyticsChoice(t *testing.T) { |
| + fx, _ := instanceFixture(t, "code-onramp-create") |
| + fx.setUser("paul@keymail.dev") |
| + c := newBrowser(t) |
| + signUp(t, fx, c, "code-onramp-create-owner") |
| + csrf := sessionToken(t, fx, c) |
| + create := func(c *http.Client, csrf, name string, count ...string) (int, string) { |
| + form := url.Values{"csrf": {csrf}, "name": {name}} |
| + for _, v := range count { |
| + form.Add("count", v) |
| + } |
| + status, loc, _ := postForm(t, c, fx.u("/apps/new"), form) |
| + return status, loc |
| + } |
| + created := func(name string) bool { |
| + has, err := fx.st.HasAppIn(OpsAccountID, name) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return has |
| + } |
| + |
| + // The account default is off (no setting). Ticked: the app's own edge. |
| + if st, loc := create(c, csrf, "shop-on", "edge", "off"); st != http.StatusSeeOther || loc != fx.path("/apps/shop-on") { |
| + t.Fatalf("owner create ticked = %d -> %q", st, loc) |
| + } |
| + if res, _ := telemetry.Resolve(context.Background(), fx.rel, fx.sqid, "shop-on"); res.Count != telemetry.CountEdge || res.CountFrom != "app" { |
| + t.Errorf("ticked over an off default: %+v, want edge from the app", res) |
| + } |
| + // Unticked matches the default: nothing written, the app follows. |
| + if st, _ := create(c, csrf, "shop-off", "off"); st != http.StatusSeeOther || !created("shop-off") { |
| + t.Fatalf("owner create unticked = %d", st) |
| + } |
| + if appAnalyticsObject(t, fx, "shop-off") { |
| + t.Error("a choice matching the account default wrote an app setting") |
| + } |
| + |
| + // Default on: unticked gives the app its own off; ticked writes nothing. |
| + setAccountAnalytics(t, fx, telemetry.CountEdge) |
| + create(c, csrf, "shop-quiet", "off") |
| + if res, _ := telemetry.Resolve(context.Background(), fx.rel, fx.sqid, "shop-quiet"); res.Count != telemetry.CountOff || res.CountFrom != "app" { |
| + t.Errorf("unticked over an on default: %+v, want off from the app", res) |
| + } |
| + create(c, csrf, "shop-follow", "edge", "off") |
| + if !created("shop-follow") || appAnalyticsObject(t, fx, "shop-follow") { |
| + t.Error("ticked over an on default wrote an app setting, or created nothing") |
| + } |
| + |
| + // A member: no field (the disabled box) or the account's own choice |
| + // creates and writes nothing; a different choice is refused up front. |
| + fx.setUser("alice@keymail.dev") |
| + m := newBrowser(t) |
| + signUp(t, fx, m, "code-onramp-create-member") |
| + mcsrf := sessionToken(t, fx, m) |
| + for _, tc := range []struct { |
| + name string |
| + count []string |
| + }{{"member-plain", nil}, {"member-same", []string{"edge"}}} { |
| + if st, loc := create(m, mcsrf, tc.name, tc.count...); st != http.StatusSeeOther || loc != fx.path("/apps/"+tc.name) { |
| + t.Fatalf("member create %s = %d -> %q", tc.name, st, loc) |
| + } |
| + if appAnalyticsObject(t, fx, tc.name) { |
| + t.Errorf("member create %s wrote an app setting", tc.name) |
| + } |
| + } |
| + st, loc := create(m, mcsrf, "member-other", "off") |
| + if st != http.StatusSeeOther || loc != fx.path("/apps/new") { |
| + t.Fatalf("member create with a different choice = %d -> %q, want 303 back to the form", st, loc) |
| + } |
| + if created("member-other") { |
| + t.Fatal("a member's different analytics choice still created the app") |
| + } |
| + if _, _, body := get(t, m, fx.ts.URL+loc); !strings.Contains(body, newAppAnalyticsNotOwnerFlash) { |
| + t.Errorf("the form does not show %q", newAppAnalyticsNotOwnerFlash) |
| + } |
| +} |
| + |
| +func TestNewAppMakeAccountDefault(t *testing.T) { |
| + fx, _ := instanceFixture(t, "code-onramp-default") |
| + fx.setUser("paul@keymail.dev") |
| + c := newBrowser(t) |
| + signUp(t, fx, c, "code-onramp-default-owner") |
| + for _, tc := range []struct { |
| + count []string |
| + want string |
| + flash string |
| + }{ |
| + {[]string{"edge", "off"}, telemetry.CountEdge, analyticsAccountDefaultOnFlash}, |
| + {[]string{"off"}, telemetry.CountOff, analyticsAccountDefaultOffFlash}, |
| + } { |
| + // The whole create form, posted to the account door by the button's |
| + // formaction: name and region ride along and are ignored. |
| + form := url.Values{"csrf": {sessionToken(t, fx, c)}, "name": {"shop"}, "count": tc.count, "back": {"new-app"}} |
| + status, loc, _ := postForm(t, c, fx.u("/analytics/setting"), form) |
| + if status != http.StatusSeeOther || loc != fx.path("/apps/new") { |
| + t.Fatalf("Make this the account default = %d -> %q, want 303 to the form", status, loc) |
| + } |
| + def, err := fx.srv.accountAnalyticsDefault(context.Background(), fx.sqid) |
| + if err != nil || def.Count != tc.want || def.CountFrom != "account" { |
| + t.Errorf("account default = %+v %v, want %s from the account", def, err, tc.want) |
| + } |
| + if _, _, body := get(t, c, fx.ts.URL+loc); !strings.Contains(body, tc.flash) { |
| + t.Errorf("the form does not show %q", tc.flash) |
| + } |
| + } |
| + if has, _ := fx.st.HasAppIn(OpsAccountID, "shop"); has { |
| + t.Error("Make this the account default created the app") |
| + } |
| +} |
| + |
| +func TestNewAppAnalyticsWriteFailureSaysSo(t *testing.T) { |
| + fx, _ := instanceFixture(t, "code-onramp-fail") |
| + fx.setUser("paul@keymail.dev") |
| + c := newBrowser(t) |
| + signUp(t, fx, c, "code-onramp-fail-owner") |
| + fx.srv.cfg.Releases = &hookStore{Store: fx.rel, failPut: map[string]int{telemetry.AppKey(fx.sqid, "shop"): -1}} |
| + form := url.Values{"csrf": {sessionToken(t, fx, c)}, "name": {"shop"}, "count": {"edge", "off"}} |
| + status, loc, _ := postForm(t, c, fx.u("/apps/new"), form) |
| + if status != http.StatusSeeOther || loc != fx.path("/apps/shop") { |
| + t.Fatalf("create = %d -> %q, want the app created anyway", status, loc) |
| + } |
| + want := "Created app shop, but its analytics setting could not be saved. Set it in Settings, under Errors and analytics." |
| + if _, _, body := get(t, c, fx.ts.URL+loc); !strings.Contains(body, want) { |
| + t.Errorf("the app page does not say %q", want) |
| + } |
| + if res, _ := telemetry.Resolve(context.Background(), fx.rel, fx.sqid, "shop"); res.CountFrom == "app" { |
| + t.Errorf("the failed write left an app setting: %+v", res) |
| + } |
| +} |
| + |
| +func TestNewAccountStartsWithAnalyticsOn(t *testing.T) { |
| + fx, _ := instanceFixture(t, "code-onramp-account") |
| + fx.setUser("newcomer@keymail.dev") |
| + c := newBrowser(t) |
| + signUp(t, fx, c, "code-onramp-account-newcomer") // no membership: landing mints one |
| + accts, err := fx.st.AccountsFor("newcomer@keymail.dev") |
| + if err != nil || len(accts) != 1 { |
| + t.Fatalf("newcomer's accounts = %v %v, want the one minted", accts, err) |
| + } |
| + st, _, err := telemetry.Read(context.Background(), fx.rel, telemetry.AccountKey(accts[0].Sqid)) |
| + if err != nil || st.Analytics == nil || st.Analytics.Count != telemetry.CountEdge || st.Analytics.Door != "" { |
| + t.Fatalf("new account's telemetry = %+v %v, want count edge and nothing else", st.Analytics, err) |
| + } |
| + // An account that already existed is unchanged: no object written. |
| + if st, etag, _ := telemetry.Read(context.Background(), fx.rel, telemetry.AccountKey(fx.sqid)); etag != "" || st.Analytics != nil { |
| + t.Errorf("the existing account gained an analytics setting: %+v", st.Analytics) |
| + } |
| +} |
| + |
| +// failTelemetryStore refuses every write of an account's telemetry object. |
| +type failTelemetryStore struct{ release.Store } |
| + |
| +func (f failTelemetryStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + if strings.HasPrefix(key, "accounts/") && strings.HasSuffix(key, "/telemetry.json") { |
| + return "", errors.New("telemetry put refused") |
| + } |
| + return f.Store.Put(ctx, key, body, ifMatch) |
| +} |
| + |
| +// A new account whose analytics setting cannot be written is not reported as |
| +// created: the same failure answer as any other post-manifest failure, and no |
| +// membership is published. Existing accounts are untouched. |
| +func TestNewAccountFailsWhenAnalyticsCannotBeStarted(t *testing.T) { |
| + fx, _ := instanceFixture(t, "code-onramp-account-fail") |
| + fx.setUser("paul@keymail.dev") |
| + c := newBrowser(t) |
| + signUp(t, fx, c, "code-onramp-account-fail-owner") |
| + before, err := fx.st.AccountsFor("paul@keymail.dev") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fx.srv.cfg.Releases = failTelemetryStore{fx.rel} |
| + form := url.Values{"csrf": {sessionToken(t, fx, c)}, "name": {"second"}} |
| + status, loc, _ := postForm(t, c, fx.ts.URL+"/accounts/new", form) |
| + if status != http.StatusInternalServerError || strings.Contains(loc, "/a/") { |
| + t.Fatalf("create account = %d -> %q, want the failure answer", status, loc) |
| + } |
| + after, err := fx.st.AccountsFor("paul@keymail.dev") |
| + if err != nil || len(after) != len(before) { |
| + t.Fatalf("accounts after the failed create = %d, want %d (%v)", len(after), len(before), err) |
| + } |
| + if _, etag, _ := telemetry.Read(context.Background(), fx.rel, telemetry.AccountKey(fx.sqid)); etag != "" { |
| + t.Error("the existing account gained a telemetry object") |
| + } |
| +} |
| + |
| +// The CLI door: the same rules, with the choice echoed back. |
| +func TestAPICreateAppAnalytics(t *testing.T) { |
| + fx, member := instanceFixture(t, "code-onramp-api") |
| + owner := cliToken(t, fx, "paul@keymail.dev", "code-onramp-api-owner") |
| + create := func(token, body string) (int, map[string]any) { |
| + status, _, raw := rawReq(t, http.MethodPost, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/new", token, body) |
| + var out map[string]any |
| + _ = json.Unmarshal([]byte(raw), &out) |
| + return status, out |
| + } |
| + // Owner, default off: --analytics gives the app its own edge. |
| + st, out := create(owner, `{"name":"api-on","analytics":"edge"}`) |
| + if st != http.StatusOK || out["analytics"] != "edge" || out["analytics_from"] != "app" { |
| + t.Fatalf("owner --analytics = %d %v", st, out) |
| + } |
| + // Owner, --no-analytics matches the default: nothing written. |
| + st, out = create(owner, `{"name":"api-off","analytics":"off"}`) |
| + if st != http.StatusOK || out["analytics"] != "off" || out["analytics_from"] != "default" || appAnalyticsObject(t, fx, "api-off") { |
| + t.Fatalf("owner --no-analytics = %d %v", st, out) |
| + } |
| + // No flag: follows the account, and the echo says so. |
| + st, out = create(member, `{"name":"api-plain"}`) |
| + if st != http.StatusOK || out["analytics"] != "off" || out["analytics_from"] != "default" { |
| + t.Fatalf("member, no flag = %d %v", st, out) |
| + } |
| + // A member asking for something else is refused before the claim. |
| + st, out = create(member, `{"name":"api-member","analytics":"edge"}`) |
| + if st != http.StatusForbidden || out["error"] != newAppAnalyticsNotOwnerMsg { |
| + t.Fatalf("member --analytics = %d %v, want 403 %q", st, out, newAppAnalyticsNotOwnerMsg) |
| + } |
| + if has, _ := fx.st.HasAppIn(OpsAccountID, "api-member"); has { |
| + t.Fatal("the refused create still claimed the name") |
| + } |
| + if st, _ = create(owner, `{"name":"api-bad","analytics":"browser"}`); st != http.StatusBadRequest { |
| + t.Fatalf("analytics=browser = %d, want 400", st) |
| + } |
| +} |
diff --git a/internal/console/analyticsonramp.go b/internal/console/analyticsonramp.go| new file mode 100644 |
| index 000000000..42073a436 |
| --- /dev/null |
| +++ b/internal/console/analyticsonramp.go |
| @@ -0,0 +1,131 @@ |
| +package console |
| + |
| +// The analytics on-ramp's create-time half |
| +// (docs/superpowers/plans/2026-10-26-analytics-onramp.md, items 2 and 3): |
| +// a new app's analytics choice, made on either create door, and the account |
| +// setting a new account starts with. Both reuse the telemetry objects the |
| +// settings doors write (analyticsview.go); there is no new storage. |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "log" |
| + |
| + "github.com/carlosframework/platform/internal/telemetry" |
| +) |
| + |
| +// errAnalyticsNotOwner is a create that asked for analytics different from |
| +// the account's default, from someone who is not an owner. Only an owner may |
| +// change analytics (the settings doors' owner gate), so the create is refused |
| +// before the name is claimed rather than the choice being quietly dropped. |
| +var errAnalyticsNotOwner = errors.New("console: only an owner can choose analytics for a new app") |
| + |
| +// Copy deck 2026-10-26-analytics-onramp-copy.md, AN-C17 (browser) and |
| +// AN-C36 (the API, printed by the CLI). |
| +const ( |
| + newAppAnalyticsNotOwnerFlash = "Only an owner can change analytics for a new app. Nothing was created." |
| + newAppAnalyticsNotOwnerMsg = "only an owner can choose analytics for a new app. Leave out --analytics and --no-analytics to follow the account" |
| +) |
| + |
| +// newAppAnalyticsSaveFailedFlash is AN-C18: the app exists, its analytics |
| +// choice did not stick, and the owner is told where to set it. |
| +func newAppAnalyticsSaveFailedFlash(app string) string { |
| + return "Created app " + app + ", but its analytics setting could not be saved. Set it in Settings, under Errors and analytics." |
| +} |
| + |
| +// accountAnalyticsDefault is what an app without its own setting resolves |
| +// to in this account: the account object folded over the built-in default. |
| +// Resolve with an EMPTY app name reads the account level alone (no app key |
| +// is built, and no app ever writes one), which is the same single read the |
| +// account settings page makes directly (handleAccountSettings, via |
| +// telemetry.Read on AccountKey) so that page can tell an unread object from |
| +// an absent one. No deployment bucket resolves to the built-in default. |
| +func (s *Server) accountAnalyticsDefault(ctx context.Context, sqid string) (telemetry.Resolved, error) { |
| + return telemetry.Resolve(ctx, s.cfg.Releases, sqid, "") |
| +} |
| + |
| +// checkNewAppAnalytics runs before the claim. choice is "" (follow the |
| +// account), telemetry.CountEdge or telemetry.CountOff, already validated. An |
| +// owner may choose either. Anyone else may only name what the account |
| +// already resolves to, which writes nothing; a default that cannot be read |
| +// refuses rather than guessing. |
| +func (s *Server) checkNewAppAnalytics(ctx context.Context, sqid, choice string, owner bool) error { |
| + if choice == "" || owner { |
| + return nil |
| + } |
| + def, err := s.accountAnalyticsDefault(ctx, sqid) |
| + if err != nil { |
| + return err |
| + } |
| + if def.Count != choice { |
| + return errAnalyticsNotOwner |
| + } |
| + return nil |
| +} |
| + |
| +// applyNewAppAnalytics runs after a successful claim. It gives the app its |
| +// own setting only when the choice differs from what the app resolves to |
| +// (the account's default, for a new name); a choice matching it writes |
| +// nothing, so the app goes on following the account. The write is the app |
| +// settings door's: the same mutation, audit row and serial bump. |
| +// |
| +// Only an owner's choice is written. checkNewAppAnalytics let a non-owner |
| +// through only when the choice matched the account, so a difference seen |
| +// here means the default moved in between; the app then follows the account, |
| +// which is what the non-owner could have had anyway. |
| +func (s *Server) applyNewAppAnalytics(ctx context.Context, acct *Account, app, addr, choice string, owner bool) error { |
| + if choice == "" || !owner || s.cfg.Releases == nil { |
| + return nil |
| + } |
| + res, err := telemetry.Resolve(ctx, s.cfg.Releases, acct.Sqid, app) |
| + if err != nil { |
| + return err |
| + } |
| + if res.Count == choice { |
| + return nil |
| + } |
| + if err := s.updateAppTelemetry(ctx, acct, app, "analytics-setting", func(st *telemetry.Settings) { |
| + mergeAnalytics(st, choice, "") |
| + }); err != nil { |
| + return err |
| + } |
| + s.audit(acct, app, addr, "analytics-setting", "set "+analyticsAudit(choice, "")+" for this app") |
| + s.bumpSerial(ctx) |
| + return nil |
| +} |
| + |
| +// newAppAnalyticsView is the Create an app form's analytics block: the |
| +// account's default, which the checkbox starts from. nil hides the block |
| +// (no bucket, or a default that could not be read), and the app then |
| +// follows the account. |
| +type newAppAnalyticsView struct { |
| + On bool |
| +} |
| + |
| +func (s *Server) newAppAnalytics(ctx context.Context, sqid string) *newAppAnalyticsView { |
| + if s.cfg.Releases == nil { |
| + return nil |
| + } |
| + def, err := s.accountAnalyticsDefault(ctx, sqid) |
| + if err != nil { |
| + log.Printf("console: new app form %s: read analytics default: %v", sqid, err) |
| + return nil |
| + } |
| + return &newAppAnalyticsView{On: def.Count == telemetry.CountEdge} |
| +} |
| + |
| +// startNewAccountAnalytics writes analytics on as a new account's own |
| +// setting (plan item 3): new accounts count from the start, and an owner can |
| +// turn it off in the account's Settings. Accounts that already exist have no |
| +// such object written, so they keep the built-in default. A failure is |
| +// returned: mintAccount runs this before the account's membership exists and |
| +// fails the creation, so no account is left looking created with analytics |
| +// silently off. |
| +func (s *Server) startNewAccountAnalytics(ctx context.Context, sqid string) error { |
| + if s.cfg.Releases == nil { |
| + return nil |
| + } |
| + return telemetry.Update(ctx, s.cfg.Releases, telemetry.AccountKey(sqid), func(st *telemetry.Settings) { |
| + mergeAnalytics(st, telemetry.CountEdge, "") |
| + }) |
| +} |
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/apicli.go b/internal/console/apicli.go| index 99091e896..c4ca4b72d 100644 |
| --- a/internal/console/apicli.go |
| +++ b/internal/console/apicli.go |
| @@ -31,6 +31,7 @@ import ( |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/svcrole" |
| + "github.com/carlosframework/platform/internal/telemetry" |
| "github.com/carlosframework/platform/internal/version" |
| ) |
| @@ -405,12 +406,35 @@ func (s *Server) handleAPICreateApp(w http.ResponseWriter, r *http.Request) { |
| BuildProbe string `json:"build_probe"` |
| Region string `json:"region"` |
| Timezone string `json:"timezone"` |
| + // Analytics is the new app's counting choice (`carlos apps create |
| + // --analytics/--no-analytics`): "" follows the account, otherwise |
| + // edge or off. An older console ignores the key; the "analytics" |
| + // echo below is how the CLI tells. |
| + Analytics string `json:"analytics"` |
| } |
| if !readJSON(w, r, &req) { |
| return |
| } |
| name := normalizeAppName(req.Name) |
| place := strings.TrimSpace(req.Place) |
| + // Like control_plane: a choice the caller may not make refuses the whole |
| + // create before the claim. Only a person who owns the account may choose |
| + // analytics different from the account's; a service credential holds no |
| + // role, so it may only name what the account already has. |
| + analyticsOwner := p.Kind == PrincipalUser && acct.Role == RoleOwner |
| + if req.Analytics != "" && !validCount(req.Analytics) { |
| + jsonError(w, http.StatusBadRequest, `analytics must be "edge", "off" or absent`) |
| + return |
| + } |
| + if err := s.checkNewAppAnalytics(r.Context(), acct.Sqid, req.Analytics, analyticsOwner); err != nil { |
| + if errors.Is(err, errAnalyticsNotOwner) { |
| + jsonError(w, http.StatusForbidden, newAppAnalyticsNotOwnerMsg) |
| + return |
| + } |
| + log.Printf("console: api create %s/%s: read analytics default: %v", acct.Sqid, name, err) |
| + jsonError(w, http.StatusBadGateway, "could not read the account's analytics setting. Try again") |
| + return |
| + } |
| // Validated BEFORE claimApp, like place: a refused flag refuses the WHOLE |
| // create rather than leaving a claimed name with the wrong shape, and a |
| // shape the server is certain to refuse costs no claim attempt. |
| @@ -541,6 +565,17 @@ func (s *Server) handleAPICreateApp(w http.ResponseWriter, r *http.Request) { |
| "build_probe": gotProbe, |
| } |
| s.echoCreatedRegion(r.Context(), acct, name, out) |
| + // "analytics" and "analytics_from" echo what the app now resolves to, |
| + // read back after the write, so the CLI compares that with what it |
| + // asked for. A failed write leaves the app following the account. |
| + if err := s.applyNewAppAnalytics(r.Context(), acct, name, addr, req.Analytics, analyticsOwner); err != nil { |
| + log.Printf("console: api create %s/%s: analytics setting: %v", acct.Sqid, name, err) |
| + } |
| + if res, err := telemetry.Resolve(r.Context(), s.cfg.Releases, acct.Sqid, name); err != nil { |
| + log.Printf("console: api create %s/%s: read back analytics: %v", acct.Sqid, name, err) |
| + } else { |
| + out["analytics"], out["analytics_from"] = res.Count, res.CountFrom |
| + } |
| writeJSON(w, http.StatusOK, out) |
| default: |
| // Any future claimOutcome lands here rather than silently 200ing |
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| new file mode 100644 |
| index 000000000..782a819ae |
| --- /dev/null |
| +++ b/internal/console/approved_analytics_onramp_copy_test.go |
| @@ -0,0 +1,127 @@ |
| +package console |
| + |
| +import ( |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// The copy gate of the analytics on-ramp plan |
| +// (docs/superpowers/plans/2026-10-26-analytics-onramp.md). The deck is |
| +// docs/superpowers/plans/2026-10-26-analytics-onramp-copy.md, in the same |
| +// shape as the console navigation deck (approved_nav_copy_test.go): one table |
| +// with the columns id, where, old, new, checked by, status. Rows whose file |
| +// sits outside this package name it relative to here ("../../apps.go"). |
| +const onrampCopyDeckPath = "../../docs/superpowers/plans/2026-10-26-analytics-onramp-copy.md" |
| + |
| +// onrampCopyBuilt is every deck row whose text the code, templates or docs |
| +// 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{ |
| + "AN-C01": true, "AN-C02": true, "AN-C03": true, "AN-C04": true, "AN-C05": true, "AN-C06": true, |
| + "AN-C10": true, "AN-C11": true, "AN-C12": true, "AN-C13": true, "AN-C14": true, "AN-C15": true, |
| + "AN-C16": true, "AN-C17": true, "AN-C18": true, "AN-C19": true, "AN-C20": true, "AN-C21": true, |
| + "AN-C22": true, "AN-C30": true, "AN-C31": true, "AN-C32": true, "AN-C33": true, "AN-C34": true, |
| + "AN-C35": true, "AN-C36": true, "AN-C40": true, "AN-C41": true, "AN-C42": 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. |
| +var onrampCopyTestFiles = []string{"*_test.go", "../../*_test.go"} |
| + |
| +func parseOnrampCopyDeck(t *testing.T) []navCopyRow { |
| + t.Helper() |
| + raw, err := os.ReadFile(onrampCopyDeckPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var rows []navCopyRow |
| + for _, line := range strings.Split(string(raw), "\n") { |
| + if !strings.HasPrefix(line, "| AN-") { |
| + continue |
| + } |
| + line = strings.TrimSpace(line) |
| + line = strings.TrimSuffix(strings.TrimPrefix(line, "| "), " |") |
| + cells := strings.Split(line, " | ") |
| + if len(cells) != 6 { |
| + t.Fatalf("deck row has %d cells, want 6: %.60q", len(cells), line) |
| + } |
| + rows = append(rows, navCopyRow{ |
| + ID: strings.TrimSpace(cells[0]), Where: strings.TrimSpace(cells[1]), |
| + Old: strings.TrimSpace(cells[2]), New: strings.TrimSpace(cells[3]), |
| + CheckedBy: strings.TrimSpace(cells[4]), Status: strings.TrimSpace(cells[5]), |
| + }) |
| + } |
| + return rows |
| +} |
| + |
| +func TestAnalyticsOnrampCopyDeckIsApprovedAndApplied(t *testing.T) { |
| + rows := parseOnrampCopyDeck(t) |
| + if len(rows) < 25 { |
| + t.Fatalf("deck parsed %d rows, want at least 25", len(rows)) |
| + } |
| + byID := map[string]navCopyRow{} |
| + for _, r := range rows { |
| + if _, dup := byID[r.ID]; dup { |
| + t.Errorf("%s appears twice in the deck", r.ID) |
| + } |
| + byID[r.ID] = r |
| + if r.Status != "approved" && r.Status != "removed" { |
| + t.Errorf("%s status is %q, want approved or removed", r.ID, r.Status) |
| + } |
| + if strings.Contains(r.New, "—") { |
| + t.Errorf("%s: new text holds an em dash", r.ID) |
| + } |
| + } |
| + for id := range onrampCopyBuilt { |
| + if _, ok := byID[id]; !ok { |
| + t.Errorf("onrampCopyBuilt names %s, which has no deck row", id) |
| + } |
| + } |
| + |
| + var sources string |
| + testSources := func() string { |
| + if sources == "" { |
| + var b strings.Builder |
| + for _, pat := range onrampCopyTestFiles { |
| + files, err := filepath.Glob(pat) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, f := range files { |
| + raw, err := os.ReadFile(f) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + b.Write(raw) |
| + b.WriteByte('\n') |
| + } |
| + } |
| + sources = b.String() |
| + } |
| + return sources |
| + } |
| + |
| + for _, r := range rows { |
| + if !onrampCopyBuilt[r.ID] { |
| + continue |
| + } |
| + if r.CheckedBy != "gate" { |
| + if !strings.Contains(testSources(), "func "+r.CheckedBy+"(") { |
| + t.Errorf("%s: its test %s does not exist", r.ID, r.CheckedBy) |
| + } |
| + continue |
| + } |
| + file, _, _ := strings.Cut(r.Where, " ") |
| + raw, err := os.ReadFile(file) |
| + if err != nil { |
| + t.Errorf("%s: %v", r.ID, err) |
| + continue |
| + } |
| + if !strings.Contains(navSpace(string(raw)), navSpace(r.New)) { |
| + t.Errorf("%s: %s does not contain %q", r.ID, file, r.New) |
| + } |
| + } |
| +} |
diff --git a/internal/console/appsettings_sections_test.go b/internal/console/appsettings_sections_test.go| index 0e2cbfbb6..8a1885fde 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/regionpicker_test.go b/internal/console/regionpicker_test.go| index 2a36efc90..e7b4aa64c 100644 |
| --- a/internal/console/regionpicker_test.go |
| +++ b/internal/console/regionpicker_test.go |
| @@ -18,13 +18,24 @@ import ( |
| func has(body, plain string) bool { return strings.Contains(body, html.EscapeString(plain)) } |
| // newAppFormGolden is the base tree's own rendering of the create-app form |
| -// (the branch base, switch off), with the session's CSRF value blanked. |
| +// (the branch base, switch off), with the session's CSRF value blanked, plus |
| +// the analytics on-ramp's checkbox block as an owner sees it on an account |
| +// whose default is off (analyticsonramp.go): the picker's absence is what |
| +// this pins, and the analytics block sits where the picker would. |
| const newAppFormGolden = `<form class="signin" method="post" action="/a/bab/apps/new"> |
| <input type="hidden" name="csrf" value="CSRF"> |
| <label class="visually-hidden" for="app-name">App name</label> |
| <input id="app-name" type="text" name="name" placeholder="my-app" autofocus |
| required pattern="[A-Za-z][A-Za-z0-9-]{0,31}" maxlength="32"> |
| + <label><input type="checkbox" name="count" value="edge"> |
| + Count page views and visitors with analytics</label> |
| + <input type="hidden" name="count" value="off"> |
| + <p class="small">No JavaScript, no cookie, no stored IP. |
| + This account's default is off.</p> |
| <button type="submit">Create app</button> |
| + <input type="hidden" name="back" value="new-app"> |
| + <button type="submit" class="btn-sm" formaction="/a/bab/analytics/setting" formnovalidate>Make this the account default</button> |
| + <p class="small">The account default also applies to every existing app without its own setting.</p> |
| </form>` |
| // newAppForm is the rendered <form>…</form>, CSRF value blanked. |
diff --git a/internal/console/server.go b/internal/console/server.go| index 34f966e5e..8fb24ff7b 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -2026,6 +2026,9 @@ func normalizeHost(host string) string { |
| // page is the one bag every template reads from; unused fields are ignored. |
| type page struct { |
| RegionPicker *regionPickerView // new-app page: nil = no picker |
| + // NewAppAnalytics is the new-app page's analytics checkbox: nil = no |
| + // checkbox, and the app follows the account (analyticsonramp.go). |
| + NewAppAnalytics *newAppAnalyticsView |
| AccountStore *accountStoreView |
| StoreQueue *storeQueueView |
| @@ -2673,6 +2676,15 @@ func (s *Server) mintAccount(ctx context.Context, name, ownerAddr string) (*Acco |
| if err != nil { |
| return nil, err |
| } |
| + // The default-on analytics setting is written after the manifest and |
| + // before the membership is published, so an account that exists for its |
| + // owner always has it. A failure is handled like a failed CreateAccount |
| + // below: the account is stranded and the caller reports the outage. |
| + if err := s.startNewAccountAnalytics(ctx, sqid); err != nil { |
| + log.Printf("console: minted account %s (id %d, %q) into the bucket but could not turn analytics on: "+ |
| + "%v — accounts/%s/account.json is stranded with no owner", sqid, id, name, err, sqid) |
| + return nil, err |
| + } |
| if err := s.store.CreateAccount(id, sqid, name, ownerAddr, now); err != nil { |
| // The manifest already landed, so the id is claimed and there is now an |
| // account in the bucket with no console row and no owner. It is |
| @@ -4941,6 +4953,7 @@ func (s *Server) handleNewAppForm(w http.ResponseWriter, r *http.Request) { |
| p.Title = "Create an app" |
| p.ActiveNav = "apps" |
| p.RegionPicker = s.newAppPicker(r.Context(), s.personIP(r)) |
| + p.NewAppAnalytics = s.newAppAnalytics(r.Context(), acct.Sqid) |
| s.render(w, http.StatusOK, "app_new", p) |
| } |
| @@ -4977,6 +4990,26 @@ func (s *Server) handleNewApp(w http.ResponseWriter, r *http.Request) { |
| fail(regionCopy.Unavailable) |
| return |
| } |
| + // The analytics checkbox (the on-ramp): "count" is edge or off from an |
| + // owner's form, absent from a member's (whose checkbox is disabled) and |
| + // from any older form, which then follows the account. A member's |
| + // hand-written choice that differs from the account is refused here, |
| + // before the claim, rather than silently dropped. |
| + owner := role == RoleOwner |
| + choice := r.FormValue("count") |
| + if choice != "" && !validCount(choice) { |
| + fail("Choose edge or off for counting.") |
| + return |
| + } |
| + if err := s.checkNewAppAnalytics(r.Context(), acct.Sqid, choice, owner); err != nil { |
| + if errors.Is(err, errAnalyticsNotOwner) { |
| + fail(newAppAnalyticsNotOwnerFlash) |
| + return |
| + } |
| + log.Printf("console: create %s/%s: read analytics default: %v", acct.Sqid, name, err) |
| + fail("Could not create the app. Please try again.") |
| + return |
| + } |
| // The browser door never places at create time, so the second return |
| // (what actually stuck) is "" here and there is nothing to echo it to — |
| // this form has no placement concept at all. With |
| @@ -4992,7 +5025,7 @@ func (s *Server) handleNewApp(w http.ResponseWriter, r *http.Request) { |
| fail("Could not create the app. Please try again.") |
| return |
| } |
| - outcome, msg, held := s.claimApp(r.Context(), acct, name, addr, "", role == RoleOwner, rq) |
| + outcome, msg, held := s.claimApp(r.Context(), acct, name, addr, "", owner, rq) |
| switch outcome { |
| case claimInvalid: |
| fail("Invalid app name — lowercase letters, digits, and dashes, starting with a letter.") |
| @@ -5021,7 +5054,14 @@ func (s *Server) handleNewApp(w http.ResponseWriter, r *http.Request) { |
| detail = fmt.Sprintf(regionCopy.AuditCreated, name, regionlabel.ForCode(region, s.regionHome(), s.regionNames()).Text) |
| } |
| s.audit(acct, name, addr, "create", detail) |
| - s.setFlash(w, "ok", "Created app "+name+" — it's yours.") |
| + // After the claim, like the CLI door's flags: a failed write leaves the |
| + // app created and following the account, and says so. |
| + if err := s.applyNewAppAnalytics(r.Context(), acct, name, addr, choice, owner); err != nil { |
| + log.Printf("console: create %s/%s: analytics setting: %v", acct.Sqid, name, err) |
| + s.setFlash(w, "err", newAppAnalyticsSaveFailedFlash(name)) |
| + } else { |
| + s.setFlash(w, "ok", "Created app "+name+" — it's yours.") |
| + } |
| http.Redirect(w, r, home+"apps/"+url.PathEscape(name), http.StatusSeeOther) |
| } |
| } |
diff --git a/internal/console/templates/account_settings.html b/internal/console/templates/account_settings.html| index 43513848b..546b94865 100644 |
| --- a/internal/console/templates/account_settings.html |
| +++ b/internal/console/templates/account_settings.html |
| @@ -203,8 +203,8 @@ concluding anything.</p> |
| {{end}} |
| <p class="small">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 and cannot be |
| -joined across days. Whether that needs consent where your visitors are is your call, which is why it |
| -is off until you turn it on.</p> |
| +joined across days. Whether that needs consent where your visitors are is your call. New accounts |
| +start with analytics on.</p> |
| <h2>Delete this account</h2> |
| {{if .HasApps}} |
diff --git a/internal/console/templates/app_analytics.html b/internal/console/templates/app_analytics.html| index 8a1fc3628..712ee6623 100644 |
| --- a/internal/console/templates/app_analytics.html |
| +++ b/internal/console/templates/app_analytics.html |
| @@ -5,13 +5,25 @@ |
| <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}} |
| +{{/* The range picker always shows: numbers counted while analytics was on |
| + stay reachable after it is switched off. With nothing counted in the |
| + window there are no empty tables, chart or "Nothing yet" rows. */}} |
| <form method="get" class="toolbar"> |
| <label>range |
| <select name="range"> |
| @@ -22,6 +34,7 @@ or for the whole account in the account's <a href="{{.Nav}}/settings">Settings</ |
| </label> |
| <button type="submit" class="btn-sm">Update</button> |
| </form> |
| +{{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 +58,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}} |
diff --git a/internal/console/templates/app_new.html b/internal/console/templates/app_new.html| index efd6e13b1..25424081d 100644 |
| --- a/internal/console/templates/app_new.html |
| +++ b/internal/console/templates/app_new.html |
| @@ -39,7 +39,29 @@ |
| .catch(function () {}); |
| })(); |
| </script>{{end}} |
| + {{- /* The checkbox comes before the hidden "off": a ticked box posts |
| + count=edge first, and FormValue reads the first value. A member's box |
| + is disabled and posts nothing, so the app follows the account. */}} |
| + {{- with .NewAppAnalytics}} |
| + <label><input type="checkbox" name="count" value="edge"{{if .On}} checked{{end}}{{if not $.IsOwner}} disabled{{end}}> |
| + Count page views and visitors with analytics</label> |
| + {{- if $.IsOwner}} |
| + <input type="hidden" name="count" value="off"> |
| + {{- end}} |
| + <p class="small">No JavaScript, no cookie, no stored IP. |
| + {{if .On}}This account's default is on.{{else}}This account's default is off.{{end}} |
| + {{- if not $.IsOwner}} Only an owner can change this.{{end}}</p> |
| + {{- end}} |
| <button type="submit">Create app</button> |
| + {{- /* After Create app on purpose: Enter in the name field presses the |
| + form's first submit button, and that must create the app, never |
| + change the account default. This one posts the same form to the |
| + account's analytics door, which comes back here (back=new-app). */}} |
| + {{- if and .NewAppAnalytics .IsOwner}} |
| + <input type="hidden" name="back" value="new-app"> |
| + <button type="submit" class="btn-sm" formaction="{{.Base}}/analytics/setting" formnovalidate>Make this the account default</button> |
| + <p class="small">The account default also applies to every existing app without its own setting.</p> |
| + {{- end}} |
| </form> |
| <p class="small">Names are lowercase letters, digits, and dashes, starting with a letter — unique within this account, not across the platform.</p> |
| {{template "bottom" .}}{{end}} |
diff --git a/internal/console/templates/app_settings.html b/internal/console/templates/app_settings.html| index 6ec60d656..09be4156e 100644 |
| --- a/internal/console/templates/app_settings.html |
| +++ b/internal/console/templates/app_settings.html |
| @@ -438,8 +438,8 @@ the {{.AnalyticsSetting.CountFrom}}. Only the account owner can change it.</p> |
| {{end}} |
| <p class="small">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 and cannot be |
| -joined across days. Whether that needs consent where your visitors are is your call, which is why it |
| -is off until you turn it on.</p> |
| +joined across days. Whether that needs consent where your visitors are is your call. New accounts |
| +start with analytics on.</p> |
| {{end}} |
| {{if eq .SettingsSection "general"}} |
| <h2>{{.SwapCopy.Heading}}</h2> |
diff --git a/internal/console/testdata/perf-budgets.txt b/internal/console/testdata/perf-budgets.txt| index 91ec374af..0f28acfb1 100644 |
| --- a/internal/console/testdata/perf-budgets.txt |
| +++ b/internal/console/testdata/perf-budgets.txt |
| @@ -29,6 +29,7 @@ GET /auth/cli/whoami skip: a bearer-token JSON door, not a screen; timed in prod |
| /fleet/economics/tier skip: POST-only door; a GET answers 404 on its first line by design (economicspass.go) |
| # Deferred parts: timed and printed, exempt from 150 ms and the call count. |
| +GET /a/{sqid}/apps/new calls 1: the account telemetry settings, which set the analytics checkbox the form starts from (1 S3 call warm, 10 ms or less) |
| GET /a/{sqid}/apps/{app}/logs/data deferred: deferred part (the Logs tab's data endpoint) |
| # Known slow today (measured 2026-10-26 after console-perf-quick-wins, with |
diff --git a/internal/provision/testdata/plan14-root-reads-analytics-onramp.tsv b/internal/provision/testdata/plan14-root-reads-analytics-onramp.tsv| new file mode 100644 |
| index 000000000..eec4287aa |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-analytics-onramp.tsv |
| @@ -0,0 +1,6 @@ |
| +# Census overlay analytics-onramp, written by census-propose (#369). census-ruling-analytics-onramp, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-analytics-onramp.md. |
| +# 1 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@legacy 8c434beae959cfe9e96aa3a8081db31bcbdd03f54189a57d3f381760be8e416d internal/telemetry/telemetry.go Resolve legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=PROPOSED-s3-change-index;identity=unchanged (the console and the agent);basis=the fold over the defaults moved into Fold, which the agent's switch pass calls over cached settings; the same two telemetry.Read calls, offsets moved;rev3=census-ruling-analytics-onramp;basis=An empty app name now returns the account setting alone instead of reading apps/<sqid>//telemetry.json; same object family (the account telemetry object), no new root read. file:Read@167,file:Read@335 1762a8b1979dcfcdbb440742b25a6c01465fd8891466cb41e5007108a3e1e9ed |
| +internal/telemetry/telemetry.go Resolve legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=PROPOSED-s3-change-index;identity=unchanged (the console and the agent);basis=the fold over the defaults moved into Fold, which the agent's switch pass calls over cached settings; the same two telemetry.Read calls, offsets moved;rev3=census-ruling-analytics-onramp;basis=An empty app name now returns the account setting alone instead of reading apps/<sqid>//telemetry.json; same object family (the account telemetry object), no new root read. file:Read@167,file:Read@335 1762a8b1979dcfcdbb440742b25a6c01465fd8891466cb41e5007108a3e1e9ed |
| +@coverage . f507b706fb72ea1fa7f28ff99b4193525b15a8408bda4c18c9d93288ca023c64 |
| +@coverage internal/telemetry 7e0e6ad650a66ef7ffd36ffc26aceef3f04f6f2926ea5b91b44b367291d6367f |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 092af8496..3bef53d39 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -12,3 +12,4 @@ plan14-root-reads-usage-attribution-390.tsv 5192052a23d2fdd6f5d48b5617fe28a9bb03 |
| plan14-root-reads-ha-p1a-433.tsv f8acbc0dd8828636e3f73d9afd0e539d3dfd1346e0232d91903c33d6eb27d820 |
| plan14-root-reads-rollup-tenant-tags.tsv f8acbc0dd8828636e3f73d9afd0e539d3dfd1346e0232d91903c33d6eb27d820 |
| plan14-root-reads-alias-wake-338.tsv deeddee1bf22a18562acda97cc34c6d73ee0dff1825100c73fa0be4c6a3f3e7b |
| +plan14-root-reads-analytics-onramp.tsv f5afdacd495705841fcc8441eaefe0efb9db7056de281bb06d1714960a5575b7 |
diff --git a/internal/telemetry/telemetry.go b/internal/telemetry/telemetry.go| index 33f7a5e0f..c0c48e52a 100644 |
| --- a/internal/telemetry/telemetry.go |
| +++ b/internal/telemetry/telemetry.go |
| @@ -105,7 +105,10 @@ type Resolved struct { |
| } |
| // Resolve reads both levels and folds them over the defaults. A store |
| -// error fails the resolve; an absent object at either level is fine. |
| +// error fails the resolve; an absent object at either level is fine. An |
| +// empty app resolves the account level alone (the account settings page and |
| +// the create form ask that way): there is no app object to read, and |
| +// AppKey(sqid, "") is a key some stores refuse outright. |
| func Resolve(ctx context.Context, s release.Store, sqid, app string) (Resolved, error) { |
| if s == nil { |
| return Fold(Settings{}, Settings{}), nil |
| @@ -114,6 +117,9 @@ func Resolve(ctx context.Context, s release.Store, sqid, app string) (Resolved, |
| if err != nil { |
| return Fold(Settings{}, Settings{}), err |
| } |
| + if app == "" { |
| + return Fold(acct, Settings{}), nil |
| + } |
| appSt, _, err := Read(ctx, s, AppKey(sqid, app)) |
| if err != nil { |
| return Fold(Settings{}, Settings{}), err |
diff --git a/internal/telemetry/telemetry_test.go b/internal/telemetry/telemetry_test.go| index 3e2dc5557..6dd3ca170 100644 |
| --- a/internal/telemetry/telemetry_test.go |
| +++ b/internal/telemetry/telemetry_test.go |
| @@ -36,6 +36,12 @@ func TestResolveAppThenAccountThenDefault(t *testing.T) { |
| if r.LogLevel != LogLevelWarn || r.Count != CountOff || r.CountFrom != "app" { |
| t.Fatalf("app override = %+v", r) |
| } |
| + // An empty app is the account level alone, on a store that refuses the |
| + // "apps/bab//telemetry.json" key a read of AppKey("bab", "") would name. |
| + r, err = Resolve(ctx, s, "bab", "") |
| + if err != nil || r.Count != CountEdge || r.CountFrom != "account" || r.LogLevel != LogLevelWarn { |
| + t.Fatalf("account alone = %+v %v", r, err) |
| + } |
| // Update preserves the other key. |
| if err := Update(ctx, s, AppKey("bab", "web"), func(st *Settings) { st.Errors = &Errors{LogLevel: LogLevelError} }); err != nil { |
| t.Fatal(err) |