Skip to content

Phase E2: Compute dashboard #495

Closed
Closed

Description

@neuromechanist

Goal

After this phase a signed-in person has a /compute page on the app host that shows their access state, their CPU and GPU balances, a usage chart, their jobs from every front door and the current queue estimates.
A person without active access sees why and how to get it, not an error.

Routing

Scope

In: src/pages/compute/index.astro and its components; the app-host route classification; the compute-api.ts additions; the pure chart geometry and formatting helpers; job-state badges; light, dark and phone layouts.
Out: the job page (#496); submitting a job from the web (not in this epic; the CLI submits); the admin views (#497).

Design references

Design section 5 (two pools, units in thousandths of an SU), section 6 (usage figures table), section 7 (job states table), section 8 (queue estimates, "not enough data").
Website ADR 0007 (hand-rolled SVG charts), ADR 0006 (two-host model), the chart components src/components/PipelineSuccessChart.astro and HistogramChart.astro, src/lib/host.ts (APP_ROUTE_PREFIXES), src/lib/admin-badges.ts (badges with a defined answer for an unknown value), src/pages/dashboard.astro (session guard, tier handling), src/lib/dashboard-api.ts (client shape, deadlines).

Changes

  • src/lib/host.ts: add "/compute" to APP_ROUTE_PREFIXES with a test in host.test.ts; without it the middleware redirects the app-host request to the marketing host. Check src/middleware.ts for route-scoped headers that a new app route needs (CSP and cache rules), and say in the plan what you found.
  • src/pages/compute/index.astro: a session guard like the dashboard (redirect to /login?next=/compute); SSR reads GET /compute/me, the last-30-days usage with group=day,partition, and the first page of jobs, each independently, so one failed read degrades one panel (a SectionErrorNotice style notice naming what failed), never the page. Panels: Access (state badge; for any state other than active, the state's copy from ACCOUNT_COPY and a link to /settings#compute-access; for suspended or revoked, the frozen note); Balances (CPU and GPU: available, held and charged, as SU with three decimals and a bar of available over granted); Usage (the chart below plus a visually hidden table with the same numbers); Jobs (a table with name, state badge, front door, partition, created, charge, each row linking to /compute/jobs/<id>; "Load more" fetches the next page through the /api/v1 proxy with next_after); Queue (partition, median and 90th percentile wait, sample count; a null figure reads "not enough data" with the count, never a dash that looks like zero).
  • src/components/ComputeUsageChart.astro with geometry in src/lib/compute-chart.ts (pure, unit-tested): bar x and width from the day count, y from a "nice" axis ceiling, tick values and labels, stack offsets per partition, a zero-height bar for a zero day. SVG with role="img", a <title> and <desc>, colours from tokens (add --chart-* tokens to src/styles/tokens.css for light and dark if the existing ones do not suffice), no animation beyond what prefers-reduced-motion allows, a legend, and a text fallback table. No chart library.
  • src/lib/compute-format.ts (pure): formatSu(milli) (never floating-point sums: integer thousandths in, string out), formatWait(seconds), formatDuration. src/lib/compute-badges.ts: label, tone and icon per job state (created, uploading, submitted, queued, running, archiving, finished, failed, cancelled, unreported) with the neutral raw-text pill for a state this build does not know, as admin-badges.ts does.
  • src/lib/compute-api.ts: getComputeUsage, listComputeJobs (and getComputeMe from Phase E1: Compute access card #494), SSR with cookieHeader, browser through /api/v1; zod or hand-written guards in the style of the neighbouring clients; a shape the guard rejects is an error, never an empty list.
  • Add a "Compute" link to the app navigation only where the person has active access, or to the dashboard header otherwise; the planner decides where and records it.
  • Fixtures under test/fixtures/compute/ captured from the merged routes of a local backend (a fresh account, an account with a charge, a frozen account, a thin queue sample), with the capture command in each test file.

Tests (write these first)

  1. compute-chart.test.ts: geometry for a known usage fixture (bar positions, nice ceiling, stack offsets), a single day, an all-zero range, one large outlier. Fails if the ceiling is computed from the sum of an unstacked maximum.
  2. compute-format.test.ts: thousandths to SU strings including 0, 999, 1000, a very large pool, and a negative balance (an overrun can take a balance below zero and it must print as negative, not as zero).
  3. compute-badges.test.ts: every known state, and an unknown state renders its raw text.
  4. compute-api.test.ts: each client parses its captured fixture; a malformed body raises; a 403 maps to the typed error the page renders as the access panel, not as a broken page.
  5. host.test.ts: /compute and /compute/jobs/abc are app routes.
  6. Queue panel logic: a null median renders "not enough data" with the count (a pure view-model function, tested).
  7. Browser check: the page in each access state, with the local backend and the Tapis stand-in producing real charges; light and dark; phone width with no horizontal scroll; keyboard focus order; the chart's text fallback; a forced failure of each read.

Acceptance criteria

  • Numbers on the page equal what nemar compute balance and nemar compute list print for the same account.
  • No panel's failure blanks the page; no unknown value renders as zero or as an empty list.
  • The chart is hand-rolled SVG, themed by tokens, with a text alternative.
  • /compute is served only on the app host and redirects signed-out visitors to login.

Gates

bun run typecheck && bun run lint && bun run test && bun run build; then the browser check against the local backend.

Rules that bite here

  • ADR 0007: no chart library; every colour a token; both themes equal.
  • Null-safety: the API may send nulls for any thin sample; do not tighten format helpers that Astro silently drops on a throw.
  • Amounts are integers in thousandths; summing floats on the page would disagree with the CLI.
  • Untrusted text (job names) renders as text nodes only.
  • Scoped Astro styles do not cross components; duplicate with a sync comment.

Escalate to the owner if

  • The merged /compute/me/usage cannot return what the chart needs (no per-partition grouping).
  • A route the page needs is missing; file a nemar-cli issue rather than computing it client-side.

When merged

Update the architecture map in AGENTS.md (the new page, components and lib files) and the #493 epic issue; note the fixture capture commands.

Activity

  1. neuromechanist commented on Nov 7, 2026

    @neuromechanist
    ContributorAuthor

    Hand-off from the compute epic review (nemar-cli PR #2063), for the compute dashboard.

    When a compute job's results are ready, the platform mails the person one link: <APP_BASE_URL>/compute/jobs/ (computeJobPageUrl in nemar-cli backend/src/services/compute-results.ts). The mail never links to a file, because a result link is a bearer link made only on request.

    So the page at /compute/jobs/ must exist on the website before the compute switch is turned on for people. Otherwise the first thing a person sees of the service is a 404.

    What the page can use: POST /compute/jobs//links returns the owner's seven-day result links, at most 1,000 at a time (an optional {after} cursor in the request body pages on), and POST /compute/jobs//cancel cancels a job. Both answers are now declared as open schemas in nemar-cli shared/contract/compute-responses.ts (ComputeLinksResponseSchema, ComputeCancelResponseSchema), with snake_case keys. Only the job's owner is served; anyone else gets job_not_found.

    This is also item 10 of the owner checklist in nemar-cli .context/compute-program/README.md (section 8).

  2. neuromechanist commented on Nov 7, 2026

    @neuromechanist
    ContributorAuthor

    Plan for Phase E2: the /compute dashboard

    Planner output for website#495 (epic website#493), written by reading the merged website epic branch (E1, PR 502, ADR 0030) and nemar-cli's Epic D branch at e0685a25 (phases D1 to D4).
    Where the issue text and the merged code differ, the code won, and each case is listed under "Where the issue and the code differ" so the implementer does not build the issue's version.
    Implementer: Sonnet, from origin/feature/issue-493-epic-compute-web (it holds E1), on a branch feature/issue-495-compute-dashboard, one PR into the epic branch.

    1. The backend as merged

    Every route below is mounted under /compute (backend/src/routes/compute/read.ts; contract shared/contract/compute-user.ts).
    Credential rule (routes/compute/auth.ts): a CLI key, the web session cookie, or an OpenID Connect token with compute.read.
    The website uses the cookie only: server side with the visitor's Cookie header, browser side through the /api/v1 proxy.
    All four answer Cache-Control: private, no-store.
    They answer in every access state (none, requested, active, suspended, denied, revoked) and with the compute switch off, because they are reads of the ledger and the job index.

    Route Query Response
    GET /compute/me none { access, pools, frozen, limits, queue }
    GET /compute/me/usage from, to (YYYY-MM-DD, UTC, both ends counted, at most 366 days; default is the 30 days ending today UTC), group (comma list of day, app, partition, source, each once) { from, to, group: string[], rows: [...] }
    GET /compute/me/jobs state (one job state), limit (1 to 100, default 25), after (the cursor) { jobs: [...], next_after: string | null }
    GET /compute/me/jobs/:id none { job, stale? } (phase #496; this is the only read that asks the cluster)

    GET /compute/me fields:

    • access: state (a string; today one of the closed six), requested_at, granted_at, terms_version (string or null), current_terms_version (string), terms_published (boolean), requests_open (optional boolean; false in production while the terms are unpublished).
    • pools: exactly cpu and gpu, each { granted_milli, held_milli, charged_milli, available_milli }.
      All integers; available_milli may be negative (an overrun, or a grant corrected below what is used).
      A pool nobody granted is all zeros, and the backend says that is true.
    • frozen: boolean, true when any of the person's pools is frozen (an ended account, a suspension).
    • limits: partitions[] (name, pool, max_nodes, max_cores_per_node, max_gpus_per_node, max_minutes; only partitions offered to people), max_live_jobs, results_days.
    • queue[]: one per offered partition: partition, median_seconds and p90_seconds (non-negative integers or null), count, window_days (7 today).
      Null figures with the count when fewer than 5 jobs started in the window.
      The wait is scheduler submission to start, over the last 7 days, newest 2,000 per partition, whoever submitted them and from whichever front door; it is the platform's queue, not the person's, and the same for everybody.

    GET /compute/me/usage rows: the requested group keys plus charged_milli (integer) and jobs (count of distinct jobs).

    • It is the net charge from the ledger (charges, overruns, settlements, administrator corrections and refunds), so a row can be negative.
    • A group with no net charge has no row, so a quiet day is absent, not a zero row.
    • day is the UTC day of the ledger entry (the settlement), not the day the job was created.
    • partition, app and source are null on an administrator's correction that names no job.
    • With group=day,partition a row is { day, partition, charged_milli, jobs }.

    GET /compute/me/jobs job fields: id (job_ and 24 lowercase hex digits), kind (batch or interactive), source (cli, web, partner, pipeline), state, app_id, app_version, partition, pool, resources (nodes, cores_per_node, memory_mb nullable, gpus, minutes), created_at, started_at, ended_at (nullable), charged_milli (0 until the job ends), failure_code (nullable), cancel_requested (boolean).
    Newest first by (created_at, id).
    The cursor is YYYY-MM-DDTHH:MM:SS|job_<24 hex>, opaque to the client: pass next_after back as after, URL-encoded (it contains |).
    It is exact: no job is shown twice or skipped, and a job created meanwhile is newer than the cursor and only appears on a reload.
    Job states (shared/compute-state.ts), ten: created, uploading, submitted, queued, running, archiving, finished, failed, cancelled, unreported.
    Terminal: finished, failed, cancelled.
    Times everywhere are the database clock in UTC as YYYY-MM-DD HH:MM:SS with no zone marker.

    Errors on the read routes are { "error": "<sentence>", "code": "<word>" }.
    The sentence is in error and the machine word in code, the reverse of what the website's readError and parseAccountErrorBody assume (they read error as the code).
    Words and statuses (COMPUTE_USER_ERROR_STATUS): invalid_range, invalid_group, invalid_state, invalid_limit, invalid_cursor (400); invalid_token, missing_credential (401); forbidden_credential, insufficient_scope (403); job_not_found (404); policy_unavailable (503, /compute/me only: the owner's policy could not be read, so the limits cannot be stated).
    The four credential words (invalid_token, missing_credential, forbidden_credential, insufficient_scope) cannot occur for a cookie session.
    What a cookie session can meet before the route runs is authMiddleware's own shapes: 401 { error: "Missing Authorization header" } (no or expired session) and 403 { error: "Account not approved", status, message } for an account that is not active (an unverified pending one).
    Compute access is never a 403 on a read.

    The contract schemas are open (passthrough), words the Worker may grow (state, partition, source) are strings, and every addition is optional.
    The website's guards must therefore be tolerant of extra keys and unknown words, and strict about the types of the keys the page reads.

    2. Where the issue and the code differ

    1. There is no job name. The user job has no name column (a spec's name lives in spec.json only), so the "name" column cannot exist. The list identifies a job by its id and app.
    2. getComputeMe is not in E1. The issue says it comes from Phase E1: Compute access card #494, but E1 merged no compute-api.ts; this phase creates the module with all three reads.
    3. Frozen note. The issue shows it for suspended or revoked accounts. The CLI (nemar compute balance) shows it only for an active account whose pools are frozen, because every other state already has its own sentence, and "Contact support to find out why" under an ended account would mislead. The code wins.
    4. A 403 is not the access panel. /compute/me answers 200 for every access state; the access panel is driven by access.state. A 403 is only an inactive account (Account not approved).
    5. Error bodies swap error and code (section 1), so the compute client needs its own parser.
    6. Queue estimates are not a separate route; they are queue inside GET /compute/me, one read serves access, balances and queue.
    7. Charged amount. Both the CLI and the issue say three decimals (suFixed), which differs from the contract's formatSu (shortest exact decimal: 12.5). The page uses the CLI's three-decimal form.
    8. No per-pool usage and no "compute is switched off" flag are served (section 12).
    9. The shared sentence compute_access.granted.body promises that you can "submit jobs from there"; the epic builds no web submission (section 14).

    3. Routes, files, and what changes

    No middleware change is needed (checked): a request with a session cookie skips the edge page cache and privateIfPublicHtml forces public HTML to private; the base CSP (connect-src 'self' https://*.nemar.org, inline scripts allowed) covers the same-origin /api/v1 fetch and inline SVG.
    The page still sets Cache-Control: private, no-store itself (balances change when a job settles; /oauth pages set the same).
    src/lib/host.ts does need "/compute" in APP_ROUTE_PREFIXES (prefix matching is path === prefix || path.startsWith(prefix + "/"), so /compute/jobs/abc is covered and /computex is not).
    Without it the marketing host serves nothing for the route and canonicalOriginFor would declare the marketing origin.

    New files (flat component names, as the issue asks for the chart):

    File Role
    src/pages/compute/index.astro the page (SSR); #496 later adds compute/jobs/[id].astro beside it
    src/lib/compute-contract.ts hand copy of the vocabulary the page depends on (job states, sources, access states, usage groups, COMPUTE_JOBS_PAGE_DEFAULT 25 and _MAX 100, COMPUTE_QUEUE_MIN_SAMPLES 5, the user error words), drift-tested
    src/lib/compute-api.ts browser-safe client: getComputeMe, getComputeUsage, listComputeJobs, ComputeApiError, the guards
    src/lib/compute-format.ts formatSu, formatSuShort, formatDuration, formatUtcTime, sumMilli
    src/lib/compute-chart.ts pure chart geometry
    src/lib/compute-badges.ts state label, tone and icon, plus source labels
    src/lib/compute-view.ts pure view models: access, balances, queue, job row, panel selection
    src/lib/compute-labels.ts the page's short UI words (headings, column headers, button text); sentences are NOT here
    src/components/ComputeAccessPanel.astro, ComputeBalances.astro, ComputeUsageChart.astro, ComputeJobsTable.astro, ComputeJobBadge.astro, ComputeQueueTable.astro, ComputePanelNotice.astro the panels
    scripts/capture-compute-read-fixtures.mjs, test/fixtures/compute/*.json captured fixtures (section 10)
    tests section 11

    Changed files: src/lib/host.ts + host.test.ts; src/styles/tokens.css (chart tokens); src/components/UserMenu.astro and src/pages/settings.astro (the link); src/lib/account-copy.ts + account-copy.test.ts (new keys); .github/workflows/ci.yml (one more sparse-checkout path and variable for the new contract drift test); scripts/local-backend.mjs + .context/local-backend.md; on merge AGENTS.md architecture map, CHANGELOG.md, .context/handoff.md.

    No new ADR (the epic reserved one, taken by ADR 0030).
    Record the decisions that are expensive to reverse (one chart per pool, independent panels, three-decimal parity with the CLI, no synthesized figures) as a short addendum to ADR 0030 in this PR.

    4. Data fetching and caching

    • The page frontmatter reads /compute/me first (it is needed for the access state), then usage and jobs in parallel, each in its own try/catch returning { ok: true, data } | { ok: false, error }, so one failure degrades one panel and never the page.
      Usage and jobs are read only when the state is active, suspended or revoked (the state comes from /me, or from the session user when /me itself failed), and not at all for an unverified account.
      For none, requested, denied and an unknown state nothing exists to read and the calls are skipped.
    • SSR calls pass { cookieHeader, fetch: apiFetch } (ADR 0026: server-only calls leave over the service binding, naming the visitor; news/index.astro is the precedent).
      compute-api.ts itself imports nothing from api-fetch.ts so it stays browser-safe (test/client-bundle-guard.test.ts must stay green).
    • Deadlines use resolveSignal with DEFAULT_REQUEST_TIMEOUT_MS (5 s) for all three; none is decorative (the page is its content).
    • Browser calls (Load more) go to /api/v1/compute/me/jobs?limit=25&after=<encoded cursor> through the existing generic proxy (no proxy change; GET is allowed, the cookie is forwarded, the proxy hard-codes no-store).
    • No client-side caching, no api-cache.ts (that is for catalog reads), no polling.
      The list serves the stored job record, which can lag a live job: the row links to the job page (Phase E3: Job page #496), which asks the cluster when the record is over 60 seconds old.
      A "Refresh" link (a plain link to /compute#jobs) is the whole freshness story in E2.
    • The usage request is group=day,partition with no from/to: the server's default window (30 days ending today, UTC) is authoritative, and the chart's axis comes from the response's from and to, so the page never builds a date from a clock.
    • compute-api.ts returns typed results; a non-OK response becomes ComputeApiError { status, code?, sentence?, kind } where kind is one of session (401), account (403), unavailable (404 or 5xx or policy_unavailable), rejected (other 4xx), timeout, network, shape.
      The parser reads { error: sentence, code }, and the 403 { error, status, message } shape separately.
      A body the guard rejects is kind: "shape", an error, never an empty list or zeros.

    Guards are hand-written (the repo has no schema library; do not add one): required keys are checked for type (Number.isSafeInteger for every *_milli, count, *_seconds; strings for ids and times; booleans), nullable keys accept null and nothing else, extra keys are ignored, unknown words in state/partition/source pass as strings.
    The guards copy out only the keys the page reads, so a key the Worker adds later (including any new pool name) cannot reach the markup by iteration.

    5. States the page must handle

    Decided by a pure panelsFor(accessState, flags) in compute-view.ts, tested.

    Situation What renders
    Signed out redirect to /login?next=/compute before any read (same as the dashboard)
    Unverified account (deriveAccountTier === "unverified") no reads; the Access panel shows the verify line from gapsForFields(["email_verified"], { block: "compute_access" }), as Settings does
    /me returns 401 redirect to /login?next=/compute
    /me returns 403 the Access panel with the backend's message as inert text; no other panel
    /me returns 404 one notice: compute is not available on this server (this is the release gate: a website talking to an API without Epic D)
    /me returns 503 policy_unavailable or any other failure the Access panel falls back to the session's compute_access state (E1's deriveComputeAccessState) and says nothing more; Balances and Queue show the notice naming what failed; usage and jobs still render if they succeeded
    none Access panel only. If requests_open (fall back to terms_published when the key is absent): badge, the label compute_access.request.cta as a link to /settings#compute-access. If not open: compute_access.terms_unpublished.body and no link
    requested Access panel: badge, requested.lede_dated with requested_at, requested.body. No other panel
    denied Access panel with compute_access.closed.body. No other panel
    active all five panels
    active and frozen as active, plus the frozen sentence (new key) in the Access panel
    suspended, revoked Access panel with suspended.body or closed.body, then Balances, Usage and Jobs read-only (history and balance are true and the person may need them); no Queue panel (it only helps someone who can submit); no frozen sentence
    a state outside the closed six Access panel with the raw word as inert text in a neutral badge; no other panel (the page decides nothing the backend did not state)
    Granted, zero usage Balances with the real numbers, Usage with the empty state ("No charges in this period." plus the axes drawn faintly), Jobs with "No jobs yet." These are three different branches from the three error branches.
    One panel's read failed ComputePanelNotice: error icon, "Could not load ", the reason class (session expired, unavailable, timed out, unexpected response) and the backend's sentence as inert text when it sent one, and a Try again link to /compute. The text says the figures are missing, which is not the same as zero.
    "Compute disabled" Not served by any read (see section 12). Do not guess it from an empty list.
    Loading SSR means no first-paint loading state. Only Load more has one: the button is disabled with aria-busy="true" and its text changes; a failure puts an inline message under the table with a Retry that keeps the same cursor.

    6. Balances and units

    Amounts are integer milli-SU. Nothing on this page divides by 1000 as a float.

    • formatSu(milli) returns the CLI's suFixed string: integer part, a dot, exactly three digits, a leading - for negatives (0 is 0.000, 999 is 0.999, 1000 is 1.000, 12500 is 12.500, -500 is -0.500, -1 is -0.001).
      No thousands separator (so the digits match nemar compute balance), tabular numerals in the CSS.
      It throws RangeError for a non-safe integer, like the CLI; the client guard rejects such a body as shape, and view-model builders run inside the panel's own try/catch, so a throw becomes that panel's notice. (Astro silently drops a component whose render throws; nothing in a template calls it directly.)
    • formatSuShort(milli) (axis ticks only): the shortest exact decimal (2.5, 10), valid because every tick is an exact multiple of the step.
    • sumMilli(values) sums integers and throws if the running sum leaves the safe range. All totals (the window total, a day total) use it. No unrounded float ever reaches a label.
    • Rounding: none for any printed amount. Only SVG coordinates and CSS widths are rounded (to 3 decimals), and never printed.
    • A negative available_milli prints as negative in the danger tone with a minus sign (never 0.000, never parentheses), and the existing sentence about overruns is shown under the table (new key).

    Presentation: one card per pool (CPU, GPU, in that order, from pools.cpu and pools.gpu only), each with four rows (Granted, Held, Charged, Available) and a bar of available / granted.
    The bar is decoration (aria-hidden); the numbers carry the meaning.
    Granted 0 means no bar and the plain fact "Nothing granted" (local label).
    Negative available means an empty bar.
    The two pools are different currencies and are never added together anywhere on the page.
    Under the cards: the units note and the available note (new keys), then the frozen sentence when it applies.

    What the word "tenant" must never become on this page.
    Behind the platform there is a partner-side pool (the tenant pool) and a platform budget that pay for jobs that were not reserved by a person, and a sweep that indexes the partner's unreserved jobs.
    No /compute/me* route serves them: the statements carry the person's own account, flag_unreserved = 0 keeps swept jobs out of the list, and the usage ledger filter is the person's own pools.
    So the page must not render, hint at, sum with, or invent: a shared or institutional allocation, a "platform remaining" figure, "covered by" language for a partner job, or anything keyed off an unrecognized pool.
    Concretely: render only pools.cpu and pools.gpu by name (never Object.keys(pools)), and show a partner job's source as the plain label "Partner site" with no sentence about who pays.
    A test feeds a /me body with an extra pools.tenant key and an extra top-level key and asserts neither reaches the view model.

    7. The usage chart

    Form: a daily bar chart of net SU charged over the response's window, one chart per pool, each bar stacked by partition.
    This refines the issue's single stacked chart for two reasons found in the contract: CPU SU and GPU SU are different currencies (adding them in one bar would be a meaningless total), and splitting by pool keeps each chart to at most three partition series plus one "other" series, which is what a legible categorical palette can hold.

    • A row belongs to a pool through /me's limits.partitions[].pool (the only pool mapping the backend serves).
      A row cannot be drawn when its partition is null (an administrator's correction) or not in the offered list. Those rows are not hidden: they are summed into a line under the charts ("Adjustments and other partitions: X SU") and listed in the table.
      This is a real backend gap (section 12); do not guess a pool from the partition's name.
    • Axes: x is the response's days from from to to, one band per day (a day without a row is a zero-height bar, which is true: the contract says a quiet group has no row). y is milli-SU from 0 to a nice ceiling computed from the largest stacked day total (the sum of the segments of one day, not the largest single segment; the issue's first test).
      Nice step = 1, 2 or 5 times a power of ten in milli-SU, aiming at about four intervals; ceiling = the next multiple of the step at or above the maximum; an all-zero range uses a 1 SU ceiling so the empty chart still has an axis.
    • A segment is drawn only for a positive net charge. A negative net row (refund or correction in that partition) is excluded from the bar, counted, and listed in the table with a visible note, so the geometry never draws below the baseline.
      A non-zero segment is never thinner than 1 px (minVisible), a zero day draws nothing.
    • Stack order and colors are by the partition's position in the offered list for that pool, not by data order, so a color keeps its meaning across windows. A pool has at most three offered partitions today; any further or unknown partition joins the "other" series.
    • Geometry is computeUsageChart({ from, to, rows, partitionsOfPool, otherLabel }) => { days[], series[], ticks[], xLabels, ceilingMilli, totalMilli, omitted }, pure and integer-based; the function that picks the nice step takes and returns integers.
    • Rendering (follow MetricSparkline): the SVG holds only bars and gridlines, with preserveAspectRatio="none", viewBox of 10 * days by 100, and vector-effect="non-scaling-stroke" on gridlines. Axis labels are HTML, positioned by percentage, so text stays crisp at any width and never scales down on a phone.
      X labels: the geometry returns a regular set (about 6 labels, as Nov 3) and a sparse set (3 labels: first, middle, last); CSS shows the sparse set below 480 px.
    • Colors: new tokens in tokens.css, defined for light, for the prefers-color-scheme: dark block guarded by :root:not([data-theme="light"]), and for :root[data-theme="dark"]: --chart-series-1..4, --chart-grid, --chart-axis.
      Suggested values (verify at least 3:1 against --admin-surface in both themes, and that series 1 and 2 stay separable in a grayscale and deuteranopia simulation; the dataviz skill has the validator): light #2a78d6, #0f766e, #b45309, #64748b; dark #3987e5, #2dd4bf, #fbbf24, #94a3b8.
      Series are also separated by a 1 px surface-colored gap and by the legend order, never by color alone. Four series is the maximum the page has to tell apart.
    • No animation at all (so prefers-reduced-motion is satisfied by construction).
    • Accessibility: <figure> with a <figcaption> (title, the window, the unit), the SVG role="img" with aria-labelledby pointing at a <title> and a <desc> that state the total, the number of days with charges, and the busiest day; each bar has a <title> ("Nov 3: gpu 2.500 SU, gpu-shared 0.500 SU, total 3.000 SU").
      Next to the chart a <details> ("Show the numbers", a local label) holds a real table of the same rows (day, one column per series, total) with exact three-decimal values; it lists only days that have a charge and says so. It is not visually hidden, so keyboard and low-vision users get it, and a copy of the page without CSS still has the data.
    • Empty state: when the window has no row for the pool, the figure keeps its axes and shows the text "No charges in this period." in place of bars. A pool with no row and nothing ever granted is not drawn at all.
    • Phone width: the chart is inline-size: 100% with a fixed height (220 px, 180 px below 480 px); the panel has the layout's 16 px gutter; the table in <details> scrolls inside its own container, never the page.
    • Copy: the sentence "Net charge by UTC day of the charge, not the day a job was created" is a new shared key (section 9); the chart title, axis names and legend are local labels.

    8. The jobs list

    Columns (all from the served fields): Job (the id in monospace, a link to /compute/jobs/<id>), State (badge), App (app_id and app_version), Partition, Front door (source), Created (UTC), Charged.
    A "cancel requested" mark (text plus icon) is added to a live job's state cell when cancel_requested is true.

    • Charged for a terminal job prints formatSu (so 0.000 is a true zero); for a live job with charged_milli = 0 it prints "Not charged yet" (a local label), because the backend charges at the end. This differs from the CLI, which prints - for zero; the comparison the acceptance criterion needs is on non-zero amounts.
    • Front door labels (local, in compute-badges.ts): cli "Command line", web "Website", partner "Partner site", pipeline "NEMAR pipeline"; an unknown word prints raw.
    • Created: YYYY-MM-DD HH:MM UTC in a <time datetime="...Z"> whose title carries the seconds. formatUtcTime parses the database text as UTC explicitly ("2026-11-05 12:00:00" becomes 2026-11-05T12:00:00Z; the bare string is parsed as local time by some engines, so a test pins it).
    • Pagination: first page of 25 server side. next_after non-null means a "Load more" control. It is an <a href="/compute?after=<encoded cursor>#jobs"> that works without JavaScript (the SSR page then renders that page of jobs; an invalid_cursor becomes the Jobs notice with a link back to the first page), and a page script intercepts it to fetch the next page through /api/v1 and append rows. The button is hidden when next_after is null, and it reads the cursor from the last answer each time, never computing one.
    • Rows are built from one pure jobRowView(job) (cells as data: kind, text, href); the SSR template and the page script are two thin renderers over it. The script builds DOM with createElement and textContent only. A source-level test forbids innerHTML, insertAdjacentHTML, set:html and outerHTML in every Compute file.
    • Untrusted text: there is no free-text job name, but app_id, app_version, partition, source, failure_code and any unknown state word come from the backend and render as text nodes through displaySafeLine-style escaping of controls and bidirectional characters (reuse mail-display.ts's set; ADR 0029 is the precedent). The job id is also checked against job_[0-9a-f]{24} before it is placed in an href; a row whose id fails the check renders without a link rather than with a guessed one.
    • Empty list: "No jobs yet." (local label), distinct from the error notice.
    • Narrow screens: below 640 px the table becomes stacked blocks (job id and badge on the first line, app, partition and front door on the second, created and charged on the third), with each cell labeled by a data-label; DOM order equals reading order; no horizontal page scroll at 360 px.
    • No state filter in E2 (the backend supports ?state=; the CLI has --state); listed as a follow-up.

    State badges (compute-badges.ts over admin-badges.ts's badgeLabel, badgeTone, badgeIcon, which already return a neutral raw-text pill for an unknown word and use Object.hasOwn, so constructor is unknown, not a function):

    State Label Tone Icon
    created Created neutral neutral
    uploading, submitted, queued, running, archiving the same word capitalized info progress
    finished Finished success ok
    failed Failed danger error
    cancelled Cancelled neutral neutral
    unreported Unreported warning warn
    anything else the raw word neutral neutral

    That is five tones in use (neutral, info, success, danger, warning), each with its own icon shape or word, never color alone.
    ComputeJobBadge.astro copies ImportStatusBadge.astro's structure and scoped styles with a sync comment.
    When any row is unreported, a legend line under the table shows the new unreported sentence (section 9) once.

    9. Queue estimates and honesty about uncertainty

    Panel "Recent queue waits" (a local label), shown for active accounts only, from /me.queue:

    • Columns: Partition, Median, 90th percentile, Jobs counted (with the window as a plain number of days from window_days).
    • median_seconds and p90_seconds print with formatDuration, the CLI's durationText (37s, 4m 12s, 1h 5m); 0 prints 0s, which is a real value and must differ from the unknown case.
    • When either figure is null, both cells read "Not enough data" and the count cell reads "N of 5 jobs" using the mirrored minimum (COMPUTE_QUEUE_MIN_SAMPLES, drift-tested). It never prints -, 0 or an empty cell.
    • The count is always shown beside a figure, so a reader can weigh a median of five against a median of two thousand. The page invents no confidence labels and no threshold of its own.
    • The panel never uses the words "estimated wait" or "your wait": it says what happened (waits between scheduler submission and start, recent jobs, the whole platform) and ends with the new queue note ("It describes the queue of the whole platform, not yours, and it is a recent average, not a promise").
    • An empty queue array (no partition offered) prints "No partitions are offered right now." (local label).
    • A partition order is the backend's.

    New shared sentences (keys in section 10): the units note, the available note, the frozen sentence, the usage note, the queue note, the unreported note, and the Settings link label.

    10. Copy: new keys, and which side

    Rule found in the code: test/account-copy-drift.test.ts fails on any website key the nemar-cli contract lacks; test/account-copy-parity.test.ts in nemar-cli fails on any non-cli. key the website lacks; a key is added to both files in the same step, and the CLI-only ones are cli.-prefixed and the website ignores them. Every value must be a plain string literal with no double quote and only declared {placeholders} (none are added).
    Existing keys reused with no change: compute_access.section.title, the six compute_access.state.*, compute_access.request.cta, compute_access.requested.lede, .lede_dated, .body, compute_access.suspended.body, compute_access.closed.body, compute_access.terms_unpublished.body, compute_access.docs_link.

    Add on BOTH sides (nemar-cli shared/contract/account-copy.ts and website src/lib/account-copy.ts; seven keys):

    Key Value
    compute_page.frozen.body Your pools are frozen, so new jobs are refused. Contact support to find out why. (identical to the CLI's string today)
    compute_page.units_note Amounts are service units (SU). (identical to the CLI's)
    compute_page.available_note Available is granted minus held minus charged and can be negative after an overrun. (the CLI help text)
    compute_page.queue_note It describes the queue of the whole platform, not yours, and it is a recent average, not a promise.
    compute_page.usage_note Net charge by UTC day of the charge, not the day a job was created. A day with no charge has no bar.
    compute_page.unreported_note NEMAR has not heard from the cluster about this job for a while. It may still finish; an administrator looks at jobs in this state.
    compute_access.granted.link Open your compute page

    On the nemar-cli side the same change makes src/commands/compute-read.ts read the first two (and embed the third and fourth in its help text) from ACCOUNT_COPY, so the two surfaces cannot drift; that is a nemar-cli issue and a small PR to file before this phase starts (nemar-cli is a separate repository and this phase must not edit it).
    Until it lands, develop against a nemar-cli worktree with the keys added, and run the drift test with NEMAR_CLI_ACCOUNT_COPY=<worktree>/shared/contract/account-copy.ts; the same CI gate as E1 applies (red until the keys are on nemar-cli dev, so the keys must not reach website staging earlier).
    The website side also updates account-copy.test.ts (the pinned key count and list) in step.

    Not shared, on purpose: headings, column headers, "Load more", "Show the numbers", "No jobs yet.", "No charges in this period.", "Not enough data", "Not charged yet", pool names, the front-door labels, the notice texts. They are single labels or state descriptions of this page, not statements the CLI also makes, so they live in src/lib/compute-labels.ts. test/compute-dashboard-ui.test.ts fails if a page or component contains a string literal of 40 or more characters with a space in it outside compute-labels.ts and the copy table, which is how E1 kept sentences out of call sites.
    Do not add a website-only key to account-copy.ts: the drift test would fail it as unmirrored.

    11. Fixtures, and the capture command

    New script scripts/capture-compute-read-fixtures.mjs, in the style of E1's capture-compute-fixtures.mjs:

    NEMAR_CLI_DIR=<nemar-cli checkout of the Epic D branch> bun scripts/capture-compute-read-fixtures.mjs

    It imports the backend's own test helpers (backend/test/helpers/compute-user-seed.ts: readApp, personWithKey, insertJob, chargeAt, correctionAt, sqliteAt; compute-seed.ts: fundAccount; d1.ts: freshDb), seeds a real migrated database through the real ledger services (placeHold, settleFinal, so the pool totals come from the ledger's triggers), calls the real router with a real hashed key, and writes the bodies unchanged.
    Request times in the seed are fixed (explicit created_at values and explicit from/to on the capture request, recorded in each file's _provenance) so a rerun produces the same bytes; only queue samples are seeded relative to now, and their figures are seconds, so they are stable.
    Each file carries _provenance (command, nemar-cli commit, route, request) and each test file names the same command in its header.
    Emails are @example.org; no job body contains an identity.

    File Content
    me-states.json GET /compute/me for each of the six states (zero pools, with the real limits and queue)
    me-active-with-usage.json granted, held and charged non-zero, enough queue samples for figures
    me-frozen.json active with a frozen pool
    me-overrun.json a negative available_milli
    me-thin-queue.json a partition with 3 samples (null figures with the count) next to one with figures
    usage-day-partition.json several days, both pools, a day-boundary entry, a null-partition correction, a quiet gap
    usage-empty.json the fresh account's rows: []
    usage-outlier.json one large day among small ones
    jobs-page1.json, jobs-page2.json limit=2 so next_after exists, then the page it points at
    jobs-all-states.json one job in each of the ten states
    jobs-empty.json { jobs: [], next_after: null }
    errors.json real refusals: invalid_cursor, invalid_limit, invalid_group, invalid_range, invalid_state, the 401 for no credential, the 403 Account not approved for a pending account

    The unreachable ones (policy_unavailable, a 502 with no JSON, a timeout) are tested as transport conditions with a real Response or an aborted AbortSignal, which the repo's rule allows for failure paths.
    Never hand-write a body that a route can produce.

    12. What the backend does not serve (file nemar-cli issues; do not synthesize)

    1. Pool on usage rows. GET /compute/me/usage cannot group by pool, and an administrator's correction has a null partition, so the page cannot say which pool a correction touched. Ask for pool as a fifth group (the ledger entry already has the pool). Until it lands, section 7's "adjustments and other partitions" line is the honest fallback.
    2. A job name or label. The submission spec has a name, but the user job view does not carry it. Ask only if the owner wants named jobs in the list; otherwise the id and app stay.
    3. Whether new jobs are being accepted. Compute on or off is not in any read (access.requests_open covers access requests only), so the page cannot say "new jobs are paused". Ask for a boolean on GET /compute/me if the owner wants a banner.
    4. The copy keys of section 10 (the nemar-cli half).
    5. Not asked for, noted: the list has no total count, no server-side search, and serves the stored record without asking the cluster; none blocks this phase.

    Website follow-ups to file (not part of this PR): a usage window selector, a ?state= filter, a Limits disclosure (the data is already in /me), and the ADR 0030 hand-off (replace compute-terms.ts, its drift test and COMPUTE_REQUESTS_ENABLED with access.current_terms_version and access.requests_open, now that /compute/me exists; see question 4).

    13. Navigation and the Settings link

    • UserMenu.astro gets a "Compute" item for a session whose compute_access is active, suspended or revoked (the states in which a person has, or had, a balance and jobs). For none, requested, denied and absent it stays out of the menu; the Settings card is that person's entry.
    • The Settings compute card, in its active branch, gets a link Open your compute page (compute_access.granted.link) to /compute, which ADR 0030 recorded as waiting for this phase. A source test pins both.
    • No dashboard-header link. The Compute page links back to /settings#compute-access for every non-active state.

    14. Gates, tests, and the browser check

    Write the pure tests first (each should fail against a deliberately broken helper before the helper exists):

    1. compute-format.test.ts: the vectors in section 6 plus 123456789012 (123456789.012), the largest safe integer, a non-safe integer and NaN and 1.5 (throw), the CLI parity table (suFixed and durationText vectors copied from nemar-cli's own tests), the UTC parse (2026-11-05 12:00:00 equals Date.UTC(2026, 10, 5, 12) whatever TZ is), formatSuShort.
    2. compute-chart.test.ts: known fixture bar positions and heights; nice ceiling (from the stacked total, with a case where the largest single segment is smaller than the largest stack); one day; an all-zero range; one large outlier; a negative net row (omitted and counted, never below zero); a null-partition and an unknown-partition row (summed aside); stable series colors across two windows; a month boundary and 366 days; label sets (regular and sparse); minimum 1 px for a tiny nonzero segment; integer-only inputs.
    3. compute-badges.test.ts: the ten states; unknown and constructor/__proto__ render raw text and neutral; the four source labels and an unknown source.
    4. compute-api.test.ts: each captured file parses; extra keys are ignored; an extra pools.tenant key and an unknown top-level key are dropped; malformed bodies raise shape (a missing gpu pool, a float amount, a string amount, jobs not an array, next_after absent); an empty jobs list is distinct from a rejected body; error mapping from the captured refusals (401 to session, 403 to account with the backend message, 400 words to rejected with code and sentence read from the right keys, 404 to unavailable); a non-JSON 502; a timeout; URL building (SSR base versus /api/v1, group=day,partition, limit, an after containing | round-trips exactly).
    5. compute-view.test.ts: panelsFor for every state including an unknown one; the access view per state (which copy keys, which link, requests_open fallback to terms_published); the frozen sentence only when active and frozen; the balance view including a negative and a zero grant; the queue view (null median prints "Not enough data" with the count and the minimum, 0 seconds prints 0s); jobRowView (live job with zero charge, terminal zero charge, unsafe id has no href, hostile app id stays text).
    6. host.test.ts: /compute and /compute/jobs/abc are app routes; /computex is not; the marketing host redirects them to the app host; canonicalOriginFor("/compute", ...) is the app origin.
    7. test/compute-dashboard-ui.test.ts (source level, like compute-access-ui.test.ts): the session guard and redirect; one try/catch per read; fetch: apiFetch for the SSR calls; Cache-Control: private, no-store set; no innerHTML, insertAdjacentHTML, set:html, outerHTML in any Compute file; no hex or rgb( color literal in the chart and badge components; the chart has role="img", <title>, <desc>, the <details> table, and no animation or transition; every ACCOUNT_COPY key the page uses exists; no long sentence literal outside the copy table and compute-labels.ts; the Settings link and the menu item.
    8. test/compute-user-contract-drift.test.ts: compute-contract.ts against nemar-cli's shared/contract/compute-user.ts and shared/compute-state.ts read as text (states, sources, usage groups, page bounds, minimum samples, error words), strict in CI through NEMAR_CLI_COMPUTE_USER_CONTRACT and NEMAR_CLI_COMPUTE_STATE with the two paths added to ci.yml's sparse checkout, as the terms drift test does.
    9. Update account-copy.test.ts for the seven keys.

    Mutation check (E1's standard): the PR lists, for each pure helper, at least one deliberate mutation that a test catches (ceiling from the largest segment; formatSu dividing as a float; the parse as local time; Object.keys(pools); a null queue figure printed as -).

    Gates, in order: bun run typecheck && bun run lint && bun run test && bun run build.
    Known from E1: bun run build can stop in generate:og when the production catalog answers 500; run astro build and say so if that happens. The two drift tests are red against nemar-cli dev until the Epic D keys reach it; run them with the variables pointed at the Epic D worktree and say which commit.

    Browser check for this phase (real browser, local backend per .context/local-backend.md: NEMAR_CLI_DIR=<Epic D worktree> bun scripts/local-backend.mjs, then PUBLIC_API_BASE_URL=http://localhost:8787 bun run dev; paste the persona cookie).
    Seed data without a mock: add a --seed-compute option to scripts/local-backend.mjs (loopback guards unchanged) that grants the active persona through the real admin route, then writes jobs in all ten states and ledger entries on several days through the backend's own seed helpers and ledger services, plus one correction and one frozen persona.
    The "real charges through the Epic A stand-in" run (a CLI-submitted job settling) belongs to the epic-level check of #496/#498; this phase only needs charges in the ledger.

    • Every access state: none (requests open and closed), requested, active, suspended, denied, revoked, and the unverified persona; each shows only the panels in section 5.
    • Active with a fresh grant: real balances equal nemar compute balance for the same account (compare all twelve numbers), an empty chart with the empty message, "No jobs yet.", and the queue panel with real counts.
    • Active with charges: the chart bars match nemar compute list --json summed by day; the table in <details> matches the bars; a correction line appears under the charts.
    • Jobs: all ten state badges, the unreported legend, Load more appends (check no duplicate and no gap with the next cursor), works with JavaScript off through the ?after= link, an edited bad after gives the Jobs notice, row links go to /compute/jobs/<id>.
    • A thin queue sample reads "Not enough data" with the count; a figure of 0 seconds reads 0s.
    • The frozen persona shows the frozen sentence; an overrun prints a negative available.
    • A forced failure of each read separately (stop the backend between reads, or point one URL at a closed port through a local-only environment variable in the test run; do not ship the switch): only that panel shows its notice, the rest render, and no unknown value looks like zero.
    • Light and dark (toggle and system), 360 px and 768 px and desktop: no horizontal page scroll, chart labels legible, series distinguishable.
    • Keyboard only: focus order is access, balances, <details>, table links, Load more; a visible focus ring; the <details> opens with Enter and Space.
    • A screen reader (or the accessibility tree dump) reads the chart's summary and the table.
    • A hostile app_id seeded with markup and control characters renders as inert text.
    • /compute on the marketing host redirects to the app host; signed out redirects to login with next.

    15. Risks

    1. Production API without Epic D. A website built against an API that has no /compute routes gets 404 on /me. The page says so (one notice), but the epic's release gate stands: do not promote until the production API serves /compute/me; check with a request.
    2. Copy keys landing order. The website drift test is red until the seven keys are in nemar-cli dev; the nemar-cli issue and PR should be filed first, and the keys must not reach staging earlier.
    3. Chart legibility. Four categorical colors plus separation is the limit; the token values above are suggestions that must pass the contrast and grayscale check, not an assumption.
    4. Stale rows. A live job's state in the list can lag; the job page refreshes. The page does not poll.
    5. Row markup drift between the SSR template and the script. Mitigated by jobRowView and the no-innerHTML test; the browser check compares appended rows with SSR rows.
    6. Date pitfalls. The database time has no zone; one helper parses it, tested under a non-UTC TZ.
    7. Money sums. A float or an unsafe integer would disagree with the CLI; sumMilli throws and the panel degrades.
    8. Rate limit. Three SSR reads per render; the service binding keys the limiter by visitor (ADR 0026), and Load more is one read per click.
    9. Per-pool charts rely on /me's offered list. A partition removed from policy later falls into "other partitions" until the backend gap in section 12 is closed.

    16. What depends on the Tapis tenant not existing yet

    Nothing in this phase calls Tapis. The three reads are ledger and job-index reads, they work with compute switched off, and the only read that asks the cluster is GET /compute/me/jobs/:id (phase #496).
    Everything here therefore works locally and on staging with the Epic A stand-in or with no stand-in at all, using rows written through the backend's real ledger services.
    What will look different once real jobs exist: charges arrive when real jobs settle (until then Usage is honestly empty and balances show only the starting grant), and the queue panel reads "Not enough data" with small counts until at least five jobs per partition have started in a week.
    In production, requests_open is false while the terms are unpublished, so the none state shows the closed-requests sentence; nothing here needs to change when the tenant and the terms go live.

    17. Commit plan (atomic, under 50 characters, no emojis, no co-author lines)

    1. Mirror the compute read vocabulary (contract file, drift test, CI path)
    2. Capture compute read fixtures (script and files)
    3. Add SU and time formatters
    4. Add usage chart geometry
    5. Add compute job state badges
    6. Add the compute read client
    7. Add compute view models
    8. Add chart color tokens
    9. Route /compute to the app host
    10. Add compute page copy keys
    11. Add the compute page with access and balances
    12. Add the usage chart panel
    13. Add the jobs panel with Load more
    14. Add the queue panel
    15. Link compute from the menu and Settings
    16. Seed compute data in the local backend
    17. Record the phase (ADR 0030 addendum, AGENTS.md map, CHANGELOG, handoff)

    Close the issue by hand after merge with a comment naming the PR and merge commit (Closes #N closes nothing on a non-default branch), update the epic issue, and record the fixture capture command there.

    18. Open questions for the owner

    1. Chart form. OK to draw one chart per pool (CPU and GPU) instead of one stacked chart, because the two pools are different currencies? The alternative is one chart whose bar total adds unlike units, which I advise against.
    2. Zero charge. OK that the list prints a true zero for a finished job (0.000) and "Not charged yet" for a live one, where the CLI prints - for both?
    3. Granted sentence. compute_access.granted.body (shared with the CLI) says you can "submit jobs from there", but the epic builds no web submission. Reword the key in both repositories, or leave it until a web submit exists? This phase does not repeat that sentence on /compute.
    4. ADR 0030 hand-off. Now that GET /compute/me is merged, should the removal of compute-terms.ts, its drift test and COMPUTE_REQUESTS_ENABLED ride on this phase as its own last commit, or stay a separate follow-up? I planned it as a follow-up to keep this PR on the dashboard.
    5. Navigation. Is the menu item for active, suspended and revoked accounts the right rule, or should every signed-in account with any compute state see it?
    6. Backend gaps. Which of section 12's items 1 to 3 do you want filed now? Item 1 (pool on usage rows) blocks drawing corrections.
    7. A Limits view. The data (limits) is already fetched; do you want it in this phase as a disclosure, or later?
    8. Frozen account. Confirm the CLI's rule (frozen sentence only for an active account) over the issue's (suspended or revoked).
  3. neuromechanist commented on Nov 7, 2026

    @neuromechanist
    ContributorAuthor

    Merged in #505 (442be8b) with the copy keys in nemarOrg/nemar-cli#2082 (caf3a77a).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions