Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

[Component Audit] ChatSystemMessage: wrap long notices in narrow chats (#6655)

Cindy Zhangf04b50199e4b
diff --git a/.changeset/chat-system-message-wrap.md b/.changeset/chat-system-message-wrap.md
new file mode 100644
index 0000000000..5ab816ddac
--- /dev/null
+++ b/.changeset/chat-system-message-wrap.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Allow long ChatSystemMessage content to wrap within narrow chat layouts instead of crossing the container edge.
+
+@cixzhang
diff --git a/.github/scripts/lib/a11y-story-identity.js b/.github/scripts/lib/a11y-story-identity.js
index 05d8f88639..b19434aaa6 100644
--- a/.github/scripts/lib/a11y-story-identity.js
+++ b/.github/scripts/lib/a11y-story-identity.js
@@ -16,6 +16,7 @@ const A11Y_STORY_OWNER_PREFIXES = Object.freeze([
['a11y-button-pattern--sidenav-collapse-', 'core/SideNavCollapseButton'],
['a11y-button-pattern--chat-send', 'core/ChatSendButton'],
['a11y-chatsendbutton-audit--', 'core/ChatSendButton'],
+ ['a11y-chatsystemmessage-audit--', 'core/ChatSystemMessage'],
['a11y-button-pattern--button-', 'core/Button'],
['a11y-checkbox-pattern--list-item-', 'core/CheckboxListItem'],
['a11y-checkbox-pattern--menu-item-', 'core/DropdownMenuCheckboxItem'],
diff --git a/.github/scripts/lib/a11y-story-identity.test.mjs b/.github/scripts/lib/a11y-story-identity.test.mjs
index e4778093a5..85fc32f0c5 100644
--- a/.github/scripts/lib/a11y-story-identity.test.mjs
+++ b/.github/scripts/lib/a11y-story-identity.test.mjs
@@ -78,6 +78,8 @@ describe('a11y story identity migration', () => {
],
['a11y-button-pattern--chat-send', 'core/ChatSendButton'],
['a11y-chatsendbutton-audit--chat-send-small', 'core/ChatSendButton'],
+ ['a11y-chatsystemmessage-audit--states', 'core/ChatSystemMessage'],
+ ['a11y-chatsystemmessage-audit--narrow', 'core/ChatSystemMessage'],
[
'a11y-chatsendbutton-audit--chat-send-stop-small',
'core/ChatSendButton',
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 3d0ce47cdf..b4f1b928bb 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1073,6 +1073,35 @@ jobs:
retention-days: 30
if-no-files-found: error
+ # ChatSystemMessage is noninteractive, but its status/separator semantics,
+ # delegated paint, contrast, and narrow reflow still require exact-head
+ # browser receipts rather than source-only claims.
+ - name: Run ChatSystemMessage audit browser evidence
+ if: github.event_name == 'pull_request' && startsWith(github.event.pull_request.title, '[Component Audit] ChatSystemMessage:')
+ env:
+ ASTRYX_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
+ run: |
+ node .github/scripts/accessibility-audit.js \
+ --storybook-dir apps/storybook/dist \
+ --output chat-system-message-a11y-report.json \
+ --components ChatSystemMessage \
+ --baseline .github/a11y-baseline.json \
+ --fail-on-new
+ pnpm exec playwright test \
+ packages/core/src/Chat/__tests__/ChatSystemMessage.a11y.chromium.spec.ts \
+ --project chromium
+
+ - name: Upload ChatSystemMessage audit evidence
+ if: always() && github.event_name == 'pull_request' && startsWith(github.event.pull_request.title, '[Component Audit] ChatSystemMessage:')
+ uses: actions/upload-artifact@v7
+ with:
+ name: chat-system-message-audit-evidence-${{ needs.build-storybook.outputs.short_hash }}
+ path: |
+ chat-system-message-a11y-report.json
+ test-results/chat-system-message-audit-evidence/
+ retention-days: 30
+ if-no-files-found: error
+
# Run the exhaustive contract/fixture matrix at release time. PRs retain
# scoped axe validation and the fast interaction guards above; they must
# not pay for every component's browser bindings on every change.
diff --git a/apps/storybook/rtl-audit/verified-not-applicable.json b/apps/storybook/rtl-audit/verified-not-applicable.json
index 71f1be626e..9b1f65b1c8 100644
--- a/apps/storybook/rtl-audit/verified-not-applicable.json
+++ b/apps/storybook/rtl-audit/verified-not-applicable.json
@@ -280,5 +280,16 @@
{
"component": "core/ChatMessageMetadata",
"reason": "The metadata row owns no directional glyph, contextual directional separator, physical inline positioning, prev/next control order, horizontal scrolling, dragging, overlay, or arrow-key behavior. Sender-dependent row reversal uses CSS flex direction relative to the surrounding writing direction and is verified separately by matched LTR/RTL Chromium receipts. The RTL audit's D1, D2, D3, D5, and D6 detectors therefore have no applicable target for this component."
+ },
+ {
+ "component": "core/ChatSystemMessage",
+ "reason": "ChatSystemMessage uses centered flex layout and logical block spacing only. Its default content follows normal document direction; optional icon artwork is caller-owned. The divider branch delegates a symmetric horizontal rule and centered label to Divider. The component owns no left/right glyph, physical inline positioning, directional order, horizontal scrolling or dragging, side-placed overlay, or horizontal keyboard behavior. Its dedicated audit fixtures cover both variants, optional default-branch icon content, and narrow layout without adding a component-owned RTL dimension.",
+ "evidence": {
+ "apps/storybook/stories/ChatSystemMessage.stories.tsx": "sha256:ac979e4e63e32d5f6542f39c9f8cfeeab4636643db2513c987f84746bf79a4ee",
+ "apps/storybook/stories/ChatSystemMessageAudit.stories.tsx": "sha256:54e81ad2fb8360c9d30ce8f6f33a8aa4fde8602d2ba2ab8774d03638ee8c0a82",
+ "packages/core/src/Chat/ChatSystemMessage.tsx": "sha256:11273238c02e6b48292cb2444b1229e5a06eb08494d32696e88143b5ad2e1ca3",
+ "packages/core/src/Chat/index.ts": "sha256:0f4a9d3ee08b4fcd43698ad017460aad109c500d2411913f509506d2a27387bb",
+ "packages/core/src/Divider/Divider.tsx": "sha256:f302b5c9eecde40b486c09d49c71cb7dab158e2fcedcb38c0145671c45d9cf8d"
+ }
}
]
diff --git a/apps/storybook/stories/ChatSystemMessage.stories.tsx b/apps/storybook/stories/ChatSystemMessage.stories.tsx
new file mode 100644
index 0000000000..adbcd2f13f
--- /dev/null
+++ b/apps/storybook/stories/ChatSystemMessage.stories.tsx
@@ -0,0 +1,34 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChatSystemMessage.stories.tsx
+ * @input ChatSystemMessage default and divider variants
+ * @output Canonical Storybook fixture for component and RTL discovery
+ * @position Public ChatSystemMessage story outside the audit-only namespace
+ */
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {ChatSystemMessage} from '@astryxdesign/core/Chat';
+
+const meta = {
+ title: 'Core/ChatSystemMessage',
+ component: ChatSystemMessage,
+ tags: ['no-visual'],
+ args: {
+ children: 'Conversation started',
+ },
+} satisfies Meta<typeof ChatSystemMessage>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+export const Variants: Story = {
+ render: () => (
+ <div style={{display: 'grid', gap: 16, width: 320}}>
+ <ChatSystemMessage icon={<span aria-hidden="true">●</span>}>
+ Conversation started
+ </ChatSystemMessage>
+ <ChatSystemMessage variant="divider">Today</ChatSystemMessage>
+ </div>
+ ),
+};
diff --git a/apps/storybook/stories/ChatSystemMessageAudit.stories.tsx b/apps/storybook/stories/ChatSystemMessageAudit.stories.tsx
new file mode 100644
index 0000000000..a87fa8a805
--- /dev/null
+++ b/apps/storybook/stories/ChatSystemMessageAudit.stories.tsx
@@ -0,0 +1,91 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChatSystemMessageAudit.stories.tsx
+ * @input ChatSystemMessage in its distinct public visual and semantic partitions
+ * @output Checked-in single-subject fixtures for exact-head component audit evidence
+ * @position Browser evidence fixtures outside the shared Chat story inventory
+ */
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {ChatMessageList, ChatSystemMessage} from '@astryxdesign/core/Chat';
+import {Icon} from '@astryxdesign/core/Icon';
+
+const LONG_SYSTEM_MESSAGE =
+ 'Messages are end-to-end encrypted for everyone in this conversation and on every signed-in device.';
+
+const meta = {
+ title: 'a11y/ChatSystemMessage audit',
+ component: ChatSystemMessage,
+ args: {children: 'Conversation started'},
+ tags: ['no-visual'],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'Single-subject fixtures for exact-head ChatSystemMessage audit evidence. The dedicated namespace is excluded from stable visual baselines and explicitly routed to the component accessibility owner.',
+ },
+ },
+ },
+} satisfies Meta<typeof ChatSystemMessage>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+export const States: Story = {
+ render: () => (
+ <div style={{display: 'grid', gap: 24, width: 480, maxWidth: '100%'}}>
+ <ChatSystemMessage data-system-message-case="default">
+ Conversation started
+ </ChatSystemMessage>
+ <ChatSystemMessage
+ data-system-message-case="default-icon"
+ icon={<Icon icon="info" size="sm" />}>
+ Messages are end-to-end encrypted
+ </ChatSystemMessage>
+ <ChatSystemMessage data-system-message-case="divider" variant="divider">
+ Today
+ </ChatSystemMessage>
+ <ChatSystemMessage
+ data-system-message-case="divider-icon"
+ icon={<Icon icon="info" size="sm" />}
+ variant="divider">
+ March 15, 2026
+ </ChatSystemMessage>
+ <ChatMessageList align="top">
+ <ChatSystemMessage data-system-message-case="nested-log">
+ Conversation archived
+ </ChatSystemMessage>
+ </ChatMessageList>
+ </div>
+ ),
+};
+
+export const Narrow: Story = {
+ render: () => (
+ <div
+ style={{
+ display: 'grid',
+ gap: 24,
+ gridTemplateColumns: 'minmax(0, 1fr)',
+ width: 280,
+ maxWidth: '100%',
+ }}>
+ <ChatSystemMessage
+ data-system-message-case="narrow-default"
+ icon={<Icon icon="info" size="sm" />}>
+ Conversation marked as resolved
+ </ChatSystemMessage>
+ <ChatSystemMessage
+ data-system-message-case="narrow-divider"
+ variant="divider">
+ March 15, 2026
+ </ChatSystemMessage>
+ <ChatSystemMessage
+ data-system-message-case="long-default"
+ icon={<Icon icon="info" size="sm" />}>
+ {LONG_SYSTEM_MESSAGE}
+ </ChatSystemMessage>
+ </div>
+ ),
+};
diff --git a/packages/core/src/Chat/ChatSystemMessage.doc.mjs b/packages/core/src/Chat/ChatSystemMessage.doc.mjs
index ca7fb293c2..911607b28a 100644
--- a/packages/core/src/Chat/ChatSystemMessage.doc.mjs
+++ b/packages/core/src/Chat/ChatSystemMessage.doc.mjs
@@ -6,24 +6,28 @@ export const docs = {
name: 'ChatSystemMessage',
subComponentOf: 'Chat',
displayName: 'Chat System Message',
- description: 'Centered system message for non-sender content like date separators, membership changes, and status notices. It is not a chat bubble; it has no avatar, no alignment, and no sender context. Use the divider variant for temporal breaks and default for inline status updates.',
+ description:
+ 'Centered system message for non-sender content like date separators, membership changes, and status notices. It is not a chat bubble; it has no avatar, no alignment, and no sender context. Use the divider variant for temporal breaks and default for inline status updates.',
props: [
{
name: 'children',
type: 'ReactNode',
- description: 'System message content: a short, factual string like a date, a join/leave notice, or a status change.',
+ description:
+ 'System message content: factual text or React content such as a date, join/leave notice, or status change. Long default content wraps within the available width.',
required: true,
},
{
name: 'variant',
type: "'default' | 'divider'",
- description: "Visual variant. 'default' renders centered text. 'divider' adds horizontal lines on each side via Divider: use for date separators and section breaks.",
+ description:
+ "Visual variant. 'default' renders centered text. 'divider' adds horizontal lines on each side via Divider: use for date separators and section breaks.",
default: "'default'",
},
{
name: 'icon',
type: 'ReactNode',
- description: 'Leading icon that reinforces the message type. Wrap in Icon for consistent sizing. Use for membership changes, encryption notices, or AI activity.',
+ description:
+ 'Optional caller-provided icon content. Rendered before the message in the default variant; the divider variant currently does not render it. Wrap in Icon for consistent sizing.',
slotElements: [
{
__element: 'Icon',
@@ -34,27 +38,126 @@ export const docs = {
},
],
},
+ {
+ name: 'xstyle',
+ type: 'StyleXStyles',
+ description:
+ 'StyleX styles for layout customization. Must be a stylex.create() value: not an inline style object like style={{}}.',
+ },
],
+ theming: {
+ targets: [
+ {className: 'astryx-chat-system-message', visualProps: ['variant']},
+ ],
+ },
+ usage: {
+ description:
+ 'Use ChatSystemMessage for concise, non-sender content inside a chat transcript. Choose the default variant for factual status notices and the divider variant for date or section breaks. Long default content wraps within the available width. The component exposes status semantics and the divider branch includes a labelled separator.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Keep the visible message concise and self-contained so it remains understandable without an icon.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Use the divider variant for temporal or section boundaries and the default variant for factual status notices.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use ChatSystemMessage for sender-authored content; use ChatMessage and ChatMessageBubble instead.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use caller-provided icon artwork as the only source of meaning; the visible message must carry the same information.',
+ },
+ ],
+ anatomy: [
+ {
+ name: 'System message',
+ required: true,
+ description:
+ 'The noninteractive status row that carries the chat-system-message theme target.',
+ },
+ {
+ name: 'Content',
+ required: true,
+ description: 'The concise caller-provided message or divider label.',
+ },
+ {
+ name: 'Icon content',
+ required: false,
+ description:
+ 'Rendered before the message in the default variant; the divider variant currently does not render it.',
+ },
+ {
+ name: 'Divider',
+ required: false,
+ description:
+ 'A labelled horizontal Divider rendered by the divider variant.',
+ },
+ ],
+ },
};
export const docsZh = {
name: 'ChatSystemMessage',
displayName: 'Chat System Message',
- description: '居中的系统消息,用于日期分隔、成员变更和状态通知等非发送者内容。没有头像、对齐或气泡。使用 divider 变体做时间分隔,default 做内联状态更新。',
+ description:
+ '居中的系统消息,用于日期分隔、成员变更和状态通知等非发送者内容。没有头像、对齐或气泡。使用 divider 变体做时间分隔,default 做内联状态更新。',
propDescriptions: {
- children: '系统消息内容,简短的事实性文本,如日期、加入/离开通知或状态变更。',
- variant: "视觉变体。'default' 渲染居中文本。'divider' 通过 Divider 在两侧添加水平线,用于日期分隔和段落分隔。",
- icon: '增强消息类型辨识度的前置图标。使用 Icon 包裹以获得一致的尺寸。',
+ children:
+ '事实性系统消息内容,如日期、加入/离开通知或状态变更;较长的 default 内容会在可用宽度内换行。',
+ variant:
+ "视觉变体。'default' 渲染居中文本。'divider' 通过 Divider 在两侧添加水平线,用于日期分隔和段落分隔。",
+ icon: '可选的调用方图标内容。default 变体会在消息前渲染;divider 变体当前不会渲染。使用 Icon 包裹以获得一致的尺寸。',
+ xstyle: '用于布局自定义的 StyleX 样式。',
+ },
+ theming: {
+ targets: [
+ {className: 'astryx-chat-system-message', visualProps: ['variant']},
+ ],
},
};
export const docsDense = {
name: 'ChatSystemMessage',
displayName: 'Chat System Message',
- description: 'centered non-sender msg; divider variant for date breaks, default for status notices; supports leading icon',
+ description:
+ 'centered non-sender msg; divider variant for date breaks, default for status notices; accepts optional icon content',
+ usage: {
+ description:
+ 'Use for concise non-sender content in chat. Default is a factual status row; divider is a labelled date/section break.',
+ bestPractices: [
+ {
+ guidance: true,
+ description: 'Keep visible content concise and self-contained.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Use divider for temporal/section boundaries and default for factual notices.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use for sender-authored content; use ChatMessage and ChatMessageBubble.',
+ },
+ {
+ guidance: false,
+ description: 'Rely on icon artwork as the only source of meaning.',
+ },
+ ],
+ },
propDescriptions: {
- children: 'short factual text: date, join/leave, status change',
- variant: 'default=centered text, divider=horizontal lines via Divider for date/section breaks',
- icon: 'leading icon reinforcing msg type; wrap in Icon',
+ children:
+ 'factual React content: date, join/leave, status change; long default content wraps',
+ variant:
+ 'default=centered text, divider=horizontal lines via Divider for date/section breaks',
+ icon: 'optional caller icon; rendered before default message; divider currently does not render it',
+ xstyle: 'additional StyleX layout styles',
},
};
diff --git a/packages/core/src/Chat/ChatSystemMessage.spec.md b/packages/core/src/Chat/ChatSystemMessage.spec.md
new file mode 100644
index 0000000000..ad87b13055
--- /dev/null
+++ b/packages/core/src/Chat/ChatSystemMessage.spec.md
@@ -0,0 +1,225 @@
+---
+schema_version: 3
+template_version: 6
+kind: component
+id: component:ChatSystemMessage
+authority: draft
+archive_reason: null
+superseded_by: null
+approved_by: null
+approved_at: null
+owners: [cixzhang]
+review_triggers: [public-api, behavior, layout, theming, accessibility, testing]
+verified_by:
+ [
+ packages/core/src/Chat/ChatSystemMessage.test.tsx,
+ packages/core/src/Chat/__tests__/ChatSystemMessage.a11y.chromium.spec.ts,
+ packages/core/src/theme/themingTargets.test.ts,
+ apps/storybook/stories/ChatSystemMessageAudit.stories.tsx,
+ apps/storybook/rtl-audit/verified-not-applicable.json,
+ ]
+modules: []
+families: []
+design_specs: []
+architecture:
+ [
+ architecture:public-component-api,
+ architecture:component-theming-surface,
+ architecture:component-test-sufficiency,
+ architecture:react-component-runtime,
+ architecture:theme-tokens,
+ architecture:knowledge-contracts,
+ ]
+contributing: []
+system_specs: [spec:AST-002, spec:AST-009, spec:AST-020, spec:AST-029]
+---
+
+# ChatSystemMessage component contract
+
+## Contract at a glance
+
+| Area | Contract |
+| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | The exported noninteractive chat row accepts required content, `default` or `divider` presentation, optional icon content, and supported root DOM, styling, and ref inputs. |
+| Behavior | The default branch centers and wraps content with optional icon content in a status region. The divider branch delegates its labelled separator to Divider and currently does not render the `icon` input. |
+| End-user impact | People can distinguish factual chat notices from sender messages and can identify temporal or section breaks through a labelled separator. |
+| Builder impact | Builders choose between a plain status row and a labelled divider and provide self-contained content. No new caller choice is introduced by this observational record. |
+| Compatibility/readiness | This draft records the wrapping correction plus released observable behavior. The unresolved divider/icon combination remains unchanged and requires an owner decision before its behavior changes. |
+| Review checks | Reject lost status or separator semantics, dropped supported root inputs, target/anatomy drift, or claims that the unresolved divider/icon combination has been settled. |
+| Governing rules | `architecture:public-component-api/INV3`, `architecture:public-component-api/INV5`, `architecture:public-component-api/INV9`; `spec:AST-002/FR15`; `architecture:component-theming-surface/INV3-INV6`; `architecture:component-test-sufficiency`; `spec:AST-009`; `spec:AST-020`; `spec:AST-029`. |
+
+This table is a review projection. The draft body below records checkable current
+behavior and does not create product policy.
+
+## Intent
+
+ChatSystemMessage presents concise non-sender content inside a chat transcript. It
+separates system-originated notices from sender messages and delegates labelled date
+or section separators to Divider.
+
+## Compatibility and migration
+
+- Released default preserved: yes; the default branch now allows long content to wrap within its container.
+- Compatibility class: additive layout correction, observational documentation, and evidence.
+- Controlled/uncontrolled behavior: not applicable; the component owns no state.
+- Migration decision: none for wrapping. Any divider/icon type restriction would require an explicit compatibility decision under `architecture:public-component-api/INV9`.
+
+Consumer migration instructions belong in consumer docs and release notes.
+
+## Ownership boundary
+
+**Owns**
+
+- The non-sender status row and its `chat-system-message` target.
+- Selection between the default centered row and the delegated divider composition.
+- Wrapping default-variant content within the available inline space while keeping icon artwork from shrinking.
+- Root DOM, styling, and ref composition.
+
+**Does not own / non-goals**
+
+- Sender identity, avatar, bubble, transcript ordering, or scrolling.
+- Divider rule paint, label placement, separator role, or separator naming, which are delegated to `component:Divider`.
+- Long Divider-label overflow and forced-colors rule paint, which remain shared `component:Divider` advisories rather than ChatSystemMessage-owned defects.
+- Divider's falsey-label rendering. Empty string and empty Fragment content leave the separator without a visible label or accessible name; numeric zero renders stray `00` text with no accessible name. This is a shared `spec:AST-002/FR15` advisory routed to `component:Divider`.
+- The semantic or directional meaning of caller-provided content or icon artwork.
+- Announcement timing or spoken output; claims at that layer require `spec:AST-009` evidence.
+
+## Public concepts
+
+Consumer syntax remains in `ChatSystemMessage.doc.mjs`. This table closes the
+observable public surface without deciding the unresolved divider/icon contract.
+
+| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
+| ---------------- | -------------------------------------------------------- | --------------------------------------------------------------------------- | ----------------------------------------------------- | --------- | ----------------------------------- | -------------------------- | --------------------------------------------------- |
+| Presentation | `default`; `divider` | Selects a centered status row or a labelled horizontal Divider composition. | Every render. | `default` | `component:ChatSystemMessage` | Observed released surface | Values outside the public union are rejected by TS. |
+| Content | caller-provided `ReactNode` | Supplies the visible status or separator label. | Both variants. | Required | caller and component | Observed released surface | Missing content is rejected by TS. |
+| Icon content | omitted; caller-provided `ReactNode` | Supplies optional caller-owned icon content associated with the message. | Rendered by default and currently ignored by divider. | Omitted | caller and component | Unsettled released surface | Divider currently ignores the input; see OQ1. |
+| Root surface | ref; supported DOM/data/ARIA/events; class/style/xstyle | Extends the component-owned root without replacing its owned role or state. | Both variants. | Omitted | `architecture:public-component-api` | Observed released surface | Unsupported BaseProps omissions stay unsupported. |
+| Status semantics | persistent `role="status"`; delegated labelled separator | Exposes the row as status content and the divider child as a separator. | Status on both; separator on divider. | Fixed | component and `component:Divider` | Observed released surface | Consumer role input does not replace owned role. |
+
+## Behavioral and layout contract
+
+| ID | Candidate invariant | Basis | Draft review state |
+| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- |
+| FR1 | The default branch MUST render the required content in a centered, noninteractive status row, allow long content to wrap within the available inline space, and preserve optional icon geometry. | Current source, released docs, tests, and examples | Verified current behavior |
+| FR2 | For truthy content, the divider branch MUST render the content through Divider as a labelled horizontal separator inside the component's status root. Falsey content follows the shared Divider advisory recorded in AV1. | Current source, released docs, Divider implementation, tests, and examples | Verified current behavior; shared Divider advisory |
+| FR3 | The divider branch currently ignores `icon`; this draft MUST NOT convert that observation into a stable restriction, a requirement to render the icon, or a warning policy. | `architecture:public-component-api/INV3`, `architecture:public-component-api/INV5`, and `spec:AST-002/FR15` | Human API decision required; see OQ1 |
+| FR4 | Supported root DOM, data, ARIA, className, style, xstyle, and ref inputs MUST reach or compose on the root while component-owned `role="status"` and reflected `variant` remain intact. | Current source plus `architecture:public-component-api/INV5-INV8` | Verified current behavior and existing focused evidence |
+| FR5 | The component MUST use semantic color, spacing, and typography tokens and logical layout; the `variant` state remains reflected on the single `chat-system-message` target. | Current source, `architecture:theme-tokens`, and theming architecture | Verified current behavior |
+| FR6 | The component remains render-only: props determine output without Effects, state mirrors, observers, listeners, timers, or owned async resources. | Current source and `architecture:react-component-runtime/INV1-INV8` | Verified current behavior |
+
+### Allowed variation
+
+- **AV1 - Caller content.** Text and other React content may vary while remaining
+ self-contained. Empty strings, numeric zero, and empty Fragments are reachable
+ `ReactNode` partitions. The default variant keeps `role="status"` and renders the
+ content unchanged: empty string and empty Fragment content remain empty, while
+ numeric zero renders one `0`. In the divider variant, the status root and separator
+ remain; empty string and empty Fragment content produce no visible label or
+ accessible name, while numeric zero paints stray `00` text with no accessible name.
+ The divider's falsey-label behavior is a shared `spec:AST-002/FR15` advisory routed
+ to `component:Divider`.
+- **AV2 - Caller styling.** Supported root styling inputs may extend the component
+ without replacing owned status semantics or variant reflection.
+- **AV3 - Delegated Divider paint.** Divider owns its rule and label paint and may
+ evolve within its own contract.
+
+### Representative states
+
+| State | Required invariant | Allowed variation |
+| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- |
+| Default | Centered status content is present. | Content, theme, and root styling. |
+| Default with icon | Optional icon content and visible content render together. | Caller-provided artwork and content. |
+| Default long content | Content wraps without crossing either inline edge or creating page overflow. | Theme and localized content. |
+| Divider | A labelled horizontal separator presents the supplied content. | Label content, theme, and root styling. |
+| Divider with icon | Current output is measured without deciding the ignored-input contract. | No behavior change until OQ1 is resolved. |
+| Empty ReactNode | The default variant keeps `role="status"` and renders content unchanged (empty or one `0`). In the divider variant, the status root and separator remain; empty content has no label/name, while numeric zero paints stray `00` without a name. | Empty string, numeric zero, empty Fragment. |
+| Narrow/coarse pointer | The noninteractive row remains visible without horizontal page overflow. | Theme and supported content. |
+
+### Transformation and precedence order
+
+- **ORD1 - Select branch.** `variant="divider"` selects the Divider branch;
+ every other supported value uses the default branch.
+- **ORD2 - Compose root.** Apply component-owned target/state and styles, then
+ compose supported consumer styling and root inputs while retaining the owned
+ status role.
+- **ORD3 - Delegate divider.** Divider owns separator semantics and paint inside
+ the component root.
+
+### Performance and resources
+
+- **PR1 - Render-only projection.** The component adds no Effect, observer,
+ listener, timer, state mirror, or owned asynchronous lifecycle.
+
+## Accessibility contract
+
+- **AR1 - Status exposure.** The root currently exposes `role="status"` for both
+ variants. Browser evidence may prove role exposure; spoken announcement timing is
+ outside this draft and requires `spec:AST-009` evidence.
+- **AR2 - Divider relationship.** For truthy content, the divider branch delegates a
+ horizontal `separator` whose labelled target contains the visible label; focused DOM
+ tests verify the computed accessible name. Falsey content follows the shared Divider
+ advisory in AV1.
+- **AR3 - Caller content.** Visible content remains the self-contained message.
+ Caller-provided icon content does not replace that text.
+- **AR4 - Noninteractive surface.** The component introduces no focus target,
+ keyboard command, pointer action, disabled state, or interactive state machine.
+
+## Design relationships
+
+| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
+| ---------------- | -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | -------------- | ------------------ |
+| System message | Centers a concise non-sender row and owns the component target. | Current source and released consumer docs | Supporting | FR1, FR4, FR5 |
+| Content | Presents the caller's visible message. | Current source and released consumer docs | Prominent | FR1, FR2, AR3 |
+| Icon content | Supplies optional caller-owned artwork associated with the message; variant behavior is unsettled. | Current source and released consumer docs; divider unsettled | Supporting | FR1, FR3, AR3 |
+| Divider | Delegates labelled separator paint and semantics to Divider. | `component:Divider` observed implementation and docs | Supporting | FR2, AR2 |
+
+This observational draft does not choose new spacing, proportions, color roles,
+icon artwork, live-region timing, or divider/icon behavior.
+
+## Family and system relationships
+
+- `component:Divider` owns the delegated separator structure, role, name,
+ paint, long-label overflow, and falsey-label behavior. The numeric-zero `00`
+ output with no accessible name is a shared `spec:AST-002/FR15` advisory.
+- `architecture:public-component-api` owns released exports, BaseProps reachability,
+ styling composition, and the ref contract.
+- `architecture:component-theming-surface` owns the target/anatomy mapping and
+ variant reflection.
+- `architecture:component-test-sufficiency` owns bounded, mutation-sensitive evidence
+ for applicable promises and established public seams.
+- `architecture:react-component-runtime` owns the render-only lifecycle boundary.
+- `architecture:theme-tokens` owns the semantic token vocabulary.
+- `spec:AST-009` owns any future claim about spoken announcement timing or AT output.
+- `spec:AST-020` owns evidence-layer and accessibility completeness boundaries.
+- `spec:AST-029` owns this observational audit backfill and prevents it from settling
+ new public meaning.
+
+## Verification map
+
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------------- | --------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- |
+| FR1, AR1, AR3 | `ChatSystemMessage.test.tsx`, scoped axe, and exact-head Chromium receipts | Default, default with icon, long content, nested live log, neutral light/dark | Missing content, status role, icon content, wrapping, or browser-visible subject fails focused or browser evidence. | `audit:ChatSystemMessage/accessibility` |
+| FR2, AR2 | `ChatSystemMessage.test.tsx`, Divider tests, scoped axe, and exact-head Chromium receipts | Truthy divider labels plus empty string, numeric zero, and empty Fragment observations | Lost separator role, truthy label association, orientation, content, or paint fails focused or browser evidence; falsey anomalies stay routed to Divider. | `audit:ChatSystemMessage/behavior` |
+| FR3 | Closed audit inventory and exact-head observation of the divider/icon partition | Divider with supplied icon | The audit must expose, not silently omit, the unresolved branch; implementation remains unchanged until owner decision. | `audit:ChatSystemMessage/public-api` |
+| FR4 | Mutation-sensitive root-passthrough tests, source inspection, type checks, and target reflection | Default and divider roots | Removing ref, className, style, xstyle, ARIA forwarding, or owned role precedence fails focused tests. | `audit:ChatSystemMessage/public-api` |
+| FR5 | `themingTargets.test.ts`, source inspection, generated build, and exact-head computed paint | Both variants and color modes | Target/state metadata drift, raw styling, physical layout, or unresolved mode paint fails checks or browser evidence. | `audit:ChatSystemMessage/theming` |
+| FR6 | Source inspection, strict lint, and component test suite | Every render | Adding hidden state or an owned external resource triggers runtime review and corresponding evidence. | `audit:ChatSystemMessage/code-health` |
+| RTL relation | Source-hashed verified-N/A record | Both variants and caller-owned icon content | Directional component-owned content, physical positioning, ordering, scroll/drag, overlay, or horizontal keyboard behavior invalidates the record. | `audit:ChatSystemMessage/i18n-rtl` |
+| Browser matrix | `ChatSystemMessage.a11y.chromium.spec.ts` exact-head 10-sensor receipts | Default, icon, wrapped long content, divider, unresolved divider/icon, nested live log, 320px/coarse pointer, light/dark, D7 pairs | Stale build, wrong story, incorrect mode, missing semantics, default overflow, failed contrast, blank crop, or page error fails closed. | `audit:ChatSystemMessage/visual` |
+| Documentation and surface | Consumer docs, published declarations, block metadata, explicit story ownership, exports, and `check:knowledge` | Props, `./Chat` subpath, four blocks, draft record | Missing or stale public docs, export, owner route, target map, or knowledge shape fails validation or review. | `audit:ChatSystemMessage/docs` |
+
+## Decision log
+
+None. This draft records the wrapping correction, released observable behavior,
+and audit evidence. It introduces no public API, default, divider/icon decision,
+ownership transfer, or subjective visual decision.
+
+## Open questions
+
+- **OQ1 - Which explicit contract should govern `icon` with `variant="divider"`: render the icon with the divider label; introduce a breaking type restriction with the migration required by `architecture:public-component-api/INV9`; or retain the current no-op with documentation and a development warning?** (`human-api`)
+
+## Content boundary
+
+This file does not duplicate consumer examples, audit scores, screenshots,
+eligibility data, or shared Divider and system rules. It links to their owners.
diff --git a/packages/core/src/Chat/ChatSystemMessage.test.tsx b/packages/core/src/Chat/ChatSystemMessage.test.tsx
index d48f0ca001..9f1e8d2ae0 100644
--- a/packages/core/src/Chat/ChatSystemMessage.test.tsx
+++ b/packages/core/src/Chat/ChatSystemMessage.test.tsx
@@ -1,9 +1,25 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {describe, it, expect} from 'vitest';
+import {createRef, Fragment} from 'react';
+import {describe, expect, it} from 'vitest';
import {render, screen} from '@testing-library/react';
+import * as stylex from '@stylexjs/stylex';
import {ChatSystemMessage} from './ChatSystemMessage';
+const xstyleProbe = stylex.create({
+ root: {marginBlockStart: '13px'},
+});
+
+function expectProbeClasses(element: HTMLElement): void {
+ const classes = (stylex.props(xstyleProbe.root).className ?? '')
+ .split(' ')
+ .filter(className => className !== '' && !className.includes('__'));
+ expect(classes.length).toBeGreaterThan(0);
+ for (const className of classes) {
+ expect(element).toHaveClass(className);
+ }
+}
+
describe('ChatSystemMessage', () => {
it('renders children', () => {
render(<ChatSystemMessage>Conversation started</ChatSystemMessage>);
@@ -12,7 +28,6 @@ describe('ChatSystemMessage', () => {
it('renders default variant without divider lines', () => {
const {container} = render(<ChatSystemMessage>Hello</ChatSystemMessage>);
- // Divider lines have aria-hidden, so check there are none
const hiddenElements = container.querySelectorAll('[aria-hidden]');
expect(hiddenElements.length).toBe(0);
});
@@ -27,7 +42,7 @@ describe('ChatSystemMessage', () => {
expect(screen.getByRole('separator')).toHaveAccessibleName('Today');
});
- it('renders icon', () => {
+ it('renders icon in the default variant', () => {
render(
<ChatSystemMessage icon={<span data-testid="icon">*</span>}>
Notice
@@ -36,40 +51,117 @@ describe('ChatSystemMessage', () => {
expect(screen.getByTestId('icon')).toBeTruthy();
});
+ it('detects changes to the current divider and icon output for OQ1', () => {
+ // OQ1 is unresolved. This assertion detects current-output changes; it does
+ // not select whether Divider should render, reject, or warn on the icon.
+ render(
+ <ChatSystemMessage
+ icon={<span data-testid="divider-icon">*</span>}
+ variant="divider">
+ Today
+ </ChatSystemMessage>,
+ );
+ expect(screen.queryByTestId('divider-icon')).not.toBeInTheDocument();
+ });
+
it('applies variant class', () => {
render(
<ChatSystemMessage variant="divider" data-testid="sys">
Today
</ChatSystemMessage>,
);
- const el = screen.getByTestId('sys');
- expect(el).toHaveAttribute('data-variant', 'divider');
+ expect(screen.getByTestId('sys')).toHaveAttribute(
+ 'data-variant',
+ 'divider',
+ );
});
- it('applies data-testid', () => {
- render(<ChatSystemMessage data-testid="my-sys">Hello</ChatSystemMessage>);
- expect(screen.getByTestId('my-sys')).toBeTruthy();
+ it.each(['default', 'divider'] as const)(
+ 'preserves the complete root passthrough seam for %s',
+ variant => {
+ const ref = createRef<HTMLDivElement>();
+ render(
+ <ChatSystemMessage
+ ref={ref}
+ variant={variant}
+ data-testid={`sys-${variant}`}
+ aria-label={`${variant} system message`}
+ role="note"
+ className="consumer-system-message"
+ style={{outlineOffset: '3px'}}
+ xstyle={xstyleProbe.root}>
+ {variant === 'divider' ? 'Today' : 'Conversation started'}
+ </ChatSystemMessage>,
+ );
+
+ const root = screen.getByTestId(`sys-${variant}`);
+ expect(ref.current).toBe(root);
+ expect(root).toHaveClass('consumer-system-message');
+ expect(root).toHaveStyle({outlineOffset: '3px'});
+ expectProbeClasses(root);
+ expect(root).toHaveAttribute('aria-label', `${variant} system message`);
+ expect(root).toHaveAttribute('role', 'status');
+ expect(root).toHaveAttribute('data-variant', variant);
+ },
+ );
+
+ it.each([
+ {name: 'empty string', value: '', text: ''},
+ {name: 'numeric zero', value: 0, text: '0'},
+ {
+ name: 'empty fragment',
+ value: (
+ <Fragment>
+ {null}
+ {null}
+ </Fragment>
+ ),
+ text: '',
+ },
+ ])('keeps the default root for $name children', ({value, text}) => {
+ render(
+ <ChatSystemMessage data-testid="empty-partition">
+ {value}
+ </ChatSystemMessage>,
+ );
+ const root = screen.getByTestId('empty-partition');
+ expect(root).toHaveAttribute('role', 'status');
+ expect(root).toHaveTextContent(text);
});
- it('forwards rest props (data-*, id)', () => {
+ it.each([
+ {name: 'empty string', value: ''},
+ {name: 'numeric zero', value: 0},
+ {
+ name: 'empty fragment',
+ value: (
+ <Fragment>
+ {null}
+ {null}
+ </Fragment>
+ ),
+ },
+ ])('keeps the divider root for $name children', ({value}) => {
render(
- <ChatSystemMessage data-testid="sys" data-custom="x" id="sys-1">
- Hello
+ <ChatSystemMessage variant="divider" data-testid="empty-partition">
+ {value}
</ChatSystemMessage>,
);
- const el = screen.getByTestId('sys');
- expect(el).toHaveAttribute('data-custom', 'x');
- expect(el).toHaveAttribute('id', 'sys-1');
+ const root = screen.getByTestId('empty-partition');
+ expect(root).toHaveAttribute('role', 'status');
+ expect(root).toContainElement(screen.getByRole('separator'));
});
- it('forwards rest props in the divider variant', () => {
+ it('records Divider numeric-zero output for the shared FR15 advisory', () => {
render(
- <ChatSystemMessage variant="divider" data-testid="sys" data-custom="x">
- Today
+ <ChatSystemMessage variant="divider" data-testid="divider-zero">
+ {0}
</ChatSystemMessage>,
);
- const el = screen.getByTestId('sys');
- expect(el).toHaveAttribute('data-custom', 'x');
- expect(el).toHaveAttribute('role', 'status');
+ const root = screen.getByTestId('divider-zero');
+ const separator = screen.getByRole('separator');
+ expect(root).toHaveTextContent('00');
+ expect(separator).not.toHaveAccessibleName();
+ expect(separator).not.toHaveAttribute('aria-labelledby');
});
});
diff --git a/packages/core/src/Chat/ChatSystemMessage.tsx b/packages/core/src/Chat/ChatSystemMessage.tsx
index 712de67b8e..3dbf48d3cb 100644
--- a/packages/core/src/Chat/ChatSystemMessage.tsx
+++ b/packages/core/src/Chat/ChatSystemMessage.tsx
@@ -6,7 +6,7 @@
* @file ChatSystemMessage.tsx
* @input Uses React, StyleX, theme tokens
* @output Exports ChatSystemMessage component and ChatSystemMessageProps
- * @position Centered system/notice message in a chat thread
+ * @position Centered, wrapping system/notice message in a chat thread
*
* Renders centered, muted system messages like "conversation started",
* date separators, or status updates. Not a sender message — no avatar,
@@ -53,8 +53,8 @@ export interface ChatSystemMessageProps extends BaseProps<HTMLDivElement> {
variant?: ChatSystemMessageVariant;
/**
- * Optional icon rendered before the text.
- * Accepts any ReactNode — typically an Icon.
+ * Optional caller-provided icon content associated with the message.
+ * Accepts any ReactNode, typically an Icon.
*/
icon?: ReactNode;
}
@@ -85,13 +85,11 @@ const styles = stylex.create({
alignItems: 'center',
flexShrink: 0,
},
- // Content wrapper (to keep text + icon together)
+ // Content wrapper
content: {
display: 'inline-flex',
alignItems: 'center',
gap: spacingVars['--spacing-1-5'],
- flexShrink: 0,
- whiteSpace: 'nowrap',
},
});
diff --git a/packages/core/src/Chat/__tests__/ChatSystemMessage.a11y.chromium.spec.ts b/packages/core/src/Chat/__tests__/ChatSystemMessage.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..8352332459
--- /dev/null
+++ b/packages/core/src/Chat/__tests__/ChatSystemMessage.a11y.chromium.spec.ts
@@ -0,0 +1,1004 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChatSystemMessage.a11y.chromium.spec.ts
+ * @input Exact-head Storybook build plus checked-in ChatSystemMessage audit fixtures
+ * @output Chromium PNGs, canonical 10-sensor receipts, D7 pairs, and a fail-closed manifest
+ * @position Real-browser evidence for the ChatSystemMessage component audit
+ */
+
+import {createHash} from 'node:crypto';
+import {execFileSync} from 'node:child_process';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {expect, test, type Browser, type Page} from '@playwright/test';
+// @ts-expect-error -- pngjs ships no declarations; runtime support is pinned.
+import {PNG} from 'pngjs';
+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+const OUTPUT = path.resolve('test-results/chat-system-message-audit-evidence');
+const STATES_STORY = 'a11y-chatsystemmessage-audit--states';
+const NARROW_STORY = 'a11y-chatsystemmessage-audit--narrow';
+
+type Mode = 'light' | 'dark';
+type Direction = 'ltr';
+type Rgba = {r: number; g: number; b: number; a: number};
+
+interface AuditCase {
+ key: string;
+ storyId: string;
+ text: string;
+ variant: 'default' | 'divider';
+ expectedIconCount: number | null;
+ narrow: boolean;
+ expectWrap?: boolean;
+ nestedInLiveLog?: boolean;
+}
+
+interface ContrastPair {
+ part: 'text' | 'icon' | 'divider-line';
+ meaningful: boolean;
+ foreground: string;
+ backdrop: string;
+ ratio: number | null;
+ threshold: number | null;
+ exception: string | null;
+ passed: boolean;
+}
+
+interface ImageReceipt {
+ file: string;
+ sha256: string;
+ width: number;
+ height: number;
+ distinctColors: number;
+ nonBlank: boolean;
+}
+
+const CASES: AuditCase[] = [
+ {
+ key: 'default',
+ storyId: STATES_STORY,
+ text: 'Conversation started',
+ variant: 'default',
+ expectedIconCount: 0,
+ narrow: false,
+ },
+ {
+ key: 'default-icon',
+ storyId: STATES_STORY,
+ text: 'Messages are end-to-end encrypted',
+ variant: 'default',
+ expectedIconCount: 1,
+ narrow: false,
+ },
+ {
+ key: 'divider',
+ storyId: STATES_STORY,
+ text: 'Today',
+ variant: 'divider',
+ expectedIconCount: 0,
+ narrow: false,
+ },
+ {
+ key: 'divider-icon',
+ storyId: STATES_STORY,
+ text: 'March 15, 2026',
+ variant: 'divider',
+ // The public contract for this combination is unresolved. Record the
+ // observed count without freezing either candidate behavior in this test.
+ expectedIconCount: null,
+ narrow: false,
+ },
+ {
+ key: 'nested-log',
+ storyId: STATES_STORY,
+ text: 'Conversation archived',
+ variant: 'default',
+ expectedIconCount: 0,
+ narrow: false,
+ nestedInLiveLog: true,
+ },
+ {
+ key: 'narrow-default',
+ storyId: NARROW_STORY,
+ text: 'Conversation marked as resolved',
+ variant: 'default',
+ expectedIconCount: 1,
+ narrow: true,
+ },
+ {
+ key: 'narrow-divider',
+ storyId: NARROW_STORY,
+ text: 'March 15, 2026',
+ variant: 'divider',
+ expectedIconCount: 0,
+ narrow: true,
+ },
+ {
+ key: 'long-default',
+ storyId: NARROW_STORY,
+ text: 'Messages are end-to-end encrypted for everyone in this conversation and on every signed-in device.',
+ variant: 'default',
+ expectedIconCount: 1,
+ narrow: true,
+ expectWrap: true,
+ },
+];
+
+let server: StaticServer;
+let head = '';
+let build = '';
+let browserVersion = 'unknown';
+const receipts: Record<string, unknown>[] = [];
+
+function parseRgb(value: string): Rgba | null {
+ const channels = value.match(/[\d.]+/g)?.map(Number) ?? [];
+ return channels.length >= 3
+ ? {r: channels[0], g: channels[1], b: channels[2], a: channels[3] ?? 1}
+ : null;
+}
+
+function composite(foreground: Rgba, background: Rgba): Rgba {
+ const alpha = foreground.a + background.a * (1 - foreground.a);
+ const channel = (front: number, back: number) =>
+ alpha === 0
+ ? 0
+ : (front * foreground.a + back * background.a * (1 - foreground.a)) /
+ alpha;
+ return {
+ r: channel(foreground.r, background.r),
+ g: channel(foreground.g, background.g),
+ b: channel(foreground.b, background.b),
+ a: alpha,
+ };
+}
+
+function luminance(color: Rgba): number {
+ const linear = [color.r, color.g, color.b].map(channel => {
+ const value = channel / 255;
+ return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
+ });
+ return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2];
+}
+
+function contrastRatio(foreground: string, background: string): number | null {
+ const front = parseRgb(foreground);
+ const back = parseRgb(background);
+ if (front == null || back == null) {
+ return null;
+ }
+ const resolved = front.a < 1 ? composite(front, back) : front;
+ const first = luminance(resolved);
+ const second = luminance(back);
+ return Number(
+ (
+ (Math.max(first, second) + 0.05) /
+ (Math.min(first, second) + 0.05)
+ ).toFixed(2),
+ );
+}
+
+function inspectPng(file: string, bytes: Buffer): ImageReceipt {
+ const png = PNG.sync.read(bytes);
+ const colors = new Set<string>();
+ for (let index = 0; index < png.data.length; index += 4) {
+ colors.add(
+ `${png.data[index]},${png.data[index + 1]},${png.data[index + 2]},${png.data[index + 3]}`,
+ );
+ }
+ return {
+ file,
+ sha256: createHash('sha256').update(bytes).digest('hex'),
+ width: png.width,
+ height: png.height,
+ distinctColors: colors.size,
+ nonBlank: colors.size > 1,
+ };
+}
+
+function storyUrl(storyId: string, mode: Mode): string {
+ return (
+ `${server.origin}/iframe.html?id=${storyId}&viewMode=story` +
+ `&globals=colorMode:${mode};astryxTheme:neutral;direction:ltr`
+ );
+}
+
+async function openCase(
+ page: Page,
+ auditCase: AuditCase,
+ mode: Mode,
+): Promise<{errors: string[]}> {
+ const errors: string[] = [];
+ page.removeAllListeners('pageerror');
+ page.on('pageerror', error => errors.push(String(error)));
+ browserVersion = page.context().browser()?.version() ?? 'unknown';
+ await page.goto(storyUrl(auditCase.storyId, mode));
+ await page.locator(`[data-system-message-case="${auditCase.key}"]`).waitFor();
+ await page.waitForFunction(
+ expected =>
+ document.documentElement.getAttribute('data-theme') === expected,
+ mode,
+ );
+ await holdMotionStill(page);
+ await page.evaluate(async () => document.fonts.ready);
+ return {errors};
+}
+
+async function capture(
+ page: Page,
+ auditCase: AuditCase,
+ mode: Mode,
+ errors: string[],
+ options: {
+ viewport?: {width: number; height: number};
+ coarsePointer?: boolean;
+ touchPoints?: boolean;
+ } = {},
+): Promise<string[]> {
+ const viewport = options.viewport ?? {width: 1024, height: 768};
+ await page.setViewportSize(viewport);
+ const target = page.locator(`[data-system-message-case="${auditCase.key}"]`);
+ const actual = await target.evaluate(element => {
+ const root = element as HTMLElement;
+ const rootStyle = getComputedStyle(root);
+ const separator = root.querySelector<HTMLElement>('[role="separator"]');
+ const labelId = separator?.getAttribute('aria-labelledby');
+ const label = labelId ? document.getElementById(labelId) : null;
+ const textElement = label ?? root;
+ const content = root.firstElementChild as HTMLElement | null;
+ const textStyle = getComputedStyle(textElement);
+ const line = separator?.firstElementChild as HTMLElement | null;
+ const lineStyle = line ? getComputedStyle(line) : null;
+ const rect = root.getBoundingClientRect();
+ const contentRect = content?.getBoundingClientRect() ?? null;
+ const liveLog = root.closest<HTMLElement>('[role="log"]');
+ const textLineTops = new Set<number>();
+ const textWalker = document.createTreeWalker(
+ textElement,
+ NodeFilter.SHOW_TEXT,
+ );
+ for (
+ let textNode = textWalker.nextNode();
+ textNode != null;
+ textNode = textWalker.nextNode()
+ ) {
+ if ((textNode.textContent ?? '').trim() === '') {
+ continue;
+ }
+ const range = document.createRange();
+ range.selectNodeContents(textNode);
+ for (const lineRect of range.getClientRects()) {
+ if (lineRect.width > 0 && lineRect.height > 0) {
+ textLineTops.add(Math.round(lineRect.top * 2) / 2);
+ }
+ }
+ }
+ const textLineCount = textLineTops.size;
+ const parse = (value: string) => {
+ const channels = value.match(/[\d.]+/g)?.map(Number) ?? [];
+ return channels.length >= 3
+ ? {r: channels[0], g: channels[1], b: channels[2], a: channels[3] ?? 1}
+ : null;
+ };
+ const candidates: Element[] = [];
+ for (
+ let current = root.parentElement;
+ current != null;
+ current = current.parentElement
+ ) {
+ candidates.push(current);
+ }
+ candidates.push(document.body, document.documentElement);
+ const surfaceBackground =
+ candidates
+ .map(candidate => getComputedStyle(candidate).backgroundColor)
+ .find(value => {
+ const color = parse(value);
+ return color != null && color.a > 0.99;
+ }) ?? 'transparent';
+ const surface = parse(surfaceBackground);
+ const surfaceLuminanceClass =
+ surface == null
+ ? 'unknown'
+ : (() => {
+ const linear = [surface.r, surface.g, surface.b].map(channel => {
+ const value = channel / 255;
+ return value <= 0.04045
+ ? value / 12.92
+ : ((value + 0.055) / 1.055) ** 2.4;
+ });
+ const value =
+ 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2];
+ return value > 0.5 ? 'light' : 'dark';
+ })();
+ return {
+ storyId: new URL(location.href).searchParams.get('id'),
+ selectorCount: document.querySelectorAll(
+ `[data-system-message-case="${root.dataset.systemMessageCase}"]`,
+ ).length,
+ visible: rect.width > 0 && rect.height > 0,
+ text: (root.textContent ?? '').replace(/\s+/g, ' ').trim(),
+ role: root.getAttribute('role'),
+ variant: root.getAttribute('data-variant'),
+ separatorCount: root.querySelectorAll('[role="separator"]').length,
+ separatorOrientation: separator?.getAttribute('aria-orientation') ?? null,
+ separatorLabelledTargetText:
+ label?.textContent?.replace(/\s+/g, ' ').trim() ?? null,
+ iconCount: root.querySelectorAll('svg, [data-slot="icon"]').length,
+ interactiveCount: root.querySelectorAll(
+ 'button, a[href], input, select, textarea, [tabindex]:not([tabindex="-1"])',
+ ).length,
+ direction: rootStyle.direction,
+ color: textStyle.color,
+ iconColor:
+ root.querySelector('svg, [data-slot="icon"]') == null
+ ? null
+ : getComputedStyle(
+ root.querySelector('svg, [data-slot="icon"]') as Element,
+ ).color,
+ lineColor: lineStyle?.backgroundColor ?? null,
+ fontSize: textStyle.fontSize,
+ geometry: {x: rect.x, y: rect.y, width: rect.width, height: rect.height},
+ contentGeometry:
+ contentRect == null
+ ? null
+ : {
+ x: contentRect.x,
+ y: contentRect.y,
+ width: contentRect.width,
+ height: contentRect.height,
+ },
+ contentStartsWithinRoot:
+ contentRect == null || contentRect.left >= rect.left - 1,
+ contentEndsWithinRoot:
+ contentRect == null || contentRect.right <= rect.right + 1,
+ textLineCount,
+ liveLog:
+ liveLog == null
+ ? null
+ : {
+ role: liveLog.getAttribute('role'),
+ ariaLive: liveLog.getAttribute('aria-live'),
+ },
+ overflowFree:
+ root.scrollWidth <= root.clientWidth + 1 &&
+ document.documentElement.scrollWidth <= innerWidth + 1,
+ mode: document.documentElement.getAttribute('data-theme'),
+ theme:
+ document
+ .querySelector('[data-astryx-theme]')
+ ?.getAttribute('data-astryx-theme') ?? null,
+ colorScheme: getComputedStyle(document.documentElement).colorScheme,
+ surfaceBackground,
+ surfaceLuminanceClass,
+ viewport: {width: innerWidth, height: innerHeight},
+ devicePixelRatio,
+ reducedMotion: matchMedia('(prefers-reduced-motion: reduce)').matches,
+ forcedColors: matchMedia('(forced-colors: active)').matches,
+ coarsePointer: matchMedia('(pointer: coarse)').matches,
+ hoverCapable: matchMedia('(hover: hover)').matches,
+ touchPoints: navigator.maxTouchPoints,
+ fontsReady: document.fonts.status === 'loaded',
+ storyError: [
+ ...document.querySelectorAll(
+ '.sb-errordisplay, [data-testid="story-error"]',
+ ),
+ ].some(node => {
+ const box = node.getBoundingClientRect();
+ const style = getComputedStyle(node);
+ return (
+ box.width > 0 &&
+ box.height > 0 &&
+ style.display !== 'none' &&
+ style.visibility !== 'hidden' &&
+ style.opacity !== '0'
+ );
+ }),
+ };
+ });
+
+ const file = `ChatSystemMessage__${auditCase.key}__neutral-${mode}__ltr.png`;
+ const bytes = await target.screenshot({animations: 'disabled'});
+ fs.writeFileSync(path.join(OUTPUT, file), bytes);
+ const image = inspectPng(file, bytes);
+ const textRatio = contrastRatio(actual.color, actual.surfaceBackground);
+ const contrastPairs: ContrastPair[] = [
+ {
+ part: 'text',
+ meaningful: true,
+ foreground: actual.color,
+ backdrop: actual.surfaceBackground,
+ ratio: textRatio,
+ threshold: 4.5,
+ exception: null,
+ passed: textRatio != null && textRatio >= 4.5,
+ },
+ ];
+ if (actual.iconColor != null) {
+ contrastPairs.push({
+ part: 'icon',
+ meaningful: false,
+ foreground: actual.iconColor,
+ backdrop: actual.surfaceBackground,
+ ratio: contrastRatio(actual.iconColor, actual.surfaceBackground),
+ threshold: null,
+ exception:
+ 'The caller-provided icon appears with visible text and is not the only source of meaning.',
+ passed: true,
+ });
+ }
+ if (actual.lineColor != null) {
+ contrastPairs.push({
+ part: 'divider-line',
+ meaningful: false,
+ foreground: actual.lineColor,
+ backdrop: actual.surfaceBackground,
+ ratio: contrastRatio(actual.lineColor, actual.surfaceBackground),
+ threshold: null,
+ exception:
+ 'The visible label and labelled separator expose the section boundary without relying on the painted rule.',
+ passed: true,
+ });
+ }
+
+ const expected = {
+ build: head,
+ storyId: auditCase.storyId,
+ theme: 'neutral',
+ mode,
+ direction: 'ltr' as Direction,
+ viewport,
+ reducedMotion: true,
+ forcedColors: false,
+ coarsePointer: options.coarsePointer ?? false,
+ touchPoints: options.touchPoints ?? false,
+ role: 'status',
+ variant: auditCase.variant,
+ text: auditCase.text,
+ separatorCount: auditCase.variant === 'divider' ? 1 : 0,
+ separatorOrientation: auditCase.variant === 'divider' ? 'horizontal' : null,
+ separatorLabelledTargetText:
+ auditCase.variant === 'divider' ? auditCase.text : null,
+ iconCount: auditCase.expectedIconCount,
+ interactiveCount: 0,
+ expectWrap: auditCase.expectWrap ?? false,
+ textLineExpectation: auditCase.expectWrap ? 'multiple' : 'single',
+ liveLog: auditCase.nestedInLiveLog
+ ? {role: 'log', ariaLive: 'polite'}
+ : null,
+ };
+ const failures: string[] = [];
+ const check = (condition: boolean, message: string) => {
+ if (!condition) {
+ failures.push(message);
+ }
+ };
+
+ const textLineCountMatches = expected.expectWrap
+ ? actual.textLineCount >= 2
+ : actual.textLineCount === 1;
+
+ check(actual.storyId === expected.storyId, 'Storybook story id drifted');
+ check(actual.selectorCount === 1, 'expected exactly one audit subject');
+ check(actual.visible, 'audit subject has no visible geometry');
+ check(actual.text === expected.text, 'visible content drifted');
+ check(actual.role === expected.role, 'status role drifted');
+ check(actual.variant === expected.variant, 'variant reflection drifted');
+ check(
+ actual.separatorCount === expected.separatorCount,
+ 'separator count drifted',
+ );
+ check(
+ actual.separatorOrientation === expected.separatorOrientation,
+ 'separator orientation drifted',
+ );
+ check(
+ actual.separatorLabelledTargetText === expected.separatorLabelledTargetText,
+ 'separator labelled target text drifted',
+ );
+ if (expected.iconCount != null) {
+ check(actual.iconCount === expected.iconCount, 'icon presence drifted');
+ }
+ check(
+ actual.interactiveCount === expected.interactiveCount,
+ 'component unexpectedly owns an interactive target',
+ );
+ check(actual.direction === expected.direction, 'computed direction drifted');
+ check(actual.overflowFree, 'component or page has horizontal overflow');
+ check(
+ textLineCountMatches,
+ `text line count ${actual.textLineCount} does not match the ${expected.textLineExpectation} expectation`,
+ );
+ if (expected.expectWrap) {
+ check(
+ actual.contentStartsWithinRoot,
+ 'long content crosses the root start edge',
+ );
+ check(
+ actual.contentEndsWithinRoot,
+ 'long content crosses the root end edge',
+ );
+ }
+ check(
+ JSON.stringify(actual.liveLog) === JSON.stringify(expected.liveLog),
+ 'live-log composition drifted',
+ );
+ check(actual.theme === expected.theme, 'neutral theme did not settle');
+ check(actual.mode === expected.mode, 'color mode did not settle');
+ check(actual.colorScheme.includes(mode), 'computed color-scheme drifted');
+ check(
+ actual.surfaceLuminanceClass === mode,
+ 'surface luminance does not match color mode',
+ );
+ check(
+ actual.viewport.width === viewport.width &&
+ actual.viewport.height === viewport.height,
+ 'viewport drifted',
+ );
+ check(actual.devicePixelRatio === 1, 'device pixel ratio drifted');
+ check(actual.reducedMotion, 'motion was not held still');
+ check(!actual.forcedColors, 'forced-colors unexpectedly active');
+ check(
+ actual.coarsePointer === expected.coarsePointer,
+ 'pointer modality drifted',
+ );
+ if (expected.touchPoints) {
+ check(actual.touchPoints > 0, 'coarse-pointer context has no touch points');
+ }
+ check(actual.fontsReady, 'fonts did not settle');
+ check(!actual.storyError, 'Storybook rendered an error surface');
+ check(errors.length === 0, 'page emitted an error');
+ check(image.nonBlank, 'subject crop is blank');
+ for (const pair of contrastPairs) {
+ check(pair.passed, `${pair.part} contrast pair failed`);
+ }
+
+ const sensorRows = {
+ Build: {
+ expected: {headSha: head},
+ observed: {checkoutSha: head, storybookSha: build},
+ passed: build === head,
+ },
+ Story: {
+ expected: {id: expected.storyId, case: auditCase.key},
+ observed: {id: actual.storyId, selectorCount: actual.selectorCount},
+ passed: actual.storyId === expected.storyId && actual.selectorCount === 1,
+ },
+ Theme: {
+ expected: expected.theme,
+ observed: actual.theme,
+ passed: actual.theme === expected.theme,
+ },
+ 'Color mode': {
+ expected: {
+ mode,
+ colorScheme: mode,
+ surfaceLuminanceClass: mode,
+ },
+ observed: {
+ mode: actual.mode,
+ colorScheme: actual.colorScheme,
+ surfaceBackground: actual.surfaceBackground,
+ surfaceLuminanceClass: actual.surfaceLuminanceClass,
+ },
+ passed:
+ actual.mode === mode &&
+ actual.colorScheme.includes(mode) &&
+ actual.surfaceLuminanceClass === mode,
+ },
+ Direction: {
+ expected: expected.direction,
+ observed: actual.direction,
+ passed: actual.direction === expected.direction,
+ },
+ 'Viewport/media': {
+ expected: {
+ viewport,
+ devicePixelRatio: 1,
+ reducedMotion: true,
+ forcedColors: false,
+ coarsePointer: expected.coarsePointer,
+ },
+ observed: {
+ viewport: actual.viewport,
+ devicePixelRatio: actual.devicePixelRatio,
+ reducedMotion: actual.reducedMotion,
+ forcedColors: actual.forcedColors,
+ coarsePointer: actual.coarsePointer,
+ hoverCapable: actual.hoverCapable,
+ touchPoints: actual.touchPoints,
+ },
+ passed:
+ actual.viewport.width === viewport.width &&
+ actual.viewport.height === viewport.height &&
+ actual.devicePixelRatio === 1 &&
+ actual.reducedMotion &&
+ !actual.forcedColors &&
+ actual.coarsePointer === expected.coarsePointer &&
+ (!expected.touchPoints || actual.touchPoints > 0),
+ },
+ 'Rendered state': {
+ expected: {
+ role: expected.role,
+ variant: expected.variant,
+ text: expected.text,
+ separatorCount: expected.separatorCount,
+ separatorOrientation: expected.separatorOrientation,
+ separatorLabelledTargetText: expected.separatorLabelledTargetText,
+ iconCount: expected.iconCount,
+ interactiveCount: 0,
+ liveLog: expected.liveLog,
+ },
+ observed: {
+ role: actual.role,
+ variant: actual.variant,
+ text: actual.text,
+ separatorCount: actual.separatorCount,
+ separatorOrientation: actual.separatorOrientation,
+ separatorLabelledTargetText: actual.separatorLabelledTargetText,
+ iconCount: actual.iconCount,
+ interactiveCount: actual.interactiveCount,
+ liveLog: actual.liveLog,
+ dividerIconContract:
+ auditCase.key === 'divider-icon' ? 'unresolved' : null,
+ contrastPairs,
+ },
+ passed:
+ actual.role === expected.role &&
+ actual.variant === expected.variant &&
+ actual.text === expected.text &&
+ actual.separatorCount === expected.separatorCount &&
+ actual.separatorOrientation === expected.separatorOrientation &&
+ actual.separatorLabelledTargetText ===
+ expected.separatorLabelledTargetText &&
+ (expected.iconCount == null ||
+ actual.iconCount === expected.iconCount) &&
+ actual.interactiveCount === 0 &&
+ JSON.stringify(actual.liveLog) === JSON.stringify(expected.liveLog) &&
+ contrastPairs.every(pair => pair.passed),
+ },
+ 'Subject geometry': {
+ expected: {
+ visible: true,
+ overflowFree: true,
+ nonZero: true,
+ wraps: expected.expectWrap,
+ textLineExpectation: expected.textLineExpectation,
+ insideInlineEdges: expected.expectWrap,
+ },
+ observed: {
+ ...actual.geometry,
+ contentGeometry: actual.contentGeometry,
+ contentStartsWithinRoot: actual.contentStartsWithinRoot,
+ contentEndsWithinRoot: actual.contentEndsWithinRoot,
+ textLineCount: actual.textLineCount,
+ overflowFree: actual.overflowFree,
+ },
+ passed:
+ actual.visible &&
+ actual.geometry.width > 0 &&
+ actual.geometry.height > 0 &&
+ actual.overflowFree &&
+ textLineCountMatches &&
+ (!expected.expectWrap ||
+ (actual.contentStartsWithinRoot && actual.contentEndsWithinRoot)),
+ },
+ 'Settled render': {
+ expected: {fontsReady: true, pageErrors: 0, storyError: false},
+ observed: {
+ fontsReady: actual.fontsReady,
+ pageErrors: errors,
+ storyError: actual.storyError,
+ },
+ passed: actual.fontsReady && errors.length === 0 && !actual.storyError,
+ },
+ Image: {
+ expected: {nonBlank: true, nonZeroPixels: true},
+ observed: image,
+ passed: image.nonBlank && image.width > 0 && image.height > 0,
+ },
+ };
+ const receipt = {
+ frame: `${auditCase.key}__neutral-${mode}__ltr`,
+ passed: failures.length === 0,
+ failures,
+ expected,
+ observed: actual,
+ contrastPairs,
+ sensors: sensorRows,
+ image,
+ };
+ fs.writeFileSync(
+ path.join(OUTPUT, `${file}.sensors.json`),
+ `${JSON.stringify(receipt, null, 2)}\n`,
+ );
+ receipts.push(receipt);
+ return failures.map(detail => `${auditCase.key}/${mode}: ${detail}`);
+}
+
+async function writeContactSheet(page: Page): Promise<ImageReceipt> {
+ const figures = receipts
+ .map(receipt => {
+ const image = receipt.image as ImageReceipt;
+ const bytes = fs.readFileSync(path.join(OUTPUT, image.file));
+ return `<figure><img src="data:image/png;base64,${bytes.toString('base64')}" alt=""><figcaption>${String(receipt.frame)}</figcaption></figure>`;
+ })
+ .join('');
+ await page.setViewportSize({width: 1200, height: 900});
+ await page.setContent(`<!doctype html>
+ <style>
+ html { color-scheme: light; background: #f3f4f6; }
+ body { margin: 20px; font: 12px/1.35 system-ui, sans-serif; color: #111827; }
+ h1 { margin: 0 0 16px; font-size: 20px; }
+ main { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; }
+ figure { margin: 0; padding: 10px; border: 1px solid #d1d5db; border-radius: 6px; background: white; }
+ img { display: block; width: 100%; height: 96px; object-fit: contain; }
+ figcaption { margin-top: 8px; overflow-wrap: anywhere; }
+ </style>
+ <h1>ChatSystemMessage exact-head state evidence</h1>
+ <main>${figures}</main>`);
+ await page.locator('img').evaluateAll(async images => {
+ await Promise.all(
+ images.map(async image => {
+ const candidate = image as HTMLImageElement;
+ if (candidate.complete) {
+ return;
+ }
+ await new Promise<void>((resolve, reject) => {
+ candidate.addEventListener('load', () => resolve(), {once: true});
+ candidate.addEventListener(
+ 'error',
+ () => reject(new Error('contact-sheet image failed')),
+ {once: true},
+ );
+ });
+ }),
+ );
+ });
+ const file = 'ChatSystemMessage__contact-sheet.png';
+ const bytes = await page.screenshot({fullPage: true, animations: 'disabled'});
+ fs.writeFileSync(path.join(OUTPUT, file), bytes);
+ return inspectPng(file, bytes);
+}
+
+async function mobilePage(
+ browser: Browser,
+): Promise<{page: Page; close: () => Promise<void>}> {
+ const context = await browser.newContext({
+ viewport: {width: 320, height: 640},
+ deviceScaleFactor: 1,
+ hasTouch: true,
+ isMobile: true,
+ reducedMotion: 'reduce',
+ });
+ return {
+ page: await context.newPage(),
+ close: async () => {
+ await context.close();
+ },
+ };
+}
+
+test.describe.configure({mode: 'serial', retries: 0});
+
+test.beforeAll(async () => {
+ head = execFileSync('git', ['rev-parse', 'HEAD'], {encoding: 'utf8'}).trim();
+ const dirtyTracked = execFileSync(
+ 'git',
+ ['status', '--porcelain', '--untracked-files=no'],
+ {encoding: 'utf8'},
+ ).trim();
+ const dirtyEvidenceFiles = execFileSync(
+ 'git',
+ [
+ 'status',
+ '--porcelain',
+ '--untracked-files=all',
+ '--',
+ 'apps/storybook/stories/ChatSystemMessage.stories.tsx',
+ 'apps/storybook/stories/ChatSystemMessageAudit.stories.tsx',
+ 'packages/core/src/Chat/__tests__/ChatSystemMessage.a11y.chromium.spec.ts',
+ ],
+ {encoding: 'utf8'},
+ ).trim();
+ const dirty = [dirtyTracked, dirtyEvidenceFiles].filter(Boolean).join('\n');
+ if (dirty !== '') {
+ throw new Error(
+ `browser evidence requires a clean committed source set: ${dirty}`,
+ );
+ }
+ if (process.env.ASTRYX_HEAD_SHA && process.env.ASTRYX_HEAD_SHA !== head) {
+ throw new Error('PR head differs from the checked out source');
+ }
+ fs.rmSync(OUTPUT, {recursive: true, force: true});
+ fs.mkdirSync(OUTPUT, {recursive: true});
+ server = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+ const stamp = await fetch(`${server.origin}/astryx-build-sha.txt`);
+ if (!stamp.ok) {
+ throw new Error('Storybook build is missing its source stamp');
+ }
+ build = (await stamp.text()).trim();
+ if (build !== head) {
+ throw new Error('Storybook bytes differ from the PR head');
+ }
+});
+
+test.afterAll(async () => {
+ const expectedFrames = CASES.flatMap(auditCase =>
+ (['light', 'dark'] as const).map(
+ mode => `${auditCase.key}__neutral-${mode}__ltr`,
+ ),
+ );
+ const observedFrames = new Set(
+ receipts.map(receipt => String(receipt.frame)),
+ );
+ const d7ContrastPairs = receipts.flatMap(receipt =>
+ (receipt.contrastPairs as ContrastPair[]).map(pair => ({
+ frame: receipt.frame,
+ ...pair,
+ })),
+ );
+ const matrixFailures = [
+ ...expectedFrames
+ .filter(frame => !observedFrames.has(frame))
+ .map(frame => `missing frame: ${frame}`),
+ ...receipts
+ .filter(receipt => receipt.passed !== true)
+ .map(receipt => `failed frame: ${String(receipt.frame)}`),
+ ...d7ContrastPairs
+ .filter(pair => !pair.passed)
+ .map(pair => `failed D7 pair: ${String(pair.frame)}/${pair.part}`),
+ ];
+ const contactSheetFile = 'ChatSystemMessage__contact-sheet.png';
+ const contactSheetPath = path.join(OUTPUT, contactSheetFile);
+ const contactSheet = fs.existsSync(contactSheetPath)
+ ? inspectPng(contactSheetFile, fs.readFileSync(contactSheetPath))
+ : null;
+ if (contactSheet?.nonBlank !== true) {
+ matrixFailures.push('missing or blank contact sheet');
+ }
+ if (head && build) {
+ fs.writeFileSync(
+ path.join(OUTPUT, 'manifest.json'),
+ `${JSON.stringify(
+ {
+ version: 1,
+ component: 'core/ChatSystemMessage',
+ headSha: head,
+ storybookSha: build,
+ browser: browserVersion,
+ failClosed: true,
+ matrixComplete: matrixFailures.length === 0,
+ matrixFailures,
+ sensorCount: 10,
+ requiredSensors: [
+ 'Build',
+ 'Story',
+ 'Theme',
+ 'Color mode',
+ 'Direction',
+ 'Viewport/media',
+ 'Rendered state',
+ 'Subject geometry',
+ 'Settled render',
+ 'Image',
+ ],
+ visualEvidence: {
+ requiredPair: true,
+ reason:
+ 'The production wrapping repair changes long-content pixels. The PR report links the failing-before and fixed-after exact-head artifacts and receipts.',
+ subjectiveAcceptanceClaimed: false,
+ contactSheet,
+ },
+ unresolved: {
+ dividerIcon:
+ 'The public icon input is supplied to the divider fixture and its observed output is recorded without asserting either candidate contract.',
+ },
+ notApplicable: {
+ hover: 'ChatSystemMessage has no component-owned interaction.',
+ focus:
+ 'ChatSystemMessage introduces no focusable element or focus-visible state.',
+ pressed: 'ChatSystemMessage has no activation behavior.',
+ disabled: 'ChatSystemMessage exposes no disabled state.',
+ loading: 'ChatSystemMessage exposes no loading state.',
+ selected: 'ChatSystemMessage exposes no selection state.',
+ keyboard: 'ChatSystemMessage owns no keyboard interaction.',
+ pointerTarget: 'ChatSystemMessage owns no pointer target.',
+ },
+ emptyContentPartitions: {
+ emptyString:
+ 'Focused unit evidence: the default variant keeps role=status and renders the content unchanged (empty). In the divider variant, the status root and separator remain; no visible label or accessible name is produced.',
+ numericZero:
+ 'Focused unit evidence: the default variant keeps role=status and renders the content unchanged as one 0. In the divider variant, the status root and separator remain; Divider paints two zero text nodes (textContent="00") with no accessible name.',
+ emptyFragment:
+ 'Focused unit evidence: the default variant keeps role=status and renders the content unchanged (empty). In the divider variant, the status root and separator remain; no visible label or accessible name is produced.',
+ },
+ sharedAdvisories: {
+ dividerFalseyLabel:
+ 'Under spec:AST-002/FR15, empty string and empty Fragment content leave the separator without a visible label or accessible name, while numeric zero paints stray textContent="00" with no accessible name. This shared advisory is routed to component:Divider.',
+ dividerLongLabelOverflow:
+ 'Source inspection shows that a long divider label can cross the inline edge because Divider owns a non-shrinking label. This is routed to component:Divider without assigning the defect to ChatSystemMessage.',
+ dividerForcedColors:
+ 'The Divider rule may disappear in forced colors; this audit does not exercise that mode and routes the advisory to component:Divider.',
+ },
+ unverified: {
+ forcedColors:
+ 'Forced-colors rendering was not exercised. The default row makes no support claim, and the disappearing Divider rule is a shared component:Divider advisory.',
+ assistiveTechnology:
+ 'Browser role exposure is measured, but spoken announcement timing and output were not verified with real assistive technology.',
+ nestedLiveRegions:
+ 'The nested-log frame records role=status inside ChatMessageList role=log aria-live=polite, but double-announcement behavior is unverified under spec:AST-009/FR4 and FR10.',
+ },
+ stateVisualConformance: {
+ default: ['text', 'text-with-icon', 'wrapped-long-content'],
+ divider: [
+ 'labelled-separator',
+ 'unresolved-divider-icon-observation',
+ ],
+ nestedLiveLog: ['status-inside-polite-log-unverified'],
+ colorModes: ['light', 'dark'],
+ narrowCoarsePointer: [
+ 'default-with-icon',
+ 'divider',
+ 'wrapped-long-content',
+ ],
+ },
+ frames: receipts,
+ d7ContrastPairs,
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+ }
+ await server?.close();
+ expect(matrixFailures, 'complete exact-head evidence matrix').toEqual([]);
+});
+
+test('captures the complete neutral light and dark state matrix', async ({
+ page,
+}) => {
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ const failures: string[] = [];
+ for (const mode of ['light', 'dark'] as const) {
+ for (const auditCase of CASES.filter(item => !item.narrow)) {
+ const {errors} = await openCase(page, auditCase, mode);
+ failures.push(...(await capture(page, auditCase, mode, errors)));
+ }
+ }
+ expect(failures).toEqual([]);
+});
+
+test('captures 320px coarse-pointer reflow and the contact sheet', async ({
+ browser,
+}) => {
+ const mobile = await mobilePage(browser);
+ try {
+ const failures: string[] = [];
+ for (const mode of ['light', 'dark'] as const) {
+ for (const auditCase of CASES.filter(item => item.narrow)) {
+ const {errors} = await openCase(mobile.page, auditCase, mode);
+ failures.push(
+ ...(await capture(mobile.page, auditCase, mode, errors, {
+ viewport: {width: 320, height: 640},
+ coarsePointer: true,
+ touchPoints: true,
+ })),
+ );
+ }
+ }
+ const contactSheet = await writeContactSheet(mobile.page);
+ expect(contactSheet.nonBlank).toBe(true);
+ expect(failures).toEqual([]);
+ } finally {
+ await mobile.close();
+ }
+});