Skip to content

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

TypeScript

[Component Audit] ChatMessageBubble: make state evidence direct (#6600)

Cindy Zhangc8f136a23f68
diff --git a/.changeset/chat-message-bubble-slots.md b/.changeset/chat-message-bubble-slots.md
new file mode 100644
index 0000000000..fa780414df
--- /dev/null
+++ b/.changeset/chat-message-bubble-slots.md
@@ -0,0 +1,11 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Keep numeric zero aligned in ChatMessageBubble name and metadata slots.
+
+The aligned wrappers are omitted for non-rendering scalar values (`null`,
+`undefined`, booleans, and the empty string), while numeric `0` remains visible
+inside the same inset as other slot content.
+
+@cixzhang
diff --git a/.github/scripts/ci-test-routing.test.mjs b/.github/scripts/ci-test-routing.test.mjs
index 67e5cd4bef..c2c87a90b7 100644
--- a/.github/scripts/ci-test-routing.test.mjs
+++ b/.github/scripts/ci-test-routing.test.mjs
@@ -229,6 +229,41 @@ describe('ci.yml RTL package sharding', () => {
expect(commands).toContain('has_stable_visual=false');
});
+ it('binds component evidence source, Storybook bytes, and RTL code to the PR head', () => {
+ const exactRef = '${{ github.event.pull_request.head.sha || github.sha }}';
+ for (const name of ['build-storybook', 'pr-a11y', 'pr-rtl-shard']) {
+ const checkout = workflow.jobs[name].steps.find(candidate =>
+ candidate.uses?.startsWith('actions/checkout@'),
+ );
+ expect(checkout?.with?.ref, `${name} checkout is not exact-head`).toBe(
+ exactRef,
+ );
+ }
+ const storybookVerify = workflow.jobs['build-storybook'].steps.find(
+ candidate => candidate.name === 'Verify Storybook source checkout',
+ );
+ expect(storybookVerify.if).toContain(
+ "needs.check-scope.outputs.tooling_only != 'true'",
+ );
+ expect(runLines(workflow.jobs['build-storybook'])).toContain(
+ 'astryx-build-sha.txt',
+ );
+ expect(runLines(workflow.jobs['pr-a11y'])).toContain('git rev-parse HEAD');
+ expect(runLines(shard)).toContain('git rev-parse HEAD');
+
+ const evidence = read(
+ 'packages/core/src/Chat/__tests__/ChatMessageBubble.a11y.chromium.spec.ts',
+ );
+ const provenance = read(
+ 'packages/core/src/Chat/__tests__/ChatMessageBubble.auditProvenance.ts',
+ );
+ expect(evidence).toContain("execFileSync('git', ['rev-parse', 'HEAD']");
+ expect(evidence).toContain('resolveChatMessageBubbleAuditProvenance');
+ expect(provenance).toContain('/astryx-build-sha.txt');
+ expect(provenance).toContain('storybookSha !== checkoutSha');
+ expect(provenance).toContain("mode: 'local-unstamped'");
+ });
+
it('keeps PR accessibility scoped while RTL retains its canonical resolver', () => {
expect(runLines(workflow.jobs['pr-a11y'])).toContain(
'.github/scripts/a11y-pr-scope.mjs',
diff --git a/.github/scripts/release-check-workflow.test.mjs b/.github/scripts/release-check-workflow.test.mjs
index 36bbfd50c8..49d3ca195a 100644
--- a/.github/scripts/release-check-workflow.test.mjs
+++ b/.github/scripts/release-check-workflow.test.mjs
@@ -205,7 +205,11 @@ describe('explicit release routing', () => {
for (const item of jobs[name].steps) {
if (item.uses?.startsWith('actions/checkout@')) {
// Omitted ref is the event SHA, not the mutable default branch.
- expect([undefined, '${{ github.sha }}']).toContain(item.with?.ref);
+ expect([
+ undefined,
+ '${{ github.sha }}',
+ '${{ github.event.pull_request.head.sha || github.sha }}',
+ ]).toContain(item.with?.ref);
expect(item.with?.repository).toBeUndefined();
}
}
diff --git a/.github/scripts/rtl-audit-coverage.test.mjs b/.github/scripts/rtl-audit-coverage.test.mjs
index 8de8fb913c..1ff9a78fa7 100644
--- a/.github/scripts/rtl-audit-coverage.test.mjs
+++ b/.github/scripts/rtl-audit-coverage.test.mjs
@@ -15,6 +15,7 @@ import {
buildComponentCoverage,
buildStoryComponentRoutes,
classifyDirectionalDecorationPair,
+ classifyLogicalGroupedCorners,
classifyLogicalInlinePair,
collectDirectionalDecorations,
filterStoryRoutesByPackages,
@@ -248,6 +249,98 @@ describe('classifyLogicalInlinePair', () => {
});
});
+function groupedCornerMeasurement(direction = 'ltr', physicalSide = 'left') {
+ const full = 28;
+ const inset = 6;
+ const left = physicalSide === 'left';
+ const corners = (topInset, bottomInset) => ({
+ topLeft: left && topInset ? inset : full,
+ topRight: !left && topInset ? inset : full,
+ bottomRight: !left && bottomInset ? inset : full,
+ bottomLeft: left && bottomInset ? inset : full,
+ });
+ return {
+ direction,
+ writingMode: 'horizontal-tb',
+ boxes: [
+ {
+ visible: true,
+ width: 180,
+ height: 44,
+ corners: corners(false, true),
+ },
+ {
+ visible: true,
+ width: 180,
+ height: 44,
+ corners: corners(true, true),
+ },
+ {
+ visible: true,
+ width: 180,
+ height: 44,
+ corners: corners(true, false),
+ },
+ ],
+ };
+}
+
+describe('classifyLogicalGroupedCorners', () => {
+ it('passes an inline-start group that mirrors left to right', () => {
+ expect(
+ classifyLogicalGroupedCorners(
+ groupedCornerMeasurement('ltr', 'left'),
+ groupedCornerMeasurement('rtl', 'right'),
+ 'inline-start',
+ ),
+ ).toMatchObject({
+ verdict: 'pass',
+ ltr: {physicalSide: 'left', insetRadius: 6, fullRadius: 28},
+ rtl: {physicalSide: 'right', insetRadius: 6, fullRadius: 28},
+ });
+ });
+
+ it('passes an inline-end group that mirrors right to left', () => {
+ expect(
+ classifyLogicalGroupedCorners(
+ groupedCornerMeasurement('ltr', 'right'),
+ groupedCornerMeasurement('rtl', 'left'),
+ 'inline-end',
+ ),
+ ).toMatchObject({
+ verdict: 'pass',
+ ltr: {physicalSide: 'right'},
+ rtl: {physicalSide: 'left'},
+ });
+ });
+
+ it('fails grouped corners that stay on the LTR physical side', () => {
+ expect(
+ classifyLogicalGroupedCorners(
+ groupedCornerMeasurement('ltr', 'left'),
+ groupedCornerMeasurement('rtl', 'left'),
+ 'inline-start',
+ ),
+ ).toMatchObject({verdict: 'fail'});
+ });
+
+ it('fails when any grouped subject is missing or hidden', () => {
+ const rtl = groupedCornerMeasurement('rtl', 'right');
+ rtl.boxes[1] = null;
+ expect(
+ classifyLogicalGroupedCorners(
+ groupedCornerMeasurement('ltr', 'left'),
+ rtl,
+ 'inline-start',
+ ),
+ ).toMatchObject({
+ verdict: 'fail',
+ reason:
+ 'grouped-corner subjects must be three visible horizontal LTR/RTL boxes',
+ });
+ });
+});
+
describe('buildComponentCoverage', () => {
it('classifies measured, verified N/A, unexplained gaps, and stale declarations', () => {
const coverage = buildComponentCoverage({
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 0bf1f40af7..de4afd4ccd 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -580,11 +580,21 @@ jobs:
if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true' && needs.check-scope.outputs.tooling_only != 'true'
uses: actions/checkout@v7
with:
+ # Component evidence artifacts are named for and reviewed at the PR
+ # head, so build their Storybook bytes from that exact tree rather
+ # than GitHub's synthetic merge checkout.
+ ref: ${{ github.event.pull_request.head.sha || github.sha }}
# Depth 50 (same as check-scope) so analyze-pr.js's three-dot diff
# can find a merge base — depth 1 breaks it ("no merge base") and
# the analysis silently reported zero changed components.
fetch-depth: 50
+ - name: Verify Storybook source checkout
+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true' && needs.check-scope.outputs.tooling_only != 'true' && github.event_name == 'pull_request'
+ env:
+ EXPECTED_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
+ run: test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD_SHA"
+
- name: Fetch base branch for PR analysis
if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true' && needs.check-scope.outputs.tooling_only != 'true' && github.event_name == 'pull_request'
run: git fetch origin ${{ github.base_ref }} --depth=50
@@ -651,6 +661,10 @@ jobs:
if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true' && needs.check-scope.outputs.tooling_only != 'true'
run: pnpm -F @astryxdesign/storybook build
+ - name: Stamp Storybook source revision
+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true' && needs.check-scope.outputs.tooling_only != 'true'
+ run: git rev-parse HEAD > apps/storybook/dist/astryx-build-sha.txt
+
- name: Compute PR preview path
if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true' && needs.check-scope.outputs.tooling_only != 'true' && github.event_name == 'pull_request'
id: urls
@@ -857,6 +871,14 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v7
+ with:
+ ref: ${{ github.event.pull_request.head.sha || github.sha }}
+
+ - name: Verify evidence checkout
+ if: github.event_name == 'pull_request'
+ env:
+ EXPECTED_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
+ run: test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD_SHA"
# Dependencies are installed later, together with the Playwright browser,
# because the analysis artifact has to be downloaded first.
@@ -937,6 +959,34 @@ jobs:
- name: Run story play guard
run: node .github/scripts/story-play-guard.js --storybook-dir apps/storybook/dist
+ # ChatMessageBubble is nested under the shared Chat source directory, so
+ # the generic stable-visual owner cannot select its dedicated fixture.
+ # Run the component's bounded evidence matrix only when the PR scope names
+ # it, and upload the receipted frames below.
+ - name: Run ChatMessageBubble audit browser evidence
+ if: github.event_name == 'pull_request'
+ env:
+ ASTRYX_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
+ run: |
+ COMPONENTS=$(node .github/scripts/a11y-pr-scope.mjs analysis.json)
+ case ",${COMPONENTS}," in
+ *,core/ChatMessageBubble,*)
+ pnpm exec playwright test \
+ packages/core/src/Chat/__tests__/ChatMessageBubble.a11y.chromium.spec.ts \
+ --project chromium
+ ;;
+ *) echo "ChatMessageBubble not in PR scope; skipping audit evidence." ;;
+ esac
+
+ - name: Upload ChatMessageBubble audit evidence
+ if: always() && github.event_name == 'pull_request'
+ uses: actions/upload-artifact@v7
+ with:
+ name: chat-message-bubble-audit-evidence-${{ needs.build-storybook.outputs.short_hash }}
+ path: test-results/chat-message-bubble-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.
@@ -1385,8 +1435,8 @@ jobs:
# The scheduled full sweep also runs in rtl-weekly.yml.
#
# Three auto dimensions: D1 icon-mirror, D5 positional-mirror, and D6
- # contextual directional decorations. Curated D2/D3/D4 adds behavior that
- # needs selectors. The applicability rollup treats unexplained all-N/A as a
+ # contextual directional decorations. Curated D2/D3/D4/D7/D8/D9 add
+ # behavior and geometry that need selectors. The applicability rollup treats unexplained all-N/A as a
# coverage gap for both new and existing components.
#
# Audit findings remain SOFT while the stability window is observed: the audit
@@ -1414,6 +1464,14 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v7
+ with:
+ ref: ${{ github.event.pull_request.head.sha || github.sha }}
+
+ - name: Verify RTL checkout
+ if: github.event_name == 'pull_request'
+ env:
+ EXPECTED_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
+ run: test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD_SHA"
- name: Setup Node and pnpm
uses: ./.github/actions/setup
diff --git a/apps/storybook/rtl-audit/README.md b/apps/storybook/rtl-audit/README.md
index f17efe36cf..9f3c68c535 100644
--- a/apps/storybook/rtl-audit/README.md
+++ b/apps/storybook/rtl-audit/README.md
@@ -202,7 +202,7 @@ D6 returns **N-A** when a story contains no contextual decoration. The
applicability layer below decides whether that N-A is explained; D6 itself does
not turn absence into a pass.
-### B. Curated precision — D2 / D3 / D4 / D7 / D8
+### B. Curated precision — D2 / D3 / D4 / D7 / D8 / D9
`targets.json` holds the geometry/behavior dimensions that genuinely need
hand-written selectors, run **in addition** to auto-discovery:
@@ -223,8 +223,13 @@ hand-written selectors, run **in addition** to auto-discovery:
fixtures fail closed because they cannot prove the relationship. Real
Chromium startup self-checks prove horizontal and vertical-writing passes plus
a hidden-subject failure before any component result is accepted.
+- **D9 logical grouped corners** — configured first/middle/last subjects must
+ tighten the end/both/start corners on one declared logical inline side, keep
+ every opposite-side corner full, and mirror the physical side between LTR and
+ RTL. Missing, hidden, symmetric, inconsistent, or physically pinned groups
+ fail rather than earning coverage for parent alignment.
-D1 and D6 are intentionally **not** in `targets.json`; auto-discovery covers
+D1, D5, and D6 are intentionally **not** in `targets.json`; auto-discovery covers
them universally.
### C. Applicability: no unexplained all-N/A components
@@ -322,7 +327,7 @@ Edit `targets.json`. Each entry is:
{
"component": "MyComponent", // explicit alias for grouped story titles
"storyId": "core-mycomponent--some-story", // must exist in dist/index.json
- "dims": ["D2", "D3"], // D2/D3/D4 only (D1 is auto)
+ "dims": ["D2", "D3", "D9"], // D2/D3/D4/D7/D8/D9 only (D1/D5/D6 are auto)
"setup": {
"args": {"position": "start"}, // optional: drive Storybook args
"click": "img", // optional: reveal the target after args settle
@@ -334,6 +339,16 @@ Edit `targets.json`. Each entry is:
"nextButton": "button[aria-label=\"Scroll right\"]",
"overlay": "…",
"overlayRoot": "…", // D4
+ "groups": [
+ // D9
+ {
+ "name": "primary",
+ "logicalSide": "inline-start",
+ "first": "[data-testid=group-first]",
+ "middle": "[data-testid=group-middle]",
+ "last": "[data-testid=group-last]",
+ },
+ ],
},
}
```
diff --git a/apps/storybook/rtl-audit/rtl-audit-coverage.mjs b/apps/storybook/rtl-audit/rtl-audit-coverage.mjs
index 74495889a7..29ae0a350f 100644
--- a/apps/storybook/rtl-audit/rtl-audit-coverage.mjs
+++ b/apps/storybook/rtl-audit/rtl-audit-coverage.mjs
@@ -579,6 +579,128 @@ export function classifyLogicalInlinePair(ltr, rtl, tolerancePx = 0.5) {
};
}
+/**
+ * Classify a first/middle/last group whose tightened corners belong to one
+ * logical inline side. The contracted corner sequence must be end/both/start,
+ * its opposite corners must stay full, and the physical side must mirror.
+ */
+export function classifyLogicalGroupedCorners(
+ ltr,
+ rtl,
+ logicalSide,
+ tolerancePx = 0.5,
+) {
+ const close = (left, right) => Math.abs(left - right) <= tolerancePx;
+ if (!['inline-start', 'inline-end'].includes(logicalSide)) {
+ return {verdict: 'fail', reason: 'grouped corners need a logical side'};
+ }
+
+ const measurements = [ltr, rtl];
+ if (
+ !measurements.every(
+ measurement =>
+ measurement?.boxes?.length === 3 &&
+ measurement.writingMode === 'horizontal-tb' &&
+ measurement.boxes.every(
+ box =>
+ box?.visible === true &&
+ Number.isFinite(box.width) &&
+ Number.isFinite(box.height) &&
+ box.width > 0 &&
+ box.height > 0 &&
+ ['topLeft', 'topRight', 'bottomRight', 'bottomLeft'].every(
+ corner => Number.isFinite(box.corners?.[corner]),
+ ),
+ ),
+ ) ||
+ ltr.direction !== 'ltr' ||
+ rtl.direction !== 'rtl'
+ ) {
+ return {
+ verdict: 'fail',
+ reason:
+ 'grouped-corner subjects must be three visible horizontal LTR/RTL boxes',
+ };
+ }
+
+ const evaluateDirection = measurement => {
+ const physicalSide =
+ (logicalSide === 'inline-start') === (measurement.direction === 'ltr')
+ ? 'left'
+ : 'right';
+ const oppositeSide = physicalSide === 'left' ? 'right' : 'left';
+ const sideTop = physicalSide === 'left' ? 'topLeft' : 'topRight';
+ const sideBottom =
+ physicalSide === 'left' ? 'bottomLeft' : 'bottomRight';
+ const oppositeTop = oppositeSide === 'left' ? 'topLeft' : 'topRight';
+ const oppositeBottom =
+ oppositeSide === 'left' ? 'bottomLeft' : 'bottomRight';
+ const [first, middle, last] = measurement.boxes;
+ const inset = [
+ first.corners[sideBottom],
+ middle.corners[sideTop],
+ middle.corners[sideBottom],
+ last.corners[sideTop],
+ ];
+ const full = [
+ first.corners[sideTop],
+ last.corners[sideBottom],
+ ...measurement.boxes.flatMap(box => [
+ box.corners[oppositeTop],
+ box.corners[oppositeBottom],
+ ]),
+ ];
+ const insetConsistent = inset.every(value => close(value, inset[0]));
+ const fullConsistent = full.every(value => close(value, full[0]));
+ const distinct = full[0] > inset[0] + tolerancePx;
+ return {
+ pass: insetConsistent && fullConsistent && distinct,
+ physicalSide,
+ insetRadius: inset[0],
+ fullRadius: full[0],
+ };
+ };
+
+ const ltrResult = evaluateDirection(ltr);
+ const rtlResult = evaluateDirection(rtl);
+ const mirrored = ltr.boxes.every((box, index) => {
+ const other = rtl.boxes[index];
+ return (
+ close(box.corners.topLeft, other.corners.topRight) &&
+ close(box.corners.topRight, other.corners.topLeft) &&
+ close(box.corners.bottomRight, other.corners.bottomLeft) &&
+ close(box.corners.bottomLeft, other.corners.bottomRight)
+ );
+ });
+
+ if (!ltrResult.pass || !rtlResult.pass) {
+ return {
+ verdict: 'fail',
+ reason:
+ 'first/middle/last corners do not preserve the contracted/full sequence',
+ ltr: ltrResult,
+ rtl: rtlResult,
+ };
+ }
+ if (!mirrored || ltrResult.physicalSide === rtlResult.physicalSide) {
+ return {
+ verdict: 'fail',
+ reason: 'grouped corners stay on a physical side instead of mirroring',
+ ltr: ltrResult,
+ rtl: rtlResult,
+ };
+ }
+ return {
+ verdict: 'pass',
+ reason:
+ `${logicalSide} grouped corners mirror ${ltrResult.physicalSide}→` +
+ `${rtlResult.physicalSide} with ${ltrResult.insetRadius}px inset and ` +
+ `${ltrResult.fullRadius}px full radii`,
+ ltr: ltrResult,
+ rtl: rtlResult,
+ };
+}
+
function resultIsApplicable(result) {
return result?.verdict === 'pass' || result?.verdict === 'fail';
}
diff --git a/apps/storybook/rtl-audit/rtl-audit.mjs b/apps/storybook/rtl-audit/rtl-audit.mjs
index 997b58ba32..f3dcab26fb 100644
--- a/apps/storybook/rtl-audit/rtl-audit.mjs
+++ b/apps/storybook/rtl-audit/rtl-audit.mjs
@@ -20,14 +20,14 @@
* in repeated-item or between-sibling contexts mirror exactly once.
* (B) CURATED PRECISION — targets.json entries add D2 (order-flip),
* D3 (behavior-flip), D4 (overlay-side), D7 (coarse hit alignment),
- * and D8 (logical inline-edge mirroring): the geometry/behavior dims that
- * genuinely need hand-written selectors.
+ * D8 (logical inline-edge mirroring), and D9 (logical grouped corners):
+ * the geometry/behavior dims that genuinely need hand-written selectors.
* (C) APPLICABILITY: every component is measured, explicitly verified N/A,
* or reported as a coverage gap. An all-N/A result is never called clean.
* @input --storybook-dir <path> --output <file> [--targets <path>]
* [--verified-not-applicable <path>] [--filter <csv>] [--packages <csv>]
* [--auto-only] [--curated-only]
- * @output JSON scorecard: D1/D5/D6 auto verdicts, curated D2/D3/D4/D7/D8
+ * @output JSON scorecard: D1/D5/D6 auto verdicts, curated D2/D3/D4/D7/D8/D9
* results, exact planned/completed scan counts, and a component coverage
* rollup. Mirrors the pr-a11y accessibility-audit harness.
* @position internal test harness; run by the soft-gated `pr-rtl` CI job and
@@ -54,6 +54,7 @@ import {
buildAuditedComponentRoster,
buildComponentCoverage,
buildStoryComponentRoutes,
+ classifyLogicalGroupedCorners,
classifyLogicalInlinePair,
collectDirectionalDecorations,
componentFromTarget,
@@ -707,7 +708,7 @@ async function autoD1(page, port, storyId, component) {
}
// ===========================================================================
-// CURATED precision dims (D2/D3/D4) — hand selectors from targets.json
+// CURATED precision dims (D2/D3/D4/D7/D8/D9) — hand selectors from targets.json
// ===========================================================================
async function checkD2(page, port, t, card) {
const {prev, next} = t.selectors;
@@ -897,6 +898,61 @@ async function checkD8LogicalInline(page, port, t, card) {
);
}
+async function measureGroupedCorners(page, group) {
+ return page.evaluate(({first, middle, last}) => {
+ const selectors = [first, middle, last];
+ const boxes = selectors.map(selector => {
+ const elements = document.querySelectorAll(selector);
+ if (elements.length !== 1) return null;
+ const element = elements[0];
+ const style = getComputedStyle(element);
+ const rect = element.getBoundingClientRect();
+ const number = value => Number.parseFloat(value);
+ const visible = typeof element.checkVisibility === 'function'
+ ? element.checkVisibility({checkOpacity: true, checkVisibilityCSS: true})
+ : style.display !== 'none' && style.visibility !== 'hidden' && Number(style.opacity) !== 0;
+ return {
+ visible, width: rect.width, height: rect.height,
+ direction: style.direction, writingMode: style.writingMode,
+ corners: {
+ topLeft: number(style.borderTopLeftRadius),
+ topRight: number(style.borderTopRightRadius),
+ bottomRight: number(style.borderBottomRightRadius),
+ bottomLeft: number(style.borderBottomLeftRadius),
+ },
+ };
+ });
+ return {
+ direction: boxes.find(Boolean)?.direction ?? null,
+ writingMode: boxes.find(Boolean)?.writingMode ?? null,
+ boxes,
+ };
+ }, group).catch(() => null);
+}
+
+async function checkD9GroupedCorners(page, port, t, card) {
+ const groups = t.selectors?.groups;
+ if (!Array.isArray(groups) || groups.length === 0) {
+ card.dims.D9 = 'N-A';
+ card.notes.push('D9: no grouped-corner selectors configured');
+ return;
+ }
+ const run = async rtl => {
+ await page.goto(storyUrl(port, t.storyId, rtl), {waitUntil: 'domcontentloaded'});
+ await settle(page); await doSetup(page, t);
+ return Promise.all(groups.map(group => measureGroupedCorners(page, group)));
+ };
+ const ltr = await run(false), rtl = await run(true);
+ const results = groups.map((group, index) => ({
+ name: group.name,
+ logicalSide: group.logicalSide,
+ ...classifyLogicalGroupedCorners(ltr[index], rtl[index], group.logicalSide),
+ }));
+ card.dims.D9 = results.every(result => result.verdict === 'pass') ? 'pass' : 'fail';
+ card.notes.push(...results.map(result => `D9 ${result.name ?? result.logicalSide}: ${result.reason}`));
+ card.groupedCorners = results;
+}
+
async function scoreCurated(page, coarsePage, port, t) {
const card = {component: t.component, storyId: t.storyId, dims: {}, notes: []};
for (const dim of t.dims) {
@@ -906,6 +962,7 @@ async function scoreCurated(page, coarsePage, port, t) {
else if (dim === 'D4') await checkD4(page, port, t, card);
else if (dim === 'D7') await checkD7CoarseHit(coarsePage, port, t, card);
else if (dim === 'D8') await checkD8LogicalInline(page, port, t, card);
+ else if (dim === 'D9') await checkD9GroupedCorners(page, port, t, card);
// D1 is handled by auto-discovery; ignore any stray D1 in curated entries.
} catch (e) {
card.dims[dim] = 'ERROR';
diff --git a/apps/storybook/rtl-audit/targets.json b/apps/storybook/rtl-audit/targets.json
index bfcec9a279..d776c1ba5d 100644
--- a/apps/storybook/rtl-audit/targets.json
+++ b/apps/storybook/rtl-audit/targets.json
@@ -11,9 +11,7 @@
{
"component": "Button",
"storyId": "core-button--icon-with-text",
- "dims": [
- "D2"
- ],
+ "dims": ["D2"],
"selectors": {
"prev": "[data-testid=\"button-leading-icon\"]",
"next": "[data-testid=\"button-label\"]"
@@ -134,14 +132,35 @@
{
"component": "ScrollableArea",
"storyId": "core-scrollablearea--rtl-behavior-probe",
- "dims": [
- "D3"
- ],
+ "dims": ["D3"],
"selectors": {
"scroller": "[data-rtl-scroll-probe]",
"nextButton": "[data-rtl-scroll-button]"
}
},
+ {
+ "component": "ChatMessageBubble",
+ "storyId": "core-chatmessagebubble--states",
+ "dims": ["D9"],
+ "selectors": {
+ "groups": [
+ {
+ "name": "assistant",
+ "logicalSide": "inline-start",
+ "first": "[data-testid=\"assistant-group-first\"]",
+ "middle": "[data-testid=\"assistant-group-middle\"]",
+ "last": "[data-testid=\"assistant-group-last\"]"
+ },
+ {
+ "name": "user",
+ "logicalSide": "inline-end",
+ "first": "[data-testid=\"user-group-first\"]",
+ "middle": "[data-testid=\"user-group-middle\"]",
+ "last": "[data-testid=\"user-group-last\"]"
+ }
+ ]
+ }
+ },
{
"component": "Chat",
"storyId": "core-chat--mixed-content",
diff --git a/apps/storybook/stories/ChatMessageBubble.stories.tsx b/apps/storybook/stories/ChatMessageBubble.stories.tsx
new file mode 100644
index 0000000000..a8292e6a90
--- /dev/null
+++ b/apps/storybook/stories/ChatMessageBubble.stories.tsx
@@ -0,0 +1,171 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import type {CSSProperties, ReactNode} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import {
+ ChatMessage,
+ ChatMessageBubble,
+ ChatMessageMetadata,
+} from '@astryxdesign/core/Chat';
+
+const meta: Meta<typeof ChatMessageBubble> = {
+ title: 'Core/ChatMessageBubble',
+ component: ChatMessageBubble,
+ tags: ['autodocs'],
+};
+
+export default meta;
+type Story = StoryObj<typeof ChatMessageBubble>;
+
+const fixtureStyle: CSSProperties = {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 20,
+ maxWidth: 720,
+};
+
+const panelStyle: CSSProperties = {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 8,
+ padding: 12,
+ border: '1px solid var(--color-border-primary)',
+ borderRadius: 8,
+};
+
+const labelStyle: CSSProperties = {
+ color: 'var(--color-text-secondary)',
+ fontSize: 12,
+ fontWeight: 600,
+};
+
+function Panel({state, children}: {state: string; children: ReactNode}) {
+ return (
+ <section data-bubble-audit-state={state} style={panelStyle}>
+ <div style={labelStyle}>{state}</div>
+ {children}
+ </section>
+ );
+}
+
+export const States: Story = {
+ render: () => (
+ <div data-chat-message-bubble-audit style={fixtureStyle}>
+ <Panel state="sender-alignment">
+ <ChatMessage sender="assistant">
+ <ChatMessageBubble name="Navi">Assistant message</ChatMessageBubble>
+ </ChatMessage>
+ <ChatMessage sender="user">
+ <ChatMessageBubble name="You">User message</ChatMessageBubble>
+ </ChatMessage>
+ </Panel>
+
+ <Panel state="filled-and-ghost">
+ <ChatMessage sender="assistant">
+ <ChatMessageBubble>Filled assistant bubble</ChatMessageBubble>
+ <ChatMessageBubble variant="ghost" width="100%">
+ Ghost assistant content spans the message column
+ </ChatMessageBubble>
+ </ChatMessage>
+ <ChatMessage sender="user">
+ <ChatMessageBubble>Filled user bubble</ChatMessageBubble>
+ <ChatMessageBubble variant="ghost">
+ Ghost user content
+ </ChatMessageBubble>
+ </ChatMessage>
+ </Panel>
+
+ <Panel state="assistant-group">
+ <ChatMessage sender="assistant">
+ <ChatMessageBubble
+ data-testid="assistant-group-first"
+ group="first"
+ name="Navi">
+ First assistant bubble
+ </ChatMessageBubble>
+ <ChatMessageBubble
+ data-testid="assistant-group-middle"
+ group="middle">
+ Middle assistant bubble
+ </ChatMessageBubble>
+ <ChatMessageBubble
+ data-testid="assistant-group-last"
+ group="last"
+ metadata={<ChatMessageMetadata timestamp="10:32 AM" />}>
+ Last assistant bubble
+ </ChatMessageBubble>
+ </ChatMessage>
+ </Panel>
+
+ <Panel state="user-group">
+ <ChatMessage sender="user">
+ <ChatMessageBubble
+ data-testid="user-group-first"
+ group="first"
+ name="You">
+ First user bubble
+ </ChatMessageBubble>
+ <ChatMessageBubble data-testid="user-group-middle" group="middle">
+ Middle user bubble
+ </ChatMessageBubble>
+ <ChatMessageBubble
+ data-testid="user-group-last"
+ group="last"
+ metadata={
+ <ChatMessageMetadata timestamp="10:33 AM" status="read" />
+ }>
+ Last user bubble
+ </ChatMessageBubble>
+ </ChatMessage>
+ </Panel>
+
+ <Panel state="density">
+ {(['compact', 'balanced', 'spacious'] as const).map(density => (
+ <ChatMessage key={density} sender="assistant" density={density}>
+ <ChatMessageBubble>{density} density</ChatMessageBubble>
+ </ChatMessage>
+ ))}
+ </Panel>
+
+ <Panel state="numeric-slots">
+ <ChatMessage sender="assistant">
+ <ChatMessageBubble
+ data-testid="numeric-slot-bubble"
+ name={0}
+ metadata={0}>
+ Zero is valid React content
+ </ChatMessageBubble>
+ </ChatMessage>
+ </Panel>
+
+ <Panel state="empty-content">
+ <ChatMessage sender="assistant">
+ <ChatMessageBubble>{null}</ChatMessageBubble>
+ </ChatMessage>
+ </Panel>
+ </div>
+ ),
+};
+
+export const NarrowLongContent: Story = {
+ render: () => (
+ <div
+ data-chat-message-bubble-narrow
+ style={{...fixtureStyle, width: 320, maxWidth: '100%'}}>
+ <Panel state="narrow-long-content">
+ <ChatMessage sender="assistant">
+ <ChatMessageBubble name="Navi">
+ A long message wraps without forcing horizontal scrolling, including
+ the unbroken value
+ abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789.
+ </ChatMessageBubble>
+ </ChatMessage>
+ <ChatMessage sender="user">
+ <ChatMessageBubble width="100%">
+ A full-width bubble remains inside its narrow parent.
+ </ChatMessageBubble>
+ </ChatMessage>
+ </Panel>
+ </div>
+ ),
+};
diff --git a/packages/core/src/Chat/ChatMessageBubble.doc.mjs b/packages/core/src/Chat/ChatMessageBubble.doc.mjs
index 5a368faece..523f8af309 100644
--- a/packages/core/src/Chat/ChatMessageBubble.doc.mjs
+++ b/packages/core/src/Chat/ChatMessageBubble.doc.mjs
@@ -7,7 +7,8 @@ export const docs = {
subComponentOf: 'Chat',
displayName: 'Chat Message Bubble',
isHiddenFromOverview: true,
- description: 'Styled content container for the chat "bubble." Reads sender from parent ChatMessage context to auto-style the background. Use filled for standard messages and ghost when content needs alignment without a visible boundary. Supports name/metadata slots aligned with bubble padding, and multi-bubble grouping via the group prop for consecutive messages from the same sender.',
+ description:
+ 'Styled content container for the chat "bubble." Reads sender from parent ChatMessage context to auto-style the background. Use filled for standard messages and ghost when content needs alignment without a visible boundary. Supports name/metadata slots aligned with bubble padding, and multi-bubble grouping via the group prop for consecutive messages from the same sender.',
props: [
{
name: 'children',
@@ -18,18 +19,21 @@ export const docs = {
{
name: 'variant',
type: "'filled' | 'ghost'",
- description: "Visual variant. 'filled' renders sender-colored background (default). 'ghost' renders transparent background but keeps padding for alignment.",
+ description:
+ "Visual variant. 'filled' renders sender-colored background (default). 'ghost' renders transparent background but keeps padding for alignment.",
default: "'filled'",
},
{
name: 'name',
type: 'ReactNode',
- description: "Sender name rendered above the bubble, aligned with bubble text padding. Use on the first bubble in a message. If the first content is raw (no bubble), use ChatMessage's `name` prop instead.",
+ description:
+ "Sender name rendered above the bubble, aligned with bubble text padding. Use on the first bubble in a message. Non-rendering scalar values (null, undefined, booleans, and the empty string) omit the aligned wrapper; numeric 0 remains aligned. If the first content is raw (no bubble), use ChatMessage's `name` prop instead.",
},
{
name: 'metadata',
type: 'ReactNode',
- description: "Metadata content rendered below the bubble, aligned with bubble text padding. Use on the last bubble in a message. If the last content is raw (no bubble), use ChatMessage's `metadata` prop instead.",
+ description:
+ "Metadata content rendered below the bubble, aligned with bubble text padding. Use on the last bubble in a message. Non-rendering scalar values (null, undefined, booleans, and the empty string) omit the aligned wrapper; numeric 0 remains aligned. If the last content is raw (no bubble), use ChatMessage's `metadata` prop instead.",
slotElements: [
{
__element: 'Text',
@@ -43,12 +47,14 @@ export const docs = {
{
name: 'group',
type: "'first' | 'middle' | 'last'",
- description: 'Position within a multi-bubble group. Controls corner radius reduction on the sender side. Leave unset for standalone bubbles (full radius).',
+ description:
+ 'Position within a multi-bubble group. Controls corner radius reduction on the sender side. Leave unset for standalone bubbles (full radius).',
},
{
name: 'width',
type: 'SizeValue',
- description: 'Width of the bubble (number = pixels, string = used as-is). When set, replaces the default max(80%, 280px) width cap. Combine with variant="ghost" to let custom content (an artifact card, attachments) span the full message column.',
+ description:
+ 'Width of the bubble (number = pixels, string = used as-is). When set, replaces the default max(80%, 280px) width cap. Combine with variant="ghost" to let custom content (an artifact card, attachments) span the full message column.',
},
],
};
@@ -57,14 +63,18 @@ export const docsZh = {
name: 'ChatMessageBubble',
isHiddenFromOverview: true,
displayName: 'Chat Message Bubble',
- description: '样式化的气泡容器,从父上下文读取发送者信息进行自动样式化。支持 name/metadata 插槽、多气泡分组和透明变体。',
+ description:
+ '样式化的气泡容器,从父上下文读取发送者信息进行自动样式化。支持 name/metadata 插槽、多气泡分组和透明变体。',
propDescriptions: {
children: '气泡内容:文本、Markdown 或任何 ReactNode。',
- variant: "视觉变体。'filled' 渲染发送者颜色背景,'ghost' 渲染透明背景但保持填充对齐。",
- name: '气泡上方渲染的发送者名称,与气泡文本内边距对齐。用于消息中的第一个气泡。',
- metadata: '气泡下方渲染的元数据内容,与气泡文本内边距对齐。用于消息中的最后一个气泡。',
+ variant:
+ "视觉变体。'filled' 渲染发送者颜色背景,'ghost' 渲染透明背景但保持填充对齐。",
+ name: '气泡上方渲染的发送者名称,与气泡文本内边距对齐。null、undefined、布尔值和空字符串会省略对齐容器;数字 0 仍保持对齐。用于消息中的第一个气泡。',
+ metadata:
+ '气泡下方渲染的元数据内容,与气泡文本内边距对齐。null、undefined、布尔值和空字符串会省略对齐容器;数字 0 仍保持对齐。用于消息中的最后一个气泡。',
group: '多气泡组中的位置。控制发送者侧的圆角缩减。',
- width: '气泡宽度(数字 = 像素,字符串 = 按原样使用)。设置后替代默认的 max(80%, 280px) 宽度上限;与 ghost 变体组合可让自定义内容占满消息列宽度。',
+ width:
+ '气泡宽度(数字 = 像素,字符串 = 按原样使用)。设置后替代默认的 max(80%, 280px) 宽度上限;与 ghost 变体组合可让自定义内容占满消息列宽度。',
},
};
@@ -72,14 +82,17 @@ export const docsDense = {
name: 'ChatMessageBubble',
isHiddenFromOverview: true,
displayName: 'Chat Message Bubble',
- description: 'styled bubble container; reads sender from context; supports name/metadata slots, group corners, ghost variant',
+ description:
+ 'styled bubble container; reads sender from context; supports name/metadata slots, group corners, ghost variant',
propDescriptions: {
children: 'bubble content: text, Markdown, any ReactNode',
variant: 'filled (sender bg) or ghost (transparent, keeps padding)',
- name: 'sender name above bubble, aligned w/ bubble padding',
+ name: 'sender name above bubble; omits non-rendering scalars; keeps numeric 0 aligned',
displayName: 'sender name above bubble, aligned w/ bubble padding',
- metadata: 'metadata below bubble, aligned w/ bubble padding',
+ metadata:
+ 'metadata below bubble; omits non-rendering scalars; keeps numeric 0 aligned',
group: 'position in multi-bubble group; controls corner radius reduction',
- width: 'bubble width (number=px, string=as-is); replaces default max(80%,280px) cap; ghost+width="100%" spans full message column',
+ width:
+ 'bubble width (number=px, string=as-is); replaces default max(80%,280px) cap; ghost+width="100%" spans full message column',
},
};
diff --git a/packages/core/src/Chat/ChatMessageBubble.spec.md b/packages/core/src/Chat/ChatMessageBubble.spec.md
new file mode 100644
index 0000000000..f0049f4bea
--- /dev/null
+++ b/packages/core/src/Chat/ChatMessageBubble.spec.md
@@ -0,0 +1,263 @@
+---
+schema_version: 3
+template_version: 6
+kind: component
+id: component:ChatMessageBubble
+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/ChatMessageBubble.test.tsx,
+ packages/core/src/Chat/__tests__/ChatMessageBubble.a11y.chromium.spec.ts,
+ apps/storybook/stories/ChatMessageBubble.stories.tsx,
+ apps/storybook/rtl-audit/targets.json,
+ packages/core/src/theme/themingTargets.test.ts,
+ ]
+modules: []
+families: []
+design_specs: []
+architecture:
+ [
+ architecture:public-component-api,
+ architecture:component-style-authoring,
+ architecture:component-theming-surface,
+ architecture:theme-tokens,
+ architecture:component-test-sufficiency,
+ architecture:knowledge-contracts,
+ ]
+contributing: []
+system_specs: [spec:AST-029]
+---
+
+# ChatMessageBubble component contract
+
+## Contract at a glance
+
+| Area | Contract |
+| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | Required `children`; optional `variant`, `name`, `metadata`, `group`, and `width`; root `div` passthrough, styles, and ref. This audit changes no public API shape or default. |
+| Behavior | The bubble derives sender and density from Chat message context, paints filled or ghost content, groups logical sender-side corners, and keeps renderable scalar name/metadata content inside aligned wrappers. |
+| End-user impact | Numeric zero stays aligned above or below the bubble instead of escaping its wrapper, while non-rendering scalars no longer create empty spacing. Direct light/dark, a11y, RTL, and narrow-layout evidence protects the result. |
+| Builder impact | Existing props and values remain compatible. Builders passing `0` now get the same aligned placement as other visible scalars; nullish, boolean, and empty-string slot values emit no wrapper. |
+| Compatibility/readiness | Patch-compatible behavior correction. `@astryxdesign/[email protected]` already ships this surface through `./Chat`. The draft records the scalar correction and leaves composite/asynchronous content ownership and local visual representation unsettled. |
+| Review checks | Reject a dropped root passthrough/ref, missing target metadata, physical grouped-corner logic, an explicit width that retains the default cap, scalar `0` outside its wrapper, empty scalar wrappers, or a claim that settles the open composite boundary. |
+| Governing rules | `architecture:public-component-api/INV1, INV5, INV6, INV8–INV9`; `architecture:component-theming-surface/INV4, INV6–INV8`; `architecture:component-test-sufficiency/INV1–INV7, INV10–INV11`; WCAG 2.2 SC 1.4.10. |
+
+This table is a review projection; the body below is authoritative.
+
+## Intent
+
+ChatMessageBubble is the optional sender-aware painted content surface inside a
+ChatMessage. It gives conversation content a bubble boundary, text inset,
+grouped-corner treatment, and aligned name/metadata placement that raw message
+content does not have.
+
+This record is an observational backfill written during the 2026-09-24
+whole-component audit. It describes verified shipped behavior. It does not
+decide new visual direction, expand the variant axis, or decide how the
+component should inspect composite or asynchronous React content.
+
+## Compatibility and migration
+
+- Released default preserved: yes — `@astryxdesign/[email protected]` ships the `./Chat`
+ subpath, all six component props, the assistant/balanced fallback, and the
+ filled default.
+- Compatibility class: patch. Visible numeric zero is moved into the existing
+ aligned wrapper; non-rendering scalar slots no longer create wrappers.
+- Controlled/uncontrolled behavior: unchanged — the component owns no state.
+- Migration decision: none. Existing consumers need no code change.
+
+Consumer migration instructions belong in consumer docs and release notes.
+
+## Ownership boundary
+
+**Owns**
+
+- The bubble root's fill, text color, typography, radius, padding, wrapping, and
+ width cap.
+- Mapping message sender and density context to bubble paint and geometry.
+- Grouped corner geometry on the sender side, using logical corners.
+- The aligned wrappers around optional `name` and `metadata` content.
+- Root DOM passthrough, consumer style composition, and the root ref.
+
+**Does not own / non-goals**
+
+- Message semantics, sender layout, avatar placement, or message-level names and
+ metadata — owned by ChatMessage or the shared Chat composition surface.
+- Timestamp, delivery status, and footer semantics — owned by
+ ChatMessageMetadata.
+- The meaning, accessibility, lifetime, or eventual rendered output of
+ caller-supplied React nodes.
+- List scrolling, transcript semantics, composer behavior, or system notices —
+ owned by their Chat components.
+
+## Public concepts
+
+| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
+| ---------------------------- | ----------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ----------------------------------------- | ---------------------- | ---------------------------------------- | ------------- | -------------------------------------------------------------------------------- |
+| `children` | any `ReactNode` | Content rendered inside the bubble root | always | required | caller | stable | n/a — required |
+| `variant` | `filled`, `ghost` | Selects a filled sender-aware boundary or transparent aligned content | always | `filled` | component | stable | closed union; rejected by types |
+| `name` | omitted; any `ReactNode` | Optional content above the bubble in an aligned wrapper | always | omitted | caller/component wrapper | stable | non-rendering scalars omit; visible scalars including `0` align; see FR7 and OQ1 |
+| `metadata` | omitted; any `ReactNode` | Optional content below the bubble in an aligned wrapper | always | omitted | caller/component wrapper | stable | non-rendering scalars omit; visible scalars including `0` align; see FR7 and OQ1 |
+| `group` | omitted, `first`, `middle`, `last` | Tightens sender-side corners for consecutive bubbles | filled, ghost | omitted | component | stable | omitted keeps full radius; other values rejected by types |
+| `width` | omitted; any `SizeValue` | Replaces the default width cap with an explicit width | filled, ghost | omitted | caller | stable | numbers become CSS pixels; strings pass through |
+| message context | sender `user`, `assistant`, `system`; density `compact`, `balanced`, `spacious`; absent | Selects reflected sender/density and corresponding paint and geometry | when nested or standalone | assistant and balanced | Chat context / this projection | observational | absent context uses component fallbacks |
+| root `div` | `BaseProps<HTMLDivElement>` and `ref` | Extends and references the element carrying children, paint, target, and bubble geometry | always | none | `architecture:public-component-api` | stable | component target data and consumer styling compose |
+| `chat-message-bubble` target | sender, variant, and density reflected as `data-*`; exact guaranteed-property set not separately declared in docs | Public selector for the painting bubble root | always | one target per bubble | `architecture:component-theming-surface` | stable | undeclared generic properties remain best effort |
+
+Consumer syntax and prop defaults remain in `ChatMessageBubble.doc.mjs`.
+
+## Behavioral and layout contract
+
+Draft requirements identify their basis so observed code is not mistaken for an
+intentional decision. A `current` contract contains no unresolved rows.
+
+| ID | Candidate invariant | Basis | Draft review state |
+| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | ------------------------- |
+| FR1 | The component MUST always render one root `div` for `children`, including when the caller supplies non-rendering child content. | shipped implementation and required `children` public seam | verified observation |
+| FR2 | The root MUST reflect the resolved sender. `user` selects user paint; `assistant`, `system`, and absent context use the non-user paint path; absent context reflects `assistant`. | shipped implementation and browser/unit evidence | verified observation |
+| FR3 | The root MUST reflect the resolved density. `compact` uses the compact radius and inset; `balanced` is the fallback; `spacious` uses its wider block and inline inset. | shipped implementation and browser/unit evidence | verified observation |
+| FR4 | `filled` MUST paint sender-aware bubble styles; `ghost` MUST remove the fill and block-axis padding while preserving inline alignment. | shipped implementation, consumer docs, and rendered evidence | verified observation |
+| FR5 | `first`, `middle`, and `last` MUST tighten the logical sender-side end, both, and start corner respectively. User uses inline-end; every non-user sender uses inline-start. | shipped implementation plus real-browser LTR/RTL evidence | verified observation |
+| FR6 | Omitted `width` MUST keep `max(80%, 280px)`. An explicit number or string MUST set width and replace the default cap with `none`. | shipped consumer docs, implementation, and unit evidence | verified observation |
+| FR7 | `name` and `metadata` MUST omit their aligned wrappers for null, undefined, booleans, and the empty string. Visible scalar values, including numeric zero, MUST remain inside their aligned wrappers. Non-scalar React nodes remain opaque. | shared `isRenderable` scalar contract, public `ReactNode` seam, and red-before-green evidence | settled scalar obligation |
+| FR8 | Root `ref`, neutral DOM/data/ARIA props, class, style, and `xstyle` MUST reach or combine on the painting root without losing the component target or owned styles. | `architecture:public-component-api/INV5, INV6, INV8` | settled obligation |
+| FR9 | Exactly one `chat-message-bubble` target MUST ride the painting root and reflect sender, variant, and density. | `architecture:component-theming-surface/INV4, INV6–INV8`; public Chat docs | settled obligation |
+
+FR7 corrects two reachable scalar mismatches. JavaScript truthiness previously
+returned numeric `0` as an unwrapped Fragment sibling, so React painted it
+outside the promised alignment, while `true` created an empty wrapper and gap.
+The shared scalar predicate now keeps visible scalars in their wrappers and
+omits scalar values that React does not paint.
+
+The public type also admits arrays, Fragments, elements, one-shot iterables,
+lazy content, and promises. The scalar correction does not traverse, clone,
+consume, await, or materialize those values: each remains caller-owned opaque
+content. Whether any composite or asynchronous category should be normalized is
+OQ1 rather than an implicit extension of this patch.
+
+### Allowed variation
+
+- **AV1 — Theme tokens.** Resolved colors, radii, spacing, and typography may vary
+ by theme while the semantic token roles remain.
+- **AV2 — Caller content.** Child, name, and metadata node structure and semantics
+ remain caller-owned.
+- **AV3 — Absolute geometry.** Token-resolved padding and radius may vary; logical
+ sender-side grouping and width precedence do not.
+
+### Representative states
+
+| State | Required invariant | Allowed variation |
+| ------------------------- | -------------------------------------------------------------------- | ---------------------------------- |
+| standalone | assistant sender and balanced density fallback; one painting target | caller content |
+| assistant/system, filled | non-user paint; inline-start grouped corners | token-resolved paint |
+| user, filled | user paint; inline-end grouped corners | token-resolved paint |
+| any sender, ghost | transparent surface; inline inset retained; block inset removed | themed text and padding |
+| compact/balanced/spacious | reflected density and corresponding padding/radius path | resolved token scale |
+| group first/middle/last | logical sender-side corner sequence in LTR and RTL | token-resolved radii |
+| numeric slot `0` | visible zero remains inside the aligned wrapper | none |
+| non-rendering scalar slot | null, undefined, booleans, and empty string emit no aligned wrapper | none |
+| opaque name/metadata | non-scalar inputs emit wrappers without traversal or materialization | eventual caller-owned React output |
+| width omitted/explicit | default cap retained / explicit width replaces cap | valid CSS length |
+| narrow/long text | text wraps with no horizontal overflow at 320 CSS px | line breaks and resulting height |
+
+### Transformation and precedence order
+
+- **ORD1 — Context to paint.** Resolve sender/density from the nearest message
+ context or local fallback, select paint and geometry, then merge component
+ theme props, StyleX output, and consumer styling inputs through the shared
+ `mergeProps` contract.
+- **ORD2 — Width.** Apply the default maximum width when omitted; when explicit,
+ set width and replace that cap before consumer styling composition.
+- **ORD3 — Grouping.** Resolve sender side first, then group position, then use
+ logical corner properties so CSS direction mirrors the physical edge.
+
+### Performance and resources
+
+- **PR1 — Pure render derivation.** The component owns no state, Effect, event
+ listener, observer, timer, or animation frame. Every output derives from props
+ and context during render.
+- **PR2 — Caller content is not inspected.** The current implementation does not
+ traverse, clone, consume, await, or materialize caller-supplied React nodes.
+ Whether to preserve that boundary or normalize selected inputs is OQ1.
+
+## Accessibility contract
+
+- **AR1 — Display surface.** ChatMessageBubble adds no widget role, tab stop,
+ keyboard behavior, focus management, announcement, or accessible name of its
+ own. Semantics belong to the enclosing ChatMessage and caller content.
+- **AR2 — Content preservation.** Caller DOM and ARIA passthrough reach the bubble
+ root under FR8; component target metadata MUST NOT overwrite neutral caller ARIA.
+- **AR3 — Reflow.** At a 320 CSS-px parent width, long content and the documented
+ full-width case MUST wrap without horizontal page overflow (WCAG 2.2 SC 1.4.10).
+- **AR4 — Color.** Bubble text remains meaningful content and requires WCAG 2.2
+ AA text contrast against the final rendered bubble/backdrop in light and dark.
+ The component uses semantic token pairs; rendered measurement remains the audit
+ oracle.
+
+## Design relationships
+
+| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
+| ---------------- | ----------------------------------------------------- | ------------------------ | -------------- | ------------------ |
+| bubble content | sender-aware filled boundary or aligned ghost surface | unsettled | primary | FR2–FR4 |
+| grouped corners | visually connect consecutive bubbles on sender side | unsettled | supporting | FR5 |
+| name | align auxiliary content with bubble text inset | unsettled | supporting | FR7 |
+| metadata | align auxiliary content with bubble text inset | unsettled | supporting | FR7 |
+
+No `authority: current` design record owns ChatMessageBubble's local
+representation today. These rows record shipped appearance for review; they do
+not authorize a redesign or convert rendered judgment into policy.
+
+## Family and system relationships
+
+- The shared Chat consumer docs own composition guidance across message, bubble,
+ metadata, list, layout, and composer components.
+- `architecture:public-component-api` owns export, passthrough, styling-input,
+ and ref behavior.
+- `architecture:component-theming-surface` owns the painting target and reflected
+ axes. It does not independently require this closed variant axis to become
+ extensible; that would need a component-level public API decision.
+- `architecture:component-test-sufficiency` owns the closed, risk-based evidence
+ inventory and the red-before-green requirement for any future slot repair.
+- `spec:AST-029` owns the Night Watch observational backfill and remediation flow.
+
+## Verification map
+
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| -------- | -------------------------------------------------------------------- | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------- | --------------------------------------- |
+| FR1–FR3 | `ChatMessageBubble.test.tsx`; dedicated Storybook fixture | standalone; user/assistant; compact/balanced/spacious | removing fallback/reflection or a density path fails DOM or browser state evidence | `audit:ChatMessageBubble/behavior` |
+| FR4, FR9 | `themingTargets.test.ts`; scoped axe report; Chromium evidence | filled; ghost; user/assistant/density | dropping reflection or moving the target fails DOM, generated, or rendered evidence | `audit:ChatMessageBubble/theming` |
+| FR5 | dedicated RTL target plus Chromium LTR/RTL frames | user/assistant × first/middle/last | physical corner logic or wrong sender side fails mirrored geometry and pixels | `audit:ChatMessageBubble/rtl` |
+| FR6 | `ChatMessageBubble.test.tsx`; narrow browser fixture | omitted; string `100%`; number `420` | retaining the cap or changing numeric CSS semantics fails the width assertions | `audit:ChatMessageBubble/behavior` |
+| FR7 | `ChatMessageBubble.test.tsx`; pre-fix Chromium receipts and pixels | zero; true; false; empty string; nullish; opaque non-scalars | reverting to truthiness loses wrapper alignment or restores an empty scalar wrapper | `audit:ChatMessageBubble/behavior` |
+| FR8 | public-API checks and existing `data-testid`/style composition tests | ref; DOM/data/ARIA; class; style | removing rest/ref forwarding or replacing consumer styling fails shared or focused checks | `audit:ChatMessageBubble/public-api` |
+| AR1–AR4 | scoped axe report; Chromium receipts and pixels; narrow fixture | all visible states, light/dark, RTL, 320px | a semantic violation, low-contrast pair, or horizontal overflow fails its owning evidence layer | `audit:ChatMessageBubble/accessibility` |
+
+## Decision log
+
+No component-local decision has been approved. This draft records only verified
+shipped behavior and the evidence routes added by the audit.
+
+## Open questions
+
+- **OQ1 — Should ChatMessageBubble keep every non-scalar `ReactNode`
+ name/metadata value as caller-owned opaque content, or normalize selected
+ arrays, Fragments, one-shot iterables, lazy values, or promises into a stable,
+ rerender-safe empty/non-empty contract?** (`human-api`)
+- **OQ2 — Should the aligned name and metadata wrappers become independently
+ themeable, inherit a current owner, or remain intentionally unreachable?**
+ (`human-api`)
+- **OQ3 — Which current design owner, if any, should make filled/ghost usage and
+ grouped-corner representation durable rather than observational?**
+ (`human-design`)
+
+## Content boundary
+
+This file does not duplicate the consumer prop table/examples, current audit
+scores, implementation steps, or shared architecture rules. Those remain in
+`ChatMessageBubble.doc.mjs`, the audit report, and their canonical owners.
diff --git a/packages/core/src/Chat/ChatMessageBubble.test.tsx b/packages/core/src/Chat/ChatMessageBubble.test.tsx
index 8104b40331..791bc500d8 100644
--- a/packages/core/src/Chat/ChatMessageBubble.test.tsx
+++ b/packages/core/src/Chat/ChatMessageBubble.test.tsx
@@ -1,5 +1,6 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+import {createRef, type ReactNode} from 'react';
import {describe, it, expect} from 'vitest';
import {render, screen} from '@testing-library/react';
import {ChatMessage} from './ChatMessage';
@@ -66,6 +67,98 @@ describe('ChatMessageBubble', () => {
expect(screen.getByTestId('my-bubble')).toBeTruthy();
});
+ it('renders aligned name and metadata slots around the bubble root', () => {
+ render(
+ <ChatMessage sender="assistant">
+ <ChatMessageBubble
+ data-testid="bubble"
+ name="Navi"
+ metadata={<span>10:32 AM</span>}>
+ Hi
+ </ChatMessageBubble>
+ </ChatMessage>,
+ );
+ const bubble = screen.getByTestId('bubble');
+
+ expect(bubble.previousElementSibling).toHaveTextContent('Navi');
+ expect(bubble.nextElementSibling).toHaveTextContent('10:32 AM');
+ });
+
+ it('keeps numeric zero inside the aligned name and metadata slots', () => {
+ render(
+ <ChatMessageBubble data-testid="bubble" name={0} metadata={0}>
+ Zero slots
+ </ChatMessageBubble>,
+ );
+ const bubble = screen.getByTestId('bubble');
+
+ expect(bubble.previousElementSibling).toHaveAttribute('data-chat-name');
+ expect(bubble.previousElementSibling).toHaveTextContent('0');
+ expect(bubble.nextElementSibling).toHaveTextContent('0');
+ });
+
+ it.each([
+ ['null', null],
+ ['undefined', undefined],
+ ['false', false],
+ ['true', true],
+ ['empty string', ''],
+ ] satisfies [string, ReactNode][])(
+ 'omits aligned wrappers for %s',
+ (_, value) => {
+ const {container} = render(
+ <ChatMessageBubble data-testid="bubble" name={value} metadata={value}>
+ Empty scalar slots
+ </ChatMessageBubble>,
+ );
+ const bubble = screen.getByTestId('bubble');
+
+ expect(container.querySelector('[data-chat-name]')).toBeNull();
+ expect(bubble.previousElementSibling).toBeNull();
+ expect(bubble.nextElementSibling).toBeNull();
+ },
+ );
+
+ it('forwards the ref and neutral DOM props to the bubble root', () => {
+ const ref = createRef<HTMLDivElement>();
+ render(
+ <ChatMessageBubble
+ ref={ref}
+ id="bubble-id"
+ aria-label="Message content"
+ data-consumer="preserved"
+ data-testid="bubble">
+ Standalone
+ </ChatMessageBubble>,
+ );
+ const bubble = screen.getByTestId('bubble');
+
+ expect(ref.current).toBe(bubble);
+ expect(bubble).toHaveAttribute('id', 'bubble-id');
+ expect(bubble).toHaveAttribute('aria-label', 'Message content');
+ expect(bubble).toHaveAttribute('data-consumer', 'preserved');
+ });
+
+ it('reflects both built-in visual variants on the painting root', () => {
+ render(
+ <>
+ <ChatMessageBubble data-testid="filled">Filled</ChatMessageBubble>
+ <ChatMessageBubble data-testid="ghost" variant="ghost">
+ Ghost
+ </ChatMessageBubble>
+ </>,
+ );
+
+ expect(screen.getByTestId('filled')).toHaveAttribute(
+ 'data-variant',
+ 'filled',
+ );
+ expect(screen.getByTestId('ghost')).toHaveAttribute(
+ 'data-variant',
+ 'ghost',
+ );
+ });
+
it('ghost variant aligns custom content with the bubble text column (#2574)', () => {
// Repro from the issue: a raw child renders flush with the message
// edge — it carries none of the inset the bubble's name slot gets.
diff --git a/packages/core/src/Chat/ChatMessageBubble.tsx b/packages/core/src/Chat/ChatMessageBubble.tsx
index fc35a76d86..b240230fdb 100644
--- a/packages/core/src/Chat/ChatMessageBubble.tsx
+++ b/packages/core/src/Chat/ChatMessageBubble.tsx
@@ -38,7 +38,7 @@ import {
typographyVars,
} from '../theme/tokens.stylex';
import {useChatMessageContext} from './ChatContext';
-import {mergeProps} from '../utils';
+import {isRenderable, mergeProps} from '../utils';
import type {SizeValue} from '../utils/types';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
@@ -64,6 +64,7 @@ export interface ChatMessageBubbleProps extends BaseProps<HTMLDivElement> {
/**
* Sender name rendered above the bubble, aligned with bubble text padding.
+ * Non-rendering scalar values omit the aligned wrapper; numeric zero remains.
* Use when the first content in a message is a bubble.
* If the first content is raw (no bubble), use ChatMessage's `name`
* prop instead.
@@ -72,6 +73,7 @@ export interface ChatMessageBubbleProps extends BaseProps<HTMLDivElement> {
/**
* Metadata content rendered below the bubble, aligned with bubble text padding.
+ * Non-rendering scalar values omit the aligned wrapper; numeric zero remains.
* Use when the last content in a message is a bubble.
* If the last content is raw (no bubble), use ChatMessage's `metadata`
* prop instead.
@@ -289,9 +291,12 @@ export function ChatMessageBubble({
? styles.metadataPaddingSpacious
: styles.metadataPaddingBalanced;
+ const hasName = isRenderable(name);
+ const hasMetadata = isRenderable(metadata);
+
return (
<>
- {name && (
+ {hasName && (
<div
data-chat-name
{...stylex.props(
@@ -324,7 +329,7 @@ export function ChatMessageBubble({
)}>
{children}
</div>
- {metadata && (
+ {hasMetadata && (
<div
{...stylex.props(
metadataPaddingStyle,
diff --git a/packages/core/src/Chat/__tests__/ChatMessageBubble.a11y.chromium.spec.ts b/packages/core/src/Chat/__tests__/ChatMessageBubble.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..0d8d08e252
--- /dev/null
+++ b/packages/core/src/Chat/__tests__/ChatMessageBubble.a11y.chromium.spec.ts
@@ -0,0 +1,457 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChatMessageBubble.a11y.chromium.spec.ts
+ * @input Uses the dedicated ChatMessageBubble Storybook fixtures
+ * @output Real-Chromium light, dark, RTL, density, grouping, empty, and
+ * narrow-overflow evidence with sensor receipts
+ * @position Browser evidence for the ChatMessageBubble component contract
+ */
+
+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 Locator, type Page} from '@playwright/test';
+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+import {
+ type ChatMessageBubbleAuditProvenance,
+ resolveChatMessageBubbleAuditProvenance,
+} from './ChatMessageBubble.auditProvenance';
+
+const OUTPUT = path.resolve('test-results/chat-message-bubble-audit-evidence');
+const STATES_STORY = 'core-chatmessagebubble--states';
+const NARROW_STORY = 'core-chatmessagebubble--narrow-long-content';
+const STATES = [
+ 'sender-alignment',
+ 'filled-and-ghost',
+ 'assistant-group',
+ 'user-group',
+ 'density',
+ 'numeric-slots',
+ 'empty-content',
+] as const;
+
+interface Receipt {
+ state: string;
+ storyId: string;
+ build: string;
+ browser: string;
+ theme: string;
+ colorMode: string;
+ direction: string;
+ viewport: {width: number; height: number};
+ devicePixelRatio: number;
+ media: {reducedMotion: boolean; coarsePointer: boolean};
+ rendered: Record<string, unknown>;
+ geometry: {selectorCount: number; width: number; height: number};
+ settled: {fontsReady: boolean; pageErrors: number};
+ image: {file: string; sha256: string; width: number; height: number};
+}
+
+const receipts: Receipt[] = [];
+let storybook: StaticServer;
+let browserVersion = 'unknown';
+let auditProvenance: ChatMessageBubbleAuditProvenance | null = null;
+
+function pageErrors(page: Page): string[] {
+ const errors: string[] = [];
+ page.on('pageerror', error => errors.push(String(error)));
+ return errors;
+}
+
+test.beforeAll(async () => {
+ const checkoutSha = execFileSync('git', ['rev-parse', 'HEAD'], {
+ encoding: 'utf8',
+ }).trim();
+ fs.mkdirSync(OUTPUT, {recursive: true});
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+ auditProvenance = await resolveChatMessageBubbleAuditProvenance({
+ checkoutSha,
+ expectedHeadSha: process.env.ASTRYX_HEAD_SHA,
+ storybookOrigin: storybook.origin,
+ });
+});
+
+test.afterAll(async () => {
+ if (auditProvenance == null) {
+ await storybook?.close();
+ return;
+ }
+ const manifestPath = path.join(OUTPUT, 'manifest.json');
+ const previous = fs.existsSync(manifestPath)
+ ? (JSON.parse(fs.readFileSync(manifestPath, 'utf8')).frames ?? [])
+ : [];
+ const frames = [...previous, ...receipts].filter(
+ (frame, index, all) =>
+ all.findIndex(
+ other =>
+ other.state === frame.state &&
+ other.storyId === frame.storyId &&
+ other.colorMode === frame.colorMode &&
+ other.direction === frame.direction,
+ ) === index,
+ );
+ fs.writeFileSync(
+ manifestPath,
+ `${JSON.stringify(
+ {
+ version: 2,
+ component: 'core/ChatMessageBubble',
+ headSha: auditProvenance.headSha,
+ checkoutSha: auditProvenance.checkoutSha,
+ storybookSha: auditProvenance.storybookSha,
+ provenanceMode: auditProvenance.mode,
+ browser: browserVersion,
+ frames,
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+ await storybook?.close();
+});
+
+async function openStory(
+ page: Page,
+ storyId: string,
+ {
+ colorMode = 'light',
+ direction = 'ltr',
+ }: {colorMode?: 'light' | 'dark'; direction?: 'ltr' | 'rtl'} = {},
+): Promise<string[]> {
+ const errors = pageErrors(page);
+ browserVersion = page.context().browser()?.version() ?? 'unknown';
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=${storyId}&viewMode=story` +
+ `&globals=colorMode:${colorMode};astryxTheme:neutral;direction:${direction}`,
+ );
+ await page.locator('#storybook-root > *').waitFor();
+ await holdMotionStill(page);
+ await page.evaluate(async () => document.fonts.ready);
+ return errors;
+}
+
+function stateLocator(page: Page, state: string): Locator {
+ return page.locator(`[data-bubble-audit-state="${state}"]`);
+}
+
+function pngImage(file: string, bytes: Buffer) {
+ return {
+ file,
+ sha256: createHash('sha256').update(bytes).digest('hex'),
+ width: bytes.readUInt32BE(16),
+ height: bytes.readUInt32BE(20),
+ };
+}
+
+async function capture(
+ page: Page,
+ locator: Locator,
+ {
+ state,
+ storyId,
+ colorMode,
+ direction,
+ errors,
+ }: {
+ state: string;
+ storyId: string;
+ colorMode: 'light' | 'dark';
+ direction: 'ltr' | 'rtl';
+ errors: string[];
+ },
+): Promise<Receipt> {
+ const box = await locator.boundingBox();
+ if (box == null) {
+ throw new Error(`${state}: the evidence subject has no visible box`);
+ }
+ const rendered = await locator.evaluate(host => {
+ const bubbles = [...host.querySelectorAll('.astryx-chat-message-bubble')];
+ const numeric = host.querySelector('[data-testid="numeric-slot-bubble"]');
+
+ const parseColor = (input: string): [number, number, number, number] => {
+ if (input === 'transparent') {
+ return [0, 0, 0, 0];
+ }
+ const channels = input.match(/[\d.]+/g)?.map(Number) ?? [];
+ return [
+ channels[0] ?? 0,
+ channels[1] ?? 0,
+ channels[2] ?? 0,
+ channels[3] ?? 1,
+ ];
+ };
+ const over = (
+ foreground: [number, number, number, number],
+ backdrop: [number, number, number, number],
+ ): [number, number, number, number] => {
+ const alpha = foreground[3] + backdrop[3] * (1 - foreground[3]);
+ if (alpha === 0) {
+ return [0, 0, 0, 0];
+ }
+ return [
+ (foreground[0] * foreground[3] +
+ backdrop[0] * backdrop[3] * (1 - foreground[3])) /
+ alpha,
+ (foreground[1] * foreground[3] +
+ backdrop[1] * backdrop[3] * (1 - foreground[3])) /
+ alpha,
+ (foreground[2] * foreground[3] +
+ backdrop[2] * backdrop[3] * (1 - foreground[3])) /
+ alpha,
+ alpha,
+ ];
+ };
+ const backdropOf = (element: Element) => {
+ const layers: [number, number, number, number][] = [];
+ for (
+ let current: Element | null = element;
+ current != null;
+ current = current.parentElement
+ ) {
+ layers.push(parseColor(getComputedStyle(current).backgroundColor));
+ }
+ const dark =
+ getComputedStyle(document.documentElement).colorScheme === 'dark';
+ return layers
+ .reverse()
+ .reduce(over, dark ? [0, 0, 0, 1] : [255, 255, 255, 1]);
+ };
+ const luminance = (color: [number, number, number, number]) => {
+ const linear = color.slice(0, 3).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];
+ };
+ const ratio = (
+ foreground: [number, number, number, number],
+ backdrop: [number, number, number, number],
+ ) => {
+ const paintedForeground = over(foreground, backdrop);
+ const lighter = Math.max(
+ luminance(paintedForeground),
+ luminance(backdrop),
+ );
+ const darker = Math.min(
+ luminance(paintedForeground),
+ luminance(backdrop),
+ );
+ return (lighter + 0.05) / (darker + 0.05);
+ };
+
+ return {
+ bubbleCount: bubbles.length,
+ targetValues: bubbles.map(element => {
+ const styles = getComputedStyle(element);
+ const backdrop = backdropOf(element);
+ return {
+ sender: element.getAttribute('data-sender'),
+ variant: element.getAttribute('data-variant'),
+ density: element.getAttribute('data-density'),
+ color: styles.color,
+ backgroundColor: styles.backgroundColor,
+ backdrop: `rgb(${backdrop.slice(0, 3).map(Math.round).join(', ')})`,
+ contrastRatio:
+ element.textContent?.trim() === ''
+ ? null
+ : Number(ratio(parseColor(styles.color), backdrop).toFixed(2)),
+ corners: {
+ topLeft: styles.borderTopLeftRadius,
+ topRight: styles.borderTopRightRadius,
+ bottomRight: styles.borderBottomRightRadius,
+ bottomLeft: styles.borderBottomLeftRadius,
+ },
+ };
+ }),
+ nameSlots: host.querySelectorAll('[data-chat-name]').length,
+ numericNameAligned:
+ numeric?.previousElementSibling?.hasAttribute('data-chat-name') ??
+ false,
+ numericMetadataAligned:
+ numeric?.nextElementSibling?.textContent?.trim() === '0',
+ overflowFree: host.scrollWidth <= host.clientWidth + 1,
+ };
+ });
+ const window = await page.evaluate(() => ({
+ width: globalThis.innerWidth,
+ height: globalThis.innerHeight,
+ dpr: globalThis.devicePixelRatio,
+ reducedMotion: matchMedia('(prefers-reduced-motion: reduce)').matches,
+ coarsePointer: matchMedia('(pointer: coarse)').matches,
+ }));
+ const bytes = await locator.screenshot({animations: 'disabled'});
+ const file = `chat-message-bubble__${state}__${colorMode}__${direction}.png`;
+ fs.writeFileSync(path.join(OUTPUT, file), bytes);
+ if (auditProvenance == null) {
+ throw new Error('ChatMessageBubble audit provenance is unresolved');
+ }
+ const receipt: Receipt = {
+ state,
+ storyId,
+ build: auditProvenance.build,
+ browser: browserVersion,
+ theme:
+ (await page
+ .locator('[data-astryx-theme]')
+ .first()
+ .getAttribute('data-astryx-theme')) ?? 'neutral',
+ colorMode,
+ direction: await locator.evaluate(
+ element => getComputedStyle(element).direction,
+ ),
+ viewport: {width: window.width, height: window.height},
+ devicePixelRatio: window.dpr,
+ media: {
+ reducedMotion: window.reducedMotion,
+ coarsePointer: window.coarsePointer,
+ },
+ rendered,
+ geometry: {
+ selectorCount: await locator.count(),
+ width: Math.round(box.width),
+ height: Math.round(box.height),
+ },
+ settled: {fontsReady: true, pageErrors: errors.length},
+ image: pngImage(file, bytes),
+ };
+ receipts.push(receipt);
+ return receipt;
+}
+
+type CornerName = 'topLeft' | 'topRight' | 'bottomRight' | 'bottomLeft';
+
+function expectGroupedCorners(
+ receipt: Receipt,
+ sender: 'assistant' | 'user',
+): void {
+ const values = receipt.rendered.targetValues as {
+ sender: string;
+ corners: Record<CornerName, string>;
+ }[];
+ expect(values).toHaveLength(3);
+ expect(values.every(value => value.sender === sender)).toBe(true);
+
+ const senderSideIsLeft =
+ (sender === 'assistant' && receipt.direction === 'ltr') ||
+ (sender === 'user' && receipt.direction === 'rtl');
+ const top: CornerName = senderSideIsLeft ? 'topLeft' : 'topRight';
+ const bottom: CornerName = senderSideIsLeft ? 'bottomLeft' : 'bottomRight';
+ const oppositeTop: CornerName = senderSideIsLeft ? 'topRight' : 'topLeft';
+ const oppositeBottom: CornerName = senderSideIsLeft
+ ? 'bottomRight'
+ : 'bottomLeft';
+ const [first, middle, last] = values;
+
+ expect(first.corners[bottom]).toBe(middle.corners[bottom]);
+ expect(middle.corners[top]).toBe(last.corners[top]);
+ expect(first.corners[bottom]).not.toBe(first.corners[top]);
+ expect(last.corners[top]).not.toBe(last.corners[bottom]);
+ expect(values.map(value => value.corners[oppositeTop])).toEqual([
+ first.corners[oppositeTop],
+ first.corners[oppositeTop],
+ first.corners[oppositeTop],
+ ]);
+ expect(values.map(value => value.corners[oppositeBottom])).toEqual([
+ first.corners[oppositeBottom],
+ first.corners[oppositeBottom],
+ first.corners[oppositeBottom],
+ ]);
+}
+
+test('captures every visible state in neutral light and dark', async ({
+ page,
+}) => {
+ for (const colorMode of ['light', 'dark'] as const) {
+ const errors = await openStory(page, STATES_STORY, {colorMode});
+ for (const state of STATES) {
+ const locator = stateLocator(page, state);
+ const receipt = await capture(page, locator, {
+ state,
+ storyId: STATES_STORY,
+ colorMode,
+ direction: 'ltr',
+ errors,
+ });
+ expect(receipt.geometry.selectorCount).toBe(1);
+ expect(receipt.geometry.width).toBeGreaterThan(0);
+ expect(receipt.geometry.height).toBeGreaterThan(0);
+ const ratios = (
+ receipt.rendered.targetValues as {contrastRatio: number | null}[]
+ )
+ .map(value => value.contrastRatio)
+ .filter((value): value is number => value != null);
+ for (const ratio of ratios) {
+ expect(
+ ratio,
+ `${state}/${colorMode}: bubble text contrast`,
+ ).toBeGreaterThanOrEqual(4.5);
+ }
+ if (state === 'assistant-group' || state === 'user-group') {
+ expectGroupedCorners(
+ receipt,
+ state === 'assistant-group' ? 'assistant' : 'user',
+ );
+ }
+ if (state === 'numeric-slots') {
+ expect(receipt.rendered.nameSlots).toBe(1);
+ expect(receipt.rendered.numericNameAligned).toBe(true);
+ expect(receipt.rendered.numericMetadataAligned).toBe(true);
+ }
+ }
+ expect(errors).toEqual([]);
+ }
+});
+
+test('captures sender alignment and grouped corners in RTL', async ({page}) => {
+ for (const colorMode of ['light', 'dark'] as const) {
+ const errors = await openStory(page, STATES_STORY, {
+ colorMode,
+ direction: 'rtl',
+ });
+ for (const state of ['sender-alignment', 'assistant-group', 'user-group']) {
+ const receipt = await capture(page, stateLocator(page, state), {
+ state,
+ storyId: STATES_STORY,
+ colorMode,
+ direction: 'rtl',
+ errors,
+ });
+ expect(receipt.direction).toBe('rtl');
+ if (state === 'assistant-group' || state === 'user-group') {
+ expectGroupedCorners(
+ receipt,
+ state === 'assistant-group' ? 'assistant' : 'user',
+ );
+ }
+ }
+ expect(errors).toEqual([]);
+ }
+});
+
+test('keeps long content inside a 320px fixture', async ({page}) => {
+ for (const colorMode of ['light', 'dark'] as const) {
+ const errors = await openStory(page, NARROW_STORY, {colorMode});
+ const subject = page.locator('[data-chat-message-bubble-narrow]');
+ const receipt = await capture(page, subject, {
+ state: 'narrow-long-content',
+ storyId: NARROW_STORY,
+ colorMode,
+ direction: 'ltr',
+ errors,
+ });
+ expect(receipt.geometry.width).toBeLessThanOrEqual(320);
+ expect(receipt.rendered.overflowFree).toBe(true);
+ expect(errors).toEqual([]);
+ }
+});
diff --git a/packages/core/src/Chat/__tests__/ChatMessageBubble.auditProvenance.test.ts b/packages/core/src/Chat/__tests__/ChatMessageBubble.auditProvenance.test.ts
new file mode 100644
index 0000000000..eea65d2be5
--- /dev/null
+++ b/packages/core/src/Chat/__tests__/ChatMessageBubble.auditProvenance.test.ts
@@ -0,0 +1,91 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChatMessageBubble.auditProvenance.test.ts
+ * @input Local unstamped and CI exact-head provenance fixtures
+ * @output Fail-open local execution and fail-closed CI provenance contracts
+ * @position Focused regression tests for the Bubble browser evidence boundary
+ */
+
+import {describe, expect, it, vi} from 'vitest';
+import {
+ type BuildStampResponse,
+ resolveChatMessageBubbleAuditProvenance,
+} from './ChatMessageBubble.auditProvenance';
+
+const HEAD = 'a'.repeat(40);
+const OTHER_HEAD = 'b'.repeat(40);
+
+function stamp(status: number, body = '') {
+ return vi.fn(async (): Promise<BuildStampResponse> => ({
+ ok: status >= 200 && status < 300,
+ status,
+ text: async () => body,
+ }));
+}
+
+describe('ChatMessageBubble audit provenance', () => {
+ it('runs an ordinary local Storybook build without an exact-head stamp', async () => {
+ const fetchStamp = stamp(404);
+
+ await expect(
+ resolveChatMessageBubbleAuditProvenance({
+ checkoutSha: HEAD,
+ storybookOrigin: 'http://127.0.0.1:6006',
+ fetchStamp,
+ }),
+ ).resolves.toEqual({
+ mode: 'local-unstamped',
+ headSha: null,
+ checkoutSha: HEAD,
+ storybookSha: null,
+ build: 'local-unstamped',
+ });
+ expect(fetchStamp).toHaveBeenCalledWith(
+ 'http://127.0.0.1:6006/astryx-build-sha.txt',
+ );
+ });
+
+ it('fails closed when CI Storybook provenance is missing', async () => {
+ await expect(
+ resolveChatMessageBubbleAuditProvenance({
+ checkoutSha: HEAD,
+ expectedHeadSha: HEAD,
+ storybookOrigin: 'http://127.0.0.1:6006',
+ fetchStamp: stamp(404),
+ }),
+ ).rejects.toThrow(
+ 'exact-head evidence requires Storybook source provenance',
+ );
+ });
+
+ it('fails closed when the CI Storybook stamp differs from the checkout', async () => {
+ await expect(
+ resolveChatMessageBubbleAuditProvenance({
+ checkoutSha: HEAD,
+ expectedHeadSha: HEAD,
+ storybookOrigin: 'http://127.0.0.1:6006',
+ fetchStamp: stamp(200, OTHER_HEAD),
+ }),
+ ).rejects.toThrow(
+ `Storybook ${OTHER_HEAD} does not match checkout ${HEAD}`,
+ );
+ });
+
+ it('records exact-head provenance only when CI head, checkout, and stamp match', async () => {
+ await expect(
+ resolveChatMessageBubbleAuditProvenance({
+ checkoutSha: HEAD,
+ expectedHeadSha: HEAD,
+ storybookOrigin: 'http://127.0.0.1:6006',
+ fetchStamp: stamp(200, `${HEAD}\n`),
+ }),
+ ).resolves.toEqual({
+ mode: 'exact-head',
+ headSha: HEAD,
+ checkoutSha: HEAD,
+ storybookSha: HEAD,
+ build: HEAD,
+ });
+ });
+});
diff --git a/packages/core/src/Chat/__tests__/ChatMessageBubble.auditProvenance.ts b/packages/core/src/Chat/__tests__/ChatMessageBubble.auditProvenance.ts
new file mode 100644
index 0000000000..19efad07a4
--- /dev/null
+++ b/packages/core/src/Chat/__tests__/ChatMessageBubble.auditProvenance.ts
@@ -0,0 +1,91 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChatMessageBubble.auditProvenance.ts
+ * @input Checkout SHA, optional reviewed head, and the served Storybook stamp
+ * @output Truthful local or exact-head provenance for browser evidence
+ * @position Pure provenance boundary shared by the Bubble browser audit and tests
+ */
+
+export interface BuildStampResponse {
+ ok: boolean;
+ status: number;
+ text(): Promise<string>;
+}
+
+export interface ChatMessageBubbleAuditProvenance {
+ mode: 'exact-head' | 'checkout-bound' | 'local-unstamped';
+ headSha: string | null;
+ checkoutSha: string;
+ storybookSha: string | null;
+ build: string;
+}
+
+interface ResolveAuditProvenanceOptions {
+ checkoutSha: string;
+ expectedHeadSha?: string;
+ storybookOrigin: string;
+ fetchStamp?: (url: string) => Promise<BuildStampResponse>;
+}
+
+/**
+ * Bind CI evidence to one reviewed tree while leaving an ordinary local
+ * Storybook build runnable without making an exact-head claim it cannot prove.
+ */
+export async function resolveChatMessageBubbleAuditProvenance({
+ checkoutSha,
+ expectedHeadSha,
+ storybookOrigin,
+ fetchStamp = async url => fetch(url),
+}: ResolveAuditProvenanceOptions): Promise<ChatMessageBubbleAuditProvenance> {
+ const expectedHead = expectedHeadSha?.trim() || null;
+ if (expectedHead != null && checkoutSha !== expectedHead) {
+ throw new Error(
+ `ChatMessageBubble evidence checkout ${checkoutSha} does not match reviewed head ${expectedHead}`,
+ );
+ }
+
+ const response = await fetchStamp(`${storybookOrigin}/astryx-build-sha.txt`);
+ const storybookSha = response.ok ? (await response.text()).trim() : null;
+
+ if (expectedHead != null) {
+ if (storybookSha == null) {
+ throw new Error(
+ `ChatMessageBubble exact-head evidence requires Storybook source provenance (HTTP ${response.status})`,
+ );
+ }
+ if (storybookSha !== checkoutSha) {
+ throw new Error(
+ `ChatMessageBubble Storybook ${storybookSha} does not match checkout ${checkoutSha}`,
+ );
+ }
+ return {
+ mode: 'exact-head',
+ headSha: expectedHead,
+ checkoutSha,
+ storybookSha,
+ build: storybookSha,
+ };
+ }
+ if (storybookSha != null && storybookSha !== checkoutSha) {
+ throw new Error(
+ `ChatMessageBubble Storybook ${storybookSha} does not match checkout ${checkoutSha}`,
+ );
+ }
+ if (storybookSha != null) {
+ return {
+ mode: 'checkout-bound',
+ headSha: null,
+ checkoutSha,
+ storybookSha,
+ build: storybookSha,
+ };
+ }
+ return {
+ mode: 'local-unstamped',
+ headSha: null,
+ checkoutSha,
+ storybookSha: null,
+ build: 'local-unstamped',
+ };
+}