π OpenHands: AI-Driven Development
refactor(markdown): give alerts readable theme roles (#18696)
Engel Nyst87b9496342c9
diff --git a/__tests__/components/features/files-tab/file-content-viewer.test.tsx b/__tests__/components/features/files-tab/file-content-viewer.test.tsxindex 734dbb2dcd..25647b06a0 100644--- a/__tests__/components/features/files-tab/file-content-viewer.test.tsx+++ b/__tests__/components/features/files-tab/file-content-viewer.test.tsx@@ -1,11 +1,21 @@import React from "react";-import { render, screen } from "@testing-library/react";+import { act, render, screen } from "@testing-library/react";+import { readFileSync } from "node:fs";+import { resolve } from "node:path";+import { compile, optimize } from "@tailwindcss/node";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { FileContentViewer } from "#/components/features/files-tab/file-content-viewer";import type { ViewMode } from "#/components/features/files-tab/view-mode";import { useWorkspaceMutationCounter } from "#/stores/use-workspace-mutation-counter";+import { AGENT_SERVER_UI_DEFAULT_CSS_VARIABLES } from "#/styles/agent-server-ui-style-scope";+import {+ applyColorTheme,+ COLOR_THEMES,+ DEFAULT_COLOR_THEME,+ type ColorThemeKey,+} from "#/themes/color-themes";// Mock the *services* the file-content hook depends on β not the hook itself β// so the real classification (text decoded, then flipped to binary on a NUL@@ -121,4 +131,175 @@ describe("FileContentViewer", () => {).toBeInTheDocument();},);++ it("keeps alert prose descendants readable without recoloring ordinary Markdown or links", async () => {+ // Use the real file hook, viewer, prose wrapper and Markdown components.+ const markdown = [+ "**Ordinary emphasis**",+ "",+ "> [!NOTE]",+ "> **Alert emphasis** and `alert-code`.",+ ">",+ "> ##### Alert heading",+ ">",+ "> <kbd>Alert key</kbd>",+ ">",+ "> <figure><figcaption>Alert caption</figcaption></figure>",+ ">",+ "> 1. Ordered alert item",+ ">",+ "> - Bulleted alert item",+ ">",+ "> [**Linked emphasis**](https://example.com/qa)",+ ">",+ "> > [!CAUTION]",+ "> > **Nested emphasis**",+ ].join("\n");+ fetchMock.mockResolvedValue({+ ok: true,+ status: 200,+ arrayBuffer: async () => new TextEncoder().encode(markdown).buffer,+ });+ act(() => applyColorTheme(DEFAULT_COLOR_THEME));+ const { container } = renderViewer("alerts.md");+ const viewer = await screen.findByTestId("file-content-viewer-markdown");+ const compiler = await compile(+ readFileSync(resolve("src/tailwind.css"), "utf8"),+ { base: resolve("src"), onDependency: () => {} },+ );+ const css = optimize(+ compiler.build(+ [...container.querySelectorAll("[class]")].flatMap((element) => [+ ...element.classList,+ ]),+ ),+ ).code;+ // Flatten build layers/supports for jsdom, retaining emitted selectors,+ // cascade order, custom properties and modern translucent color branches.+ const rules = [...css.matchAll(/([^{}]+)\{([^{}]*)\}/g)].filter(+ ([, selector]) => !selector.trim().startsWith("@"),+ );+ const sheet = document.createElement("style");+ sheet.textContent = rules+ .map(([, selector, declarations]) => `${selector}{${declarations}}`)+ .join("\n");+ document.head.appendChild(sheet);+ try {+ for (const key of Object.keys(COLOR_THEMES) as ColorThemeKey[]) {+ act(() => applyColorTheme(key));+ const theme = COLOR_THEMES[key];+ const variables: Record<string, string> = {+ ...AGENT_SERVER_UI_DEFAULT_CSS_VARIABLES,+ ...theme.scale,+ ...theme.tokens,+ };+ // jsdom retains var() in computed colors; resolve the actual inherited+ // prose variables against this shipped palette rather than guessing ink.+ const color = (element: Element, value: string): number[] => {+ const reference = /^var\((--[\w-]+)\)$/.exec(value);+ if (reference) {+ const name = reference[1];+ let resolved = variables[name];+ for (+ let owner: Element | null = element;+ !resolved && owner;+ owner = owner.parentElement+ ) {+ resolved = getComputedStyle(owner).getPropertyValue(name).trim();+ }+ expect(resolved, `${key} ${name}`).toBeTruthy();+ return color(element, resolved);+ }+ if (value === "inherit")+ return color(+ element.parentElement!,+ getComputedStyle(element.parentElement!).color,+ );+ if (value.startsWith("#"))+ return [1, 3, 5].map(+ (offset) => parseInt(value.slice(offset, offset + 2), 16) / 255,+ );+ const rgb = value.match(/^rgb\((\d+), (\d+), (\d+)\)$/);+ expect(rgb, value).not.toBeNull();+ return rgb!.slice(1).map((channel) => Number(channel) / 255);+ };+ const background = (element: Element): number[] => {+ const value = getComputedStyle(element).backgroundColor;+ if (!value || value === "rgba(0, 0, 0, 0)")+ return background(element.parentElement!);+ const mix = value.match(+ /^color-mix\(in \w+, (var\(--[\w-]+\)) ([\d.]+)%, transparent\)$/,+ );+ if (!mix) return color(element, value);+ const weight = Number(mix[2]) / 100;+ const parent = background(element.parentElement!);+ return color(element, mix[1]).map(+ (channel, index) => channel * weight + parent[index] * (1 - weight),+ );+ };+ const luminance = (channels: number[]) => {+ const linear = channels.map((channel) =>+ channel <= 0.04045+ ? channel / 12.92+ : ((channel + 0.055) / 1.055) ** 2.4,+ );+ return linear[0] * 0.2126 + linear[1] * 0.7152 + linear[2] * 0.0722;+ };+ const contrast = (ink: number[], surface: number[]) => {+ const [dark, light] = [luminance(ink), luminance(surface)].sort(+ (a, b) => a - b,+ );+ return (light + 0.05) / (dark + 0.05);+ };+ const alert = viewer.querySelector(+ '[data-testid="markdown-alert-note"]',+ )!;+ for (const element of alert.querySelectorAll(+ "strong, h5, code, kbd, figcaption",+ )) {+ expect(+ contrast(+ color(element, getComputedStyle(element).color),+ background(element),+ ),+ `${key} ${element.textContent}`,+ ).toBeGreaterThanOrEqual(4.5);+ }+ for (const item of alert.querySelectorAll("li")) {+ let markerColor = getComputedStyle(item).color;+ for (const [, selector, declarations] of rules) {+ if (+ selector.includes("::marker") &&+ item.matches(+ selector+ .replaceAll(" ::marker", " *")+ .replaceAll("::marker", ""),+ )+ ) {+ markerColor =+ declarations.match(/(?:^|;)\s*color:\s*([^;]+);/)?.[1] ??+ markerColor;+ }+ }+ expect(+ contrast(color(item, markerColor), background(item)),+ `${key} ${item.textContent} marker`,+ ).toBeGreaterThanOrEqual(+ item.parentElement!.tagName === "OL" ? 4.5 : 3,+ );+ }+ const ordinary = screen.getByText("Ordinary emphasis");+ expect(color(ordinary, getComputedStyle(ordinary).color)).toEqual(+ color(ordinary, "var(--oh-foreground)"),+ );+ const linked = screen.getByText("Linked emphasis");+ expect(color(linked, getComputedStyle(linked).color)).toEqual(+ color(linked, "var(--oh-link)"),+ );+ }+ } finally {+ sheet.remove();+ act(() => applyColorTheme(DEFAULT_COLOR_THEME));+ }+ });});diff --git a/__tests__/themes/color-themes.test.tsx b/__tests__/themes/color-themes.test.tsxindex 7bc1a7ef9e..4f924e9494 100644--- a/__tests__/themes/color-themes.test.tsx+++ b/__tests__/themes/color-themes.test.tsx@@ -1,7 +1,11 @@import { act, render, screen } from "@testing-library/react";import { readFileSync } from "node:fs";-import { afterEach, describe, expect, it } from "vitest";+import { resolve as resolvePath } from "node:path";+import { compile } from "@tailwindcss/node";+import { afterEach, beforeAll, describe, expect, it } from "vitest";import { AgentServerUIRoot } from "#/components/providers/agent-server-ui-root";+import { MarkdownRenderer } from "#/components/features/markdown/markdown-renderer";+import { ALERT_TYPES } from "#/components/features/markdown/remark-github-alerts";import { AGENT_SERVER_UI_DEFAULT_CSS_VARIABLES } from "#/styles/agent-server-ui-style-scope";import {AVAILABLE_COLOR_THEMES,@@ -9,12 +13,96 @@ import {applyColorTheme,} from "#/themes/color-themes";-const defaultWarningColor = readFileSync(- `${process.cwd()}/src/tailwind.css`,- "utf-8",-).match(/^\s*--oh-warning:\s*([^;]+);/m)?.[1];+const stylesheet = readFileSync(resolvePath("src/tailwind.css"), "utf-8");+const defaultWarningColor = stylesheet.match(+ /^\s*--oh-warning:\s*([^;]+);/m,+)?.[1];+let alertColors: Array<{+ type: (typeof ALERT_TYPES)[number];+ title: string | undefined;+ icon: string | undefined;+ border: string | undefined;+ background: string | undefined;+ body: string | undefined;+ tintWeight: number;+}>;describe("color themes", () => {+ beforeAll(async () => {+ const { container, unmount } = render(+ <MarkdownRenderer includeStandard>+ {ALERT_TYPES.map((type) => `> [!${type}]\n> Alert body.`).join("\n\n")}+ </MarkdownRenderer>,+ );+ const compiler = await compile(stylesheet, {+ base: resolvePath("src"),+ onDependency: () => {},+ });+ const css = compiler.build(+ [...container.querySelectorAll("[class]")].flatMap((element) => [+ ...element.classList,+ ]),+ );+ const declaration = (element: Element, property: string) => {+ for (const candidate of element.classList) {+ const selector = `.${candidate.replace(/[^\w-]/g, "\\$&")} {`;+ const start = css.indexOf(selector);+ if (start < 0) continue;+ const rule = css.slice(+ start + selector.length,+ css.indexOf("}", start),+ );+ // Modern browsers use Tailwind's later color-mix branch rather than+ // its opaque fallback, so retain the last emitted declaration.+ const value = [+ ...rule.matchAll(+ new RegExp(`(?:^|[;{])\\s*${property}:\\s*([^;]+);`, "g"),+ ),+ ].at(-1)?.[1];+ if (value) return value;+ }+ return undefined;+ };+ const inheritedInk = (element: Element): string | undefined =>+ declaration(element, "color") ??+ (element.parentElement ? inheritedInk(element.parentElement) : undefined);++ alertColors = ALERT_TYPES.map((type) => {+ const alert = screen.getByTestId(`markdown-alert-${type}`);+ const title = alert.querySelector("p")!;+ const background = declaration(alert, "background-color");+ return {+ type,+ title: inheritedInk(title),+ icon: inheritedInk(title.querySelector("svg")!),+ border: declaration(alert, "border-left-color"),+ background,+ body: inheritedInk(alert.querySelector(":scope > div")!),+ tintWeight:+ Number(background?.match(/ ([\d.]+)%, transparent\)/)?.[1]) / 100,+ };+ });+ unmount();+ });++ it("builds rendered Markdown alerts from their public theme roles", () => {+ for (const alert of alertColors) {+ const token = `--oh-markdown-alert-${alert.type}` as const;+ const role = `var(${token})`;+ expect(alert.title).toBe(role);+ expect(alert.icon).toBe(role);+ expect(alert.border).toBe(role);+ expect(alert.background).toContain(role);+ expect(alert.tintWeight).toBeGreaterThan(0);+ expect(alert.tintWeight).toBeLessThan(1);+ expect(alert.body).toBe("var(--oh-contrast)");+ // The public embedding defaults describe the actual shipped stylesheet.+ expect(AGENT_SERVER_UI_DEFAULT_CSS_VARIABLES[token]).toBe(+ stylesheet.match(new RegExp(`^\\s*${token}:\\s*([^;]+);`, "m"))?.[1],+ );+ }+ });+// @spec MCP-004 β Form feedback follows readable theme text roles// @spec WN-001 β Warning feedback also meets the small-text contrast contractit.each(Object.entries(COLOR_THEMES))(@@ -75,23 +163,44 @@ describe("color themes", () => {`--oh-link against ${surfaceRole}`,).toBeGreaterThanOrEqual(4.5);- // Single GitHub alert panels tint each Markdown host surface at 10%.- // These are the shipped Tailwind v4 alert colors resolved to sRGB.- for (const [alert, color] of [- ["Note", "#2b7fff"],- ["Tip", "#00bc7d"],- ["Important", "#ad46ff"],- ["Warning", "#efb100"],- ["Caution", "#ff2056"],- ]) {- const host = channels(resolve(surfaceRole));- const alertSurface = channels(color).map(- (channel, index) => channel * 0.1 + host[index] * 0.9,+ // Alerts occur in chat, user bubbles, files/plans and raised tool results.+ // Include each parent/child hue pairing for one level of nested alerts.+ const host = channels(resolve(surfaceRole));+ const tint = (+ type: (typeof ALERT_TYPES)[number],+ surface: number[],+ ) => {+ const { tintWeight } = alertColors.find(+ (alert) => alert.type === type,+ )!;+ return channels(resolve(`--oh-markdown-alert-${type}`)).map(+ (channel, index) =>+ channel * tintWeight + surface[index] * (1 - tintWeight),);- expect(- contrast(luminance(resolve("--oh-link")), luminance(alertSurface)),- `--oh-link against ${alert} tint over ${surfaceRole}`,- ).toBeGreaterThanOrEqual(4.5);+ };+ for (const type of ALERT_TYPES) {+ const alertInk = channels(resolve(`--oh-markdown-alert-${type}`));+ const surfaces = [+ host,+ ...ALERT_TYPES.map((parent) => tint(parent, host)),+ ];+ for (const surface of surfaces) {+ const panel = tint(type, surface);+ for (const [name, ink] of [+ ["title/icon", alertInk],+ ["body", channels(resolve("--oh-contrast"))],+ ["link", channels(resolve("--oh-link"))],+ ] as const) {+ expect(+ contrast(luminance(ink), luminance(panel)),+ `${type} ${name} on a tinted panel over ${surfaceRole}`,+ ).toBeGreaterThanOrEqual(4.5);+ }+ expect(+ contrast(luminance(alertInk), luminance(surface)),+ `${type} border against its surrounding surface`,+ ).toBeGreaterThanOrEqual(3);+ }}}@@ -290,11 +399,16 @@ describe("color themes", () => {});// @spec MCP-004 β Form feedback follows readable theme text roles// @spec WN-001 β Warning feedback can be overridden by an embedding host- it("preserves host feedback colors when the selected palette changes", () => {+ it("preserves host feedback and Markdown alert colors when the palette changes", () => {const overrides = {"--oh-feedback-error": "#672727","--oh-feedback-success": "#24542d","--oh-feedback-warning": "#755300",+ "--oh-markdown-alert-note": "#213f67",+ "--oh-markdown-alert-tip": "#215431",+ "--oh-markdown-alert-important": "#533167",+ "--oh-markdown-alert-warning": "#675321",+ "--oh-markdown-alert-caution": "#672131",} as const;render(<AgentServerUIRootdiff --git a/src/components/features/markdown/blockquote.tsx b/src/components/features/markdown/blockquote.tsxindex 39d0214272..fafee76c71 100644--- a/src/components/features/markdown/blockquote.tsx+++ b/src/components/features/markdown/blockquote.tsx@@ -14,48 +14,40 @@ import { cn } from "#/utils/utils";interface AlertConfig {label: string;icon: IconType;- // Per-alert color overrides. We stick to Tailwind palette utilities so- // the classes show up in the source for the v4 content scanner.+ // Literal semantic recipes remain visible to the Tailwind content scanner.containerClass: string;- titleClass: string;- iconClass: string;}const ALERT_CONFIG: Record<AlertType, AlertConfig> = {note: {label: "Note",icon: FaCircleInfo,- containerClass: "border-l-blue-500 bg-blue-500/10",- titleClass: "text-blue-300",- iconClass: "text-blue-400",+ containerClass:+ "border-l-markdown-alert-note bg-markdown-alert-note/5 text-markdown-alert-note",},tip: {label: "Tip",icon: FaLightbulb,- containerClass: "border-l-emerald-500 bg-emerald-500/10",- titleClass: "text-emerald-300",- iconClass: "text-emerald-400",+ containerClass:+ "border-l-markdown-alert-tip bg-markdown-alert-tip/5 text-markdown-alert-tip",},important: {label: "Important",icon: FaCircleExclamation,- containerClass: "border-l-purple-500 bg-purple-500/10",- titleClass: "text-purple-300",- iconClass: "text-purple-400",+ containerClass:+ "border-l-markdown-alert-important bg-markdown-alert-important/5 text-markdown-alert-important",},warning: {label: "Warning",icon: FaTriangleExclamation,- containerClass: "border-l-yellow-500 bg-yellow-500/10",- titleClass: "text-yellow-300",- iconClass: "text-yellow-400",+ containerClass:+ "border-l-markdown-alert-warning bg-markdown-alert-warning/5 text-markdown-alert-warning",},caution: {label: "Caution",icon: FaCircleStop,- containerClass: "border-l-rose-500 bg-rose-500/10",- titleClass: "text-rose-300",- iconClass: "text-rose-400",+ containerClass:+ "border-l-markdown-alert-caution bg-markdown-alert-caution/5 text-markdown-alert-caution",},};@@ -95,16 +87,13 @@ export function blockquote({config.containerClass,)}>- <p- className={cn(- "flex items-center gap-2 font-semibold",- config.titleClass,- )}- >- <Icon aria-hidden className={cn("shrink-0", config.iconClass)} />+ <p className="flex items-center gap-2 font-semibold">+ <Icon aria-hidden className="shrink-0" /><span>{config.label}</span></p>- <div className="text-content">{children}</div>+ <div className="text-contrast prose-strong:text-inherit prose-headings:text-contrast prose-code:text-contrast prose-kbd:text-contrast prose-figcaption:text-contrast marker:text-contrast">+ {children}+ </div></div>);}diff --git a/src/styles/agent-server-ui-style-scope.ts b/src/styles/agent-server-ui-style-scope.tsindex 742fdec590..578fcb1a96 100644--- a/src/styles/agent-server-ui-style-scope.ts+++ b/src/styles/agent-server-ui-style-scope.ts@@ -27,6 +27,11 @@ export const AGENT_SERVER_UI_DEFAULT_CSS_VARIABLES = {// @spec MCP-004 β Form feedback follows readable theme text roles"--oh-feedback-error": "var(--oh-color-danger)","--oh-feedback-success": "var(--oh-color-success)",+ "--oh-markdown-alert-note": "#8EC5FF",+ "--oh-markdown-alert-tip": "#5EE9B5",+ "--oh-markdown-alert-important": "#D8B4FE",+ "--oh-markdown-alert-warning": "#FFE02A",+ "--oh-markdown-alert-caution": "#FFB3BF","--oh-color-basic": "var(--cool-grey-400)","--oh-color-tertiary": "var(--cool-grey-800)","--oh-color-tertiary-light": "var(--cool-grey-300)",diff --git a/src/tailwind.css b/src/tailwind.cssindex ce0df66bdc..3f4202339a 100644--- a/src/tailwind.css+++ b/src/tailwind.css@@ -23,6 +23,12 @@--color-feedback-success: var(--oh-feedback-success);/* @spec WN-001 β Warning text has a separate readable theme role */--color-feedback-warning: var(--oh-feedback-warning);+ /* GitHub Markdown alert ink also owns its border and translucent fill. */+ --color-markdown-alert-note: var(--oh-markdown-alert-note);+ --color-markdown-alert-tip: var(--oh-markdown-alert-tip);+ --color-markdown-alert-important: var(--oh-markdown-alert-important);+ --color-markdown-alert-warning: var(--oh-markdown-alert-warning);+ --color-markdown-alert-caution: var(--oh-markdown-alert-caution);--color-basic: var(--oh-color-basic);--color-tertiary: var(--oh-color-tertiary);--color-tertiary-light: var(--oh-color-tertiary-light);@@ -94,6 +100,11 @@/* Small feedback text has its own contrast contract, separate from controls. */--oh-feedback-error: var(--oh-color-danger);--oh-feedback-success: var(--oh-color-success);+ --oh-markdown-alert-note: #8EC5FF;+ --oh-markdown-alert-tip: #5EE9B5;+ --oh-markdown-alert-important: #D8B4FE;+ --oh-markdown-alert-warning: #FFE02A;+ --oh-markdown-alert-caution: #FFB3BF;--oh-color-basic: var(--cool-grey-400);--oh-color-tertiary: var(--cool-grey-800);--oh-color-tertiary-light: var(--cool-grey-300);diff --git a/src/themes/README.md b/src/themes/README.mdindex a07624b0d9..5b048adb76 100644--- a/src/themes/README.md+++ b/src/themes/README.md@@ -42,6 +42,12 @@ them; changing the page background alone is not a complete theme.the built-in modal surface and leave the general danger/success/warning controlcolors unchanged. Embedded hosts can override `--oh-feedback-error`,`--oh-feedback-success`, and `--oh-feedback-warning` for their surfaces.+- GitHub Markdown alerts own five `--oh-markdown-alert-*` roles: note, tip,+ important, warning, and caution. Each supplies title/icon ink, the left border,+ and a 5% panel tint. Built-in values keep text readable over Markdown host+ surfaces, including one level of nested alerts; bodies use `contrast` and+ underlined links retain `link`. Embedded hosts can override the five roles+ through `styleOverrides` for their own surfaces.- Use `focus` for keyboard outlines and rings on neutral controls. The defaultrole meets 3:1 against base, modal, raised, and interactive-hover surfaces;retain the control's outline width/offset and preserve host `--oh-focus`diff --git a/src/themes/color-theme/definitions/light-plus.ts b/src/themes/color-theme/definitions/light-plus.tsindex 7542a0b362..4935b5ee16 100644--- a/src/themes/color-theme/definitions/light-plus.ts+++ b/src/themes/color-theme/definitions/light-plus.ts@@ -65,6 +65,12 @@ export const LIGHT_PLUS_TOKENS: Partial<// Feedback text must remain readable on the light modal surface."--oh-feedback-error": "#C0282D","--oh-feedback-success": "#0F734D",+ // Alert ink clears small-text contrast on tinted and nested Markdown panels.+ "--oh-markdown-alert-note": "#005A99",+ "--oh-markdown-alert-tip": "#08633F",+ "--oh-markdown-alert-important": "#7E22CE",+ "--oh-markdown-alert-warning": "#6D4C00",+ "--oh-markdown-alert-caution": "#AA2025",// @spec WN-001 β Darker warning text preserves contrast on light surfaces"--oh-feedback-warning": "#7D5D08","--oh-color-basic": "#616161",diff --git a/src/themes/color-theme/definitions/solarized-light.ts b/src/themes/color-theme/definitions/solarized-light.tsindex 078b646261..e975ce9990 100644--- a/src/themes/color-theme/definitions/solarized-light.ts+++ b/src/themes/color-theme/definitions/solarized-light.ts@@ -67,6 +67,12 @@ const SOLARIZED_LIGHT_TOKENS: Partial<"--oh-color-success": "#859900","--oh-feedback-error": "#BB2A26","--oh-feedback-success": "#5D6A00",+ // Alert ink clears small-text contrast on tinted and nested Markdown panels.+ "--oh-markdown-alert-note": "#005A88",+ "--oh-markdown-alert-tip": "#4E5A00",+ "--oh-markdown-alert-important": "#6C3CA6",+ "--oh-markdown-alert-warning": "#735400",+ "--oh-markdown-alert-caution": "#A5201C",// @spec WN-001 β Darker warning text preserves contrast on Solarized surfaces"--oh-feedback-warning": "#735400","--oh-color-basic": "#839496",