From 768f3ae591f60ee192c14ece1806fecbf8a30414 Mon Sep 17 00:00:00 2001 From: Derek Mackley Date: Fri, 20 Nov 2026 18:30:59 -0600 Subject: [PATCH] show the live cluster metrics in a telemetry band under the hero and answer cluster commands in the terminal --- src/App.tsx | 3 + .../molecules/StatTile/StatTile.css | 113 ++++++++++++++++ .../molecules/StatTile/StatTile.stories.tsx | 59 +++++++++ .../molecules/StatTile/StatTile.tsx | 125 ++++++++++++++++++ src/components/molecules/StatTile/index.ts | 2 + .../molecules/StatTileGrid/StatTileGrid.css | 15 +++ .../StatTileGrid/StatTileGrid.stories.tsx | 59 +++++++++ .../molecules/StatTileGrid/StatTileGrid.tsx | 53 ++++++++ .../molecules/StatTileGrid/index.ts | 2 + .../TelemetryStatusLine.css | 48 +++++++ .../TelemetryStatusLine.stories.tsx | 38 ++++++ .../TelemetryStatusLine.tsx | 49 +++++++ .../molecules/TelemetryStatusLine/index.ts | 2 + .../molecules/VersionChips/VersionChips.css | 48 +++++++ .../VersionChips/VersionChips.stories.tsx | 39 ++++++ .../molecules/VersionChips/VersionChips.tsx | 36 +++++ .../molecules/VersionChips/index.ts | 2 + .../ClusterTelemetry/ClusterTelemetry.css | 93 +++++++++++++ .../ClusterTelemetry.stories.tsx | 87 ++++++++++++ .../ClusterTelemetry/ClusterTelemetry.tsx | 99 ++++++++++++++ .../organisms/ClusterTelemetry/index.ts | 2 + .../organisms/Greetings/Greetings.stories.tsx | 4 +- .../organisms/Greetings/Greetings.tsx | 7 +- .../organisms/Greetings/commands.test.ts | 80 ++++++++++- .../organisms/Greetings/commands.ts | 121 ++++++++++++++++- src/utils/__tests__/clusterTelemetry.test.ts | 59 +++++++++ src/utils/clusterTelemetry.ts | 102 ++++++++++++++ 27 files changed, 1335 insertions(+), 12 deletions(-) create mode 100644 src/components/molecules/StatTile/StatTile.css create mode 100644 src/components/molecules/StatTile/StatTile.stories.tsx create mode 100644 src/components/molecules/StatTile/StatTile.tsx create mode 100644 src/components/molecules/StatTile/index.ts create mode 100644 src/components/molecules/StatTileGrid/StatTileGrid.css create mode 100644 src/components/molecules/StatTileGrid/StatTileGrid.stories.tsx create mode 100644 src/components/molecules/StatTileGrid/StatTileGrid.tsx create mode 100644 src/components/molecules/StatTileGrid/index.ts create mode 100644 src/components/molecules/TelemetryStatusLine/TelemetryStatusLine.css create mode 100644 src/components/molecules/TelemetryStatusLine/TelemetryStatusLine.stories.tsx create mode 100644 src/components/molecules/TelemetryStatusLine/TelemetryStatusLine.tsx create mode 100644 src/components/molecules/TelemetryStatusLine/index.ts create mode 100644 src/components/molecules/VersionChips/VersionChips.css create mode 100644 src/components/molecules/VersionChips/VersionChips.stories.tsx create mode 100644 src/components/molecules/VersionChips/VersionChips.tsx create mode 100644 src/components/molecules/VersionChips/index.ts create mode 100644 src/components/organisms/ClusterTelemetry/ClusterTelemetry.css create mode 100644 src/components/organisms/ClusterTelemetry/ClusterTelemetry.stories.tsx create mode 100644 src/components/organisms/ClusterTelemetry/ClusterTelemetry.tsx create mode 100644 src/components/organisms/ClusterTelemetry/index.ts create mode 100644 src/utils/__tests__/clusterTelemetry.test.ts create mode 100644 src/utils/clusterTelemetry.ts diff --git a/src/App.tsx b/src/App.tsx index 8e02dcdf..33737ae9 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -31,6 +31,7 @@ import { HelmetProvider } from 'react-helmet-async'; // Lazy load components const Greetings = lazy(() => import("@organisms/Greetings")); +const ClusterTelemetry = lazy(() => import("@organisms/ClusterTelemetry")); const Skills = lazy(() => import("@organisms/Skills")); const Education = lazy(() => import("@organisms/Education")); const Experience = lazy(() => import("@organisms/Experience")); @@ -54,6 +55,7 @@ const componentsToDebug = { // Organism components Greetings, + ClusterTelemetry, Skills, Experience, Projects, @@ -150,6 +152,7 @@ function App() {
}> + diff --git a/src/components/molecules/StatTile/StatTile.css b/src/components/molecules/StatTile/StatTile.css new file mode 100644 index 00000000..01f3704a --- /dev/null +++ b/src/components/molecules/StatTile/StatTile.css @@ -0,0 +1,113 @@ +/* StatTile: one live number in a card. Figure is the hero. */ + +.stat-tile { + position: relative; + display: flex; + flex-direction: column; + gap: var(--spacing-2); + box-sizing: border-box; + min-width: 0; + margin: 0; + padding: var(--spacing-4) min(var(--spacing-4), 4vw); + background: var(--surface-card); + border: 1px solid var(--surface-border); + border-radius: var(--radius-card); + box-shadow: var(--shadow-card); + overflow: hidden; +} + +/* Thin tone rule along the top edge */ +.stat-tile::before { + content: ''; + position: absolute; + inset: 0 0 auto 0; + height: 2px; + background: var(--stat-tile-accent, var(--surface-border)); +} + +.stat-tile--success { + --stat-tile-accent: var(--color-success); +} + +.stat-tile--warning { + --stat-tile-accent: var(--color-warning); +} + +.stat-tile__label { + font-family: var(--font-family-jetbrains); + font-size: var(--font-size-xs); + font-weight: var(--font-weight-medium); + letter-spacing: var(--letter-spacing-technical); + text-transform: uppercase; + color: var(--color-text-muted); + overflow-wrap: anywhere; +} + +.stat-tile__reading { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 0 var(--spacing-1); + margin: 0; + min-height: 2.75rem; + font-family: var(--font-family-jetbrains); +} + +.stat-tile__value { + font-size: min(2.5rem, 8.5vw); + font-weight: var(--font-weight-bold); + line-height: 1.1; + font-variant-numeric: tabular-nums; + color: var(--color-text); + overflow-wrap: anywhere; +} + +.stat-tile--success .stat-tile__value { + color: var(--color-success); +} + +.stat-tile--warning .stat-tile__value { + color: var(--color-warning); +} + +.stat-tile__unit { + font-size: var(--font-size-sm); + font-weight: var(--font-weight-medium); + letter-spacing: var(--letter-spacing-technical); + text-transform: uppercase; + color: var(--color-primary); +} + +/* Loading shimmer */ +.stat-tile__skeleton { + display: block; + width: min(6rem, 70%); + height: 2rem; + border-radius: var(--border-radius-sm, 4px); + background: var(--color-skeleton-bg); +} + +.stat-tile--animated .stat-tile__skeleton { + background: linear-gradient( + 90deg, + var(--color-skeleton-bg) 0%, + rgba(var(--color-primary-rgb), 0.16) 50%, + var(--color-skeleton-bg) 100% + ); + background-size: 200% 100%; + animation: stat-tile-shimmer 1.4s ease-in-out infinite; +} + +.stat-tile__sr { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} + +@keyframes stat-tile-shimmer { + from { background-position: 200% 0; } + to { background-position: -200% 0; } +} diff --git a/src/components/molecules/StatTile/StatTile.stories.tsx b/src/components/molecules/StatTile/StatTile.stories.tsx new file mode 100644 index 00000000..db96705c --- /dev/null +++ b/src/components/molecules/StatTile/StatTile.stories.tsx @@ -0,0 +1,59 @@ +import type { Meta, StoryObj } from '@storybook/react-vite'; +import { expect, waitFor, within } from 'storybook/test'; +import StatTile from './StatTile'; + +const meta = { + title: 'Molecules/StatTile', + component: StatTile, + tags: ['autodocs'], + parameters: { + docs: { + description: { + component: + 'One live number: a big monospace figure, a small unit and a mono caption. The figure counts up from 0 the first time it is seen (final value at once under reduced motion). Tones: success for good news, warning (amber) for anything that needs a look. Never red. Must sit inside a `dl`.', + }, + }, + }, + decorators: [ + (Story) => ( +
+ +
+ ), + ], + args: { label: 'Pods', value: '266', animated: true }, + argTypes: { + tone: { control: 'inline-radio', options: ['default', 'success', 'warning'] }, + loading: { control: 'boolean' }, + animated: { control: 'boolean' }, + }, +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const Default: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await expect(canvas.getByText('Pods')).toBeInTheDocument(); + await waitFor(() => expect(canvas.getByText('266')).toBeInTheDocument(), { timeout: 3000 }); + }, +}; + +export const WithUnit: Story = { args: { label: 'Power draw', value: '1,074', unit: 'W' } }; + +export const Decimal: Story = { args: { label: 'Memory', value: '13.8', unit: '%' } }; + +export const Success: Story = { args: { label: 'Alerts', value: '0', tone: 'success' } }; + +/** Alerts above zero are amber with the real count. */ +export const Warning: Story = { args: { label: 'Alerts', value: '1', tone: 'warning' } }; + +export const Loading: Story = { args: { loading: true } }; + +export const NoAnimation: Story = { + args: { animated: false, label: 'Nodes', value: '11' }, + play: async ({ canvasElement }) => { + await expect(within(canvasElement).getByText('11')).toBeInTheDocument(); + }, +}; diff --git a/src/components/molecules/StatTile/StatTile.tsx b/src/components/molecules/StatTile/StatTile.tsx new file mode 100644 index 00000000..1c528db3 --- /dev/null +++ b/src/components/molecules/StatTile/StatTile.tsx @@ -0,0 +1,125 @@ +import { useEffect, useRef, useState } from 'react'; +import { useMotionEnabled } from '@utils/motion'; +import './StatTile.css'; + +export type StatTileTone = 'default' | 'success' | 'warning'; + +export interface StatTileProps { + /** Small caption, e.g. "Pods" */ + label: string; + /** The figure as written, e.g. "1,074" or "13.8". Omit while loading. */ + value?: string; + /** Small unit after the figure, e.g. "W", "%" */ + unit?: string; + /** default: neutral; success: good news; warning: needs a look (amber, never red) */ + tone?: StatTileTone; + /** Shows a shimmer instead of a figure */ + loading?: boolean; + /** Count up from 0 the first time the tile is seen */ + animated?: boolean; +} + +const COUNT_MS = 800; + +const decimalsOf = (figure: string): number => figure.split('.')[1]?.length ?? 0; + +const toNumber = (figure: string): number | null => { + const n = Number(figure.replace(/,/g, '')); + return Number.isFinite(n) ? n : null; +}; + +const format = (n: number, decimals: number): string => + n.toLocaleString('en-US', { minimumFractionDigits: decimals, maximumFractionDigits: decimals }); + +/** Counts from 0 to the figure once the element is on screen. Returns the text to show. */ +const useCountUp = (figure: string | undefined, enabled: boolean, target: React.RefObject) => { + const end = figure === undefined ? null : toNumber(figure); + const counts = enabled && end !== null; + const [text, setText] = useState( + figure !== undefined && counts ? format(0, decimalsOf(figure)) : figure, + ); + const played = useRef(false); + + useEffect(() => { + if (figure === undefined) { + setText(undefined); + return; + } + if (!counts || end === null || played.current) { + setText(figure); + return; + } + + const decimals = decimalsOf(figure); + let frame = 0; + let observer: IntersectionObserver | null = null; + + const run = () => { + played.current = true; + const start = performance.now(); + const tick = (now: number) => { + const t = Math.min(1, (now - start) / COUNT_MS); + const eased = 1 - Math.pow(1 - t, 3); + setText(t >= 1 ? figure : format(end * eased, decimals)); + if (t < 1) frame = requestAnimationFrame(tick); + }; + frame = requestAnimationFrame(tick); + }; + + const node = target.current; + if (node && typeof IntersectionObserver !== 'undefined') { + observer = new IntersectionObserver((entries) => { + if (entries.some((e) => e.isIntersecting)) { + observer?.disconnect(); + run(); + } + }, { threshold: 0.4 }); + observer.observe(node); + } else { + run(); + } + + return () => { + observer?.disconnect(); + cancelAnimationFrame(frame); + }; + }, [figure, counts, end, target]); + + return { text, done: text === figure }; +}; + +/** + * One live number: a big monospace figure with a small unit and a caption. + * Shows a shimmer while loading. Props only; the parent supplies the data. + */ +const StatTile = ({ label, value, unit, tone = 'default', loading = false, animated = true }: StatTileProps) => { + const motionOn = useMotionEnabled(animated); + const ref = useRef(null); + const { text, done } = useCountUp(loading ? undefined : value, motionOn, ref); + + return ( +
+
{label}
+
+ {loading ? ( + + Loading + + ) : ( + <> + + {text} + + {unit ? {unit} : null} + + )} +
+
+ ); +}; + +export default StatTile; diff --git a/src/components/molecules/StatTile/index.ts b/src/components/molecules/StatTile/index.ts new file mode 100644 index 00000000..3f93c446 --- /dev/null +++ b/src/components/molecules/StatTile/index.ts @@ -0,0 +1,2 @@ +export { default } from './StatTile'; +export type { StatTileProps, StatTileTone } from './StatTile'; diff --git a/src/components/molecules/StatTileGrid/StatTileGrid.css b/src/components/molecules/StatTileGrid/StatTileGrid.css new file mode 100644 index 00000000..fd97c39a --- /dev/null +++ b/src/components/molecules/StatTileGrid/StatTileGrid.css @@ -0,0 +1,15 @@ +.stat-tile-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(100%, 9rem), 1fr)); + gap: min(var(--spacing-3), 3vw); + margin: 0; + padding: 0; +} + +/* Wide screens: two even rows of four */ +@media (min-width: 900px) { + .stat-tile-grid { + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: var(--spacing-4); + } +} diff --git a/src/components/molecules/StatTileGrid/StatTileGrid.stories.tsx b/src/components/molecules/StatTileGrid/StatTileGrid.stories.tsx new file mode 100644 index 00000000..7f65e39a --- /dev/null +++ b/src/components/molecules/StatTileGrid/StatTileGrid.stories.tsx @@ -0,0 +1,59 @@ +import type { Meta, StoryObj } from '@storybook/react-vite'; +import { expect, waitFor, within } from 'storybook/test'; +import StatTileGrid from './StatTileGrid'; +import type { StatTileGridItem } from './StatTileGrid'; + +const tiles: StatTileGridItem[] = [ + { id: 'nodes', label: 'Nodes', value: '11' }, + { id: 'pods', label: 'Pods', value: '266' }, + { id: 'services', label: 'Services up', value: '69' }, + { id: 'uptime', label: 'Uptime', value: '8', unit: 'days' }, + { id: 'power', label: 'Power draw', value: '1,074', unit: 'W' }, + { id: 'cpu', label: 'CPU', value: '12.3', unit: '%' }, + { id: 'memory', label: 'Memory', value: '14', unit: '%' }, + { id: 'alerts', label: 'Alerts', value: '0', tone: 'success' }, +]; + +const meta = { + title: 'Molecules/StatTileGrid', + component: StatTileGrid, + tags: ['autodocs'], + parameters: { + layout: 'padded', + docs: { + description: { + component: + 'Responsive grid of StatTiles: four columns on wide screens, two on a phone, one at large text sizes. While loading it shows shimmer tiles with only their captions.', + }, + }, + }, + args: { + tiles, + animated: true, + placeholders: tiles.map((t) => t.label), + }, +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const Default: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await waitFor(() => expect(canvas.getByText('1,074')).toBeInTheDocument(), { timeout: 3000 }); + await expect(canvas.getAllByTestId('stat-tile')).toHaveLength(8); + }, +}; + +/** Alerts above zero show the real count in amber. */ +export const WithAlert: Story = { + args: { tiles: tiles.map((t) => (t.id === 'alerts' ? { ...t, value: '2', tone: 'warning' as const } : t)) }, +}; + +export const Loading: Story = { args: { loading: true } }; + +export const NoAnimation: Story = { args: { animated: false } }; + +export const Phone: Story = { + parameters: { viewport: { defaultViewport: 'mobile1' } }, +}; diff --git a/src/components/molecules/StatTileGrid/StatTileGrid.tsx b/src/components/molecules/StatTileGrid/StatTileGrid.tsx new file mode 100644 index 00000000..0709af73 --- /dev/null +++ b/src/components/molecules/StatTileGrid/StatTileGrid.tsx @@ -0,0 +1,53 @@ +import StatTile from '@molecules/StatTile'; +import type { StatTileTone } from '@molecules/StatTile'; +import './StatTileGrid.css'; + +export interface StatTileGridItem { + id: string; + label: string; + value: string; + unit?: string; + tone?: StatTileTone; +} + +export interface StatTileGridProps { + /** Tiles to show. Ignored while `loading`. */ + tiles: StatTileGridItem[]; + /** Shows `placeholders` shimmering tiles instead of figures */ + loading?: boolean; + /** Captions for the shimmer tiles while loading */ + placeholders?: string[]; + /** Whether the figures count up and the shimmer moves */ + animated?: boolean; + /** Accessible name for the list of readings */ + ariaLabel?: string; +} + +/** + * A responsive grid of StatTiles. Two columns on a phone, one at large text + * sizes, four on a wide screen. Props only. + */ +const StatTileGrid = ({ + tiles, + loading = false, + placeholders = [], + animated = true, + ariaLabel = 'Live readings', +}: StatTileGridProps) => ( +
+ {loading + ? placeholders.map((label) => ) + : tiles.map((tile) => ( + + ))} +
+); + +export default StatTileGrid; diff --git a/src/components/molecules/StatTileGrid/index.ts b/src/components/molecules/StatTileGrid/index.ts new file mode 100644 index 00000000..19c65cbf --- /dev/null +++ b/src/components/molecules/StatTileGrid/index.ts @@ -0,0 +1,2 @@ +export { default } from './StatTileGrid'; +export type { StatTileGridProps, StatTileGridItem } from './StatTileGrid'; diff --git a/src/components/molecules/TelemetryStatusLine/TelemetryStatusLine.css b/src/components/molecules/TelemetryStatusLine/TelemetryStatusLine.css new file mode 100644 index 00000000..88fe3f47 --- /dev/null +++ b/src/components/molecules/TelemetryStatusLine/TelemetryStatusLine.css @@ -0,0 +1,48 @@ +.telemetry-status { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--spacing-1) var(--spacing-3); + margin: 0; + font-family: var(--font-family-jetbrains); + font-size: var(--font-size-sm); + letter-spacing: var(--letter-spacing-technical); + color: var(--color-text-muted); +} + +.telemetry-status__dot { + width: 10px; + height: 10px; + flex-shrink: 0; + border-radius: 50%; + background: var(--color-primary); + box-shadow: 0 0 8px rgba(var(--color-primary-rgb), 0.7); +} + +.telemetry-status--degraded .telemetry-status__dot { + background: var(--color-warning); + box-shadow: 0 0 8px rgba(var(--color-warning-rgb), 0.7); +} + +.telemetry-status--loading .telemetry-status__dot, +.telemetry-status--offline .telemetry-status__dot { + background: var(--color-gray-600); + box-shadow: none; +} + +.telemetry-status__state { + font-weight: var(--font-weight-medium); + color: var(--color-text); +} + +.telemetry-status--up .telemetry-status__state { + color: var(--color-primary); +} + +.telemetry-status--degraded .telemetry-status__state { + color: var(--color-warning); +} + +.telemetry-status__updated { + color: var(--color-text-muted); +} diff --git a/src/components/molecules/TelemetryStatusLine/TelemetryStatusLine.stories.tsx b/src/components/molecules/TelemetryStatusLine/TelemetryStatusLine.stories.tsx new file mode 100644 index 00000000..ba7dd283 --- /dev/null +++ b/src/components/molecules/TelemetryStatusLine/TelemetryStatusLine.stories.tsx @@ -0,0 +1,38 @@ +import type { Meta, StoryObj } from '@storybook/react-vite'; +import { expect, within } from 'storybook/test'; +import TelemetryStatusLine from './TelemetryStatusLine'; + +const meta = { + title: 'Molecules/TelemetryStatusLine', + component: TelemetryStatusLine, + tags: ['autodocs'], + parameters: { + docs: { + description: { + component: + 'A live dot, the cluster state in words and the local time of the last reading. The dot pulses; it stays still under reduced motion or when `animated` is false. Degraded is amber, offline and loading are grey.', + }, + }, + }, + args: { state: 'up', updatedAt: '2026-11-20T19:12:00.000Z', animated: true }, + argTypes: { state: { control: 'inline-radio', options: ['up', 'degraded', 'loading', 'offline'] } }, +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const Up: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await expect(canvas.getByText('cluster up')).toBeInTheDocument(); + await expect(canvas.getByText(/updated/)).toBeInTheDocument(); + }, +}; + +export const Degraded: Story = { args: { state: 'degraded' } }; + +export const Loading: Story = { args: { state: 'loading', updatedAt: undefined } }; + +export const Offline: Story = { args: { state: 'offline', updatedAt: undefined } }; + +export const NoAnimation: Story = { args: { animated: false } }; diff --git a/src/components/molecules/TelemetryStatusLine/TelemetryStatusLine.tsx b/src/components/molecules/TelemetryStatusLine/TelemetryStatusLine.tsx new file mode 100644 index 00000000..beaa4732 --- /dev/null +++ b/src/components/molecules/TelemetryStatusLine/TelemetryStatusLine.tsx @@ -0,0 +1,49 @@ +import { motion } from 'framer-motion'; +import { useMotionEnabled } from '@utils/motion'; +import { formatUpdated } from '@utils/clusterTelemetry'; +import './TelemetryStatusLine.css'; + +export type TelemetryState = 'up' | 'degraded' | 'loading' | 'offline'; + +export interface TelemetryStatusLineProps { + state: TelemetryState; + /** Text next to the dot. Defaults from `state`. */ + label?: string; + /** ISO timestamp of the last reading; shown as local time */ + updatedAt?: string; + /** Whether the dot pulses */ + animated?: boolean; +} + +const DEFAULT_LABEL: Record = { + up: 'cluster up', + degraded: 'cluster degraded', + loading: 'reading the cluster', + offline: 'telemetry offline', +}; + +/** A live dot, the cluster state in words, and when it was last read. Props only. */ +const TelemetryStatusLine = ({ state, label, updatedAt, animated = true }: TelemetryStatusLineProps) => { + const motionOn = useMotionEnabled(animated); + const pulse = motionOn && state !== 'offline'; + const time = updatedAt ? formatUpdated(updatedAt) : null; + + return ( +

+

+ ); +}; + +export default TelemetryStatusLine; diff --git a/src/components/molecules/TelemetryStatusLine/index.ts b/src/components/molecules/TelemetryStatusLine/index.ts new file mode 100644 index 00000000..a9fc08be --- /dev/null +++ b/src/components/molecules/TelemetryStatusLine/index.ts @@ -0,0 +1,2 @@ +export { default } from './TelemetryStatusLine'; +export type { TelemetryStatusLineProps, TelemetryState } from './TelemetryStatusLine'; diff --git a/src/components/molecules/VersionChips/VersionChips.css b/src/components/molecules/VersionChips/VersionChips.css new file mode 100644 index 00000000..a1b39dcc --- /dev/null +++ b/src/components/molecules/VersionChips/VersionChips.css @@ -0,0 +1,48 @@ +.version-chips { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--spacing-2) var(--spacing-4); +} + +.version-chips__list { + display: flex; + flex-wrap: wrap; + gap: var(--spacing-2); + margin: 0; + padding: 0; + list-style: none; +} + +.version-chips__chip { + display: inline-flex; + align-items: center; + gap: var(--spacing-2); + box-sizing: border-box; + min-height: 1.75rem; + min-width: 0; + padding: 0 var(--spacing-3); + font-family: var(--font-family-jetbrains); + font-size: var(--font-size-xs); + letter-spacing: var(--letter-spacing-technical); + background: var(--surface-inset); + border: 1px solid var(--surface-border); + border-radius: var(--radius-chip); +} + +.version-chips__name { + color: var(--color-text-muted); +} + +.version-chips__value { + font-weight: var(--font-weight-medium); + color: var(--color-primary); +} + +.version-chips__note { + margin: 0; + font-family: var(--font-family-jetbrains); + font-size: var(--font-size-xs); + letter-spacing: var(--letter-spacing-technical); + color: var(--color-text-muted); +} diff --git a/src/components/molecules/VersionChips/VersionChips.stories.tsx b/src/components/molecules/VersionChips/VersionChips.stories.tsx new file mode 100644 index 00000000..a84cb077 --- /dev/null +++ b/src/components/molecules/VersionChips/VersionChips.stories.tsx @@ -0,0 +1,39 @@ +import type { Meta, StoryObj } from '@storybook/react-vite'; +import { expect, within } from 'storybook/test'; +import VersionChips from './VersionChips'; + +const meta = { + title: 'Molecules/VersionChips', + component: VersionChips, + tags: ['autodocs'], + parameters: { + docs: { + description: { + component: 'Chips for the software the cluster runs, with an optional quiet note after them. Renders nothing when it has neither.', + }, + }, + }, + args: { + items: [ + { label: 'Talos', value: '1.14.5' }, + { label: 'Kubernetes', value: '1.37.2' }, + { label: 'Flux', value: '2.10.1' }, + ], + note: 'running for 646 days', + }, +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const Default: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await expect(canvas.getByText('Talos')).toBeInTheDocument(); + await expect(canvas.getByText('running for 646 days')).toBeInTheDocument(); + }, +}; + +export const ChipsOnly: Story = { args: { note: undefined } }; + +export const NoteOnly: Story = { args: { items: [] } }; diff --git a/src/components/molecules/VersionChips/VersionChips.tsx b/src/components/molecules/VersionChips/VersionChips.tsx new file mode 100644 index 00000000..d8a22233 --- /dev/null +++ b/src/components/molecules/VersionChips/VersionChips.tsx @@ -0,0 +1,36 @@ +import './VersionChips.css'; + +export interface VersionChipItem { + /** Software name, e.g. "Talos" */ + label: string; + /** Version, e.g. "1.14.5" */ + value: string; +} + +export interface VersionChipsProps { + items: VersionChipItem[]; + /** Quiet text after the chips, e.g. "running for 646 days" */ + note?: string; +} + +/** A row of "name version" chips with an optional quiet note. Props only. */ +const VersionChips = ({ items, note }: VersionChipsProps) => { + if (items.length === 0 && !note) return null; + return ( +
+ {items.length > 0 && ( +
    + {items.map((item) => ( +
  • + {item.label} + {item.value} +
  • + ))} +
+ )} + {note ?

{note}

: null} +
+ ); +}; + +export default VersionChips; diff --git a/src/components/molecules/VersionChips/index.ts b/src/components/molecules/VersionChips/index.ts new file mode 100644 index 00000000..acff3802 --- /dev/null +++ b/src/components/molecules/VersionChips/index.ts @@ -0,0 +1,2 @@ +export { default } from './VersionChips'; +export type { VersionChipsProps, VersionChipItem } from './VersionChips'; diff --git a/src/components/organisms/ClusterTelemetry/ClusterTelemetry.css b/src/components/organisms/ClusterTelemetry/ClusterTelemetry.css new file mode 100644 index 00000000..16ef0513 --- /dev/null +++ b/src/components/organisms/ClusterTelemetry/ClusterTelemetry.css @@ -0,0 +1,93 @@ +/* + * ClusterTelemetry: compact band under the hero. Same header voice as the + * other sections (mono kicker, bold title) but tighter. + */ + +.cluster-telemetry { + position: relative; + padding: min(3rem, 10vw) 0; +} + +.cluster-telemetry__inner { + display: flex; + flex-direction: column; + gap: min(var(--spacing-5), 6vw); + box-sizing: border-box; + width: 100%; + max-width: 1200px; + margin: 0 auto; + padding: 0 min(1rem, 4vw); +} + +.cluster-telemetry__header { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + justify-content: space-between; + gap: var(--spacing-3) var(--spacing-5); + padding-bottom: min(var(--spacing-4), 5vw); + border-bottom: 1px solid rgba(var(--color-cyan-rgb), 0.2); +} + +.cluster-telemetry__kicker { + margin: 0 0 var(--spacing-2); + font-family: var(--font-family-jetbrains); + font-size: var(--font-size-sm); + letter-spacing: var(--letter-spacing-technical); + color: var(--color-cyan); +} + +.cluster-telemetry__title { + margin: 0; + font-family: var(--font-family-inter); + font-size: min(var(--font-size-2xl), 8vw); + font-weight: var(--font-weight-bold); + line-height: var(--line-height-tight); + color: var(--color-white); +} + +.cluster-telemetry__lede { + margin: var(--spacing-2) 0 0; + max-width: 44rem; + font-family: var(--font-family-inter); + font-size: var(--font-size-base); + line-height: var(--line-height-base); + color: var(--color-text-muted); +} + +.cluster-telemetry__meta { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: var(--spacing-3) var(--spacing-5); +} + +.cluster-telemetry__link { + overflow-wrap: anywhere; + font-family: var(--font-family-jetbrains); + font-size: var(--font-size-sm); + letter-spacing: var(--letter-spacing-technical); + color: var(--color-primary); + text-decoration: none; + border-bottom: 1px solid transparent; +} + +.cluster-telemetry__link:hover { + border-bottom-color: var(--color-primary); +} + +.cluster-telemetry__link:focus-visible { + outline: none; + box-shadow: var(--ring-focus); + border-radius: var(--border-radius-sm); +} + +.cluster-telemetry__sr { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} diff --git a/src/components/organisms/ClusterTelemetry/ClusterTelemetry.stories.tsx b/src/components/organisms/ClusterTelemetry/ClusterTelemetry.stories.tsx new file mode 100644 index 00000000..a1e31a5c --- /dev/null +++ b/src/components/organisms/ClusterTelemetry/ClusterTelemetry.stories.tsx @@ -0,0 +1,87 @@ +import type { Meta, StoryObj } from '@storybook/react-vite'; +import { expect, waitFor, within } from 'storybook/test'; +import type { ClusterStatusData } from '@/types/cluster'; +import ClusterTelemetry from './ClusterTelemetry'; + +const badge = (title: string, value: string, color = 'green') => ({ title, value, color }); + +// Shaped like the /api/cluster-status response +const okData: ClusterStatusData = { + updatedAt: '2026-11-20T19:12:00.000Z', + badges: { + cluster_status: badge('Cluster', 'up'), + cluster_node_count: badge('Nodes', '11'), + cluster_pod_count: badge('Pods', '266'), + services_up: badge('Services', '69 up'), + cluster_uptime_days: badge('Uptime', '8d'), + cluster_age_days: badge('Age', '646d', 'red'), + cluster_cpu_usage: badge('CPU', '12.3%'), + cluster_memory_usage: badge('Memory', '13.8%'), + cluster_power_usage: badge('Power', '1,074w'), + cluster_alert_count: badge('Alerts', '0'), + talos_version: badge('Talos', '1.14.5', 'blue'), + kubernetes_version: badge('Kubernetes', '1.37.2', 'blue'), + flux_version: badge('Flux', '2.10.1', 'blue'), + }, +}; + +const degradedData: ClusterStatusData = { + ...okData, + badges: { + ...okData.badges, + cluster_status: badge('Cluster', 'degraded', 'yellow'), + cluster_alert_count: badge('Alerts', '3', 'red'), + }, +}; + +const meta = { + title: 'Organisms/ClusterTelemetry', + component: ClusterTelemetry, + tags: ['autodocs'], + parameters: { + layout: 'fullscreen', + docs: { + description: { + component: + 'The live telemetry band under the hero: stat tiles with the numbers from the cluster serving the page, a status line, version chips and a link to the repo. Colours follow the data with the site\'s own meaning: zero alerts green, any alerts amber (with the real count), degraded amber, cluster age never red. Loading shows shimmer tiles; when the feed is down it says "Telemetry offline" and shows no numbers. In the app it reads `useClusterStatus`; the stories pass `result` instead.', + }, + }, + }, + args: { result: { status: 'ok', data: okData } }, +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const Ok: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await expect(canvas.getByRole('heading', { name: /runs in my garage/i })).toBeInTheDocument(); + await waitFor(() => expect(canvas.getByText('1,074')).toBeInTheDocument(), { timeout: 3000 }); + await expect(canvas.getByText('cluster up')).toBeInTheDocument(); + await expect(canvas.getByText('running for 646 days')).toBeInTheDocument(); + }, +}; + +export const Degraded: Story = { + args: { result: { status: 'ok', data: degradedData } }, + play: async ({ canvasElement }) => { + await expect(within(canvasElement).getByText('cluster degraded')).toBeInTheDocument(); + }, +}; + +export const Loading: Story = { + args: { result: { status: 'loading', data: null } }, + play: async ({ canvasElement }) => { + await expect(within(canvasElement).queryByText('266')).toBeNull(); + }, +}; + +export const ErrorState: Story = { + args: { result: { status: 'error', data: null } }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await expect(canvas.getByText('Telemetry offline')).toBeInTheDocument(); + await expect(canvas.queryByText('266')).toBeNull(); + }, +}; diff --git a/src/components/organisms/ClusterTelemetry/ClusterTelemetry.tsx b/src/components/organisms/ClusterTelemetry/ClusterTelemetry.tsx new file mode 100644 index 00000000..fd568399 --- /dev/null +++ b/src/components/organisms/ClusterTelemetry/ClusterTelemetry.tsx @@ -0,0 +1,99 @@ +import { motion } from 'framer-motion'; +import StatTileGrid from '@molecules/StatTileGrid'; +import TelemetryStatusLine from '@molecules/TelemetryStatusLine'; +import VersionChips from '@molecules/VersionChips'; +import useClusterStatus from '@hooks/useClusterStatus'; +import { useAnimation } from '@context/AnimationContext'; +import { slideUpVariants, useMotionEnabled } from '@utils/motion'; +import { ageSentence, telemetryTiles, versionItems } from '@utils/clusterTelemetry'; +import { clusterHealth } from '@molecules/ClusterStatus/clusterSummary'; +import type { ClusterStatusResult } from '@/types/cluster'; +import './ClusterTelemetry.css'; + +export const CLUSTER_REPO_URL = 'https://github.com/dapperdivers/dapper-cluster'; + +const PLACEHOLDER_LABELS = ['Nodes', 'Pods', 'Services up', 'Uptime', 'Power draw', 'CPU', 'Memory', 'Alerts']; + +export interface ClusterTelemetryProps { + /** Use this reading instead of fetching one (stories and tests) */ + result?: ClusterStatusResult; +} + +/** + * The live telemetry band under the hero: the numbers from the Kubernetes + * cluster that serves this page. Shows only what the cluster reported; + * while loading it shimmers, and when the feed is down it says so. + */ +const ClusterTelemetry = ({ result }: ClusterTelemetryProps) => { + const live = useClusterStatus(); + const { status, data } = result ?? live; + const { animationEnabled } = useAnimation(); + const motionOn = useMotionEnabled(animationEnabled); + + const ok = status === 'ok' && data !== null; + const tiles = ok ? telemetryTiles(data) : []; + const hasFigures = tiles.length > 0; + const health = ok ? clusterHealth(data) : 'unknown'; + + const state = status === 'loading' ? 'loading' : !ok || (!hasFigures && health === 'unknown') ? 'offline' : health === 'degraded' ? 'degraded' : 'up'; + + return ( + +
+
+
+ +

