diff --git a/devlog/_plan/260909_usage_custom_range_disclosure/000_plan.md b/devlog/_plan/260909_usage_custom_range_disclosure/000_plan.md new file mode 100644 index 0000000000..50af45c95c --- /dev/null +++ b/devlog/_plan/260909_usage_custom_range_disclosure/000_plan.md @@ -0,0 +1,55 @@ +# Usage custom date range — manual-query disclosure + +Triggered by a maintainer browser comment on `/#usage`: the custom date range block should be a +dropdown (manual lookup) by default, with the fields below it, and the current layout is visually +wrong — control heights do not line up. Scope is the usage page filter area only. + +## Design read (cxc-dev-uiux-design) + +Reading this as: a dense local analytics page for a single operator who reads the presets almost +every time and reaches for an explicit interval rarely, in the quiet utilitarian language the rest +of the dashboard already speaks. Tokens come from `gui/src/styles.css`; nothing new is invented. + +``` +DESIGN_VARIANCE: 3 +MOTION_INTENSITY: 1 +Product density profile: D5 +Reasoning: dashboard/admin surface for repeated operator work — the expressive default kit is +domain-gated off, so the work is restraint, alignment and disclosure rather than decoration. +``` + +Do's: one obvious path (presets), expert control demoted behind a labelled disclosure, every +control on one height, left-aligned so the block reads with the page it belongs to. +Don'ts: no second full-width flex-end row, no decorative motion, no hidden applied state. + +## Problem + +`Usage.tsx` renders the custom-range `
` unconditionally under the page subtitle and reuses +`.usage-filters`, which is `justify-content: flex-end`. Three consequences: + +1. Two empty `datetime-local` fields are the second thing on the page even though the answer the + page exists to give is already rendered from a preset (UX-LAZY-01: an expert fork at top level). +2. The row is pushed to the right edge with a wide empty gutter, and the help caption underneath + starts at the left edge, so the two halves do not read as one control. +3. `align-items: center` centers a label+input stack (≈57px) against `btn-sm` buttons (≈26px), so + Apply/Clear float in the middle of the fields instead of sitting on their baseline. + +## Work phases + +1. wp1: collapse the block behind a closed-by-default disclosure trigger, render the fields in a + bottom-aligned grid panel on one control height, keep the applied interval visible while + collapsed, and update `gui/tests/usage-custom-range.test.tsx`. +2. wp2: publish as a PR against `dev` with a GUI screenshot and merge on exact-head CI; depends + on wp1. + +## Contract + +- Trigger reuses the existing `usage.range.custom` label, so no locale catalog gains a key. +- Collapsed state renders no date inputs; `aria-expanded`/`aria-controls` carry the state. +- An applied window keeps its `role="status"` interval line outside the panel, so collapsing never + hides which interval the numbers cover (progressive disclosure names what stays hidden). +- Draft text, validation, request identity and cache behavior are untouched: this is presentation. + +Verification: see `010_audit.md`. The maintainer forbade local suite runs mid-unit, so the +repository-wide `bun run test` is NOT RUN locally and remote exact-head CI is the only +full-suite evidence for this change. diff --git a/devlog/_plan/260909_usage_custom_range_disclosure/010_audit.md b/devlog/_plan/260909_usage_custom_range_disclosure/010_audit.md new file mode 100644 index 0000000000..73acc8b1ba --- /dev/null +++ b/devlog/_plan/260909_usage_custom_range_disclosure/010_audit.md @@ -0,0 +1,44 @@ +# Audit and verification record + +## Independent review (explorer reviewer, A gate) + +Verdict NEAR-PASS. The reviewer read the four touched files, ran the focused suite and +typecheck, and measured the rendered panel in headless Chrome rather than trusting the CSS +comments. It cleared the behavioral half: `rangeOpen` feeds only `aria-expanded`, the +`is-active` class and the conditional render, and `loadUsage`, `resourceKey`, `presetKey`, +the held-cache gating and the `UsageWindowMismatchError` receipt check are untouched, so +request identity and caching cannot have moved. Every `var()` in the new block resolves, no +other `.usage-range*` selector exists in `gui/src`, and `usage.range.custom` is already in all +ten catalogs, so promoting it from `aria-label` to visible text adds no key. + +Findings folded in: + +1. **BLOCKING — measured spacing defect.** `repeat(2, minmax(0, 200px))` capped each date + track at 200px, but `.input` carries `min-width: auto` and a `datetime-local` control's + intrinsic minimum is ~206px in Chrome at this font size. Measured `input w=206.0` in a + 200px track, leaving a 2px visible gap where the grid declares 8px — and worse for locales + whose date format is longer than `mm/dd/yyyy`. That is the exact rhythm defect this change + exists to repair. Fixed by sizing every track to its content: `repeat(4, auto)` with + `justify-content: start`. +2. **MINOR — dangling IDREF.** `aria-controls` named a panel that is unmounted while closed. + Now emitted only while open. +3. **MINOR — hidden validation state.** `rangeError` survived a collapse, so a submitted + invalid range left an alert behind an unmarked trigger. Closing now retires the error while + keeping the draft; covered by a new regression test. +4. **MINOR — vacuous-assertion risk.** The `interval()` helper was class-coupled; it is now + scoped to `.usage-range-bar [role="status"]`. +5. **MINOR, accepted.** Disclosure state across a preset click stays open and is left unpinned. + +## Verification status + +| Check | Result | +|---|---| +| `bun run typecheck` | pass (before the no-local-suite instruction) | +| `cd gui && bun test tests` | 1937 pass / 0 fail (before the instruction; 26 in the usage suite after the review fixes) | +| `cd gui && bun run lint` | pass | +| `cd gui && bun run build` | pass | +| `bun run test` (repository-wide) | **NOT RUN** — killed on the maintainer's explicit instruction | +| Rendered browser check | Collapsed, open, applied-then-collapsed, validation error, dark theme and 430px width, against a live proxy | + +Screenshots in `assets/`: `010_before.png` is the shipped 2.49.0 layout, `020_after_collapsed.png` +and `030_after_open.png` are this change. Remote exact-head CI is the full-suite authority. diff --git a/devlog/_plan/260909_usage_custom_range_disclosure/assets/010_before.png b/devlog/_plan/260909_usage_custom_range_disclosure/assets/010_before.png new file mode 100644 index 0000000000..56ae4fb615 Binary files /dev/null and b/devlog/_plan/260909_usage_custom_range_disclosure/assets/010_before.png differ diff --git a/devlog/_plan/260909_usage_custom_range_disclosure/assets/020_after_collapsed.png b/devlog/_plan/260909_usage_custom_range_disclosure/assets/020_after_collapsed.png new file mode 100644 index 0000000000..d1d692f08a Binary files /dev/null and b/devlog/_plan/260909_usage_custom_range_disclosure/assets/020_after_collapsed.png differ diff --git a/devlog/_plan/260909_usage_custom_range_disclosure/assets/030_after_open.png b/devlog/_plan/260909_usage_custom_range_disclosure/assets/030_after_open.png new file mode 100644 index 0000000000..3ac6661ffc Binary files /dev/null and b/devlog/_plan/260909_usage_custom_range_disclosure/assets/030_after_open.png differ diff --git a/gui/src/pages/Usage.tsx b/gui/src/pages/Usage.tsx index cfcf00e578..96f0f1db0c 100644 --- a/gui/src/pages/Usage.tsx +++ b/gui/src/pages/Usage.tsx @@ -5,6 +5,7 @@ import { formatTokens } from "../format-tokens"; import { formatEstimatedUsdValue as formatUsdEstimate } from "../intl-formatters"; import { readSessionListCache, writeSessionListCache } from "../session-list-cache"; import { EmptyState, Notice } from "../ui"; +import { IconChevron } from "../icons"; import { modelLabel } from "../model-display"; import { useDataSurface } from "../data-surface"; import { DataSurfaceSkeleton } from "../components/data-surface"; @@ -804,6 +805,7 @@ export default function Usage({ apiBase, connected = false, apiKeyId }: { apiBas const [draftWindow, setDraftWindow] = useState({ since: "", until: "" }); const [customWindow, setCustomWindow] = useState(null); const [rangeError, setRangeError] = useState(null); + const [rangeOpen, setRangeOpen] = useState(false); const since = customWindow?.since; const until = customWindow?.until; @@ -877,54 +879,85 @@ export default function Usage({ apiBase, connected = false, apiKeyId }: { apiBas

{t("usage.subtitle")}

- { - event.preventDefault(); - const result = parseUsageTimeRange(draftWindow.since, draftWindow.until); - if (result.ok === false) { - setRangeError(result.error); - return; - } - setRangeError(null); - setCustomWindow(result.window); - }}> -
- - - - + {/* + An explicit interval is the rare path — the presets answer the question almost every + time — so the two date fields open on request instead of greeting every visit as the + second thing on the page. The applied interval stays outside the panel: collapsing the + controls must never hide which window the totals below actually cover. + */} +
+
+ + {customWindow &&

{(() => { + const formatter = new Intl.DateTimeFormat(locale, { + year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", + second: "2-digit", fractionalSecondDigits: 3, timeZoneName: "short", + }); + return t("usage.range.applied", { start: formatter.format(customWindow.since), end: formatter.format(customWindow.until) }); + })()}

}
-

{t("usage.range.help")}

- {rangeError && } - {customWindow &&

{(() => { - const formatter = new Intl.DateTimeFormat(locale, { - year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", - second: "2-digit", fractionalSecondDigits: 3, timeZoneName: "short", - }); - return t("usage.range.applied", { start: formatter.format(customWindow.since), end: formatter.format(customWindow.until) }); - })()}

} - + {rangeOpen && ( +
{ + event.preventDefault(); + const result = parseUsageTimeRange(draftWindow.since, draftWindow.until); + if (result.ok === false) { + setRangeError(result.error); + return; + } + setRangeError(null); + setCustomWindow(result.window); + }}> +
+ + + + +
+

{t("usage.range.help")}

+ {rangeError && } +
+ )} +
{/* Only shown when connected. Naming the source is a two-plane concept: it answers "which store served these numbers", and that question only exists once there are diff --git a/gui/src/styles.css b/gui/src/styles.css index a5838be7e4..1a51a2f40e 100644 --- a/gui/src/styles.css +++ b/gui/src/styles.css @@ -2508,6 +2508,45 @@ button.prov-account-row.active { cursor: default; } /* Top-align with Storage: centering against the taller filter chips dropped the "Usage" title. */ .usage-head { flex-wrap: wrap; align-items: flex-start; } .usage-filters { display: flex; align-items: center; justify-content: flex-end; gap: 8px; flex-wrap: wrap; } +/* Custom range: a disclosure, not a second filter row. It reuses the chip language of the + segmented presets above it so the page reads as one control area, and the panel is + `width: max-content` because a four-control form stretched to 1200px is what made the old + flex-end row look like a stray band across the page. */ +.usage-range { display: grid; justify-items: start; gap: 8px; margin: 10px 0 4px; } +.usage-range-bar { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; max-width: 100%; } +.usage-range-toggle { + display: inline-flex; align-items: center; gap: 6px; + min-height: var(--control-sm); padding: 4px 12px; + border: 1px solid var(--border); border-radius: var(--radius-pill); + background: var(--surface); color: var(--muted); + font: inherit; font-size: var(--text-label); font-weight: var(--weight-medium); + white-space: nowrap; cursor: pointer; + transition: color var(--motion-fast), background var(--motion-fast), border-color var(--motion-fast); +} +.usage-range-toggle:hover { background: var(--raised); color: var(--text); } +.usage-range-toggle[aria-expanded="true"] { color: var(--text); } +.usage-range-toggle.is-active { border-color: var(--accent); color: var(--text); } +.usage-range-chevron { flex: 0 0 auto; transition: transform var(--motion-fast); } +.usage-range-toggle[aria-expanded="true"] .usage-range-chevron { transform: rotate(90deg); } +.usage-range-applied { margin: 0; min-width: 0; } +.usage-range-panel { + display: grid; gap: 10px; width: max-content; max-width: 100%; + padding: 12px; border: 1px solid var(--border); border-radius: var(--radius-sm); + background: var(--surface); +} +/* `align-items: end` is the fix for the old row: a label+input stack is twice the height of a + `btn-sm`, so centering left Apply and Clear floating beside the middle of the fields. + Every track is `auto` on purpose. A fixed 200px cap does not survive contact with a + `datetime-local` control: its intrinsic minimum is about 206px in Chrome at this font size, + and it grows again for locales whose date format is longer than `mm/dd/yyyy`. The fields + then overflow their tracks and eat the gap, which is the exact rhythm defect this block + exists to fix. */ +.usage-range-fields { display: grid; grid-template-columns: repeat(4, auto); justify-content: start; align-items: end; gap: 8px; } +.usage-range-field { display: grid; gap: 4px; min-width: 0; } +.usage-range-field .field-label { margin: 0; } +.usage-range-fields .input { height: var(--control-md); padding-block: 0; } +.usage-range-action { min-height: var(--control-md); } +.usage-range-panel > p { margin: 0; } .usage-segmented { display: inline-flex; border: 1px solid var(--border); border-radius: var(--radius-pill); padding: 2px; gap: 2px; background: var(--surface); } .usage-segmented-btn { display: inline-flex; align-items: center; justify-content: center; gap: 6px; border: none; background: transparent; color: var(--muted); padding: 4px 12px; border-radius: var(--radius-pill); cursor: pointer; font: inherit; white-space: nowrap; } .usage-segmented-btn.active { background: var(--raised); color: var(--text); font-weight: var(--weight-semibold); } @@ -2529,6 +2568,11 @@ button.prov-account-row.active { cursor: default; } @media (max-width: 640px) { .usage-source-btn .usage-source-label-collapsible { display: none; } + /* Two 200px columns plus both actions stop fitting a phone content width; the panel takes + the full row and every control keeps the same height it has on desktop. */ + .usage-range-panel { width: 100%; } + .usage-range-fields { grid-template-columns: minmax(0, 1fr); } + .usage-range-action { width: 100%; } } @media (max-width: 360px) { diff --git a/gui/tests/usage-custom-range.test.tsx b/gui/tests/usage-custom-range.test.tsx index db257ba6b2..ea4e98e51c 100644 --- a/gui/tests/usage-custom-range.test.tsx +++ b/gui/tests/usage-custom-range.test.tsx @@ -85,10 +85,13 @@ async function respond(index: number, marker: string, date?: string) { await act(async () => { requests[index].resolve(Response.json(report(requests[index], marker, date))); }); } +const toggle = () => container.querySelector(".usage-range-toggle")!; const form = () => container.querySelector('form[aria-label="Custom date range"]')!; const startInput = () => form().querySelectorAll('input[type="datetime-local"]')[0]; const endInput = () => form().querySelectorAll('input[type="datetime-local"]')[1]; -const interval = () => form().querySelector('[role="status"]')?.textContent; +// The applied interval lives beside the trigger rather than inside the panel: collapsing the +// controls must not hide which window the totals cover. +const interval = () => container.querySelector('.usage-range-bar [role="status"]')?.textContent; const error = () => form().querySelector('[role="alert"]')?.textContent; const preset = (name: string) => container.querySelector(`button.usage-segmented-btn[aria-label="${name}"]`)!; @@ -97,7 +100,13 @@ async function click(button: HTMLButtonElement) { await act(async () => { button.click(); }); } +// The date fields are behind a closed-by-default disclosure, so every draft starts by opening it. +async function openRange() { + if (toggle().getAttribute("aria-expanded") !== "true") await click(toggle()); +} + async function enter(start: string, end: string) { + await openRange(); await act(async () => { for (const [input, value] of [[startInput(), start], [endInput(), end]] as const) { Object.getOwnPropertyDescriptor(testWindow.HTMLInputElement.prototype, "value")!.set!.call(input, value); @@ -357,3 +366,70 @@ test("each preset clears custom, including the retained preset; 7d never replace expect(container.querySelectorAll(".heatmap-grid .heatmap-cell")).toHaveLength(7); expect(preset("7d").getAttribute("aria-pressed")).toBe("false"); }); + +test("the range panel is closed until asked for, and collapsing it keeps the applied interval readable", async () => { + await mount(); + await respond(0, "preset-report-marker"); + // Closed is the default: a page that opens on a report should not also open on two empty + // date fields, and the collapsed panel must leave no tab stops behind. + expect(toggle().getAttribute("aria-expanded")).toBe("false"); + expect(toggle().textContent).toContain("Custom date range"); + expect(container.querySelector('form[aria-label="Custom date range"]')).toBeNull(); + expect(container.querySelectorAll('input[type="datetime-local"]')).toHaveLength(0); + expect(toggle().className).not.toContain("is-active"); + // Naming a panel that is not in the document would leave a dangling IDREF. + expect(toggle().hasAttribute("aria-controls")).toBe(false); + + await click(toggle()); + expect(toggle().getAttribute("aria-expanded")).toBe("true"); + expect(toggle().getAttribute("aria-controls")).toBe(form().id); + expect(container.querySelectorAll('input[type="datetime-local"]')).toHaveLength(2); + expect(requests).toHaveLength(1); + + await enter("2020-09-15T10:20", "2020-09-15T10:21"); + await apply(); + expect(requests[1].url).toBe(`${apiBase}/api/usage?range=30d&surface=all&${boundsQuery}`); + await respond(1, "custom-report-marker"); + const applied = interval(); + expect(applied).toContain("both inclusive"); + + // Collapsing hides the controls, never the state: the interval line and the marked trigger + // still say which window produced the numbers below. + await click(toggle()); + expect(toggle().getAttribute("aria-expanded")).toBe("false"); + expect(container.querySelectorAll('input[type="datetime-local"]')).toHaveLength(0); + expect(interval()).toBe(applied); + expect(toggle().className).toContain("is-active"); + expect(container.textContent).toContain("custom-report-marker"); + expect(requests).toHaveLength(2); + + // Reopening restores the draft that produced the applied window rather than empty fields. + await click(toggle()); + expect(startInput().value).toBe("2020-09-15T10:20"); + expect(endInput().value).toBe("2020-09-15T10:21"); + await clear(); + expect(interval()).toBeUndefined(); + expect(toggle().className).not.toContain("is-active"); + expect(startInput().value).toBe(""); +}); + +test("closing the panel retires a validation error instead of parking it out of sight", async () => { + await mount(); + await respond(0, "held-report-marker"); + await enter("2020-09-16T10:20", "2020-09-15T10:20"); + await apply(); + expect(error()).toContain("The end must"); + expect(startInput().getAttribute("aria-invalid")).toBe("true"); + expect(startInput().getAttribute("aria-describedby")).toBe("usage-range-help usage-range-error"); + + // The alert only means something beside the fields that produced it, so it does not outlive + // the panel — but the draft that produced it does. + await click(toggle()); + await click(toggle()); + expect(error()).toBeUndefined(); + expect(startInput().value).toBe("2020-09-16T10:20"); + expect(startInput().getAttribute("aria-invalid")).toBe("false"); + expect(startInput().getAttribute("aria-describedby")).toBe("usage-range-help"); + expect(requests).toHaveLength(1); + expect(container.textContent).toContain("held-report-marker"); +});