Skip to content

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

TypeScript

[Component Audit] ChatMessageList: preserve numeric empty-state content

Cindy Zhangddb63c3521ed
diff --git a/.changeset/chat-message-list-numeric-empty-state.md b/.changeset/chat-message-list-numeric-empty-state.md
new file mode 100644
index 0000000000..b1d7d0e348
--- /dev/null
+++ b/.changeset/chat-message-list-numeric-empty-state.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Render numeric zero when it is passed as the ChatMessageList empty state. A valid ReactNode should not disappear when the transcript is empty.
+
+@cixzhang
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index a68b0597d8..35edbf8859 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -987,6 +987,35 @@ jobs:
retention-days: 30
if-no-files-found: ignore
+ # A component audit needs evidence for each state it scores. The generic
+ # visual manifest does not include semantic-state or geometry sensors, so
+ # this existing Chromium owner captures bounded, fail-closed receipts.
+ - name: Run ChatMessageList audit browser evidence
+ if: github.event_name == 'pull_request' && startsWith(github.event.pull_request.title, '[Component Audit] ChatMessageList:')
+ env:
+ ASTRYX_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
+ run: |
+ node .github/scripts/accessibility-audit.js \
+ --storybook-dir apps/storybook/dist \
+ --output chat-message-list-a11y-report.json \
+ --components ChatMessageList \
+ --baseline .github/a11y-baseline.json \
+ --fail-on-new
+ pnpm exec playwright test \
+ packages/core/src/Chat/__tests__/ChatMessageList.a11y.chromium.spec.ts \
+ --project chromium
+
+ - name: Upload ChatMessageList audit evidence
+ if: always() && github.event_name == 'pull_request' && startsWith(github.event.pull_request.title, '[Component Audit] ChatMessageList:')
+ uses: actions/upload-artifact@v7
+ with:
+ name: chat-message-list-audit-evidence-${{ needs.build-storybook.outputs.short_hash }}
+ path: |
+ chat-message-list-a11y-report.json
+ test-results/chat-message-list-audit-evidence/
+ retention-days: 30
+ if-no-files-found: ignore
+
# 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 656f1928f0..b0449e9103 100644
--- a/apps/storybook/rtl-audit/verified-not-applicable.json
+++ b/apps/storybook/rtl-audit/verified-not-applicable.json
@@ -257,5 +257,14 @@
"packages/core/src/Chat/ChatLayoutScrollButton.tsx": "sha256:cb604bf1b1df34dee472865372eb0bec876e6cb733029e3b10f6da97dd33fb2c",
"packages/core/src/Chat/index.ts": "sha256:0f4a9d3ee08b4fcd43698ad017460aad109c500d2411913f509506d2a27387bb"
}
+ },
+ {
+ "component": "core/ChatMessageList",
+ "reason": "ChatMessageList owns a vertical flex transcript, symmetric logical padding and gap, a block-axis top loading sentinel, and a block-axis spacer. It has no directional glyph, inline-side placement, reordered controls, horizontal scrolling or dragging, side-placed overlay, or horizontal keyboard behavior. Message sender alignment and content belong to its child components; the list only supplies density context. The five independently owned fixtures exercise list states without adding an inline-axis signal for the RTL detectors.",
+ "evidence": {
+ "apps/storybook/stories/ChatMessageList.stories.tsx": "sha256:a5c49da2307d820da0720c00d4780f22d4039579d649905b2b1039a8f2e12d35",
+ "packages/core/src/Chat/ChatMessageList.tsx": "sha256:9d7dc59f2fa33cc13175f1093b509aea4ff54a76b9ef83d576d55f6c4d0bc541",
+ "packages/core/src/Chat/index.ts": "sha256:0f4a9d3ee08b4fcd43698ad017460aad109c500d2411913f509506d2a27387bb"
+ }
}
]
diff --git a/apps/storybook/stories/ChatMessageList.stories.tsx b/apps/storybook/stories/ChatMessageList.stories.tsx
new file mode 100644
index 0000000000..7415e2974d
--- /dev/null
+++ b/apps/storybook/stories/ChatMessageList.stories.tsx
@@ -0,0 +1,144 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChatMessageList.stories.tsx
+ * @input ChatMessageList and the existing Chat message primitives
+ * @output Reusable transcript, empty, density/alignment, overflow, and loading fixtures
+ * @position Component-owned Storybook evidence for ChatMessageList
+ */
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {
+ ChatMessage,
+ ChatMessageBubble,
+ ChatMessageList,
+ ChatSystemMessage,
+} from '@astryxdesign/core/Chat';
+import {Text} from '@astryxdesign/core/Text';
+
+const meta = {
+ title: 'Core/ChatMessageList',
+ component: ChatMessageList,
+ tags: ['autodocs'],
+ args: {children: null},
+} satisfies Meta<typeof ChatMessageList>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+const pendingOlderMessages = () =>
+ new Promise<void>(() => {
+ // Hold the documented pending state for repeatable browser evidence.
+ });
+
+export const Conversation: Story = {
+ args: {density: 'balanced', align: 'bottom', isStreaming: false},
+ render: args => (
+ <div style={{height: 440, display: 'flex', flexDirection: 'column'}}>
+ <ChatMessageList {...args}>
+ <ChatSystemMessage variant="divider">Today</ChatSystemMessage>
+ <ChatMessage sender="user">
+ <ChatMessageBubble>Could you summarize the update?</ChatMessageBubble>
+ </ChatMessage>
+ <ChatMessage sender="assistant">
+ <ChatMessageBubble>
+ The issue is resolved. The next update will include the remaining
+ details.
+ </ChatMessageBubble>
+ </ChatMessage>
+ </ChatMessageList>
+ </div>
+ ),
+};
+
+export const Empty: Story = {
+ render: () => (
+ <div style={{display: 'flex', flexWrap: 'wrap', gap: 16}}>
+ <div
+ style={{
+ width: 280,
+ height: 320,
+ display: 'flex',
+ flexDirection: 'column',
+ }}>
+ <ChatMessageList
+ aria-label="Text empty state"
+ emptyState={<Text>No messages yet</Text>}>
+ {[]}
+ </ChatMessageList>
+ </div>
+ <div
+ style={{
+ width: 280,
+ height: 320,
+ display: 'flex',
+ flexDirection: 'column',
+ }}>
+ <ChatMessageList aria-label="Numeric empty state" emptyState={0}>
+ {[]}
+ </ChatMessageList>
+ </div>
+ </div>
+ ),
+};
+
+export const DensityAndAlignment: Story = {
+ render: () => (
+ <div style={{display: 'flex', flexWrap: 'wrap', gap: 16}}>
+ {(['compact', 'balanced', 'spacious'] as const).map((density, index) => (
+ <div
+ key={density}
+ style={{
+ width: 280,
+ height: 320,
+ display: 'flex',
+ flexDirection: 'column',
+ }}>
+ <Text type="supporting">
+ {density} / {index === 0 ? 'top' : 'bottom'}
+ </Text>
+ <ChatMessageList
+ density={density}
+ align={index === 0 ? 'top' : 'bottom'}>
+ <ChatMessage sender="assistant">
+ <ChatMessageBubble>A short conversation.</ChatMessageBubble>
+ </ChatMessage>
+ </ChatMessageList>
+ </div>
+ ))}
+ </div>
+ ),
+};
+
+export const Overflow: Story = {
+ render: () => (
+ <div style={{height: 220, overflowY: 'auto'}}>
+ <ChatMessageList align="top">
+ {Array.from({length: 8}, (_, index) => (
+ <ChatMessage
+ key={index}
+ sender={index % 2 === 0 ? 'user' : 'assistant'}>
+ <ChatMessageBubble>
+ Conversation item {index + 1}. This message wraps on narrower
+ screens while the surrounding transcript remains scrollable.
+ </ChatMessageBubble>
+ </ChatMessage>
+ ))}
+ </ChatMessageList>
+ </div>
+ ),
+};
+
+export const LoadingOlder: Story = {
+ render: () => (
+ <div style={{height: 320, display: 'flex', flexDirection: 'column'}}>
+ <ChatMessageList align="top" scrollToTopAction={pendingOlderMessages}>
+ <ChatMessage sender="assistant">
+ <ChatMessageBubble>
+ Earlier message remains readable while older messages load.
+ </ChatMessageBubble>
+ </ChatMessage>
+ </ChatMessageList>
+ </div>
+ ),
+};
diff --git a/packages/core/src/Chat/ChatMessageList.spec.md b/packages/core/src/Chat/ChatMessageList.spec.md
new file mode 100644
index 0000000000..05401a8180
--- /dev/null
+++ b/packages/core/src/Chat/ChatMessageList.spec.md
@@ -0,0 +1,222 @@
+---
+schema_version: 3
+template_version: 6
+kind: component
+id: component:ChatMessageList
+authority: draft
+archive_reason: null
+superseded_by: null
+approved_by: null
+approved_at: null
+owners: [cixzhang]
+review_triggers:
+ [public-api, behavior, layout, scrolling, accessibility, theming, testing]
+verified_by:
+ [
+ packages/core/src/Chat/ChatMessageList.test.tsx,
+ packages/core/src/Chat/__tests__/ChatMessageList.a11y.chromium.spec.ts,
+ apps/storybook/stories/ChatMessageList.stories.tsx,
+ packages/core/src/theme/themingTargets.test.ts,
+ ]
+modules: []
+families: []
+design_specs: []
+architecture:
+ [
+ architecture:public-component-api,
+ architecture:component-test-sufficiency,
+ architecture:component-style-authoring,
+ architecture:component-theming-surface,
+ architecture:react-component-runtime,
+ architecture:knowledge-contracts,
+ ]
+contributing: []
+system_specs: [spec:AST-029]
+---
+
+# ChatMessageList component contract
+
+This draft is an observational account of shipped `core/ChatMessageList`. Its
+candidate invariants name their source and evidence; they do not decide any
+new API, default, loading protocol, or visual direction. The current shared
+records linked above continue to govern independently.
+
+## Contract at a glance
+
+| Area | Contract |
+| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | `children`, `emptyState`, `scrollToTopAction`, `density`, `gap`, `align`, `isStreaming`, the root's `BaseProps<HTMLDivElement>`, and `ref`. |
+| Behavior | A polite log holds caller messages. Density selects row spacing and passes through context. A top sentinel can request older messages. A spacer moves short lists down by default. |
+| End-user impact | A reader with a numeric empty-state value sees `0`; other transcript arrangements remain unchanged. |
+| Builder impact | None. No new caller choice or migration is introduced. |
+| Compatibility/readiness | The published `./Chat` subpath and its defaults remain unchanged. This is a draft pending verification and exact-head owner review. |
+| Review checks | Reject a claim that the list owns ChatLayout auto-scroll, that a draft settles an unobserved loading policy, or that DOM `aria-busy` proves spoken output. |
+| Governing rules | `architecture:public-component-api/INV1, INV5–INV8`; `architecture:react-component-runtime/INV3, INV5–INV6`; `spec:AST-029/FR2–FR5`. |
+
+This table is a review projection; the body below describes the observed
+surface rather than creating new authority.
+
+## Intent
+
+ChatMessageList is the presentational message container within the Chat
+composition. It owns a flex-column transcript, spacing/density context, an
+optional empty state and older-message sentinel, and the log's rendered ARIA
+attributes. `ChatLayout` owns auto-follow scrolling and the dock; message and
+bubble components own sender presentation and content.
+
+Consumer prop syntax and examples remain in `ChatMessageList.doc.mjs`.
+
+## Compatibility and migration
+
+- Released default preserved: yes. The published Core package exposes `./Chat`
+ with `ChatMessageList` and `ChatMessageListProps`.
+- Compatibility class: no new API, default, or migration. Visible numeric
+ empty-state content follows the existing `ReactNode` type.
+- Controlled/uncontrolled behavior: not applicable; there is no controlled
+ value on this component.
+- Migration decision: none.
+
+## Ownership boundary
+
+**Owns**
+
+- The outer log element, its public DOM/ref/style passthrough, and the
+ `chat-message-list` target with its `density` selector.
+- The inner flex-column message box and density-based padding and gap.
+- The short-list block spacer when `align` is `bottom`.
+- The optional `emptyState` substitution and older-message sentinel/loading
+ indicator.
+- Passing the inner content element to `ChatLayoutContext.contentRef` while a
+ layout is present.
+
+**Does not own / non-goals**
+
+- Auto-scroll, scroll-to-bottom, dock, and scroll-owner selection, which belong
+ to `component:ChatLayout` and its scroll hooks.
+- Sender identity, message alignment, bubbles, metadata, and text semantics,
+ which belong to their child components.
+- The caller's region landmark or an accessible name for arbitrary transcript
+ context; no new naming policy is made by this draft.
+
+## Public concepts
+
+| Concept | Closed values or states | Meaning observed | Availability | Default | Owner | Stability | Invalid-value behavior |
+| ------------------- | ----------------------------------------------- | --------------------------------------------------------------- | ------------- | ---------- | --------- | --------- | -------------------------------------------------- |
+| `children` | `ReactNode` | Top-level transcript content | every render | required | caller | released | null, false, or `[]` counts empty at the top level |
+| `emptyState` | `ReactNode`; omitted | Substitutes for top-level empty children | empty state | omitted | caller | released | absent renders no substitute |
+| `scrollToTopAction` | async function; omitted | Invoked when the top sentinel intersects | when supplied | omitted | caller | released | absent creates no sentinel or observer |
+| `density` | `compact`; `balanced`; `spacious` | Chooses message spacing and child density context | every render | `balanced` | component | released | closed type union |
+| `gap` | published `SpacingStep`; omitted | Overrides the list's top-level row gap independently of density | every render | omitted | caller | released | closed type union |
+| `align` | `top`; `bottom` | Positions short content at the start or block end | every render | `bottom` | component | released | closed type union |
+| `isStreaming` | `true`; `false` | Exposes `aria-busy` on the polite log while streaming | every render | `false` | caller | released | boolean |
+| root passthrough | `ref`, accepted DOM/data/ARIA and styling props | Extends the outer log element | every render | omitted | caller | released | owned role/live/busy attributes retain precedence |
+
+The table records the implementation's top-level emptiness test; it does not
+promise recursive child inspection or resolve the meaning of arbitrary
+non-rendering React nodes.
+
+## Behavioral and layout contract
+
+These candidate invariants record observable shipped behavior. A `verify`
+state means the audit has not upgraded implementation into policy.
+
+| ID | Candidate invariant | Basis | Draft review state |
+| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------ | ------------------ |
+| FR1 | The outer root renders `role="log"`, `aria-live="polite"`, and `tabIndex=0`; `isStreaming=true` adds `aria-busy="true"`, which is absent otherwise. | Shipped source, colocated DOM tests and consumer docs | verify |
+| FR2 | The chosen density is reflected as `data-density` on the root and flows to child messages through `ChatListContext`; it selects three spacing groups. | Shipped source, colocated density test, family docs | verify |
+| FR3 | The optional `gap` replaces only the top-level row gap; density still selects padding and context. | Shipped source and consumer docs | verify |
+| FR4 | `emptyState` renders only when `children` is nullish, `false`, or an empty top-level array. Otherwise the passed children render unchanged. | Shipped source, empty-array and numeric-zero tests | verify |
+| FR5 | `align="bottom"` includes a flex spacer before messages; `align="top"` omits it. Overflowing content is not given a different rendering path. | Shipped source, colocated tests, existing family story | verify |
+| FR6 | Supplying `scrollToTopAction` creates an observed top sentinel. An intersection starts its async transition, and a top-positioned spinner renders while it is pending. | Shipped source, consumer docs, focused async test | verify |
+| FR7 | Inside ChatLayout, the inner content element is passed to the layout's `contentRef` and removed from that registration on cleanup; standalone lists have no layout ref. | Shipped source and context definition | verify |
+| FR8 | The root receives `ref`, accepted DOM/data/ARIA props, and composed `className`, `style`, and `xstyle`; component-owned log semantics are applied after forwarded props. | Shipped source and shared public API authority | verify |
+
+For the `emptyState` slot, numeric `0` is visible content. Nullish values,
+booleans, and an empty string do not create an empty wrapper. This describes
+scalar output only; it does not decide how to inspect nested children.
+
+### Allowed variation
+
+- **AV1 - Content.** Any caller-owned ReactNode may be placed in the list; the
+ list does not infer sender metadata from children.
+- **AV2 - Spacing.** Density selects token-based defaults; the optional `gap`
+ selects a published spacing step without changing the child density.
+- **AV3 - Scroll ownership.** The list may be used alone or inside ChatLayout;
+ auto-follow behavior remains outside this component.
+
+### Representative states
+
+| State | Observed result | Allowed variation |
+| ----------------------------- | ----------------------------------------------------- | ------------------------------------------ |
+| Two messages and a system row | Polite log with messages in source order | Caller controls row content |
+| Empty top-level children | Optional centered empty state | An omitted empty state leaves an empty log |
+| Compact/balanced/spacious | Different token-derived row spacing and child density | `gap` may override only row spacing |
+| Short top/bottom list | Bottom includes a spacer, top omits it | Container height is caller-owned |
+| Streaming | Log has `aria-busy=true` | Message content remains caller-owned |
+| Top action pending | Spinner above content while transition is pending | Async action result is caller-owned |
+
+### Performance and resources
+
+- An `IntersectionObserver` is installed only when `scrollToTopAction` exists,
+ and disconnected on cleanup. Its root is ChatLayout's scroll container when
+ available, otherwise the document viewport.
+- An Effect registers the inner content element with ChatLayout, then clears
+ that registration on cleanup. This draft does not prescribe an internal hook
+ or listener implementation.
+
+## Accessibility contract
+
+- The shipped root is a focusable polite log with `aria-busy` reflecting
+ `isStreaming`; this describes browser-exposed semantics, not an observed
+ screen-reader announcement transcript.
+- The loading spinner is a separate child of the log. The list adds no
+ interactive button or directional keyboard behavior of its own.
+- Caller-supplied content remains responsible for names and semantics inside
+ messages. This record does not claim one browser/AT pairing proves another.
+
+## Design relationships
+
+No current component-local design decision is added by this observational
+backfill. Spacing uses portable semantic token steps. The family consumer doc
+owns the published `chat-message-list` theme target and its `density` axis.
+This record does not choose a new visual representation or a new theming target.
+
+## Family and system relationships
+
+- No `family:chat` authority record currently exists. `Chat.doc.mjs` is the
+ consumer family document, not a product-authority family contract.
+- `ChatLayout` owns the scroll container and provides `contentRef`; the list
+ registers its content element without taking over ChatLayout's scrolling.
+- `spec:AST-029` governs observational audit backfills and keeps their
+ evidence inventory separate from component policy.
+
+## Verification map
+
+| Contract | Evidence | Representative states | Mutation or failure expectation | Audit section |
+| -------- | ------------------------------------------------------------------- | ---------------------------------- | -------------------------------------------------------- | -------------------------- |
+| FR1 | `ChatMessageList.test.tsx` ARIA assertions; Chromium audit receipts | rest, streaming | Dropping busy or the log role changes the exposed state | `audit:ChatMessageList/§1` |
+| FR2–FR3 | density test, theming-target guard, rendered comparison | three densities and gap override | Losing density reflection or row spacing becomes visible | `audit:ChatMessageList/§2` |
+| FR4–FR5 | empty/align tests, component-owned Storybook and Chromium receipts | empty, top and bottom | Empty substitute or short-list placement changes | `audit:ChatMessageList/§4` |
+| FR6 | `ChatMessageList.test.tsx` async action/status test | sentinel absent, pending, settled | Action loss or stuck spinner fails the focused test | `audit:ChatMessageList/§6` |
+| FR7 | ChatLayout integration and source review | standalone, inside layout, unmount | Content observation can lose registration | `audit:ChatMessageList/§7` |
+| FR8 | `themingTargets.test.ts`, focused root passthrough inspection | ref, DOM/ARIA, styling | Consumer inputs fail to reach or compose on the root | `audit:ChatMessageList/§3` |
+
+## Decision log
+
+None. This draft settles no component-local product decision.
+
+## Open questions
+
+- **OQ1 - What is the intended overlap policy for repeated top-sentinel
+ intersections while an async load remains pending?** (`human-api`) The current
+ source invokes the action on intersection; this record does not add a
+ single-flight, initial-load, or exhaustion guarantee.
+- **OQ2 - Should emptiness inspect nested non-rendering ReactNode values?**
+ (`human-api`) The shipped test is limited to the top-level `children` value.
+ Do not reinterpret that test as a policy about generators, fragments,
+ promised children, or arrays of non-rendering values.
+
+## Content boundary
+
+This file contains no audit score, screenshot matrix, run transcript, consumer
+prop example, new public API, or cross-component visual policy.
diff --git a/packages/core/src/Chat/ChatMessageList.test.tsx b/packages/core/src/Chat/ChatMessageList.test.tsx
index 213f075fd7..39bd3b1de8 100644
--- a/packages/core/src/Chat/ChatMessageList.test.tsx
+++ b/packages/core/src/Chat/ChatMessageList.test.tsx
@@ -1,7 +1,14 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {describe, it, expect} from 'vitest';
-import {render, screen} from '@testing-library/react';
+/**
+ * @file ChatMessageList.test.tsx
+ * @input React Testing Library, Vitest, and the public ChatMessageList surface
+ * @output Observable log, empty-state, alignment, and async-loading regressions
+ * @position Colocated component behavior tests
+ */
+
+import {describe, it, expect, vi} from 'vitest';
+import {act, render, screen} from '@testing-library/react';
import {ChatMessageList} from './ChatMessageList';
import {ChatMessage} from './ChatMessage';
import {ChatMessageBubble} from './ChatMessageBubble';
@@ -55,6 +62,11 @@ describe('ChatMessageList', () => {
expect(screen.getByText('No messages yet')).toBeTruthy();
});
+ it('renders an accepted numeric empty state', () => {
+ render(<ChatMessageList emptyState={0}>{[]}</ChatMessageList>);
+ expect(screen.getByRole('log')).toHaveTextContent('0');
+ });
+
it('applies density class', () => {
render(
<ChatMessageList density="compact" data-testid="list">
@@ -129,4 +141,54 @@ describe('ChatMessageList', () => {
);
expect(screen.getByText('Hello')).toBeTruthy();
});
+
+ it('loads older messages through the top sentinel and exposes pending status', async () => {
+ let notify!: IntersectionObserverCallback;
+ let complete!: () => void;
+ const observeSentinel = vi.fn();
+ const disconnect = vi.fn();
+ const action = vi.fn(
+ async () =>
+ new Promise<void>(resolve => {
+ complete = resolve;
+ }),
+ );
+ class Observer {
+ constructor(callback: IntersectionObserverCallback) {
+ notify = callback;
+ }
+ observe = observeSentinel;
+ disconnect = disconnect;
+ }
+ vi.stubGlobal('IntersectionObserver', Observer);
+ try {
+ const {unmount} = render(
+ <ChatMessageList scrollToTopAction={action}>
+ <div>Earlier message</div>
+ </ChatMessageList>,
+ );
+ expect(observeSentinel).toHaveBeenCalledTimes(1);
+ act(() => {
+ notify(
+ [{isIntersecting: false} as IntersectionObserverEntry],
+ {} as IntersectionObserver,
+ );
+ });
+ expect(action).not.toHaveBeenCalled();
+ act(() => {
+ notify(
+ [{isIntersecting: true} as IntersectionObserverEntry],
+ {} as IntersectionObserver,
+ );
+ });
+ expect(action).toHaveBeenCalledTimes(1);
+ expect(screen.getByRole('status', {name: 'Loading'})).toBeTruthy();
+ await act(async () => complete());
+ expect(screen.queryByRole('status', {name: 'Loading'})).toBeNull();
+ unmount();
+ expect(disconnect).toHaveBeenCalledTimes(1);
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
});
diff --git a/packages/core/src/Chat/ChatMessageList.tsx b/packages/core/src/Chat/ChatMessageList.tsx
index 3f2468f4ce..0f1cc5cba2 100644
--- a/packages/core/src/Chat/ChatMessageList.tsx
+++ b/packages/core/src/Chat/ChatMessageList.tsx
@@ -4,7 +4,8 @@
/**
* @file ChatMessageList.tsx
- * @input Uses React, StyleX, ChatListContext, theme tokens, spacing step utilities
+ * @input Uses React, StyleX, ChatListContext, theme tokens, spacing step utilities,
+ * and isRenderable to preserve accepted empty-state content
* @output Exports ChatMessageList component and ChatMessageListProps
* @position Presentational message container — holds ChatMessage children
*
@@ -31,7 +32,7 @@ import {
type ChatDensity,
useChatLayoutContext,
} from './ChatContext';
-import {mergeProps} from '../utils';
+import {isRenderable, mergeProps} from '../utils';
import {Spinner} from '../Spinner';
import type {BaseProps} from '../BaseProps';
import type {SpacingStep} from '../utils/types';
@@ -321,7 +322,7 @@ export function ChatMessageList({
{/* Messages or empty state */}
{hasChildren ? (
children
- ) : emptyState ? (
+ ) : isRenderable(emptyState) ? (
<div {...stylex.props(styles.emptyState)}>{emptyState}</div>
) : null}
</div>
diff --git a/packages/core/src/Chat/__tests__/ChatMessageList.a11y.chromium.spec.ts b/packages/core/src/Chat/__tests__/ChatMessageList.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..1a9ff16940
--- /dev/null
+++ b/packages/core/src/Chat/__tests__/ChatMessageList.a11y.chromium.spec.ts
@@ -0,0 +1,456 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChatMessageList.a11y.chromium.spec.ts
+ * @input Uses the component-owned Storybook fixtures and exact-head build stamp
+ * @output Chromium screenshots and fail-closed semantic sensor receipts
+ * @position Browser evidence for the ChatMessageList 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';
+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-message-list-audit-evidence');
+const CONVERSATION = 'core-chatmessagelist--conversation';
+const EMPTY = 'core-chatmessagelist--empty';
+const DENSITIES = 'core-chatmessagelist--density-and-alignment';
+const OVERFLOW = 'core-chatmessagelist--overflow';
+const LOADING = 'core-chatmessagelist--loading-older';
+const VIEWPORT = {width: 1024, height: 768};
+
+interface Case {
+ state: string;
+ storyId: string;
+ index: number;
+ targetCount: number;
+ articleCount: number;
+ density: 'compact' | 'balanced' | 'spacious';
+ busy: boolean;
+ text?: string;
+ name?: string;
+ args?: string;
+ viewport?: {width: number; height: number};
+ direction?: 'ltr' | 'rtl';
+ coarsePointer?: boolean;
+ requiresOverflow?: boolean;
+ statusName?: string;
+}
+
+// Expectations are authored from the public fixture and component source, not
+// discovered from the page under test.
+const CASES: Case[] = [
+ {
+ state: 'conversation',
+ storyId: CONVERSATION,
+ index: 0,
+ targetCount: 1,
+ articleCount: 2,
+ density: 'balanced',
+ busy: false,
+ text: 'The issue is resolved.',
+ },
+ {
+ state: 'empty',
+ storyId: EMPTY,
+ index: 0,
+ targetCount: 2,
+ articleCount: 0,
+ density: 'balanced',
+ busy: false,
+ name: 'Text empty state',
+ text: 'No messages yet',
+ },
+ // This input-state receipt is identical on the broken and corrected builds.
+ // The separate visible-output case below must reject the old blank result.
+ {
+ state: 'numeric-empty',
+ storyId: EMPTY,
+ index: 1,
+ targetCount: 2,
+ articleCount: 0,
+ density: 'balanced',
+ busy: false,
+ name: 'Numeric empty state',
+ },
+ {
+ state: 'numeric-empty-visible',
+ storyId: EMPTY,
+ index: 1,
+ targetCount: 2,
+ articleCount: 0,
+ density: 'balanced',
+ busy: false,
+ name: 'Numeric empty state',
+ text: '0',
+ },
+ {
+ state: 'compact-top',
+ storyId: DENSITIES,
+ index: 0,
+ targetCount: 3,
+ articleCount: 1,
+ density: 'compact',
+ busy: false,
+ text: 'A short conversation.',
+ },
+ {
+ state: 'balanced-bottom',
+ storyId: DENSITIES,
+ index: 1,
+ targetCount: 3,
+ articleCount: 1,
+ density: 'balanced',
+ busy: false,
+ text: 'A short conversation.',
+ },
+ {
+ state: 'spacious-bottom',
+ storyId: DENSITIES,
+ index: 2,
+ targetCount: 3,
+ articleCount: 1,
+ density: 'spacious',
+ busy: false,
+ text: 'A short conversation.',
+ },
+ {
+ state: 'streaming',
+ storyId: CONVERSATION,
+ index: 0,
+ targetCount: 1,
+ articleCount: 2,
+ density: 'balanced',
+ busy: true,
+ text: 'The issue is resolved.',
+ args: 'isStreaming:true',
+ },
+ {
+ state: 'overflow',
+ storyId: OVERFLOW,
+ index: 0,
+ targetCount: 1,
+ articleCount: 8,
+ density: 'balanced',
+ busy: false,
+ text: 'Conversation item 1.',
+ requiresOverflow: true,
+ },
+ {
+ state: 'loading-older',
+ storyId: LOADING,
+ index: 0,
+ targetCount: 1,
+ articleCount: 1,
+ density: 'balanced',
+ busy: false,
+ text: 'Earlier message remains readable',
+ statusName: 'Loading',
+ },
+];
+
+const frames: Record<string, unknown>[] = [];
+let storybook: StaticServer;
+let checkoutSha: string;
+let storybookSha: string;
+let browserVersion = 'unknown';
+
+test.beforeAll(async () => {
+ checkoutSha = execFileSync('git', ['rev-parse', 'HEAD'], {
+ encoding: 'utf8',
+ }).trim();
+ const expectedHead = process.env.ASTRYX_HEAD_SHA;
+ if (expectedHead && expectedHead !== checkoutSha) {
+ throw new Error('The audited checkout does not match the PR head');
+ }
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+ const stamp = await fetch(`${storybook.origin}/astryx-build-sha.txt`);
+ if (!stamp.ok) {
+ throw new Error(
+ `The Storybook build has no source stamp (${stamp.status})`,
+ );
+ }
+ storybookSha = (await stamp.text()).trim();
+ if (storybookSha !== checkoutSha) {
+ throw new Error(
+ 'The served Storybook build does not match the audited checkout',
+ );
+ }
+ fs.mkdirSync(OUTPUT, {recursive: true});
+});
+
+test.afterAll(async () => {
+ if (checkoutSha && storybookSha) {
+ fs.writeFileSync(
+ path.join(OUTPUT, 'manifest.json'),
+ `${JSON.stringify(
+ {
+ version: 1,
+ component: 'core/ChatMessageList',
+ headSha: checkoutSha,
+ storybookSha,
+ browser: browserVersion,
+ frames,
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+ }
+ await storybook?.close();
+});
+
+async function capture(page: Page, scenario: Case, mode: 'light' | 'dark') {
+ const errors: string[] = [];
+ const onError = (error: Error) => errors.push(String(error));
+ page.on('pageerror', onError);
+ const viewport = scenario.viewport ?? VIEWPORT;
+ try {
+ await page.setViewportSize(viewport);
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ browserVersion = page.context().browser()?.version() ?? 'unknown';
+ const direction = scenario.direction ?? 'ltr';
+ const args = scenario.args
+ ? `&args=${encodeURIComponent(scenario.args)}`
+ : '';
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=${scenario.storyId}&viewMode=story&globals=colorMode:${mode};astryxTheme:neutral;direction:${direction}${args}`,
+ );
+ const logs = page.getByRole('log');
+ await logs.first().waitFor();
+ if (scenario.statusName) {
+ await page.getByRole('status', {name: scenario.statusName}).waitFor();
+ }
+ await holdMotionStill(page);
+ await page.evaluate(async () => document.fonts.ready);
+ await page.waitForFunction(
+ expected =>
+ document.documentElement.getAttribute('data-theme') === expected,
+ mode,
+ );
+ const subject = logs.nth(scenario.index);
+ const box = await subject.boundingBox();
+ const observed = await subject.evaluate(
+ (node, measures) => ({
+ role: node.getAttribute('role'),
+ name: node.getAttribute('aria-label'),
+ live: node.getAttribute('aria-live'),
+ busy: node.getAttribute('aria-busy'),
+ density: node.getAttribute('data-density'),
+ direction: getComputedStyle(node).direction,
+ text: (node as HTMLElement).innerText,
+ articleCount: node.querySelectorAll('article').length,
+ width: node.getBoundingClientRect().width,
+ height: node.getBoundingClientRect().height,
+ scrollWidth: node.scrollWidth,
+ clientWidth: node.clientWidth,
+ ...(measures.overflow
+ ? {
+ parentScrollHeight: node.parentElement?.scrollHeight ?? 0,
+ parentClientHeight: node.parentElement?.clientHeight ?? 0,
+ }
+ : {}),
+ ...(measures.status
+ ? {
+ statusName: node
+ .querySelector('[role="status"]')
+ ?.getAttribute('aria-label'),
+ }
+ : {}),
+ }),
+ {
+ overflow: Boolean(scenario.requiresOverflow),
+ status: Boolean(scenario.statusName),
+ },
+ );
+ const environment = await page.evaluate(() => ({
+ theme: document
+ .querySelector('[data-astryx-theme]')
+ ?.getAttribute('data-astryx-theme'),
+ mode: document.documentElement.getAttribute('data-theme'),
+ colorScheme: getComputedStyle(document.documentElement).colorScheme,
+ fonts: document.fonts.status,
+ viewport: {width: innerWidth, height: innerHeight},
+ dpr: devicePixelRatio,
+ reducedMotion: matchMedia('(prefers-reduced-motion: reduce)').matches,
+ coarsePointer: matchMedia('(pointer: coarse)').matches,
+ forcedColors: matchMedia('(forced-colors: active)').matches,
+ horizontalOverflow: document.documentElement.scrollWidth > innerWidth + 1,
+ storyError: [
+ ...document.querySelectorAll(
+ '.sb-errordisplay, [data-testid="story-error"]',
+ ),
+ ].some(element => {
+ const box = element.getBoundingClientRect();
+ const style = getComputedStyle(element);
+ return (
+ box.width > 0 &&
+ box.height > 0 &&
+ box.bottom > 0 &&
+ box.right > 0 &&
+ box.top < innerHeight &&
+ box.left < innerWidth &&
+ style.display !== 'none' &&
+ style.visibility !== 'hidden' &&
+ style.opacity !== '0'
+ );
+ }),
+ }));
+
+ // All assertions precede the screenshot, so a failed sensor cannot mint evidence.
+ expect(await logs.count(), scenario.state).toBe(scenario.targetCount);
+ expect(box, scenario.state).not.toBeNull();
+ expect(await subject.isVisible()).toBe(true);
+ expect(observed.role).toBe('log');
+ expect(observed.live).toBe('polite');
+ expect(observed.busy).toBe(scenario.busy ? 'true' : null);
+ expect(observed.density).toBe(scenario.density);
+ expect(observed.direction).toBe(direction);
+ expect(observed.articleCount).toBe(scenario.articleCount);
+ if (scenario.name != null) {
+ expect(observed.name).toBe(scenario.name);
+ }
+ if (scenario.text != null) {
+ expect(observed.text).toContain(scenario.text);
+ }
+ if (scenario.statusName != null) {
+ expect(observed.statusName).toBe(scenario.statusName);
+ }
+ expect(observed.width).toBeGreaterThan(0);
+ expect(observed.height).toBeGreaterThan(0);
+ if (scenario.requiresOverflow) {
+ expect(observed.parentScrollHeight ?? 0).toBeGreaterThan(
+ (observed.parentClientHeight ?? 0) + 1,
+ );
+ }
+ expect(environment.theme).toBe('neutral');
+ expect(environment.mode).toBe(mode);
+ expect(environment.colorScheme).toBe(mode);
+ expect(environment.fonts).toBe('loaded');
+ expect(environment.viewport).toEqual(viewport);
+ expect(environment.reducedMotion).toBe(true);
+ expect(environment.forcedColors).toBe(false);
+ expect(environment.coarsePointer).toBe(scenario.coarsePointer ?? false);
+ expect(environment.storyError).toBe(false);
+ if (viewport.width === 320) {
+ expect(environment.horizontalOverflow).toBe(false);
+ expect(observed.scrollWidth).toBeLessThanOrEqual(
+ observed.clientWidth + 1,
+ );
+ }
+ expect(errors).toEqual([]);
+
+ const file = `ChatMessageList__${scenario.state}__neutral-${mode}__${direction}.png`;
+ const png = await (
+ scenario.requiresOverflow ? subject.locator('xpath=..') : subject
+ ).screenshot({animations: 'disabled'});
+ expect(png.length).toBeGreaterThan(100);
+ const receipt = {
+ expected: {
+ build: checkoutSha,
+ storyId: scenario.storyId,
+ theme: 'neutral',
+ mode,
+ direction,
+ viewport,
+ targetCount: scenario.targetCount,
+ articleCount: scenario.articleCount,
+ density: scenario.density,
+ busy: scenario.busy,
+ name: scenario.name,
+ text: scenario.text,
+ coarsePointer: scenario.coarsePointer ?? false,
+ ...(scenario.requiresOverflow ? {requiresOverflow: true} : {}),
+ ...(scenario.statusName ? {statusName: scenario.statusName} : {}),
+ },
+ observed: {
+ build: storybookSha,
+ storyId: scenario.storyId,
+ targetCount: await logs.count(),
+ ...observed,
+ ...environment,
+ pageErrors: errors.length,
+ selectorVisible: await subject.isVisible(),
+ geometry: box,
+ },
+ image: {
+ file,
+ sha256: createHash('sha256').update(png).digest('hex'),
+ width: png.readUInt32BE(16),
+ height: png.readUInt32BE(20),
+ },
+ browser: browserVersion,
+ passed: true,
+ };
+ fs.writeFileSync(path.join(OUTPUT, file), png);
+ fs.writeFileSync(
+ path.join(OUTPUT, `${file}.sensors.json`),
+ `${JSON.stringify(receipt, null, 2)}\n`,
+ );
+ frames.push({
+ state: scenario.state,
+ mode,
+ direction,
+ receipt: `${file}.sensors.json`,
+ image: receipt.image,
+ });
+ } finally {
+ page.off('pageerror', onError);
+ }
+}
+
+test('captures transcript states in Chromium light and dark', async ({
+ page,
+}) => {
+ for (const mode of ['light', 'dark'] as const) {
+ for (const scenario of CASES) {
+ await capture(page, scenario, mode);
+ }
+ }
+});
+
+test('captures right-to-left and narrow coarse-pointer transcripts', async ({
+ browser,
+ page,
+}: {
+ browser: Browser;
+ page: Page;
+}) => {
+ for (const mode of ['light', 'dark'] as const) {
+ await capture(page, {...CASES[0], state: 'rtl', direction: 'rtl'}, mode);
+ }
+ const context = await browser.newContext({
+ viewport: {width: 320, height: 640},
+ deviceScaleFactor: 1,
+ hasTouch: true,
+ isMobile: true,
+ reducedMotion: 'reduce',
+ });
+ try {
+ const touchPage = await context.newPage();
+ for (const mode of ['light', 'dark'] as const) {
+ await capture(
+ touchPage,
+ {
+ ...CASES[0],
+ state: 'narrow-touch',
+ viewport: {width: 320, height: 640},
+ coarsePointer: true,
+ },
+ mode,
+ );
+ }
+ } finally {
+ await context.close();
+ }
+});