Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
grade forge label chips for the active theme so pale labels stay legible on day themes
[._.]/ Adam Eivy3e6a812c6d9b
diff --git a/client/src/components/apps/tabs/IssuesTab.jsx b/client/src/components/apps/tabs/IssuesTab.jsxindex b528ad6806..a591ed9675 100644--- a/client/src/components/apps/tabs/IssuesTab.jsx+++ b/client/src/components/apps/tabs/IssuesTab.jsx@@ -9,7 +9,9 @@ import Banner from '../../ui/Banner';import Pill from '../../ui/Pill';import toast from '../../ui/Toast';import ProviderModelSelector from '../../ProviderModelSelector';+import { useThemeContext } from '../../ThemeContext';import useProviderModels from '../../../hooks/useProviderModels';+import { chipColors } from '../../../lib/chipContrast';import { isProcessProvider } from '../../../utils/providers';import * as api from '../../../services/api';import socket from '../../../services/socket';@@ -59,24 +61,25 @@ const EMPTY_REASONS = {/*** Label chips carry the forge's own color, which is arbitrary per-repo data —* so it can't be a Tailwind class (those must be literal strings in source).- * Render it as a tinted chip via inline style: the color for text and border,- * a low-alpha wash of it for the background, which stays legible on the dark- * surface for the full hue range. A label with no color gets no inline style, so+ * Render it as a tinted chip via inline style: a low-alpha wash of the label's+ * own color for the background, and `chipContrast` for the text/border, which+ * keeps the hue but moves its lightness until it clears WCAG AA on the ACTIVE+ * theme mode. Verbatim label color only ever worked on night themes — GitHub's+ * pale defaults (`plan` #fef2c0, `effort:*` #c5def5) rendered as ~1.1:1 on the+ * day themes, i.e. invisible.+ *+ * A label with no color — or a color we can't parse — gets no inline style, so* the chip keeps its own neutral look (the `muted` Pill tone on a row chip).*/-const labelChipStyle = (color) => (color ? {- color,- borderColor: `${color}66`,- backgroundColor: `${color}1a`-} : undefined);-function LabelChip({ label }) {+ const { theme } = useThemeContext();+ const style = chipColors(label.color, theme?.mode);return (<Pillsize="xs"- tone={label.color ? 'bare' : 'muted'}+ tone={style ? 'bare' : 'muted'}title={label.description || undefined}- style={labelChipStyle(label.color)}+ style={style}>{label.name}</Pill>@@ -98,6 +101,16 @@ function LabelChip({ label }) {* routinely runs 20+ labels wide.*/function LabelFilterChip({ facet, hidden, onToggle }) {+ const { theme } = useThemeContext();+ const style = hidden ? null : chipColors(facet.color, theme?.mode);+ // The theme utilities carry `!important` (index.css remaps `.bg-port-bg`,+ // `.border-port-border`, and day-mode `.text-gray-300`), and author+ // `!important` beats an inline declaration — so a chip that ships BOTH renders+ // in theme neutrals with its graded color silently dead. Emit the neutrals+ // only when there's no graded style to paint, the way `Pill tone="bare"` does.+ const neutral = hidden+ ? 'border-port-border bg-port-bg text-gray-500 line-through opacity-60 hover:opacity-100'+ : 'border-port-border bg-port-bg text-gray-300 hover:opacity-80';return (<buttontype="button"@@ -108,11 +121,9 @@ function LabelFilterChip({ facet, hidden, onToggle }) {? `${facet.description} — click to ${hidden ? 'show' : 'hide'} these issues`: `Click to ${hidden ? 'show' : 'hide'} issues labeled ${facet.name}`}className={`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] transition-opacity ${- hidden- ? 'border-port-border bg-port-bg text-gray-500 line-through opacity-60 hover:opacity-100'- : 'border-port-border bg-port-bg text-gray-300 hover:opacity-80'+ style ? 'hover:opacity-80' : neutral}`}- style={hidden ? undefined : labelChipStyle(facet.color)}+ style={style}>{facet.name}<span className="font-mono opacity-70">{facet.count}</span>diff --git a/client/src/components/apps/tabs/IssuesTab.test.jsx b/client/src/components/apps/tabs/IssuesTab.test.jsxindex 2ee8ed5c42..7f840d9d10 100644--- a/client/src/components/apps/tabs/IssuesTab.test.jsx+++ b/client/src/components/apps/tabs/IssuesTab.test.jsx@@ -17,6 +17,14 @@ const { socketHandlers, socketMock } = vi.hoisted(() => {vi.mock('../../../services/socket', () => ({ default: socketMock }));+// Label chips grade their color against the ACTIVE theme mode, so the mode has+// to be steerable per test. The real provider runs a settings fetch on mount,+// which this suite has no business exercising.+const { themeMode } = vi.hoisted(() => ({ themeMode: { current: 'night' } }));+vi.mock('../../ThemeContext', () => ({+ useThemeContext: () => ({ theme: { mode: themeMode.current } }),+}));+vi.mock('../../../services/api', () => ({getAppIssues: vi.fn(),createSlashdoTask: vi.fn(),@@ -24,6 +32,7 @@ vi.mock('../../../services/api', () => ({}));import * as api from '../../../services/api';+import { chipColors, parseColor } from '../../../lib/chipContrast';import IssuesTab from './IssuesTab';const ISSUE = {@@ -60,6 +69,7 @@ const renderTab = async () => {};beforeEach(() => {+ themeMode.current = 'night';socketHandlers.clear();socketMock.on.mockClear();socketMock.off.mockClear();@@ -88,6 +98,39 @@ describe('IssuesTab', () => {expect(screen.getByText('acme/widget')).toBeInTheDocument();});+ // The AA guarantee itself is `lib/chipContrast.test.js`'s job. What this suite+ // owns is the wiring: the chip is styled for the ACTIVE theme mode, not a+ // hardcoded one. #fef2c0 is GitHub's default pale yellow — the color that+ // rendered as white-on-cream before chips were graded per mode.+ it.each(['day', 'night'])('styles label chips for the %s theme mode', async (mode) => {+ themeMode.current = mode;+ api.getAppIssues.mockResolvedValue(okPayload([{+ ...ISSUE,+ labels: [{ name: 'plan', color: '#fef2c0', description: 'Planned work' }],+ }]));+ await renderTab();++ const chip = await screen.findByTitle('Planned work');+ expect(chip).toHaveTextContent('plan');+ // parseColor on both sides: jsdom normalizes an inline `#rrggbb` to `rgb(…)`,+ // so comparing the raw strings would pass no matter which mode was used.+ const other = mode === 'day' ? 'night' : 'day';+ expect(parseColor(chip.style.color)).toEqual(parseColor(chipColors('#fef2c0', mode).color));+ expect(parseColor(chip.style.color)).not.toEqual(parseColor(chipColors('#fef2c0', other).color));+ });++ it('leaves a colorless label on the neutral chip instead of an inline color', async () => {+ api.getAppIssues.mockResolvedValue(okPayload([{+ ...ISSUE,+ labels: [{ name: 'feature', color: null, description: 'No forge color' }],+ }]));+ await renderTab();++ const chip = await screen.findByTitle('No forge color');+ expect(chip.style.color).toBe('');+ expect(chip.className).toContain('text-gray-300');+ });+it('keeps the description collapsed until the user expands it', async () => {await renderTab();@@ -325,6 +368,32 @@ describe('IssuesTab', () => {expect(await screen.findByText('Crash on save')).toBeInTheDocument();});+ it('never ships a filter chip with both a graded color and the theme utilities that override it', async () => {+ // `.bg-port-bg` / `.border-port-border` / day-mode `.text-gray-300` are all+ // `!important` in index.css, and author `!important` beats an inline style —+ // so a chip carrying both renders in theme neutrals with its label color+ // silently dead. Colored chips drop the utilities; colorless ones keep them.+ api.getAppIssues.mockResolvedValue(okPayload([+ ISSUE,+ { ...ISSUE, number: 43, labels: [{ name: 'feature', color: null, description: '' }] },+ ]));+ await renderTab();++ const colored = await screen.findByRole('button', { name: 'bug (1)' });+ expect(colored.style.color).not.toBe('');+ expect(colored.className).not.toMatch(/text-gray-300|bg-port-bg|border-port-border/);++ const colorless = screen.getByRole('button', { name: 'feature (1)' });+ expect(colorless.style.color).toBe('');+ expect(colorless.className).toContain('text-gray-300');++ // Hidden chips are struck through in theme neutrals — no inline color to lose.+ fireEvent.click(colored);+ const hidden = await screen.findByRole('button', { name: 'bug (1)' });+ expect(hidden.style.color).toBe('');+ expect(hidden.className).toContain('line-through');+ });+it('resets label and assignee filters when the app changes', async () => {const inProgress = {...ISSUE,diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex b70ae7d57f..319832fb42 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -99,6 +99,7 @@ grep -i "what you want to do" client/src/lib/README.md| `youtubeUrl.js` | `isYoutubeVideoUrl(text)` / `youtubeVideoId(url)` — single-video YouTube URL detection. Client mirror of `YOUTUBE_INGEST_URL_RE` in `server/services/youtubeIngest.js` (behavioral parity pinned by `server/lib/youtubeUrl.mirror.test.js`); deliberately excludes playlists and channels. Quick Capture uses it to swap to the ingest submit path and reveal the ingest options panel. Also `INGEST_OPTIONS` — the single table of the three ingest artifacts (`key` / `settingKey` / `fallback` / `label` / `hint`) — plus `defaultIngestOptions()` and `ingestOptionsFromSettings(settings)`. Everything that enumerates the switches derives from that table; add an artifact there, not at each call site. || `boundedMap.js` | `evictOldest(map, max, onEvict?)` — evict oldest-first (`map.keys().next().value`) until a Map is within `max`, with an optional per-evicted-key teardown callback for a companion timer map; `ORPHAN_BUFFER_MAX` (64), the shared cap for the orphan-event race-buffers. The one home for the "stash an unmatched event in a `jobId → …` Map, evict the oldest on overflow" idiom shared by `useSceneRenderLifecycle`, `useImageGenQueue`, and `clientErrorReporter`. || `buildStamp.js` | Does the bundle this browser loaded come from the same git commit the API is running (#4694)? `SERVED_BUILD_ID` (the server-injected build-id meta tag; null under `npm run dev`) is the trust gate — `BUNDLE_STAMP` is the raw `__BUILD_STAMP__` Vite define, `TRUSTED_BUNDLE_STAMP` is it only when the page came from a real build, since the define is frozen at dev-server start while HMR serves every commit since. **Display or compare `TRUSTED_BUNDLE_STAMP`, never `BUNDLE_STAMP`.** `compareBuildStamps(bundle, server)` → `match`/`mismatch`/`unknown` (absent on either side is always `unknown`); `resolveBuildFrame(signals, {embeddedBuildId})` → `reload`/`drift`/`null`, the two staleness kinds that need different remedies; `createBuildDriftWatcher({embeddedBuildId, fetchIdentity, onShow, onClear})` is the tested state machine that merges the pushed bundle hash with the fetched commit and latches once per kind; `describeBuild({commit, branch, dirty})` renders one line. Consumed by `services/socket.js`, `components/Layout.jsx`, and `components/system-resources/BuildStampPanel.jsx`. |+| `chipContrast.js` | Contrast-safe chip colors for arbitrary, externally-supplied colors — forge issue-label hexes first (`apps/tabs/IssuesTab.jsx`). `chipColors(color, mode)` → `{ color, borderColor, backgroundColor }` for an inline `style` (null when the color is missing/unparseable, so the caller falls back to a neutral chip): the wash keeps the label's own color, while the text/border keep its HUE and move only its LIGHTNESS, by the smallest step that clears WCAG AA against the chip's own tint on the ACTIVE theme mode. Memoized per (color, mode). Graded against `SURFACES` — the worst-case surface per mode (darkest `day`, lightest `night`), which the test re-derives from `THEMES` so a new theme can't silently escape the grading. Plus the primitives: `parseColor` (`#rgb`/`#rrggbb`/bare hex/`rgb()`), `relativeLuminance`, `contrastRatio`, `blend`, `chipBackdrop`, `rgbToHsl`/`hslToRgb`, `ensureReadable`. Pure — the caller passes `theme.mode`, nothing here reads the DOM. || `clientErrorReporter.js` | `reportClientError({ type, error?, message?, ... })` — POSTs window.onerror + unhandledrejection events to `/api/client-errors` with throttle + dedup, dropping browser-extension errors (see `extensionErrors.js`) before either gate. Wired from `main.jsx`; never call directly from React components. || `clinicianReport.js` | Pure builders for the MeatSpace clinician-export view (`/meatspace/export`). `buildClinicianReport({ tests, config })` → structured report model (blood panels grouped by category with reference ranges + out-of-range flags, plus a lifestyle summary); `reportToMarkdown(report)` → copy-paste markdown. Reuses the Blood tab's `REFERENCE_RANGES` / `getBloodValueStatus` so printed flags match the UI. Also exports `buildBloodTestModel`, `buildLifestyleModel`, `getCategoryForKey`, `formatRange`. || `quotaBurnPatch.js` | `mergeQuotaBurnPatch(base, patch)` — mirrors the server's quota-burn config merge (top-level + per-family keys merge, a family's `jobs` array replaces) so the Quota Burn page can apply an edit optimistically and accumulate debounced edits into one PUT body. `applyQuotaBurnPreset(job, preset)` / `jobFromPreset(preset, { id, appId })` — copy a catalog prompt preset into a job, preserving the user's own step name and app choice. `quotaBurnJobIsSpent(job, ranAt)` — whether a `run once` step has had its one dispatch, gated on the optimistic config's own `runOnce` so a just-ticked checkbox reads as spent before the save round-trips (the client mirror of the server's `jobIsSpent`). `UNLIMITED_DISPATCHES` / `isUnlimitedDispatchCap(cap)` / `dispatchCapInput(value)` — the -1 "no dispatch cap" sentinel (the default), mirrored from the server. |diff --git a/client/src/lib/chipContrast.js b/client/src/lib/chipContrast.jsnew file mode 100644index 0000000000..88cc7e8252--- /dev/null+++ b/client/src/lib/chipContrast.js@@ -0,0 +1,219 @@+// Contrast-safe chip colors for arbitrary, externally-supplied colors — forge+// issue-label hexes being the first consumer (`IssuesTab`).+//+// The problem this solves: a forge label color is repo data, picked by whoever+// created the label with no idea which PortOS theme it will land on. Rendering+// it verbatim as chip text works on the night themes it was eyeballed against+// and falls apart on the day themes — GitHub's default pale yellows/greens+// (`plan` at #fef2c0, `effort:*` at similar tints) come out as white-on-cream,+// i.e. invisible. The mirror failure exists on night themes for a very dark+// label color.+//+// The fix keeps the label's HUE (the thing the user recognizes it by) and moves+// only its LIGHTNESS, by the smallest step that clears WCAG AA against the chip's+// own tinted backdrop. A label already legible on the active mode is returned+// untouched.+//+// Pure + side-effect free: the caller passes the active theme `mode`+// (`'day' | 'night'`, from `useThemeContext().theme.mode`); nothing here reads+// the DOM.++import { THEMES } from '../themes/portosThemes.js';+import { clamp } from '../utils/formatters.js';++// `"234 228 219"` (the `--port-*` color-var form) → `{ r, g, b }`.+const parseTriple = (triple) => {+ const [r, g, b] = String(triple).trim().split(/\s+/).map(Number);+ return { r, g, b };+};++// Chip background is a low-alpha wash of the ORIGINAL color (so the tint still+// reads as that label's hue) and the border a stronger one of the adjusted color.+export const WASH_ALPHA = 0.16;+export const BORDER_ALPHA = 0.4;++// WCAG 2.1 AA for normal text.+const MIN_CONTRAST = 4.5;++const byte = (n) => clamp(Math.round(n), 0, 255);++/**+ * Parse a color into `{ r, g, b }` (0–255), or null when it isn't a form we can+ * reason about. Handles `#rgb`, `#rrggbb`, bare hex with no `#` (what the GitHub+ * API returns before `appIssues.js` prefixes it), and `rgb()`/`rgba()` (what a+ * browser hands back when reading an inline style). Named CSS colors and `hsl()`+ * return null — the caller falls back to a neutral chip rather than shipping an+ * unreadable guess.+ */+export function parseColor(raw) {+ if (typeof raw !== 'string') return null;+ const value = raw.trim().toLowerCase();+ if (!value) return null;++ const rgbMatch = value.match(/^rgba?\(([^)]+)\)$/);+ if (rgbMatch) {+ const parts = rgbMatch[1].split(/[\s,/]+/).filter(Boolean).map(Number);+ if (parts.length < 3 || parts.slice(0, 3).some(Number.isNaN)) return null;+ return { r: clamp(parts[0], 0, 255), g: clamp(parts[1], 0, 255), b: clamp(parts[2], 0, 255) };+ }++ // Expand `#rgb` shorthand by doubling each nibble, then parse the one 6-digit form.+ const hex = value.replace(/^#/, '').replace(/^[0-9a-f]{3}$/, (m) => m.replace(/./g, (c) => c + c));+ if (!/^[0-9a-f]{6}$/.test(hex)) return null;+ return {+ r: parseInt(hex.slice(0, 2), 16),+ g: parseInt(hex.slice(2, 4), 16),+ b: parseInt(hex.slice(4, 6), 16),+ };+}++/** `{ r, g, b }` → `#rrggbb`. */+const toHex = ({ r, g, b }) => `#${[r, g, b].map((n) => byte(n).toString(16).padStart(2, '0')).join('')}`;++/** `{ r, g, b }` + alpha → `rgba(r, g, b, a)`. */+const toRgba = ({ r, g, b }, alpha) => `rgba(${byte(r)}, ${byte(g)}, ${byte(b)}, ${alpha})`;++/** WCAG relative luminance (0 = black, 1 = white). */+export function relativeLuminance({ r, g, b }) {+ const channel = (n) => {+ const c = n / 255;+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;+ };+ return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);+}++/**+ * The WORST-case chip surface in each theme mode, derived from the shipped+ * themes rather than hand-copied: the darkest surface a `day` theme puts a chip+ * on (dark text needs the most help there) and the lightest a `night` theme+ * does. Grading against these means every other surface of that mode lands with+ * MORE contrast, never less — and a newly added theme is covered automatically+ * instead of silently escaping the guarantee.+ *+ * Both `--port-bg` and `--port-card` count: a chip can sit on the page or on a+ * card, so neither may fall outside the reference.+ */+export const SURFACES = Object.values(THEMES).reduce((acc, theme) => {+ const mode = theme.mode === 'day' ? 'day' : 'night';+ for (const token of ['--port-bg', '--port-card']) {+ const surface = parseTriple(theme.colors[token]);+ const worse = mode === 'day'+ ? relativeLuminance(surface) < relativeLuminance(acc[mode])+ : relativeLuminance(surface) > relativeLuminance(acc[mode]);+ if (worse) acc[mode] = surface;+ }+ return acc;+}, { day: { r: 255, g: 255, b: 255 }, night: { r: 0, g: 0, b: 0 } });++/** WCAG contrast ratio between two opaque colors (1–21). */+export function contrastRatio(a, b) {+ const la = relativeLuminance(a);+ const lb = relativeLuminance(b);+ return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);+}++/** Composite `fg` at `alpha` over opaque `bg` (source-over). */+export function blend(fg, bg, alpha) {+ return {+ r: fg.r * alpha + bg.r * (1 - alpha),+ g: fg.g * alpha + bg.g * (1 - alpha),+ b: fg.b * alpha + bg.b * (1 - alpha),+ };+}++/** RGB (0–255) → HSL with h in [0,360), s/l in [0,1]. */+export function rgbToHsl({ r, g, b }) {+ const rn = r / 255;+ const gn = g / 255;+ const bn = b / 255;+ const max = Math.max(rn, gn, bn);+ const min = Math.min(rn, gn, bn);+ const l = (max + min) / 2;+ const d = max - min;+ if (d === 0) return { h: 0, s: 0, l };+ const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);+ let h;+ if (max === rn) h = ((gn - bn) / d) % 6;+ else if (max === gn) h = (bn - rn) / d + 2;+ else h = (rn - gn) / d + 4;+ h *= 60;+ return { h: (h + 360) % 360, s, l };+}++/** HSL (h in [0,360), s/l in [0,1]) → RGB (0–255). */+export function hslToRgb({ h, s, l }) {+ const c = (1 - Math.abs(2 * l - 1)) * s;+ const hp = ((h % 360) + 360) % 360 / 60;+ const x = c * (1 - Math.abs((hp % 2) - 1));+ const m = l - c / 2;+ const [r1, g1, b1] = hp < 1 ? [c, x, 0]+ : hp < 2 ? [x, c, 0]+ : hp < 3 ? [0, c, x]+ : hp < 4 ? [0, x, c]+ : hp < 5 ? [x, 0, c]+ : [c, 0, x];+ return {+ r: Math.round((r1 + m) * 255),+ g: Math.round((g1 + m) * 255),+ b: Math.round((b1 + m) * 255),+ };+}++/** What a chip's text actually sits on: the wash of `rgb` over that mode's surface. */+export function chipBackdrop(rgb, mode) {+ return blend(rgb, SURFACES[mode] ?? SURFACES.night, WASH_ALPHA);+}++/**+ * Move `rgb` toward the smallest lightness that clears `MIN_CONTRAST` against+ * `backdrop`, keeping hue and saturation. The direction comes from the backdrop+ * itself — a light backdrop darkens, a dark one lightens — so the surface and+ * the adjustment can never disagree. Returns the input untouched when it already+ * clears; returns the extreme (pure black / pure white for that hue) when nothing+ * in that direction does, since a hue that can't reach AA is still far more+ * legible at the extreme than where it started.+ */+export function ensureReadable(rgb, backdrop) {+ if (contrastRatio(rgb, backdrop) >= MIN_CONTRAST) return rgb;+ const { h, s, l } = rgbToHsl(rgb);+ const step = relativeLuminance(backdrop) > 0.5 ? -0.02 : 0.02;+ let best = rgb;+ for (let next = l + step; next >= 0 && next <= 1; next += step) {+ best = hslToRgb({ h, s, l: next });+ if (contrastRatio(best, backdrop) >= MIN_CONTRAST) return best;+ }+ return best;+}++// A repo's label palette is a few dozen colors that repeat on every row, and the+// lightness search runs up to ~50 iterations per miss — so memoize per+// (color, mode). The cache also hands React a stable `style` object across+// renders, which it can skip diffing.+const cache = new Map();++/**+ * Chip styles for an arbitrary color under the active theme mode:+ * `{ color, borderColor, backgroundColor }` ready to spread into an inline+ * `style`, or null when the color is missing/unparseable so the caller can fall+ * back to its own neutral chip.+ */+export function chipColors(raw, mode) {+ const key = `${raw}|${mode}`;+ if (cache.has(key)) return cache.get(key);++ const rgb = parseColor(raw);+ // Wash + border stay translucent so they composite against each theme's real+ // surface. Grading happens against the reference surface, which is the worst+ // case for its mode — every other surface of that mode lands with MORE+ // contrast, never less.+ const backdrop = rgb && chipBackdrop(rgb, mode);+ const text = rgb && ensureReadable(rgb, backdrop);+ const style = rgb ? {+ color: toHex(text),+ borderColor: toRgba(text, BORDER_ALPHA),+ backgroundColor: toRgba(rgb, WASH_ALPHA),+ } : null;++ cache.set(key, style);+ return style;+}diff --git a/client/src/lib/chipContrast.test.js b/client/src/lib/chipContrast.test.jsnew file mode 100644index 0000000000..ebe7be3de0--- /dev/null+++ b/client/src/lib/chipContrast.test.js@@ -0,0 +1,240 @@+import { describe, it, expect } from 'vitest';+import {+ BORDER_ALPHA,+ SURFACES,+ WASH_ALPHA,+ blend,+ chipBackdrop,+ chipColors,+ contrastRatio,+ ensureReadable,+ hslToRgb,+ parseColor,+ relativeLuminance,+ rgbToHsl,+} from './chipContrast.js';+import { THEMES } from '../themes/portosThemes.js';++// The GitHub default palette that motivated this module, plus the two hues that+// were already marginal on night themes and one near-black that only night+// breaks on.+const FORGE_COLORS = {+ plan: '#fef2c0',+ 'effort:medium': '#c5def5',+ 'area:devtools': '#bfd4f2',+ enhancement: '#a2eeef',+ 'needs-input': '#d4c5f9',+ 'repo-study': '#fbca04',+ ux: '#d93f0b',+ bug: '#d73a4a',+ 'model:light': '#0e8a16',+ 'model:medium': '#1d76db',+ 'good first issue': '#7057ff',+ midnight: '#0b0b23',+ white: '#ffffff',+ black: '#000000',+};++// What the rendered chip text actually sits on, from a hex string.+const backdropFor = (color, mode) => chipBackdrop(parseColor(color), mode);++describe('parseColor', () => {+ it('parses #rrggbb', () => {+ expect(parseColor('#1d76db')).toEqual({ r: 0x1d, g: 0x76, b: 0xdb });+ });++ it('parses #rgb shorthand by doubling each nibble', () => {+ expect(parseColor('#f0a')).toEqual({ r: 255, g: 0, b: 170 });+ });++ it('parses bare hex — what the GitHub API returns before appIssues.js prefixes it', () => {+ expect(parseColor('d73a4a')).toEqual(parseColor('#d73a4a'));+ });++ it('is case-insensitive and tolerates surrounding whitespace', () => {+ expect(parseColor(' #D73A4A ')).toEqual(parseColor('#d73a4a'));+ });++ it('parses rgb() and rgba(), dropping alpha', () => {+ expect(parseColor('rgb(29, 118, 219)')).toEqual({ r: 29, g: 118, b: 219 });+ expect(parseColor('rgba(29 118 219 / 0.5)')).toEqual({ r: 29, g: 118, b: 219 });+ });++ it('returns null for values it cannot reason about, rather than guessing', () => {+ // A named color or hsl() would need a lookup/second parser; the caller's+ // neutral-chip fallback is the honest answer.+ for (const bad of [null, undefined, 42, '', ' ', 'rebeccapurple', 'hsl(210 50% 40%)', '#12345', 'rgb(1, 2)']) {+ expect(parseColor(bad)).toBeNull();+ }+ });+});++describe('relativeLuminance / contrastRatio', () => {+ it('anchors black at 0 and white at 1', () => {+ expect(relativeLuminance({ r: 0, g: 0, b: 0 })).toBeCloseTo(0, 6);+ expect(relativeLuminance({ r: 255, g: 255, b: 255 })).toBeCloseTo(1, 6);+ });++ it('gives black-on-white the WCAG maximum of 21', () => {+ expect(contrastRatio({ r: 0, g: 0, b: 0 }, { r: 255, g: 255, b: 255 })).toBeCloseTo(21, 4);+ });++ it('is symmetric and bottoms out at 1 for identical colors', () => {+ const a = { r: 29, g: 118, b: 219 };+ const b = { r: 234, g: 228, b: 219 };+ expect(contrastRatio(a, b)).toBeCloseTo(contrastRatio(b, a), 10);+ expect(contrastRatio(a, a)).toBeCloseTo(1, 10);+ });+});++describe('blend', () => {+ it('at alpha 1 is the foreground and at alpha 0 the background', () => {+ const fg = { r: 255, g: 0, b: 0 };+ const bg = { r: 0, g: 0, b: 255 };+ expect(blend(fg, bg, 1)).toEqual(fg);+ expect(blend(fg, bg, 0)).toEqual(bg);+ });++ it('lands halfway at alpha 0.5', () => {+ expect(blend({ r: 200, g: 100, b: 0 }, { r: 0, g: 0, b: 100 }, 0.5))+ .toEqual({ r: 100, g: 50, b: 50 });+ });+});++describe('rgbToHsl / hslToRgb', () => {+ it('round-trips saturated hues', () => {+ for (const hex of Object.values(FORGE_COLORS)) {+ const rgb = parseColor(hex);+ expect(hslToRgb(rgbToHsl(rgb))).toEqual(rgb);+ }+ });++ it('reports achromatic colors as zero-saturation', () => {+ expect(rgbToHsl({ r: 128, g: 128, b: 128 })).toEqual({ h: 0, s: 0, l: 128 / 255 });+ });+});++describe('ensureReadable', () => {+ it('leaves a color that already clears AA untouched', () => {+ const rgb = parseColor('#0b0b23');+ const backdrop = backdropFor('#0b0b23', 'day');+ expect(contrastRatio(rgb, backdrop)).toBeGreaterThanOrEqual(4.5);+ expect(ensureReadable(rgb, backdrop)).toEqual(rgb);+ });++ it('darkens on day and lightens on night — never the wrong direction', () => {+ const rgb = parseColor('#d73a4a');+ const day = ensureReadable(rgb, backdropFor('#d73a4a', 'day'));+ const night = ensureReadable(rgb, backdropFor('#d73a4a', 'night'));+ expect(relativeLuminance(day)).toBeLessThan(relativeLuminance(rgb));+ expect(relativeLuminance(night)).toBeGreaterThan(relativeLuminance(rgb));+ });++ it('preserves hue — the thing the user recognizes the label by', () => {+ for (const hex of ['#fef2c0', '#c5def5', '#0e8a16', '#7057ff']) {+ const rgb = parseColor(hex);+ for (const mode of ['day', 'night']) {+ const out = ensureReadable(rgb, backdropFor(hex, mode));+ expect(rgbToHsl(out).h).toBeCloseTo(rgbToHsl(rgb).h, 0);+ }+ }+ });++ it('moves the SMALLEST step that clears AA — one step back would fail', () => {+ const hex = '#fef2c0';+ const rgb = parseColor(hex);+ const backdrop = backdropFor(hex, 'day');+ const out = ensureReadable(rgb, backdrop);+ expect(contrastRatio(out, backdrop)).toBeGreaterThanOrEqual(4.5);+ // Step back toward the original by one 2% lightness increment.+ const { h, s, l } = rgbToHsl(out);+ const undone = hslToRgb({ h, s, l: Math.min(1, l + 0.02) });+ expect(contrastRatio(undone, backdrop)).toBeLessThan(4.5);+ });++ it('returns the extreme rather than the input when no lightness clears AA', () => {+ // Pure white against a white-washed light surface can never reach 4.5:1 on+ // day — the loop must still hand back the darkest end, not give up at white.+ const white = { r: 255, g: 255, b: 255 };+ const out = ensureReadable(white, blend(white, SURFACES.day, WASH_ALPHA));+ expect(relativeLuminance(out)).toBeLessThan(relativeLuminance(white));+ });+});++describe('chipColors', () => {+ it('returns null for a missing or unparseable color so the caller can fall back', () => {+ for (const bad of [null, undefined, '', 'rebeccapurple']) {+ expect(chipColors(bad, 'day')).toBeNull();+ expect(chipColors(bad, 'night')).toBeNull();+ }+ });++ it.each(['day', 'night'])('clears WCAG AA for every forge color on %s themes', (mode) => {+ for (const [name, hex] of Object.entries(FORGE_COLORS)) {+ const style = chipColors(hex, mode);+ const ratio = contrastRatio(parseColor(style.color), backdropFor(hex, mode));+ expect(ratio, `${name} on ${mode}`).toBeGreaterThanOrEqual(4.5);+ }+ });++ it('is the regression guard for the day-theme bug: the old verbatim color failed AA', () => {+ // #fef2c0 (`plan`) rendered as its own hex was ~1.1:1 on cream — invisible.+ const backdrop = backdropFor('#fef2c0', 'day');+ expect(contrastRatio(parseColor('#fef2c0'), backdrop)).toBeLessThan(1.5);+ expect(contrastRatio(parseColor(chipColors('#fef2c0', 'day').color), backdrop))+ .toBeGreaterThanOrEqual(4.5);+ });++ it('keeps the wash and border translucent so they composite on each theme surface', () => {+ const style = chipColors('#1d76db', 'night');+ const { r, g, b } = parseColor(style.color);+ expect(style.backgroundColor).toBe(`rgba(29, 118, 219, ${WASH_ALPHA})`);+ expect(style.borderColor).toBe(`rgba(${r}, ${g}, ${b}, ${BORDER_ALPHA})`);+ expect(style.color).toMatch(/^#[0-9a-f]{6}$/);+ });++ it('washes with the ORIGINAL color, not the adjusted one — the tint keeps the label hue', () => {+ const style = chipColors('#fef2c0', 'day');+ expect(style.backgroundColor).toContain('254, 242, 192');+ expect(style.color).not.toBe('#fef2c0');+ });++ it('treats an unknown mode as night, matching the theme default', () => {+ expect(chipColors('#d73a4a', undefined)).toEqual(chipColors('#d73a4a', 'night'));+ });++ it('picks opposite adjustments for the same color across modes', () => {+ const day = chipColors('#7057ff', 'day');+ const night = chipColors('#7057ff', 'night');+ expect(relativeLuminance(parseColor(day.color)))+ .toBeLessThan(relativeLuminance(parseColor(night.color)));+ });+});++// Every AA guarantee above rests on SURFACES really being the worst case per+// mode. It's derived from THEMES rather than hand-copied, so a new theme is+// covered automatically — this asserts the derivation actually holds, and that+// it covers both chip-bearing surfaces (a chip sits on the page OR on a card).+describe('SURFACES bounds every shipped theme', () => {+ const surfacesOf = (theme) => ['--port-bg', '--port-card'].map((token) => {+ const [r, g, b] = theme.colors[token].split(/\s+/).map(Number);+ return { r, g, b };+ });++ it.each(['day', 'night'])('%s themes never render a chip on a harder surface', (mode) => {+ const reference = relativeLuminance(SURFACES[mode]);+ const themes = Object.values(THEMES).filter((t) => (t.mode === 'day' ? 'day' : 'night') === mode);+ expect(themes.length).toBeGreaterThan(0);++ for (const theme of themes) {+ for (const surface of surfacesOf(theme)) {+ const lum = relativeLuminance(surface);+ // Day grades dark text, so the darkest day surface is the hardest;+ // night grades light text, so the lightest night surface is.+ const message = `${theme.id} surface luminance ${lum.toFixed(3)} vs reference ${reference.toFixed(3)}`;+ if (mode === 'day') expect(lum, message).toBeGreaterThanOrEqual(reference);+ else expect(lum, message).toBeLessThanOrEqual(reference);+ }+ }+ });+});diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 8bf430e19b..1936c2fa3d 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -72,6 +72,7 @@ export * from './audioRecorder.js';export * from './bareUrl.js';export * from './boundedMap.js';export * from './buildStamp.js';+export * from './chipContrast.js';export * from './clientErrorReporter.js';export * from './clinicianReport.js';export * from './clipboard.js';