operator-people-detail
Squashed from operator-people-detail into main.
29 files changed,
+1,627
−61
approved_operator_pages_copy_test.go+81 −9docs/superpowers/plans/2026-10-27-operator-people-detail-copy.md+109 −0docs/superpowers/reviews/CODEX-REVIEW-BRIEF-operator-people-detail.md+34 −0internal/console/auditdetail.go+239 −0internal/console/auditdetail_test.go+219 −0internal/console/claim_invariant_fixtures_test.go+1 −0internal/console/claim_invariant_probes_read_test.go+1 −0internal/console/lastseen_test.go+93 −0internal/console/opactivity.go+66 −21internal/console/opactivity_test.go+9 −6internal/console/opdashboard_test.go+3 −3internal/console/oppeople_test.go+1 −1internal/console/opperson.go+135 −0internal/console/opperson_test.go+364 −0internal/console/opstore.go+110 −2internal/console/opstore_test.go+30 −2internal/console/perfwalk_test.go+7 −0internal/console/server.go+17 −4internal/console/static/ops.css+20 −4internal/console/templates/app_activity.html+1 −1internal/console/templates/app_overview.html+1 −1internal/console/templates/opparts.html+10 −0internal/console/templates/ops_activity.html+7 −3internal/console/templates/ops_dashboard.html+2 −2internal/console/templates/ops_people.html+1 −1internal/console/templates/ops_person.html+34 −0internal/console/testdata/claim-routes.txt+1 −0internal/provision/operator_people_detail_census_test.go+30 −0internal/provision/plan9_b8_census_test.go+1 −1
CI passed — run details
diff --git a/approved_operator_pages_copy_test.go b/approved_operator_pages_copy_test.go| index aa8555ba5..f18189df9 100644 |
| --- a/approved_operator_pages_copy_test.go |
| +++ b/approved_operator_pages_copy_test.go |
| @@ -11,7 +11,9 @@ import ( |
| ) |
| // The copy gate of the operator pages plan (spec 2026-10-25, Part 3). The |
| -// record is docs/superpowers/plans/2026-10-25-operator-pages-copy.md. It |
| +// record is docs/superpowers/plans/2026-10-25-operator-pages-copy.md, and |
| +// the operator people detail change's record continues its ids |
| +// (2026-10-27-operator-people-detail-copy.md, OPS-155 to OPS-181). It |
| // reuses the moves gate's helpers (parseCopyTable, checkMovesInventory, |
| // checkMovesNoEmDash, checkRunBuilt, checkRunApplied) as the edge asset cache |
| // gate does. |
| @@ -21,11 +23,19 @@ import ( |
| // - TestOperatorPagesCopyBuiltRowsAreApprovedAndPresent: an id in |
| // operatorPagesCopyBuilt is an approved row, and its text is in the file |
| // it names. No pending string reaches code or templates. |
| +// - TestOperatorPeopleDetailCopyInventory and |
| +// TestOperatorPeopleDetailCopyBuiltRowsAreApprovedAndPresent: the same |
| +// two checks for the second record, its rows OPS-155 to OPS-181 and its |
| +// built list operatorPeopleDetailCopyBuilt. |
| // |
| // A row's file is a path relative to internal/console/, so the built rows are |
| // checked under operatorPagesCopyRoot. |
| const operatorPagesCopyRecordPath = "docs/superpowers/plans/2026-10-25-operator-pages-copy.md" |
| +// operatorPeopleDetailCopyRecordPath is the second record: the person page, |
| +// Activity's person filter and what an audit row says. |
| +const operatorPeopleDetailCopyRecordPath = "docs/superpowers/plans/2026-10-27-operator-people-detail-copy.md" |
| + |
| const operatorPagesCopyRoot = "internal/console" |
| var operatorPagesCopyIDPattern = regexp.MustCompile(`^OPS-[0-9]+$`) |
| @@ -39,6 +49,33 @@ var operatorPagesCopyIDs = func() []string { |
| return ids |
| }() |
| +// operatorPeopleDetailCopyIDs is the second record's inventory, pinned: |
| +// OPS-155 to OPS-181. |
| +var operatorPeopleDetailCopyIDs = func() []string { |
| + ids := make([]string, 0, 27) |
| + for i := 155; i <= 181; i++ { |
| + ids = append(ids, "OPS-"+strconv.Itoa(i)) |
| + } |
| + return ids |
| +}() |
| + |
| +// operatorPeopleDetailCopyBuilt is every row of the second record the code |
| +// or templates carry: all of them. OPS-174, OPS-177 and OPS-180 are checked through |
| +// operatorPagesShortGoText. |
| +var operatorPeopleDetailCopyBuilt = []string{ |
| + // The person page (opperson.go, templates/ops_person.html). |
| + "OPS-155", "OPS-156", "OPS-157", "OPS-158", "OPS-159", "OPS-160", |
| + // Activity's person filter (templates/ops_activity.html). |
| + "OPS-161", "OPS-162", |
| + // What an audit row says (auditdetail.go). |
| + "OPS-163", "OPS-164", "OPS-165", "OPS-166", "OPS-167", "OPS-168", "OPS-169", "OPS-170", |
| + "OPS-171", "OPS-172", "OPS-173", "OPS-174", "OPS-175", "OPS-176", |
| + // A service's run (auditdetail.go). |
| + "OPS-177", |
| + // Review fixes: uploaded files, the box's explanation, no exit code. |
| + "OPS-178", "OPS-179", "OPS-180", "OPS-181", |
| +} |
| + |
| // operatorPagesCopyBuilt is every row whose text the code or templates carry. |
| // The task that writes a row's text adds its entry here in the same commit. |
| // An entry is "OPS-n", checked in the row's file, or "OPS-n@<path>", checked |
| @@ -97,7 +134,10 @@ func operatorPagesBuiltRows(rows []copyRow, entries []string) ([]copyRow, []stri |
| // literal in its Go file, exactly: a two-letter word is checked as a literal, |
| // never as a fragment of a longer one. |
| var operatorPagesShortGoText = map[string]bool{ |
| - "OPS-80": true, // "OK", jobs.go |
| + "OPS-80": true, // "OK", jobs.go |
| + "OPS-174": true, // "<run> on <box>", auditdetail.go's "%s on %s" |
| + "OPS-177": true, // "<sentence>. <requester>", auditdetail.go's "%s. %s" |
| + "OPS-180": true, // "<run>. <detail>", auditdetail.go's "%s. %s" |
| } |
| // checkOperatorPagesBuilt is every problem with the built entries: not |
| @@ -117,7 +157,10 @@ func checkOperatorPagesBuilt(rows []copyRow, entries []string, root string) []st |
| } |
| // checkShortGoText is the check for an operatorPagesShortGoText row: an |
| -// approved row whose Go file has a string literal equal to its text. |
| +// approved row whose Go file has a string literal equal to its text, or, |
| +// for a row with a placeholder, one whole text pattern of the file (a |
| +// literal or a format, with the file's consts read in place) that speaks |
| +// the row exactly. |
| func checkShortGoText(r copyRow, root string) []string { |
| if r.Status != "approved" { |
| return nil // entryBuiltRows has already refused it |
| @@ -129,19 +172,31 @@ func checkShortGoText(r copyRow, root string) []string { |
| if err != nil { |
| return []string{r.ID + ": " + err.Error()} |
| } |
| - if !goLiteralMatches(body, func(v string) bool { return v == r.Text }) { |
| - return []string{r.ID + ": " + r.Path() + " has no string literal that is exactly " + strconv.Quote(r.Text)} |
| + if goLiteralMatches(body, func(v string) bool { return v == r.Text }) { |
| + return nil |
| + } |
| + if copyPlaceholder.MatchString(r.Text) { |
| + for _, p := range goTextPatterns(r.Path(), body) { |
| + if movesRowSpoken(r.Text, p) { |
| + return nil |
| + } |
| + } |
| } |
| - return nil |
| + return []string{r.ID + ": " + r.Path() + " has no string literal that is exactly " + strconv.Quote(r.Text)} |
| } |
| func mustParseOperatorPagesCopyRecord(t *testing.T) []copyRow { |
| t.Helper() |
| - raw, err := os.ReadFile(operatorPagesCopyRecordPath) |
| + return mustParseOperatorCopyRecordAt(t, operatorPagesCopyRecordPath) |
| +} |
| + |
| +func mustParseOperatorCopyRecordAt(t *testing.T, path string) []copyRow { |
| + t.Helper() |
| + raw, err := os.ReadFile(path) |
| if err != nil { |
| t.Fatal(err) |
| } |
| - rows, err := parseCopyTable(string(raw), operatorPagesCopyRecordPath, operatorPagesCopyIDPattern, "an OPS-<n>") |
| + rows, err := parseCopyTable(string(raw), path, operatorPagesCopyIDPattern, "an OPS-<n>") |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -161,6 +216,20 @@ func TestOperatorPagesCopyBuiltRowsAreApprovedAndPresent(t *testing.T) { |
| reportAll(t, checkOperatorPagesBuilt(mustParseOperatorPagesCopyRecord(t), operatorPagesCopyBuilt, operatorPagesCopyRoot)) |
| } |
| +func TestOperatorPeopleDetailCopyInventory(t *testing.T) { |
| + rows := mustParseOperatorCopyRecordAt(t, operatorPeopleDetailCopyRecordPath) |
| + reportAll(t, checkMovesInventory(rows, operatorPeopleDetailCopyIDs)) |
| + reportAll(t, checkMovesNoEmDash(rows)) |
| + if len(rows) != 27 { |
| + t.Errorf("the record has %d rows, want 27", len(rows)) |
| + } |
| +} |
| + |
| +func TestOperatorPeopleDetailCopyBuiltRowsAreApprovedAndPresent(t *testing.T) { |
| + rows := mustParseOperatorCopyRecordAt(t, operatorPeopleDetailCopyRecordPath) |
| + reportAll(t, checkOperatorPagesBuilt(rows, operatorPeopleDetailCopyBuilt, operatorPagesCopyRoot)) |
| +} |
| + |
| // The gate itself (not acceptance: a unit test of the helper): an entry is |
| // checked in the row's file under the root, a pending row, an unknown id and |
| // a missing text are each refused, and a placeholder row matches on its fixed |
| @@ -175,13 +244,14 @@ func TestOperatorPagesCopyGateChecksTheRowsFile(t *testing.T) { |
| } |
| write("page.html", "<p>Nobody has signed up yet.</p>\n<p>2 things need attention</p>\n") |
| write("other.html", "<p>Something else entirely.</p>\n") |
| - write("short.go", "package p\n\nconst word = \"OK\"\n") |
| + write("short.go", "package p\n\nconst word = \"OK\"\n\nconst on = \"%s on %s\"\n") |
| write("long.go", "package p\n\nconst word = \"OKAY\" // OK\n") |
| rows := []copyRow{ |
| {ID: "OPS-1", File: "page.html (the empty state)", Text: "Nobody has signed up yet.", Status: "approved"}, |
| {ID: "OPS-2", File: "page.html", Text: "<n> things need attention", Status: "approved"}, |
| {ID: "OPS-3", File: "page.html", Text: "A pending sentence goes here.", Status: "pending"}, |
| {ID: "OPS-80", File: "short.go (status word)", Text: "OK", Status: "approved"}, |
| + {ID: "OPS-174", File: "short.go (a tail)", Text: "<run> on <box>", Status: "approved"}, |
| } |
| cases := []struct { |
| name string |
| @@ -196,6 +266,8 @@ func TestOperatorPagesCopyGateChecksTheRowsFile(t *testing.T) { |
| {"an entry named twice", []string{"OPS-1", "OPS-1"}, "twice"}, |
| {"a short text is a whole literal", []string{"OPS-80"}, ""}, |
| {"a short text inside a longer literal or a comment", []string{"OPS-80@long.go"}, "no string literal that is exactly"}, |
| + {"a short placeholder row is a whole format", []string{"OPS-174"}, ""}, |
| + {"a short placeholder row with no such format", []string{"OPS-174@long.go"}, "no string literal that is exactly"}, |
| } |
| for _, c := range cases { |
| t.Run(c.name, func(t *testing.T) { |
diff --git a/docs/superpowers/plans/2026-10-27-operator-people-detail-copy.md b/docs/superpowers/plans/2026-10-27-operator-people-detail-copy.md| new file mode 100644 |
| index 000000000..1b52b9ac4 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-10-27-operator-people-detail-copy.md |
| @@ -0,0 +1,109 @@ |
| +# Operator people detail: copy record |
| + |
| +Every new user-facing string of the operator people detail change (branch |
| +`operator-people-detail`): the person page at `/fleet/people/{address}`, |
| +Activity's filter by person (`?who=`), and the readable "What" of audit |
| +rows. The ids continue the OPS-n series of `2026-10-25-operator-pages-copy.md` |
| +(OPS-1 to OPS-154). The gate is `approved_operator_pages_copy_test.go` at |
| +the repo root, which reads both records. The format and the rules are that |
| +record's: one table per heading, columns id, file, text, status; the file |
| +cell is a path relative to `internal/console/`; in a Go file the text is one |
| +string literal or one `fmt.Sprintf` format, with a format verb where the row |
| +has a `<placeholder>`. |
| + |
| +Where the strings show. The operator pages are for the people who run the |
| +platform and nobody else. The audit row sentences (OPS-163 to OPS-177) also |
| +show on the customer console's app Activity tab and the app overview's |
| +Recent activity, in place of the raw text those rows stored. |
| + |
| +Strings that already have an OPS row and show unchanged on the new page |
| +(Joined, Last seen, Accounts, not yet, Account, Plan, Apps, Latest activity, |
| +When, What, App, none) are not rows here. |
| + |
| +Approved 2026-10-27 by delegation to Luna (`gpt-5.6-luna`, read-only, on |
| +the house rules: no em dashes, plain, short, human text only). Luna changed |
| +six rows (OPS-155, OPS-163, OPS-164, OPS-166, OPS-171, OPS-175) and left |
| +sixteen alone. Its text is applied verbatim. OPS-171 is a whole sentence: |
| +no tail is appended to it. |
| + |
| +Placeholders: `<address>` an email address; `<command>` the command a run |
| +ran, its words joined by spaces; `<version>` an app version; `<n>` a whole |
| +number; `<signal>` a signal number; `<reason>` why a box interrupted or |
| +refused a run, as the box recorded it; `<duration>` how long a run took, |
| +such as `2m3s`; `<box>` a box's label; `<run>` one of OPS-165 to OPS-170 or OPS-172; |
| +`<action>` an audit action name, such as `store-apply`; `<sentence>` one of |
| +OPS-163 to OPS-175; `<requester>` the run package's line for a service's run; `<files>` and |
| +`<name>` uploaded file names; `<detail>` the box's explanation of a result. |
| + |
| +## The person page |
| + |
| +| id | file | text | status | |
| +|---|---|---|---| |
| +| OPS-155 | templates/ops_person.html (the page subhead) | Their accounts and latest activity. | approved | |
| +| OPS-156 | opperson.go (a stat label) | Apps created | approved | |
| +| OPS-157 | templates/ops_person.html (the accounts column) | Role | approved | |
| +| OPS-158 | templates/ops_person.html (no accounts) | Not a member of any account. | approved | |
| +| OPS-159 | templates/ops_person.html (no activity) | No activity yet. | approved | |
| +| OPS-160 | templates/ops_person.html (the link to Activity) | All their activity | approved | |
| + |
| +## Activity, filtered to one person |
| + |
| +| id | file | text | status | |
| +|---|---|---|---| |
| +| OPS-161 | templates/ops_activity.html | Showing only <address>. | approved | |
| +| OPS-162 | templates/ops_activity.html (the link that drops the person filter) | Show all people | approved | |
| + |
| +## What an audit row says |
| + |
| +| id | file | text | status | |
| +|---|---|---|---| |
| +| OPS-163 | auditdetail.go (run-start) | Started <command> (<version>) | approved | |
| +| OPS-164 | auditdetail.go (run-start, no version known) | Started <command> | approved | |
| +| OPS-165 | auditdetail.go (run-end) | Run ended with exit code <n> | approved | |
| +| OPS-166 | auditdetail.go (run-end) | Run stopped by signal <signal> | approved | |
| +| OPS-167 | auditdetail.go (run-end) | Run timed out | approved | |
| +| OPS-168 | auditdetail.go (run-end) | Run was cancelled | approved | |
| +| OPS-169 | auditdetail.go (run-end) | Run was interrupted (<reason>) | approved | |
| +| OPS-170 | auditdetail.go (run-end) | Run was refused (<reason>) | approved | |
| +| OPS-171 | auditdetail.go (run-end) | No box picked up the run | approved | |
| +| OPS-172 | auditdetail.go (run-end, no result recorded) | Run ended | approved | |
| +| OPS-173 | auditdetail.go (run-end, when it started and ended) | <run> after <duration> | approved | |
| +| OPS-174 | auditdetail.go (run-end, when a box ran it) | <run> on <box> | approved | |
| +| OPS-175 | auditdetail.go (run-end, output cut off) | <run>. Its output was cut off | approved | |
| +| OPS-176 | auditdetail.go (any other row that stored data, with the data below it) | Recorded <action> | approved | |
| + |
| +## A service's run |
| + |
| +A run a service started (a run credential, or a schedule) stores the |
| +service's line beside its data, in the run package's words (`run by service |
| +ci (scheduled)`, `run by service ci for <address> (as stated by the |
| +service)`). The run-start and run-end sentences keep it after them. |
| + |
| +Approved 2026-10-27 by a one-string Luna check (`gpt-5.6-luna`, same house |
| +rules). Luna changed the drafted comma to a full stop, so the run package's |
| +lower-case line stays exactly as approved; its text is applied verbatim. |
| + |
| +| id | file | text | status | |
| +|---|---|---|---| |
| +| OPS-177 | auditdetail.go (a service's run-start or run-end) | <sentence>. <requester> | approved | |
| + |
| +## Review fixes |
| + |
| +Astra's review (round 1, READY AFTER FIXES) found that the sentences |
| +dropped facts the stored rows showed, and that OPS-175 named a cause the |
| +result does not establish: a run's output is also cut off when its upload |
| +to storage fails. OPS-175 now states the cut-off alone. A run-start row |
| +keeps the files the run uploaded (OPS-178, each OPS-179); a run-end row |
| +keeps the box's own explanation (OPS-180), such as why an instance did not |
| +wake; and a result with no exit code says so (OPS-181) rather than reading |
| +as exit code 0. |
| + |
| +Approved 2026-10-27 by a Luna check (`gpt-5.6-luna`, same house rules) of |
| +the five rows. Luna kept all five as drafted. |
| + |
| +| id | file | text | status | |
| +|---|---|---|---| |
| +| OPS-178 | auditdetail.go (run-start, files uploaded) | <sentence>. Uploaded <files> | approved | |
| +| OPS-179 | auditdetail.go (one uploaded file; <files> is these joined by commas) | <name> (<n> bytes) | approved | |
| +| OPS-180 | auditdetail.go (run-end, the box's explanation) | <run>. <detail> | approved | |
| +| OPS-181 | auditdetail.go (run-end, no exit code recorded) | Run ended with no exit code recorded | approved | |
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-operator-people-detail.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-operator-people-detail.md| new file mode 100644 |
| index 000000000..41410d2d3 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-operator-people-detail.md |
| @@ -0,0 +1,34 @@ |
| +# Review brief: branch operator-people-detail, round 1 of 3 |
| + |
| +Repo carlos/platform, branch `operator-people-detail`, code at a0545441416d247b04b05cb4df83e5655f58e592. |
| +Under review: the diff `origin/main...a0545441416d247b04b05cb4df83e5655f58e592`. |
| +Authorities: Paul's request in chat (2026-10-27): operators can click a person to see more about them; JSON details in activity rows are summarised rather than dumped into a table cell. The operator-pages plan `docs/superpowers/plans/2026-10-25-operator-pages.md` (Global Constraints, Decisions) still binds. The copy record `docs/superpowers/plans/2026-10-27-operator-people-detail-copy.md` is Luna-approved; review wording only for factual errors. |
| + |
| +You are an independent reviewer. Read the code and check every claim against it. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- Operator pages use the Rastrillo shell; customer pages keep their design (wording-only changes on app_activity.html and app_overview.html are in scope). |
| +- Operator pages read only SQLite (0 S3) for People, Activity and the new person page. |
| + |
| +## What to check |
| + |
| +1. The gate: GET /fleet/people/{address} and /fleet/activity?who= answer a non-operator exactly as other operator routes do, with operatorOnly first and no read before it; an unknown address is 404 with no writes. |
| +2. Addresses: case handling matches how users rows are stored; links URL-escape the address; a hostile address (quotes, angle brackets, %, /, very long) cannot break the page, the SQL or a link. |
| +3. The new audit index and queries: additive migration, each query uses its index (TestOperatorQueryPlans), paging and filters combine correctly (who + account + kind). |
| +4. The run and JSON formatter: every run-start and run-end shape (exit, signal, timed out, cancelled, interrupted, refused, truncated, service requester, missing or malformed fields) renders a correct sentence; non-JSON and non-object details are untouched; the <details> JSON is escaped; customer pages show the same facts as before, worded as sentences, and nothing an account member could not already see. |
| +5. Census: `make census-card` names nothing. The record-write census (9B8) re-pins `NewServer` in a branch layer because a route was added; answer APPROVE or ESCALATE for that re-pin (does any record write change, move into a new function, or gain a new caller?). |
| + |
| +## 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 with evidence (file:line), failure scenario and fix. Then the census verdict line. End with exactly one verdict: READY, READY AFTER FIXES, or NOT READY. |
| + |
| +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/auditdetail.go b/internal/console/auditdetail.go| new file mode 100644 |
| index 000000000..912b28e20 |
| --- /dev/null |
| +++ b/internal/console/auditdetail.go |
| @@ -0,0 +1,239 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "encoding/json" |
| + "fmt" |
| + "strings" |
| + "time" |
| + "unicode/utf8" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/runs" |
| +) |
| + |
| +// What an audit row says: the one formatter every feed of audit rows reads |
| +// its Detail through (the operator dashboard, Activity and the person page; |
| +// the customer console's app Activity tab and Recent activity). Most rows |
| +// store a sentence, written when the action happened, and show it as it is. |
| +// run-start and run-end store JSON (apiruns.go's runStartDetail, |
| +// apirunsfollow.go's auditRunEnd); they read as sentences built from it. Any |
| +// other row whose Detail is a JSON object reads as a short summary, and the |
| +// operator pages hold the data itself, indented, under it (copy record |
| +// 2026-10-27-operator-people-detail-copy.md, OPS-163 to OPS-181). |
| + |
| +// The words (OPS-163 to OPS-181). The run-end heads but auditRunNotPickedUp |
| +// are sentences the tails (after, on, truncated) are appended to. |
| +const ( |
| + auditRunStart = "Started %s (%s)" |
| + auditRunStartBare = "Started %s" |
| + auditRunExit = "Run ended with exit code %d" |
| + auditRunSignal = "Run stopped by signal %s" |
| + auditRunTimedOut = "Run timed out" |
| + auditRunCancelled = "Run was cancelled" |
| + auditRunInterrupted = "Run was interrupted (%s)" |
| + auditRunRefused = "Run was refused (%s)" |
| + auditRunNotPickedUp = "No box picked up the run" |
| + auditRunEnded = "Run ended" |
| + auditRunAfter = "%s after %s" |
| + auditRunOn = "%s on %s" |
| + auditRunTruncated = "%s. Its output was cut off" |
| + auditRecordedAction = "Recorded %s" |
| + // auditRunRequester follows a service's run sentence with the run |
| + // package's own line for it (runs.Request.ServiceLine). |
| + auditRunRequester = "%s. %s" |
| + // Review fixes (OPS-178 to OPS-181): the files a run uploaded, each |
| + // with its size; the box's explanation of a result; a result with no |
| + // exit code. |
| + auditRunUploaded = "%s. Uploaded %s" |
| + auditRunFileSize = "%s (%s bytes)" |
| + auditRunDetail = "%s. %s" |
| + auditRunNoExit = "Run ended with no exit code recorded" |
| +) |
| + |
| +// The rows the formatter reads, and how it lays them out. |
| +const ( |
| + auditActionRunStart = "run-start" |
| + auditActionRunEnd = "run-end" |
| + // auditClipRunes is the length past which a cell that shows one line |
| + // may cut Text, so Title carries the whole of it. |
| + auditClipRunes = 60 |
| + auditJSONIndent = " " |
| + // auditRunEnd's outcomes (runEndOutcome) beside provision's. |
| + auditRunOutcomeLost = "lost" |
| + auditRunOutcomeEnded = "result" |
| +) |
| + |
| +// auditWhat is how one audit row's Detail shows. Text is the sentence, the |
| +// summary or the stored text. Title, when set, is the whole of a Text long |
| +// enough that a one-line cell may cut it. JSON, when set, is the stored |
| +// object indented, for a <details> under Text: every row that stored an |
| +// object keeps it there, a run row's sentence included, so nothing it |
| +// recorded is out of an operator's reach. |
| +type auditWhat struct { |
| + Text, Title, JSON string |
| +} |
| + |
| +// auditWhatOf is how the row with action and detail shows. |
| +func auditWhatOf(action, detail string) auditWhat { |
| + var w auditWhat |
| + if auditJSONObject(detail) { |
| + var buf bytes.Buffer |
| + if json.Indent(&buf, []byte(strings.TrimSpace(detail)), "", auditJSONIndent) == nil { |
| + w.JSON = buf.String() |
| + } |
| + } |
| + switch text, ok := auditRunSentence(action, detail); { |
| + case ok: |
| + w.Text = text |
| + case w.JSON != "": |
| + w.Text = fmt.Sprintf(auditRecordedAction, action) |
| + default: |
| + w.Text = detail |
| + } |
| + if utf8.RuneCountInString(w.Text) > auditClipRunes { |
| + w.Title = w.Text |
| + } |
| + return w |
| +} |
| + |
| +// auditText is auditWhatOf's Text: the words alone, for the customer |
| +// console's lists, which show a row's text and nothing else. A run row's |
| +// sentence keeps the facts those lists showed in its stored JSON: the |
| +// files the run uploaded and the box's own explanation of its result. |
| +func auditText(action, detail string) string { return auditWhatOf(action, detail).Text } |
| + |
| +// auditJSONObject reports whether detail is one JSON object. |
| +func auditJSONObject(detail string) bool { |
| + d := strings.TrimSpace(detail) |
| + if !strings.HasPrefix(d, "{") { |
| + return false |
| + } |
| + var v map[string]json.RawMessage |
| + return json.Unmarshal([]byte(d), &v) == nil |
| +} |
| + |
| +// auditRunFile is one file a run-start row records (runStartDetail). |
| +type auditRunFile struct { |
| + Name string `json:"name"` |
| + Size int64 `json:"size"` |
| +} |
| + |
| +// auditRunSentence is the sentence of a run-start or run-end row whose |
| +// Detail reads as the JSON that row stores; ok is false for any other row, |
| +// and for one whose Detail does not read. |
| +func auditRunSentence(action, detail string) (string, bool) { |
| + switch action { |
| + case auditActionRunStart: |
| + var d struct { |
| + Argv []string `json:"argv"` |
| + Files []auditRunFile `json:"files"` |
| + Version string `json:"version"` |
| + Requester string `json:"requester"` |
| + } |
| + if json.Unmarshal([]byte(detail), &d) != nil || len(d.Argv) == 0 { |
| + return "", false |
| + } |
| + command := strings.Join(d.Argv, " ") |
| + s := fmt.Sprintf(auditRunStart, command, d.Version) |
| + if d.Version == "" { |
| + s = fmt.Sprintf(auditRunStartBare, command) |
| + } |
| + if len(d.Files) > 0 { |
| + files := make([]string, 0, len(d.Files)) |
| + for _, f := range d.Files { |
| + files = append(files, fmt.Sprintf(auditRunFileSize, f.Name, opNumber(int(f.Size)))) |
| + } |
| + s = fmt.Sprintf(auditRunUploaded, s, strings.Join(files, ", ")) |
| + } |
| + return auditRunBy(s, d.Requester), true |
| + case auditActionRunEnd: |
| + var d struct { |
| + Outcome string `json:"outcome"` |
| + Result json.RawMessage `json:"result"` |
| + Requester string `json:"requester"` |
| + } |
| + if json.Unmarshal([]byte(detail), &d) != nil || d.Outcome == "" { |
| + return "", false |
| + } |
| + // The result as recorded, and whether it holds an exit code at |
| + // all: runs.Result reads a missing or null exit as 0. |
| + var res *runs.Result |
| + var exit struct { |
| + Exit *int `json:"exit"` |
| + } |
| + if len(d.Result) > 0 && string(d.Result) != "null" { |
| + res = new(runs.Result) |
| + if json.Unmarshal(d.Result, res) != nil || json.Unmarshal(d.Result, &exit) != nil { |
| + return "", false |
| + } |
| + } |
| + return auditRunBy(auditRunEndSentence(d.Outcome, res, exit.Exit != nil), d.Requester), true |
| + } |
| + return "", false |
| +} |
| + |
| +// auditRunBy is a run sentence followed by the service's line when a |
| +// service ran it ("" for a person's run, whose row's actor names them). |
| +func auditRunBy(sentence, requester string) string { |
| + if requester == "" { |
| + return sentence |
| + } |
| + return fmt.Sprintf(auditRunRequester, sentence, requester) |
| +} |
| + |
| +// auditRunEndSentence is a run-end row's sentence: how the run ended (the |
| +// CLI's runExit order: refused, cancelled, timed out, interrupted, a |
| +// signal, an exit code), how long it ran when it started and ended, the |
| +// box that ran it, the box's own explanation, and whether its output was |
| +// cut off (which says nothing of why: a full output and a failed upload |
| +// both cut it). outcome is auditRunEnd's (runEndOutcome); res is nil when |
| +// no result was recorded; exitKnown says whether res records an exit code, |
| +// and a result that ended without one never reads as exit code 0. |
| +func auditRunEndSentence(outcome string, res *runs.Result, exitKnown bool) string { |
| + if res == nil { |
| + switch outcome { |
| + case provision.RunExpired: |
| + return auditRunNotPickedUp |
| + case provision.RunCancelled: |
| + return auditRunCancelled |
| + case auditRunOutcomeLost: |
| + return fmt.Sprintf(auditRunInterrupted, runs.InterruptedLost) |
| + } |
| + return auditRunEnded |
| + } |
| + var s string |
| + switch { |
| + case res.Refused == runs.RefusedExpired || outcome == provision.RunExpired: |
| + return auditRunNotPickedUp |
| + case res.Refused != "": |
| + s = fmt.Sprintf(auditRunRefused, res.Refused) |
| + case res.Cancelled: |
| + s = auditRunCancelled |
| + case res.TimedOut: |
| + s = auditRunTimedOut |
| + case res.Interrupted != "": |
| + s = fmt.Sprintf(auditRunInterrupted, res.Interrupted) |
| + case res.Signal != "": |
| + s = fmt.Sprintf(auditRunSignal, res.Signal) |
| + case (outcome == auditRunOutcomeEnded || outcome == "") && exitKnown: |
| + s = fmt.Sprintf(auditRunExit, res.Exit) |
| + case outcome == auditRunOutcomeEnded || outcome == "": |
| + s = auditRunNoExit |
| + default: |
| + s = auditRunEnded |
| + } |
| + if !res.Started.IsZero() && res.Ended.After(res.Started) { |
| + s = fmt.Sprintf(auditRunAfter, s, res.Ended.Sub(res.Started).Round(time.Second)) |
| + } |
| + if res.Box != "" { |
| + s = fmt.Sprintf(auditRunOn, s, res.Box) |
| + } |
| + if res.Detail != "" { |
| + s = fmt.Sprintf(auditRunDetail, s, res.Detail) |
| + } |
| + if res.Truncated { |
| + s = fmt.Sprintf(auditRunTruncated, s) |
| + } |
| + return s |
| +} |
diff --git a/internal/console/auditdetail_test.go b/internal/console/auditdetail_test.go| new file mode 100644 |
| index 000000000..721a71e77 |
| --- /dev/null |
| +++ b/internal/console/auditdetail_test.go |
| @@ -0,0 +1,219 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "encoding/json" |
| + "html" |
| + "net/http" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/runs" |
| +) |
| + |
| +// What an audit row says (auditdetail.go). |
| + |
| +// runEndJSON is a run-end row's Detail as auditRunEnd marshals it. |
| +func runEndJSON(t *testing.T, outcome string, res *runs.Result) string { |
| + t.Helper() |
| + d := struct { |
| + ID string `json:"id"` |
| + Outcome string `json:"outcome"` |
| + Result *runs.Result `json:"result,omitempty"` |
| + }{"r-1", outcome, res} |
| + b, err := json.Marshal(d) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return string(b) |
| +} |
| + |
| +func TestAuditWhatOfRunRows(t *testing.T) { |
| + start := time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC) |
| + ran := func(r runs.Result) *runs.Result { |
| + r.Started, r.Ended, r.Box = start, start.Add(2*time.Minute+3*time.Second), "uk-1" |
| + return &r |
| + } |
| + for _, c := range []struct { |
| + name, action, detail, want string |
| + }{ |
| + {"run-start with a version", "run-start", |
| + runStartDetail(runs.Request{ID: "r-1", Argv: []string{"bin/migrate", "--up"}}, "v12"), |
| + "Started bin/migrate --up (v12)"}, |
| + {"run-start with no version", "run-start", |
| + runStartDetail(runs.Request{ID: "r-1", Argv: []string{"rake", "db:seed"}}, ""), |
| + "Started rake db:seed"}, |
| + {"an exit code", "run-end", runEndJSON(t, "result", ran(runs.Result{Exit: 3})), |
| + "Run ended with exit code 3 after 2m3s on uk-1"}, |
| + {"exit 0 with no times or box", "run-end", runEndJSON(t, "result", &runs.Result{}), |
| + "Run ended with exit code 0"}, |
| + {"timed out", "run-end", runEndJSON(t, "result", ran(runs.Result{TimedOut: true, Exit: -1})), |
| + "Run timed out after 2m3s on uk-1"}, |
| + {"cancelled while running", "run-end", runEndJSON(t, provision.RunCancelled, ran(runs.Result{Cancelled: true})), |
| + "Run was cancelled after 2m3s on uk-1"}, |
| + {"cancelled before it started", "run-end", runEndJSON(t, provision.RunCancelled, &runs.Result{Cancelled: true}), |
| + "Run was cancelled"}, |
| + {"cancelled with no result", "run-end", runEndJSON(t, provision.RunCancelled, nil), |
| + "Run was cancelled"}, |
| + {"interrupted", "run-end", runEndJSON(t, "result", ran(runs.Result{Interrupted: runs.InterruptedAgentRestart})), |
| + "Run was interrupted (the box's agent restarted) after 2m3s on uk-1"}, |
| + {"lost", "run-end", runEndJSON(t, "lost", &runs.Result{Interrupted: runs.InterruptedLost, Box: "uk-1"}), |
| + "Run was interrupted (its box stopped reporting) on uk-1"}, |
| + {"lost with no result", "run-end", runEndJSON(t, "lost", nil), |
| + "Run was interrupted (its box stopped reporting)"}, |
| + {"refused", "run-end", runEndJSON(t, "result", &runs.Result{Refused: runs.RefusedWake, Box: "uk-1"}), |
| + "Run was refused (wake) on uk-1"}, |
| + {"never picked up", "run-end", runEndJSON(t, provision.RunExpired, &runs.Result{Refused: runs.RefusedExpired}), |
| + "No box picked up the run"}, |
| + {"never picked up, no result", "run-end", runEndJSON(t, provision.RunExpired, nil), |
| + "No box picked up the run"}, |
| + {"a signal", "run-end", runEndJSON(t, "result", ran(runs.Result{Signal: "9"})), |
| + "Run stopped by signal 9 after 2m3s on uk-1"}, |
| + {"a service's run-start", "run-start", |
| + runStartDetail(runs.Request{ID: "r-1", Argv: []string{"import"}, ByService: "ci", OnBehalfOf: "ann@example.com"}, "v2"), |
| + "Started import (v2). run by service ci for ann@example.com (as stated by the service)"}, |
| + {"a scheduled run's run-end", "run-end", |
| + `{"id":"r-1","outcome":"result","result":{"exit":0},"requester":"run by service ci (scheduled)"}`, |
| + "Run ended with exit code 0. run by service ci (scheduled)"}, |
| + {"output cut off", "run-end", runEndJSON(t, "result", ran(runs.Result{Exit: 0, Truncated: true})), |
| + "Run ended with exit code 0 after 2m3s on uk-1. Its output was cut off"}, |
| + // The shape a run whose every output upload failed leaves |
| + // (internal/host's TestRunOutputIsBoundedWhenEveryChunkFails): a |
| + // few bytes of output, nothing stored, cut off. No cause is named. |
| + {"output uploads failed", "run-end", runEndJSON(t, "result", &runs.Result{Exit: 1, Truncated: true, LastSeq: 0, Box: "uk-1"}), |
| + "Run ended with exit code 1 on uk-1. Its output was cut off"}, |
| + {"files uploaded", "run-start", |
| + runStartDetail(runs.Request{ID: "r-1", Argv: []string{"import", "x.csv"}, |
| + Files: []runs.File{{Name: "x.csv", Size: 1234}, {Name: "notes.txt", Size: 7}}}, "v2"), |
| + "Started import x.csv (v2). Uploaded x.csv (1,234 bytes), notes.txt (7 bytes)"}, |
| + {"a refusal with the box's explanation", "run-end", |
| + runEndJSON(t, "result", &runs.Result{Refused: runs.RefusedWake, Detail: "the instance stopped while it was waking", Box: "uk-1"}), |
| + "Run was refused (wake) on uk-1. the instance stopped while it was waking"}, |
| + {"no exit field", "run-end", `{"id":"r-1","outcome":"result","result":{}}`, |
| + "Run ended with no exit code recorded"}, |
| + {"a null exit", "run-end", `{"id":"r-1","outcome":"result","result":{"exit":null,"box":"uk-1"}}`, |
| + "Run ended with no exit code recorded on uk-1"}, |
| + {"an explicit exit 0", "run-end", `{"id":"r-1","outcome":"result","result":{"exit":0}}`, |
| + "Run ended with exit code 0"}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + w := auditWhatOf(c.action, c.detail) |
| + if w.Text != c.want { |
| + t.Errorf("auditWhatOf(%s, %s) = %+v, want %q", c.action, c.detail, w, c.want) |
| + } |
| + // The operator pages keep everything the row recorded. |
| + var want bytes.Buffer |
| + if err := json.Indent(&want, []byte(c.detail), "", " "); err != nil || w.JSON != want.String() { |
| + t.Errorf("auditWhatOf(%s, %s).JSON = %q, want the row's JSON indented", c.action, c.detail, w.JSON) |
| + } |
| + if got := auditText(c.action, c.detail); got != c.want { |
| + t.Errorf("auditText = %q, want %q", got, c.want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestAuditWhatOfOtherRows(t *testing.T) { |
| + // A sentence stays as written. |
| + if w := auditWhatOf("promote", "Made v2 live"); w != (auditWhat{Text: "Made v2 live"}) { |
| + t.Errorf("a sentence = %+v", w) |
| + } |
| + // Long text: whole, with the whole of it in Title. |
| + long := strings.Repeat("Set a variable that is long ", 4) |
| + if w := auditWhatOf("env-set", long); w.Text != long || w.Title != long || w.JSON != "" { |
| + t.Errorf("long text = %+v", w) |
| + } |
| + // Any other JSON object: the summary, and the object indented. |
| + w := auditWhatOf("store-apply", `{"note":"<b>uploads</b>","size":3}`) |
| + if w.Text != "Recorded store-apply" || w.JSON != "{\n \"note\": \"<b>uploads</b>\",\n \"size\": 3\n}" { |
| + t.Errorf("a JSON row = %+v", w) |
| + } |
| + // A run row that does not read as its JSON, and JSON that is not an |
| + // object, stay as stored. |
| + for _, c := range [][2]string{{"run-start", "Started something"}, {"run-end", `{"outcome":`}, {"env-set", `["a","b"]`}, {"env-set", `{"a":1} trailing`}} { |
| + if w := auditWhatOf(c[0], c[1]); w.Text != c[1] || w.JSON != "" { |
| + t.Errorf("auditWhatOf(%q, %q) = %+v, want it as stored", c[0], c[1], w) |
| + } |
| + } |
| +} |
| + |
| +// TestOperatorFeedsShowWhat: on Activity, the dashboard and a person page, |
| +// a JSON row is its summary over the escaped, indented data in a native |
| +// <details>, and long text is one line with its whole in title. |
| +func TestOperatorFeedsShowWhat(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + w := seedOperatorWorld(t, fx) |
| + long := strings.Repeat("Changed a long setting ", 4) |
| + for _, r := range []Activity{ |
| + {Action: "store-apply", Detail: `{"note":"<script>alert(1)</script>"}`}, |
| + {Action: "env-set", Detail: long}, |
| + } { |
| + if err := fx.st.RecordActivity(w.shop.ID, "shop", "ann@example.com", r, w.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for path, body := range map[string]string{ |
| + "/fleet/activity": peopleGet(t, fx, w.c, "/fleet/activity"), |
| + "/fleet": dashGet(t, fx, w.c), |
| + "/fleet/people/ann@example.com": personGet(t, fx, w.c, "ann@example.com"), |
| + } { |
| + details := "<details co-what><summary>Recorded store-apply</summary><pre>{\n "note": "<script>alert(1)</script>"\n}</pre></details>" |
| + if !strings.Contains(body, details) { |
| + t.Errorf("%s: the JSON row is not its summary over its data:\n%s", path, body) |
| + } |
| + if strings.Contains(body, "<script>alert(1)") { |
| + t.Errorf("%s: the stored data reached the page unescaped", path) |
| + } |
| + clip := `<span co-clip title="` + html.EscapeString(long) + `">` + html.EscapeString(long) + `</span>` |
| + if !strings.Contains(body, clip) { |
| + t.Errorf("%s: the long row is not one line with its whole in title", path) |
| + } |
| + } |
| +} |
| + |
| +// TestRunRowsReadAsSentences is production-wired: a run started and |
| +// finished through the real doors writes its run-start and run-end rows, |
| +// and the customer console's app Activity tab and Recent activity, and the |
| +// operator's Activity, show them as sentences, not their JSON. |
| +func TestRunRowsReadAsSentences(t *testing.T) { |
| + fx := runFixture(t) |
| + id := fx.finishedRun(t) |
| + if status, body := fx.post(t, id, "ack", `{"last_seq":1}`); status != http.StatusOK { |
| + t.Fatalf("ack: %d %s", status, body) |
| + } |
| + if rows := fx.runEnds(t, id); len(rows) != 1 { |
| + t.Fatalf("run-end rows %q, want 1", rows) |
| + } |
| + fx.setUser("paul@keymail.dev") // runFixture's last sign-in was alice's |
| + c := signInOperator(t, fx.consoleFixture) |
| + pages := map[string]string{} |
| + operator := fx.ts.URL + "/fleet/activity" |
| + for _, path := range []string{fx.u("/apps/shop/activity"), fx.u("/apps/shop"), operator} { |
| + status, _, body := get(t, c, path) |
| + if status != http.StatusOK { |
| + t.Fatalf("GET %s = %d", path, status) |
| + } |
| + pages[path] = body |
| + } |
| + for path, body := range pages { |
| + for _, want := range []string{"Started import x.csv", "Run ended with exit code 0"} { |
| + if !strings.Contains(body, want) { |
| + t.Errorf("%s has no %q", path, want) |
| + } |
| + } |
| + if path == operator { |
| + // The sentence opens onto everything the row recorded. |
| + for _, want := range []string{"<details co-what><summary>Started import x.csv", ""argv": [", ""outcome": "result""} { |
| + if !strings.Contains(body, want) { |
| + t.Errorf("%s has no %q", path, want) |
| + } |
| + } |
| + continue |
| + } |
| + if strings.Contains(body, `"argv"`) || strings.Contains(body, `"outcome"`) || strings.Contains(body, `"argv"`) { |
| + t.Errorf("%s shows a run row's JSON", path) |
| + } |
| + } |
| +} |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index 1ec1236d2..d652a234b 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -897,6 +897,7 @@ var claimFixtures = map[string]claimFixture{ |
| "route GET /fleet/index": claimRead("operator section index; reads nothing remote"), |
| "route GET /fleet/metrics": claimRead("operator box metrics"), |
| "route GET /fleet/people": claimRead("operator people and accounts list; SQLite only"), |
| + "route GET /fleet/people/{address}": claimRead("operator person page; SQLite only, writes nothing"), |
| "route GET /fleet/store": claimRead("operator entitlement queue page"), |
| "route GET /healthz": claimRead("answers ok and the build"), |
| "route GET /invite/{token}": claimRead("shows an invitation; joining is the POST"), |
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go| index 1ef3c27d4..b4529b1bd 100644 |
| --- a/internal/console/claim_invariant_probes_read_test.go |
| +++ b/internal/console/claim_invariant_probes_read_test.go |
| @@ -177,6 +177,7 @@ var claimReadProbes = map[string]claimProbe{ |
| "route GET /fleet/index": claimPageRead(nil, "/fleet/index", "rst-shell-console=\"index\""), |
| "route GET /fleet/metrics": claimPageRead(nil, "/fleet/metrics", "<h1>Metrics</h1>"), |
| "route GET /fleet/people": claimPageRead(nil, "/fleet/people", "<h1>People and accounts</h1>"), |
| + "route GET /fleet/people/{address}": claimPageRead(nil, "/fleet/people/paul@keymail.dev", "<h1>paul@keymail.dev</h1>"), |
| "route GET /fleet/store": claimPageRead(claimWorldApply, "/fleet/store", "<h1>Storage requests</h1>"), |
| "route GET /healthz": claimPageRead(nil, "/healthz", "ok"), |
| "route GET /static/{hash}/{file...}": claimPageRead(nil, assetURL("rastrillo/tokens.css"), "--rst-"), |
diff --git a/internal/console/lastseen_test.go b/internal/console/lastseen_test.go| index 5c551d55c..62ef83b90 100644 |
| --- a/internal/console/lastseen_test.go |
| +++ b/internal/console/lastseen_test.go |
| @@ -4,6 +4,7 @@ import ( |
| "database/sql" |
| "errors" |
| "net/http" |
| + "strings" |
| "sync" |
| "testing" |
| "time" |
| @@ -293,3 +294,95 @@ BEGIN SELECT RAISE(ABORT, 'test: last_seen refused'); END;`); err != nil { |
| t.Fatalf("lastSeenWrites after a second GET within the hour = +%d, want +1 (the failed write's reservation kept)", got) |
| } |
| } |
| + |
| +// rollSeen puts the console where a roll leaves it: a fresh process holds no |
| +// reservation, and the stored last_seen is the column's default for address. |
| +func rollSeen(t *testing.T, fx *consoleFixture, address string) { |
| + t.Helper() |
| + fx.srv.seenMu.Lock() |
| + clear(fx.srv.seen) |
| + fx.srv.seenMu.Unlock() |
| + if _, err := fx.st.db.Exec(`UPDATE users SET last_seen = 0 WHERE address = ?`, address); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// TestLastSeenAfterARollThroughTheRealRoutes is the flagship report's |
| +// witness (People showed "not yet" for a person who had used ship, promote |
| +// and run since the roll): through the console's own wiring, a person's CLI |
| +// token on the deploy doors and a browser session on an app page and on |
| +// People each set users.last_seen on a console that has just started. |
| +func TestLastSeenAfterARollThroughTheRealRoutes(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + shipVersion(t, fx, "kass", "v3") |
| + seedChannel(t, fx, "kass", "beta", "v3") |
| + tok := cliToken(t, fx, lastSeenPaul, "code-"+t.Name()) |
| + |
| + for _, door := range []string{ |
| + "/api/cli/apps/" + fx.sqid + "/kass/channels", |
| + "/api/cli/apps/" + fx.sqid + "/kass/releases", |
| + "/api/cli/apps", |
| + } { |
| + rollSeen(t, fx, lastSeenPaul) |
| + if status, out := getJSON(t, fx.ts.URL+door, tok); status != http.StatusOK { |
| + t.Fatalf("GET %s with Paul's CLI token = %d %v", door, status, out) |
| + } |
| + if seen, _ := lastSeenOf(t, fx, lastSeenPaul); seen == 0 { |
| + t.Fatalf("GET %s with Paul's CLI token left last_seen 0", door) |
| + } |
| + } |
| + |
| + // A promote: the deploy door's POST. |
| + rollSeen(t, fx, lastSeenPaul) |
| + status, out := postJSON(t, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/kass/promote", |
| + map[string]string{"channel": "canary/x", "version": "v3"}, tok) |
| + if status != http.StatusOK { |
| + t.Fatalf("POST promote with Paul's CLI token = %d %v", status, out) |
| + } |
| + if seen, _ := lastSeenOf(t, fx, lastSeenPaul); seen == 0 { |
| + t.Fatal("POST promote with Paul's CLI token left last_seen 0") |
| + } |
| + |
| + browser := signInPaul(t, fx) |
| + if err := fx.st.SetOperator(lastSeenPaul, true); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, page := range []string{"/apps/kass", "/fleet/people"} { |
| + rollSeen(t, fx, lastSeenPaul) |
| + u := fx.ts.URL + page |
| + if !strings.HasPrefix(page, "/fleet") { |
| + u = fx.u(page) |
| + } |
| + status, _, body := get(t, browser, u) |
| + if status != http.StatusOK { |
| + t.Fatalf("GET %s = %d", page, status) |
| + } |
| + if seen, _ := lastSeenOf(t, fx, lastSeenPaul); seen == 0 { |
| + t.Fatalf("GET %s in a browser session left last_seen 0", page) |
| + } |
| + if page == "/fleet/people" && strings.Contains(body, ">not yet<") { |
| + t.Fatalf("People shows the viewer as not yet seen:\n%s", body) |
| + } |
| + } |
| +} |
| + |
| +// TestLastSeenOnTheGatedStore: with CARLOS_HOST_CLAIM on, the database |
| +// opens gated (OpenGated) and users is a NonApp table; the gate does not |
| +// refuse the last-seen write on either path. |
| +func TestLastSeenOnTheGatedStore(t *testing.T) { |
| + cx := newClaimCase(t) |
| + if !cx.srv.cfg.HostClaim { |
| + t.Fatal("the claim console is not enabled") |
| + } |
| + addr := lastSeenPaul |
| + for name, do := range map[string]func(){ |
| + "a CLI token": func() { cx.apiReply(t, http.MethodGet, "/api/cli/apps", "") }, |
| + "a session": func() { cx.pageReply(t, "/settings") }, |
| + } { |
| + rollSeen(t, cx.consoleFixture, addr) |
| + do() |
| + if seen, ok := lastSeenOf(t, cx.consoleFixture, addr); !ok || seen == 0 { |
| + t.Errorf("%s on the gated store left last_seen %d (row %v)", name, seen, ok) |
| + } |
| + } |
| +} |
diff --git a/internal/console/opactivity.go b/internal/console/opactivity.go| index 7362792a9..0e3deae2c 100644 |
| --- a/internal/console/opactivity.go |
| +++ b/internal/console/opactivity.go |
| @@ -6,10 +6,12 @@ import ( |
| "net/http" |
| "net/url" |
| "strconv" |
| + "strings" |
| ) |
| // Activity (/fleet/activity, spec 2026-10-25 Part 3): every audit row on the |
| -// platform, newest first, filtered by kind and by account, fifty to a page |
| +// platform, newest first, filtered by kind, by account and by person (who), |
| +// fifty to a page |
| // with Newest and Older links keyed on the row id. SQLite only: no bucket |
| // read, no remote call. |
| @@ -61,32 +63,36 @@ func (k feedKind) filter() ActivityFilter { |
| } |
| // feedQuery is the page's parameters, parsed and clamped. Account is the |
| -// sqid as given; the handler resolves it. |
| +// sqid as given and Who the address as given; the handler resolves each. |
| type feedQuery struct { |
| - Kind, Account string |
| - Before int64 |
| + Kind, Account, Who string |
| + Before int64 |
| } |
| -// parseFeedQuery reads kind, account and before: an unknown kind is "all"; |
| -// before is a positive integer, else 0; account is kept as text. |
| +// parseFeedQuery reads kind, account, who and before: an unknown kind is |
| +// "all"; before is a positive integer, else 0; account and who are kept as |
| +// text, who trimmed. |
| func parseFeedQuery(v url.Values) feedQuery { |
| - q := feedQuery{Kind: feedKindOf(v.Get("kind")).Key, Account: v.Get("account")} |
| + q := feedQuery{Kind: feedKindOf(v.Get("kind")).Key, Account: v.Get("account"), Who: strings.TrimSpace(v.Get("who"))} |
| if n, err := strconv.ParseInt(v.Get("before"), 10, 64); err == nil && n > 0 { |
| q.Before = n |
| } |
| return q |
| } |
| -// href is the feed's URL with q's kind and account (each when set), and |
| -// before when it is positive. |
| +// href is the feed's URL with q's kind (unless it is the default, or ""), |
| +// account and who (each when set), and before when it is positive. |
| func (q feedQuery) href() string { |
| v := url.Values{} |
| - if q.Kind != feedKinds[0].Key { |
| + if q.Kind != "" && q.Kind != feedKinds[0].Key { |
| v.Set("kind", q.Kind) |
| } |
| if q.Account != "" { |
| v.Set("account", q.Account) |
| } |
| + if q.Who != "" { |
| + v.Set("who", q.Who) |
| + } |
| if q.Before > 0 { |
| v.Set("before", strconv.FormatInt(q.Before, 10)) |
| } |
| @@ -96,36 +102,53 @@ func (q feedQuery) href() string { |
| return "/fleet/activity" |
| } |
| -// AccountHref is the feed of one account, keeping the kind: where a row's |
| -// account name links. |
| +// AccountHref is the feed of one account, keeping the kind and the person: |
| +// where a row's account name links. |
| func (q feedQuery) AccountHref(sqid string) string { |
| - return feedQuery{Kind: q.Kind, Account: sqid}.href() |
| + return feedQuery{Kind: q.Kind, Account: sqid, Who: q.Who}.href() |
| } |
| -// ClearAccountHref is the feed without the account filter, keeping the kind. |
| +// ClearAccountHref is the feed without the account filter, keeping the kind |
| +// and the person. |
| func (q feedQuery) ClearAccountHref() string { |
| - return feedQuery{Kind: q.Kind}.href() |
| + return feedQuery{Kind: q.Kind, Who: q.Who}.href() |
| +} |
| + |
| +// ClearWhoHref is the feed without the person filter, keeping the kind and |
| +// the account. |
| +func (q feedQuery) ClearWhoHref() string { |
| + return feedQuery{Kind: q.Kind, Account: q.Account}.href() |
| +} |
| + |
| +// first is q on its first page: before dropped. |
| +func (q feedQuery) first() feedQuery { |
| + q.Before = 0 |
| + return q |
| } |
| // feedView is the page's data (page.Feed). AccountName is the filter line's |
| // name when an account filter is on: the account's name, or the sqid as |
| // given when no account has it. AccountDeleted marks a deleted account. |
| +// Who is the person line's address when a person filter is on: the |
| +// person's stored address, or the address as given, lower-cased, when no |
| +// one has it; WhoHref is their page, "" when no one has it. |
| type feedView struct { |
| Query feedQuery |
| Kind opDropdown |
| AccountName string |
| AccountDeleted bool |
| + Who, WhoHref string |
| Rows []FeedRow |
| Pager opPager |
| } |
| // feedDropdown is the kind filter: the current kind as its label, each |
| -// kind's link keeping the account and dropping before. |
| +// kind's link keeping the account and the person and dropping before. |
| func feedDropdown(q feedQuery) opDropdown { |
| cur := feedKindOf(q.Kind) |
| d := opDropdown{Label: cur.Label, Aria: fmt.Sprintf("Filter by kind: %s", cur.Label)} |
| for _, k := range feedKinds { |
| - d.Items = append(d.Items, opTab{Label: k.Label, Href: feedQuery{Kind: k.Key, Account: q.Account}.href(), Current: k.Key == cur.Key}) |
| + d.Items = append(d.Items, opTab{Label: k.Label, Href: feedQuery{Kind: k.Key, Account: q.Account, Who: q.Who}.href(), Current: k.Key == cur.Key}) |
| } |
| return d |
| } |
| @@ -135,7 +158,10 @@ func feedDropdown(q feedQuery) opDropdown { |
| // know whether Older exists. The account filter is resolved whatever the |
| // account's deleted_at (OperatorAccountBySqid), so a deleted account's |
| // history stays reachable from its links; a sqid with no row shows nothing. |
| -// A failed read is a 500, since an empty feed would say nothing happened. |
| +// The person filter is resolved as the person page resolves its address |
| +// (operatorPersonNamed); an address no one has is matched lower-cased, and |
| +// finds whatever rows that address made. A failed read is a 500, since an |
| +// empty feed would say nothing happened. |
| func (s *Server) handleActivity(w http.ResponseWriter, r *http.Request) { |
| addr, raw, ok := s.operatorOnly(w, r) |
| if !ok { |
| @@ -143,9 +169,27 @@ func (s *Server) handleActivity(w http.ResponseWriter, r *http.Request) { |
| } |
| q := parseFeedQuery(r.URL.Query()) |
| p := s.opPage(addr, raw, "activity") |
| - v := &feedView{Query: q, Kind: feedDropdown(q)} |
| + |
| + // The person first: every link the page builds carries the address as |
| + // resolved, whatever case it was typed in. |
| + var actor, whoHref string |
| + if q.Who != "" { |
| + person, err := s.operatorPersonNamed(q.Who) |
| + if err != nil { |
| + log.Printf("console: activity person %q: %v", q.Who, err) |
| + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) |
| + return |
| + } |
| + actor = opCanonicalAddress(q.Who) |
| + if person != nil { |
| + actor, whoHref = person.Address, opPersonPath(person.Address) |
| + } |
| + q.Who = actor |
| + } |
| + v := &feedView{Query: q, Kind: feedDropdown(q), Who: actor, WhoHref: whoHref} |
| f := feedKindOf(q.Kind).filter() |
| + f.Actor = actor |
| if q.Account != "" { |
| a, err := s.store.OperatorAccountBySqid(q.Account) |
| if err != nil { |
| @@ -172,10 +216,11 @@ func (s *Server) handleActivity(w http.ResponseWriter, r *http.Request) { |
| } |
| v.Rows = rows |
| if q.Before > 0 { |
| - v.Pager.Items = append(v.Pager.Items, opPageItem{Label: "Newest", Href: feedQuery{Kind: q.Kind, Account: q.Account}.href()}) |
| + v.Pager.Items = append(v.Pager.Items, opPageItem{Label: "Newest", Href: q.first().href()}) |
| } |
| if older { |
| - next := feedQuery{Kind: q.Kind, Account: q.Account, Before: rows[len(rows)-1].ID} |
| + next := q.first() |
| + next.Before = rows[len(rows)-1].ID |
| v.Pager.Items = append(v.Pager.Items, opPageItem{Label: "Older", Href: next.href()}) |
| } |
| p.Feed = v |
diff --git a/internal/console/opactivity_test.go b/internal/console/opactivity_test.go| index 396d5e3e9..83c13c1b3 100644 |
| --- a/internal/console/opactivity_test.go |
| +++ b/internal/console/opactivity_test.go |
| @@ -14,13 +14,15 @@ import ( |
| // Activity at /fleet/activity (opactivity.go, templates/ops_activity.html). |
| -// feedRow is one rendered row's cells: who, the account cell's markup, |
| -// what and the app cell's markup. |
| -type feedRow struct{ Who, Account, What, App string } |
| +// feedRow is one rendered row's cells: who, where who links ("" for no |
| +// link), the account cell's markup, what and the app cell's markup. |
| +type feedRow struct{ Who, WhoHref, Account, What, App string } |
| +// feedRowCells is one row: When; Who, a link to the person page or plain |
| +// text; the account; What on one line (op_what's plain form); the app. |
| var feedRowCells = regexp.MustCompile(`^><span class="rst-cell-mut" title="[^"]*">[^<]*</span>` + |
| - `<span>([^<]*)</span>(<a href="[^"]*">[^<]*</a>|<span class="rst-cell-mut">none</span>)` + |
| - `<span>([^<]*)</span>(<span>[^<]*</span>|<span class="rst-cell-mut">none</span>)</div>`) |
| + `(?:<a href="([^"]*)">([^<]*)</a>|<span>([^<]*)</span>)(<a href="[^"]*">[^<]*</a>|<span class="rst-cell-mut">none</span>)` + |
| + `<span co-clip(?: title="[^"]*")?>([^<]*)</span>(<span>[^<]*</span>|<span class="rst-cell-mut">none</span>)</div>`) |
| // feedRows is the page's rows, newest first, each parsed to its cells. |
| func feedRows(t *testing.T, body string) []feedRow { |
| @@ -35,7 +37,8 @@ func feedRows(t *testing.T, body string) []feedRow { |
| if m == nil { |
| t.Fatalf("a feed row is not When, Who, Account, What, App: %s", r) |
| } |
| - out = append(out, feedRow{Who: html.UnescapeString(m[1]), Account: m[2], What: html.UnescapeString(m[3]), App: m[4]}) |
| + out = append(out, feedRow{Who: html.UnescapeString(m[2] + m[3]), WhoHref: html.UnescapeString(m[1]), |
| + Account: m[4], What: html.UnescapeString(m[5]), App: m[6]}) |
| } |
| return out |
| } |
diff --git a/internal/console/opdashboard_test.go b/internal/console/opdashboard_test.go| index 4d1152053..731617eba 100644 |
| --- a/internal/console/opdashboard_test.go |
| +++ b/internal/console/opdashboard_test.go |
| @@ -614,7 +614,7 @@ func TestDashboardLatestActivityAndNewestPeople(t *testing.T) { |
| } |
| for i, f := range feed { |
| r := rows[i+1] |
| - if !strings.Contains(r, "<span>"+f.Address+"</span>") || !strings.Contains(r, "<span>"+f.Detail+"</span>") { |
| + if !strings.Contains(r, `<a href="/fleet/people/`+f.Address+`">`+f.Address+"</a>") || !strings.Contains(r, "<span co-clip>"+f.Detail+"</span>") { |
| t.Errorf("activity row %d is not feed row %d (%s %s): %s", i+1, f.ID, f.Address, f.Detail, r) |
| } |
| } |
| @@ -623,7 +623,7 @@ func TestDashboardLatestActivityAndNewestPeople(t *testing.T) { |
| } |
| var signin, promotes string |
| for _, r := range rows[1:] { |
| - if strings.Contains(r, "<span>Signed in</span>") { |
| + if strings.Contains(r, "<span co-clip>Signed in</span>") { |
| signin = r |
| } |
| if strings.Contains(r, " live</span>") { |
| @@ -653,7 +653,7 @@ func TestDashboardLatestActivityAndNewestPeople(t *testing.T) { |
| } |
| for i, w := range want { |
| r := people[i+1] |
| - if !strings.Contains(r, `<span class="rst-nm">`+w[0]+`</span>`) || !strings.Contains(r, w[1]) { |
| + if !strings.Contains(r, `<a class="rst-nm" href="/fleet/people/`+w[0]+`">`+w[0]+`</a>`) || !strings.Contains(r, w[1]) { |
| t.Errorf("people row %d = %s, want %s with %s", i+1, r, w[0], w[1]) |
| } |
| } |
diff --git a/internal/console/oppeople_test.go b/internal/console/oppeople_test.go| index 544b7090d..4768e5fae 100644 |
| --- a/internal/console/oppeople_test.go |
| +++ b/internal/console/oppeople_test.go |
| @@ -90,7 +90,7 @@ func TestPeoplePageListsPeopleAndAccounts(t *testing.T) { |
| t.Errorf("no row for %s", p.addr) |
| continue |
| } |
| - wants := []string{`<span class="rst-nm">` + p.addr + `</span>`, peopleTitle(w.now.Add(-p.joined)), fmt.Sprintf("<span>%d</span>", p.accounts)} |
| + wants := []string{`<a class="rst-nm" href="/fleet/people/` + p.addr + `">` + p.addr + `</a>`, peopleTitle(w.now.Add(-p.joined)), fmt.Sprintf("<span>%d</span>", p.accounts)} |
| if p.seen { |
| wants = append(wants, peopleTitle(w.now)) |
| } else { |
diff --git a/internal/console/opperson.go b/internal/console/opperson.go| new file mode 100644 |
| index 000000000..e0fd45ce6 |
| --- /dev/null |
| +++ b/internal/console/opperson.go |
| @@ -0,0 +1,135 @@ |
| +package console |
| + |
| +import ( |
| + "log" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + "time" |
| +) |
| + |
| +// One person (/fleet/people/{address}): their address as the page's |
| +// heading, when they joined and were last seen, how many accounts they are |
| +// in and apps they made, each of those accounts with their role, and their |
| +// latest activity. SQLite only: no bucket read, no remote call, and no |
| +// write of its own (copy record 2026-10-27-operator-people-detail-copy.md). |
| + |
| +// personFeedSize is the most activity rows the page shows; the rest are on |
| +// Activity, filtered to the person. |
| +const personFeedSize = 20 |
| + |
| +// The band's words: OPS-156, and the labels it shares with the dashboard |
| +// and People (OPS-55, OPS-111, OPS-112, and OPS-113's "not yet"). |
| +const ( |
| + personStatApps = "Apps created" |
| + personJoined = "Joined" |
| + personLastSeen = "Last seen" |
| + personAccounts = "Accounts" |
| + personNeverSeen = "not yet" |
| +) |
| + |
| +// opPersonPath is the person page of address: its path, the address |
| +// escaped as one segment. The people lists link every row here. |
| +func opPersonPath(address string) string { |
| + return "/fleet/people/" + url.PathEscape(address) |
| +} |
| + |
| +// opPersonHref is where an audit row's actor links: the person page when |
| +// the actor is an address, "" when it names no person (a service, an app |
| +// credential, the console itself). It is the template func opPersonHref. |
| +func opPersonHref(actor string) string { |
| + if !ValidAddress(actor) { |
| + return "" |
| + } |
| + return opPersonPath(actor) |
| +} |
| + |
| +// opCanonicalAddress is address in the form users rows store a typed |
| +// address (canonicalAddress): trimmed and lower-cased. |
| +func opCanonicalAddress(address string) string { |
| + return strings.ToLower(strings.TrimSpace(address)) |
| +} |
| + |
| +// operatorPersonNamed is the person an operator's URL names: the users row |
| +// with exactly that address when there is one (every link the pages build |
| +// carries a row's stored address, so a row made before addresses were |
| +// lower-cased is reached by its own link even beside a lower-cased twin), |
| +// else the row with the address lower-cased, as canonicalAddress stores a |
| +// typed one. nil when neither exists. |
| +func (s *Server) operatorPersonNamed(address string) (*PersonDetail, error) { |
| + raw := strings.TrimSpace(address) |
| + if raw == "" { |
| + return nil, nil |
| + } |
| + p, err := s.store.OperatorPerson(raw) |
| + if err != nil || p != nil { |
| + return p, err |
| + } |
| + if canon := opCanonicalAddress(raw); canon != raw { |
| + return s.store.OperatorPerson(canon) |
| + } |
| + return nil, nil |
| +} |
| + |
| +// opAgo is a past instant as the ago template func writes it. |
| +func opAgo(t time.Time) string { return humanAge(time.Since(t)) + " ago" } |
| + |
| +// personView is the page's data (page.Person). |
| +type personView struct { |
| + Person *PersonDetail |
| + Stats []opStat |
| + Feed []FeedRow |
| + ActivityRef string |
| +} |
| + |
| +// personStats is the band: joined, last seen, accounts, apps created. |
| +func personStats(p *PersonDetail) []opStat { |
| + seen := opStat{Label: personLastSeen, Value: personNeverSeen} |
| + if !p.LastSeen.IsZero() { |
| + seen.Value, seen.Note = opAgo(p.LastSeen), p.LastSeen.Format("2006-01-02 15:04 UTC") |
| + } |
| + return []opStat{ |
| + {Label: personJoined, Value: opAgo(p.Joined), Note: p.Joined.Format("2006-01-02 15:04 UTC")}, |
| + seen, |
| + {Label: personAccounts, Value: opNumber(len(p.Accounts))}, |
| + {Label: personStatApps, Value: opNumber(p.Apps)}, |
| + } |
| +} |
| + |
| +// handlePerson serves one person, for signed-in operators only, behind |
| +// operatorOnly's 404-to-everyone gate, which runs before anything is read. |
| +// An address with no users row is the same plain 404, and the page writes |
| +// nothing. A failed read is a 500, since a missing part would say the |
| +// person has no accounts or did nothing. |
| +func (s *Server) handlePerson(w http.ResponseWriter, r *http.Request) { |
| + addr, raw, ok := s.operatorOnly(w, r) |
| + if !ok { |
| + return |
| + } |
| + person, err := s.operatorPersonNamed(r.PathValue("address")) |
| + if err != nil { |
| + log.Printf("console: person %q: %v", r.PathValue("address"), err) |
| + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) |
| + return |
| + } |
| + if person == nil { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + feed, err := s.store.ActivityFeed(ActivityFilter{Actor: person.Address}, 0, personFeedSize) |
| + if err != nil { |
| + log.Printf("console: person %s activity: %v", person.Address, err) |
| + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) |
| + return |
| + } |
| + p := s.opPage(addr, raw, "people") |
| + p.Title = person.Address |
| + p.Op.Up = "/fleet/people" |
| + p.Person = &personView{ |
| + Person: person, |
| + Stats: personStats(person), |
| + Feed: feed, |
| + ActivityRef: feedQuery{Who: person.Address}.href(), |
| + } |
| + s.render(w, http.StatusOK, "ops_person", p) |
| +} |
diff --git a/internal/console/opperson_test.go b/internal/console/opperson_test.go| new file mode 100644 |
| index 000000000..ebfd1400d |
| --- /dev/null |
| +++ b/internal/console/opperson_test.go |
| @@ -0,0 +1,364 @@ |
| +package console |
| + |
| +import ( |
| + "fmt" |
| + "html" |
| + "net/http" |
| + "regexp" |
| + "slices" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// One person at /fleet/people/{address} (opperson.go, |
| +// templates/ops_person.html), and Activity filtered to one person (?who=). |
| + |
| +// personGet is GET /fleet/people/<escaped> as c, which must answer 200. |
| +func personGet(t *testing.T, fx *consoleFixture, c *http.Client, escaped string) string { |
| + t.Helper() |
| + status, _, body := get(t, c, fx.ts.URL+"/fleet/people/"+escaped) |
| + if status != http.StatusOK { |
| + t.Fatalf("/fleet/people/%s = %d:\n%s", escaped, status, body) |
| + } |
| + return body |
| +} |
| + |
| +// personSection is the card under the h2 named title, up to the next h2. |
| +func personSection(t *testing.T, body, title string) string { |
| + t.Helper() |
| + return dashCut(t, body, "<h2>"+title+"</h2>", "<div rst-box-head>") |
| +} |
| + |
| +// opTotalChanges is the store's write count: every row any statement has |
| +// inserted, updated or deleted on its one connection since it opened. |
| +func opTotalChanges(t *testing.T, fx *consoleFixture) int64 { |
| + t.Helper() |
| + var n int64 |
| + if err := fx.st.db.QueryRow(`SELECT total_changes()`).Scan(&n); err != nil { |
| + t.Fatal(err) |
| + } |
| + return n |
| +} |
| + |
| +func TestPersonPageIsOperatorOnly(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + w := seedOperatorWorld(t, fx) |
| + out := newBrowser(t) |
| + ghostStatus, _, ghost := get(t, out, fx.ts.URL+"/this-route-does-not-exist") |
| + if ghostStatus != http.StatusNotFound { |
| + t.Fatalf("sanity: missing route = %d", ghostStatus) |
| + } |
| + notOperator := newBrowser(t) |
| + fx.setUser("cat@example.com") |
| + signUp(t, fx, notOperator, "code-"+t.Name()) |
| + for _, path := range []string{"/fleet/people/ann@example.com", "/fleet/people/nobody@example.com", |
| + "/fleet/activity?who=ann@example.com"} { |
| + for who, c := range map[string]*http.Client{"signed out": out, "not an operator": notOperator} { |
| + if st, _, body := get(t, c, fx.ts.URL+path); st != ghostStatus || body != ghost { |
| + t.Errorf("%s %s = %d %q, want the missing-route 404", path, who, st, body) |
| + } |
| + } |
| + } |
| + // The operator sees the page, in the shell, under People and accounts. |
| + body := personGet(t, fx, w.c, "ann@example.com") |
| + assertOpShell(t, "/fleet/people/ann@example.com", body) |
| +} |
| + |
| +// TestPersonPageUnknownAddressWritesNothing: an address with no users row |
| +// is the missing-route 404, and the request writes no row anywhere. The |
| +// operator's own last-seen hour is reserved by a first request, so the |
| +// gate has nothing to write either. |
| +func TestPersonPageUnknownAddressWritesNothing(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + w := seedOperatorWorld(t, fx) |
| + ghostStatus, _, ghost := get(t, newBrowser(t), fx.ts.URL+"/this-route-does-not-exist") |
| + personGet(t, fx, w.c, "ann@example.com") |
| + for _, path := range []string{"nobody@example.com", "NOBODY@example.com", "%20", "x%2Fy@example.com"} { |
| + before, seen := opTotalChanges(t, fx), fx.srv.lastSeenWrites.Load() |
| + st, _, body := get(t, w.c, fx.ts.URL+"/fleet/people/"+path) |
| + if st != ghostStatus || body != ghost { |
| + t.Errorf("/fleet/people/%s = %d %q, want the missing-route 404", path, st, body) |
| + } |
| + if after := opTotalChanges(t, fx); after != before { |
| + t.Errorf("/fleet/people/%s changed %d rows, want none", path, after-before) |
| + } |
| + if got := fx.srv.lastSeenWrites.Load(); got != seen { |
| + t.Errorf("/fleet/people/%s wrote last_seen", path) |
| + } |
| + } |
| + var n int |
| + if err := fx.st.db.QueryRow(`SELECT COUNT(*) FROM users WHERE lower(address) = 'nobody@example.com'`).Scan(&n); err != nil || n != 0 { |
| + t.Fatalf("users rows for nobody@example.com = %d (%v), want none", n, err) |
| + } |
| +} |
| + |
| +func TestPersonPageShowsThePerson(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + w := seedOperatorWorld(t, fx) |
| + // After shop's membership, which minting stamped on the wall clock. |
| + if err := fx.st.AddMember(w.notes.ID, "ann@example.com", RoleMember, time.Now().Add(time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + // A row by someone else, which ann's page must not show. |
| + if err := fx.st.RecordActivity(w.shop.ID, "shop", "cat@example.com", Activity{Action: "rename", Detail: "Renamed by cat"}, w.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + body := personGet(t, fx, w.c, "ann@example.com") |
| + |
| + if !strings.Contains(body, "<h1>ann@example.com</h1>") || !strings.Contains(body, "<title>ann@example.com") { |
| + t.Errorf("the page is not headed by the address:\n%s", dashCut(t, body, "<header rst-page-header>", "</header>")) |
| + } |
| + if !strings.Contains(body, "<p rst-page-header-sub>Their accounts and latest activity.</p>") { |
| + t.Error("no subhead") |
| + } |
| + stats := dashCut(t, body, "<div rst-stats rst-card>", "<div rst-box-head>") |
| + for _, want := range []string{ |
| + `<span rst-stat-label>Joined</span><span rst-stat-num>`, |
| + `<span rst-stat-label>Last seen</span><span rst-stat-num>`, |
| + `<span rst-stat-label>Accounts</span><span rst-stat-num>2</span>`, |
| + `<span rst-stat-label>Apps created</span><span rst-stat-num>1</span>`, |
| + `<span rst-stat-note>` + w.now.Format("2006-01-02 15:04 UTC") + `</span>`, |
| + } { |
| + if !strings.Contains(stats, want) { |
| + t.Errorf("the band has no %s:\n%s", want, stats) |
| + } |
| + } |
| + if strings.Contains(stats, "not yet") { |
| + t.Errorf("ann was seen, the band says not yet:\n%s", stats) |
| + } |
| + |
| + accounts := personSection(t, body, "Accounts") |
| + if !strings.Contains(accounts, "<span>Account</span><span>Role</span><span>Plan</span><span>Apps</span>") { |
| + t.Errorf("accounts head:\n%s", accounts) |
| + } |
| + shopRow := fmt.Sprintf(`<a class="rst-nm" href="/fleet/activity?account=%s">shop</a><span>owner</span>`, w.shop.Sqid) |
| + notesRow := fmt.Sprintf(`<a class="rst-nm" href="/fleet/activity?account=%s">notes</a><span>member</span>`, w.notes.Sqid) |
| + si, ni := strings.Index(accounts, shopRow), strings.Index(accounts, notesRow) |
| + if si < 0 || ni < 0 || si > ni { |
| + t.Errorf("accounts are not shop (owner) then notes (member), in the order ann joined them:\n%s", accounts) |
| + } |
| + if !strings.Contains(accounts[si:], "<span>1</span></div>") { |
| + t.Errorf("shop's row does not count its one app:\n%s", accounts) |
| + } |
| + |
| + activity := personSection(t, body, "Latest activity") |
| + if !strings.Contains(activity, `<a rst-btn="ghost" href="/fleet/activity?who=ann%40example.com">All their activity</a>`) { |
| + t.Errorf("no link to all of ann's activity:\n%s", activity) |
| + } |
| + if !strings.Contains(activity, "<span>When</span><span>Account</span><span>What</span><span>App</span>") { |
| + t.Errorf("activity head:\n%s", activity) |
| + } |
| + for _, want := range []string{"<span co-clip>Made v2 live</span>", "<span co-clip>Invited dan@example.com</span>"} { |
| + if !strings.Contains(activity, want) { |
| + t.Errorf("ann's activity has no %s:\n%s", want, activity) |
| + } |
| + } |
| + for _, not := range []string{"Renamed by cat", "Made v1 live", "Signed in<"} { |
| + if strings.Contains(activity, not) { |
| + t.Errorf("ann's activity shows someone else's %q:\n%s", not, activity) |
| + } |
| + } |
| + |
| + // The same person whatever the case of the URL. |
| + if b := personGet(t, fx, w.c, "Ann@Example.COM"); !strings.Contains(b, "<h1>ann@example.com</h1>") { |
| + t.Error("Ann@Example.COM is not ann@example.com's page") |
| + } |
| + |
| + // Someone with no account and nothing done. |
| + body = personGet(t, fx, w.c, "dan@example.com") |
| + for _, want := range []string{ |
| + `<span rst-stat-label>Last seen</span><span rst-stat-num>not yet</span>`, |
| + `<span rst-stat-label>Accounts</span><span rst-stat-num>0</span>`, |
| + "<p rst-empty-body>Not a member of any account.</p>", |
| + "<p rst-empty-body>No activity yet.</p>", |
| + } { |
| + if !strings.Contains(body, want) { |
| + t.Errorf("dan's page has no %s", want) |
| + } |
| + } |
| +} |
| + |
| +func TestPersonPageShowsTwentyRows(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + w := seedOperatorWorld(t, fx) |
| + for i := 0; i < 30; i++ { |
| + if err := fx.st.RecordActivity(w.shop.ID, "shop", "ann@example.com", |
| + Activity{Action: "env-set", Detail: fmt.Sprintf("Set variable %02d", i)}, w.now.Add(time.Duration(i)*time.Second)); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + activity := personSection(t, personGet(t, fx, w.c, "ann@example.com"), "Latest activity") |
| + if n := strings.Count(activity, "<div rst-lrow>"); n != personFeedSize { |
| + t.Fatalf("%d activity rows, want %d", n, personFeedSize) |
| + } |
| + if !strings.Contains(activity, "Set variable 29") || strings.Contains(activity, "Set variable 09<") { |
| + t.Errorf("the rows are not the newest twenty:\n%s", activity) |
| + } |
| +} |
| + |
| +var opPersonLink = regexp.MustCompile(`<a class="rst-nm" href="(/fleet/people/[^"]*)">([^<]*)</a>`) |
| + |
| +// TestPersonLinksRoundTrip: every people-list link reaches its person's |
| +// page, an address with a slash and a quote included: each is escaped as |
| +// one path segment, and the page names the stored address. |
| +func TestPersonLinksRoundTrip(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + w := seedOperatorWorld(t, fx) |
| + odd := "o'brien/ops+1@example.com" |
| + if _, err := fx.st.EnsureUser(odd, w.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + links := opPersonLink.FindAllStringSubmatch(peopleGet(t, fx, w.c, "/fleet/people"), -1) |
| + links = append(links, opPersonLink.FindAllStringSubmatch(dashGet(t, fx, w.c), -1)...) |
| + found := false |
| + for _, m := range links { |
| + href, addr := html.UnescapeString(m[1]), html.UnescapeString(m[2]) |
| + if addr == odd { |
| + found = true |
| + if href != "/fleet/people/o%27brien%2Fops+1@example.com" { |
| + t.Errorf("%s links to %s", odd, href) |
| + } |
| + } |
| + status, _, body := get(t, w.c, fx.ts.URL+href) |
| + h1 := regexp.MustCompile(`<h1>([^<]*)</h1>`).FindStringSubmatch(body) |
| + if status != http.StatusOK || h1 == nil || html.UnescapeString(h1[1]) != addr { |
| + t.Errorf("%s (%s) = %d %q, want %s's page", href, addr, status, h1, addr) |
| + } |
| + } |
| + if !found { |
| + t.Fatalf("no people-list link names %s", odd) |
| + } |
| +} |
| + |
| +// TestWhoLinksOnlyPeople: Activity's and the dashboard's Who links a |
| +// person's address to their page; a service's name stays text. |
| +func TestWhoLinksOnlyPeople(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + w := seedOperatorWorld(t, fx) |
| + if err := fx.st.RecordActivity(w.shop.ID, "shop", "service:"+w.shop.Sqid+"/ci", |
| + Activity{Action: "promote", Detail: "Made v3 live"}, w.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + for path, body := range map[string]string{"/fleet/activity": peopleGet(t, fx, w.c, "/fleet/activity"), "/fleet": dashGet(t, fx, w.c)} { |
| + if !strings.Contains(body, "<span>service:"+w.shop.Sqid+"/ci</span>") { |
| + t.Errorf("%s: the service's Who is not plain text", path) |
| + } |
| + if strings.Contains(body, `href="/fleet/people/service`) { |
| + t.Errorf("%s: the service's Who links to a person page", path) |
| + } |
| + if !strings.Contains(body, `<a href="/fleet/people/ann@example.com">ann@example.com</a>`) { |
| + t.Errorf("%s: ann's Who is not a link to her page", path) |
| + } |
| + } |
| +} |
| + |
| +func TestActivityFiltersByPerson(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + w := seedOperatorWorld(t, fx) |
| + feedSeedMore(t, fx, w, 60) // ann's: 60 more rows on shop |
| + |
| + // Any case finds ann; the line names her, links to her page and clears. |
| + body := peopleGet(t, fx, w.c, "/fleet/activity?who=ANN@example.com") |
| + rows := feedRows(t, body) |
| + if len(rows) != feedPageSize { |
| + t.Fatalf("%d rows, want a full page of ann's", len(rows)) |
| + } |
| + for _, r := range rows { |
| + if r.Who != "ann@example.com" || r.WhoHref != "/fleet/people/ann@example.com" { |
| + t.Fatalf("a row by %q (%q) in ann's feed", r.Who, r.WhoHref) |
| + } |
| + } |
| + line := `Showing only <a href="/fleet/people/ann@example.com">ann@example.com</a>. <a href="/fleet/activity">Show all people</a>` |
| + if !strings.Contains(body, line) { |
| + t.Errorf("no person filter line %q in:\n%s", line, feedFilterLine(body)) |
| + } |
| + older := feedPagerLink(body, "Older") |
| + if !strings.Contains(older, "who=ann%40example.com") { |
| + t.Errorf("Older drops the person: %q", older) |
| + } |
| + more := feedRows(t, peopleGet(t, fx, w.c, older)) |
| + for _, r := range more { |
| + if r.Who != "ann@example.com" { |
| + t.Fatalf("a row by %q on ann's second page", r.Who) |
| + } |
| + } |
| + if ids, _ := feedAudit(t, fx, "address = ?", "ann@example.com"); len(more) != len(ids)-feedPageSize { |
| + t.Errorf("ann's second page has %d rows, want the %d after her first page", len(more), len(ids)-feedPageSize) |
| + } |
| + |
| + // With a kind: her deploy only. The kind's links keep the person, and |
| + // an account link in a row keeps both. |
| + body = peopleGet(t, fx, w.c, "/fleet/activity?who=ann@example.com&kind=deploys") |
| + if got := feedWhats(feedRows(t, body)); len(got) != 1 || got[0] != "Made v2 live" { |
| + t.Errorf("ann's deploys = %q, want [Made v2 live]", got) |
| + } |
| + if !strings.Contains(body, "kind=signins&who=ann%40example.com") { |
| + t.Error("the kind dropdown drops the person") |
| + } |
| + if !strings.Contains(body, fmt.Sprintf("account=%s&kind=deploys&who=ann%%40example.com", w.shop.Sqid)) { |
| + t.Error("a row's account link drops the person") |
| + } |
| + // Account and person together: both lines, each clearing only itself. |
| + body = peopleGet(t, fx, w.c, fmt.Sprintf("/fleet/activity?who=ann@example.com&account=%s", w.notes.Sqid)) |
| + if rows := feedRows(t, body); len(rows) != 0 { |
| + t.Errorf("ann has %d rows in notes, want none", len(rows)) |
| + } |
| + if !strings.Contains(body, fmt.Sprintf(`<a href="/fleet/activity?who=ann%%40example.com">Show all accounts</a>`)) || |
| + !strings.Contains(body, fmt.Sprintf(`<a href="/fleet/activity?account=%s">Show all people</a>`, w.notes.Sqid)) { |
| + t.Errorf("the two clear links do not each keep the other filter:\n%s", body) |
| + } |
| + |
| + // No one has the address: the line names it, unlinked, and nothing shows. |
| + body = peopleGet(t, fx, w.c, "/fleet/activity?who=Nobody@Example.com") |
| + if !strings.Contains(body, `Showing only nobody@example.com. <a href="/fleet/activity">Show all people</a>`) { |
| + t.Errorf("an unknown person's line: %q", feedFilterLine(body)) |
| + } |
| + if !strings.Contains(body, "No activity matches these filters.") { |
| + t.Error("an unknown person's feed is not empty") |
| + } |
| +} |
| + |
| +// TestPersonLookupPrefersTheExactAddress: a row made before addresses were |
| +// lower-cased (Ann@example.com) beside its lower-cased twin: each one's own |
| +// link, on the person page and in Activity's ?who=, reaches that row, and |
| +// a case no row has falls back to the lower-cased one. |
| +func TestPersonLookupPrefersTheExactAddress(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + w := seedOperatorWorld(t, fx) |
| + const legacy = "Ann@example.com" |
| + if _, err := fx.st.EnsureUser(legacy, w.now.Add(-time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.st.AddMember(w.notes.ID, legacy, RoleMember, w.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.st.RecordActivity(w.notes.ID, "notes", legacy, Activity{Action: "rename", Detail: "Renamed by the legacy row"}, w.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + shopLink := fmt.Sprintf(`href="/fleet/activity?account=%s">shop</a>`, w.shop.Sqid) |
| + notesLink := fmt.Sprintf(`href="/fleet/activity?account=%s">notes</a>`, w.notes.Sqid) |
| + for _, c := range []struct { |
| + path, h1, has, hasNot, did, didNot string |
| + }{ |
| + {legacy, legacy, notesLink, shopLink, "Renamed by the legacy row", "Made v2 live"}, |
| + {"ann@example.com", "ann@example.com", shopLink, notesLink, "Made v2 live", "Renamed by the legacy row"}, |
| + {"ANN@example.com", "ann@example.com", shopLink, notesLink, "Made v2 live", "Renamed by the legacy row"}, |
| + } { |
| + body := personGet(t, fx, w.c, c.path) |
| + accounts := personSection(t, body, "Accounts") |
| + activity := personSection(t, body, "Latest activity") |
| + if !strings.Contains(body, "<h1>"+c.h1+"</h1>") || !strings.Contains(accounts, c.has) || strings.Contains(accounts, c.hasNot) || |
| + !strings.Contains(activity, c.did) || strings.Contains(activity, c.didNot) { |
| + t.Errorf("/fleet/people/%s is not %s's page:\n%s", c.path, c.h1, body) |
| + } |
| + whos := feedWhats(feedRows(t, peopleGet(t, fx, w.c, "/fleet/activity?who="+c.path))) |
| + if !slices.Contains(whos, c.did) || slices.Contains(whos, c.didNot) { |
| + t.Errorf("?who=%s shows %q, want %s's rows", c.path, whos, c.h1) |
| + } |
| + } |
| + // The People list's link for the legacy row carries its own case. |
| + if !strings.Contains(peopleGet(t, fx, w.c, "/fleet/people"), `<a class="rst-nm" href="/fleet/people/Ann@example.com">Ann@example.com</a>`) { |
| + t.Error("People does not link the legacy row by its stored address") |
| + } |
| +} |
diff --git a/internal/console/opstore.go b/internal/console/opstore.go| index 2ee7b60fa..214b0a08e 100644 |
| --- a/internal/console/opstore.go |
| +++ b/internal/console/opstore.go |
| @@ -10,7 +10,8 @@ import ( |
| "time" |
| ) |
| -// The operator pages' reads (/fleet, /fleet/people, /fleet/activity), with |
| +// The operator pages' reads (/fleet, /fleet/people, /fleet/people/{address}, |
| +// /fleet/activity), with |
| // their column and indexes, kept here so the feature is one file to read. |
| // |
| // Every statement below is a package-level constant so that |
| @@ -40,6 +41,9 @@ func (s *Store) migrateOperatorPages() error { |
| `CREATE INDEX IF NOT EXISTS memberships_by_address ON memberships (address, added_at);`, |
| `CREATE INDEX IF NOT EXISTS apps_by_creator ON apps (created_by);`, |
| `CREATE INDEX IF NOT EXISTS audit_by_action ON audit (action, id);`, |
| + // One person's rows, newest first: the person page and Activity's |
| + // ?who= filter. audit.address is the actor. |
| + `CREATE INDEX IF NOT EXISTS audit_by_actor ON audit (address, id);`, |
| } { |
| if _, err := s.db.Exec(stmt); err != nil { |
| return err |
| @@ -131,6 +135,25 @@ LEFT JOIN live ON live.id = page.id |
| LEFT JOIN crew ON crew.id = page.id` |
| opSQLAccountBySqid = `SELECT id, sqid, name, deleted_at FROM accounts WHERE sqid = ?1` |
| + |
| + // One person (/fleet/people/{address}): their users row by its primary |
| + // key; the live apps they created (apps_by_creator); and their live |
| + // accounts, each with their role, its plan and its live apps. As for the |
| + // lists, the memberships are cut first (memberships_by_address) and the |
| + // apps counted for those accounts only. OperatorPerson puts the accounts |
| + // in membership order in Go. |
| + opSQLPerson = `SELECT address, created_at, last_seen FROM users WHERE address = ?1` |
| + opSQLPersonMade = `SELECT COUNT(*) FROM apps WHERE created_by = ?1 AND deleted_at = 0` |
| + opSQLPersonHeld = `WITH held AS MATERIALIZED (SELECT account_id AS id, role, added_at FROM memberships WHERE address = ?1), |
| +live AS (SELECT apps.account_id AS id, COUNT(*) AS n |
| + FROM held CROSS JOIN apps ON apps.account_id = held.id AND apps.deleted_at = 0 |
| + GROUP BY apps.account_id) |
| +SELECT accounts.id, accounts.sqid, accounts.name, held.role, held.added_at, |
| + COALESCE(account_plans.plan, ''), COALESCE(live.n, 0) |
| +FROM held |
| +CROSS JOIN accounts ON accounts.id = held.id AND accounts.deleted_at = 0 |
| +LEFT JOIN account_plans ON account_plans.account_id = held.id |
| +LEFT JOIN live ON live.id = held.id` |
| opSQLTouchLastSeen = `UPDATE users SET last_seen = ?1 WHERE address = ?2 AND last_seen < ?3` |
| // The activity feed, newest first by audit.id, one statement per filter |
| @@ -158,6 +181,17 @@ FROM audit LEFT JOIN accounts ON accounts.id = audit.account_id |
| opSQLFeedOther = opSQLFeedColumns + `WHERE audit.action NOT IN (SELECT value FROM json_each(?1)) ORDER BY audit.id DESC LIMIT ?2` |
| opSQLFeedOtherBefore = opSQLFeedColumns + `WHERE audit.id < ?1 |
| AND audit.action NOT IN (SELECT value FROM json_each(?2)) ORDER BY audit.id DESC LIMIT ?3` |
| + // One person: audit_by_actor. The account (?3, 0 for every account) |
| + // and the action tests are made on each row, with + keeping them off |
| + // audit_by_account and audit_by_action. |
| + opSQLFeedActor = opSQLFeedColumns + `WHERE audit.address = ?1 AND audit.id < ?2 |
| + AND (?3 = 0 OR +audit.account_id = ?3) ORDER BY audit.id DESC LIMIT ?4` |
| + opSQLFeedActorActions = opSQLFeedColumns + `WHERE audit.address = ?1 AND audit.id < ?2 |
| + AND (?3 = 0 OR +audit.account_id = ?3) |
| + AND +audit.action IN (SELECT value FROM json_each(?4)) ORDER BY audit.id DESC LIMIT ?5` |
| + opSQLFeedActorOther = opSQLFeedColumns + `WHERE audit.address = ?1 AND audit.id < ?2 |
| + AND (?3 = 0 OR +audit.account_id = ?3) |
| + AND +audit.action NOT IN (SELECT value FROM json_each(?4)) ORDER BY audit.id DESC LIMIT ?5` |
| ) |
| // OperatorAccount is an account row as an operator page sees it, deleted |
| @@ -187,6 +221,67 @@ func (s *Store) OperatorAccountBySqid(sqid string) (*OperatorAccount, error) { |
| return &a, nil |
| } |
| +// PersonAccount is one live account a person is a member of, on the |
| +// person page. |
| +type PersonAccount struct { |
| + ID int64 |
| + Sqid, Name, Role string |
| + Plan string // "" when the account has no plan row |
| + Apps int // the account's live apps |
| + Added time.Time |
| +} |
| + |
| +// PersonDetail is one person as the person page sees them. |
| +type PersonDetail struct { |
| + Address string |
| + Joined, LastSeen time.Time // LastSeen zero when never seen |
| + Apps int // live apps they created |
| + Accounts []PersonAccount |
| +} |
| + |
| +// OperatorPerson is the person whose users row has exactly that address, or |
| +// (nil, nil) when there is none. It only reads. Their accounts are in the |
| +// order they joined them (added_at, then account id). |
| +func (s *Store) OperatorPerson(address string) (*PersonDetail, error) { |
| + var p PersonDetail |
| + var joined, seen int64 |
| + err := s.db.QueryRow(opSQLPerson, address).Scan(&p.Address, &joined, &seen) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return nil, nil |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + p.Joined, p.LastSeen = time.Unix(joined, 0).UTC(), timeOrZero(seen) |
| + if err := s.db.QueryRow(opSQLPersonMade, p.Address).Scan(&p.Apps); err != nil { |
| + return nil, err |
| + } |
| + rows, err := s.db.Query(opSQLPersonHeld, p.Address) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + for rows.Next() { |
| + var a PersonAccount |
| + var added int64 |
| + if err := rows.Scan(&a.ID, &a.Sqid, &a.Name, &a.Role, &added, &a.Plan, &a.Apps); err != nil { |
| + return nil, err |
| + } |
| + a.Added = time.Unix(added, 0).UTC() |
| + p.Accounts = append(p.Accounts, a) |
| + } |
| + if err := rows.Err(); err != nil { |
| + return nil, err |
| + } |
| + sort.Slice(p.Accounts, func(i, j int) bool { |
| + if !p.Accounts[i].Added.Equal(p.Accounts[j].Added) { |
| + return p.Accounts[i].Added.Before(p.Accounts[j].Added) |
| + } |
| + return p.Accounts[i].ID < p.Accounts[j].ID |
| + }) |
| + return &p, nil |
| +} |
| + |
| // TouchLastSeen records that address was seen at now. It never moves |
| // last_seen backwards and never creates a users row. |
| func (s *Store) TouchLastSeen(address string, now time.Time) error { |
| @@ -415,9 +510,12 @@ func (s *Store) AccountsPage(q string, offset, limit int) ([]AccountRow, int, er |
| // ActivityFilter narrows the activity feed. AccountID 0 is every account; |
| // -1 means the account filter matched nothing, so the feed is empty. |
| -// Actions keeps only those actions; Exclude drops those (the "other" kind). |
| +// Actor, when set, keeps only the rows that address made (audit.address, |
| +// matched exactly). Actions keeps only those actions; Exclude drops those |
| +// (the "other" kind). |
| type ActivityFilter struct { |
| AccountID int64 |
| + Actor string |
| Actions, Exclude []string |
| } |
| @@ -443,6 +541,16 @@ func (s *Store) ActivityFeed(f ActivityFilter, beforeID int64, limit int) ([]Fee |
| if len(f.Actions) > 0 && len(actions) == 0 { |
| return nil, nil // every kind asked for is excluded |
| } |
| + if f.Actor != "" { |
| + switch { |
| + case len(actions) > 0: |
| + return s.feed(opSQLFeedActorActions, f.Actor, before, f.AccountID, opJSON(actions), limit) |
| + case len(f.Exclude) > 0: |
| + return s.feed(opSQLFeedActorOther, f.Actor, before, f.AccountID, opJSON(f.Exclude), limit) |
| + default: |
| + return s.feed(opSQLFeedActor, f.Actor, before, f.AccountID, limit) |
| + } |
| + } |
| if f.AccountID > 0 { |
| switch { |
| case len(actions) > 0: |
diff --git a/internal/console/opstore_test.go b/internal/console/opstore_test.go| index 7ebbe839f..1126775e4 100644 |
| --- a/internal/console/opstore_test.go |
| +++ b/internal/console/opstore_test.go |
| @@ -61,6 +61,7 @@ func TestMigrateOperatorPagesIsIdempotent(t *testing.T) { |
| "users_by_last_seen": "users", |
| "memberships_by_address": "memberships", |
| "apps_by_creator": "apps", |
| + "audit_by_actor": "audit", |
| } |
| for index, table := range want { |
| rows, err := s.db.Query(`SELECT name FROM pragma_index_list(?)`, table) |
| @@ -185,6 +186,30 @@ var opQueryPlans = []opPlanCase{ |
| {name: "feed other", sql: opSQLFeedOther, args: []any{`["promote","rollback"]`, 50}, |
| want: []string{"SCAN audit"}, |
| notWant: []string{"audit USING INDEX", "SCAN accounts"}}, |
| + {name: "person", sql: opSQLPerson, args: []any{"ann@example.com"}, |
| + want: []string{"SEARCH users USING INDEX sqlite_autoindex_users_1 (address=?)"}, |
| + notWant: []string{"SCAN users"}}, |
| + {name: "person apps made", sql: opSQLPersonMade, args: []any{"ann@example.com"}, |
| + want: []string{"SEARCH apps USING INDEX apps_by_creator (created_by=?)"}, |
| + notWant: []string{"SCAN apps"}}, |
| + {name: "person accounts", sql: opSQLPersonHeld, args: []any{"ann@example.com"}, |
| + want: []string{"SEARCH memberships USING INDEX memberships_by_address (address=?)", |
| + "SEARCH accounts USING INTEGER PRIMARY KEY (rowid=?)", |
| + "SEARCH account_plans USING INTEGER PRIMARY KEY (rowid=?)", |
| + "SEARCH apps USING INDEX sqlite_autoindex_apps_1 (account_id=?)"}, |
| + notWant: []string{"SCAN memberships", "SCAN apps", "SCAN accounts", "SCAN account_plans", "SEARCH held USING AUTOMATIC"}}, |
| + {name: "feed actor", sql: opSQLFeedActor, args: []any{"ann@example.com", int64(math.MaxInt64), int64(0), 50}, |
| + want: []string{"SEARCH audit USING INDEX audit_by_actor (address=? AND id<?)"}, |
| + notWant: []string{"SCAN audit", "audit_by_account", "audit_by_action", "SCAN accounts"}}, |
| + {name: "feed actor in an account", sql: opSQLFeedActor, args: []any{"ann@example.com", int64(math.MaxInt64), int64(7), 50}, |
| + want: []string{"SEARCH audit USING INDEX audit_by_actor (address=? AND id<?)"}, |
| + notWant: []string{"SCAN audit", "audit_by_account", "audit_by_action", "SCAN accounts"}}, |
| + {name: "feed actor actions", sql: opSQLFeedActorActions, args: []any{"ann@example.com", int64(math.MaxInt64), int64(0), `["promote","rollback"]`, 50}, |
| + want: []string{"SEARCH audit USING INDEX audit_by_actor (address=? AND id<?)"}, |
| + notWant: []string{"SCAN audit", "audit_by_account", "audit_by_action", "SCAN accounts"}}, |
| + {name: "feed actor other", sql: opSQLFeedActorOther, args: []any{"ann@example.com", int64(math.MaxInt64), int64(7), `["promote","rollback"]`, 50}, |
| + want: []string{"SEARCH audit USING INDEX audit_by_actor (address=? AND id<?)"}, |
| + notWant: []string{"SCAN audit", "audit_by_account", "audit_by_action", "SCAN accounts"}}, |
| {name: "feed other before", sql: opSQLFeedOtherBefore, args: []any{int64(71), `["promote","rollback"]`, 50}, |
| want: []string{"SEARCH audit USING INTEGER PRIMARY KEY (rowid<?)"}, |
| notWant: []string{"SCAN audit", "SCAN accounts"}}, |
| @@ -202,7 +227,10 @@ var opSQLByName = map[string]string{ |
| "opSQLFeedAll": opSQLFeedAll, "opSQLFeedBefore": opSQLFeedBefore, "opSQLFeedAccount": opSQLFeedAccount, |
| "opSQLFeedAccountActions": opSQLFeedAccountActions, "opSQLFeedAccountOther": opSQLFeedAccountOther, |
| "opSQLFeedAction": opSQLFeedAction, "opSQLFeedOther": opSQLFeedOther, "opSQLFeedOtherBefore": opSQLFeedOtherBefore, |
| - "opSQLPersonPage": "", "opSQLPersonLookups": "", "opSQLFeedColumns": "", |
| + "opSQLPerson": opSQLPerson, "opSQLPersonMade": opSQLPersonMade, "opSQLPersonHeld": opSQLPersonHeld, |
| + "opSQLFeedActor": opSQLFeedActor, "opSQLFeedActorActions": opSQLFeedActorActions, |
| + "opSQLFeedActorOther": opSQLFeedActorOther, |
| + "opSQLPersonPage": "", "opSQLPersonLookups": "", "opSQLFeedColumns": "", |
| } |
| // opQueryPlan is the EXPLAIN QUERY PLAN detail lines of one statement. |
| @@ -968,7 +996,7 @@ func TestPeopleAndAccountsWithConcentratedOwnership(t *testing.T) { |
| } |
| // TestMigrateOperatorPagesOnAPopulatedStore runs the migration on a store |
| -// already holding the scale fixture: the column and the eight indexes are |
| +// already holding the scale fixture: the column and the nine indexes are |
| // taken away, the store is closed, and the next Open puts them back. Both |
| // opens are timed and printed (the second is the no-op baseline). |
| func TestMigrateOperatorPagesOnAPopulatedStore(t *testing.T) { |
diff --git a/internal/console/perfwalk_test.go b/internal/console/perfwalk_test.go| index 1c2fa28ea..b1e5c281b 100644 |
| --- a/internal/console/perfwalk_test.go |
| +++ b/internal/console/perfwalk_test.go |
| @@ -525,10 +525,17 @@ func perfOperatorTargets() map[string][]perfTarget { |
| // One of the scale accounts, and a page 2,000 rows back from its newest. |
| activity = append(activity, ok("/fleet/activity?account="+opScaleAccount(3), |
| "/fleet/activity?before="+strconv.Itoa(opScaleAuditBase+1000))...) |
| + // One scale person's rows (audit_by_actor), alone, with a kind, and |
| + // with an account. |
| + activity = append(activity, ok("/fleet/activity?who=person-0@example.com", |
| + "/fleet/activity?who=person-0@example.com&kind=deploys", |
| + "/fleet/activity?who=person-0@example.com&account="+opScaleAccount(0))...) |
| return map[string][]perfTarget{ |
| "GET /fleet/people": ok("/fleet/people", "/fleet/people?show=accounts", "/fleet/people?q=person-1", |
| "/fleet/people?show=accounts&q=shop-1", "/fleet/people?page=3"), |
| "GET /fleet/activity": activity, |
| + // A scale person: an owner with apps, other members and audit rows. |
| + "GET /fleet/people/{address}": ok("/fleet/people/person-0@example.com"), |
| } |
| } |
diff --git a/internal/console/server.go b/internal/console/server.go| index 76a29d3fd..67681a899 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -211,10 +211,18 @@ var templates = template.Must(template.New("").Funcs(template.FuncMap{ |
| // is the rail a page's viewer sees, opnum a number with thousands |
| // commas, and opHeader and opEmpty build the partials' data in a |
| // template. |
| - "opRail": opRailFor, |
| - "opnum": opNumber, |
| - "opHeader": func(title, sub string) opHeader { return opHeader{Title: title, Sub: sub} }, |
| - "opEmpty": func(title, body string) opEmpty { return opEmpty{Title: title, Body: body} }, |
| + "opRail": opRailFor, |
| + "opnum": opNumber, |
| + // opWhat is how an audit row's Detail shows on the operator pages, and |
| + // auditText its words alone for the customer console (auditdetail.go). |
| + "opWhat": auditWhatOf, |
| + "auditText": auditText, |
| + // opPersonPath links a people-list row; opPersonHref an audit row's |
| + // actor, "" when the actor is not a person (opperson.go). |
| + "opPersonPath": opPersonPath, |
| + "opPersonHref": opPersonHref, |
| + "opHeader": func(title, sub string) opHeader { return opHeader{Title: title, Sub: sub} }, |
| + "opEmpty": func(title, body string) opEmpty { return opEmpty{Title: title, Body: body} }, |
| // opPill, opStat and opMeter build op_status, op_stat and op_meter's |
| // data in a template; memUsedPct is a host's used memory for its meter, |
| // and memUsed the same figure in bytes for the meter's text. |
| @@ -1689,6 +1697,7 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| s.registerRoute("GET /fleet/boxes", s.handleBoxes) |
| s.registerRoute("GET /fleet/index", s.handleOpIndex) |
| s.registerRoute("GET /fleet/people", s.handlePeople) |
| + s.registerRoute("GET /fleet/people/{address}", s.handlePerson) |
| s.registerRoute("GET /fleet/store", s.handleStoreApprovalsPage) |
| s.registerRoute("POST /fleet/store/{account}/{decision}", s.handleStoreDecisionPage) |
| s.registerRoute("POST /a/{sqid}/store/apply", s.handleStoreApplyPage) |
| @@ -2320,6 +2329,10 @@ type page struct { |
| // Feed is Activity's data (/fleet/activity, opactivity.go). |
| Feed *feedView |
| + // Person is one person's page data (/fleet/people/{address}, |
| + // opperson.go). |
| + Person *personView |
| + |
| // /fleet, below the published boxes table: the per-host PRIVATE detail |
| // read straight out of status/boxes/ (HostRows, view.go). Raw numbers |
| // render here and nowhere public — this page is session-gated to |
diff --git a/internal/console/static/ops.css b/internal/console/static/ops.css| index d0afcc1d7..e2380878b 100644 |
| --- a/internal/console/static/ops.css |
| +++ b/internal/console/static/ops.css |
| @@ -29,6 +29,8 @@ |
| [co-cols="persons"] { --rst-cols: minmax(12rem, 2fr) 7rem 7rem 6rem; } |
| [co-cols="accounts"] { --rst-cols: minmax(10rem, 2fr) 7rem minmax(6rem, 1fr) 5rem 6rem; } |
| [co-cols="feed"] { --rst-cols: 6rem minmax(10rem, 1.2fr) minmax(7rem, 1fr) minmax(12rem, 2fr) minmax(7rem, 1fr); } |
| +[co-cols="personaccts"] { --rst-cols: minmax(10rem, 2fr) 7rem minmax(6rem, 1fr) 5rem; } |
| +[co-cols="personfeed"] { --rst-cols: 6rem minmax(7rem, 1fr) minmax(12rem, 2fr) minmax(7rem, 1fr); } |
| /* On a phone, Rastrillo's rows drop to a name and one value (its |
| rst-m-hide hides the rest, at the same 800px). These lists have no |
| @@ -39,12 +41,15 @@ |
| @media (max-width: 800px) { |
| [co-cols] > [rst-lrow] { grid-template-columns: minmax(0, 1fr) auto; } |
| [co-cols="activity"] > [rst-lrow], |
| - [co-cols="feed"] > [rst-lrow] { grid-template-columns: 6rem minmax(0, 1fr); } |
| + [co-cols="feed"] > [rst-lrow], |
| + [co-cols="personfeed"] > [rst-lrow] { grid-template-columns: 6rem minmax(0, 1fr); } |
| [co-cols="people"] > [rst-lrow] > :is(:nth-child(2), :nth-child(4)), |
| [co-cols="persons"] > [rst-lrow] > :is(:nth-child(2), :nth-child(4)), |
| [co-cols="accounts"] > [rst-lrow] > :is(:nth-child(2), :nth-child(n+4)), |
| [co-cols="activity"] > [rst-lrow] > :is(:nth-child(2), :nth-child(4)), |
| [co-cols="feed"] > [rst-lrow] > :is(:nth-child(2), :nth-child(3), :nth-child(5)), |
| + [co-cols="personfeed"] > [rst-lrow] > :is(:nth-child(2), :nth-child(4)), |
| + [co-cols="personaccts"] > [rst-lrow] > :nth-child(n+3), |
| [co-cols="boxes"] > [rst-lrow] > :nth-child(n+3), |
| [co-cols="jobs"] > [rst-lrow] > :nth-child(n+3) { display: none; } |
| } |
| @@ -57,9 +62,20 @@ |
| narrowed to, and the link that drops it. */ |
| [co-filter] { color: var(--rst-text-muted); font-size: var(--rst-fs-sm); margin: 0; } |
| -/* Activity's account links (each row's account, the filter line's clear |
| - link): the accent, not the browser's default blue. */ |
| -[co-cols="feed"] a { color: var(--rst-accent); } |
| +/* Activity's account and person links (each row's account and who, the |
| + filter lines and their clear links), and the same links on the |
| + dashboard's latest activity and a person's page: the accent, not the |
| + browser's default blue. */ |
| +[co-cols="feed"] a, [co-cols="activity"] a, [co-cols="personfeed"] a { color: var(--rst-accent); } |
| + |
| +/* An audit row's What (op_what): one line, cut with an ellipsis, its |
| + whole text in the cell's title. A row that stored data opens onto it, |
| + indented, wrapped and scrolling within the cell rather than widening the |
| + row. */ |
| +[co-clip] { min-inline-size: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } |
| +[co-what] { min-inline-size: 0; } |
| +[co-what] > summary { cursor: pointer; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } |
| +[co-what] > pre { font-size: var(--rst-fs-sm); margin: var(--rst-sp-2) 0 0; max-block-size: 20rem; overflow: auto; overflow-wrap: anywhere; white-space: pre-wrap; } |
| /* A quiet note under a table or a band: what today's pages wrote as a |
| <p class="small">. */ |
diff --git a/internal/console/templates/app_activity.html b/internal/console/templates/app_activity.html| index e4e0a00a8..6d37cfdbf 100644 |
| --- a/internal/console/templates/app_activity.html |
| +++ b/internal/console/templates/app_activity.html |
| @@ -11,7 +11,7 @@ |
| {{range .Events}} |
| <tr><td>{{fmtTime .CreatedAt}}</td><td>{{.Address}}</td> |
| <td>{{if .Message}}{{.Message}}{{else}}—{{end}}</td> |
| - <td>{{if .TargetURL}}<a href="{{.TargetURL}}">{{.Detail}}</a>{{else}}{{.Detail}}{{end}}</td> |
| + <td>{{if .TargetURL}}<a href="{{.TargetURL}}">{{auditText .Action .Detail}}</a>{{else}}{{auditText .Action .Detail}}{{end}}</td> |
| </tr> |
| {{end}} |
| </table> |
diff --git a/internal/console/templates/app_overview.html b/internal/console/templates/app_overview.html| index cf12c87c7..d3baa211f 100644 |
| --- a/internal/console/templates/app_overview.html |
| +++ b/internal/console/templates/app_overview.html |
| @@ -86,7 +86,7 @@ |
| <h2>Recent activity</h2> |
| <ul class="feed"> |
| {{range .Events}} |
| - <li><span class="small" title="{{fmtTime .CreatedAt}}">{{ago .CreatedAt}}</span> {{.Address}} — {{.Detail}}</li> |
| + <li><span class="small" title="{{fmtTime .CreatedAt}}">{{ago .CreatedAt}}</span> {{.Address}} — {{auditText .Action .Detail}}</li> |
| {{end}} |
| </ul> |
| <p class="small"><a href="{{.Nav}}/apps/{{.AppName}}/activity">All activity</a></p> |
diff --git a/internal/console/templates/opparts.html b/internal/console/templates/opparts.html| index b9e019ce4..ad4ec960a 100644 |
| --- a/internal/console/templates/opparts.html |
| +++ b/internal/console/templates/opparts.html |
| @@ -97,3 +97,13 @@ |
| <div rst-lrow><span>{{.Label}}</span><span>{{template "op_status" .Status}}</span>{{if .LastRan.IsZero}}<span>{{ago .LastRan}}</span>{{else}}<span title="{{fmtTime .LastRan}}">{{ago .LastRan}}</span>{{end}}<span>{{.Note}}</span></div> |
| {{- end}} |
| </div>{{end}} |
| + |
| +{{/* An audit row's actor (a string): a link to their person page when |
| + the actor is a person's address, else the text as it is. */}} |
| +{{define "op_who"}}{{with opPersonHref .}}<a href="{{.}}">{{$}}</a>{{else}}<span>{{.}}</span>{{end}}{{end}} |
| + |
| +{{/* An audit row's What (a FeedRow): its sentence or stored text on one |
| + line, cut with its whole text in title when long; or, for a row that |
| + stored data (a run row included), its sentence or summary opening onto |
| + the data (auditdetail.go). */}} |
| +{{define "op_what"}}{{with opWhat .Action .Detail}}{{if .JSON}}<details co-what><summary{{with .Title}} title="{{.}}"{{end}}>{{.Text}}</summary><pre>{{.JSON}}</pre></details>{{else}}<span co-clip{{with .Title}} title="{{.}}"{{end}}>{{.Text}}</span>{{end}}{{end}}{{end}} |
diff --git a/internal/console/templates/ops_activity.html b/internal/console/templates/ops_activity.html| index aa9f50729..9b1d704ba 100644 |
| --- a/internal/console/templates/ops_activity.html |
| +++ b/internal/console/templates/ops_activity.html |
| @@ -1,7 +1,8 @@ |
| {{/* Activity (/fleet/activity, opactivity.go): one card of audit rows, |
| newest first, under a toolbar holding the kind filter and, when an |
| - account filter is on, the line naming it with its clear link; Newest |
| - and Older below. Everything computed in Go arrives in .Feed. */}} |
| + account or a person filter is on, the line naming each with its clear |
| + link; Newest and Older below. Everything computed in Go arrives in |
| + .Feed. */}} |
| {{define "ops_activity"}}{{template "op_top" .}} |
| {{template "op_page_header" (opHeader .Title "All activity across every account, newest first.")}} |
| {{with .Feed}} |
| @@ -11,11 +12,14 @@ |
| {{- if .AccountName}} |
| <p co-filter>Showing only {{if .AccountDeleted}}{{.AccountName}} (deleted){{else}}{{.AccountName}}{{end}}. <a href="{{.Query.ClearAccountHref}}">Show all accounts</a></p> |
| {{- end}} |
| + {{- if .Who}} |
| + <p co-filter>Showing only {{if .WhoHref}}<a href="{{.WhoHref}}">{{.Who}}</a>{{else}}{{.Who}}{{end}}. <a href="{{.Query.ClearWhoHref}}">Show all people</a></p> |
| + {{- end}} |
| </div> |
| {{- if .Rows}} |
| <div rst-lrow="head"><span>When</span><span>Who</span><span>Account</span><span>What</span><span>App</span></div> |
| {{- range .Rows}} |
| - <div rst-lrow><span class="rst-cell-mut" title="{{fmtTime .At}}">{{ago .At}}</span><span>{{.Address}}</span>{{if .AccountSqid}}<a href="{{$.Feed.Query.AccountHref .AccountSqid}}">{{.AccountName}}</a>{{else}}<span class="rst-cell-mut">none</span>{{end}}<span>{{.Detail}}</span>{{if .App}}<span>{{.App}}</span>{{else}}<span class="rst-cell-mut">none</span>{{end}}</div> |
| + <div rst-lrow><span class="rst-cell-mut" title="{{fmtTime .At}}">{{ago .At}}</span>{{template "op_who" .Address}}{{if .AccountSqid}}<a href="{{$.Feed.Query.AccountHref .AccountSqid}}">{{.AccountName}}</a>{{else}}<span class="rst-cell-mut">none</span>{{end}}{{template "op_what" .}}{{if .App}}<span>{{.App}}</span>{{else}}<span class="rst-cell-mut">none</span>{{end}}</div> |
| {{- end}} |
| {{- else}} |
| {{template "op_empty" (opEmpty "" "No activity matches these filters.")}} |
diff --git a/internal/console/templates/ops_dashboard.html b/internal/console/templates/ops_dashboard.html| index 47fc0441e..e3ab99cf3 100644 |
| --- a/internal/console/templates/ops_dashboard.html |
| +++ b/internal/console/templates/ops_dashboard.html |
| @@ -47,7 +47,7 @@ |
| <div rst-card co-cols="people"> |
| <div rst-lrow="head"><span>Person</span><span>Account</span><span>Joined</span><span>Apps</span></div> |
| {{- range .Newest}} |
| - <div rst-lrow><span class="rst-nm">{{.Address}}</span>{{if .FirstAccount}}<span>{{.FirstAccount}}</span>{{else}}<span class="rst-cell-mut">none</span>{{end}}<span class="rst-cell-mut" title="{{fmtTime .Joined}}">{{ago .Joined}}</span><span>{{opnum .Apps}}</span></div> |
| + <div rst-lrow><a class="rst-nm" href="{{opPersonPath .Address}}">{{.Address}}</a>{{if .FirstAccount}}<span>{{.FirstAccount}}</span>{{else}}<span class="rst-cell-mut">none</span>{{end}}<span class="rst-cell-mut" title="{{fmtTime .Joined}}">{{ago .Joined}}</span><span>{{opnum .Apps}}</span></div> |
| {{- end}} |
| </div> |
| {{else}}{{template "op_empty" (opEmpty "" "No one has signed up yet.")}}{{end}} |
| @@ -57,7 +57,7 @@ |
| <div rst-card co-cols="activity"> |
| <div rst-lrow="head"><span>When</span><span>Who</span><span>What</span><span>App</span></div> |
| {{- range .Activity}} |
| - <div rst-lrow><span class="rst-cell-mut" title="{{fmtTime .At}}">{{ago .At}}</span><span>{{.Address}}</span><span>{{.Detail}}</span>{{if .App}}<span>{{.App}}</span>{{else}}<span class="rst-cell-mut">none</span>{{end}}</div> |
| + <div rst-lrow><span class="rst-cell-mut" title="{{fmtTime .At}}">{{ago .At}}</span>{{template "op_who" .Address}}{{template "op_what" .}}{{if .App}}<span>{{.App}}</span>{{else}}<span class="rst-cell-mut">none</span>{{end}}</div> |
| {{- end}} |
| </div> |
| {{else}}{{template "op_empty" (opEmpty "" "Nothing has happened yet.")}}{{end}} |
diff --git a/internal/console/templates/ops_people.html b/internal/console/templates/ops_people.html| index c50657cc8..abd4835cc 100644 |
| --- a/internal/console/templates/ops_people.html |
| +++ b/internal/console/templates/ops_people.html |
| @@ -30,7 +30,7 @@ |
| {{- if .People}} |
| <div rst-lrow="head"><span>Person</span><span>Joined</span><span>Last seen</span><span>Accounts</span></div> |
| {{- range .People}} |
| - <div rst-lrow><span class="rst-nm">{{.Address}}</span><span class="rst-cell-mut" title="{{fmtTime .Joined}}">{{ago .Joined}}</span>{{if .LastSeen.IsZero}}<span class="rst-cell-mut">not yet</span>{{else}}<span class="rst-cell-mut" title="{{fmtTime .LastSeen}}">{{ago .LastSeen}}</span>{{end}}<span>{{opnum .Accounts}}</span></div> |
| + <div rst-lrow><a class="rst-nm" href="{{opPersonPath .Address}}">{{.Address}}</a><span class="rst-cell-mut" title="{{fmtTime .Joined}}">{{ago .Joined}}</span>{{if .LastSeen.IsZero}}<span class="rst-cell-mut">not yet</span>{{else}}<span class="rst-cell-mut" title="{{fmtTime .LastSeen}}">{{ago .LastSeen}}</span>{{end}}<span>{{opnum .Accounts}}</span></div> |
| {{- end}} |
| {{- else if .Query.Q}} |
| {{template "op_empty" (opEmpty "" "No people match that search.")}} |
diff --git a/internal/console/templates/ops_person.html b/internal/console/templates/ops_person.html| new file mode 100644 |
| index 000000000..78265ad00 |
| --- /dev/null |
| +++ b/internal/console/templates/ops_person.html |
| @@ -0,0 +1,34 @@ |
| +{{/* One person (/fleet/people/{address}, opperson.go): their address as |
| + the heading, the band (joined, last seen, accounts, apps created), |
| + their accounts, and their latest activity in Activity's style with a |
| + link to all of it. Everything computed in Go arrives in .Person. */}} |
| +{{define "ops_person"}}{{template "op_top" .}} |
| +{{template "op_page_header" (opHeader .Title "Their accounts and latest activity.")}} |
| +{{with .Person}} |
| +<div rst-stats rst-card> |
| + {{- range .Stats}} |
| + {{template "op_stat" .}} |
| + {{- end}} |
| +</div> |
| + |
| +<div rst-box-head><h2>Accounts</h2></div> |
| +{{if .Person.Accounts}} |
| +<div rst-card co-cols="personaccts"> |
| + <div rst-lrow="head"><span>Account</span><span>Role</span><span>Plan</span><span>Apps</span></div> |
| + {{- range .Person.Accounts}} |
| + <div rst-lrow><a class="rst-nm" href="/fleet/activity?account={{.Sqid}}">{{.Name}}</a><span>{{.Role}}</span>{{if .Plan}}<span>{{.Plan}}</span>{{else}}<span class="rst-cell-mut">none</span>{{end}}<span>{{opnum .Apps}}</span></div> |
| + {{- end}} |
| +</div> |
| +{{else}}{{template "op_empty" (opEmpty "" "Not a member of any account.")}}{{end}} |
| + |
| +<div rst-box-head><h2>Latest activity</h2><a rst-btn="ghost" href="{{.ActivityRef}}">All their activity</a></div> |
| +{{if .Feed}} |
| +<div rst-card co-cols="personfeed"> |
| + <div rst-lrow="head"><span>When</span><span>Account</span><span>What</span><span>App</span></div> |
| + {{- range .Feed}} |
| + <div rst-lrow><span class="rst-cell-mut" title="{{fmtTime .At}}">{{ago .At}}</span>{{if .AccountSqid}}<a href="/fleet/activity?account={{.AccountSqid}}">{{.AccountName}}</a>{{else}}<span class="rst-cell-mut">none</span>{{end}}{{template "op_what" .}}{{if .App}}<span>{{.App}}</span>{{else}}<span class="rst-cell-mut">none</span>{{end}}</div> |
| + {{- end}} |
| +</div> |
| +{{else}}{{template "op_empty" (opEmpty "" "No activity yet.")}}{{end}} |
| +{{end}} |
| +{{template "op_bottom" .}}{{end}} |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index 21ca29361..bb057e929 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -122,6 +122,7 @@ route GET /fleet/economics/accounts |
| route GET /fleet/index |
| route GET /fleet/metrics |
| route GET /fleet/people |
| +route GET /fleet/people/{address} |
| route GET /fleet/store |
| route GET /healthz |
| route GET /invite/{token} |
diff --git a/internal/provision/operator_people_detail_census_test.go b/internal/provision/operator_people_detail_census_test.go| new file mode 100644 |
| index 000000000..5f6f36a03 |
| --- /dev/null |
| +++ b/internal/provision/operator_people_detail_census_test.go |
| @@ -0,0 +1,30 @@ |
| +package provision |
| + |
| +// Record-write census entry for operator-people-detail (the operator person |
| +// page), layered on rootfsApps4WriteCensusInventory (main's newest at 57aec0ad). |
| +// Reviewed by the branch author. No record write is added, moved or |
| +// reclassified: |
| +// - NewServer: registers GET /fleet/people/{address} (opperson.go), an |
| +// operator page that reads SQLite only. Same "instances" literal: still |
| +// key-site. |
| +func operatorPeopleDetailWriteCensusInventory() []censusEntry { |
| + entries := append([]censusEntry(nil), rootfsApps4WriteCensusInventory()...) |
| + replacements := []censusEntry{ |
| + {"internal/console/server.go", "NewServer", "key-site", "lit:instances", "e65dbac77bd84953ddb486b9d03a5c99de6df2464387d7cdfc711249bb219d6c"}, |
| + } |
| + for _, r := range replacements { |
| + found := false |
| + for i, e := range entries { |
| + if e.File == r.File && e.Unit == r.Unit { |
| + if e.Class != r.Class || e.Kinds != r.Kinds { |
| + panic("operator-people-detail replacement reclassifies " + r.File + ":" + r.Unit) |
| + } |
| + entries[i], found = r, true |
| + } |
| + } |
| + if !found { |
| + panic("operator-people-detail replacement of an unlisted unit " + r.File + ":" + r.Unit) |
| + } |
| + } |
| + return entries |
| +} |
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go| index 5b2bd7d89..7abe29462 100644 |
| --- a/internal/provision/plan9_b8_census_test.go |
| +++ b/internal/provision/plan9_b8_census_test.go |
| @@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) { |
| if len(got) < 100 { |
| t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root) |
| } |
| - inventory := rootfsApps4WriteCensusInventory() |
| + inventory := operatorPeopleDetailWriteCensusInventory() |
| problems := append(censusDiff(inventory, got), censusPolicy(inventory)...) |
| if len(problems) > 0 { |
| t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n ")) |