+ This site runs in my garage +

+

+ These numbers are live from the Kubernetes cluster serving this page. +

+
+ + See how it's built + (opens GitHub in a new tab) + +
+ + {state === 'offline' ? ( + + ) : ( + <> + ({ id: t.id, label: t.label, value: t.number, unit: t.unit, tone: t.tone }))} + loading={status === 'loading'} + placeholders={PLACEHOLDER_LABELS} + animated={animationEnabled} + ariaLabel="Live cluster readings" + /> +
+ + {ok && } +
+ + )} +
+
+ ); +}; + +export default ClusterTelemetry; diff --git a/src/components/organisms/ClusterTelemetry/index.ts b/src/components/organisms/ClusterTelemetry/index.ts new file mode 100644 index 00000000..84ac2221 --- /dev/null +++ b/src/components/organisms/ClusterTelemetry/index.ts @@ -0,0 +1,2 @@ +export { default } from './ClusterTelemetry'; +export type { ClusterTelemetryProps } from './ClusterTelemetry'; diff --git a/src/components/organisms/Greetings/Greetings.stories.tsx b/src/components/organisms/Greetings/Greetings.stories.tsx index 768accbe..3b0d94d2 100644 --- a/src/components/organisms/Greetings/Greetings.stories.tsx +++ b/src/components/organisms/Greetings/Greetings.stories.tsx @@ -28,7 +28,7 @@ const meta = { docs: { description: { component: - 'Hero section built as a terminal. It types a short whoami sequence (any key or click skips it; reduced motion shows it at once) and leaves an interactive prompt. Commands: help, whoami, ls (ls -a), cd/open
, cat resume, contact, uptime, ping, clear, sudo hire derek. The h1, a Download Resume button and the scroll cue stay visible for people who never type.', + 'Hero section built as a terminal. It types a short whoami sequence (any key or click skips it; reduced motion shows it at once) and leaves an interactive prompt. Commands: help, whoami, ls (ls -a), cd/open
, cat resume, contact, uptime, status, kubectl get nodes, neofetch (real cluster numbers), ping, clear, sudo hire derek. The h1, a Download Resume button and the scroll cue stay visible for people who never type.', }, }, a11y: { @@ -77,7 +77,7 @@ export const TypeCommands: Story = { await step('help lists the commands', async () => { await userEvent.type(input, 'help{Enter}'); - await expect(await canvas.findByText(/cat resume/)).toBeInTheDocument(); + await expect(await canvas.findByText(/download the resume/)).toBeInTheDocument(); }); await step('ls -a reveals the hidden entry and cat points at the timeline', async () => { diff --git a/src/components/organisms/Greetings/Greetings.tsx b/src/components/organisms/Greetings/Greetings.tsx index f5bc5317..9699e332 100644 --- a/src/components/organisms/Greetings/Greetings.tsx +++ b/src/components/organisms/Greetings/Greetings.tsx @@ -6,6 +6,7 @@ import ScrollDown from '@atoms/ScrollDown'; import TerminalWindow from '@molecules/TerminalWindow'; import type { TerminalWindowLine } from '@molecules/TerminalWindow'; import useCallbackHandlers from '@/hooks/useCallbackHandlers'; +import useClusterStatus from '@hooks/useClusterStatus'; import { useAnimation } from '@context/AnimationContext'; import { slideUpVariants, useMotionEnabled } from '@utils/motion'; import { runCommand } from './commands'; @@ -14,7 +15,7 @@ import './Greetings.css'; const RESUME_PATH = '/resume/Cybersecurity_2025.pdf'; const RESUME_NAME = 'Cybersecurity_2025.pdf'; -const SUGGESTIONS = ['help', 'ls', 'cat resume', 'contact']; +const SUGGESTIONS = ['help', 'ls', 'neofetch', 'cat resume']; const MAX_LINES = 80; // Second line of the opening story; the first comes from the greeting data @@ -34,6 +35,9 @@ const Greetings = () => { const motionOn = useMotionEnabled(animationEnabled); const jobTitle = greetings.jobTitle ?? 'Principal Security Engineer'; const location = greetings.location ?? ''; + const { data: cluster } = useClusterStatus(); + const clusterRef = useRef(cluster); + clusterRef.current = cluster; const counter = useRef(0); const loadedAt = useRef(Date.now()); const nextId = () => `line-${counter.current++}`; @@ -74,6 +78,7 @@ const Greetings = () => { jobTitle, location, uptimeSeconds: Math.round((Date.now() - loadedAt.current) / 1000), + cluster: clusterRef.current, }); if (result.effect?.type === 'clear') { setLines([]); diff --git a/src/components/organisms/Greetings/commands.test.ts b/src/components/organisms/Greetings/commands.test.ts index 193feb03..f95d6268 100644 --- a/src/components/organisms/Greetings/commands.test.ts +++ b/src/components/organisms/Greetings/commands.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect } from 'vitest'; import { runCommand } from './commands'; +import type { ClusterStatusData } from '@/types/cluster'; const ctx = { name: 'Derek Mackley', jobTitle: 'Principal Security Engineer', location: 'Canton, GA', uptimeSeconds: 125 }; const text = (raw: string) => runCommand(raw, ctx).output.map((o) => o.text).join('\n'); @@ -48,8 +49,83 @@ describe('runCommand', () => { expect(runCommand('sudo rm -rf', ctx).effect).toBeUndefined(); }); - it('reports uptime from the page load time', () => { - expect(text('uptime')).toContain('up 2 min'); + it('lists the cluster section first and can open it', () => { + expect(text('ls').startsWith('cluster/')).toBe(true); + expect(runCommand('cd cluster', ctx).effect).toEqual({ type: 'scroll', section: 'cluster' }); + }); + + it('lists the new cluster commands in help', () => { + const help = text('help'); + expect(help).toContain('neofetch'); + expect(help).toContain('kubectl get nodes'); + expect(help).toContain('status'); + }); + + describe('with cluster data', () => { + const badge = (value: string) => ({ title: '', value, color: 'green' }); + const cluster: ClusterStatusData = { + updatedAt: '2026-11-20T19:12:00.000Z', + badges: { + cluster_status: badge('up'), + cluster_node_count: badge('11'), + cluster_pod_count: badge('266'), + services_up: badge('69 up'), + cluster_uptime_days: badge('8d'), + cluster_age_days: badge('646d'), + cluster_cpu_usage: badge('12.3%'), + cluster_memory_usage: badge('13.8%'), + cluster_power_usage: badge('1,074w'), + cluster_alert_count: badge('0'), + talos_version: badge('1.14.5'), + kubernetes_version: badge('1.37.2'), + flux_version: badge('2.10.1'), + }, + }; + const live = (raw: string) => runCommand(raw, { ...ctx, cluster }).output.map((o) => o.text).join('\n'); + + it('uptime prints the cluster uptime and CPU load', () => { + expect(live('uptime')).toContain('up 8 days, 11 nodes, 266 pods'); + expect(live('uptime')).toContain('load average: 12.3% cpu, 13.8% memory'); + }); + + it('kubectl get nodes prints a small table without node names', () => { + const lines = live('kubectl get nodes').split('\n'); + expect(lines[0]).toMatch(/^NODES\s+STATUS/); + expect(lines[1]).toMatch(/^11\s+up\s+1\.14\.5\s+1\.37\.2$/); + }); + + it('rejects other kubectl commands', () => { + expect(runCommand('kubectl get pods', { ...ctx, cluster }).output[0].kind).toBe('error'); + }); + + it('status summarises the badges', () => { + const status = live('status'); + expect(status).toMatch(/pods\s+266/); + expect(status).toMatch(/power\s+1,074 W/); + expect(status).toContain('running for 646 days'); + }); + + it('neofetch shows the turtle beside the facts', () => { + const fetch = live('neofetch'); + expect(fetch).toContain('OS: Talos 1.14.5'); + expect(fetch).toContain('Kubernetes: 1.37.2'); + expect(fetch).toContain('Flux: 2.10.1'); + expect(fetch).toContain('Power: 1,074 W'); + expect(fetch).toContain('>o'); + }); + }); + + describe('without cluster data', () => { + it.each(['status', 'neofetch', 'kubectl get nodes'])('%s says telemetry is offline', (cmd) => { + const result = runCommand(cmd, { ...ctx, cluster: null }); + expect(result.output[0].kind).toBe('error'); + expect(result.output[0].text).toMatch(/telemetry offline/); + }); + + it('uptime falls back to the page time and says so', () => { + expect(text('uptime')).toContain('up 2 min'); + expect(text('uptime')).toMatch(/telemetry offline/); + }); }); it('answers unknown commands in a friendly way', () => { diff --git a/src/components/organisms/Greetings/commands.ts b/src/components/organisms/Greetings/commands.ts index 3c58fab9..28e89d4b 100644 --- a/src/components/organisms/Greetings/commands.ts +++ b/src/components/organisms/Greetings/commands.ts @@ -1,7 +1,9 @@ import type { TerminalLineKind } from '@molecules/TerminalWindow'; +import type { ClusterStatusData } from '@/types/cluster'; +import { ageSentence, badgeText, splitBadgeValue } from '@utils/clusterTelemetry'; /** Page sections the terminal can open, in page order. */ -export const SECTIONS = ['skills', 'experience', 'projects', 'education', 'contact'] as const; +export const SECTIONS = ['cluster', 'skills', 'experience', 'projects', 'education', 'contact'] as const; export type SectionName = (typeof SECTIONS)[number]; export interface CommandContext { @@ -10,6 +12,8 @@ export interface CommandContext { location: string; /** Seconds since the page loaded */ uptimeSeconds: number; + /** Latest cluster reading, or null/absent when telemetry is not available */ + cluster?: ClusterStatusData | null; } export interface CommandOutput { @@ -34,7 +38,10 @@ export const COMMAND_LIST: ReadonlyArray = [ ['cd
', 'jump to a section (also: open
)'], ['cat resume', 'download the resume'], ['contact', 'jump to the contact section'], - ['uptime', 'how long you have been here'], + ['uptime', 'how long the cluster has been up'], + ['status', 'live cluster summary'], + ['kubectl get nodes', 'the cluster nodes'], + ['neofetch', 'the cluster at a glance'], ['ping', 'check that Derek is reachable'], ['clear', 'clear the screen'], ]; @@ -53,6 +60,97 @@ const formatUptime = (seconds: number): string => { return `${Math.floor(seconds / 60)} min`; }; +const OFFLINE = 'telemetry offline: the cluster is not reporting right now'; + +const TURTLE = [ + ' ______', + ' / _ _ \\_', + ' | _| || |_ _>o', + ' \\_\\_||_/_/', + ' /_/ \\_\\', +]; + +const withUnit = (raw: string | null): string | null => { + if (!raw) return null; + const { number, unit } = splitBadgeValue(raw); + if (unit === '%') return `${number}%`; + return unit ? `${number} ${unit}` : number; +}; + +const uptimeOutput = (ctx: CommandContext): CommandOutput[] => { + const data = ctx.cluster ?? null; + const days = badgeText(data, 'cluster_uptime_days'); + if (!data || !days) { + return [out(`up ${formatUptime(ctx.uptimeSeconds)} on this page, 1 visitor`), out(OFFLINE, 'muted')]; + } + const { number } = splitBadgeValue(days); + const parts = [ + `up ${number} ${number === '1' ? 'day' : 'days'}`, + withUnit(badgeText(data, 'cluster_node_count')) && `${withUnit(badgeText(data, 'cluster_node_count'))} nodes`, + withUnit(badgeText(data, 'cluster_pod_count')) && `${withUnit(badgeText(data, 'cluster_pod_count'))} pods`, + ].filter(Boolean); + const cpu = withUnit(badgeText(data, 'cluster_cpu_usage')); + const mem = withUnit(badgeText(data, 'cluster_memory_usage')); + const load = [cpu && `${cpu} cpu`, mem && `${mem} memory`].filter(Boolean).join(', '); + return [ + out(parts.join(', ')), + ...(load ? [out(`load average: ${load}`)] : []), + out(`you have been here ${formatUptime(ctx.uptimeSeconds)}`, 'muted'), + ]; +}; + +const nodesOutput = (data: ClusterStatusData | null): CommandOutput[] => { + const nodes = withUnit(badgeText(data, 'cluster_node_count')); + if (!data || !nodes) return [out(OFFLINE, 'error')]; + const status = badgeText(data, 'cluster_status') ?? 'unknown'; + const k8s = badgeText(data, 'kubernetes_version'); + const talos = badgeText(data, 'talos_version'); + const header = ['NODES'.padEnd(7), 'STATUS'.padEnd(10), talos ? 'TALOS'.padEnd(8) : '', k8s ? 'KUBERNETES' : '']; + const row = [nodes.padEnd(7), status.padEnd(10), talos ? talos.padEnd(8) : '', k8s ?? '']; + return [out(header.join('').trimEnd()), out(row.join('').trimEnd())]; +}; + +const statusOutput = (data: ClusterStatusData | null): CommandOutput[] => { + if (!data) return [out(OFFLINE, 'error')]; + const rows: Array<[string, string | null]> = [ + ['cluster', badgeText(data, 'cluster_status')], + ['nodes', withUnit(badgeText(data, 'cluster_node_count'))], + ['pods', withUnit(badgeText(data, 'cluster_pod_count'))], + ['services', badgeText(data, 'services_up')], + ['uptime', badgeText(data, 'cluster_uptime_days')], + ['age', badgeText(data, 'cluster_age_days')], + ['cpu', withUnit(badgeText(data, 'cluster_cpu_usage'))], + ['memory', withUnit(badgeText(data, 'cluster_memory_usage'))], + ['power', withUnit(badgeText(data, 'cluster_power_usage'))], + ['alerts', badgeText(data, 'cluster_alert_count')], + ]; + const lines = rows.flatMap(([k, v]) => (v ? [out(`${k.padEnd(10)}${v}`)] : [])); + if (lines.length === 0) return [out(OFFLINE, 'error')]; + const age = ageSentence(data); + return [...lines, ...(age ? [out(age, 'muted')] : [])]; +}; + +const neofetchOutput = (data: ClusterStatusData | null): CommandOutput[] => { + const talos = badgeText(data, 'talos_version'); + const k8s = badgeText(data, 'kubernetes_version'); + const flux = badgeText(data, 'flux_version'); + const power = withUnit(badgeText(data, 'cluster_power_usage')); + const facts = [ + talos && `OS: Talos ${talos}`, + k8s && `Kubernetes: ${k8s}`, + flux && `Flux: ${flux}`, + withUnit(badgeText(data, 'cluster_node_count')) && `Nodes: ${withUnit(badgeText(data, 'cluster_node_count'))}`, + withUnit(badgeText(data, 'cluster_pod_count')) && `Pods: ${withUnit(badgeText(data, 'cluster_pod_count'))}`, + power && `Power: ${power}`, + ].filter((f): f is string => Boolean(f)); + if (!data || facts.length === 0) return [out(OFFLINE, 'error')]; + const width = Math.max(...TURTLE.map((l) => l.length)) + 2; + const rows = Math.max(TURTLE.length, facts.length); + return Array.from({ length: rows }, (_, i) => + out(`${(TURTLE[i] ?? '').padEnd(width)}${facts[i] ?? ''}`.trimEnd(), 'success'), + ); +}; + /** * Works out what a typed command prints and does. * Pure: the organism applies the effect (scroll, download, clear). @@ -136,11 +234,20 @@ export const runCommand = (raw: string, ctx: CommandContext): CommandResult => { return { output: [], effect: { type: 'clear' } }; case 'uptime': - return { - output: [ - out(`up ${formatUptime(ctx.uptimeSeconds)}, 1 visitor, load average: mostly agents`), - ], - }; + return { output: uptimeOutput(ctx) }; + + case 'status': + return { output: statusOutput(ctx.cluster ?? null) }; + + case 'neofetch': + return { output: neofetchOutput(ctx.cluster ?? null) }; + + case 'kubectl': { + if (arg === 'get' && /^(nodes?|no)$/.test(args[1] ?? '')) { + return { output: nodesOutput(ctx.cluster ?? null) }; + } + return { output: [out('kubectl: this demo only knows: kubectl get nodes', 'error')] }; + } case 'ping': { const host = arg ?? 'derek'; diff --git a/src/utils/__tests__/clusterTelemetry.test.ts b/src/utils/__tests__/clusterTelemetry.test.ts new file mode 100644 index 00000000..95c74a70 --- /dev/null +++ b/src/utils/__tests__/clusterTelemetry.test.ts @@ -0,0 +1,59 @@ +import { describe, it, expect } from 'vitest'; +import { ageSentence, splitBadgeValue, telemetryTiles, versionItems } from '../clusterTelemetry'; +import type { ClusterStatusData } from '@/types/cluster'; + +const badge = (value: string, color = 'green') => ({ title: '', value, color }); +const data = (alerts: string): ClusterStatusData => ({ + updatedAt: '2026-11-20T19:12:00.000Z', + badges: { + cluster_node_count: badge('11'), + cluster_power_usage: badge('1,074w'), + cluster_memory_usage: badge('13.8%'), + services_up: badge('69 up'), + cluster_uptime_days: badge('8d'), + cluster_age_days: badge('646d', 'red'), + cluster_alert_count: badge(alerts, 'red'), + talos_version: badge('1.14.5', 'blue'), + }, +}); + +describe('splitBadgeValue', () => { + it('splits figure and unit', () => { + expect(splitBadgeValue('1,074w')).toEqual({ number: '1,074', unit: 'W' }); + expect(splitBadgeValue('13.8%')).toEqual({ number: '13.8', unit: '%' }); + expect(splitBadgeValue('69 up')).toEqual({ number: '69', unit: '' }); + expect(splitBadgeValue('8d')).toEqual({ number: '8', unit: 'days' }); + expect(splitBadgeValue('11')).toEqual({ number: '11', unit: '' }); + }); +}); + +describe('telemetryTiles', () => { + it('orders tiles and skips missing badges', () => { + expect(telemetryTiles(data('0')).map((t) => t.label)).toEqual([ + 'Nodes', 'Services up', 'Uptime', 'Power draw', 'Memory', 'Alerts', + ]); + expect(telemetryTiles(null)).toEqual([]); + }); + + it('colours alerts honestly: zero green, any amber with the real count', () => { + const alerts = (n: string) => telemetryTiles(data(n)).find((t) => t.id === 'cluster_alert_count'); + expect(alerts('0')).toMatchObject({ number: '0', tone: 'success' }); + expect(alerts('3')).toMatchObject({ number: '3', tone: 'warning' }); + }); + + it('never gives other tiles a warning or danger tone', () => { + const others = telemetryTiles(data('0')).filter((t) => t.id !== 'cluster_alert_count'); + expect(others.every((t) => t.tone === 'default')).toBe(true); + }); +}); + +describe('versions and age', () => { + it('lists only reported versions', () => { + expect(versionItems(data('0'))).toEqual([{ label: 'Talos', value: '1.14.5' }]); + }); + + it('words the age without a verdict', () => { + expect(ageSentence(data('0'))).toBe('running for 646 days'); + expect(ageSentence(null)).toBeNull(); + }); +}); diff --git a/src/utils/clusterTelemetry.ts b/src/utils/clusterTelemetry.ts new file mode 100644 index 00000000..57070c36 --- /dev/null +++ b/src/utils/clusterTelemetry.ts @@ -0,0 +1,102 @@ +import type { ClusterStatusData } from '@/types/cluster'; + +/** How a reading is coloured. Never red: age and counts are not failures. */ +export type TelemetryTone = 'default' | 'success' | 'warning'; + +export interface SplitValue { + /** The figure, as the cluster wrote it (commas and decimals kept) */ + number: string; + /** Display unit: "W", "%", "days", or empty */ + unit: string; +} + +export interface TelemetryTile { + id: string; + label: string; + number: string; + unit: string; + tone: TelemetryTone; +} + +export interface VersionItem { + label: string; + value: string; +} + +const UNIT_NAMES: Record = { w: 'W', d: 'days', up: '', '%': '%' }; + +/** Splits a badge value: "1,074w" -> 1,074 + W, "13.8%" -> 13.8 + %, "69 up" -> 69. */ +export const splitBadgeValue = (raw: string): SplitValue => { + const match = raw.trim().match(/^(\d[\d,]*(?:\.\d+)?)\s*(.*)$/); + if (!match) return { number: raw.trim(), unit: '' }; + const unit = match[2].trim(); + return { number: match[1], unit: UNIT_NAMES[unit.toLowerCase()] ?? unit }; +}; + +/** Numeric value of a figure like "1,074", or null. */ +export const parseNumber = (figure: string): number | null => { + const n = Number(figure.replace(/,/g, '')); + return Number.isFinite(n) ? n : null; +}; + +const TILES: ReadonlyArray<{ id: string; label: string }> = [ + { id: 'cluster_node_count', label: 'Nodes' }, + { id: 'cluster_pod_count', label: 'Pods' }, + { id: 'services_up', label: 'Services up' }, + { id: 'cluster_uptime_days', label: 'Uptime' }, + { id: 'cluster_power_usage', label: 'Power draw' }, + { id: 'cluster_cpu_usage', label: 'CPU' }, + { id: 'cluster_memory_usage', label: 'Memory' }, + { id: 'cluster_alert_count', label: 'Alerts' }, +]; + +/** Zero alerts is good news; any alert is a warning, not a failure. */ +const toneFor = (id: string, number: string): TelemetryTone => { + if (id !== 'cluster_alert_count') return 'default'; + const n = parseNumber(number); + if (n === null) return 'default'; + return n === 0 ? 'success' : 'warning'; +}; + +/** The stat tiles the cluster reported, in display order. Missing badges are skipped. */ +export const telemetryTiles = (data: ClusterStatusData | null): TelemetryTile[] => + TILES.flatMap(({ id, label }) => { + const badge = data?.badges[id]; + if (!badge) return []; + const { number, unit } = splitBadgeValue(badge.value); + return [{ id, label, number, unit, tone: toneFor(id, number) }]; + }); + +/** Talos, Kubernetes and Flux versions that were reported. */ +export const versionItems = (data: ClusterStatusData | null): VersionItem[] => + ( + [ + ['Talos', 'talos_version'], + ['Kubernetes', 'kubernetes_version'], + ['Flux', 'flux_version'], + ] as const + ).flatMap(([label, id]) => { + const value = data?.badges[id]?.value.trim(); + return value ? [{ label, value }] : []; + }); + +/** "running for 646 days", or null when the age was not reported. */ +export const ageSentence = (data: ClusterStatusData | null): string | null => { + const raw = data?.badges.cluster_age_days?.value; + if (!raw) return null; + const n = parseNumber(splitBadgeValue(raw).number); + if (n === null) return null; + return `running for ${n.toLocaleString('en-US')} ${n === 1 ? 'day' : 'days'}`; +}; + +/** Local time of the last reading, e.g. "7:12 PM", or null if the stamp is invalid. */ +export const formatUpdated = (iso: string): string | null => { + const date = new Date(iso); + return Number.isNaN(date.getTime()) + ? null + : date.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }); +}; + +/** Raw badge text, or null. */ +export const badgeText = (data: ClusterStatusData | null, id: string): string | null => + data?.badges[id]?.value.trim() || null;