From a44a6e604d98cc005909047a2eeb4f222be40ab0 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 20:40:35 +0000 Subject: [PATCH 01/26] Start the working record for feature 456 Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_018g33AVnD3UUpZykmcVAdbH --- specs/feature-456-runtime-container-detail/log.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 specs/feature-456-runtime-container-detail/log.md diff --git a/specs/feature-456-runtime-container-detail/log.md b/specs/feature-456-runtime-container-detail/log.md new file mode 100644 index 00000000..a0e31654 --- /dev/null +++ b/specs/feature-456-runtime-container-detail/log.md @@ -0,0 +1,8 @@ +# Log: Feature 456 - Runtime Container detail with a details column + +One line per pipeline step: date and time of day (UTC), step, member, result. Lead decisions and escalations +are quoted in full. + +| Date | Step | Member | Result | +| ---- | ---- | ------ | ------ | +| 2026-11-30 20:40 | 1 Intake | Orchestrator | Issue 456 read (enhancement, open, author LarsLaskowski), feature route to squad-spec; dependencies 451 and 452 closed; branch claude/confident-gauss-czv9z0 off main f055ace; work folder specs/feature-456-runtime-container-detail | From 69463380825c6fe0cfc2d45f77022ac59c98cff0 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 20:44:22 +0000 Subject: [PATCH 02/26] Add the spec of feature 456 Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_018g33AVnD3UUpZykmcVAdbH --- .../log.md | 1 + .../spec.md | 185 ++++++++++++++++++ 2 files changed, 186 insertions(+) create mode 100644 specs/feature-456-runtime-container-detail/spec.md diff --git a/specs/feature-456-runtime-container-detail/log.md b/specs/feature-456-runtime-container-detail/log.md index a0e31654..59ecb07b 100644 --- a/specs/feature-456-runtime-container-detail/log.md +++ b/specs/feature-456-runtime-container-detail/log.md @@ -6,3 +6,4 @@ are quoted in full. | Date | Step | Member | Result | | ---- | ---- | ------ | ------ | | 2026-11-30 20:40 | 1 Intake | Orchestrator | Issue 456 read (enhancement, open, author LarsLaskowski), feature route to squad-spec; dependencies 451 and 452 closed; branch claude/confident-gauss-czv9z0 off main f055ace; work folder specs/feature-456-runtime-container-detail | +| 2026-11-30 20:44 | 2a Spec | Lead | RESULT: DONE. spec.md written (12 criteria AC1-AC12, S1-S8, E1-E10); open questions answered; plan-check --spec clean (opus/medium · 72,514 tokens · 13 tool uses · 61 s · 22 in · 5,893 out · 532,771 cache read · 72,205 cache write · 292,764 weighted) | diff --git a/specs/feature-456-runtime-container-detail/spec.md b/specs/feature-456-runtime-container-detail/spec.md new file mode 100644 index 00000000..963a9541 --- /dev/null +++ b/specs/feature-456-runtime-container-detail/spec.md @@ -0,0 +1,185 @@ +# Spec: Runtime Container detail with a details column + +Source: Issue #456 (part of #450; builds on #451 tokens and #452 shared components) +Status: Draft + +## Problem + +The Runtime Container detail page opens with a generic title, spreads the container's facts over up to seven summary +cards of equal weight and pushes candidates and findings below three 280 px charts (issue #456, *Problem*; mockup +`docs/ui-concept/flat-refresh/preview-runtime-container-detail.png`). What the page shows and how its values are +computed stays as today ([Web UI](../../docs/areas/web-ui.md)). Facts checked against the code that differ from the +issue: + +- The page has **no vulnerability rescan** today; the per-image rescan exists on Observed Images, My Images and Runtime + Containers only. The *Rescan* in the *Details* column is new on this page (S5). +- The *Container actions* section of #280 has landed; it keeps its texts and behavior and takes the panel style (S7). +- A route with an unknown identifier already shows a not-found note with a link back + ([decision 0059](../../docs/decisions/0059-a-detail-page-shows-a-missing-record-or-a-failed-load-inline.md)); #40 is + closed. That behavior stays. +- The stored preference is shown today as a full image reference with its save time; candidate rows today read + `Saved` instead of `Select` on the stored preference, and the candidates panel shows the chip `Updating may resolve + up to {n} of {m} active findings`. These stay (S6). + +## Scenarios + +- S1: Given a known container, when the operator opens its page, then the header shows the breadcrumb + `Runtime Containers / {container name}` (the first part a link to `/runtime-containers`), the container name as the + page title, beside it the runtime status as a status chip and the update state as a status chip in its tone with + ` · {available version}` when an available version is known (`Update available · v3.2.0`), and under it the line + `{instance name} · observed {date and time}` whose instance name links to `/docker-instances/{instanceId}`. The + browser tab still reads `Runtime Container Detail`. +- S2: Given a wide window, then the page shows a main column and, to its right, a *Details* panel; given a window too + narrow for both, the *Details* panel comes directly after the header, before every other panel. +- S3: The *Details* panel lists, each with a muted label, a semibold value and optional muted lines, separated by + hairlines, in this order: + - *Runtime image*: the image reference (breaks anywhere); for an alias tag `{tag} · {resolved version}`; the short + digest `@sha256:…` in a monospace font with the full digest as tooltip (`title`). + - *Compose project and service*: `{project, else stack, else Standalone} · {service, else No service label}`, only + when project, stack or service is known. + - *Observed own image*: the linked own image as a link to `/observed-images/{id}`, else `No linked own image`. + - *Update assessment*: the update state, ` · {available version}` when known, and the update message below it when + there is one. + - *Base runtime*: only with a base runtime alert — chip `Runtime warning` (warning tone) for a container linked to + an own image, else `Runtime hint` (info tone), the summary, and the details when present. + - *Vulnerabilities*: everything the vulnerability assessment shows today (remediation hint, status chip, compact + severity chips, the details toggle with full severity chips and the `+n since last scan` / `−n fixed since last + scan` chips, `{source} · {n} active`, `Checked {date and time}` when checked) and, at the right, a secondary + button `Rescan` (S5). + - *Base image vulnerabilities*: only when base images have active findings — chip `Findings detected` (warning + tone) and the summary. +- S4: The *Resource usage* panel (meta text `Current value and the last 24 hours`) shows three cells `CPU`, `Memory` + and `Network`, each with the current value in the formats of today (`n/a` without a current sample; network + `{rx} ↓ / {tx} ↑`) and, when samples exist, a 72 px chart without axes of the stored samples of the last 24 hours + (at most 48), oldest left: CPU and memory a line over an area fill, network two lines (received, sent) on one scale. + Each chart is announced as an image named `CPU history, last 24 hours`, `Memory history, last 24 hours` or `Network + history, last 24 hours`. Under each chart one muted line gives the range of the period: `Min {cpu} · max {cpu}`, + `Min {memory} · max {memory}` (memory used, without the limit), `Max {rx} ↓ / {tx} ↑`. +- S5: When the operator presses *Rescan* in the *Details* panel, the vulnerability refresh of the container's current + image version runs as the per-image rescan does on the list pages; the button is disabled while it runs, is announced + as `Rescan vulnerabilities`, and afterwards the page reloads the container so the *Vulnerabilities* entry and the + *Vulnerability findings* panel show the new result. +- S6: The *Available tag candidates* panel shows under its title the muted line `Manual tag preference: none.` or + `Manual tag preference: {stored image reference}, saved {date and time}.`, followed by `Selecting a tag stores a + preference; it does not change or redeploy the container.`; with a stored preference a secondary button `Clear + selection` stands at the right of the panel header. Below, when update findings are active and fixable findings + exist, the info chip `Updating may resolve up to {n} of {m} active findings`. The table has `Tag` (semibold, its + resolved version below for an alias; a chip `Recommended` in the success tone on each candidate the update assessment + recommends; a chip `Selected` in the info tone on the stored preference), `Digest` (short, monospace, muted, full + digest as tooltip; `No digest` without one), `Reason`, `Published` (date, muted; `—` when unknown) and `Action` (a + secondary button `Select`, `Saved` on the stored preference). *Select* and *Clear selection* store or remove the + preference as today: all these buttons are disabled while one saves, the page reloads afterwards, and a failure shows + `Saving the tag selection failed: {reason}` or `Clearing the tag selection failed: {reason}` on the page. The + separate *Manual tag preference* section is gone. +- S7: The main column holds, in this order and as flat panels without the descriptions under their titles (the + *Container actions* texts excepted): *Container actions* (only when shown today, with its description as a muted + line, its note, buttons, outcome and action history unchanged), *Resource usage*, *Available tag candidates*, + *Update findings* (`Type`, `Summary`, `Recommended`, `Tag candidates`, content unchanged), *Vulnerability findings* + (meta text `{n} active · checked {date and time}`; the findings table with its filter and resolved-findings toggle, + flush in the panel), *Base image chain* (`Depth`, `Base image`, `Source`, `Vulnerabilities` with the status as a + status chip in its tone, the severity chips and `{n} active · {source}`), *Scan history* (`Status` as the scan status + indicator, `Trigger`, `Started`, `Error`; the scans of the 20 most recent snapshots). Every table uses the shared + table style. +- S8: While the container loads, the page shows a header skeleton and panel skeletons in the two-column shape. + +## Errors and edge cases + +- E1: A route whose container is unknown shows, as today, the note `This container is not known on this Docker + instance.` with the link `Back to Runtime Containers`; a failed load shows the alert `Loading the container failed: + {reason}`. In both the header shows the breadcrumb link `Runtime Containers` and the title `Runtime Container + Detail` (decision 0059: the page keeps its header), no chips and no description line, and no columns. +- E2: Without resource samples a usage cell shows its current value (or `n/a`), no chart and no range line; the panel + shows below the cells `No resource history is currently stored for this container.` +- E3: With one sample, or with samples that are all equal (all zero included), the chart draws a flat line at that + value and the range line shows the same value for min and max. +- E4: Without an available version the update chip and the *Update assessment* value show the state alone, with no + ` · `. An update state with no tone of its own (`Not evaluated`, `Unsupported`) and a runtime status other than + `Running`, `Paused` or `Restarting` (`Exited`) show neutral chips. +- E5: A never checked image shows `{n} active` alone as the *Vulnerability findings* meta text and no `Checked` line in + the *Vulnerabilities* entry; *Rescan* is still offered. +- E6: A failed rescan shows `Vulnerability rescan failed: {reason}` below the *Vulnerabilities* entry, is logged as + user action `VulnerabilityRescan`, and leaves the page usable; the rescan can be started again. +- E7: Leaving the route while a rescan, a save or a clear runs drops its result for the new route (decision 0060); a + rescan error of an earlier route is not shown on the new one. +- E8: A stored preference whose tag is not among the shown candidates still appears in the panel's muted line, and no + row carries `Selected`. +- E9: No candidates: the panel keeps its muted line and shows `No tag candidates are currently stored for this + container.`; no update findings, no base image chain: today's empty-state texts. +- E10: Long references, names or messages wrap inside their column. + +## Non-functional requirements + +- N1: No horizontal page overflow at window widths of 390, 768 and 1280 px; below 960 px the tables show as cards and + the three usage cells stack. +- N2: The persistent component state of the page, the number of samples (48), snapshots (20) and action runs (20) + shown, and the actions' error prefixes and logged actions stay as they are; the rescan adds no new prefix or logged + action. +- N3: The chart is a shared component that another page can reuse (Docker Instances in 8/9); its stroke stays 1.5 px + wide whatever the chart's width, and it takes its colors from the chart tokens `--dug-chart-cpu`/`-fill`, + `--dug-chart-memory`/`-fill`, `--dug-chart-net-rx`, `--dug-chart-net-tx` in both themes. +- N4: The page has no color helpers of its own for statuses any more: every status chip and indicator on it takes its + tone from the shared mapping (Web UI, *Shared display*). + +## Acceptance criteria + +- AC1: For a known container the header shows the breadcrumb with its link to `/runtime-containers`, the container + name as the title, the runtime status chip and the update chip (with ` · {version}` only when an available version is + known), and the line `{instance name} · observed {date and time}` with the instance link; the tab title stays + `Runtime Container Detail` (S1, E4). +- AC2: An unknown container and a failed load keep today's note or alert under a header with the breadcrumb link and + the title `Runtime Container Detail`, without chips, description line or columns (E1). +- AC3: The *Details* panel shows its seven entries in the order of S3 with today's contents; *Compose project and + service*, *Base runtime* and *Base image vulnerabilities* appear only under today's conditions, *Base runtime* with + the chip and tone that depend on a linked own image (S3). +- AC4: The *Rescan* button of the *Vulnerabilities* entry runs the vulnerability refresh of the container's current + image version, is disabled while it runs, is announced as `Rescan vulnerabilities`, reloads the page's container + afterwards, and on failure shows `Vulnerability rescan failed: {reason}` and logs `VulnerabilityRescan` (S5, E5, E6, + E7). +- AC5: *Resource usage* shows the three cells with today's current values, and per cell with samples a chart announced + as `{CPU|Memory|Network} history, last 24 hours` of at most 48 samples oldest first plus its range line; without + samples no chart, no range line and the empty-state text (S4, E2, E3). +- AC6: The shared chart component draws one line over an area fill, or two lines on one scale, 72 px high, without + axes, with `role="img"` and the given label; one value or equal values give a flat line (S4, E3, N3). +- AC7: The *Available tag candidates* panel shows what S6 lists, `Clear selection` only with a stored preference, + `Recommended` on every recommended candidate and `Selected` on the stored preference; its buttons save, reload and + report failures as today; no *Manual tag preference* section remains (S6, E8, E9). +- AC8: The main column shows its panels in the order of S7, *Container actions* only when shown today and with its + texts unchanged; no panel has a description line other than those S6 and S7 name; *Vulnerability findings* has the + meta text `{n} active · checked {date and time}` (`{n} active` when never checked); *Scan history* shows the status + as the scan status indicator (S7, E5, E9). +- AC9: In the page's markup the *Details* panel precedes the main column's panels, and in a narrow window it is shown + directly after the header (S2). +- AC10: No horizontal overflow at 390, 768 and 1280 px, tables as cards and stacked usage cells below 960 px, and the + loading state shows header and panel skeletons in the two-column shape — checked by hand on a build (S8, N1, E10). +- AC11: The page's status chips take their tones from the shared mapping and the page defines no status color helper; + persistent state, shown counts, error prefixes and logged actions are unchanged (N2, N4). +- AC12: `docs/areas/web-ui.md` describes the page as built (*Area documents*) (N2). + +## Out of scope + +- Container actions beyond today's (#280 follow-ups) and a change of what a manual tag selection means (#291); if #291 + lands first, the preference sentence follows the behavior then in force. +- The other detail pages (9/9) and the Docker Instances charts (8/9), which reuse the chart later. +- Links on base images of the chain (drawn in the mockup, absent today); an HTTP 404 for an unknown container. + +## Open questions + +- Axes of the histories. Answered: the charts have no axes, as drawn; each gets one muted range line under it (the + issue's proposal), in the formats of the current values (S4). +- Can the page tell the recommended candidate? Answered: yes. Every candidate carries the recommendation the update + evaluation stored with it (the candidate whose tag is the evaluation's recommended tag), and the page marks it today + by chip color; the available update version is derived from that same candidate. It gets a `Recommended` chip in the + success tone (S6). +- Should the instance name in the description line link to the instance's page? Answered: yes, to + `/docker-instances/{instanceId}` (S1), as the issue proposes. +- Is the rescan new on this page? Answered: yes (see *Problem*); the issue's *Scope* §3 asks for it, and it reuses the + per-image rescan's behavior, error text and log entry (S5). + +## Area documents + +- `docs/areas/web-ui.md`: the *Pages and routes* row of the Runtime Container detail (header, *Details* column and its + entries, the main column's panels in order, the chart without axes and its range line); the actions table (*Rescan + (per image)* also on Runtime Container detail); *Container actions section* (first panel of the main column instead + of "directly after the container summary"); *Shared display* (the shared resource chart). The document holds 4977 + words of its 5000-word limit, so the plan decides a split (for example the detail pages into their own area + document) before it grows. From a7b4aced7bf9ecdf4f7a9ef3e3225937fff336dd Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 20:46:19 +0000 Subject: [PATCH 03/26] Record the spec challenge of feature 456 Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_018g33AVnD3UUpZykmcVAdbH --- specs/feature-456-runtime-container-detail/log.md | 1 + 1 file changed, 1 insertion(+) diff --git a/specs/feature-456-runtime-container-detail/log.md b/specs/feature-456-runtime-container-detail/log.md index 59ecb07b..5427387a 100644 --- a/specs/feature-456-runtime-container-detail/log.md +++ b/specs/feature-456-runtime-container-detail/log.md @@ -7,3 +7,4 @@ are quoted in full. | ---- | ---- | ------ | ------ | | 2026-11-30 20:40 | 1 Intake | Orchestrator | Issue 456 read (enhancement, open, author LarsLaskowski), feature route to squad-spec; dependencies 451 and 452 closed; branch claude/confident-gauss-czv9z0 off main f055ace; work folder specs/feature-456-runtime-container-detail | | 2026-11-30 20:44 | 2a Spec | Lead | RESULT: DONE. spec.md written (12 criteria AC1-AC12, S1-S8, E1-E10); open questions answered; plan-check --spec clean (opus/medium · 72,514 tokens · 13 tool uses · 61 s · 22 in · 5,893 out · 532,771 cache read · 72,205 cache write · 292,764 weighted) | +| 2026-11-30 20:46 | 2a Spec challenge | Devil's Advocate | VERDICT: OBJECTIONS 1 major, 4 minor. Major: N4/AC11 contradict S7 (GetActionStatusColor of the action history, Requested has no shared tone). Minor: (1) existing VulnerabilityRescanControl is an icon button with its own Checked/Never scanned line, not matching S3/S5/E5; (2) view data lacks ImageVersionId, persisted JSON changes (N2 wording, persistent-state test); (3) reuse the list page's sparkline path logic, pin E3's flat line position; (4) PageHeader.Description is a plain string, link needs an additive description fragment (opus/medium · 76,699 tokens · 16 tool uses · 95 s · 30 in · 9,459 out · 793,214 cache read · 69,043 cache write · 346,579 weighted) | From 3741803217f615636529514bc0ff24d579bb0bca Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 20:47:29 +0000 Subject: [PATCH 04/26] Revise the spec of feature 456 after the challenge Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_018g33AVnD3UUpZykmcVAdbH --- .../log.md | 1 + .../spec.md | 93 +++++++++++-------- 2 files changed, 57 insertions(+), 37 deletions(-) diff --git a/specs/feature-456-runtime-container-detail/log.md b/specs/feature-456-runtime-container-detail/log.md index 5427387a..65d58ac6 100644 --- a/specs/feature-456-runtime-container-detail/log.md +++ b/specs/feature-456-runtime-container-detail/log.md @@ -8,3 +8,4 @@ are quoted in full. | 2026-11-30 20:40 | 1 Intake | Orchestrator | Issue 456 read (enhancement, open, author LarsLaskowski), feature route to squad-spec; dependencies 451 and 452 closed; branch claude/confident-gauss-czv9z0 off main f055ace; work folder specs/feature-456-runtime-container-detail | | 2026-11-30 20:44 | 2a Spec | Lead | RESULT: DONE. spec.md written (12 criteria AC1-AC12, S1-S8, E1-E10); open questions answered; plan-check --spec clean (opus/medium · 72,514 tokens · 13 tool uses · 61 s · 22 in · 5,893 out · 532,771 cache read · 72,205 cache write · 292,764 weighted) | | 2026-11-30 20:46 | 2a Spec challenge | Devil's Advocate | VERDICT: OBJECTIONS 1 major, 4 minor. Major: N4/AC11 contradict S7 (GetActionStatusColor of the action history, Requested has no shared tone). Minor: (1) existing VulnerabilityRescanControl is an icon button with its own Checked/Never scanned line, not matching S3/S5/E5; (2) view data lacks ImageVersionId, persisted JSON changes (N2 wording, persistent-state test); (3) reuse the list page's sparkline path logic, pin E3's flat line position; (4) PageHeader.Description is a plain string, link needs an additive description fragment (opus/medium · 76,699 tokens · 16 tool uses · 95 s · 30 in · 9,459 out · 793,214 cache read · 69,043 cache write · 346,579 weighted) | +| 2026-11-30 20:47 | 2a Spec revise (challenge) | Lead | RESULT: DONE. All 5 objections accepted and answered in the spec's Challenge section: Requested tone added to the shared mapping and action history moved to StatusChip (S7, N4, AC11); text Rescan button with one Checked line (S5, AC4, E6); persisted detail gains the image version id (N2, AC11); flat line at mid-height (E3, AC6); additive PageHeader description fragment (N5, AC1) (opus/medium · 51,914 tokens · 17 tool uses · 73 s · 28 in · 7,705 out · 1,516,290 cache read · 17,503 cache write · 272,492 weighted · continued) | diff --git a/specs/feature-456-runtime-container-detail/spec.md b/specs/feature-456-runtime-container-detail/spec.md index 963a9541..b16c4632 100644 --- a/specs/feature-456-runtime-container-detail/spec.md +++ b/specs/feature-456-runtime-container-detail/spec.md @@ -17,9 +17,7 @@ issue: - A route with an unknown identifier already shows a not-found note with a link back ([decision 0059](../../docs/decisions/0059-a-detail-page-shows-a-missing-record-or-a-failed-load-inline.md)); #40 is closed. That behavior stays. -- The stored preference is shown today as a full image reference with its save time; candidate rows today read - `Saved` instead of `Select` on the stored preference, and the candidates panel shows the chip `Updating may resolve - up to {n} of {m} active findings`. These stay (S6). +- Today's preference reference with save time, the `Saved` button label and the fixable-findings chip stay (S6). ## Scenarios @@ -56,8 +54,9 @@ issue: history, last 24 hours`. Under each chart one muted line gives the range of the period: `Min {cpu} · max {cpu}`, `Min {memory} · max {memory}` (memory used, without the limit), `Max {rx} ↓ / {tx} ↑`. - S5: When the operator presses *Rescan* in the *Details* panel, the vulnerability refresh of the container's current - image version runs as the per-image rescan does on the list pages; the button is disabled while it runs, is announced - as `Rescan vulnerabilities`, and afterwards the page reloads the container so the *Vulnerabilities* entry and the + image version runs as the per-image rescan does on the list pages; the button is a text button `Rescan` (the list + pages keep their icon button), disabled while it runs, announced as `Rescan vulnerabilities`; the entry keeps the + one `Checked` line of the assessment and no `Never scanned` text; afterwards the page reloads the container so the *Vulnerabilities* entry and the *Vulnerability findings* panel show the new result. - S6: The *Available tag candidates* panel shows under its title the muted line `Manual tag preference: none.` or `Manual tag preference: {stored image reference}, saved {date and time}.`, followed by `Selecting a tag stores a @@ -73,7 +72,8 @@ issue: separate *Manual tag preference* section is gone. - S7: The main column holds, in this order and as flat panels without the descriptions under their titles (the *Container actions* texts excepted): *Container actions* (only when shown today, with its description as a muted - line, its note, buttons, outcome and action history unchanged), *Resource usage*, *Available tag candidates*, + line, its note, buttons, outcome and action history unchanged, the run status as a status chip whose tone keeps + today's colors: *requested* orange through a new `Requested` entry of the shared mapping), *Resource usage*, *Available tag candidates*, *Update findings* (`Type`, `Summary`, `Recommended`, `Tag candidates`, content unchanged), *Vulnerability findings* (meta text `{n} active · checked {date and time}`; the findings table with its filter and resolved-findings toggle, flush in the panel), *Base image chain* (`Depth`, `Base image`, `Source`, `Vulnerabilities` with the status as a @@ -90,8 +90,8 @@ issue: Detail` (decision 0059: the page keeps its header), no chips and no description line, and no columns. - E2: Without resource samples a usage cell shows its current value (or `n/a`), no chart and no range line; the panel shows below the cells `No resource history is currently stored for this container.` -- E3: With one sample, or with samples that are all equal (all zero included), the chart draws a flat line at that - value and the range line shows the same value for min and max. +- E3: With one sample, or with samples that are all equal (all zero included), the chart draws a flat line at + mid-height and the range line shows the same value for min and max. - E4: Without an available version the update chip and the *Update assessment* value show the state alone, with no ` · `. An update state with no tone of its own (`Not evaluated`, `Unsupported`) and a runtime status other than `Running`, `Paused` or `Restarting` (`Exited`) show neutral chips. @@ -99,47 +99,47 @@ issue: the *Vulnerabilities* entry; *Rescan* is still offered. - E6: A failed rescan shows `Vulnerability rescan failed: {reason}` below the *Vulnerabilities* entry, is logged as user action `VulnerabilityRescan`, and leaves the page usable; the rescan can be started again. -- E7: Leaving the route while a rescan, a save or a clear runs drops its result for the new route (decision 0060); a - rescan error of an earlier route is not shown on the new one. -- E8: A stored preference whose tag is not among the shown candidates still appears in the panel's muted line, and no - row carries `Selected`. -- E9: No candidates: the panel keeps its muted line and shows `No tag candidates are currently stored for this - container.`; no update findings, no base image chain: today's empty-state texts. -- E10: Long references, names or messages wrap inside their column. +- E7: A rescan, save or clear result or error of an earlier route is not shown on a new one (decision 0060). +- E8: A stored preference not among the shown candidates appears only in the muted line. +- E9: Empty candidates, update findings or base image chain show today's empty-state texts. ## Non-functional requirements - N1: No horizontal page overflow at window widths of 390, 768 and 1280 px; below 960 px the tables show as cards and the three usage cells stack. -- N2: The persistent component state of the page, the number of samples (48), snapshots (20) and action runs (20) - shown, and the actions' error prefixes and logged actions stay as they are; the rescan adds no new prefix or logged - action. +- N2: The page keeps its persistent-state key and behavior (the persisted detail gains the container's image version + id, which the rescan needs); the number of samples (48), snapshots (20) and action runs (20) shown and the actions' + error prefixes and logged actions stay; the rescan adds no new prefix or logged action. - N3: The chart is a shared component that another page can reuse (Docker Instances in 8/9); its stroke stays 1.5 px wide whatever the chart's width, and it takes its colors from the chart tokens `--dug-chart-cpu`/`-fill`, `--dug-chart-memory`/`-fill`, `--dug-chart-net-rx`, `--dug-chart-net-tx` in both themes. -- N4: The page has no color helpers of its own for statuses any more: every status chip and indicator on it takes its - tone from the shared mapping (Web UI, *Shared display*). +- N4: The page has no color helpers of its own for statuses any more, the action-run status included: every status + chip and indicator on it takes its tone from the shared mapping (Web UI, *Shared display*), which gains `Requested` + in the warning tone. +- N5: The shared page header can take a description with a link; pages passing a plain-text description render as + before. ## Acceptance criteria - AC1: For a known container the header shows the breadcrumb with its link to `/runtime-containers`, the container name as the title, the runtime status chip and the update chip (with ` · {version}` only when an available version is known), and the line `{instance name} · observed {date and time}` with the instance link; the tab title stays - `Runtime Container Detail` (S1, E4). + `Runtime Container Detail`; a page passing the header a plain-text description renders it as before (S1, E4, N5). - AC2: An unknown container and a failed load keep today's note or alert under a header with the breadcrumb link and the title `Runtime Container Detail`, without chips, description line or columns (E1). - AC3: The *Details* panel shows its seven entries in the order of S3 with today's contents; *Compose project and service*, *Base runtime* and *Base image vulnerabilities* appear only under today's conditions, *Base runtime* with the chip and tone that depend on a linked own image (S3). -- AC4: The *Rescan* button of the *Vulnerabilities* entry runs the vulnerability refresh of the container's current - image version, is disabled while it runs, is announced as `Rescan vulnerabilities`, reloads the page's container +- AC4: The text button `Rescan` of the *Vulnerabilities* entry runs the vulnerability refresh of the container's + current image version, is disabled while it runs, is announced as `Rescan vulnerabilities`, leaves the entry one + `Checked` line at most and no `Never scanned`, reloads the page's container afterwards, and on failure shows `Vulnerability rescan failed: {reason}` and logs `VulnerabilityRescan` (S5, E5, E6, E7). - AC5: *Resource usage* shows the three cells with today's current values, and per cell with samples a chart announced as `{CPU|Memory|Network} history, last 24 hours` of at most 48 samples oldest first plus its range line; without samples no chart, no range line and the empty-state text (S4, E2, E3). - AC6: The shared chart component draws one line over an area fill, or two lines on one scale, 72 px high, without - axes, with `role="img"` and the given label; one value or equal values give a flat line (S4, E3, N3). + axes, with `role="img"` and the given label; one value or equal values give a flat line at mid-height (S4, E3, N3). - AC7: The *Available tag candidates* panel shows what S6 lists, `Clear selection` only with a stored preference, `Recommended` on every recommended candidate and `Selected` on the stored preference; its buttons save, reload and report failures as today; no *Manual tag preference* section remains (S6, E8, E9). @@ -150,9 +150,11 @@ issue: - AC9: In the page's markup the *Details* panel precedes the main column's panels, and in a narrow window it is shown directly after the header (S2). - AC10: No horizontal overflow at 390, 768 and 1280 px, tables as cards and stacked usage cells below 960 px, and the - loading state shows header and panel skeletons in the two-column shape — checked by hand on a build (S8, N1, E10). -- AC11: The page's status chips take their tones from the shared mapping and the page defines no status color helper; - persistent state, shown counts, error prefixes and logged actions are unchanged (N2, N4). + loading state shows header and panel skeletons in the two-column shape — checked by hand on a build (S8, N1). +- AC11: The page's status chips, the action-run status included, take their tones from the shared mapping, in which + `Requested` is the warning tone, and the page defines no status color helper; the persistent-state key, shown + counts, error prefixes and logged actions are unchanged, and a detail restored from persistent state carries the + image version id (N2, N4). - AC12: `docs/areas/web-ui.md` describes the page as built (*Area documents*) (N2). ## Out of scope @@ -160,18 +162,16 @@ issue: - Container actions beyond today's (#280 follow-ups) and a change of what a manual tag selection means (#291); if #291 lands first, the preference sentence follows the behavior then in force. - The other detail pages (9/9) and the Docker Instances charts (8/9), which reuse the chart later. -- Links on base images of the chain (drawn in the mockup, absent today); an HTTP 404 for an unknown container. +- Base image links (drawn in the mockup); an HTTP 404 for an unknown container. ## Open questions - Axes of the histories. Answered: the charts have no axes, as drawn; each gets one muted range line under it (the issue's proposal), in the formats of the current values (S4). -- Can the page tell the recommended candidate? Answered: yes. Every candidate carries the recommendation the update - evaluation stored with it (the candidate whose tag is the evaluation's recommended tag), and the page marks it today - by chip color; the available update version is derived from that same candidate. It gets a `Recommended` chip in the - success tone (S6). -- Should the instance name in the description line link to the instance's page? Answered: yes, to - `/docker-instances/{instanceId}` (S1), as the issue proposes. +- Can the page tell the recommended candidate? Answered: yes; each candidate carries the evaluation's recommendation + (shown today by chip color, and the source of the available version). It gets a `Recommended` chip in the success + tone (S6). +- Link the instance name? Answered: yes, as the issue proposes (S1). - Is the rescan new on this page? Answered: yes (see *Problem*); the issue's *Scope* §3 asks for it, and it reuses the per-image rescan's behavior, error text and log entry (S5). @@ -180,6 +180,25 @@ issue: - `docs/areas/web-ui.md`: the *Pages and routes* row of the Runtime Container detail (header, *Details* column and its entries, the main column's panels in order, the chart without axes and its range line); the actions table (*Rescan (per image)* also on Runtime Container detail); *Container actions section* (first panel of the main column instead - of "directly after the container summary"); *Shared display* (the shared resource chart). The document holds 4977 - words of its 5000-word limit, so the plan decides a split (for example the detail pages into their own area - document) before it grows. + of "directly after the container summary"); *Shared display* (the chart; `Requested` in the warning tone). At 4977 + of 5000 words, the plan decides a split. + +## Challenge + +- Major 1 (N4/AC11 contradict S7: the action history colors its status with the page's own helper, and the shared + mapping has no `Requested`). Accepted: the action-run status becomes a status chip, the shared mapping gains + `Requested` in the warning tone so today's colors stay (succeeded green, failed red, running blue, requested orange, + cancelled neutral), and N4, S7 and AC11 say so. Exempting the history was rejected: it would leave one page helper + beside the shared mapping the issue removes. +- Minor 1 (the rescan control's own `Checked`/`Never scanned` line duplicates or contradicts the card's). Accepted: + S5 and AC4 state one `Checked` line from the assessment, no `Never scanned`, a text button `Rescan` announced as + `Rescan vulnerabilities`; the list pages keep their icon button. Error text and log entry stay those of the + per-image rescan (E6). +- Minor 2 (the view data lacks the image version id; persisted JSON changes). Accepted: N2 now keeps the + persistent-state key and behavior and states that the persisted detail gains the image version id; AC11 asks that a + restored detail carries it. +- Minor 3 (one sample and equal values are drawn at different heights by the list's builder). Accepted: E3 and AC6 + name mid-height for both. Network keeps one scale (S4); the list page's sparklines and their separate scales stay as + they are. Whether the shared chart takes over the list's path logic is the plan's choice under the duplication rule. +- Minor 4 (`PageHeader` takes the description as plain text only). Accepted: N5 adds a linked description to the + shared header as an additive change; pages passing plain text render as before (AC1). From 79a1d0d451f095290bfc06cffa8c8df8736d7ebf Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 20:55:13 +0000 Subject: [PATCH 05/26] Add plan, tasks and decision record for feature 456 Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_018g33AVnD3UUpZykmcVAdbH --- ...sparklines-from-one-shared-path-builder.md | 40 +++++ docs/decisions/README.md | 1 + .../log.md | 1 + .../plan.md | 150 ++++++++++++++++++ .../spec.md | 22 +-- .../tasks.md | 14 ++ 6 files changed, 217 insertions(+), 11 deletions(-) create mode 100644 docs/decisions/0083-resource-histories-are-drawn-as-svg-sparklines-from-one-shared-path-builder.md create mode 100644 specs/feature-456-runtime-container-detail/plan.md create mode 100644 specs/feature-456-runtime-container-detail/tasks.md diff --git a/docs/decisions/0083-resource-histories-are-drawn-as-svg-sparklines-from-one-shared-path-builder.md b/docs/decisions/0083-resource-histories-are-drawn-as-svg-sparklines-from-one-shared-path-builder.md new file mode 100644 index 00000000..a2e71da9 --- /dev/null +++ b/docs/decisions/0083-resource-histories-are-drawn-as-svg-sparklines-from-one-shared-path-builder.md @@ -0,0 +1,40 @@ +# 0083: Resource histories are drawn as SVG sparklines from one shared path builder + +- **Status:** Proposed +- **Date:** 2026-11-30 +- **Area:** Web UI +- **Source:** Issue #456 +- **Supersedes:** — + +## Context + +The flat refresh (#450) draws the 24-hour resource histories of a container as small charts without axes, 72 px high, +with a constant 1.5 px stroke and an area fill in the chart tokens (#456); the Docker Instances page will use the same +chart (8/9). The detail page drew them with MudBlazor's line chart (axes, labels, 280 px). The Runtime Containers list +already draws trends of the latest samples as inline SVG paths, built by a private method of that page that places one +sample at mid-height and a series of equal values at the bottom edge. + +## Options considered + +1. **One SVG chart component over a path builder shared with the list's sparklines** — the component and the list + draw from the same code; MudBlazor's chart is not involved. The list's flat line of equal values moves from the + bottom edge to mid-height. +2. **MudBlazor's line chart with axes, labels and legend switched off** — keeps one chart library, but its stroke + scales with the drawing, its area fill and colors do not follow the chart tokens without overriding its generated + markup, and its rendering would need a probe at 72 px. +3. **A new SVG component with its own path code beside the list's** — leaves the list untouched, but duplicates the + path logic, which the quality gate's duplication condition on new code reports. + +## Decision + +Resource histories are drawn as SVG paths by a shared chart component in `Components/Common`, whose paths come from +one path builder that the Runtime Containers list uses too. One sample and a series of equal values are drawn as a +flat line at mid-height; the scale is set by the caller, so a chart can draw two series on one scale. The resulting +behavior is stated where the pages that show it are described ([Web UI](../areas/web-ui.md#pages-and-routes)). + +## Consequences + +- The list's sparklines and the detail charts change together; a series of equal values on the list now sits at + mid-height instead of the bottom edge. +- No axes: the period's range is a text line under each chart instead of grid lines. +- `ResourceUsageChartBuilder` stays for the Docker Instances page until 8/9 moves it to the shared chart. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 1610cdf9..5b6d4a7a 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -148,4 +148,5 @@ once in the [area document](../areas/README.md) of the record's area, and the re | [0080](0080-the-dashboard-counts-the-containers-advisories-and-own-images-it-lists.md) | The dashboard counts the containers, advisories and own images it lists | Accepted | 2026-11-29 | | [0081](0081-the-navigation-row-shows-from-1360-px-and-a-drawer-below.md) | The navigation row shows from 1360 px, and a drawer below | Accepted | 2026-11-29 | | [0082](0082-the-runtime-container-list-names-the-highest-active-severity-and-keeps-a-failed-checks-status-beside-it.md) | The runtime container list names the highest active severity and keeps a failed check's status beside it | Accepted | 2026-11-30 | +| [0083](0083-resource-histories-are-drawn-as-svg-sparklines-from-one-shared-path-builder.md) | Resource histories are drawn as SVG sparklines from one shared path builder | Proposed | 2026-11-30 | diff --git a/specs/feature-456-runtime-container-detail/log.md b/specs/feature-456-runtime-container-detail/log.md index 65d58ac6..fe1f1b8f 100644 --- a/specs/feature-456-runtime-container-detail/log.md +++ b/specs/feature-456-runtime-container-detail/log.md @@ -9,3 +9,4 @@ are quoted in full. | 2026-11-30 20:44 | 2a Spec | Lead | RESULT: DONE. spec.md written (12 criteria AC1-AC12, S1-S8, E1-E10); open questions answered; plan-check --spec clean (opus/medium · 72,514 tokens · 13 tool uses · 61 s · 22 in · 5,893 out · 532,771 cache read · 72,205 cache write · 292,764 weighted) | | 2026-11-30 20:46 | 2a Spec challenge | Devil's Advocate | VERDICT: OBJECTIONS 1 major, 4 minor. Major: N4/AC11 contradict S7 (GetActionStatusColor of the action history, Requested has no shared tone). Minor: (1) existing VulnerabilityRescanControl is an icon button with its own Checked/Never scanned line, not matching S3/S5/E5; (2) view data lacks ImageVersionId, persisted JSON changes (N2 wording, persistent-state test); (3) reuse the list page's sparkline path logic, pin E3's flat line position; (4) PageHeader.Description is a plain string, link needs an additive description fragment (opus/medium · 76,699 tokens · 16 tool uses · 95 s · 30 in · 9,459 out · 793,214 cache read · 69,043 cache write · 346,579 weighted) | | 2026-11-30 20:47 | 2a Spec revise (challenge) | Lead | RESULT: DONE. All 5 objections accepted and answered in the spec's Challenge section: Requested tone added to the shared mapping and action history moved to StatusChip (S7, N4, AC11); text Rescan button with one Checked line (S5, AC4, E6); persisted detail gains the image version id (N2, AC11); flat line at mid-height (E3, AC6); additive PageHeader description fragment (N5, AC1) (opus/medium · 51,914 tokens · 17 tool uses · 73 s · 28 in · 7,705 out · 1,516,290 cache read · 17,503 cache write · 272,492 weighted · continued) | +| 2026-11-30 20:55 | 2b Plan | Lead | RESULT: DONE. Spec approved by Lead; plan.md and tasks.md written, tier standard, security area Container actions touched; decision record 0083 (Proposed); shared chart via SparklinePathBuilder; new area document detail-pages.md (opus/medium · 107,760 tokens · 46 tool uses · 455 s · 88 in · 47,087 out · 7,735,359 cache read · 106,569 cache write · 1,511,004 weighted · continued) | diff --git a/specs/feature-456-runtime-container-detail/plan.md b/specs/feature-456-runtime-container-detail/plan.md new file mode 100644 index 00000000..2a74f23f --- /dev/null +++ b/specs/feature-456-runtime-container-detail/plan.md @@ -0,0 +1,150 @@ +# Plan: Runtime Container detail with a details column + +Source: Issue #456 | [spec.md](spec.md) +Tier: standard — a UI behavior change (new layout, a rescan on a new page, shared chart and tone mapping) that creates, changes or removes no security control +Security areas touched: Container actions (`Components/Pages/RuntimeContainerDetail.razor`: the section is moved and restyled; offered actions, confirmation, execution and recorded runs unchanged) + +## Problem / root cause + +See [spec.md](spec.md), *Problem*. + +## Verified facts + +| # | Claim | Evidence | Status | +| - | ----- | -------- | ------ | +| 1 | Each available candidate carries `IsRecommended` (tag equals the evaluation's recommended tag); the available update version derives from it | `UI/ApplicationViewService.cs:1127`, `Images/RuntimeContainerScanOrchestrator.cs:1307`, `UI/TagCandidateViewHelper.cs:122` | confirmed | +| 2 | The detail page has no rescan; `VulnerabilityRescanControl` rescans by `ImageVersionId`, logs `VulnerabilityRescan`, prefix `Vulnerability rescan failed`, invokes `OnRescanned` inside its `try` | `RuntimeContainerDetail.razor`; `VulnerabilityRescanControl.razor.cs:87-125` | confirmed | +| 3 | The control prints `Checked …` or `Never scanned` itself and has only an icon button | `VulnerabilityRescanControl.razor`, `.razor.cs:77` | confirmed | +| 4 | `RuntimeContainerDetailViewData` has no image version id; `ContainerSnapshot.ImageVersionId` exists | `UI/RuntimeContainerDetailViewData.cs`; `DockerUpdateGuard.Data/Entities/ContainerSnapshot.cs:23` | confirmed | +| 5 | The page has a `GetScanStatusColor` helper (issue) | its helpers are `GetUpdateStateColor`, `GetActionStatusColor`, `GetBaseRuntimeAlertColor` (`RuntimeContainerDetail.razor.cs:153-196`); scan chips use the shared `ScanStatusDisplayFormatter` (`.razor:485`), which other pages keep | refuted | +| 6 | The shared tone map has no `Requested`; the action history shows it orange today | `UI/StatusToneFormatter.cs:22-44`; `RuntimeContainerDetailTests.cs:743` | confirmed | +| 7 | The list's `BuildSparklinePath` draws one value at mid-height over the full width and equal values at the bottom (range 1); it scales each series alone; history arrives newest first | `RuntimeContainers.razor.cs:204-270`; `ApplicationViewService.cs:1053` | confirmed | +| 8 | `PageHeader.Description` is plain text only | `Components/Common/PageHeader.razor(.cs)` | confirmed | +| 9 | The history window is a fixed 24 h, at most 48 samples | `ApplicationViewService.cs:55,1054` | confirmed | +| 10 | `.dug-chart` (280 px) stays in use on Docker Instances | `DockerInstances.razor:82-109`, `app.css:525` | confirmed | +| 11 | `docs/areas/web-ui.md` holds 4977 words; released record 0060 (v1.3.11) links its anchor `#container-actions-section` | word count; `git tag --contains 856667a` | confirmed | +| 12 | The tables already switch to cards below 960 px; the page content is 912 px wide at a 960 px window | `app.css:1172`, page padding `app.css:323` | confirmed | +| 13 | Blazor Server protects persisted component state, so the restored `ImageVersionId` is not client-editable | to verify: Security, step 3 plan review, against ASP.NET Core's persistent component state (the list page persists `ImageVersionId` the same way) | unverified | + +## Tests per criterion + +| AC | Test(s) | Test file | +| -- | ------- | --------- | +| AC1 | `RuntimeContainerDetailHeaderShowsBreadcrumbChipsAndInstanceLink`; `RuntimeContainerDetailHeaderWithoutVersionShowsStateOnly` (DataRow: `Not evaluated`/`Exited` neutral) | `RuntimeContainerDetailRenderTests.cs` | +| AC1 | `PageHeaderDescriptionContentRendersFragment`; `PageHeaderAllPartsRendersDescriptionActionsBreadcrumbAndTitleContent` (kept: plain text) | `PageHeaderTests.cs` | +| AC2 | `RuntimeContainerDetailWithoutDetailShowsGenericHeader` (DataRow: not found, load failure) | `RuntimeContainerDetailTests.cs` | +| AC3 | `RuntimeContainerDetailDetailsPanelListsEntriesInOrder`; `RuntimeContainerDetailDetailsPanelHidesConditionalEntries`; `RuntimeContainerDetailBaseRuntimeEntryChipTone` (DataRow linked/unlinked) | `RuntimeContainerDetailRenderTests.cs` | +| AC3 | `VulnerabilityAssessmentCardEmbeddedRendersWithoutFrameAndLabel` | `VulnerabilityAssessmentCardTests.cs` | +| AC4 | `RuntimeContainerDetailRescanRefreshesImageVersionAndReloadsAsync`; `RuntimeContainerDetailFailedRescanShowsFixedReasonAndLogsAsync`; `RuntimeContainerDetailRescanErrorIsNotShownAfterRouteChangeAsync` | `RuntimeContainerDetailTests.cs` | +| AC4 | `VulnerabilityRescanControlWithButtonTextRendersLabelledTextButton`; `VulnerabilityRescanControlWithoutCheckedAtTextShowsNoCheckedLine` | `VulnerabilityRescanControlTests.cs` | +| AC5 | `RuntimeContainerDetailUsageCellsShowValuesAndCharts`; `RuntimeContainerDetailUsageWithoutSamplesShowsNoChartAndEmptyText` | `RuntimeContainerDetailRenderTests.cs` | +| AC5 | `ResourceHistoryChartShowsRangeLine` (DataRow per kind); `ResourceHistoryChartDrawsSamplesOldestFirst` | `ResourceHistoryChartTests.cs` | +| AC6 | `ResourceHistoryChartLineKindRendersLabelledImageWithLineAndArea`; `ResourceHistoryChartNetworkDrawsTwoLinesOnOneScale`; `ResourceHistoryChartWithoutSamplesRendersNothing` | `ResourceHistoryChartTests.cs` | +| AC6 | `SparklinePathBuilderSingleValueDrawsMidHeightLine`; `SparklinePathBuilderEqualValuesDrawMidHeightLine`; `SparklinePathBuilderUsesFrameScale`; `SparklinePathBuilderAreaPathClosesToBottom`; `SparklinePathBuilderEmptyValuesReturnEmptyPath`; `SparklinePathBuilderMultipleValuesUseCubicSegments` | `SparklinePathBuilderTests.cs` | +| AC6 | `AppStylesheetHistoryChartIs72PixelsHighInChartTokens` | `AppStylesheetRuntimeContainerDetailTests.cs` | +| AC7 | `RuntimeContainerDetailCandidatesWithoutPreferenceShowNoneLine`; `RuntimeContainerDetailCandidatesWithPreferenceShowSelectedChipAndClearButton`; `RuntimeContainerDetailCandidatesMarkRecommendedCandidate`; the existing save/clear tests (adapted) | `RuntimeContainerDetailRenderTests.cs`, `RuntimeContainerDetailTests.cs` | +| AC8 | `RuntimeContainerDetailMainColumnShowsPanelsInOrder` (DataRow with/without actions); `RuntimeContainerDetailVulnerabilityFindingsMetaText` (DataRow checked/never) | `RuntimeContainerDetailRenderTests.cs` | +| AC8 | `RuntimeContainerDetailScanHistoryShowsStatusIndicatorAsync` (replaces `…ScanHistoryChipShowsStatusColorAsync`) | `RuntimeContainerDetailTests.cs` | +| AC9 | `RuntimeContainerDetailDetailsPanelPrecedesMainColumn` | `RuntimeContainerDetailRenderTests.cs` | +| AC9 | `AppStylesheetDetailLayoutPlacesDetailsRightFrom960Pixels` | `AppStylesheetRuntimeContainerDetailTests.cs` | +| AC10 | manual: the Product Manager opens a container detail at 390, 768 and 1280 px and during a slow load, on a local run of the branch head (*Running the application* in `README.md`), step 7 Manual test; plus `DetailPageSkeletonRendersHeaderAndTwoColumns` (`DetailPageSkeletonTests.cs`) and `AppStylesheetUsageCellsStackBelow960Pixels` (`AppStylesheetRuntimeContainerDetailTests.cs`) | — | +| AC11 | `StatusToneFormatterGetStatusToneKnownValueReturnsTone` (DataRow `Requested` → Warning added) | `StatusToneFormatterTests.cs` | +| AC11 | `RuntimeContainerDetailActionHistoryShowsStatusChipInItsToneAsync` (replaces `…InItsColorAsync`, same five DataRows as tone classes) | `RuntimeContainerDetailTests.cs` | +| AC11 | `RuntimeContainerDetailRestoredStateCarriesImageVersionId` | `RuntimeContainerDetailPersistentStateTests.cs` | +| AC11 | `ApplicationViewServiceRuntimeContainerDetailCarriesImageVersionIdAsync` | `ApplicationViewServiceTests.cs` | +| AC12 | check: the Reviewer compares `docs/areas/detail-pages.md`, `web-ui.md` and `vulnerabilities.md` with the built page in step 8 | — | + +## Approach + +Early draft PR: no + +**Layout** (from the spec; the Tester decides nothing): `PageHeader` (breadcrumb, title, chips in `TitleContent`, description via the new `DescriptionContent`), the page error alert, then `div.dug-detail` holding `aside.dug-detail__aside` (the *Details* `SectionPanel`, first in markup) and `div.dug-detail__main` (panels in S7 order). CSS: one column below 960 px; from 960 px a grid `minmax(560px, 1fr) 320px` with a 24 px gap, aside in column 2, both in row 1, aside top-aligned. Details is a `
`: each entry a `div.dug-detail-list__entry` with `dt` (13 px, muted), `dd` value (semibold) and muted lines, separated by `--dug-border-inner`. Text of the update chip and the *Update assessment* value comes from one private static `FormatUpdateState(status, version)` of the page (`{status} · {version}` or `{status}`). + +**Shared pieces** +- `SparklinePathBuilder` (`UI/`) takes over the list's path code (cubic smoothing, invariant coordinates): one value → full-width line at mid-height; `Minimum == Maximum` → every point at mid-height; scale from a `SparklineFrame` (width, height, padding, minimum, maximum; `SparklineFrame.ForValues` scales to the given values). `BuildAreaPath` closes the line to the bottom edge. The list calls it with `ForValues(100, 26, 2, series)` per series; its private `BuildSparklinePath` and `FormatSvgCoordinate` go. +- `ResourceHistoryChart` (`Components/Common`): parameters `History` and `Kind`; orders the samples oldest first; renders nothing for no samples or `Kind` `NotSet`; else `div.dug-history-chart` with an `svg` (`role="img"`, `aria-label` `{CPU|Memory|Network} history, last 24 hours`, `viewBox="0 0 100 72"`, `preserveAspectRatio="none"`, every path `vector-effect="non-scaling-stroke"`): CPU/memory an area path (`--fill` token) plus a line path; network two line paths (rx, tx) on one frame over both series. Below it `span.dug-history-chart__range`: `Min {FormatCpuPercent} · max {…}`, `Min {FormatBytes} · max {…}` (memory used), `Max {FormatBytesPerSecond(rx)} ↓ / {…(tx)} ↑`. +- `DetailPageSkeleton` (`Components/Common`): a header skeleton (breadcrumb, title, description lines) and the `dug-detail` grid with one aside panel and two main panels of `MudSkeleton`s; the page shows it instead of `TableSkeleton`. +- `PageHeader.DescriptionContent` wins over `Description` when set, in the same `p.dug-page-header__description`. +- `VulnerabilityRescanControl`: `ButtonText` set → an outlined default-color `MudButton` with that text and `aria-label="Rescan vulnerabilities"` instead of the icon button (no tooltip); `ShowCheckedAt` false → no checked text and no `Never scanned`. Defaults keep the list pages unchanged. +- `VulnerabilityAssessmentCard.Embedded` → the same content without the `summary-card` paper and its label. +- `StatusToneFormatter`: `["Requested"] = StatusTone.Warning`. +- `RuntimeContainerDetailViewData.ImageVersionId` from `latestSnapshot.ImageVersionId` in `CreateRuntimeContainerDetail`. + +**Page.** *Vulnerabilities* entry: card `Embedded` with `ShowCheckedAt` and, at its right, ``; the `@key` gives every route a fresh control, so an earlier route's error never shows (E7); `HandleRescannedAsync` awaits `LoadAsync` (a failing reload reaches the control's catch: the rescan's prefix, as for Select). Chips: `StatusChip` with `StatusToneFormatter.GetStatusTone` everywhere (runtime, update, action run, base image chain with its severity summary); base runtime tone inline (`LinkedObservedImageId.HasValue ? Warning : Info`); `Recommended` Success, `Selected` Info. Scan history: `ScanStatusIndicator`. *Container actions*: a `SectionPanel` with the description as `p.dug-panel__lead` (muted), everything else as today. Candidates: `HeaderContent` = `Clear selection` with a stored preference; lead line, then the fixable chip (today's condition, `StatusChip` Info), then the table; `Published` `TimestampFormatter.FormatOptional` or `—`. *Vulnerability findings* `SectionPanel Flush`. Empty states keep today's texts. Not found / failed load: `PageHeader Title="Runtime Container Detail"` with the breadcrumb link only. Usage cells: `div.dug-usage` grid `repeat(auto-fit, minmax(220px, 1fr))`, hairlines between cells, one column below 960 px; value 24 px semibold `--dug-font-display`. + +The Dev runs the *Image build check* (`.razor` and `app.css` change) before the review. + +## Options considered + +- Chart: MudBlazor's line chart with axes switched off, or a second SVG copy beside the list's — lost; see record 0083. +- Rescan: a new detail-only rescan component — lost: it would copy the control's error handling and logging; two additive parameters keep one implementation. +- Area document: extending `web-ui.md` (past 5000 words) or moving its *Container actions section* (released record 0060 links that anchor) — lost to a new area *Detail pages* that the other detail pages (9/9) join. +- Action-history status: exempting it from the shared tones — lost (spec, *Challenge*, Major 1). + +## Affected projects and types + +| Project | Type / file | Change | +| ------- | ----------- | ------ | +| DockerUpdateGuard | `Components/Pages/RuntimeContainerDetail.razor(.cs)` | rewritten as *Approach*; three color helpers deleted; `FormatUpdateState`, `HandleRescannedAsync` added | +| DockerUpdateGuard | `Components/Pages/RuntimeContainers.razor.cs` | sparkline paths through `SparklinePathBuilder` | +| DockerUpdateGuard | `Components/Common/ResourceHistoryChart.razor(.cs)`, `DetailPageSkeleton.razor(.cs)` | new | +| DockerUpdateGuard | `Components/Common/PageHeader`, `VulnerabilityRescanControl`, `VulnerabilityAssessmentCard` (`.razor` and `.razor.cs`) | additive parameters | +| DockerUpdateGuard | `UI/SparklinePathBuilder.cs`, `UI/SparklineFrame.cs`, `UI/ResourceHistoryChartKind.cs` | new | +| DockerUpdateGuard | `UI/StatusToneFormatter.cs`, `UI/RuntimeContainerDetailViewData.cs`, `UI/ApplicationViewService.cs` | `Requested`; `ImageVersionId` | +| DockerUpdateGuard | `wwwroot/app.css` | `dug-detail*`, `dug-detail-list*`, `dug-usage*`, `dug-history-chart*`, `dug-panel__lead` | + +## Signatures (for the Dev's skeleton) + +- `public Guid ImageVersionId { get; set; }` on `RuntimeContainerDetailViewData` +- `[Parameter] public RenderFragment? DescriptionContent { get; set; }` on `PageHeader` +- `[Parameter] public string? ButtonText { get; set; }` and `[Parameter] public bool ShowCheckedAt { get; set; } = true;` on `VulnerabilityRescanControl` +- `[Parameter] public bool Embedded { get; set; }` on `VulnerabilityAssessmentCard` +- `public enum ResourceHistoryChartKind { NotSet = 0, Cpu, Memory, Network }` in `DockerUpdateGuard.UI`, each value documented +- `public partial class ResourceHistoryChart` in `DockerUpdateGuard.Components.Common` with `[Parameter, EditorRequired] public IReadOnlyList History { get; set; } = [];` and `[Parameter] public ResourceHistoryChartKind Kind { get; set; }` +- `public partial class DetailPageSkeleton` in `DockerUpdateGuard.Components.Common`, no parameters +- `internal sealed class SparklineFrame` in `DockerUpdateGuard.UI` with `public double Width { get; init; }`, `public double Height { get; init; }`, `public double Padding { get; init; }`, `public double Minimum { get; init; }`, `public double Maximum { get; init; }` and `internal static SparklineFrame ForValues(double width, double height, double padding, IEnumerable values)` +- `internal static class SparklinePathBuilder` in `DockerUpdateGuard.UI` with `internal static string BuildLinePath(IReadOnlyList values, SparklineFrame frame)` and `internal static string BuildAreaPath(IReadOnlyList values, SparklineFrame frame)` + +Deleted: RuntimeContainers.BuildSparklinePath and RuntimeContainers.FormatSvgCoordinate; RuntimeContainerDetail.GetUpdateStateColor, GetActionStatusColor and GetBaseRuntimeAlertColor are removed. + +The page's two private helpers are described in *Approach*. All names were checked against *Writing code*: no nested type, +no forbidden enum suffix, at most four parameters, no keyword names. + +## Test files + +`RuntimeContainerDetailRenderTests.cs`, `RuntimeContainerDetailTests.cs`, `RuntimeContainerDetailPersistentStateTests.cs`, `ResourceHistoryChartTests.cs` (new), `SparklinePathBuilderTests.cs` (new), `DetailPageSkeletonTests.cs` (new), `AppStylesheetRuntimeContainerDetailTests.cs` (new), `PageHeaderTests.cs`, `VulnerabilityRescanControlTests.cs`, `VulnerabilityAssessmentCardTests.cs`, `StatusToneFormatterTests.cs`, `ApplicationViewServiceTests.cs` — all in `src/Tests/DockerUpdateGuard.Tests/`. + +Existing test code to adapt (Tester): `RuntimeContainerDetailRenderTests.RuntimeContainerDetailWithHistoryRendersResponsiveChartsAndUsageCards` (asserts `dug-chart`, `summary-value`) and `…WithSelectionAndScanHistoryRendersUtcTimestampsAsync` (preference line); in `RuntimeContainerDetailTests` `FindActionSection` (`.section-paper` + `h5` → `.dug-panel` + `h2`), the action and scan history chip tests (above), and every selector on `.section-paper`/`.summary-card`; the three reflection tests of `RuntimeContainersTests` and its `_buildSparklinePathMethod` move to `SparklinePathBuilderTests`. `ScanStatusChipAssert` and `DetailPageAssert` stay as they are (other pages use them). A list test with equal sparkline values, if any, now expects mid-height. + +Files no unit test can cover: none. + +## Areas + +- New area **Detail pages** — `docs/areas/detail-pages.md (+450 words)`: scope "Layout and contents of the detail pages: header, details column, panels in order, resource history charts"; not here: routes, actions table, shared display, errors (Web UI), how values are computed (feature areas). Index row in `docs/areas/README.md`. +- `docs/areas/web-ui.md (-30 words)`; `docs/areas/vulnerabilities.md (+5 words)`. + +## Documentation updates + +All by the Dev, once green: +- `docs/areas/detail-pages.md` (new, from `_template.md`): the Runtime Container detail as built — header, two columns and their order, the *Details* entries and conditions, the main panels in order with their meta texts, the usage cells, the chart (no axes, 72 px, tokens, mid-height flat line, range line), skeleton; related decision 0083. Index row in `docs/areas/README.md`. +- `docs/areas/web-ui.md`: *Pages and routes* row of the detail → one sentence linking Detail pages; *Actions* `Rescan (per image)` *Where* adds "Runtime Container detail (text button `Rescan`, without its own last-check line)"; *General* scan status chip list drops "runtime container"; *Shared display* orange list adds `Requested`; *Container actions section* "directly after the container summary" → "as the first panel of the main column ([Detail pages](detail-pages.md))", heading → panel title with the description as a muted line; *Related decisions* adds 0083; *Not here* adds Detail pages. +- `docs/areas/vulnerabilities.md:47`: the manual rescan also from the runtime container detail page. +- `docs/ARCHITECTURE.md` §9 *Components\Common*: add the resource history chart and the detail page skeleton, linking record 0083. + +## Architecture check + +No guarantee of `.squad/project.md` or `docs/ARCHITECTURE.md` changes: the page still reads only `IApplicationViewService`, container actions keep their service, confirmation and interactive-only availability check, and the rescan uses the existing scoped enrichment call. + +## Security considerations + +- [x] No limits: no parsed input changes. +- [x] Exceptions reaching the user: a rescan or its reload failure → `Vulnerability rescan failed: {fixed reason}` (`FailureReason.FromException`); select/clear/actions unchanged. Never the exception text. +- The rescan acts on the server-loaded `ImageVersionId` of the shown container, as the list page does (fact 13). + +## Decision records + +- `docs/decisions/0083-resource-histories-are-drawn-as-svg-sparklines-from-one-shared-path-builder.md` (Proposed) + +## Out of scope / follow-ups + +- Moving the Docker Instances charts to `ResourceHistoryChart` and dropping `ResourceUsageChartBuilder` and `.dug-chart` (8/9); the other detail pages into *Detail pages* (9/9). diff --git a/specs/feature-456-runtime-container-detail/spec.md b/specs/feature-456-runtime-container-detail/spec.md index b16c4632..305382e5 100644 --- a/specs/feature-456-runtime-container-detail/spec.md +++ b/specs/feature-456-runtime-container-detail/spec.md @@ -1,7 +1,7 @@ # Spec: Runtime Container detail with a details column -Source: Issue #456 (part of #450; builds on #451 tokens and #452 shared components) -Status: Draft +Source: Issue #456 (part of #450) +Status: Approved by Lead ## Problem @@ -11,12 +11,10 @@ cards of equal weight and pushes candidates and findings below three 280 px char computed stays as today ([Web UI](../../docs/areas/web-ui.md)). Facts checked against the code that differ from the issue: -- The page has **no vulnerability rescan** today; the per-image rescan exists on Observed Images, My Images and Runtime - Containers only. The *Rescan* in the *Details* column is new on this page (S5). +- The page has **no vulnerability rescan** today (only the lists have one); *Rescan* is new here (S5). - The *Container actions* section of #280 has landed; it keeps its texts and behavior and takes the panel style (S7). -- A route with an unknown identifier already shows a not-found note with a link back - ([decision 0059](../../docs/decisions/0059-a-detail-page-shows-a-missing-record-or-a-failed-load-inline.md)); #40 is - closed. That behavior stays. +- An unknown identifier already shows a not-found note + ([decision 0059](../../docs/decisions/0059-a-detail-page-shows-a-missing-record-or-a-failed-load-inline.md)); it stays. - Today's preference reference with save time, the `Saved` button label and the fixable-findings chip stay (S6). ## Scenarios @@ -65,7 +63,7 @@ issue: exist, the info chip `Updating may resolve up to {n} of {m} active findings`. The table has `Tag` (semibold, its resolved version below for an alias; a chip `Recommended` in the success tone on each candidate the update assessment recommends; a chip `Selected` in the info tone on the stored preference), `Digest` (short, monospace, muted, full - digest as tooltip; `No digest` without one), `Reason`, `Published` (date, muted; `—` when unknown) and `Action` (a + digest as tooltip; `No digest` without one), `Reason`, `Published` (muted, in today's timestamp format; `—` when unknown) and `Action` (a secondary button `Select`, `Saved` on the stored preference). *Select* and *Clear selection* store or remove the preference as today: all these buttons are disabled while one saves, the page reloads afterwards, and a failure shows `Saving the tag selection failed: {reason}` or `Clearing the tag selection failed: {reason}` on the page. The @@ -112,7 +110,9 @@ issue: error prefixes and logged actions stay; the rescan adds no new prefix or logged action. - N3: The chart is a shared component that another page can reuse (Docker Instances in 8/9); its stroke stays 1.5 px wide whatever the chart's width, and it takes its colors from the chart tokens `--dug-chart-cpu`/`-fill`, - `--dug-chart-memory`/`-fill`, `--dug-chart-net-rx`, `--dug-chart-net-tx` in both themes. + `--dug-chart-memory`/`-fill`, `--dug-chart-net-rx`, `--dug-chart-net-tx` in both themes. The Runtime Containers + list draws its sparklines with the same path logic: its per-series scales stay, and equal values are drawn at + mid-height there too. - N4: The page has no color helpers of its own for statuses any more, the action-run status included: every status chip and indicator on it takes its tone from the shared mapping (Web UI, *Shared display*), which gains `Requested` in the warning tone. @@ -198,7 +198,7 @@ issue: persistent-state key and behavior and states that the persisted detail gains the image version id; AC11 asks that a restored detail carries it. - Minor 3 (one sample and equal values are drawn at different heights by the list's builder). Accepted: E3 and AC6 - name mid-height for both. Network keeps one scale (S4); the list page's sparklines and their separate scales stay as - they are. Whether the shared chart takes over the list's path logic is the plan's choice under the duplication rule. + name mid-height for both. Network keeps one scale (S4). The plan shares the list's path logic with the chart, so the list + keeps its separate scales and draws equal values at mid-height too (N3; Lead, step 2b). - Minor 4 (`PageHeader` takes the description as plain text only). Accepted: N5 adds a linked description to the shared header as an additive change; pages passing plain text render as before (AC1). diff --git a/specs/feature-456-runtime-container-detail/tasks.md b/specs/feature-456-runtime-container-detail/tasks.md new file mode 100644 index 00000000..2b3b3d98 --- /dev/null +++ b/specs/feature-456-runtime-container-detail/tasks.md @@ -0,0 +1,14 @@ +# Tasks: Runtime Container detail with a details column + +Plan: [plan.md](plan.md) + +| # | Group | Task | Files | Criteria | Depends on | Owner | Done | +| - | ----- | ---- | ----- | -------- | ---------- | ----- | ---- | +| 1 | G1 | Skeleton: `SparklineFrame` (`Width`, `Height`, `Padding`, `Minimum`, `Maximum`, `ForValues`), `SparklinePathBuilder` (`BuildLinePath`, `BuildAreaPath`), `ResourceHistoryChartKind` (`NotSet`, `Cpu`, `Memory`, `Network`), `ResourceHistoryChart` (`History`, `Kind`), `DetailPageSkeleton`, `PageHeader.DescriptionContent`, `VulnerabilityRescanControl.ButtonText` and `ShowCheckedAt`, `VulnerabilityAssessmentCard.Embedded`, `RuntimeContainerDetailViewData.ImageVersionId` (types `Guid`, `double`; `[Parameter]` properties; `partial` components, `sealed` frame) | `src/DockerUpdateGuard/UI/Sparkline*.cs`, `src/DockerUpdateGuard/UI/ResourceHistoryChartKind.cs`, `src/DockerUpdateGuard/UI/RuntimeContainerDetailViewData.cs`, `src/DockerUpdateGuard/Components/Common/*` | AC1, AC3, AC4, AC6, AC11 | — | Dev | [ ] | +| 2 | G1 | Tests first for the shared pieces (plan's rows in `SparklinePathBuilderTests`, `ResourceHistoryChartTests`, `DetailPageSkeletonTests`, `PageHeaderTests`, `VulnerabilityRescanControlTests`, `VulnerabilityAssessmentCardTests`, `StatusToneFormatterTests`, `ApplicationViewServiceTests`); move the reflection tests of `RuntimeContainersTests` | `src/Tests/DockerUpdateGuard.Tests/*` | AC1, AC3, AC4, AC5, AC6, AC10, AC11 | 1 | Tester | [ ] | +| 3 | G1 | Implement the shared pieces, `Requested` tone, `ImageVersionId` mapping, the list's sparklines through the builder, chart CSS | `src/DockerUpdateGuard/UI/*`, `src/DockerUpdateGuard/Components/Common/*`, `src/DockerUpdateGuard/Components/Pages/RuntimeContainers.razor.cs`, `src/DockerUpdateGuard/wwwroot/app.css` | AC1, AC3, AC4, AC5, AC6, AC10, AC11 | 2 | Dev | [ ] | +| 4 | G2 | Skeleton: no new API (page members are private) | — | — | 3 | Dev | [ ] | +| 5 | G2 | Tests first for the page and its stylesheet; adapt the existing page tests | `src/Tests/DockerUpdateGuard.Tests/RuntimeContainerDetail*.cs`, `src/Tests/DockerUpdateGuard.Tests/AppStylesheetRuntimeContainerDetailTests.cs` | AC1, AC2, AC3, AC4, AC5, AC7, AC8, AC9, AC10, AC11 | 4 | Tester | [ ] | +| 6 | G2 | Rewrite the page and add its layout CSS; delete the three color helpers; run the *Image build check* | `src/DockerUpdateGuard/Components/Pages/RuntimeContainerDetail.razor(.cs)`, `src/DockerUpdateGuard/wwwroot/app.css` | AC1, AC2, AC3, AC4, AC5, AC7, AC8, AC9, AC10, AC11 | 5 | Dev | [ ] | +| 7 | G2 | Documentation: `docs/areas/detail-pages.md` (new) and its index row, `docs/areas/web-ui.md`, `docs/areas/vulnerabilities.md`, `docs/ARCHITECTURE.md` as *Documentation updates* says | `docs/areas/*.md`, `docs/ARCHITECTURE.md` | AC12 | 6 | Dev | [ ] | +| 8 | PM | Manual check at 390, 768, 1280 px and during a slow load on a local run of the branch head | — | AC10 | 6 | Product Manager | [ ] | From a4393b320089ca1d6728de3be995267a6e326450 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 20:57:26 +0000 Subject: [PATCH 06/26] Record the plan security review of feature 456 Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_018g33AVnD3UUpZykmcVAdbH --- specs/feature-456-runtime-container-detail/log.md | 1 + 1 file changed, 1 insertion(+) diff --git a/specs/feature-456-runtime-container-detail/log.md b/specs/feature-456-runtime-container-detail/log.md index fe1f1b8f..3e29d552 100644 --- a/specs/feature-456-runtime-container-detail/log.md +++ b/specs/feature-456-runtime-container-detail/log.md @@ -10,3 +10,4 @@ are quoted in full. | 2026-11-30 20:46 | 2a Spec challenge | Devil's Advocate | VERDICT: OBJECTIONS 1 major, 4 minor. Major: N4/AC11 contradict S7 (GetActionStatusColor of the action history, Requested has no shared tone). Minor: (1) existing VulnerabilityRescanControl is an icon button with its own Checked/Never scanned line, not matching S3/S5/E5; (2) view data lacks ImageVersionId, persisted JSON changes (N2 wording, persistent-state test); (3) reuse the list page's sparkline path logic, pin E3's flat line position; (4) PageHeader.Description is a plain string, link needs an additive description fragment (opus/medium · 76,699 tokens · 16 tool uses · 95 s · 30 in · 9,459 out · 793,214 cache read · 69,043 cache write · 346,579 weighted) | | 2026-11-30 20:47 | 2a Spec revise (challenge) | Lead | RESULT: DONE. All 5 objections accepted and answered in the spec's Challenge section: Requested tone added to the shared mapping and action history moved to StatusChip (S7, N4, AC11); text Rescan button with one Checked line (S5, AC4, E6); persisted detail gains the image version id (N2, AC11); flat line at mid-height (E3, AC6); additive PageHeader description fragment (N5, AC1) (opus/medium · 51,914 tokens · 17 tool uses · 73 s · 28 in · 7,705 out · 1,516,290 cache read · 17,503 cache write · 272,492 weighted · continued) | | 2026-11-30 20:55 | 2b Plan | Lead | RESULT: DONE. Spec approved by Lead; plan.md and tasks.md written, tier standard, security area Container actions touched; decision record 0083 (Proposed); shared chart via SparklinePathBuilder; new area document detail-pages.md (opus/medium · 107,760 tokens · 46 tool uses · 455 s · 88 in · 47,087 out · 7,735,359 cache read · 106,569 cache write · 1,511,004 weighted · continued) | +| 2026-11-30 20:57 | 3 Plan security | Security | VERDICT: APPROVED. Fact 13 confirmed: persisted state is data-protected under Interactive Server only; tier standard correct; no unlisted area; no findings (opus/medium · 73,081 tokens · 19 tool uses · 119 s · 34 in · 11,255 out · 862,385 cache read · 70,560 cache write · 375,256 weighted) | From 764a74a52b471b8c5b48929769769c2d8d5f06b5 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 20:57:36 +0000 Subject: [PATCH 07/26] Add the plan challenge notes of feature 456 Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_018g33AVnD3UUpZykmcVAdbH --- .../log.md | 2 ++ .../plan.md | 27 +++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/specs/feature-456-runtime-container-detail/log.md b/specs/feature-456-runtime-container-detail/log.md index 3e29d552..06101272 100644 --- a/specs/feature-456-runtime-container-detail/log.md +++ b/specs/feature-456-runtime-container-detail/log.md @@ -11,3 +11,5 @@ are quoted in full. | 2026-11-30 20:47 | 2a Spec revise (challenge) | Lead | RESULT: DONE. All 5 objections accepted and answered in the spec's Challenge section: Requested tone added to the shared mapping and action history moved to StatusChip (S7, N4, AC11); text Rescan button with one Checked line (S5, AC4, E6); persisted detail gains the image version id (N2, AC11); flat line at mid-height (E3, AC6); additive PageHeader description fragment (N5, AC1) (opus/medium · 51,914 tokens · 17 tool uses · 73 s · 28 in · 7,705 out · 1,516,290 cache read · 17,503 cache write · 272,492 weighted · continued) | | 2026-11-30 20:55 | 2b Plan | Lead | RESULT: DONE. Spec approved by Lead; plan.md and tasks.md written, tier standard, security area Container actions touched; decision record 0083 (Proposed); shared chart via SparklinePathBuilder; new area document detail-pages.md (opus/medium · 107,760 tokens · 46 tool uses · 455 s · 88 in · 47,087 out · 7,735,359 cache read · 106,569 cache write · 1,511,004 weighted · continued) | | 2026-11-30 20:57 | 3 Plan security | Security | VERDICT: APPROVED. Fact 13 confirmed: persisted state is data-protected under Interactive Server only; tier standard correct; no unlisted area; no findings (opus/medium · 73,081 tokens · 19 tool uses · 119 s · 34 in · 11,255 out · 862,385 cache read · 70,560 cache write · 375,256 weighted) | +| 2026-11-30 20:57 | 2b Plan challenge | Devil's Advocate | VERDICT: OBJECTIONS 0 major, 5 minor. (1) Findings detected chip fixed Warning tone, not GetStatusTone; (2) SparklinePathBuilder: mid-height only when frame range is zero, single network sample uses frame scale; (3) embedded assessment card into the rescan control's LeadingContent, ShowCheckedAt hides CheckedText in both branches; (4) min-width: 0 on main and aside grid items, asserted in the stylesheet test; (5) Published null maps explicitly to the em dash, AC7 test asserts it (opus/medium · 84,369 tokens · 21 tool uses · 127 s · 42 in · 12,626 out · 1,236,075 cache read · 81,832 cache write · 454,532 weighted) | +| 2026-11-30 20:57 | 2b Challenge notes | Orchestrator | minor objections appended verbatim to plan.md | diff --git a/specs/feature-456-runtime-container-detail/plan.md b/specs/feature-456-runtime-container-detail/plan.md index 2a74f23f..d2afc0fb 100644 --- a/specs/feature-456-runtime-container-detail/plan.md +++ b/specs/feature-456-runtime-container-detail/plan.md @@ -148,3 +148,30 @@ No guarantee of `.squad/project.md` or `docs/ARCHITECTURE.md` changes: the page ## Out of scope / follow-ups - Moving the Docker Instances charts to `ResourceHistoryChart` and dropping `ResourceUsageChartBuilder` and `.dug-chart` (8/9); the other detail pages into *Detail pages* (9/9). + +## Challenge notes + +Plan challenge (mode `plan`) for specs/feature-456-runtime-container-detail: /home/user/DockerUpdateGuard/specs/feature-456-runtime-container-detail/plan.md + +The plan holds up. I checked its factual claims and they are correct: +- `RuntimeContainerDetail.razor.cs:153-196` has the helpers it lists, and `GetScanStatusColor` does not exist. +- `StatusToneFormatter.cs` has no `Requested` entry. +- The list's `BuildSparklinePath` (`RuntimeContainers.razor.cs:216-260`) uses 100/26/2, draws a single value as `M 0,13 L 100,13`, and uses range 1 when all values are equal. +- `CreateRuntimeContainerDetail` (`ApplicationViewService.cs:1851`) has `latestSnapshot` in scope. +- `PageHeader.razor` renders `Description` as plain text only. +- `TagCandidateViewData.IsRecommended` exists. +- The drawer is `Temporary`, so the 912 px content at 960 px stands. + +Tier `standard` with Security's plan review is right under *Tiers*. There are no major objections, only five minor ones for the Dev and Tester. + +**Minor objections (for the plan's Challenge notes):** + +1. **Minor — the *Base image vulnerabilities* chip tone.** Give the Details entry's `Findings detected` chip a fixed `StatusTone.Warning`, as S3 and today's markup (`RuntimeContainerDetail.razor:114`, `Color.Warning`) say. Do not take it from `StatusToneFormatter.GetStatusTone`. Evidence: the Approach says "`StatusChip` with `StatusToneFormatter.GetStatusTone` everywhere". But for `Findings detected` without a severity summary, `GetStatusTone` returns `StatusTone.Low` (`StatusToneFormatter.cs` `GetHighestSeverityTone`, the `severitySummary is null` branch), and the view data has no summary for this entry (`RuntimeContainerDetailViewData.cs:118,123`). The AC3 render test should assert the warning tone class on this chip. Why minor: one chip gets the wrong tone, and the plan does not need to change. + +2. **Minor — single-sample network chart on a shared frame.** In `SparklinePathBuilder`, draw at mid-height when the frame's `Minimum == Maximum`. A single value on a frame with a non-zero range should use the frame's scale. Otherwise one network sample with rx ≠ tx draws both lines on top of each other at mid-height, which breaks "two lines on one scale" (S4, N3). The per-series callers are unaffected: `ForValues` over one value gives a zero range, so the list and CPU/memory still draw mid-height for one sample (E3), and today's single-value test (`RuntimeContainersTests.cs:42-49`, `M 0,13 L 100,13`) still holds. Add a test that a single value on a frame with a non-zero range is drawn at its scaled height. Why minor: it only affects the one-sample network case. + +3. **Minor — where the rescan error appears (E6).** Put the embedded `VulnerabilityAssessmentCard` into the control's existing `LeadingContent`, with `ShowCheckedAt="false"` on the control. Do not place the card beside a separate control. The control's split layout (`VulnerabilityRescanControl.razor`, the `LeadingContent is not null` branch) already renders the leading content, then the error, then the button in its own column on the right. That puts `Vulnerability rescan failed: …` "below the *Vulnerabilities* entry", as E6 asks. In the plain layout the plan uses, the error `` comes after the button's `div`, so it lands in the button's column at the right. `ShowCheckedAt` must hide `CheckedText` in both branches. Why minor: the layout changes, the API does not. + +4. **Minor — overflow inside the detail grid (N1/AC10).** Give `.dug-detail__main` and `.dug-detail__aside` `min-width: 0`, and assert it in `AppStylesheetDetailLayoutPlacesDetailsRightFrom960Pixels`. Grid items default to `min-width: auto`, so a wide table row or a long unbroken value can push a cell past its track and overflow the page. Above 960 px the tables are real tables (`Breakpoint.Md`, `RuntimeContainerDetail.razor:175,212,360,424,476`) inside a main column that can be as narrow as 560 px. I have not rendered this, so it states the intent rather than a measured overflow. Why minor: it is one CSS rule, and the manual AC10 check would also catch it. + +5. **Minor — `—` for an unknown publish date has no test.** `TimestampFormatter.FormatOptional` returns `string.Empty` for null (`TimestampFormatter.cs:47-52`), not `—`. The page must map null to `—` explicitly, and an AC7 render test should assert `—` in the `Published` cell for a candidate without `PublishedAtUtc`. Why minor: it is one missing assertion and one explicit branch. From 6d7f8b3e1b3dd7809a59aca6e7899df29bc24cd8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 20:59:54 +0000 Subject: [PATCH 08/26] Add the skeleton of the shared detail page pieces Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_018g33AVnD3UUpZykmcVAdbH --- .../log.md | 1 + .../Common/DetailPageSkeleton.razor | 0 .../Common/DetailPageSkeleton.razor.cs | 6 +++ .../Components/Common/PageHeader.razor.cs | 6 +++ .../Common/ResourceHistoryChart.razor | 0 .../Common/ResourceHistoryChart.razor.cs | 28 ++++++++++ .../VulnerabilityAssessmentCard.razor.cs | 6 +++ .../VulnerabilityRescanControl.razor.cs | 12 +++++ .../UI/ResourceHistoryChartKind.cs | 27 ++++++++++ .../UI/RuntimeContainerDetailViewData.cs | 5 ++ src/DockerUpdateGuard/UI/SparklineFrame.cs | 53 +++++++++++++++++++ .../UI/SparklinePathBuilder.cs | 33 ++++++++++++ 12 files changed, 177 insertions(+) create mode 100644 src/DockerUpdateGuard/Components/Common/DetailPageSkeleton.razor create mode 100644 src/DockerUpdateGuard/Components/Common/DetailPageSkeleton.razor.cs create mode 100644 src/DockerUpdateGuard/Components/Common/ResourceHistoryChart.razor create mode 100644 src/DockerUpdateGuard/Components/Common/ResourceHistoryChart.razor.cs create mode 100644 src/DockerUpdateGuard/UI/ResourceHistoryChartKind.cs create mode 100644 src/DockerUpdateGuard/UI/SparklineFrame.cs create mode 100644 src/DockerUpdateGuard/UI/SparklinePathBuilder.cs diff --git a/specs/feature-456-runtime-container-detail/log.md b/specs/feature-456-runtime-container-detail/log.md index 06101272..57132f3b 100644 --- a/specs/feature-456-runtime-container-detail/log.md +++ b/specs/feature-456-runtime-container-detail/log.md @@ -13,3 +13,4 @@ are quoted in full. | 2026-11-30 20:57 | 3 Plan security | Security | VERDICT: APPROVED. Fact 13 confirmed: persisted state is data-protected under Interactive Server only; tier standard correct; no unlisted area; no findings (opus/medium · 73,081 tokens · 19 tool uses · 119 s · 34 in · 11,255 out · 862,385 cache read · 70,560 cache write · 375,256 weighted) | | 2026-11-30 20:57 | 2b Plan challenge | Devil's Advocate | VERDICT: OBJECTIONS 0 major, 5 minor. (1) Findings detected chip fixed Warning tone, not GetStatusTone; (2) SparklinePathBuilder: mid-height only when frame range is zero, single network sample uses frame scale; (3) embedded assessment card into the rescan control's LeadingContent, ShowCheckedAt hides CheckedText in both branches; (4) min-width: 0 on main and aside grid items, asserted in the stylesheet test; (5) Published null maps explicitly to the em dash, AC7 test asserts it (opus/medium · 84,369 tokens · 21 tool uses · 127 s · 42 in · 12,626 out · 1,236,075 cache read · 81,832 cache write · 454,532 weighted) | | 2026-11-30 20:57 | 2b Challenge notes | Orchestrator | minor objections appended verbatim to plan.md | +| 2026-11-30 20:59 | 4 Skeleton (G1) | Dev | Skeleton done: 7 new files (SparklineFrame, SparklinePathBuilder, ResourceHistoryChartKind, ResourceHistoryChart, DetailPageSkeleton) and additive parameters on PageHeader, VulnerabilityRescanControl, VulnerabilityAssessmentCard, ImageVersionId on the view data; format 0 changes, build 0 warnings; no pragmas; deviation: the two new .razor files are empty (sonnet/medium · 104,309 tokens · 8 tool uses · 121 s · 14 in · 5,816 out · 561,198 cache read · 102,814 cache write · 213,731 weighted) | diff --git a/src/DockerUpdateGuard/Components/Common/DetailPageSkeleton.razor b/src/DockerUpdateGuard/Components/Common/DetailPageSkeleton.razor new file mode 100644 index 00000000..e69de29b diff --git a/src/DockerUpdateGuard/Components/Common/DetailPageSkeleton.razor.cs b/src/DockerUpdateGuard/Components/Common/DetailPageSkeleton.razor.cs new file mode 100644 index 00000000..fa4f2927 --- /dev/null +++ b/src/DockerUpdateGuard/Components/Common/DetailPageSkeleton.razor.cs @@ -0,0 +1,6 @@ +namespace DockerUpdateGuard.Components.Common; + +/// +/// Skeleton placeholder that mirrors a detail page while data is loading +/// +public partial class DetailPageSkeleton; \ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Common/PageHeader.razor.cs b/src/DockerUpdateGuard/Components/Common/PageHeader.razor.cs index bd46648f..4d98d1b8 100644 --- a/src/DockerUpdateGuard/Components/Common/PageHeader.razor.cs +++ b/src/DockerUpdateGuard/Components/Common/PageHeader.razor.cs @@ -22,6 +22,12 @@ public partial class PageHeader [Parameter] public string? Description { get; set; } + /// + /// Rich content shown below the title in place of the plain description + /// + [Parameter] + public RenderFragment? DescriptionContent { get; set; } + /// /// Actions shown beside the title /// diff --git a/src/DockerUpdateGuard/Components/Common/ResourceHistoryChart.razor b/src/DockerUpdateGuard/Components/Common/ResourceHistoryChart.razor new file mode 100644 index 00000000..e69de29b diff --git a/src/DockerUpdateGuard/Components/Common/ResourceHistoryChart.razor.cs b/src/DockerUpdateGuard/Components/Common/ResourceHistoryChart.razor.cs new file mode 100644 index 00000000..9268bd4b --- /dev/null +++ b/src/DockerUpdateGuard/Components/Common/ResourceHistoryChart.razor.cs @@ -0,0 +1,28 @@ +using DockerUpdateGuard.UI; + +using Microsoft.AspNetCore.Components; + +namespace DockerUpdateGuard.Components.Common; + +/// +/// Chart of the resource usage history of a container +/// +public partial class ResourceHistoryChart +{ + #region Properties + + /// + /// Resource usage history to chart + /// + [Parameter] + [EditorRequired] + public IReadOnlyList History { get; set; } = []; + + /// + /// Kind of resource history to chart + /// + [Parameter] + public ResourceHistoryChartKind Kind { get; set; } + + #endregion // Properties +} \ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Common/VulnerabilityAssessmentCard.razor.cs b/src/DockerUpdateGuard/Components/Common/VulnerabilityAssessmentCard.razor.cs index 3f98458b..c4ea32dd 100644 --- a/src/DockerUpdateGuard/Components/Common/VulnerabilityAssessmentCard.razor.cs +++ b/src/DockerUpdateGuard/Components/Common/VulnerabilityAssessmentCard.razor.cs @@ -56,6 +56,12 @@ public partial class VulnerabilityAssessmentCard [Parameter] public bool ShowCheckedAt { get; set; } + /// + /// Whether the card is rendered embedded in a surrounding panel, without its own frame + /// + [Parameter] + public bool Embedded { get; set; } + /// /// Leading line that states whether updating the image can remedy the known findings, /// or null when the assessment has no active findings diff --git a/src/DockerUpdateGuard/Components/Common/VulnerabilityRescanControl.razor.cs b/src/DockerUpdateGuard/Components/Common/VulnerabilityRescanControl.razor.cs index fad67556..c64d04d0 100644 --- a/src/DockerUpdateGuard/Components/Common/VulnerabilityRescanControl.razor.cs +++ b/src/DockerUpdateGuard/Components/Common/VulnerabilityRescanControl.razor.cs @@ -41,6 +41,18 @@ public partial class VulnerabilityRescanControl [Parameter] public DateTimeOffset? CheckedAtUtc { get; set; } + /// + /// Text of the rescan button, or null for the default text + /// + [Parameter] + public string? ButtonText { get; set; } + + /// + /// Whether the timestamp of the last check is rendered + /// + [Parameter] + public bool ShowCheckedAt { get; set; } = true; + /// /// Raised after a manual rescan completed /// diff --git a/src/DockerUpdateGuard/UI/ResourceHistoryChartKind.cs b/src/DockerUpdateGuard/UI/ResourceHistoryChartKind.cs new file mode 100644 index 00000000..78558f29 --- /dev/null +++ b/src/DockerUpdateGuard/UI/ResourceHistoryChartKind.cs @@ -0,0 +1,27 @@ +namespace DockerUpdateGuard.UI; + +/// +/// Kind of resource history a chart shows +/// +public enum ResourceHistoryChartKind +{ + /// + /// No kind set + /// + NotSet = 0, + + /// + /// CPU usage + /// + Cpu, + + /// + /// Memory usage + /// + Memory, + + /// + /// Network traffic + /// + Network +} \ No newline at end of file diff --git a/src/DockerUpdateGuard/UI/RuntimeContainerDetailViewData.cs b/src/DockerUpdateGuard/UI/RuntimeContainerDetailViewData.cs index ba933d59..d123c1f6 100644 --- a/src/DockerUpdateGuard/UI/RuntimeContainerDetailViewData.cs +++ b/src/DockerUpdateGuard/UI/RuntimeContainerDetailViewData.cs @@ -12,6 +12,11 @@ public class RuntimeContainerDetailViewData /// public Guid DockerInstanceId { get; set; } + /// + /// Image version identifier of the container's current image, or empty when none is recorded + /// + public Guid ImageVersionId { get; set; } + /// /// Container identifier /// diff --git a/src/DockerUpdateGuard/UI/SparklineFrame.cs b/src/DockerUpdateGuard/UI/SparklineFrame.cs new file mode 100644 index 00000000..6f787c09 --- /dev/null +++ b/src/DockerUpdateGuard/UI/SparklineFrame.cs @@ -0,0 +1,53 @@ +namespace DockerUpdateGuard.UI; + +/// +/// Drawing frame of a sparkline: the canvas size, its padding and the value range mapped onto it +/// +internal sealed class SparklineFrame +{ + #region Properties + + /// + /// Canvas width + /// + public double Width { get; init; } + + /// + /// Canvas height + /// + public double Height { get; init; } + + /// + /// Padding between the canvas edge and the drawn line + /// + public double Padding { get; init; } + + /// + /// Smallest value of the range + /// + public double Minimum { get; init; } + + /// + /// Largest value of the range + /// + public double Maximum { get; init; } + + #endregion // Properties + + #region Static methods + + /// + /// Create the frame of a canvas whose value range spans the given values + /// + /// Canvas width + /// Canvas height + /// Padding between the canvas edge and the drawn line + /// Values the range has to span + /// Frame + internal static SparklineFrame ForValues(double width, double height, double padding, IEnumerable values) + { + throw new InvalidOperationException("Skeleton: not implemented"); + } + + #endregion // Static methods +} \ No newline at end of file diff --git a/src/DockerUpdateGuard/UI/SparklinePathBuilder.cs b/src/DockerUpdateGuard/UI/SparklinePathBuilder.cs new file mode 100644 index 00000000..6b45a017 --- /dev/null +++ b/src/DockerUpdateGuard/UI/SparklinePathBuilder.cs @@ -0,0 +1,33 @@ +namespace DockerUpdateGuard.UI; + +/// +/// Builds the SVG path data of sparklines +/// +internal static class SparklinePathBuilder +{ + #region Static methods + + /// + /// Build the SVG path data of the line through the values + /// + /// Values to draw + /// Drawing frame + /// Path data + internal static string BuildLinePath(IReadOnlyList values, SparklineFrame frame) + { + throw new InvalidOperationException("Skeleton: not implemented"); + } + + /// + /// Build the SVG path data of the filled area under the line through the values + /// + /// Values to draw + /// Drawing frame + /// Path data + internal static string BuildAreaPath(IReadOnlyList values, SparklineFrame frame) + { + throw new InvalidOperationException("Skeleton: not implemented"); + } + + #endregion // Static methods +} \ No newline at end of file From 5ee74a41d377b192ee1576a11fcd3e3a894019f5 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 21:05:07 +0000 Subject: [PATCH 09/26] Add the tests first for the shared detail page pieces Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_018g33AVnD3UUpZykmcVAdbH --- .../log.md | 1 + .../ApplicationViewServiceTests.cs | 31 ++ .../DetailPageSkeletonTests.cs | 46 +++ .../PageHeaderTests.cs | 44 +++ .../ResourceHistoryChartTests.cs | 283 ++++++++++++++++++ .../RuntimeContainersTests.cs | 68 ----- .../SparklinePathBuilderTests.cs | 186 ++++++++++++ .../StatusToneFormatterTests.cs | 2 + .../VulnerabilityAssessmentCardTests.cs | 27 ++ .../VulnerabilityRescanControlTests.cs | 65 ++++ 10 files changed, 685 insertions(+), 68 deletions(-) create mode 100644 src/Tests/DockerUpdateGuard.Tests/DetailPageSkeletonTests.cs create mode 100644 src/Tests/DockerUpdateGuard.Tests/ResourceHistoryChartTests.cs create mode 100644 src/Tests/DockerUpdateGuard.Tests/SparklinePathBuilderTests.cs diff --git a/specs/feature-456-runtime-container-detail/log.md b/specs/feature-456-runtime-container-detail/log.md index 57132f3b..a77b1e1d 100644 --- a/specs/feature-456-runtime-container-detail/log.md +++ b/specs/feature-456-runtime-container-detail/log.md @@ -14,3 +14,4 @@ are quoted in full. | 2026-11-30 20:57 | 2b Plan challenge | Devil's Advocate | VERDICT: OBJECTIONS 0 major, 5 minor. (1) Findings detected chip fixed Warning tone, not GetStatusTone; (2) SparklinePathBuilder: mid-height only when frame range is zero, single network sample uses frame scale; (3) embedded assessment card into the rescan control's LeadingContent, ShowCheckedAt hides CheckedText in both branches; (4) min-width: 0 on main and aside grid items, asserted in the stylesheet test; (5) Published null maps explicitly to the em dash, AC7 test asserts it (opus/medium · 84,369 tokens · 21 tool uses · 127 s · 42 in · 12,626 out · 1,236,075 cache read · 81,832 cache write · 454,532 weighted) | | 2026-11-30 20:57 | 2b Challenge notes | Orchestrator | minor objections appended verbatim to plan.md | | 2026-11-30 20:59 | 4 Skeleton (G1) | Dev | Skeleton done: 7 new files (SparklineFrame, SparklinePathBuilder, ResourceHistoryChartKind, ResourceHistoryChart, DetailPageSkeleton) and additive parameters on PageHeader, VulnerabilityRescanControl, VulnerabilityAssessmentCard, ImageVersionId on the view data; format 0 changes, build 0 warnings; no pragmas; deviation: the two new .razor files are empty (sonnet/medium · 104,309 tokens · 8 tool uses · 121 s · 14 in · 5,816 out · 561,198 cache read · 102,814 cache write · 213,731 weighted) | +| 2026-11-30 21:05 | 5 Tests first (G1) | Tester | Tests written for the shared pieces (SparklinePathBuilder, ResourceHistoryChart, DetailPageSkeleton, PageHeader, VulnerabilityRescanControl, VulnerabilityAssessmentCard, StatusToneFormatter, ApplicationViewService); reflection tests moved to the builder; confirmed by the orchestrator: compile, 36 of 120 filtered tests fail for the expected reason. Deferred: ResourceHistoryChartWithoutSamplesRendersNothing (sonnet/medium · 166,103 tokens · 22 tool uses · 273 s · 44 in · 33,196 out · 2,755,647 cache read · 111,433 cache write · 580,880 weighted) | diff --git a/src/Tests/DockerUpdateGuard.Tests/ApplicationViewServiceTests.cs b/src/Tests/DockerUpdateGuard.Tests/ApplicationViewServiceTests.cs index 57d8a287..3011722f 100644 --- a/src/Tests/DockerUpdateGuard.Tests/ApplicationViewServiceTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/ApplicationViewServiceTests.cs @@ -973,6 +973,37 @@ public async Task ApplicationViewServiceRuntimeContainerDetailReturnsManualSelec } } + /// + /// Verify the runtime container detail carries the image version id of its latest snapshot + /// + /// Task + [TestMethod] + [TestCategory("AC11")] + public async Task ApplicationViewServiceRuntimeContainerDetailCarriesImageVersionIdAsync() + { + var options = new DbContextOptionsBuilder().UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options; + + var dbContext = new DockerUpdateGuardDbContext(options); + + await using (dbContext.ConfigureAwait(false)) + { + var dockerInstanceId = await SeedRuntimeContainerDetailDataAsync(dbContext).ConfigureAwait(false); + var snapshot = await dbContext.ContainerSnapshots.SingleAsync(entity => entity.ContainerId == "container-a", CancellationToken.None).ConfigureAwait(false); + var service = new ApplicationViewService(dbContext, + new ImageReferenceParser(), + CreateOptionsMonitor(), + new SharedBaseImageQueryService(dbContext)); + + var detail = await service.GetRuntimeContainerDetailAsync(dockerInstanceId, "container-a", CancellationToken.None) + .ConfigureAwait(false); + + Assert.IsNotNull(detail, "Runtime container detail must be returned for the latest snapshot"); + Assert.AreNotEqual(Guid.Empty, snapshot.ImageVersionId, "The seeded snapshot must have an image version"); + Assert.AreEqual(snapshot.ImageVersionId, detail.ImageVersionId, "The runtime detail must carry the image version id of its latest snapshot"); + } + } + /// /// Verify vulnerability finding reference URLs are sanitized so only absolute http(s) URLs reach the UI /// diff --git a/src/Tests/DockerUpdateGuard.Tests/DetailPageSkeletonTests.cs b/src/Tests/DockerUpdateGuard.Tests/DetailPageSkeletonTests.cs new file mode 100644 index 00000000..0299e27e --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/DetailPageSkeletonTests.cs @@ -0,0 +1,46 @@ +using Bunit; + +using DockerUpdateGuard.Components.Common; +using DockerUpdateGuard.Tests.Helper; + +namespace DockerUpdateGuard.Tests; + +/// +/// Tests for +/// +[TestClass] +public class DetailPageSkeletonTests +{ + #region Methods + + /// + /// Verify the skeleton has the shape of a detail page: a header and the two columns with their panels + /// + /// Task + [TestMethod] + [TestCategory("AC10")] + public async Task DetailPageSkeletonRendersHeaderAndTwoColumns() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var component = testContext.Render(); + var markup = component.Markup; + var gridIndex = markup.IndexOf("dug-detail", StringComparison.Ordinal); + + Assert.HasCount(1, component.FindAll(".dug-detail"), "The skeleton must render one detail grid"); + Assert.HasCount(1, component.FindAll(".dug-detail > .dug-detail__aside"), "The skeleton must render the aside column inside the grid"); + Assert.HasCount(1, component.FindAll(".dug-detail > .dug-detail__main"), "The skeleton must render the main column inside the grid"); + Assert.HasCount(1, component.FindAll(".dug-detail__aside .dug-panel"), "The aside column must hold one panel placeholder"); + Assert.HasCount(2, component.FindAll(".dug-detail__main .dug-panel"), "The main column must hold two panel placeholders"); + Assert.IsLessThan(markup.IndexOf("dug-detail__main", StringComparison.Ordinal), markup.IndexOf("dug-detail__aside", StringComparison.Ordinal), "The aside column must precede the main column in the markup"); + Assert.IsGreaterThan(0, gridIndex, "The header placeholder must precede the grid"); + Assert.IsGreaterThan(0, MarkupTestHelper.CountSkeletons(markup[..gridIndex]), "The header must hold skeleton placeholders"); + Assert.IsGreaterThan(0, MarkupTestHelper.CountSkeletons(component.Find(".dug-detail__aside").InnerHtml), "The aside column must hold skeleton placeholders"); + Assert.IsGreaterThan(0, MarkupTestHelper.CountSkeletons(component.Find(".dug-detail__main").InnerHtml), "The main column must hold skeleton placeholders"); + } + } + + #endregion // Methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/PageHeaderTests.cs b/src/Tests/DockerUpdateGuard.Tests/PageHeaderTests.cs index b152906b..795085a7 100644 --- a/src/Tests/DockerUpdateGuard.Tests/PageHeaderTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/PageHeaderTests.cs @@ -67,6 +67,50 @@ public async Task PageHeaderAllPartsRendersDescriptionActionsBreadcrumbAndTitleC } } + /// + /// Verify a description fragment renders inside the description paragraph and wins over the plain text + /// + /// Task + [TestMethod] + [TestCategory("AC1")] + public async Task PageHeaderDescriptionContentRendersFragment() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var component = testContext.Render(parameters => parameters.Add(header => header.Title, "Container") + .Add(header => header.Description, "Plain description") + .Add(header => header.DescriptionContent, CreateFragment("Production · observed today"))); + var description = component.FindAll("p.dug-page-header__description"); + + Assert.HasCount(1, description, "The header must render exactly one description paragraph"); + Assert.AreEqual("Production", description[0].QuerySelector("a#inst")?.TextContent, "The description fragment must render its link inside the description paragraph"); + Assert.AreEqual("/docker-instances/1", description[0].QuerySelector("a#inst")?.GetAttribute("href"), "The description link must keep its target"); + Assert.Contains("observed today", description[0].TextContent, "The description fragment must render its text"); + Assert.DoesNotContain("Plain description", component.Markup, "The description fragment must win over the plain description"); + } + } + + /// + /// Verify a description fragment alone renders the description paragraph without a plain description + /// + /// Task + [TestMethod] + [TestCategory("AC1")] + public async Task PageHeaderDescriptionContentWithoutPlainDescriptionRendersParagraph() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var component = testContext.Render(parameters => parameters.Add(header => header.Title, "Container") + .Add(header => header.DescriptionContent, CreateFragment("Rich line"))); + + Assert.AreEqual("Rich line", component.Find("p.dug-page-header__description #only").TextContent, "The fragment must render without a plain description"); + } + } + #endregion // Methods #region Static methods diff --git a/src/Tests/DockerUpdateGuard.Tests/ResourceHistoryChartTests.cs b/src/Tests/DockerUpdateGuard.Tests/ResourceHistoryChartTests.cs new file mode 100644 index 00000000..b585c72e --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/ResourceHistoryChartTests.cs @@ -0,0 +1,283 @@ +using System.Globalization; +using System.Text.RegularExpressions; + +using AngleSharp.Dom; + +using Bunit; + +using DockerUpdateGuard.Components.Common; +using DockerUpdateGuard.Tests.Helper; +using DockerUpdateGuard.UI; + +namespace DockerUpdateGuard.Tests; + +/// +/// Tests for +/// +[TestClass] +public class ResourceHistoryChartTests +{ + #region Methods + + /// + /// Verify a line chart renders a labelled image with an area fill and a line that keep their stroke width + /// + /// Chart kind + /// Expected accessible name + /// Task + [TestMethod] + [TestCategory("AC6")] + [DataRow(ResourceHistoryChartKind.Cpu, "CPU history, last 24 hours")] + [DataRow(ResourceHistoryChartKind.Memory, "Memory history, last 24 hours")] + public async Task ResourceHistoryChartLineKindRendersLabelledImageWithLineAndArea(ResourceHistoryChartKind kind, string expectedLabel) + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var component = Render(testContext, kind, [CreateSample(0, 10m, 1048576L, 1024m, 512m), CreateSample(1, 50m, 3145728L, 2048m, 256m), CreateSample(2, 30m, 2097152L, 512m, 128m)]); + var svg = component.Find(".dug-history-chart svg"); + var paths = component.FindAll(".dug-history-chart svg path"); + + Assert.AreEqual("img", svg.GetAttribute("role"), "The chart must be announced as an image"); + Assert.AreEqual(expectedLabel, svg.GetAttribute("aria-label"), "The chart must carry its accessible name"); + Assert.AreEqual("0 0 100 72", svg.GetAttribute("viewBox"), "The chart must use a 100 by 72 view box"); + Assert.AreEqual("none", svg.GetAttribute("preserveAspectRatio"), "The chart must stretch to its box"); + Assert.HasCount(2, paths, "A line chart must draw an area and a line"); + Assert.IsTrue(paths.All(path => path.GetAttribute("vector-effect") == "non-scaling-stroke"), "Every path must keep its stroke width"); + Assert.HasCount(1, paths.Where(path => ReadPath(path).EndsWith('Z')).ToList(), "Exactly one path must be the closed area"); + + var line = paths.Single(path => ReadPath(path).EndsWith('Z') == false); + var area = paths.Single(path => ReadPath(path).EndsWith('Z')); + + Assert.StartsWith(ReadPath(line), ReadPath(area), "The area must follow the line"); + } + } + + /// + /// Verify a network chart draws received and sent traffic as two lines on one scale + /// + /// Task + [TestMethod] + [TestCategory("AC6")] + public async Task ResourceHistoryChartNetworkDrawsTwoLinesOnOneScale() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var component = Render(testContext, ResourceHistoryChartKind.Network, [CreateSample(0, 1m, 1L, 0m, 0m), CreateSample(1, 1m, 1L, 100m, 50m)]); + var svg = component.Find(".dug-history-chart svg"); + var paths = component.FindAll(".dug-history-chart svg path"); + + Assert.AreEqual("Network history, last 24 hours", svg.GetAttribute("aria-label"), "The chart must carry its accessible name"); + Assert.AreEqual("img", svg.GetAttribute("role"), "The chart must be announced as an image"); + Assert.HasCount(2, paths, "A network chart must draw two lines"); + Assert.IsTrue(paths.All(path => path.GetAttribute("vector-effect") == "non-scaling-stroke"), "Every path must keep its stroke width"); + Assert.DoesNotContain(path => ReadPath(path).EndsWith('Z'), paths, "A network chart must draw no area"); + + var received = ReadCoordinates(ReadPath(paths[0])); + var sent = ReadCoordinates(ReadPath(paths[1])); + + Assert.AreEqual(received[0].Y, sent[0].Y, "Both lines must start at the bottom of the shared scale"); + Assert.IsLessThan(sent[^1].Y, received[^1].Y, "The received line (100) must end above the sent line (50)"); + Assert.IsTrue(sent[^1].Y > received[^1].Y && sent[^1].Y < sent[0].Y, "The sent line must end between the top and the bottom of the shared scale, not at the top"); + } + } + + /// + /// Verify a single network sample draws each line at its scaled height instead of both at mid-height + /// + /// Task + [TestMethod] + [TestCategory("AC6")] + public async Task ResourceHistoryChartNetworkSingleSampleDrawsLinesAtScaledHeights() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var component = Render(testContext, ResourceHistoryChartKind.Network, [CreateSample(0, 1m, 1L, 100m, 50m)]); + var paths = component.FindAll(".dug-history-chart svg path"); + + Assert.HasCount(2, paths, "A network chart must draw two lines"); + + var received = ReadCoordinates(ReadPath(paths[0])); + var sent = ReadCoordinates(ReadPath(paths[1])); + + Assert.IsLessThan(sent[0].Y, received[0].Y, "The larger received rate must be drawn above the smaller sent rate"); + Assert.AreEqual(0d, received[0].X, "A single sample must start at the left edge"); + Assert.AreEqual(100d, received[^1].X, "A single sample must reach the right edge"); + } + } + + /// + /// Verify one sample or equal samples draw a flat line at mid-height + /// + /// Chart kind + /// Number of equal samples + /// Task + [TestMethod] + [TestCategory("AC6")] + [DataRow(ResourceHistoryChartKind.Cpu, 1)] + [DataRow(ResourceHistoryChartKind.Cpu, 3)] + [DataRow(ResourceHistoryChartKind.Memory, 1)] + [DataRow(ResourceHistoryChartKind.Memory, 3)] + [DataRow(ResourceHistoryChartKind.Network, 1)] + [DataRow(ResourceHistoryChartKind.Network, 3)] + public async Task ResourceHistoryChartEqualValuesDrawFlatLineAtMidHeight(ResourceHistoryChartKind kind, int sampleCount) + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var samples = Enumerable.Range(0, sampleCount) + .Select(minute => CreateSample(minute, 5m, 1048576L, 1024m, 1024m)) + .ToList(); + + var component = Render(testContext, kind, samples); + var lines = component.FindAll(".dug-history-chart svg path").Where(path => ReadPath(path).EndsWith('Z') == false).ToList(); + + Assert.IsNotEmpty(lines, "The chart must draw at least one line"); + + foreach (var line in lines) + { + var ordinates = ReadCoordinates(ReadPath(line)).Select(coordinate => coordinate.Y).Distinct().ToList(); + + Assert.HasCount(1, ordinates, $"A {kind} line of equal values must be flat"); + Assert.AreEqual(36d, ordinates[0], $"A {kind} line of equal values must be drawn at mid-height of the 72 px chart"); + } + } + } + + /// + /// Verify the chart draws the samples oldest first whatever order they arrive in + /// + /// Task + [TestMethod] + [TestCategory("AC5")] + public async Task ResourceHistoryChartDrawsSamplesOldestFirst() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + // Chronological CPU values 10, 50, 30; delivered newest first with the middle sample last + var component = Render(testContext, ResourceHistoryChartKind.Cpu, [CreateSample(2, 30m, 1L, 0m, 0m), CreateSample(0, 10m, 1L, 0m, 0m), CreateSample(1, 50m, 1L, 0m, 0m)]); + var line = component.FindAll(".dug-history-chart svg path").Single(path => ReadPath(path).EndsWith('Z') == false); + var points = ReadCoordinates(ReadPath(line)); + + Assert.IsGreaterThan(points[^1].Y, points[0].Y, "The oldest sample (10) must be drawn at the left, below the newest sample (30) at the right"); + Assert.IsGreaterThan(points[0].X, points[^1].X, "The path must run from the left to the right"); + } + } + + /// + /// Verify the range line under the chart names the minimum and maximum of the period in the formats of the current values + /// + /// Chart kind + /// Expected range text + /// Task + [TestMethod] + [TestCategory("AC5")] + [DataRow(ResourceHistoryChartKind.Cpu, "Min 10.0 % · max 50.0 %")] + [DataRow(ResourceHistoryChartKind.Memory, "Min 1.0 MB · max 3.0 MB")] + [DataRow(ResourceHistoryChartKind.Network, "Max 2.0 KB/s ↓ / 512.0 B/s ↑")] + public async Task ResourceHistoryChartShowsRangeLine(ResourceHistoryChartKind kind, string expectedText) + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + // CPU 10, 50, 30 %; memory 1, 3, 2 MB; received 1024, 2048, 512 B/s; sent 512, 256, 128 B/s + var component = Render(testContext, kind, [CreateSample(0, 10m, 1048576L, 1024m, 512m), CreateSample(1, 50m, 3145728L, 2048m, 256m), CreateSample(2, 30m, 2097152L, 512m, 128m)]); + var ranges = component.FindAll(".dug-history-chart span.dug-history-chart__range"); + + Assert.HasCount(1, ranges, "The chart must render one range line"); + Assert.AreEqual(expectedText, ranges[0].TextContent.Trim(), "The range line must show the extremes of the period"); + } + } + + /// + /// Verify equal samples show the same value as minimum and maximum + /// + /// Task + [TestMethod] + [TestCategory("AC5")] + public async Task ResourceHistoryChartEqualValuesShowSameMinimumAndMaximum() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var component = Render(testContext, ResourceHistoryChartKind.Cpu, [CreateSample(0, 0m, 1L, 0m, 0m)]); + + Assert.AreEqual("Min 0.0 % · max 0.0 %", component.Find(".dug-history-chart__range").TextContent.Trim(), "One sample must show its value as minimum and maximum"); + } + } + + #endregion // Methods + + #region Static methods + + /// + /// Create a usage sample + /// + /// Minutes after the base time + /// CPU percentage + /// Memory usage in bytes + /// Received bytes per second + /// Sent bytes per second + /// Sample + private static ResourceUsagePointViewData CreateSample(int minutes, decimal cpuPercent, long memoryUsageBytes, decimal receivedBytesPerSecond, decimal sentBytesPerSecond) + { + return new ResourceUsagePointViewData + { + CpuPercent = cpuPercent, + MemoryUsageBytes = memoryUsageBytes, + MemoryLimitBytes = 1073741824L, + NetworkRxBytesPerSecond = receivedBytesPerSecond, + NetworkTxBytesPerSecond = sentBytesPerSecond, + RecordedAtUtc = new DateTimeOffset(2026, 11, 23, 21, 0, 0, TimeSpan.Zero).AddMinutes(minutes), + }; + } + + /// + /// Render the chart + /// + /// Test context + /// Chart kind + /// Samples + /// Rendered chart + private static IRenderedComponent Render(BunitContext testContext, ResourceHistoryChartKind kind, IReadOnlyList history) + { + return testContext.Render(parameters => parameters.Add(chart => chart.Kind, kind) + .Add(chart => chart.History, history)); + } + + /// + /// Read the path data of a path element + /// + /// Path element + /// Path data + private static string ReadPath(IElement path) + { + return (path.GetAttribute("d") ?? string.Empty).Trim(); + } + + /// + /// Read every coordinate pair of path data + /// + /// Path data + /// Coordinates + private static List<(double X, double Y)> ReadCoordinates(string path) + { + return [ + .. Regex.Matches(path, @"(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)") + .Select(match => (X: double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture), + Y: double.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture))) + ]; + } + + #endregion // Static methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/RuntimeContainersTests.cs b/src/Tests/DockerUpdateGuard.Tests/RuntimeContainersTests.cs index b58f8304..2fe4c72f 100644 --- a/src/Tests/DockerUpdateGuard.Tests/RuntimeContainersTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/RuntimeContainersTests.cs @@ -1,5 +1,3 @@ -using System.Reflection; - using Bunit; using DockerUpdateGuard.Components.Pages; @@ -22,62 +20,8 @@ namespace DockerUpdateGuard.Tests; [TestClass] public class RuntimeContainersTests { - #region Fields - - /// - /// Non-public sparkline-path builder method - /// - private static readonly MethodInfo _buildSparklinePathMethod = typeof(RuntimeContainers).GetMethod("BuildSparklinePath", - BindingFlags.NonPublic | BindingFlags.Static) - ?? throw new InvalidOperationException("The runtime containers page must expose the non-public BuildSparklinePath method for sparkline rendering"); - - #endregion // Fields - #region Methods - /// - /// Verify a single sparkline sample renders as a centered horizontal path - /// - [TestMethod] - public void RuntimeContainersBuildSparklinePathSingleValueReturnsCenteredHorizontalLine() - { - var path = InvokeBuildSparklinePath([42d]); - - Assert.AreEqual("M 0,13 L 100,13", - path, - "A single sparkline sample must render as a centered horizontal line"); - } - - /// - /// Verify multiple sparkline samples render as a smoothed cubic path - /// - [TestMethod] - public void RuntimeContainersBuildSparklinePathMultipleValuesReturnsSmoothCurve() - { - var path = InvokeBuildSparklinePath([10d, 20d, 15d, 30d]); - - Assert.IsFalse(string.IsNullOrWhiteSpace(path), "A sparkline with multiple samples must produce SVG path data"); - Assert.StartsWith("M ", - path, - "A sparkline path must start with an SVG move command"); - Assert.Contains(" C ", - path, - "A sparkline with multiple samples must use cubic Bezier segments for smoothing"); - } - - /// - /// Verify empty sparkline series render no path - /// - [TestMethod] - public void RuntimeContainersBuildSparklinePathEmptyValuesReturnsEmptyString() - { - var path = InvokeBuildSparklinePath([]); - - Assert.AreEqual(string.Empty, - path, - "An empty sparkline series must not render any SVG path data"); - } - /// /// Verify a failed update check shows a fixed reason instead of the exception message and logs the exception /// @@ -304,17 +248,5 @@ private static Task> CreateSingleCon return Task.FromResult(list); } - /// - /// Invoke the non-public sparkline-path builder - /// - /// Series values - /// SVG path data - private static string InvokeBuildSparklinePath(IEnumerable values) - { - var path = _buildSparklinePathMethod.Invoke(null, [values]); - - return path as string ?? throw new InvalidOperationException("The sparkline-path builder must return SVG path data as a string"); - } - #endregion // Methods } \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/SparklinePathBuilderTests.cs b/src/Tests/DockerUpdateGuard.Tests/SparklinePathBuilderTests.cs new file mode 100644 index 00000000..074d1d49 --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/SparklinePathBuilderTests.cs @@ -0,0 +1,186 @@ +using System.Globalization; +using System.Text.RegularExpressions; + +using DockerUpdateGuard.UI; + +namespace DockerUpdateGuard.Tests; + +/// +/// Tests for and +/// +[TestClass] +public class SparklinePathBuilderTests +{ + #region Methods + + /// + /// Verify the frame of a canvas spans the range of the given values + /// + [TestMethod] + [TestCategory("AC6")] + public void SparklinePathBuilderForValuesSpansRangeOfValues() + { + var frame = SparklineFrame.ForValues(100, 26, 2, [20d, 5d, 42d, 11d]); + + Assert.AreEqual(100d, frame.Width, "The frame must keep the canvas width"); + Assert.AreEqual(26d, frame.Height, "The frame must keep the canvas height"); + Assert.AreEqual(2d, frame.Padding, "The frame must keep the padding"); + Assert.AreEqual(5d, frame.Minimum, "The frame must start at the smallest value"); + Assert.AreEqual(42d, frame.Maximum, "The frame must end at the largest value"); + } + + /// + /// Verify a single sparkline sample renders as a centered horizontal path over the full width + /// + [TestMethod] + [TestCategory("AC6")] + public void SparklinePathBuilderSingleValueDrawsMidHeightLine() + { + var path = SparklinePathBuilder.BuildLinePath([42d], SparklineFrame.ForValues(100, 26, 2, [42d])); + + Assert.AreEqual("M 0,13 L 100,13", + path, + "A single sparkline sample must render as a centered horizontal line"); + } + + /// + /// Verify equal values render at mid-height instead of the bottom edge + /// + /// Repeated value + [TestMethod] + [TestCategory("AC6")] + [DataRow(0d)] + [DataRow(7d)] + public void SparklinePathBuilderEqualValuesDrawMidHeightLine(double value) + { + double[] values = [value, value, value]; + var path = SparklinePathBuilder.BuildLinePath(values, SparklineFrame.ForValues(100, 26, 2, values)); + var coordinates = ReadCoordinates(path); + + Assert.StartsWith("M 2,13", path, "An equal-values path must start at the left padding at mid-height"); + Assert.IsNotEmpty(coordinates, "The path must hold coordinates"); + Assert.IsTrue(coordinates.All(coordinate => Math.Abs(coordinate.Y - 13d) < 0.001d), $"Every point of the equal-values path must be at mid-height: {path}"); + } + + /// + /// Verify a single value on a frame with a non-zero range is drawn at its scaled height over the full width + /// + /// Single value + /// Expected height of the line + [TestMethod] + [TestCategory("AC6")] + [DataRow(100d, 2d)] + [DataRow(0d, 24d)] + public void SparklinePathBuilderSingleValueOnFrameWithRangeDrawsAtScaledHeight(double value, double expectedY) + { + var frame = new SparklineFrame + { + Width = 100, + Height = 26, + Padding = 2, + Minimum = 0, + Maximum = 100, + }; + + var path = SparklinePathBuilder.BuildLinePath([value], frame); + + Assert.AreEqual($"M 0,{expectedY} L 100,{expectedY}", + path, + "A single value on a frame with a range must be drawn at its scaled height over the full width"); + } + + /// + /// Verify two series on one frame share its scale + /// + [TestMethod] + [TestCategory("AC6")] + public void SparklinePathBuilderUsesFrameScale() + { + var frame = new SparklineFrame + { + Width = 100, + Height = 26, + Padding = 2, + Minimum = 0, + Maximum = 100, + }; + + // Points: x = 2 and 98, y = 2 + 22 * (1 - value / 100); control points move a sixth of the way: x 2 + 96 / 6 = 18 and 98 - 96 / 6 = 82 + var fullScale = SparklinePathBuilder.BuildLinePath([0d, 100d], frame); + var halfScale = SparklinePathBuilder.BuildLinePath([0d, 50d], frame); + var ownScale = SparklinePathBuilder.BuildLinePath([0d, 50d], SparklineFrame.ForValues(100, 26, 2, [0d, 50d])); + + Assert.AreEqual("M 2,24 C 18,20.33 82,5.67 98,2", fullScale, "The series that fills the frame must span the full height"); + Assert.AreEqual("M 2,24 C 18,22.17 82,14.83 98,13", halfScale, "A series of half the frame's maximum must end at mid-height"); + Assert.AreEqual("M 2,24 C 18,20.33 82,5.67 98,2", ownScale, "A frame of the series' own values must span the full height"); + } + + /// + /// Verify the area path repeats the line and closes along the bottom edge + /// + [TestMethod] + [TestCategory("AC6")] + public void SparklinePathBuilderAreaPathClosesToBottom() + { + double[] values = [10d, 20d, 15d, 30d]; + var frame = SparklineFrame.ForValues(100, 26, 2, values); + + var line = SparklinePathBuilder.BuildLinePath(values, frame); + var area = SparklinePathBuilder.BuildAreaPath(values, frame); + + Assert.StartsWith(line, area, "The area path must start with the line path"); + Assert.Contains("98,26", area, "The area path must drop from the last point to the bottom edge"); + Assert.EndsWith("Z", area, "The area path must be closed"); + } + + /// + /// Verify empty value lists render no path + /// + [TestMethod] + [TestCategory("AC6")] + public void SparklinePathBuilderEmptyValuesReturnEmptyPath() + { + double[] values = []; + var frame = SparklineFrame.ForValues(100, 26, 2, values); + + Assert.AreEqual(string.Empty, SparklinePathBuilder.BuildLinePath(values, frame), "An empty series must not render any line path data"); + Assert.AreEqual(string.Empty, SparklinePathBuilder.BuildAreaPath(values, frame), "An empty series must not render any area path data"); + } + + /// + /// Verify multiple sparkline samples render as a smoothed cubic path + /// + [TestMethod] + [TestCategory("AC6")] + public void SparklinePathBuilderMultipleValuesUseCubicSegments() + { + double[] values = [10d, 20d, 15d, 30d]; + + var path = SparklinePathBuilder.BuildLinePath(values, SparklineFrame.ForValues(100, 26, 2, values)); + + Assert.IsFalse(string.IsNullOrWhiteSpace(path), "A sparkline with multiple samples must produce SVG path data"); + Assert.StartsWith("M 2,24 ", path, "A sparkline path must start with a move to the oldest sample at the left padding"); + Assert.Contains(" C ", path, "A sparkline with multiple samples must use cubic Bezier segments for smoothing"); + Assert.EndsWith(" 98,2", path, "The sparkline must end at the newest sample at the top right"); + } + + #endregion // Methods + + #region Static methods + + /// + /// Read every coordinate pair of path data + /// + /// Path data + /// Coordinates + private static List<(double X, double Y)> ReadCoordinates(string path) + { + return [ + .. Regex.Matches(path, @"(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)") + .Select(match => (X: double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture), + Y: double.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture))) + ]; + } + + #endregion // Static methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/StatusToneFormatterTests.cs b/src/Tests/DockerUpdateGuard.Tests/StatusToneFormatterTests.cs index 465c03e0..ccd8f065 100644 --- a/src/Tests/DockerUpdateGuard.Tests/StatusToneFormatterTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/StatusToneFormatterTests.cs @@ -17,6 +17,7 @@ public class StatusToneFormatterTests /// Expected tone [TestMethod] [TestCategory("AC1")] + [TestCategory("AC11")] [DataRow("Succeeded", StatusTone.Success)] [DataRow("Partial", StatusTone.Warning)] [DataRow("Failed", StatusTone.Danger)] @@ -38,6 +39,7 @@ public class StatusToneFormatterTests [DataRow("Restarting", StatusTone.Warning)] [DataRow("Exited", StatusTone.Neutral)] [DataRow("Dead", StatusTone.Neutral)] + [DataRow("Requested", StatusTone.Warning)] public void StatusToneFormatterGetStatusToneKnownValueReturnsTone(string status, StatusTone expectedTone) { var exact = StatusToneFormatter.GetStatusTone(status); diff --git a/src/Tests/DockerUpdateGuard.Tests/VulnerabilityAssessmentCardTests.cs b/src/Tests/DockerUpdateGuard.Tests/VulnerabilityAssessmentCardTests.cs index ff4ea3b8..9929a070 100644 --- a/src/Tests/DockerUpdateGuard.Tests/VulnerabilityAssessmentCardTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/VulnerabilityAssessmentCardTests.cs @@ -356,6 +356,33 @@ await component.Find("button.summary-card__detail-toggle") } } + /// + /// Verify the embedded card renders its content without the frame and the label + /// + /// Task + [TestMethod] + [TestCategory("AC3")] + public async Task VulnerabilityAssessmentCardEmbeddedRendersWithoutFrameAndLabel() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var component = testContext.Render(parameters => parameters.Add(card => card.Assessment, CreateAssessment()) + .Add(card => card.Embedded, true)); + var markup = component.Markup; + + Assert.IsEmpty(component.FindAll(".summary-card"), "The embedded card must render without the summary card frame"); + Assert.IsEmpty(component.FindAll(".mud-paper"), "The embedded card must render without a paper"); + Assert.DoesNotContain("Vulnerability assessment", markup, "The embedded card must render without its label"); + Assert.Contains("Findings detected", markup, "The embedded card must still render the status"); + Assert.Contains("1 Critical", markup, "The embedded card must still render the severity chips"); + Assert.Contains("Trivy · 6 active", markup, "The embedded card must still render the source and the active finding count"); + Assert.Contains("4 of 6 findings can be fixed by updating this image", markup, "The embedded card must still lead with the fixable finding statement"); + Assert.Contains("Checked 2026-03-14 10:30 UTC", markup, "The embedded card must still render the check time"); + } + } + /// /// Read the class attribute of the status chip that shows a text /// diff --git a/src/Tests/DockerUpdateGuard.Tests/VulnerabilityRescanControlTests.cs b/src/Tests/DockerUpdateGuard.Tests/VulnerabilityRescanControlTests.cs index 2b973143..1cb60e06 100644 --- a/src/Tests/DockerUpdateGuard.Tests/VulnerabilityRescanControlTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/VulnerabilityRescanControlTests.cs @@ -338,6 +338,71 @@ public async Task VulnerabilityRescanControlWithOnlyLeadingContentRendersSplitLa } } + /// + /// Verify a button text turns the icon button into an outlined text button with the same announcement and no tooltip + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task VulnerabilityRescanControlWithButtonTextRendersLabelledTextButton() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + testContext.Services.AddSingleton(Substitute.For()); + + var component = testContext.Render(parameters => parameters.Add(control => control.ImageVersionId, Guid.NewGuid()) + .Add(control => control.ButtonText, "Rescan")); + var button = component.Find("button"); + + Assert.AreEqual("Rescan", button.TextContent.Trim(), "The button must show the given text"); + Assert.AreEqual("Rescan vulnerabilities", button.GetAttribute("aria-label"), "The text button must be announced as 'Rescan vulnerabilities'"); + Assert.Contains("mud-button-outlined-default", button.GetAttribute("class") ?? string.Empty, "The text button must be an outlined button in the default color"); + Assert.IsEmpty(component.FindComponents(), "The text button must have no tooltip"); + Assert.IsEmpty(component.FindComponents(), "The text button must replace the icon button"); + } + } + + /// + /// Verify hiding the check time removes the checked text and the never-scanned hint in both layouts + /// + /// Whether the split layout is used + /// Whether the image version has a check time + /// Task + [TestMethod] + [TestCategory("AC4")] + [DataRow(false, true)] + [DataRow(false, false)] + [DataRow(true, true)] + [DataRow(true, false)] + public async Task VulnerabilityRescanControlWithoutCheckedAtTextShowsNoCheckedLine(bool withLeadingContent, bool hasCheckedAt) + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + testContext.Services.AddSingleton(Substitute.For()); + + var component = testContext.Render(parameters => + { + parameters.Add(control => control.ImageVersionId, Guid.NewGuid()) + .Add(control => control.ShowCheckedAt, false) + .Add(control => control.CheckedAtUtc, hasCheckedAt ? new DateTimeOffset(2026, 11, 23, 21, 27, 0, TimeSpan.Zero) : null); + + if (withLeadingContent) + { + parameters.Add(control => control.LeadingContent, builder => builder.AddMarkupContent(0, "LEADING-LINE")); + } + }); + + Assert.DoesNotContain("Checked", component.Markup, "A hidden check time must render no checked text"); + Assert.DoesNotContain("Never scanned", component.Markup, "A hidden check time must render no never-scanned hint"); + Assert.HasCount(1, component.FindAll("button"), "The rescan button must still render"); + Assert.AreEqual(withLeadingContent, component.Markup.Contains("LEADING-LINE", StringComparison.Ordinal), "The split layout must still render its leading content"); + } + } + #endregion // Methods #region Helper methods From acc0c09d97ce5b0f7cb563ca7de33a2b51b6c2e9 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 21:08:58 +0000 Subject: [PATCH 10/26] Implement the shared detail page pieces Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_018g33AVnD3UUpZykmcVAdbH --- .../log.md | 1 + .../Common/DetailPageSkeleton.razor | 33 +++++ .../Components/Common/PageHeader.razor | 6 +- .../Common/ResourceHistoryChart.razor | 20 +++ .../Common/ResourceHistoryChart.razor.cs | 137 ++++++++++++++++++ .../Common/VulnerabilityAssessmentCard.razor | 23 ++- .../Common/VulnerabilityRescanControl.razor | 34 ++++- .../Pages/RuntimeContainers.razor.cs | 111 ++------------ .../UI/ApplicationViewService.cs | 1 + src/DockerUpdateGuard/UI/SparklineFrame.cs | 13 +- .../UI/SparklinePathBuilder.cs | 98 ++++++++++++- .../UI/StatusToneFormatter.cs | 1 + src/DockerUpdateGuard/wwwroot/app.css | 61 ++++++++ 13 files changed, 429 insertions(+), 110 deletions(-) diff --git a/specs/feature-456-runtime-container-detail/log.md b/specs/feature-456-runtime-container-detail/log.md index a77b1e1d..4b53c9d6 100644 --- a/specs/feature-456-runtime-container-detail/log.md +++ b/specs/feature-456-runtime-container-detail/log.md @@ -15,3 +15,4 @@ are quoted in full. | 2026-11-30 20:57 | 2b Challenge notes | Orchestrator | minor objections appended verbatim to plan.md | | 2026-11-30 20:59 | 4 Skeleton (G1) | Dev | Skeleton done: 7 new files (SparklineFrame, SparklinePathBuilder, ResourceHistoryChartKind, ResourceHistoryChart, DetailPageSkeleton) and additive parameters on PageHeader, VulnerabilityRescanControl, VulnerabilityAssessmentCard, ImageVersionId on the view data; format 0 changes, build 0 warnings; no pragmas; deviation: the two new .razor files are empty (sonnet/medium · 104,309 tokens · 8 tool uses · 121 s · 14 in · 5,816 out · 561,198 cache read · 102,814 cache write · 213,731 weighted) | | 2026-11-30 21:05 | 5 Tests first (G1) | Tester | Tests written for the shared pieces (SparklinePathBuilder, ResourceHistoryChart, DetailPageSkeleton, PageHeader, VulnerabilityRescanControl, VulnerabilityAssessmentCard, StatusToneFormatter, ApplicationViewService); reflection tests moved to the builder; confirmed by the orchestrator: compile, 36 of 120 filtered tests fail for the expected reason. Deferred: ResourceHistoryChartWithoutSamplesRendersNothing (sonnet/medium · 166,103 tokens · 22 tool uses · 273 s · 44 in · 33,196 out · 2,755,647 cache read · 111,433 cache write · 580,880 weighted) | +| 2026-11-30 21:08 | 6 Implement (G1) | Dev | Shared pieces implemented; build 0 warnings; Data.Tests 39/39, Tests 2887/2888. Disputed: VulnerabilityAssessmentCardEmbeddedRendersWithoutFrameAndLabel expects the Checked line with Embedded only (no ShowCheckedAt); Dev proposes adding ShowCheckedAt=true in the test. AppStylesheetRuntimeContainerDetailTests does not exist yet (G2) (sonnet/medium · 150,539 tokens · 23 tool uses · 218 s · 44 in · 18,805 out · 2,728,794 cache read · 96,175 cache write · 487,167 weighted) | diff --git a/src/DockerUpdateGuard/Components/Common/DetailPageSkeleton.razor b/src/DockerUpdateGuard/Components/Common/DetailPageSkeleton.razor index e69de29b..8efdcf04 100644 --- a/src/DockerUpdateGuard/Components/Common/DetailPageSkeleton.razor +++ b/src/DockerUpdateGuard/Components/Common/DetailPageSkeleton.razor @@ -0,0 +1,33 @@ +
+ + + +
+
+ +
+
+
+ + + +
+
+
+
+ + + +
+
+
+
\ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Common/PageHeader.razor b/src/DockerUpdateGuard/Components/Common/PageHeader.razor index 94ba293d..2dd66cd4 100644 --- a/src/DockerUpdateGuard/Components/Common/PageHeader.razor +++ b/src/DockerUpdateGuard/Components/Common/PageHeader.razor @@ -9,7 +9,11 @@

@Title

@TitleContent - @if (string.IsNullOrWhiteSpace(Description) == false) + @if (DescriptionContent is not null) + { +

@DescriptionContent

+ } + else if (string.IsNullOrWhiteSpace(Description) == false) {

@Description

} diff --git a/src/DockerUpdateGuard/Components/Common/ResourceHistoryChart.razor b/src/DockerUpdateGuard/Components/Common/ResourceHistoryChart.razor index e69de29b..97f878a6 100644 --- a/src/DockerUpdateGuard/Components/Common/ResourceHistoryChart.razor +++ b/src/DockerUpdateGuard/Components/Common/ResourceHistoryChart.razor @@ -0,0 +1,20 @@ +@if (_hasChart) +{ +
+ + @if (_areaPath.Length > 0) + { + + } + + @if (_secondLinePath.Length > 0) + { + + } + + @_rangeText +
+} \ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Common/ResourceHistoryChart.razor.cs b/src/DockerUpdateGuard/Components/Common/ResourceHistoryChart.razor.cs index 9268bd4b..2239b5f5 100644 --- a/src/DockerUpdateGuard/Components/Common/ResourceHistoryChart.razor.cs +++ b/src/DockerUpdateGuard/Components/Common/ResourceHistoryChart.razor.cs @@ -9,6 +9,69 @@ namespace DockerUpdateGuard.Components.Common; /// public partial class ResourceHistoryChart { + #region Constants + + /// + /// Width of the chart canvas + /// + private const double ChartWidth = 100d; + + /// + /// Height of the chart canvas + /// + private const double ChartHeight = 72d; + + /// + /// Padding between the canvas edge and the lines + /// + private const double ChartPadding = 2d; + + #endregion // Constants + + #region Fields + + /// + /// Whether the chart has anything to draw + /// + private bool _hasChart; + + /// + /// Accessible name of the chart + /// + private string _label = string.Empty; + + /// + /// Path data of the filled area, empty for a chart without area + /// + private string _areaPath = string.Empty; + + /// + /// Path data of the main line + /// + private string _linePath = string.Empty; + + /// + /// Path data of the second line, empty for a chart with one line + /// + private string _secondLinePath = string.Empty; + + /// + /// CSS class of the area + /// + private string _areaCssClass = string.Empty; + + /// + /// CSS class of the main line + /// + private string _lineCssClass = string.Empty; + + /// + /// Text of the range line + /// + private string _rangeText = string.Empty; + + #endregion // Fields + #region Properties /// @@ -25,4 +88,78 @@ public partial class ResourceHistoryChart public ResourceHistoryChartKind Kind { get; set; } #endregion // Properties + + #region Methods + + /// + /// Build the chart of a CPU or memory history: an area and a line + /// + /// Samples, oldest first + private void BuildAreaChart(List samples) + { + var isCpu = Kind == ResourceHistoryChartKind.Cpu; + var values = samples.Select(point => isCpu ? (double)point.CpuPercent : point.MemoryUsageBytes) + .ToArray(); + var frame = SparklineFrame.ForValues(ChartWidth, ChartHeight, ChartPadding, values); + var cssSuffix = isCpu ? "cpu" : "memory"; + + _label = isCpu ? "CPU history, last 24 hours" : "Memory history, last 24 hours"; + _areaPath = SparklinePathBuilder.BuildAreaPath(values, frame); + _linePath = SparklinePathBuilder.BuildLinePath(values, frame); + _areaCssClass = $"dug-history-chart__area dug-history-chart__area--{cssSuffix}"; + _lineCssClass = $"dug-history-chart__line dug-history-chart__line--{cssSuffix}"; + _rangeText = isCpu + ? $"Min {ResourceUsageFormatter.FormatCpuPercent(samples.Min(point => point.CpuPercent))} · max {ResourceUsageFormatter.FormatCpuPercent(samples.Max(point => point.CpuPercent))}" + : $"Min {ResourceUsageFormatter.FormatBytes(samples.Min(point => point.MemoryUsageBytes))} · max {ResourceUsageFormatter.FormatBytes(samples.Max(point => point.MemoryUsageBytes))}"; + } + + /// + /// Build the chart of a network history: received and sent traffic as two lines on one scale + /// + /// Samples, oldest first + private void BuildNetworkChart(List samples) + { + var received = samples.Select(point => (double)point.NetworkRxBytesPerSecond) + .ToArray(); + var sent = samples.Select(point => (double)point.NetworkTxBytesPerSecond) + .ToArray(); + var frame = SparklineFrame.ForValues(ChartWidth, ChartHeight, ChartPadding, received.Concat(sent)); + + _label = "Network history, last 24 hours"; + _linePath = SparklinePathBuilder.BuildLinePath(received, frame); + _secondLinePath = SparklinePathBuilder.BuildLinePath(sent, frame); + _lineCssClass = "dug-history-chart__line dug-history-chart__line--network-rx"; + _rangeText = $"Max {ResourceUsageFormatter.FormatBytesPerSecond(samples.Max(point => point.NetworkRxBytesPerSecond))} ↓ / {ResourceUsageFormatter.FormatBytesPerSecond(samples.Max(point => point.NetworkTxBytesPerSecond))} ↑"; + } + + #endregion // Methods + + #region ComponentBase + + /// + protected override void OnParametersSet() + { + var samples = (History ?? []).OrderBy(point => point.RecordedAtUtc) + .ToList(); + + _hasChart = samples.Count > 0 && Kind != ResourceHistoryChartKind.NotSet; + _areaPath = string.Empty; + _secondLinePath = string.Empty; + + if (_hasChart == false) + { + return; + } + + if (Kind == ResourceHistoryChartKind.Network) + { + BuildNetworkChart(samples); + } + else + { + BuildAreaChart(samples); + } + } + + #endregion // ComponentBase } \ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Common/VulnerabilityAssessmentCard.razor b/src/DockerUpdateGuard/Components/Common/VulnerabilityAssessmentCard.razor index 75022636..441c1a05 100644 --- a/src/DockerUpdateGuard/Components/Common/VulnerabilityAssessmentCard.razor +++ b/src/DockerUpdateGuard/Components/Common/VulnerabilityAssessmentCard.razor @@ -1,7 +1,10 @@ @if (Assessment is not null) { - - Vulnerability assessment + RenderFragment content = @ + @if (Embedded == false) + { + Vulnerability assessment + } @if (RemediationSummary is not null) { @RemediationSummary @@ -37,5 +40,17 @@ { @Assessment.Message } - -} + ; + @if (Embedded) + { +
+ @content +
+ } + else + { + + @content + + } +} \ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Common/VulnerabilityRescanControl.razor b/src/DockerUpdateGuard/Components/Common/VulnerabilityRescanControl.razor index e599a7f6..ddacaccc 100644 --- a/src/DockerUpdateGuard/Components/Common/VulnerabilityRescanControl.razor +++ b/src/DockerUpdateGuard/Components/Common/VulnerabilityRescanControl.razor @@ -1,18 +1,35 @@ @{ - RenderFragment rescanButton = @ - + @if (string.IsNullOrWhiteSpace(ButtonText) == false) + { + - ; + OnClick="RescanAsync">@ButtonText + } + else + { + + + + } + ; } @if (LeadingContent is not null || TrailingContent is not null) {
@LeadingContent - @CheckedText + @if (ShowCheckedAt) + { + @CheckedText + } @if (string.IsNullOrWhiteSpace(_errorMessage) == false) { @_errorMessage @@ -25,7 +42,10 @@ else {
- @CheckedText + @if (ShowCheckedAt) + { + @CheckedText + } @rescanButton
@if (string.IsNullOrWhiteSpace(_errorMessage) == false) diff --git a/src/DockerUpdateGuard/Components/Pages/RuntimeContainers.razor.cs b/src/DockerUpdateGuard/Components/Pages/RuntimeContainers.razor.cs index 312ce26f..44e7b449 100644 --- a/src/DockerUpdateGuard/Components/Pages/RuntimeContainers.razor.cs +++ b/src/DockerUpdateGuard/Components/Pages/RuntimeContainers.razor.cs @@ -1,6 +1,3 @@ -using System.Globalization; -using System.Text; - using DockerUpdateGuard.Data.Entities; using DockerUpdateGuard.Images.Interfaces; using DockerUpdateGuard.Infrastructure; @@ -157,7 +154,7 @@ private static string GetCpuSparklinePath(RuntimeContainerListItemData container { ArgumentNullException.ThrowIfNull(container); - return BuildSparklinePath(GetChronologicalHistory(container.ResourceUsageHistory).Select(point => (double)point.CpuPercent)); + return BuildSeriesPath(GetChronologicalHistory(container.ResourceUsageHistory).Select(point => (double)point.CpuPercent)); } /// @@ -169,7 +166,7 @@ private static string GetMemorySparklinePath(RuntimeContainerListItemData contai { ArgumentNullException.ThrowIfNull(container); - return BuildSparklinePath(GetChronologicalHistory(container.ResourceUsageHistory).Select(point => (double)point.MemoryUsageBytes)); + return BuildSeriesPath(GetChronologicalHistory(container.ResourceUsageHistory).Select(point => (double)point.MemoryUsageBytes)); } /// @@ -181,7 +178,7 @@ private static string GetNetworkReceiveSparklinePath(RuntimeContainerListItemDat { ArgumentNullException.ThrowIfNull(container); - return BuildSparklinePath(GetChronologicalHistory(container.ResourceUsageHistory).Select(point => (double)point.NetworkRxBytesPerSecond)); + return BuildSeriesPath(GetChronologicalHistory(container.ResourceUsageHistory).Select(point => (double)point.NetworkRxBytesPerSecond)); } /// @@ -193,107 +190,31 @@ private static string GetNetworkTransmitSparklinePath(RuntimeContainerListItemDa { ArgumentNullException.ThrowIfNull(container); - return BuildSparklinePath(GetChronologicalHistory(container.ResourceUsageHistory).Select(point => (double)point.NetworkTxBytesPerSecond)); - } - - /// - /// Order resource history from oldest to newest - /// - /// Resource history - /// Chronological history - private static List GetChronologicalHistory(IReadOnlyList history) - { - ArgumentNullException.ThrowIfNull(history); - - return [.. history.OrderBy(point => point.RecordedAtUtc)]; + return BuildSeriesPath(GetChronologicalHistory(container.ResourceUsageHistory).Select(point => (double)point.NetworkTxBytesPerSecond)); } /// - /// Build a smoothed sparkline path for SVG rendering + /// Build the sparkline path of a series scaled to its own values /// - /// Series values + /// Series values /// SVG path data - private static string BuildSparklinePath(IEnumerable values) + private static string BuildSeriesPath(IEnumerable series) { - ArgumentNullException.ThrowIfNull(values); - - var valueArray = values.ToArray(); + var values = series.ToArray(); - if (valueArray.Length == 0) - { - return string.Empty; - } - - if (valueArray.Length == 1) - { - var singleY = FormatSvgCoordinate(SparklineHeight / 2d); - - return $"M 0,{singleY} L {FormatSvgCoordinate(SparklineWidth)},{singleY}"; - } - - var minimum = valueArray.Min(); - var maximum = valueArray.Max(); - var range = maximum - minimum; - - if (range <= 0d) - { - range = 1d; - } - - var usableWidth = SparklineWidth - (SparklinePadding * 2d); - var usableHeight = SparklineHeight - (SparklinePadding * 2d); - var points = valueArray.Select((value, index) => - { - var xValue = SparklinePadding + (usableWidth * index / (valueArray.Length - 1d)); - var normalizedValue = (value - minimum) / range; - var yValue = SparklinePadding + (usableHeight * (1d - normalizedValue)); - - return (X: xValue, Y: yValue); - }) - .ToArray(); - var pathBuilder = new StringBuilder(); - - pathBuilder.Append("M "); - pathBuilder.Append(FormatSvgCoordinate(points[0].X)); - pathBuilder.Append(','); - pathBuilder.Append(FormatSvgCoordinate(points[0].Y)); - - for (var index = 0; index < points.Length - 1; index++) - { - var previousPoint = index > 0 ? points[index - 1] : points[index]; - var currentPoint = points[index]; - var nextPoint = points[index + 1]; - var followingPoint = index + 2 < points.Length ? points[index + 2] : nextPoint; - var firstControlPoint = (X: currentPoint.X + ((nextPoint.X - previousPoint.X) / 6d), - Y: currentPoint.Y + ((nextPoint.Y - previousPoint.Y) / 6d)); - var secondControlPoint = (X: nextPoint.X - ((followingPoint.X - currentPoint.X) / 6d), - Y: nextPoint.Y - ((followingPoint.Y - currentPoint.Y) / 6d)); - - pathBuilder.Append(" C "); - pathBuilder.Append(FormatSvgCoordinate(firstControlPoint.X)); - pathBuilder.Append(','); - pathBuilder.Append(FormatSvgCoordinate(firstControlPoint.Y)); - pathBuilder.Append(' '); - pathBuilder.Append(FormatSvgCoordinate(secondControlPoint.X)); - pathBuilder.Append(','); - pathBuilder.Append(FormatSvgCoordinate(secondControlPoint.Y)); - pathBuilder.Append(' '); - pathBuilder.Append(FormatSvgCoordinate(nextPoint.X)); - pathBuilder.Append(','); - pathBuilder.Append(FormatSvgCoordinate(nextPoint.Y)); - } - - return pathBuilder.ToString(); + return SparklinePathBuilder.BuildLinePath(values, SparklineFrame.ForValues(SparklineWidth, SparklineHeight, SparklinePadding, values)); } /// - /// Format an SVG coordinate using invariant culture + /// Order resource history from oldest to newest /// - /// Coordinate value - /// Formatted coordinate - private static string FormatSvgCoordinate(double value) + /// Resource history + /// Chronological history + private static List GetChronologicalHistory(IReadOnlyList history) { - return value.ToString("0.##", CultureInfo.InvariantCulture); + ArgumentNullException.ThrowIfNull(history); + + return [.. history.OrderBy(point => point.RecordedAtUtc)]; } #endregion // Static methods diff --git a/src/DockerUpdateGuard/UI/ApplicationViewService.cs b/src/DockerUpdateGuard/UI/ApplicationViewService.cs index b4576c29..7519d32f 100644 --- a/src/DockerUpdateGuard/UI/ApplicationViewService.cs +++ b/src/DockerUpdateGuard/UI/ApplicationViewService.cs @@ -1872,6 +1872,7 @@ private RuntimeContainerDetailViewData CreateRuntimeContainerDetail(Guid dockerI DockerInstanceId = dockerInstanceId, ContainerId = containerId, ContainerName = latestSnapshot.Name, + ImageVersionId = latestSnapshot.ImageVersionId, DockerInstanceName = latestSnapshot.DockerInstance.Name, ImageReference = _imageReferenceParser.Format(latestSnapshot.ImageVersion), CurrentTag = latestSnapshot.ImageVersion.Tag, diff --git a/src/DockerUpdateGuard/UI/SparklineFrame.cs b/src/DockerUpdateGuard/UI/SparklineFrame.cs index 6f787c09..bd2ef701 100644 --- a/src/DockerUpdateGuard/UI/SparklineFrame.cs +++ b/src/DockerUpdateGuard/UI/SparklineFrame.cs @@ -46,7 +46,18 @@ internal sealed class SparklineFrame /// Frame internal static SparklineFrame ForValues(double width, double height, double padding, IEnumerable values) { - throw new InvalidOperationException("Skeleton: not implemented"); + ArgumentNullException.ThrowIfNull(values); + + var valueArray = values.ToArray(); + + return new SparklineFrame + { + Width = width, + Height = height, + Padding = padding, + Minimum = valueArray.Length > 0 ? valueArray.Min() : 0d, + Maximum = valueArray.Length > 0 ? valueArray.Max() : 0d, + }; } #endregion // Static methods diff --git a/src/DockerUpdateGuard/UI/SparklinePathBuilder.cs b/src/DockerUpdateGuard/UI/SparklinePathBuilder.cs index 6b45a017..babcde04 100644 --- a/src/DockerUpdateGuard/UI/SparklinePathBuilder.cs +++ b/src/DockerUpdateGuard/UI/SparklinePathBuilder.cs @@ -1,3 +1,6 @@ +using System.Globalization; +using System.Text; + namespace DockerUpdateGuard.UI; /// @@ -15,7 +18,57 @@ internal static class SparklinePathBuilder /// Path data internal static string BuildLinePath(IReadOnlyList values, SparklineFrame frame) { - throw new InvalidOperationException("Skeleton: not implemented"); + ArgumentNullException.ThrowIfNull(values); + ArgumentNullException.ThrowIfNull(frame); + + if (values.Count == 0) + { + return string.Empty; + } + + if (values.Count == 1) + { + var singleY = FormatCoordinate(GetY(values[0], frame)); + + return $"M 0,{singleY} L {FormatCoordinate(frame.Width)},{singleY}"; + } + + var usableWidth = frame.Width - (frame.Padding * 2d); + var points = values.Select((value, index) => (X: frame.Padding + (usableWidth * index / (values.Count - 1d)), Y: GetY(value, frame))) + .ToArray(); + var pathBuilder = new StringBuilder(); + + pathBuilder.Append("M "); + pathBuilder.Append(FormatCoordinate(points[0].X)); + pathBuilder.Append(','); + pathBuilder.Append(FormatCoordinate(points[0].Y)); + + for (var index = 0; index < points.Length - 1; index++) + { + var previousPoint = index > 0 ? points[index - 1] : points[index]; + var currentPoint = points[index]; + var nextPoint = points[index + 1]; + var followingPoint = index + 2 < points.Length ? points[index + 2] : nextPoint; + var firstControlPoint = (X: currentPoint.X + ((nextPoint.X - previousPoint.X) / 6d), + Y: currentPoint.Y + ((nextPoint.Y - previousPoint.Y) / 6d)); + var secondControlPoint = (X: nextPoint.X - ((followingPoint.X - currentPoint.X) / 6d), + Y: nextPoint.Y - ((followingPoint.Y - currentPoint.Y) / 6d)); + + pathBuilder.Append(" C "); + pathBuilder.Append(FormatCoordinate(firstControlPoint.X)); + pathBuilder.Append(','); + pathBuilder.Append(FormatCoordinate(firstControlPoint.Y)); + pathBuilder.Append(' '); + pathBuilder.Append(FormatCoordinate(secondControlPoint.X)); + pathBuilder.Append(','); + pathBuilder.Append(FormatCoordinate(secondControlPoint.Y)); + pathBuilder.Append(' '); + pathBuilder.Append(FormatCoordinate(nextPoint.X)); + pathBuilder.Append(','); + pathBuilder.Append(FormatCoordinate(nextPoint.Y)); + } + + return pathBuilder.ToString(); } /// @@ -26,7 +79,48 @@ internal static string BuildLinePath(IReadOnlyList values, SparklineFram /// Path data internal static string BuildAreaPath(IReadOnlyList values, SparklineFrame frame) { - throw new InvalidOperationException("Skeleton: not implemented"); + var linePath = BuildLinePath(values, frame); + + if (linePath.Length == 0) + { + return linePath; + } + + var firstX = values.Count == 1 ? 0d : frame.Padding; + var lastX = values.Count == 1 ? frame.Width : frame.Width - frame.Padding; + var bottom = FormatCoordinate(frame.Height); + + return $"{linePath} L {FormatCoordinate(lastX)},{bottom} L {FormatCoordinate(firstX)},{bottom} Z"; + } + + /// + /// Get the vertical position of a value, at mid-height when the frame has no range + /// + /// Value + /// Drawing frame + /// Vertical position + private static double GetY(double value, SparklineFrame frame) + { + var range = frame.Maximum - frame.Minimum; + + if (range <= 0d) + { + return frame.Height / 2d; + } + + var usableHeight = frame.Height - (frame.Padding * 2d); + + return frame.Padding + (usableHeight * (1d - ((value - frame.Minimum) / range))); + } + + /// + /// Format an SVG coordinate using invariant culture + /// + /// Coordinate value + /// Formatted coordinate + private static string FormatCoordinate(double value) + { + return value.ToString("0.##", CultureInfo.InvariantCulture); } #endregion // Static methods diff --git a/src/DockerUpdateGuard/UI/StatusToneFormatter.cs b/src/DockerUpdateGuard/UI/StatusToneFormatter.cs index d048b594..3b371bf0 100644 --- a/src/DockerUpdateGuard/UI/StatusToneFormatter.cs +++ b/src/DockerUpdateGuard/UI/StatusToneFormatter.cs @@ -26,6 +26,7 @@ internal static class StatusToneFormatter ["Failed"] = StatusTone.Danger, ["Running"] = StatusTone.Info, ["Pending"] = StatusTone.Neutral, + ["Requested"] = StatusTone.Warning, ["NotSet"] = StatusTone.Neutral, ["NotScanned"] = StatusTone.Neutral, ["Update available"] = StatusTone.Warning, diff --git a/src/DockerUpdateGuard/wwwroot/app.css b/src/DockerUpdateGuard/wwwroot/app.css index 8d30c1e3..2486e504 100644 --- a/src/DockerUpdateGuard/wwwroot/app.css +++ b/src/DockerUpdateGuard/wwwroot/app.css @@ -1080,6 +1080,67 @@ a { stroke: var(--dug-chart-net-tx); } +.dug-history-chart { + display: flex; + flex-direction: column; + gap: 4px; + min-width: 0; +} + +.dug-history-chart svg { + display: block; + width: 100%; + height: 72px; + overflow: visible; +} + +.dug-history-chart__line { + fill: none; + stroke-width: 1.6; + stroke-linecap: round; + stroke-linejoin: round; +} + +.dug-history-chart__line--cpu { + stroke: var(--dug-chart-cpu); +} + +.dug-history-chart__line--memory { + stroke: var(--dug-chart-memory); +} + +.dug-history-chart__line--network-rx { + stroke: var(--dug-chart-net-rx); +} + +.dug-history-chart__line--network-tx { + stroke: var(--dug-chart-net-tx); +} + +.dug-history-chart__area { + stroke: none; +} + +.dug-history-chart__area--cpu { + fill: var(--dug-chart-cpu-fill); +} + +.dug-history-chart__area--memory { + fill: var(--dug-chart-memory-fill); +} + +.dug-history-chart__range { + color: var(--dug-text-muted); + font-size: 12px; +} + +.dug-assessment-embedded { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 0.5rem; +} + .details-grid { margin-top: 0.5rem; } From d7e172dc563da72a78532cce5bc577c221d77a80 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 21:09:30 +0000 Subject: [PATCH 11/26] Record the decision on the embedded card test Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_018g33AVnD3UUpZykmcVAdbH --- specs/feature-456-runtime-container-detail/log.md | 1 + 1 file changed, 1 insertion(+) diff --git a/specs/feature-456-runtime-container-detail/log.md b/specs/feature-456-runtime-container-detail/log.md index 4b53c9d6..118758d3 100644 --- a/specs/feature-456-runtime-container-detail/log.md +++ b/specs/feature-456-runtime-container-detail/log.md @@ -16,3 +16,4 @@ are quoted in full. | 2026-11-30 20:59 | 4 Skeleton (G1) | Dev | Skeleton done: 7 new files (SparklineFrame, SparklinePathBuilder, ResourceHistoryChartKind, ResourceHistoryChart, DetailPageSkeleton) and additive parameters on PageHeader, VulnerabilityRescanControl, VulnerabilityAssessmentCard, ImageVersionId on the view data; format 0 changes, build 0 warnings; no pragmas; deviation: the two new .razor files are empty (sonnet/medium · 104,309 tokens · 8 tool uses · 121 s · 14 in · 5,816 out · 561,198 cache read · 102,814 cache write · 213,731 weighted) | | 2026-11-30 21:05 | 5 Tests first (G1) | Tester | Tests written for the shared pieces (SparklinePathBuilder, ResourceHistoryChart, DetailPageSkeleton, PageHeader, VulnerabilityRescanControl, VulnerabilityAssessmentCard, StatusToneFormatter, ApplicationViewService); reflection tests moved to the builder; confirmed by the orchestrator: compile, 36 of 120 filtered tests fail for the expected reason. Deferred: ResourceHistoryChartWithoutSamplesRendersNothing (sonnet/medium · 166,103 tokens · 22 tool uses · 273 s · 44 in · 33,196 out · 2,755,647 cache read · 111,433 cache write · 580,880 weighted) | | 2026-11-30 21:08 | 6 Implement (G1) | Dev | Shared pieces implemented; build 0 warnings; Data.Tests 39/39, Tests 2887/2888. Disputed: VulnerabilityAssessmentCardEmbeddedRendersWithoutFrameAndLabel expects the Checked line with Embedded only (no ShowCheckedAt); Dev proposes adding ShowCheckedAt=true in the test. AppStylesheetRuntimeContainerDetailTests does not exist yet (G2) (sonnet/medium · 150,539 tokens · 23 tool uses · 218 s · 44 in · 18,805 out · 2,728,794 cache read · 96,175 cache write · 487,167 weighted) | +| 2026-11-30 21:09 | 6 Decide (G1) | Lead | RESULT: DECIDED — Dev is right: Embedded does not imply the check time; FIX: Tester — add ShowCheckedAt=true to the render parameters of VulnerabilityAssessmentCardEmbeddedRendersWithoutFrameAndLabel, assertions unchanged (opus/medium · 42,430 tokens · 6 tool uses · 21 s · 8 in · 2,136 out · 102,080 cache read · 41,103 cache write · 134,342 weighted) | From c7f708e9adee6ebeb297c37680a07eafec072033 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 21:12:02 +0000 Subject: [PATCH 12/26] Cover the shared detail page pieces Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_018g33AVnD3UUpZykmcVAdbH --- .../log.md | 1 + .../ResourceHistoryChartTests.cs | 48 +++++++++++++++++++ .../VulnerabilityAssessmentCardTests.cs | 3 +- 3 files changed, 51 insertions(+), 1 deletion(-) diff --git a/specs/feature-456-runtime-container-detail/log.md b/specs/feature-456-runtime-container-detail/log.md index 118758d3..ad1b5cba 100644 --- a/specs/feature-456-runtime-container-detail/log.md +++ b/specs/feature-456-runtime-container-detail/log.md @@ -17,3 +17,4 @@ are quoted in full. | 2026-11-30 21:05 | 5 Tests first (G1) | Tester | Tests written for the shared pieces (SparklinePathBuilder, ResourceHistoryChart, DetailPageSkeleton, PageHeader, VulnerabilityRescanControl, VulnerabilityAssessmentCard, StatusToneFormatter, ApplicationViewService); reflection tests moved to the builder; confirmed by the orchestrator: compile, 36 of 120 filtered tests fail for the expected reason. Deferred: ResourceHistoryChartWithoutSamplesRendersNothing (sonnet/medium · 166,103 tokens · 22 tool uses · 273 s · 44 in · 33,196 out · 2,755,647 cache read · 111,433 cache write · 580,880 weighted) | | 2026-11-30 21:08 | 6 Implement (G1) | Dev | Shared pieces implemented; build 0 warnings; Data.Tests 39/39, Tests 2887/2888. Disputed: VulnerabilityAssessmentCardEmbeddedRendersWithoutFrameAndLabel expects the Checked line with Embedded only (no ShowCheckedAt); Dev proposes adding ShowCheckedAt=true in the test. AppStylesheetRuntimeContainerDetailTests does not exist yet (G2) (sonnet/medium · 150,539 tokens · 23 tool uses · 218 s · 44 in · 18,805 out · 2,728,794 cache read · 96,175 cache write · 487,167 weighted) | | 2026-11-30 21:09 | 6 Decide (G1) | Lead | RESULT: DECIDED — Dev is right: Embedded does not imply the check time; FIX: Tester — add ShowCheckedAt=true to the render parameters of VulnerabilityAssessmentCardEmbeddedRendersWithoutFrameAndLabel, assertions unchanged (opus/medium · 42,430 tokens · 6 tool uses · 21 s · 8 in · 2,136 out · 102,080 cache read · 41,103 cache write · 134,342 weighted) | +| 2026-11-30 21:12 | 6 Coverage (decide) (G1) | Tester | Lead's FIX applied (ShowCheckedAt=true in the embedded card test); deferred test ResourceHistoryChartWithoutSamplesRendersNothing written plus a null-history test; Tests 2893/2893 before the last test, Data.Tests 39/39; coverage 99.6% new/changed, 95.8% overall; no other gaps (sonnet/medium · 98,604 tokens · 10 tool uses · 141 s · 20 in · 5,070 out · 853,753 cache read · 45,196 cache write · 167,240 weighted) | diff --git a/src/Tests/DockerUpdateGuard.Tests/ResourceHistoryChartTests.cs b/src/Tests/DockerUpdateGuard.Tests/ResourceHistoryChartTests.cs index b585c72e..0b6573aa 100644 --- a/src/Tests/DockerUpdateGuard.Tests/ResourceHistoryChartTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/ResourceHistoryChartTests.cs @@ -216,6 +216,54 @@ public async Task ResourceHistoryChartEqualValuesShowSameMinimumAndMaximum() } } + /// + /// Verify a chart without samples, or without a kind, renders nothing + /// + /// Chart kind + /// Number of samples + /// Task + [TestMethod] + [TestCategory("AC6")] + [DataRow(ResourceHistoryChartKind.Cpu, 0)] + [DataRow(ResourceHistoryChartKind.Memory, 0)] + [DataRow(ResourceHistoryChartKind.Network, 0)] + [DataRow(ResourceHistoryChartKind.NotSet, 0)] + [DataRow(ResourceHistoryChartKind.NotSet, 2)] + public async Task ResourceHistoryChartWithoutSamplesRendersNothing(ResourceHistoryChartKind kind, int sampleCount) + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var samples = Enumerable.Range(0, sampleCount) + .Select(minute => CreateSample(minute, 5m, 1048576L, 1024m, 512m)) + .ToList(); + + var component = Render(testContext, kind, samples); + + Assert.IsEmpty(component.Markup.Trim(), $"A {kind} chart with {sampleCount} samples must render nothing"); + Assert.IsEmpty(component.FindAll("svg"), "No chart image must be rendered"); + } + } + + /// + /// Verify a chart whose history was never supplied renders nothing + /// + /// Task + [TestMethod] + [TestCategory("AC6")] + public async Task ResourceHistoryChartNullHistoryRendersNothing() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var component = Render(testContext, ResourceHistoryChartKind.Cpu, null!); + + Assert.IsEmpty(component.FindAll("svg"), "A chart without a history must render no chart image"); + } + } + #endregion // Methods #region Static methods diff --git a/src/Tests/DockerUpdateGuard.Tests/VulnerabilityAssessmentCardTests.cs b/src/Tests/DockerUpdateGuard.Tests/VulnerabilityAssessmentCardTests.cs index 9929a070..2a568c94 100644 --- a/src/Tests/DockerUpdateGuard.Tests/VulnerabilityAssessmentCardTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/VulnerabilityAssessmentCardTests.cs @@ -369,7 +369,8 @@ public async Task VulnerabilityAssessmentCardEmbeddedRendersWithoutFrameAndLabel await using (testContext) { var component = testContext.Render(parameters => parameters.Add(card => card.Assessment, CreateAssessment()) - .Add(card => card.Embedded, true)); + .Add(card => card.Embedded, true) + .Add(card => card.ShowCheckedAt, true)); var markup = component.Markup; Assert.IsEmpty(component.FindAll(".summary-card"), "The embedded card must render without the summary card frame"); From 2d339fd22ffa7fb7fd2575cb6b62de24168ad6e9 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 21:12:09 +0000 Subject: [PATCH 13/26] Skip the skeleton of G2 --- specs/feature-456-runtime-container-detail/log.md | 1 + 1 file changed, 1 insertion(+) diff --git a/specs/feature-456-runtime-container-detail/log.md b/specs/feature-456-runtime-container-detail/log.md index ad1b5cba..0bd458a2 100644 --- a/specs/feature-456-runtime-container-detail/log.md +++ b/specs/feature-456-runtime-container-detail/log.md @@ -18,3 +18,4 @@ are quoted in full. | 2026-11-30 21:08 | 6 Implement (G1) | Dev | Shared pieces implemented; build 0 warnings; Data.Tests 39/39, Tests 2887/2888. Disputed: VulnerabilityAssessmentCardEmbeddedRendersWithoutFrameAndLabel expects the Checked line with Embedded only (no ShowCheckedAt); Dev proposes adding ShowCheckedAt=true in the test. AppStylesheetRuntimeContainerDetailTests does not exist yet (G2) (sonnet/medium · 150,539 tokens · 23 tool uses · 218 s · 44 in · 18,805 out · 2,728,794 cache read · 96,175 cache write · 487,167 weighted) | | 2026-11-30 21:09 | 6 Decide (G1) | Lead | RESULT: DECIDED — Dev is right: Embedded does not imply the check time; FIX: Tester — add ShowCheckedAt=true to the render parameters of VulnerabilityAssessmentCardEmbeddedRendersWithoutFrameAndLabel, assertions unchanged (opus/medium · 42,430 tokens · 6 tool uses · 21 s · 8 in · 2,136 out · 102,080 cache read · 41,103 cache write · 134,342 weighted) | | 2026-11-30 21:12 | 6 Coverage (decide) (G1) | Tester | Lead's FIX applied (ShowCheckedAt=true in the embedded card test); deferred test ResourceHistoryChartWithoutSamplesRendersNothing written plus a null-history test; Tests 2893/2893 before the last test, Data.Tests 39/39; coverage 99.6% new/changed, 95.8% overall; no other gaps (sonnet/medium · 98,604 tokens · 10 tool uses · 141 s · 20 in · 5,070 out · 853,753 cache read · 45,196 cache write · 167,240 weighted) | +| 2026-11-30 21:12 | 4 Skeleton skipped (G2) | Orchestrator | skipped — plan.md Signatures names no API for G2; task row 4: page members are private | From c84d468ab32c3645242d38631f71a23ec4f9fb6b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 21:22:24 +0000 Subject: [PATCH 14/26] Add the page tests first for the runtime container detail Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_018g33AVnD3UUpZykmcVAdbH --- .../log.md | 1 + ...ppStylesheetRuntimeContainerDetailTests.cs | 128 +++ ...timeContainerDetailPersistentStateTests.cs | 37 + .../RuntimeContainerDetailRenderTests.cs | 896 ++++++++++++++++-- .../RuntimeContainerDetailTests.cs | 360 ++++++- 5 files changed, 1325 insertions(+), 97 deletions(-) create mode 100644 src/Tests/DockerUpdateGuard.Tests/AppStylesheetRuntimeContainerDetailTests.cs diff --git a/specs/feature-456-runtime-container-detail/log.md b/specs/feature-456-runtime-container-detail/log.md index 0bd458a2..cec6592a 100644 --- a/specs/feature-456-runtime-container-detail/log.md +++ b/specs/feature-456-runtime-container-detail/log.md @@ -19,3 +19,4 @@ are quoted in full. | 2026-11-30 21:09 | 6 Decide (G1) | Lead | RESULT: DECIDED — Dev is right: Embedded does not imply the check time; FIX: Tester — add ShowCheckedAt=true to the render parameters of VulnerabilityAssessmentCardEmbeddedRendersWithoutFrameAndLabel, assertions unchanged (opus/medium · 42,430 tokens · 6 tool uses · 21 s · 8 in · 2,136 out · 102,080 cache read · 41,103 cache write · 134,342 weighted) | | 2026-11-30 21:12 | 6 Coverage (decide) (G1) | Tester | Lead's FIX applied (ShowCheckedAt=true in the embedded card test); deferred test ResourceHistoryChartWithoutSamplesRendersNothing written plus a null-history test; Tests 2893/2893 before the last test, Data.Tests 39/39; coverage 99.6% new/changed, 95.8% overall; no other gaps (sonnet/medium · 98,604 tokens · 10 tool uses · 141 s · 20 in · 5,070 out · 853,753 cache read · 45,196 cache write · 167,240 weighted) | | 2026-11-30 21:12 | 4 Skeleton skipped (G2) | Orchestrator | skipped — plan.md Signatures names no API for G2; task row 4: page members are private | +| 2026-11-30 21:22 | 5 Tests first (G2) | Tester | Page tests written and existing ones adapted (RuntimeContainerDetailRenderTests, RuntimeContainerDetailTests, PersistentStateTests, new AppStylesheetRuntimeContainerDetailTests); confirmed by the orchestrator: compile, failures for the expected reason (old layout). Deferred: AppStylesheetHistoryChartIs72PixelsHighInChartTokens (sonnet/medium · 133,125 tokens · 33 tool uses · 559 s · 64 in · 62,680 out · 7,216,000 cache read · 240,162 cache write · 1,335,266 weighted · continued from 5 Tests first (G1)) | diff --git a/src/Tests/DockerUpdateGuard.Tests/AppStylesheetRuntimeContainerDetailTests.cs b/src/Tests/DockerUpdateGuard.Tests/AppStylesheetRuntimeContainerDetailTests.cs new file mode 100644 index 00000000..e9574dca --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/AppStylesheetRuntimeContainerDetailTests.cs @@ -0,0 +1,128 @@ +using DockerUpdateGuard.Tests.Helper; + +namespace DockerUpdateGuard.Tests; + +/// +/// Tests for the rules of wwwroot/app.css that lay out the runtime container detail page +/// +[TestClass] +public class AppStylesheetRuntimeContainerDetailTests +{ + #region Constants + + /// + /// Shipped stylesheet below the host project directory + /// + private const string StylesheetPath = "wwwroot/app.css"; + + /// + /// Start of the media context of the wide layout, which begins at 960 px + /// + private const string WideContextStart = "@media (min-width: 960"; + + #endregion // Constants + + #region Fields + + /// + /// Column templates that stack the usage cells + /// + private static readonly string[] _stackedColumns = ["1fr", "minmax(0, 1fr)"]; + + #endregion // Fields + + #region Methods + + /// + /// Verify the details column sits right of the main column from 960 px and both columns may shrink below their content + /// + [TestMethod] + [TestCategory("AC9")] + public void AppStylesheetDetailLayoutPlacesDetailsRightFrom960Pixels() + { + var grid = GetDeclarations(".dug-detail", context => context.StartsWith(WideContextStart, StringComparison.Ordinal)); + var aside = GetDeclarations(".dug-detail__aside", context => context.StartsWith(WideContextStart, StringComparison.Ordinal)); + var main = GetDeclarations(".dug-detail__main", context => context.StartsWith(WideContextStart, StringComparison.Ordinal)); + + Assert.AreEqual("grid", grid.GetValueOrDefault("display"), "The detail layout must be a grid from 960 px"); + Assert.AreEqual("minmax(560px, 1fr) 320px", grid.GetValueOrDefault("grid-template-columns"), "The grid must hold the main column and a 320 px details column"); + Assert.AreEqual("24px", grid.GetValueOrDefault("gap"), "The columns must be 24 px apart"); + Assert.AreEqual("2", aside.GetValueOrDefault("grid-column"), "The details column must be the second column"); + Assert.AreEqual("1", aside.GetValueOrDefault("grid-row"), "The details column must share the first row"); + Assert.AreEqual("start", aside.GetValueOrDefault("align-self"), "The details column must be top-aligned"); + Assert.AreEqual("1", main.GetValueOrDefault("grid-column"), "The main column must be the first column"); + Assert.AreEqual("1", main.GetValueOrDefault("grid-row"), "The main column must share the first row"); + Assert.AreEqual("0", GetDeclarations(".dug-detail__main", _ => true).GetValueOrDefault("min-width"), "The main column must shrink below its content"); + Assert.AreEqual("0", GetDeclarations(".dug-detail__aside", _ => true).GetValueOrDefault("min-width"), "The details column must shrink below its content"); + } + + /// + /// Verify the usage cells form an auto-fitting grid that stacks into one column below 960 px + /// + [TestMethod] + [TestCategory("AC10")] + public void AppStylesheetUsageCellsStackBelow960Pixels() + { + var grid = GetDeclarations(".dug-usage", context => context.Length == 0); + var narrow = GetDeclarations(".dug-usage", context => context.StartsWith("@media (max-width: 959", StringComparison.Ordinal) || context.StartsWith("@media (max-width: 960", StringComparison.Ordinal)); + + Assert.AreEqual("grid", grid.GetValueOrDefault("display"), "The usage cells must form a grid"); + Assert.AreEqual("repeat(auto-fit, minmax(220px, 1fr))", grid.GetValueOrDefault("grid-template-columns"), "The usage cells must fit as many columns as are 220 px wide"); + Assert.Contains(narrow.GetValueOrDefault("grid-template-columns") ?? string.Empty, _stackedColumns, "The usage cells must stack below 960 px"); + } + + /// + /// Verify the entries of the details list are separated by the inner border token + /// + [TestMethod] + [TestCategory("AC3")] + public void AppStylesheetDetailListSeparatesEntriesWithInnerBorder() + { + var entry = GetDeclarations(".dug-detail-list__entry", context => context.Length == 0); + + var hairlines = entry.Where(declaration => declaration.Key.StartsWith("border", StringComparison.Ordinal) && declaration.Value.Contains("var(--dug-border-inner)", StringComparison.Ordinal)).ToList(); + + Assert.IsNotEmpty(hairlines, "An entry must be separated by a hairline in the inner border token"); + } + + /// + /// Verify the lead line of a panel is muted + /// + [TestMethod] + [TestCategory("AC8")] + public void AppStylesheetPanelLeadIsMuted() + { + var lead = GetDeclarations(".dug-panel__lead", context => context.Length == 0); + + Assert.AreEqual("var(--dug-text-muted)", lead.GetValueOrDefault("color"), "The lead line must use the muted text color"); + } + + #endregion // Methods + + #region Helper methods + + /// + /// Merge the declarations of the rules whose selector entry is exactly the given one and whose media context matches + /// + /// Selector entry + /// Media context predicate; the context of a top-level rule is empty + /// Property name to value, later rules winning + private static Dictionary GetDeclarations(string selector, Func matchContext) + { + var merged = new Dictionary(); + var rules = StylesheetReader.GetRules(StylesheetReader.ReadHostFile(StylesheetPath)) + .Where(rule => matchContext(rule.Context) && StylesheetReader.SplitTopLevel(rule.Selector, ',').Contains(selector)); + + foreach (var rule in rules) + { + foreach (var (name, value) in StylesheetReader.GetDeclarationList(rule.Body)) + { + merged[name] = value; + } + } + + return merged; + } + + #endregion // Helper methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/RuntimeContainerDetailPersistentStateTests.cs b/src/Tests/DockerUpdateGuard.Tests/RuntimeContainerDetailPersistentStateTests.cs index bc19b98f..d9ed3b0e 100644 --- a/src/Tests/DockerUpdateGuard.Tests/RuntimeContainerDetailPersistentStateTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/RuntimeContainerDetailPersistentStateTests.cs @@ -1,6 +1,7 @@ using Bunit; using DockerUpdateGuard.Components.Pages; +using DockerUpdateGuard.Data.Entities; using DockerUpdateGuard.Images.Interfaces; using DockerUpdateGuard.Tests.Helper; using DockerUpdateGuard.UI; @@ -120,6 +121,42 @@ public async Task RuntimeContainerDetailPersistsLoadedStateForPrerender() } } + /// + /// Verify a detail restored from persistent state carries the image version id the rescan needs + /// + /// Task + [TestMethod] + [TestCategory("AC11")] + public async Task RuntimeContainerDetailRestoredStateCarriesImageVersionId() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var viewService = Substitute.For(); + var enrichmentService = Substitute.For(); + var dockerInstanceId = Guid.NewGuid(); + var imageVersionId = Guid.NewGuid(); + var detail = CreateDetail(dockerInstanceId, "restored-container"); + + detail.ImageVersionId = imageVersionId; + testContext.Services.AddSingleton(enrichmentService); + RegisterServices(testContext, viewService); + + testContext.GetPersistentComponentState().Persist(StateKey, detail); + + var component = testContext.Render(parameters => parameters.Add(page => page.DockerInstanceId, dockerInstanceId) + .Add(page => page.ContainerId, ContainerId)); + var rescan = component.FindAll("button").SingleOrDefault(button => button.TextContent.Trim() == "Rescan"); + + Assert.IsNotNull(rescan, "The restored page must offer the rescan"); + + await rescan.ClickAsync().ConfigureAwait(false); + + await enrichmentService.Received(1).RefreshImageVersionAsync(imageVersionId, ScanTriggerSource.Manual, Arg.Any()).ConfigureAwait(false); + } + } + /// /// Register the services required to render the page /// diff --git a/src/Tests/DockerUpdateGuard.Tests/RuntimeContainerDetailRenderTests.cs b/src/Tests/DockerUpdateGuard.Tests/RuntimeContainerDetailRenderTests.cs index 9fd07092..da71eadb 100644 --- a/src/Tests/DockerUpdateGuard.Tests/RuntimeContainerDetailRenderTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/RuntimeContainerDetailRenderTests.cs @@ -1,8 +1,16 @@ +using System.Text.RegularExpressions; + +using AngleSharp.Dom; + using Bunit; +using DockerUpdateGuard.Data.Entities; +using DockerUpdateGuard.Portainer.Data; +using DockerUpdateGuard.Portainer.Interfaces; using DockerUpdateGuard.Tests.Helper; using DockerUpdateGuard.UI; +using Microsoft.AspNetCore.Components; using Microsoft.Extensions.DependencyInjection; using NSubstitute; @@ -17,58 +25,674 @@ namespace DockerUpdateGuard.Tests; [TestClass] public class RuntimeContainerDetailRenderTests { + #region Constants + + /// + /// Container identifier used by the tests + /// + private const string ContainerId = "abc123"; + + /// + /// Digest of the runtime image + /// + private const string FullDigest = "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + + #endregion // Constants + + #region Fields + + /// + /// Time the detail was observed + /// + private static readonly DateTimeOffset _observedAtUtc = new(2026, 11, 23, 21, 27, 0, TimeSpan.Zero); + + #endregion // Fields + #region Methods /// - /// Verify the resource-history charts render inside the responsive chart wrapper and the current-usage cards render + /// Verify the usage panel shows the current values and a chart with a range line per cell + /// + /// Task + [TestMethod] + [TestCategory("AC5")] + public async Task RuntimeContainerDetailUsageCellsShowValuesAndCharts() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var detail = CreateDetail(); + + detail.CurrentResourceUsage = CreateUsagePoint(0); + detail.ResourceUsageHistory = [CreateUsagePoint(1), CreateUsagePoint(0)]; + + var component = Render(testContext, detail); + var panel = FindPanel(component, "Resource usage"); + var cells = panel.QuerySelectorAll(".dug-usage > *").ToList(); + var expected = new[] + { + ("CPU", "12.5 %", "CPU history, last 24 hours"), + ("Memory", "256.0 MB / 1.0 GB", "Memory history, last 24 hours"), + ("Network", "1.0 KB/s ↓ / 512.0 B/s ↑", "Network history, last 24 hours") + }; + + Assert.AreEqual("Current value and the last 24 hours", panel.QuerySelector(".dug-panel__meta")?.TextContent.Trim(), "The panel must carry its meta text"); + Assert.HasCount(3, cells, "The panel must show three usage cells"); + + for (var index = 0; index < expected.Length; index++) + { + var (label, value, chartLabel) = expected[index]; + + var text = Normalize(cells[index].TextContent); + + Assert.StartsWith(label, text, $"The {label} cell must start with its label"); + Assert.Contains(value, text, $"The {label} cell must show the current value"); + Assert.AreEqual(chartLabel, cells[index].QuerySelector("svg[role='img']")?.GetAttribute("aria-label"), $"The {label} cell must show its chart as a labelled image"); + Assert.IsNotNull(cells[index].QuerySelector(".dug-history-chart__range"), $"The {label} cell must show its range line"); + } + + Assert.DoesNotContain("No resource history is currently stored for this container.", component.Markup, "The empty-state text must stay hidden with samples"); + Assert.DoesNotContain("dug-chart\"", component.Markup, "The old chart wrapper must be gone"); + } + } + + /// + /// Verify the usage panel without samples shows the current values or n/a, no chart and the empty text + /// + /// Task + [TestMethod] + [TestCategory("AC5")] + public async Task RuntimeContainerDetailUsageWithoutSamplesShowsNoChartAndEmptyText() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var component = Render(testContext, CreateDetail()); + var panel = FindPanel(component, "Resource usage"); + var cells = panel.QuerySelectorAll(".dug-usage > *").ToList(); + + Assert.HasCount(3, cells, "The panel must still show its three cells"); + Assert.IsTrue(cells.All(cell => Normalize(cell.TextContent).Contains("n/a", StringComparison.Ordinal)), "Every cell must show n/a without a current sample"); + Assert.IsEmpty(panel.QuerySelectorAll("svg"), "No chart must render without samples"); + Assert.IsEmpty(panel.QuerySelectorAll(".dug-history-chart__range"), "No range line must render without samples"); + Assert.Contains("No resource history is currently stored for this container.", panel.TextContent, "The panel must show the empty-state text"); + } + } + + /// + /// Verify the header shows the breadcrumb, the status chips and the line with the instance link + /// + /// Task + [TestMethod] + [TestCategory("AC1")] + public async Task RuntimeContainerDetailHeaderShowsBreadcrumbChipsAndInstanceLink() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var detail = CreateDetail(); + + detail.UpdateStatus = "Update available"; + detail.AvailableUpdateVersionTag = "v3.2.0"; + + var component = Render(testContext, detail); + var breadcrumb = component.Find(".dug-page-header__breadcrumb"); + var chips = component.FindAll(".dug-page-header__title-row .dug-chip").ToList(); + var description = component.Find("p.dug-page-header__description"); + var instanceLink = description.QuerySelector("a"); + var breadcrumbLink = breadcrumb.QuerySelector("a"); + + Assert.AreEqual("api", component.Find("h1").TextContent.Trim(), "The title must be the container name"); + Assert.AreEqual("Runtime Containers", breadcrumbLink?.TextContent.Trim(), "The breadcrumb must start with the list link"); + Assert.AreEqual("/runtime-containers", breadcrumbLink?.GetAttribute("href"), "The breadcrumb link must point to the list"); + Assert.Contains("api", Normalize(breadcrumb.TextContent), "The breadcrumb must end with the container name"); + Assert.HasCount(2, chips, "The title row must show the runtime status and the update chip"); + Assert.AreEqual("Running", chips[0].TextContent.Trim(), "The first chip must show the runtime status"); + Assert.Contains("dug-chip--info", chips[0].ClassName ?? string.Empty, "A running container must have the info tone"); + Assert.AreEqual("Update available · v3.2.0", chips[1].TextContent.Trim(), "The second chip must show the update state and the available version"); + Assert.Contains("dug-chip--warning", chips[1].ClassName ?? string.Empty, "An available update must have the warning tone"); + Assert.AreEqual("Production · observed 2026-11-23 21:27 UTC", Normalize(description.TextContent), "The description must show the instance and the observation time"); + Assert.AreEqual($"/docker-instances/{detail.DockerInstanceId}", instanceLink?.GetAttribute("href"), "The instance name must link to its page"); + Assert.AreEqual("Production", instanceLink?.TextContent.Trim(), "The link must carry the instance name"); + } + } + + /// + /// Verify the header shows the update state alone without an available version and neutral chips for states without a tone + /// + /// Runtime status + /// Update state + /// Expected tone of the runtime chip + /// Task + [TestMethod] + [TestCategory("AC1")] + [DataRow("Exited", "Not evaluated", "neutral")] + [DataRow("Running", "Unsupported", "info")] + public async Task RuntimeContainerDetailHeaderWithoutVersionShowsStateOnly(string runtimeStatus, string updateStatus, string runtimeTone) + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var detail = CreateDetail(); + + detail.RuntimeStatus = runtimeStatus; + detail.UpdateStatus = updateStatus; + + var component = Render(testContext, detail); + var chips = component.FindAll(".dug-page-header__title-row .dug-chip").ToList(); + + Assert.HasCount(2, chips, "The title row must show two chips"); + Assert.AreEqual(runtimeStatus, chips[0].TextContent.Trim(), "The first chip must show the runtime status"); + Assert.Contains($"dug-chip--{runtimeTone}", chips[0].ClassName ?? string.Empty, "The runtime chip must take its tone from the shared mapping"); + Assert.AreEqual(updateStatus, chips[1].TextContent.Trim(), "The update chip must show the state alone"); + Assert.Contains("dug-chip--neutral", chips[1].ClassName ?? string.Empty, "A state without a tone must show a neutral chip"); + } + } + + /// + /// Verify the details panel lists its seven entries in order with today's contents + /// + /// Task + [TestMethod] + [TestCategory("AC3")] + public async Task RuntimeContainerDetailDetailsPanelListsEntriesInOrder() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var observedImageId = Guid.NewGuid(); + var detail = CreateDetail(); + + detail.ImageReference = $"ghcr.io/acme/api:latest@{FullDigest}"; + detail.CurrentTag = "latest"; + detail.ResolvedVersionTag = "1.0.5"; + detail.ComposeProject = "shop"; + detail.ServiceName = "web"; + detail.LinkedObservedImageId = observedImageId; + detail.LinkedObservedImageName = "acme/api-own"; + detail.UpdateStatus = "Update available"; + detail.AvailableUpdateVersionTag = "v3.2.0"; + detail.UpdateMessage = "A newer tag exists"; + detail.BaseRuntimeAlertSummary = "The base runtime is outdated"; + detail.BaseRuntimeAlertDetails = "Rebuild the own image"; + detail.ActiveBaseImageVulnerabilityFindingCount = 2; + detail.BaseImageVulnerabilitySummary = "2 base image findings"; + detail.VulnerabilityAssessment = CreateAssessment(); + + var component = Render(testContext, detail); + var entries = GetEntries(component); + + Assert.AreSequenceEqual(["Runtime image", "Compose project and service", "Observed own image", "Update assessment", "Base runtime", "Vulnerabilities", "Base image vulnerabilities"], + entries.Select(entry => entry.Label).ToList(), + "The details panel must list its entries in order"); + + var runtimeImage = entries[0].Value; + var digest = runtimeImage.QuerySelector("[title]"); + + Assert.Contains("ghcr.io/acme/api:latest", Normalize(runtimeImage.TextContent), "The runtime image entry must show the image reference"); + Assert.Contains("latest · 1.0.5", Normalize(runtimeImage.TextContent), "An alias tag must show its resolved version"); + Assert.AreEqual(FullDigest, digest?.GetAttribute("title"), "The full digest must be the tooltip"); + Assert.StartsWith("@sha256:", digest?.TextContent.Trim() ?? string.Empty, "The short digest must start with @sha256:"); + Assert.Contains("shop · web", Normalize(entries[1].Value.TextContent), "The compose entry must show the project and the service"); + Assert.AreEqual($"/observed-images/{observedImageId}", entries[2].Value.QuerySelector("a")?.GetAttribute("href"), "The own image must link to its page"); + Assert.Contains("acme/api-own", entries[2].Value.TextContent, "The own image link must carry its name"); + Assert.Contains("Update available · v3.2.0", Normalize(entries[3].Value.TextContent), "The update entry must show the state and the version"); + Assert.Contains("A newer tag exists", entries[3].Value.TextContent, "The update entry must show the update message"); + + var baseRuntime = Normalize(entries[4].Value.TextContent); + + Assert.Contains("Runtime warning", baseRuntime, "The base runtime entry must show its chip"); + Assert.Contains("The base runtime is outdated", baseRuntime, "The base runtime entry must show the summary"); + Assert.Contains("Rebuild the own image", baseRuntime, "The base runtime entry must show the details"); + + var vulnerabilities = Normalize(entries[5].Value.TextContent); + + Assert.Contains("Findings detected", vulnerabilities, "The vulnerabilities entry must show the assessment status"); + Assert.Contains("Trivy · 6 active", vulnerabilities, "The vulnerabilities entry must show the source and the active count"); + Assert.Contains("Checked 2026-03-14 10:30 UTC", vulnerabilities, "The vulnerabilities entry must show the check time"); + Assert.IsNotNull(FindButton(entries[5].Value, "Rescan"), "The vulnerabilities entry must offer the rescan"); + Assert.Contains("2 base image findings", entries[6].Value.TextContent, "The base image entry must show the summary"); + } + } + + /// + /// Verify the conditional entries are hidden under their conditions + /// + /// Task + [TestMethod] + [TestCategory("AC3")] + public async Task RuntimeContainerDetailDetailsPanelHidesConditionalEntries() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var component = Render(testContext, CreateDetail()); + var entries = GetEntries(component); + + Assert.AreSequenceEqual(["Runtime image", "Observed own image", "Update assessment", "Vulnerabilities"], + entries.Select(entry => entry.Label).ToList(), + "Without a compose label, a base runtime alert and base image findings only four entries must show"); + Assert.Contains("No linked own image", entries[1].Value.TextContent, "An unlinked container must say so"); + } + } + + /// + /// Verify the base runtime entry takes its chip and tone from the link to an own image + /// + /// Whether the container is linked to an own image + /// Expected chip text + /// Expected tone + /// Task + [TestMethod] + [TestCategory("AC3")] + [DataRow(true, "Runtime warning", "warning")] + [DataRow(false, "Runtime hint", "info")] + public async Task RuntimeContainerDetailBaseRuntimeEntryChipTone(bool linked, string expectedText, string expectedTone) + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var detail = CreateDetail(); + + detail.BaseRuntimeAlertSummary = "The base runtime is outdated"; + detail.LinkedObservedImageId = linked ? Guid.NewGuid() : null; + detail.LinkedObservedImageName = linked ? "acme/api-own" : null; + + var component = Render(testContext, detail); + var chip = GetEntries(component).Single(entry => entry.Label == "Base runtime").Value.QuerySelector(".dug-chip"); + + Assert.AreEqual(expectedText, chip?.TextContent.Trim(), "The chip must name the alert kind"); + Assert.Contains($"dug-chip--{expectedTone}", chip?.ClassName ?? string.Empty, "The chip must have the tone of the alert kind"); + } + } + + /// + /// Verify the base image findings chip has the fixed warning tone, not the tone of an empty severity summary + /// + /// Task + [TestMethod] + [TestCategory("AC3")] + public async Task RuntimeContainerDetailBaseImageVulnerabilitiesChipHasFixedWarningTone() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var detail = CreateDetail(); + + detail.ActiveBaseImageVulnerabilityFindingCount = 3; + detail.BaseImageVulnerabilitySummary = "3 base image findings"; + + var component = Render(testContext, detail); + var chip = GetEntries(component).Single(entry => entry.Label == "Base image vulnerabilities").Value.QuerySelector(".dug-chip"); + + Assert.AreEqual("Findings detected", chip?.TextContent.Trim(), "The chip must say that findings are detected"); + Assert.Contains("dug-chip--warning", chip?.ClassName ?? string.Empty, "The chip must have the fixed warning tone"); + } + } + + /// + /// Verify the assessment sits in the rescan control's leading content, with one check line and the button at its right /// /// Task [TestMethod] - public async Task RuntimeContainerDetailWithHistoryRendersResponsiveChartsAndUsageCards() + [TestCategory("AC4")] + public async Task RuntimeContainerDetailVulnerabilitiesEntryPlacesCardInRescanControlLeadingContent() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var detail = CreateDetail(); + + detail.VulnerabilityAssessment = CreateAssessment(); + + var component = Render(testContext, detail); + var entry = GetEntries(component).Single(item => item.Label == "Vulnerabilities").Value; + var control = entry.QuerySelector(".vulnerability-rescan-control--split"); + var details = control?.QuerySelector(".vulnerability-rescan-control__details"); + + Assert.IsNotNull(control, "The entry must use the split layout of the rescan control"); + Assert.Contains("Findings detected", details?.TextContent ?? string.Empty, "The assessment must sit in the control's leading content"); + Assert.IsEmpty(entry.QuerySelectorAll(".summary-card"), "The embedded assessment must have no card frame"); + Assert.IsEmpty(entry.QuerySelectorAll(".summary-label"), "The embedded assessment must have no label"); + Assert.AreEqual(1, Regex.Count(entry.TextContent, "Checked ", RegexOptions.None, TimeSpan.FromSeconds(1)), "The entry must show exactly one check line"); + Assert.DoesNotContain("Never scanned", entry.TextContent, "The entry must not show the never-scanned hint"); + Assert.IsNull(details?.QuerySelector("button[aria-label='Rescan vulnerabilities']"), "The button must stand beside the details, not inside them"); + Assert.AreEqual("Rescan", entry.QuerySelector("button[aria-label='Rescan vulnerabilities']")?.TextContent.Trim(), "The text button must be announced as 'Rescan vulnerabilities'"); + } + } + + /// + /// Verify a never checked image shows no check line and no never-scanned hint but still offers the rescan + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task RuntimeContainerDetailNeverCheckedVulnerabilitiesShowNoCheckLineButRescan() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var detail = CreateDetail(); + + detail.VulnerabilityAssessment = new VulnerabilityAssessmentViewData + { + Status = "Not scanned", + Source = "Trivy", + ActiveFindingCount = 0, + }; + + var component = Render(testContext, detail); + var entry = GetEntries(component).Single(item => item.Label == "Vulnerabilities").Value; + + Assert.DoesNotContain("Checked", entry.TextContent, "A never checked image must show no check line"); + Assert.DoesNotContain("Never scanned", entry.TextContent, "The entry must not show the never-scanned hint"); + Assert.IsNotNull(FindButton(entry, "Rescan"), "The rescan must still be offered"); + } + } + + /// + /// Verify the candidates panel without a stored preference shows the none line, the explanation and no clear button + /// + /// Task + [TestMethod] + [TestCategory("AC7")] + public async Task RuntimeContainerDetailCandidatesWithoutPreferenceShowNoneLine() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var component = Render(testContext, CreateDetail()); + var panel = FindPanel(component, "Available tag candidates"); + var lead = Normalize(panel.QuerySelector(".dug-panel__lead")?.TextContent ?? string.Empty); + + Assert.Contains("Manual tag preference: none.", lead, "The lead must say that no preference is stored"); + Assert.Contains("Selecting a tag stores a preference; it does not change or redeploy the container.", lead, "The lead must explain what selecting does"); + Assert.IsNull(FindButton(panel, "Clear selection"), "No clear button must show without a preference"); + Assert.IsEmpty(component.FindAll(".dug-panel__title").Where(title => title.TextContent.Trim() == "Manual tag preference"), "The separate preference section must be gone"); + } + } + + /// + /// Verify a stored preference shows its line with the save time, the selected chip, the saved button and the clear button in the header + /// + /// Task + [TestMethod] + [TestCategory("AC7")] + public async Task RuntimeContainerDetailCandidatesWithPreferenceShowSelectedChipAndClearButton() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var detail = CreateDetail(); + + detail.ManualSelectionImage = "docker.io/company/api:2.0.0"; + detail.ManualSelectionAtUtc = new DateTimeOffset(2026, 11, 23, 23, 27, 0, TimeSpan.FromHours(2)); + detail.AvailableTagCandidates = [CreateCandidate("2.0.0", isSelected: true), CreateCandidate("2.1.0")]; + + var component = Render(testContext, detail); + var panel = FindPanel(component, "Available tag candidates"); + var rows = panel.QuerySelectorAll("tbody tr").ToList(); + var selectedChip = rows[0].QuerySelectorAll("[data-label='Tag'] .dug-chip").SingleOrDefault(chip => chip.TextContent.Trim() == "Selected"); + + Assert.Contains("Manual tag preference: docker.io/company/api:2.0.0, saved 2026-11-23 21:27 UTC.", Normalize(panel.QuerySelector(".dug-panel__lead")?.TextContent ?? string.Empty), "The lead must name the stored preference and its save time"); + Assert.AreEqual("Clear selection", panel.QuerySelector(".dug-panel__header button")?.TextContent.Trim(), "The header button must clear the selection"); + Assert.HasCount(2, rows, "Both candidates must show"); + Assert.IsNotNull(selectedChip, "The stored preference must carry the selected chip"); + Assert.Contains("dug-chip--info", selectedChip.ClassName ?? string.Empty, "The selected chip must have the info tone"); + Assert.IsNull(rows[1].QuerySelectorAll("[data-label='Tag'] .dug-chip").FirstOrDefault(chip => chip.TextContent.Trim() == "Selected"), "Only the stored preference must be selected"); + Assert.AreEqual("Saved", rows[0].QuerySelector("[data-label='Action'] button")?.TextContent.Trim(), "The stored preference must offer Saved"); + Assert.AreEqual("Select", rows[1].QuerySelector("[data-label='Action'] button")?.TextContent.Trim(), "Another candidate must offer Select"); + } + } + + /// + /// Verify a stored preference outside the shown candidates appears only in the lead line + /// + /// Task + [TestMethod] + [TestCategory("AC7")] + public async Task RuntimeContainerDetailCandidatesPreferenceOutsideCandidatesAppearsOnlyInLead() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var detail = CreateDetail(); + + detail.ManualSelectionImage = "docker.io/company/api:9.9.9"; + detail.AvailableTagCandidates = [CreateCandidate("2.1.0")]; + + var component = Render(testContext, detail); + var panel = FindPanel(component, "Available tag candidates"); + + Assert.Contains("docker.io/company/api:9.9.9", panel.QuerySelector(".dug-panel__lead")?.TextContent ?? string.Empty, "The lead must name the stored preference"); + Assert.IsEmpty(panel.QuerySelectorAll("tbody .dug-chip").Where(chip => chip.TextContent.Trim() == "Selected"), "No candidate must carry the selected chip"); + } + } + + /// + /// Verify the recommended candidates carry the success chip and the others do not + /// + /// Task + [TestMethod] + [TestCategory("AC7")] + public async Task RuntimeContainerDetailCandidatesMarkRecommendedCandidate() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var detail = CreateDetail(); + + detail.AvailableTagCandidates = [CreateCandidate("2.1.0", isRecommended: true), CreateCandidate("2.0.0")]; + + var component = Render(testContext, detail); + var rows = FindPanel(component, "Available tag candidates").QuerySelectorAll("tbody tr").ToList(); + var recommended = rows[0].QuerySelectorAll("[data-label='Tag'] .dug-chip").SingleOrDefault(chip => chip.TextContent.Trim() == "Recommended"); + + Assert.IsNotNull(recommended, "The recommended candidate must carry the recommended chip"); + Assert.Contains("dug-chip--success", recommended.ClassName ?? string.Empty, "The recommended chip must have the success tone"); + Assert.Contains("2.1.0", rows[0].QuerySelector("[data-label='Tag']")?.TextContent ?? string.Empty, "The tag must be shown as text"); + Assert.IsEmpty(rows[1].QuerySelectorAll(".dug-chip"), "A candidate that is neither recommended nor selected must carry no chip"); + } + } + + /// + /// Verify the published cell shows the time of a known date and a dash for an unknown one + /// + /// Task + [TestMethod] + [TestCategory("AC7")] + public async Task RuntimeContainerDetailCandidatePublishedShowsTimeOrDash() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var detail = CreateDetail(); + var known = CreateCandidate("2.1.0"); + var unknown = CreateCandidate("2.0.0"); + + known.PublishedAtUtc = new DateTimeOffset(2026, 11, 20, 8, 5, 0, TimeSpan.Zero); + unknown.PublishedAtUtc = null; + detail.AvailableTagCandidates = [known, unknown]; + + var component = Render(testContext, detail); + var rows = FindPanel(component, "Available tag candidates").QuerySelectorAll("tbody tr").ToList(); + + Assert.AreEqual("2026-11-20 08:05 UTC", rows[0].QuerySelector("[data-label='Published']")?.TextContent.Trim(), "A known publish date must be shown in the timestamp format"); + Assert.AreEqual("—", rows[1].QuerySelector("[data-label='Published']")?.TextContent.Trim(), "An unknown publish date must be shown as a dash"); + } + } + + /// + /// Verify the main column shows its panels in the order of the spec, the container actions only when shown + /// + /// Whether the container actions are shown + /// Task + [TestMethod] + [TestCategory("AC8")] + [DataRow(true)] + [DataRow(false)] + public async Task RuntimeContainerDetailMainColumnShowsPanelsInOrder(bool withActions) { var testContext = BlazorTestContextFactory.Create(); await using (testContext) { var viewService = Substitute.For(); - var tagSelectionService = Substitute.For(); - var instanceId = Guid.NewGuid(); - - viewService.GetRuntimeContainerDetailAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Task.FromResult(new RuntimeContainerDetailViewData - { - DockerInstanceId = instanceId, - ContainerId = "abc123", - ContainerName = "api", - DockerInstanceName = "local", - ImageReference = "docker.io/company/api:1.0.0", - ActiveBaseImageVulnerabilityFindingCount = 1, - BaseImageVulnerabilitySummary = "1 base image finding", - VulnerabilityAssessment = new VulnerabilityAssessmentViewData - { - Status = "Findings detected", - Source = "Trivy", - ActiveFindingCount = 3, - FixableFindingCount = 2, - NewFindingCount = 1, - ResolvedFindingCount = 1, - CheckedAtUtc = DateTimeOffset.UtcNow, - Message = "Scan completed", - }, - CurrentResourceUsage = CreateUsagePoint(), - ResourceUsageHistory = [CreateUsagePoint(), CreateUsagePoint()], - })); + var detail = CreateDetail(); + viewService.GetRuntimeContainerDetailAsync(detail.DockerInstanceId, ContainerId, Arg.Any()) + .Returns(detail); testContext.Services.AddSingleton(viewService); - testContext.Services.AddSingleton(tagSelectionService); - testContext.AddHiddenContainerActions(); + testContext.Services.AddSingleton(Substitute.For()); - var component = testContext.Render(parameters => parameters.Add(page => page.DockerInstanceId, instanceId) - .Add(page => page.ContainerId, "abc123")); - var markup = component.Markup; + var containerActionService = Substitute.For(); + + containerActionService.GetAvailabilityAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(withActions + ? new ContainerActionAvailabilityData + { + IsShown = true, + IsCurrent = true, + IsSupported = true, + OfferedActions = [ContainerActionType.StopContainer], + } + : new ContainerActionAvailabilityData()); + testContext.Services.AddSingleton(containerActionService); + testContext.SetRendererInfo(new RendererInfo("Server", true)); + + var component = testContext.Render(parameters => parameters.Add(page => page.DockerInstanceId, detail.DockerInstanceId) + .Add(page => page.ContainerId, ContainerId)); + List expected = ["Resource usage", "Available tag candidates", "Update findings", "Vulnerability findings", "Base image chain", "Scan history"]; + + if (withActions) + { + expected.Insert(0, "Container actions"); + + await component.WaitForAssertionAsync(() => Assert.IsNotEmpty(component.FindAll(".dug-detail__main .dug-panel"), "The page must render its panels"), TimeSpan.FromSeconds(2)).ConfigureAwait(false); + await component.WaitForAssertionAsync(() => Assert.Contains("Container actions", component.Find(".dug-detail__main").TextContent, "The actions panel must render once the availability is known"), TimeSpan.FromSeconds(2)).ConfigureAwait(false); + } + + var titles = component.FindAll(".dug-detail__main > .dug-panel .dug-panel__title").Select(title => title.TextContent.Trim()).ToList(); - Assert.Contains("dug-chart", markup, "The resource-history charts must render inside the responsive chart wrapper"); - Assert.Contains("summary-value", markup, "The current-usage summary cards must render their values"); + Assert.AreSequenceEqual(expected, titles, "The main column must show its panels in order"); + Assert.IsEmpty(component.FindAll(".section-description"), "No panel may carry a description line of the old style"); + + var leads = component.FindAll(".dug-detail__main .dug-panel__lead") + .Select(GetPanelTitle) + .Distinct() + .ToList(); + + Assert.IsTrue(leads.All(title => title is "Container actions" or "Available tag candidates"), "Only the actions and candidates panels may carry a lead line"); + } + } + + /// + /// Verify the findings panel shows the active count and the check time, or the count alone when never checked + /// + /// Whether the image was checked + /// Expected meta text + /// Task + [TestMethod] + [TestCategory("AC8")] + [DataRow(true, "6 active · checked 2026-03-14 10:30 UTC")] + [DataRow(false, "6 active")] + public async Task RuntimeContainerDetailVulnerabilityFindingsMetaText(bool isChecked, string expectedMeta) + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var detail = CreateDetail(); + + detail.VulnerabilityAssessment = CreateAssessment(); + detail.VulnerabilityAssessment.CheckedAtUtc = isChecked ? detail.VulnerabilityAssessment.CheckedAtUtc : null; + + var component = Render(testContext, detail); + var panel = FindPanel(component, "Vulnerability findings"); + + Assert.AreEqual(expectedMeta, panel.QuerySelector(".dug-panel__meta")?.TextContent.Trim(), "The panel must carry its meta text"); + Assert.Contains("dug-panel--flush", panel.ClassName ?? string.Empty, "The findings table must sit flush in its panel"); + } + } + + /// + /// Verify the details panel precedes the main column in the markup and the page header precedes both + /// + /// Task + [TestMethod] + [TestCategory("AC9")] + public async Task RuntimeContainerDetailDetailsPanelPrecedesMainColumn() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var component = Render(testContext, CreateDetail()); + var grid = component.Find(".dug-detail"); + var children = grid.Children.ToList(); + + Assert.HasCount(2, children, "The grid must hold the aside and the main column"); + Assert.AreEqual("ASIDE", children[0].TagName, "The details aside must come first"); + Assert.Contains("dug-detail__aside", children[0].ClassName ?? string.Empty, "The first child must be the aside column"); + Assert.Contains("dug-detail__main", children[1].ClassName ?? string.Empty, "The second child must be the main column"); + Assert.AreEqual("Details", children[0].QuerySelector(".dug-panel__title")?.TextContent.Trim(), "The aside must hold the details panel"); + Assert.IsLessThan(component.Markup.IndexOf("dug-detail__aside", StringComparison.Ordinal), component.Markup.IndexOf("dug-page-header", StringComparison.Ordinal), "The header must precede the details panel"); + } + } + + /// + /// Verify the base image chain shows its columns and the status in a chip of the shared tone + /// + /// Task + [TestMethod] + [TestCategory("AC11")] + public async Task RuntimeContainerDetailBaseImageChainShowsStatusChipInSharedTone() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var detail = CreateDetail(); + + detail.BaseImages = [ + new BaseImageRelationshipData + { + Depth = 1, + ImageReference = "docker.io/library/alpine:3.20", + SourceReference = "label", + VulnerabilityAssessment = new VulnerabilityAssessmentViewData + { + Status = "No findings", + Source = "Trivy", + ActiveFindingCount = 0, + }, + } + ]; + + var component = Render(testContext, detail); + var panel = FindPanel(component, "Base image chain"); + var headers = panel.QuerySelectorAll("thead th").Select(header => header.TextContent.Trim()).ToList(); + var cell = panel.QuerySelector("td[data-label='Vulnerabilities']"); + + Assert.AreSequenceEqual(["Depth", "Base image", "Source", "Vulnerabilities"], headers, "The chain table must show its columns"); + Assert.AreEqual("No findings", cell?.QuerySelector(".dug-chip")?.TextContent.Trim(), "The status must be a status chip"); + Assert.Contains("dug-chip--success", cell?.QuerySelector(".dug-chip")?.ClassName ?? string.Empty, "The chip must take its tone from the shared mapping"); + Assert.Contains("0 active · Trivy", Normalize(cell?.TextContent ?? string.Empty), "The cell must show the active count and the source"); } } @@ -77,55 +701,120 @@ public async Task RuntimeContainerDetailWithHistoryRendersResponsiveChartsAndUsa /// /// Task [TestMethod] - [TestCategory("AC3")] + [TestCategory("AC7")] public async Task RuntimeContainerDetailWithSelectionAndScanHistoryRendersUtcTimestampsAsync() { var testContext = BlazorTestContextFactory.Create(); await using (testContext) { - var viewService = Substitute.For(); - var tagSelectionService = Substitute.For(); - var instanceId = Guid.NewGuid(); - - viewService.GetRuntimeContainerDetailAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Task.FromResult(new RuntimeContainerDetailViewData - { - DockerInstanceId = instanceId, - ContainerId = "abc123", - ContainerName = "api", - DockerInstanceName = "local", - ImageReference = "docker.io/company/api:1.0.0", - ManualSelectionImage = "docker.io/company/api:2.0.0", - ManualSelectionAtUtc = new DateTimeOffset(2026, 11, 23, 23, 27, 0, TimeSpan.FromHours(2)), - ScanHistory = [ - new ScanHistoryItemData - { - Status = "Succeeded", - TriggerSource = "Manual", - StartedAtUtc = new DateTimeOffset(2026, 11, 23, 10, 5, 0, TimeSpan.FromHours(2)), - }, - ], - })); + var detail = CreateDetail(); - testContext.Services.AddSingleton(viewService); - testContext.Services.AddSingleton(tagSelectionService); - testContext.AddHiddenContainerActions(); + detail.ImageReference = "docker.io/company/api:1.0.0"; + detail.ManualSelectionImage = "docker.io/company/api:2.0.0"; + detail.ManualSelectionAtUtc = new DateTimeOffset(2026, 11, 23, 23, 27, 0, TimeSpan.FromHours(2)); + detail.ScanHistory = [ + new ScanHistoryItemData + { + Status = "Succeeded", + TriggerSource = "Manual", + StartedAtUtc = new DateTimeOffset(2026, 11, 23, 10, 5, 0, TimeSpan.FromHours(2)), + }, + ]; - var component = testContext.Render(parameters => parameters.Add(page => page.DockerInstanceId, instanceId) - .Add(page => page.ContainerId, "abc123")); + var component = Render(testContext, detail); var markup = component.Markup; - Assert.Contains("Saved 2026-11-23 21:27 UTC", markup, "The saved tag selection time must be shown in UTC"); + Assert.Contains("saved 2026-11-23 21:27 UTC", markup, "The saved tag selection time must be shown in UTC"); Assert.Contains("2026-11-23 08:05 UTC", markup, "The scan history start must be shown in UTC"); } } + #endregion // Methods + + #region Static methods + + /// + /// Collapse the white space of a text + /// + /// Text + /// Text with single spaces + private static string Normalize(string text) + { + return Regex.Replace(text, @"\s+", " ", RegexOptions.None, TimeSpan.FromSeconds(1)).Trim(); + } + /// - /// Create a resource usage point for the tests + /// Create a detail of a running container observed at a fixed time /// + /// Detail + private static RuntimeContainerDetailViewData CreateDetail() + { + return new RuntimeContainerDetailViewData + { + DockerInstanceId = Guid.Parse("11111111-2222-3333-4444-555555555555"), + ImageVersionId = Guid.NewGuid(), + ContainerId = ContainerId, + ContainerName = "api", + DockerInstanceName = "Production", + ImageReference = "ghcr.io/acme/api:1.0.0", + CurrentTag = "1.0.0", + RuntimeStatus = "Running", + RecordedAtUtc = _observedAtUtc, + UpdateStatus = "Not evaluated", + VulnerabilityAssessment = new VulnerabilityAssessmentViewData + { + Status = "No findings", + }, + }; + } + + /// + /// Create a vulnerability assessment with findings, checked at a fixed time + /// + /// Assessment + private static VulnerabilityAssessmentViewData CreateAssessment() + { + return new VulnerabilityAssessmentViewData + { + Status = "Findings detected", + Source = "Trivy", + ActiveFindingCount = 6, + FixableFindingCount = 4, + CheckedAtUtc = new DateTimeOffset(2026, 3, 14, 10, 30, 0, TimeSpan.Zero), + SeveritySummary = new VulnerabilitySeveritySummaryViewData + { + CriticalCount = 1, + HighCount = 2, + }, + }; + } + + /// + /// Create a tag candidate + /// + /// Tag + /// Whether the update assessment recommends the candidate + /// Whether the candidate is the stored preference + /// Candidate + private static TagCandidateViewData CreateCandidate(string tag, bool isRecommended = false, bool isSelected = false) + { + return new TagCandidateViewData + { + Tag = tag, + Digest = $"sha256:{tag.Replace(".", string.Empty, StringComparison.Ordinal)}aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + Reason = "Newer release", + IsRecommended = isRecommended, + IsSelected = isSelected, + }; + } + + /// + /// Create a resource usage point + /// + /// Minutes after the base time /// Resource usage point - private static ResourceUsagePointViewData CreateUsagePoint() + private static ResourceUsagePointViewData CreateUsagePoint(int minutes) { return new ResourceUsagePointViewData { @@ -134,9 +823,76 @@ private static ResourceUsagePointViewData CreateUsagePoint() MemoryLimitBytes = 1024 * 1024 * 1024, NetworkRxBytesPerSecond = 1024, NetworkTxBytesPerSecond = 512, - RecordedAtUtc = DateTimeOffset.UtcNow, + RecordedAtUtc = _observedAtUtc.AddMinutes(minutes), }; } - #endregion // Methods + /// + /// Render the page for a detail with hidden container actions + /// + /// Test context + /// Detail the view service answers + /// Rendered page + private static IRenderedComponent Render(BunitContext testContext, RuntimeContainerDetailViewData detail) + { + var viewService = Substitute.For(); + + viewService.GetRuntimeContainerDetailAsync(detail.DockerInstanceId, ContainerId, Arg.Any()) + .Returns(detail); + testContext.Services.AddSingleton(viewService); + testContext.Services.AddSingleton(Substitute.For()); + testContext.AddHiddenContainerActions(); + + return testContext.Render(parameters => parameters.Add(page => page.DockerInstanceId, detail.DockerInstanceId) + .Add(page => page.ContainerId, ContainerId)); + } + + /// + /// Find the panel with a title + /// + /// Rendered page + /// Panel title + /// Panel element + private static IElement FindPanel(IRenderedComponent component, string title) + { + return component.FindAll("section.dug-panel") + .Single(panel => panel.QuerySelector(".dug-panel__title")?.TextContent.Trim() == title); + } + + /// + /// Read the entries of the details panel + /// + /// Rendered page + /// Label and value element of each entry, in order + private static List<(string Label, IElement Value)> GetEntries(IRenderedComponent component) + { + return [ + .. component.FindAll(".dug-detail__aside dl .dug-detail-list__entry") + .Select(entry => (Label: entry.QuerySelector("dt")?.TextContent.Trim() ?? string.Empty, Value: entry.QuerySelector("dd") ?? entry)) + ]; + } + + /// + /// Find the button with the given text below an element + /// + /// Element to search + /// Button text + /// Button, or null when there is none + private static IElement? FindButton(IElement root, string text) + { + return root.QuerySelectorAll("button") + .FirstOrDefault(button => button.TextContent.Trim() == text); + } + + /// + /// Read the title of the panel an element sits in + /// + /// Element + /// Panel title + private static string? GetPanelTitle(IElement element) + { + return element.Closest("section.dug-panel")?.QuerySelector(".dug-panel__title")?.TextContent.Trim(); + } + + #endregion // Static methods } \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/RuntimeContainerDetailTests.cs b/src/Tests/DockerUpdateGuard.Tests/RuntimeContainerDetailTests.cs index b059ab75..dc8ad5b6 100644 --- a/src/Tests/DockerUpdateGuard.Tests/RuntimeContainerDetailTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/RuntimeContainerDetailTests.cs @@ -1,8 +1,13 @@ +using System.Reflection; + +using AngleSharp.Dom; + using Bunit; using DockerUpdateGuard.Components.Common; using DockerUpdateGuard.Components.Pages; using DockerUpdateGuard.Data.Entities; +using DockerUpdateGuard.Images.Interfaces; using DockerUpdateGuard.Portainer.Data; using DockerUpdateGuard.Portainer.Interfaces; using DockerUpdateGuard.Tests.Data; @@ -165,6 +170,10 @@ public async Task RuntimeContainerDetailWithFixableFindingsShowsFixableSummaryAn Assert.Contains("Updating may resolve up to 1 of 2 active findings", component.Markup, "The available tag candidates section must show the fixable update hint chip"); + + var hint = component.FindAll(".dug-chip").Single(chip => chip.TextContent.Contains("Updating may resolve", StringComparison.Ordinal)); + + Assert.Contains("dug-chip--info", hint.ClassName ?? string.Empty, "The fixable update hint must be a status chip in the info tone"); } } @@ -728,19 +737,19 @@ public async Task RuntimeContainerDetailAfterFailedActionShowsOutcomeAsErrorAsyn } /// - /// Verify the history shows each run status in a chip of its color + /// Verify the history shows each run status in a status chip of its tone /// /// Run status - /// Expected chip color class + /// Expected chip tone class /// Task [TestMethod] - [TestCategory("AC10")] - [DataRow("Succeeded", "mud-chip-color-success")] - [DataRow("Failed", "mud-chip-color-error")] - [DataRow("Running", "mud-chip-color-info")] - [DataRow("Requested", "mud-chip-color-warning")] - [DataRow("Cancelled", "mud-chip-color-default")] - public async Task RuntimeContainerDetailActionHistoryShowsStatusChipInItsColorAsync(string status, string expectedColorClass) + [TestCategory("AC11")] + [DataRow("Succeeded", "dug-chip--success")] + [DataRow("Failed", "dug-chip--danger")] + [DataRow("Running", "dug-chip--info")] + [DataRow("Requested", "dug-chip--warning")] + [DataRow("Cancelled", "dug-chip--neutral")] + public async Task RuntimeContainerDetailActionHistoryShowsStatusChipInItsToneAsync(string status, string expectedToneClass) { var viewService = Substitute.For(); var containerActionService = CreateContainerActionService(CreateAvailability("Running")); @@ -761,12 +770,12 @@ public async Task RuntimeContainerDetailActionHistoryShowsStatusChipInItsColorAs { var page = RenderActionPage(testContext); - await page.WaitForAssertionAsync(() => Assert.HasCount(1, FindActionSection(page).QuerySelectorAll("tbody tr .mud-chip"), "The history must list the run"), TimeSpan.FromSeconds(WaitSeconds)).ConfigureAwait(false); + await page.WaitForAssertionAsync(() => Assert.HasCount(1, FindActionSection(page).QuerySelectorAll("tbody tr .dug-chip"), "The history must list the run"), TimeSpan.FromSeconds(WaitSeconds)).ConfigureAwait(false); - var chip = FindActionSection(page).QuerySelector("tbody tr .mud-chip"); + var chip = FindActionSection(page).QuerySelector("tbody tr .dug-chip"); Assert.AreEqual(status, chip?.TextContent.Trim(), "The chip must show the run status"); - Assert.Contains(expectedColorClass, chip?.ClassName ?? string.Empty, $"Status {status} must be shown in the chip color '{expectedColorClass}'"); + Assert.Contains(expectedToneClass, chip?.ClassName ?? string.Empty, $"Status {status} must be shown in the chip tone '{expectedToneClass}'"); } } @@ -1556,16 +1565,17 @@ await tagSelectionService.Received(1) } /// - /// Verify the scan history table shows the scan status in a chip of its color + /// Verify the scan history table shows the scan status as the status indicator of its tone /// /// Scan status - /// Expected chip color class + /// Expected indicator tone class /// Task [TestMethod] - [TestCategory("AC4")] - [DataRow("Succeeded", "mud-chip-color-success")] - [DataRow("Partial", "mud-chip-color-warning")] - public async Task RuntimeContainerDetailScanHistoryChipShowsStatusColorAsync(string status, string expectedColorClass) + [TestCategory("AC8")] + [DataRow("Succeeded", "dug-status--success")] + [DataRow("Partial", "dug-status--warning")] + [DataRow("Failed", "dug-status--danger")] + public async Task RuntimeContainerDetailScanHistoryShowsStatusIndicatorAsync(string status, string expectedToneClass) { var viewService = Substitute.For(); var testContext = CreateLoadContext(viewService, new TestLogger()); @@ -1587,10 +1597,294 @@ public async Task RuntimeContainerDetailScanHistoryChipShowsStatusColorAsync(str var page = RenderLoadPage(testContext, LoadContainerId); - await ScanStatusChipAssert.AssertChipAsync(page, - root => ScanStatusChipAssert.FindSectionCellChips(root, "Scan history", "Status"), - status, - expectedColorClass).ConfigureAwait(false); + await ScanStatusChipAssert.AssertChipAsync(page, FindScanHistoryIndicators, status, expectedToneClass).ConfigureAwait(false); + + Assert.IsEmpty(FindPanel(page, "Scan history").QuerySelectorAll("td[data-label='Status'] .mud-chip"), "The scan status must not be a chip"); + } + } + + /// + /// Verify an unknown container and a failed load keep the page header with the breadcrumb link and the generic title only + /// + /// Scenario, NotFound or LoadFailure + /// Task + [TestMethod] + [TestCategory("AC2")] + [DataRow("NotFound")] + [DataRow("LoadFailure")] + public async Task RuntimeContainerDetailWithoutDetailShowsGenericHeader(string scenario) + { + var viewService = Substitute.For(); + var testContext = CreateLoadContext(viewService, new TestLogger()); + + await using (testContext) + { + viewService.GetRuntimeContainerDetailAsync(_loadInstanceId, LoadContainerId, Arg.Any()) + .Returns(scenario == "NotFound" + ? Task.FromResult(null) + : Task.FromException(new InvalidOperationException("secret text"))); + + var page = RenderLoadPage(testContext, LoadContainerId); + + if (scenario == "NotFound") + { + await DetailPageAssert.AssertNotFoundAsync(page, "This container is not known on this Docker instance.", "Back to Runtime Containers", "/runtime-containers").ConfigureAwait(false); + } + else + { + await DetailPageAssert.AssertLoadErrorAsync(page, "Loading the container failed: unexpected error", "secret text").ConfigureAwait(false); + } + + var link = page.Find(".dug-page-header__breadcrumb a"); + + Assert.AreEqual("Runtime Container Detail", page.Find("h1").TextContent.Trim(), "The header must show the generic title"); + Assert.AreEqual("Runtime Containers", link.TextContent.Trim(), "The breadcrumb must show the list link"); + Assert.AreEqual("/runtime-containers", link.GetAttribute("href"), "The breadcrumb link must point to the list"); + Assert.IsEmpty(page.FindAll(".dug-page-header .dug-chip"), "The header must show no chips"); + Assert.IsEmpty(page.FindAll(".dug-page-header__description"), "The header must show no description line"); + Assert.IsEmpty(page.FindAll(".dug-detail"), "The page must show no columns"); + } + } + + /// + /// Verify the rescan runs the refresh of the container's image version, is disabled while it runs and reloads the container afterwards + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task RuntimeContainerDetailRescanRefreshesImageVersionAndReloadsAsync() + { + var viewService = Substitute.For(); + var enrichmentService = Substitute.For(); + var gate = new TaskCompletionSource(); + var imageVersionId = Guid.NewGuid(); + var testContext = CreateLoadContext(viewService, new TestLogger(), enrichmentService); + + await using (testContext) + { + enrichmentService.RefreshImageVersionAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(gate.Task); + viewService.GetRuntimeContainerDetailAsync(_loadInstanceId, LoadContainerId, Arg.Any()) + .Returns(CreateRescanDetail(imageVersionId, "Findings detected")); + + var page = RenderLoadPage(testContext, LoadContainerId); + + await DetailPageAssert.AssertLoadedAsync(page, "load-api", "This container is not known on this Docker instance.").ConfigureAwait(false); + + Assert.Contains("Findings detected", FindVulnerabilitiesEntry(page).TextContent, "The entry must show the assessment before the rescan"); + Assert.AreEqual("Rescan vulnerabilities", FindButton(page, "Rescan").GetAttribute("aria-label"), "The button must be announced as 'Rescan vulnerabilities'"); + + viewService.GetRuntimeContainerDetailAsync(_loadInstanceId, LoadContainerId, Arg.Any()) + .Returns(CreateRescanDetail(imageVersionId, "No findings")); + + var click = FindButton(page, "Rescan").ClickAsync(); + + await page.WaitForAssertionAsync(() => Assert.IsTrue(FindButton(page, "Rescan").HasAttribute("disabled"), "The button must be disabled while the rescan runs"), TimeSpan.FromSeconds(WaitSeconds)).ConfigureAwait(false); + + gate.SetResult(); + + await click.ConfigureAwait(false); + await enrichmentService.Received(1).RefreshImageVersionAsync(imageVersionId, ScanTriggerSource.Manual, Arg.Any()).ConfigureAwait(false); + await page.WaitForAssertionAsync(() => Assert.Contains("No findings", FindVulnerabilitiesEntry(page).TextContent, "The entry must show the reloaded assessment"), TimeSpan.FromSeconds(WaitSeconds)).ConfigureAwait(false); + await viewService.Received(2).GetRuntimeContainerDetailAsync(_loadInstanceId, LoadContainerId, Arg.Any()).ConfigureAwait(false); + Assert.IsFalse(FindButton(page, "Rescan").HasAttribute("disabled"), "The button must be enabled again afterwards"); + } + } + + /// + /// Verify a failed rescan shows a fixed reason below the vulnerabilities entry, logs the action, keeps the page usable and can be started again + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task RuntimeContainerDetailFailedRescanShowsFixedReasonAndLogsAsync() + { + var viewService = Substitute.For(); + var enrichmentService = Substitute.For(); + var controlLogger = new TestLogger(); + var exception = new InvalidOperationException("connection to db.internal.test:5432 refused"); + var testContext = CreateLoadContext(viewService, new TestLogger(), enrichmentService, controlLogger); + + await using (testContext) + { + enrichmentService.RefreshImageVersionAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.FromException(exception)); + viewService.GetRuntimeContainerDetailAsync(_loadInstanceId, LoadContainerId, Arg.Any()) + .Returns(CreateRescanDetail(Guid.NewGuid(), "Findings detected")); + + var page = RenderLoadPage(testContext, LoadContainerId); + + await DetailPageAssert.AssertLoadedAsync(page, "load-api", "This container is not known on this Docker instance.").ConfigureAwait(false); + await FindButton(page, "Rescan").ClickAsync().ConfigureAwait(false); + + UserActionFailureAssert.AssertShown(page.Markup, "Vulnerability rescan failed: unexpected error", "db.internal.test", "refused"); + UserActionFailureAssert.AssertLogged(controlLogger, "VulnerabilityRescan", exception); + Assert.Contains("Vulnerability rescan failed: unexpected error", FindVulnerabilitiesEntry(page).QuerySelector(".vulnerability-rescan-control__details")?.TextContent ?? string.Empty, "The error must show below the assessment inside the vulnerabilities entry"); + Assert.Contains("load-api", page.Markup, "The page must stay usable"); + Assert.IsFalse(FindButton(page, "Rescan").HasAttribute("disabled"), "The rescan must be startable again"); + + await FindButton(page, "Rescan").ClickAsync().ConfigureAwait(false); + await enrichmentService.Received(2).RefreshImageVersionAsync(Arg.Any(), ScanTriggerSource.Manual, Arg.Any()).ConfigureAwait(false); + await viewService.Received(1).GetRuntimeContainerDetailAsync(_loadInstanceId, LoadContainerId, Arg.Any()).ConfigureAwait(false); + } + } + + /// + /// Verify a failing reload after the rescan shows the rescan's prefix and keeps the shown detail + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task RuntimeContainerDetailRescanReloadFailureShowsRescanPrefixAsync() + { + var viewService = Substitute.For(); + var enrichmentService = Substitute.For(); + var controlLogger = new TestLogger(); + var exception = new InvalidOperationException("secret text"); + var testContext = CreateLoadContext(viewService, new TestLogger(), enrichmentService, controlLogger); + + await using (testContext) + { + viewService.GetRuntimeContainerDetailAsync(_loadInstanceId, LoadContainerId, Arg.Any()) + .Returns(CreateRescanDetail(Guid.NewGuid(), "Findings detected")); + + var page = RenderLoadPage(testContext, LoadContainerId); + + await DetailPageAssert.AssertLoadedAsync(page, "load-api", "This container is not known on this Docker instance.").ConfigureAwait(false); + + viewService.GetRuntimeContainerDetailAsync(_loadInstanceId, LoadContainerId, Arg.Any()) + .Returns(Task.FromException(exception)); + + await FindButton(page, "Rescan").ClickAsync().ConfigureAwait(false); + + UserActionFailureAssert.AssertShown(page.Markup, "Vulnerability rescan failed: unexpected error", "secret text"); + Assert.DoesNotContain("Loading the container failed", page.Markup, "The reload failure must carry the rescan's prefix"); + Assert.Contains("load-api", page.Markup, "The shown detail must stay"); + DetailPageAssert.AssertLoadLoggedOnce(controlLogger, "VulnerabilityRescan", exception); + } + } + + /// + /// Verify the error of a rescan of an earlier route is not shown on a new route + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task RuntimeContainerDetailRescanErrorIsNotShownAfterRouteChangeAsync() + { + var viewService = CreateRouteViewService(); + var containerActionService = CreateRouteActionService(CreateAvailability("Running"), CreateAvailability("Running")); + var enrichmentService = Substitute.For(); + var testContext = CreateRouteContext(viewService, containerActionService, Substitute.For(), new TestLogger(), null, enrichmentService, new TestLogger()); + + await using (testContext) + { + enrichmentService.RefreshImageVersionAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.FromException(new InvalidOperationException("secret text"))); + + var page = RenderRoutePage(testContext, RouteContainerA); + + await page.WaitForAssertionAsync(() => Assert.Contains(RouteNameA, page.Markup, "The first route must load"), TimeSpan.FromSeconds(WaitSeconds)).ConfigureAwait(false); + await FindButton(page, "Rescan").ClickAsync().ConfigureAwait(false); + + Assert.Contains("Vulnerability rescan failed: unexpected error", page.Markup, "The error must show on its own route"); + + MoveRoute(page, RouteContainerB); + + await page.WaitForAssertionAsync(() => Assert.Contains(RouteNameB, page.Markup, "The second route must load"), TimeSpan.FromSeconds(WaitSeconds)).ConfigureAwait(false); + + Assert.DoesNotContain("Vulnerability rescan failed", page.Markup, "The error of the earlier route must not show on the new one"); + } + } + + /// + /// Verify the page defines no status color helper of its own + /// + [TestMethod] + [TestCategory("AC11")] + public void RuntimeContainerDetailDefinesNoStatusColorHelper() + { + var helpers = typeof(RuntimeContainerDetail).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .Where(method => method.ReturnType == typeof(Color)) + .Select(method => method.Name) + .ToList(); + + Assert.IsEmpty(helpers, $"The page must take every status tone from the shared mapping, but defines: {string.Join(", ", helpers)}"); + } + + /// + /// Create the detail of the rescan tests: a container with an image version and an assessment status + /// + /// Image version identifier + /// Vulnerability assessment status + /// Detail + private static RuntimeContainerDetailViewData CreateRescanDetail(Guid imageVersionId, string assessmentStatus) + { + var detail = CreateLoadDetail(LoadContainerId, "load-api"); + + detail.ImageVersionId = imageVersionId; + detail.VulnerabilityAssessment = new VulnerabilityAssessmentViewData + { + Status = assessmentStatus, + Source = "Trivy", + ActiveFindingCount = assessmentStatus == "No findings" ? 0 : 2, + CheckedAtUtc = new DateTimeOffset(2026, 11, 23, 21, 27, 0, TimeSpan.Zero), + }; + + return detail; + } + + /// + /// Find the Vulnerabilities entry of the details panel + /// + /// Rendered page + /// Entry element + private static IElement FindVulnerabilitiesEntry(IRenderedComponent page) + { + return page.FindAll(".dug-detail-list__entry") + .Single(entry => entry.QuerySelector("dt")?.TextContent.Trim() == "Vulnerabilities"); + } + + /// + /// Find a panel by its title + /// + /// Rendered page + /// Panel title + /// Panel element + private static IElement FindPanel(IRenderedComponent page, string title) + { + return page.FindAll("section.dug-panel") + .Single(panel => panel.QuerySelector(".dug-panel__title")?.TextContent.Trim() == title); + } + + /// + /// Find the scan status indicators of the scan history table + /// + /// Rendered page + /// Indicators + private static IEnumerable FindScanHistoryIndicators(IRenderedComponent page) + { + return page.FindAll("section.dug-panel") + .Where(panel => panel.QuerySelector(".dug-panel__title")?.TextContent.Trim() == "Scan history") + .SelectMany(panel => panel.QuerySelectorAll("td[data-label='Status'] .dug-status")); + } + + /// + /// Register the services of the rescan before the test context is first used + /// + /// Test context + /// Vulnerability enrichment service; null registers none + /// Logger of the rescan control; null registers none + private static void RegisterRescanServices(BunitContext testContext, IVulnerabilityEnrichmentService? enrichmentService, TestLogger? controlLogger) + { + if (enrichmentService is not null) + { + testContext.Services.AddSingleton(enrichmentService); + } + + if (controlLogger is not null) + { + testContext.Services.AddSingleton>(controlLogger); } } @@ -1750,7 +2044,7 @@ private static IDialogService CreateFailingDialogService(Exception exception) /// True when the section is rendered private static bool HasActionSection(IRenderedComponent page) { - return page.FindAll(".section-paper h5") + return page.FindAll(".dug-panel .dug-panel__title") .Any(heading => heading.TextContent.Trim() == "Container actions"); } @@ -1880,8 +2174,8 @@ .. page.FindAll("button") /// Section element private static AngleSharp.Dom.IElement FindActionSection(IRenderedComponent page) { - return page.FindAll(".section-paper") - .Single(section => section.QuerySelector("h5")?.TextContent.Trim() == "Container actions"); + return page.FindAll("section.dug-panel") + .Single(section => section.QuerySelector("h2")?.TextContent.Trim() == "Container actions"); } /// @@ -1929,14 +2223,20 @@ await page.WaitForAssertionAsync(() => Assert.ContainsSingle(button => button.Te /// /// View service substitute /// Logger registered for the page + /// Vulnerability enrichment service of the rescan; null registers none + /// Logger registered for the rescan control; null keeps the default /// Test context - private static BunitContext CreateLoadContext(IApplicationViewService viewService, TestLogger logger) + private static BunitContext CreateLoadContext(IApplicationViewService viewService, + TestLogger logger, + IVulnerabilityEnrichmentService? enrichmentService = null, + TestLogger? controlLogger = null) { var testContext = BlazorTestContextFactory.Create(); testContext.Services.AddSingleton(viewService); testContext.Services.AddSingleton(Substitute.For()); testContext.Services.AddSingleton>(logger); + RegisterRescanServices(testContext, enrichmentService, controlLogger); testContext.AddHiddenContainerActions(); return testContext; @@ -2052,15 +2352,21 @@ private static RuntimeContainerDetailViewData CreateRouteDetail(string container /// Tag selection service substitute /// Logger registered for the page /// Dialog service replacing MudBlazor's; null keeps MudBlazor's + /// Vulnerability enrichment service of the rescan; null registers none + /// Logger registered for the rescan control; null keeps the default /// Test context private static BunitContext CreateRouteContext(IApplicationViewService viewService, IContainerActionService containerActionService, IRuntimeContainerTagSelectionService tagSelectionService, TestLogger logger, - IDialogService? dialogService = null) + IDialogService? dialogService = null, + IVulnerabilityEnrichmentService? enrichmentService = null, + TestLogger? controlLogger = null) { var testContext = BlazorTestContextFactory.Create(); + RegisterRescanServices(testContext, enrichmentService, controlLogger); + testContext.Services.AddSingleton(viewService); testContext.Services.AddSingleton(tagSelectionService); testContext.Services.AddSingleton(containerActionService); From bd2bff366f4e0ac286e40803f6b1a608846a9421 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 21:31:41 +0000 Subject: [PATCH 15/26] Rewrite the runtime container detail page with a details column Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_018g33AVnD3UUpZykmcVAdbH --- docs/ARCHITECTURE.md | 8 +- docs/areas/README.md | 1 + docs/areas/detail-pages.md | 107 +++ docs/areas/vulnerabilities.md | 2 +- docs/areas/web-ui.md | 17 +- .../log.md | 1 + .../Pages/RuntimeContainerDetail.razor | 807 ++++++++---------- .../Pages/RuntimeContainerDetail.razor.cs | 80 +- src/DockerUpdateGuard/wwwroot/app.css | 145 ++++ 9 files changed, 684 insertions(+), 484 deletions(-) create mode 100644 docs/areas/detail-pages.md diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index e5e771af..69c2804f 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -433,9 +433,13 @@ Pages, routes and what each page shows or triggers are specified in the component tree, at the cost of `ApplicationViewService` being a fairly wide surface (one method per page/section). - **`Components\Common`** holds cross-page building blocks: loading - skeletons and the vulnerability widgets shared between the + skeletons (the detail page skeleton among them) and the vulnerability + widgets shared between the Vulnerabilities page and image/container detail pages, the - `ContainerActionConfirmation` dialog, and the status chip, scan status + `ContainerActionConfirmation` dialog, the resource history chart (SVG paths + from one path builder shared with the Runtime Containers list, + [decision 0083](decisions/0083-resource-histories-are-drawn-as-svg-sparklines-from-one-shared-path-builder.md)), + and the status chip, scan status indicator, severity bar, page header and section panel, which take their tone from `UI\StatusToneFormatter` ([decision 0079](decisions/0079-statuses-map-to-tones-in-one-mapping-beside-the-chip-colors-of-unconverted-pages.md)). diff --git a/docs/areas/README.md b/docs/areas/README.md index 2dbc11a7..916a7eeb 100644 --- a/docs/areas/README.md +++ b/docs/areas/README.md @@ -40,5 +40,6 @@ operator or another component can rely on — formats, limits, error behavior, g | [Container actions](container-actions.md) | Portainer endpoints and authentication, insecure HTTP opt-in, start/stop/restart of containers, when they are offered, and their recorded runs | Container discovery (Docker instances) | | [Scan engine](scan-engine.md) | Background jobs and their intervals, dynamic own-image interval, overlap rules, scan runs, crash recovery, retention and cleanup, single-instance assumption | What a scan evaluates (the feature areas) | | [Web UI](web-ui.md) | Pages and routes, what each page shows and triggers, dashboard refresh, error and not-found pages, theme | How the shown values are computed (the feature areas) | +| [Detail pages](detail-pages.md) | Layout and contents of the detail pages: header, details column, panels in order, resource history charts | Routes, actions table, shared display and errors (Web UI); how values are computed (the feature areas) | | [Telemetry](telemetry.md) | Logs, traces and metrics, OTLP export, activity and instrument names, inventory gauges, what never reaches telemetry | Deployment of the observability stack (`INSTALL.md`) | diff --git a/docs/areas/detail-pages.md b/docs/areas/detail-pages.md new file mode 100644 index 00000000..326a3a47 --- /dev/null +++ b/docs/areas/detail-pages.md @@ -0,0 +1,107 @@ +# Detail pages + +## Scope + +The layout and contents of the detail pages, so far the Runtime Container detail: its header, the details column, the +panels of the main column in order and the resource history charts. Operators rely on it to find a container's state +at a glance. + +## Behavior + +### Runtime Container detail header + +- The header shows the breadcrumb `Runtime Containers / {container name}`, the first part linking to + `/runtime-containers`, and the container name as the page title. Beside the title stand two status chips: the + runtime status and the update state, the latter as `{state} · {available version}` when an available version is + known and as the state alone otherwise. Both take their tone from the shared mapping + ([Web UI](web-ui.md#shared-display)), so a status without a tone, such as `Exited` or `Not evaluated`, is neutral. +- Under the title, the line `{instance name} · observed {date and time}` links the instance name to its page. + The browser tab reads `Runtime Container Detail`. +- A page whose container is unknown or whose load failed shows the title `Runtime Container Detail` and the + breadcrumb link `Runtime Containers` only, with the note or alert of [Web UI](web-ui.md#shared-behavior), no chips, + no description line and no columns. While loading, the page shows a skeleton of the header and of both columns. + +### Layout + +- Below 960 px the page is one column, the *Details* panel directly after the header and before every other panel. + From 960 px the main column stands left and the *Details* panel right, 320 px wide and top-aligned, 24 px apart; the + main column is at least 560 px wide. In the markup the *Details* panel always precedes the main column. Both columns + may shrink below their content, so wide values wrap instead of overflowing the page. +- Below 960 px the tables show as cards and the three usage cells stack. + +### Details panel + +The panel lists these entries in order, each with a muted label, a semibold value and muted lines, separated by +hairlines: + +1. *Runtime image*: the image reference; for an alias tag `{tag} · {resolved version}`; the short digest + `@sha256:…` in a monospace font, with the full digest as its tooltip. +2. *Compose project and service*, only when the project, stack or service is known: + `{project, else stack, else Standalone} · {service, else No service label}`. +3. *Observed own image*: a link to the own image, else `No linked own image`. +4. *Update assessment*: the update state like the header chip, and the update message when there is one. +5. *Base runtime*, only with a base runtime alert: the chip `Runtime warning` (warning tone) for a container linked to + an own image, else `Runtime hint` (info tone), then the summary and the details when present. +6. *Vulnerabilities*: the vulnerability assessment as [Vulnerabilities](vulnerabilities.md) defines it, with one + `Checked {date and time}` line when the image was checked and none otherwise, and the text button `Rescan`, + announced as `Rescan vulnerabilities`. A rescan refreshes the container's current image version and reloads the page; + a failure shows `Vulnerability rescan failed: {reason}` under the assessment. +7. *Base image vulnerabilities*, only when base images have active findings: the chip `Findings detected` in the + warning tone and the summary. + +### Main column + +The panels follow in this order, without description lines except where stated: + +1. *Container actions*, only when [Web UI](web-ui.md#container-actions-section) shows it, with its description as a + muted line. +2. *Resource usage*, meta text `Current value and the last 24 hours`: three cells `CPU`, `Memory` and `Network`, each + with the current value (`n/a` without a current sample) in 24 px type and, with samples, a chart. Without samples + the cells show no chart and the panel says `No resource history is currently stored for this container.` +3. *Available tag candidates*: a muted line `Manual tag preference: none.` or `Manual tag preference: {image}, saved + {date and time}.` followed by `Selecting a tag stores a preference; it does not change or redeploy the container.`; + `Clear selection` in the panel header with a stored preference; the info chip `Updating may resolve up to {n} of + {m} active findings` when updating can fix findings; the table `Tag`, `Digest`, `Reason`, `Published` (`—` when + unknown) and `Action`. A candidate the update assessment recommends carries the chip `Recommended` (success + tone), the stored preference the chip `Selected` (info tone) and the button `Saved` instead of `Select`. +4. *Update findings*. +5. *Vulnerability findings*, meta text `{n} active · checked {date and time}`, or `{n} active` when never checked, with + the findings table flush in the panel. +6. *Base image chain* with `Depth`, `Base image`, `Source` and `Vulnerabilities` (status chip, severity chips and + `{n} active · {source}`). +7. *Scan history*, the scans of the 20 most recent snapshots, the status as the scan status indicator. + +Empty candidates, update findings and base image chain show the empty-state texts of [Web UI](web-ui.md). + +### Resource history charts + +- A chart shows the stored samples of the last 24 hours, at most 48, oldest at the left, 72 px high and without axes. + CPU and memory draw a line over an area fill, network two lines (received, sent) on one scale. Each chart is + announced as an image named `CPU history, last 24 hours`, `Memory history, last 24 hours` or `Network history, last + 24 hours`. +- One sample, or samples that are all equal, draw a flat line at mid-height; the same holds for the sparklines of the + Runtime Containers list, whose series keep their own scales. The stroke is 1.5 px wide whatever the chart's width, and + the colors come from the chart tokens of both themes. +- Under each chart one muted line gives the range of the period: `Min {cpu} · max {cpu}`, `Min {memory} · max {memory}` + (memory used, without the limit) and `Max {received} ↓ / {sent} ↑`. + +## Limits and errors + +- Saving or clearing a tag preference and the container actions report failures as [Web UI](web-ui.md) states; a + result or error of an earlier route is not shown on a new one. +- The page shows the 20 most recent scan snapshots and the 20 most recent action runs, and at most 48 samples per chart. + +## Related decisions + +- [`decisions/0083-resource-histories-are-drawn-as-svg-sparklines-from-one-shared-path-builder.md`](../decisions/0083-resource-histories-are-drawn-as-svg-sparklines-from-one-shared-path-builder.md) + — the charts and the list's sparklines share one path builder. +- [`decisions/0059-a-detail-page-shows-a-missing-record-or-a-failed-load-inline.md`](../decisions/0059-a-detail-page-shows-a-missing-record-or-a-failed-load-inline.md) + — a missing record or a failed load shows inline under the page header. + +## Not here + +- Routes, the actions table, shared display and error behavior in [Web UI](web-ui.md). +- How update states, tag candidates, vulnerability values and resource values are computed in + [Update detection](update-detection.md), [Vulnerabilities](vulnerabilities.md) and + [Docker instances](docker-instances.md). +- The other detail pages, which join this area when they are converted. diff --git a/docs/areas/vulnerabilities.md b/docs/areas/vulnerabilities.md index 059b7a52..6c4f08eb 100644 --- a/docs/areas/vulnerabilities.md +++ b/docs/areas/vulnerabilities.md @@ -45,7 +45,7 @@ All keys live under `DockerUpdateGuard:Vulnerabilities`: - A full refresh runs on the schedule `DockerUpdateGuard:Scanning:VulnerabilityRefreshIntervalMinutes` (default `180`, range `1`–`10080`, see [Scan engine](scan-engine.md)) and can be started manually from the scan history page. - A **manual rescan** of a single image version can be started from the observed image, own image and runtime - container lists. It follows the same rules for that one image version. An image version that does not exist is + container lists and from the runtime container detail page. It follows the same rules for that one image version. An image version that does not exist is ignored without a scan run. - Every refresh is recorded as one scan run of type *vulnerability* with trigger *scheduled* or *manual*, also when it covers no image version. diff --git a/docs/areas/web-ui.md b/docs/areas/web-ui.md index 646b647b..1ef07170 100644 --- a/docs/areas/web-ui.md +++ b/docs/areas/web-ui.md @@ -37,7 +37,7 @@ to read the state the other areas compute and to start manual scans; it computes - Timestamps are shown in UTC as `yyyy-MM-dd HH:mm UTC`, the same for every browser and independent of the time zone and culture of the server process. The resource chart labels are UTC too: the first and the last label read `MM-dd HH:mm UTC`, the visible labels between them `HH:mm`. -- The scan status chips of the scan history, observed image, My Images, runtime container and image detail +- The scan status chips of the scan history, observed image, My Images and image detail pages share one color mapping: `Succeeded` green, `Partial` and `Pending` orange, `Failed` red, `Running` blue; any other value, such as `NotSet` or `NotScanned`, stays neutral. The chip text is the status name. - While a page loads its data it shows placeholder skeletons; a list without data shows an explanatory empty state. A @@ -55,7 +55,7 @@ to read the state the other areas compute and to start manual scans; it computes ### Shared display - The shared components show a status as a chip in the tone of its text, compared ignoring letter case: green for - `Succeeded`, `Up to date` and `No findings`; orange for `Partial`, `Update available`, `Paused` and `Restarting`; + `Succeeded`, `Up to date` and `No findings`; orange for `Partial`, `Requested`, `Update available`, `Paused` and `Restarting`; red for `Failed`; blue for `Running` and `Manual review required`; every other text, an unknown, empty or missing one included, is neutral. A status chip takes its colors from the theme's chip color pairs; the scan status indicator shows a dot in the tone's color beside the status text, which alone carries the meaning. @@ -81,7 +81,7 @@ to read the state the other areas compute and to start manual scans; it computes | `/observed-images` | Observed Images | The registration form and the manually registered images with latest scan, active update findings, derived-runtime hint and vulnerability status | | `/observed-images/{id}` | Observed Image detail | One observed image: reference, latest scan, whether it is an own or a manual image, derived-runtime hint, running containers (own images only), base image chain, vulnerability findings and update findings with tag candidates; no scan history | | `/runtime-containers` | Runtime Containers | A panel `Container inventory` with the meta text `{n} containers on {m} Docker instances`; seven columns: container (name, tag with the version an alias resolves to, link to the own image), instance, CPU, memory and network usage with a trend of up to the 12 latest samples, update state with the available version, and vulnerabilities (chip, count line, last check, rescan, base image warning); [0082](../decisions/0082-the-runtime-container-list-names-the-highest-active-severity-and-keeps-a-failed-checks-status-beside-it.md) | -| `/runtime-containers/{instanceId}/{containerId}` | Runtime Container detail | One container: image and digest, Compose project, linked own image, update state and message, derived-runtime hint, base image chain, resource usage history, manual tag preference, available tag candidates, update findings, vulnerability findings and the scans of its 20 most recent snapshots; for a container of a Docker instance with Portainer enabled, the *Container actions* section with the 20 most recent action runs of the container | +| `/runtime-containers/{instanceId}/{containerId}` | Runtime Container detail | One container, laid out as [Detail pages](detail-pages.md) describes; with Portainer enabled for its Docker instance, a *Container actions* panel with the 20 most recent action runs of the container | | `/docker-instances` | Docker Instances | Configured Docker instances with endpoint, connection kind, latest runtime scan status and time, current resource usage and number of containers; with exactly one instance its current usage and usage history are shown on this page directly | | `/docker-instances/{id}` | Docker Instance detail | The containers currently observed on one instance with linked own image and resource usage | | `/base-images` | Shared Base Images | Base images used by two or more enabled images or containers, with the images built on them, the containers and number of enabled observed images that use them, and their vulnerability status | @@ -107,7 +107,7 @@ to read the state the other areas compute and to start manual scans; it computes | Register and scan | Observed Images | Registers an image from name (trimmed), image reference and optional description ([Image catalog](image-catalog.md)), scans it immediately as a manual observed-image scan and opens its detail page; a reference already tracked as an enabled own image is rejected with an `Open own image` link to that image and starts no scan | | Check image updates | Runtime Containers | Runs a manual runtime container scan of all enabled Docker instances | | Refresh vulnerabilities | Scan History, shown only when vulnerability scanning is enabled | Runs a manual vulnerability refresh of all live images; the page also shows when the next scheduled refresh is expected | -| Rescan (per image) | Observed Images, My Images, Runtime Containers | Runs a manual vulnerability refresh of that one image version; with it the time of the last check or "Never scanned"; the button is announced as `Rescan vulnerabilities` | +| Rescan (per image) | Observed Images, My Images, Runtime Containers, Runtime Container detail (text button `Rescan`, without its own last-check line) | Runs a manual vulnerability refresh of that one image version; with it the time of the last check or "Never scanned"; the button is announced as `Rescan vulnerabilities` | | Select / Clear selection | Runtime Container detail | Stores or removes a manual tag preference for that container ([Update detection](update-detection.md)); it does not change or redeploy the container | | Start / Stop / Restart | Runtime Container detail, *Container actions* section | Starts, stops or restarts that container through Portainer after a confirmation, and records the action as an action run ([Container actions](container-actions.md)) | @@ -129,15 +129,15 @@ to read the state the other areas compute and to start manual scans; it computes ### Container actions section -- The runtime container detail page shows a *Container actions* section directly after the container summary when +- The runtime container detail page shows a *Container actions* panel, the first of the main column ([Detail pages](detail-pages.md)), when [Container actions](container-actions.md#container-availability) says it is shown. The page asks only once it is interactive, never while the server renders it first (the check contacts Portainer), and again when the route changes to another container; until the answer arrives, and for a Docker instance that is disabled or has Portainer disabled, no section appears. If the question itself fails, the section stays hidden and the failure is logged as user action `LoadContainerActions`. - The section holds, in this order: - 1. the heading `Container actions` with the description `Start, stop or restart this container through Portainer. - Every action asks for confirmation and is recorded.`; + 1. the panel title `Container actions` with the description `Start, stop or restart this container through Portainer. + Every action asks for confirmation and is recorded.` as a muted line; 2. the note `Runtime status as of the last runtime scan (