An open source design system that's fully customizable and agent ready
TypeScript
fix(Comments): announce error banners and progress labels through the shared channel (#7902)
Ojas Mutrejab4b978da294e
diff --git a/.changeset/comments-error-announcement-key.md b/.changeset/comments-error-announcement-key.mdnew file mode 100644index 0000000000..1e229c06ff--- /dev/null+++ b/.changeset/comments-error-announcement-key.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Comments: the failure announcement spoken for a Comments error banner now comes from the `@astryx.comments.errorAnnouncement` locale entry, so it can be translated like the rest of the component's messages.++@HelloOjasMutrejadiff --git a/packages/core/locales/en.json b/packages/core/locales/en.jsonindex fce94c3da8..7f27140ba7 100644--- a/packages/core/locales/en.json+++ b/packages/core/locales/en.json@@ -2171,6 +2171,10 @@"defaultMessage": "Resolved by {name}","description": "Tooltip of the Resolved text on a comment thread in a lab Comments panel. `name` is the person who resolved it."},+ "@astryx.comments.errorAnnouncement": {+ "defaultMessage": "{title} {description}",+ "description": "Screen-reader announcement for an error Banner in a lab Comments panel that has a title and a description, read once when the Banner appears. `title` is the Banner's title (for example `Couldn't send this comment.`) and `description` its description (for example `Retrying didn't work.`). Reorder or punctuate as the language needs."+ },"@astryx.comments.retryFailed": {"defaultMessage": "Retrying didn't work.","description": "Error shown on a comment in a lab Comments panel that failed to post when retrying it failed too."diff --git a/packages/lab/src/Comments/CommentComposer.test.tsx b/packages/lab/src/Comments/CommentComposer.test.tsxindex 1dbc7d5f4e..30adf9f03d 100644--- a/packages/lab/src/Comments/CommentComposer.test.tsx+++ b/packages/lab/src/Comments/CommentComposer.test.tsx@@ -12,6 +12,11 @@ import {it,vi,} from 'vitest';+const announce = vi.hoisted(() => vi.fn());+vi.mock('@astryxdesign/core/hooks', async importOriginal => ({+ ...(await importOriginal<typeof import('@astryxdesign/core/hooks')>()),+ useAnnounce: () => announce,+}));// The full emoji set renders slowly in jsdom; the composer only needs a few.vi.mock('../EmojiPicker/emojiData', () => ({EMOJI_GROUPS: [@@ -70,6 +75,7 @@ class ResizeObserverStub {}beforeEach(() => {+ announce.mockClear();vi.stubGlobal('ResizeObserver', ResizeObserverStub);Element.prototype.scrollIntoView = () => {};});@@ -78,6 +84,17 @@ afterEach(() => {vi.unstubAllGlobals();});+/** The composer's failure Banner, which carries no live role. */+function composerErrorBanner(): HTMLElement {+ const banner = document.querySelector<HTMLElement>(+ '[data-composer-error="banner"]',+ );+ if (banner == null) {+ throw new Error('Composer error Banner not found');+ }+ return banner;+}+async function settle() {await act(() => new Promise<void>(resolve => setTimeout(resolve, 0)));}@@ -289,9 +306,41 @@ describe('CommentComposer', () => {});});expect(onUploadImages).not.toHaveBeenCalled();- expect(screen.getByRole('alert').textContent).toContain(- 'Only image files can be added',+ const banner = composerErrorBanner();+ expect(banner.textContent).toContain('Only image files can be added');+ // The Banner has no live role: it is announced once through the channel.+ expect(banner).not.toHaveAttribute('role');+ expect(announce).toHaveBeenCalledTimes(1);+ expect(announce).toHaveBeenCalledWith(+ expect.stringContaining('Only image files can be added'),+ 'assertive',+ );+ });++ it('announces a second refusal with the same words again', async () => {+ render(+ <CommentComposer+ value=""+ onChange={() => {}}+ onSubmit={() => {}}+ onUploadImages={vi.fn()}+ />,);+ const input = document.querySelector('input[type="file"]');+ if (!(input instanceof HTMLInputElement)) {+ throw new Error('File input not found');+ }+ for (const name of ['first.pdf', 'second.pdf']) {+ await act(async () => {+ fireEvent.change(input, {+ target: {+ files: [new File(['%PDF'], name, {type: 'application/pdf'})],+ },+ });+ });+ }+ // Each refusal is its own occasion (AST-086 FR6), though the words match.+ expect(announce).toHaveBeenCalledTimes(2);});it('shows an error with Retry, and a quoted passage the viewer can remove', () => {@@ -309,8 +358,9 @@ describe('CommentComposer', () => {highlightColor="green"/>,);- const alert = screen.getByRole('alert');- fireEvent.click(within(alert).getByRole('button', {name: 'Retry'}));+ fireEvent.click(+ within(composerErrorBanner()).getByRole('button', {name: 'Retry'}),+ );expect(onRetry).toHaveBeenCalledTimes(1);expect(documentdiff --git a/packages/lab/src/Comments/CommentComposer.tsx b/packages/lab/src/Comments/CommentComposer.tsxindex a95aea13c8..858570f22b 100644--- a/packages/lab/src/Comments/CommentComposer.tsx+++ b/packages/lab/src/Comments/CommentComposer.tsx@@ -259,6 +259,13 @@ export function CommentComposerBase({[focusKey],);const [actionError, setActionError] = useState<ErrorBannerContent>();+ // Counts action failures so each one mounts its own Banner: a second failure+ // with the same words is a new occasion and is announced again (AST-086 FR6).+ const [actionErrorSerial, setActionErrorSerial] = useState(0);+ const reportActionError = (content: ErrorBannerContent) => {+ setActionError(content);+ setActionErrorSerial(serial => serial + 1);+ };const [isActionPending, setIsActionPending] = useState(false);const [isPickerOpen, setIsPickerOpen] = useState(false);@@ -303,7 +310,7 @@ export function CommentComposerBase({}} catch {if (isMountedRef.current) {- setActionError({+ reportActionError({title: t('@astryx.commentComposer.uploadFailed'),actionLabel: t('@astryx.comments.retry'),onAction: () => beginImageUpload(files),@@ -322,7 +329,7 @@ export function CommentComposerBase({}const images = files.filter(file => file.type.startsWith('image/'));if (images.length !== files.length) {- setActionError({+ reportActionError({title: t('@astryx.commentComposer.imagesOnly'),actionLabel: t('@astryx.commentComposer.chooseImages'),onAction: () => {@@ -378,6 +385,7 @@ export function CommentComposerBase({<VStack gap={1} width="100%" aria-busy={isBusy || undefined}>{errorBanner != null && (<ErrorBanner+ key={error != null ? 'error' : `action-${actionErrorSerial}`}content={errorBanner}// The Banner unmounts once the retry starts; keep focus in the input.onBeforeAction={() => inputRef.current?.focus()}diff --git a/packages/lab/src/Comments/CommentParts.tsx b/packages/lab/src/Comments/CommentParts.tsxindex bbeb08c5b9..70eecb77c8 100644--- a/packages/lab/src/Comments/CommentParts.tsx+++ b/packages/lab/src/Comments/CommentParts.tsx@@ -13,7 +13,13 @@* @position Internal building blocks of the Comments family*/-import {useState, type CSSProperties, type ReactNode, type Ref} from 'react';+import {+ useRef,+ useState,+ type CSSProperties,+ type ReactNode,+ type Ref,+} from 'react';import * as stylex from '@stylexjs/stylex';import {Avatar} from '@astryxdesign/core/Avatar';import {Badge} from '@astryxdesign/core/Badge';@@ -51,6 +57,7 @@ import {spacingVars,} from '@astryxdesign/core/theme/tokens.stylex';import {CommentIcon} from './icons';+import {useStatusAnnouncement} from './useStatusAnnouncement';import {eventAnchorId, type AnyComment} from './utils';import type {CommentAnchor,@@ -260,11 +267,18 @@ export type ErrorBannerContent = {actionLabel?: string;onAction?: () => void;isActionDisabled?: boolean;+ /** Its own retry is running: say nothing until the outcome (FR6). */+ isRetrying?: boolean;+ /** The failure was already announced elsewhere; this Banner stays silent. */+ isAnnounced?: boolean;};/**- * An inline failure as an error Banner. It sets role="alert" itself (Banner- * adds no live-region role from `status`), so mounting it announces it.+ * An inline failure as an error Banner. The Banner carries no live role: it+ * mounts already holding its text, which may not be announced. The failure is+ * announced once, assertively, through the shared channel instead, unless the+ * Banner sits inside a live container such as the chat log, which delivers it+ * (spec:AST-086 FR2, FR4, FR5).*/export function ErrorBanner({actionRef,@@ -279,10 +293,21 @@ export function ErrorBanner({[dataAttribute: `data-${string}`]: string | undefined;}) {const {actionLabel, description, isActionDisabled, onAction, title} = content;+ const t = useTranslator();+ const bannerRef = useRef<HTMLDivElement>(null);+ useStatusAnnouncement(+ bannerRef,+ content.isRetrying === true || content.isAnnounced === true+ ? null+ : description != null+ ? t('@astryx.comments.errorAnnouncement', {title, description})+ : title,+ 'assertive',+ );return (<Banner+ ref={bannerRef}status="error"- role="alert"container="card"title={title}description={description}@@ -466,6 +491,11 @@ export function CommentAnchorQuote({/** A comment its author is still writing: what it is doing, and where to watch. */export function CommentProgressStatus({progress}: {progress: CommentProgress}) {+ const labelRef = useRef<HTMLElement>(null);+ // The label carries no live role: it mounts already holding its text. It is+ // announced politely through the shared channel, unless the chat log around+ // it delivers it (spec:AST-086 FR2, FR4).+ useStatusAnnouncement(labelRef, progress.label, 'polite');return (<HStackgap={1}@@ -474,9 +504,9 @@ export function CommentProgressStatus({progress}: {progress: CommentProgress}) {width="100%"data-comment-progress="shimmer"><Text+ ref={labelRef}type="body"color="secondary"- role="status"xstyle={partStyles.progressLabel}>{progress.label}</Text>@@ -724,17 +754,23 @@ export function HistoryDialog({}content={<LayoutContent>+ {/* The shared channel is not exposed while a native modal is open+ (spec:AST-086), so a failure here is delivered by a persistent+ alert slot inside the dialog. The slot is mounted empty and the+ Banner is added to it (FR3). */}+ <div role="alert">+ {!history.isLoading && history.error != null && (+ <Banner+ status="error"+ title={t('@astryx.comments.historyFailed')}+ description={history.error}+ container="section"+ />+ )}+ </div>{history.isLoading ? (<Spinner size="lg" label={t('@astryx.comments.historyLoading')} />- ) : history.error != null ? (- <Banner- status="error"- role="alert"- title={t('@astryx.comments.historyFailed')}- description={history.error}- container="section"- />- ) : history.versions.length === 0 ? (+ ) : history.error != null ? null : history.versions.length === 0 ? (<EmptyStatetitle={t('@astryx.comments.historyEmptyTitle')}description={t('@astryx.comments.historyEmptyDescription')}diff --git a/packages/lab/src/Comments/CommentRow.tsx b/packages/lab/src/Comments/CommentRow.tsxindex 648e7b0c4d..387ed93ee0 100644--- a/packages/lab/src/Comments/CommentRow.tsx+++ b/packages/lab/src/Comments/CommentRow.tsx@@ -502,6 +502,8 @@ export function CommentRow({actionLabel: can.retry ? t('@astryx.comments.retry') : undefined,onAction: can.retry ? () => scope.retry(comment) : undefined,isActionDisabled: rowActionsBusy,+ isRetrying: isBusy,+ isAnnounced: actionFailure?.isAnnounced,}}// The Banner unmounts once the retry starts; keep focus on the comment.onBeforeAction={() => articleRef.current?.focus()}@@ -536,6 +538,7 @@ export function CommentRow({? t('@astryx.comments.retry'): undefined,onAction: actionFailure.retry,+ isAnnounced: actionFailure.isAnnounced,}}onBeforeAction={() => articleRef.current?.focus()}data-comment-action-error="banner"@@ -624,9 +627,7 @@ export function CommentRow({{hasHistory ? (<MetadataActionLinklabel={t('@astryx.comments.edited')}- accessibleLabel={t(- '@astryx.comments.viewHistory',- )}+ accessibleLabel={t('@astryx.comments.viewHistory')}actionRole="history"textType="body"onClick={() => scope.openHistory(comment)}@@ -705,9 +706,7 @@ export function CommentRow({triggers={composerTriggers ?? []}agentCommands={agentCommands}hasEmojiPicker={hasEmojiPicker}- onActionPendingChange={- scope.composerActionPendingChange- }+ onActionPendingChange={scope.composerActionPendingChange}onUploadImages={uploaderFor({kind: 'edit',commentId: comment.id,diff --git a/packages/lab/src/Comments/Comments.doc.mjs b/packages/lab/src/Comments/Comments.doc.mjsindex c16f65ba48..bdc8ca1b73 100644--- a/packages/lab/src/Comments/Comments.doc.mjs+++ b/packages/lab/src/Comments/Comments.doc.mjs@@ -166,7 +166,7 @@ export const docs = {category: 'Content',criterion: '4.1.3 Status Messages',description:- 'Failures show in alert Banners next to the thing that failed, each with Retry when the action can be repeated. A failed delete is announced once, assertively, as the confirmation dialog changes its text.',+ 'Failures show in error Banners next to the thing that failed, each with Retry when the action can be repeated. A Banner carries no live role of its own: its failure is announced once, assertively, through the shared announcement channel, unless it sits inside the chat log, which delivers it. The progress label of a comment still being written follows the same rule, politely. The edit-history dialog announces its failure through an alert region inside the dialog. A failed delete is announced once, assertively, as the confirmation dialog changes its text.',},],},diff --git a/packages/lab/src/Comments/Comments.test.tsx b/packages/lab/src/Comments/Comments.test.tsxindex f40ae76966..bc943d5c69 100644--- a/packages/lab/src/Comments/Comments.test.tsx+++ b/packages/lab/src/Comments/Comments.test.tsx@@ -24,6 +24,24 @@ import {// jsdom has no layout, so the measuring OverflowList is replaced by one that// collapses exactly the comment actions a test names.const overflowControl = vi.hoisted(() => ({collapsed: new Set<string>()}));+const announce = vi.hoisted(() => vi.fn());+// Records each announcement and still speaks it through the real channel, which+// other tests here read back.+vi.mock('@astryxdesign/core/hooks', async importOriginal => {+ const actual =+ await importOriginal<typeof import('@astryxdesign/core/hooks')>();+ return {+ ...actual,+ useAnnounce: () => {+ const speak = actual.useAnnounce();+ return (message: string, politeness?: 'polite' | 'assertive') => {+ announce(message, politeness);+ speak(message, politeness);+ };+ },+ };+});+vi.mock('@astryxdesign/core/OverflowList', async () => {const React = await import('react');type Item = {@@ -82,12 +100,6 @@ import type {CommentUser,} from './types';-// The page's shared live regions are not the component's error Banner.-const errorBanner = () =>- screen- .queryAllByRole('alert')- .find(element => !element.hasAttribute('data-astryx-live-region'));-const VIEWER: CommentUser = {id: 'avery', name: 'Avery Kim'};const OTHER: CommentUser = {id: 'maya', name: 'Maya Chen'};const AGENT: CommentUser = {@@ -133,6 +145,15 @@ const COMMENTS: readonly CommentThreadData[] = [},];+/** An inline failure Banner by its data attribute; it carries no live role. */+function bannerByData(attribute: string): HTMLElement {+ const banner = document.querySelector<HTMLElement>(`[${attribute}]`);+ if (banner == null) {+ throw new Error(`No Banner with ${attribute}`);+ }+ return banner;+}+/** A plain composer standing in for the contenteditable one. */function TestComposer(props: CommentComposerRenderProps) {return (@@ -267,6 +288,7 @@ afterAll(() => {});beforeEach(() => {+ announce.mockClear();overflowControl.collapsed = new Set();writeText.mockReset();writeText.mockResolvedValue(undefined);@@ -392,9 +414,10 @@ describe('Comments rendering', () => {);const article = articleByAuthor('Release Assistant');expect(within(article).getByText('Agent')).toBeTruthy();- expect(within(article).getByRole('status').textContent).toBe(- 'Checking the rollout…',- );+ // The label carries no live role; the chat log around it delivers it.+ const progressLabel = within(article).getByText('Checking the rollout…');+ expect(progressLabel).not.toHaveAttribute('role');+ expect(within(article).queryByRole('status')).toBeNull();expect(within(article).getByRole('link', {name: 'Open session'}),).toBeTruthy();@@ -906,12 +929,13 @@ describe('Comments threads', () => {}),);await flush();- const banner = errorBanner()!;+ const banner = bannerByData('data-comment-action-error');+ expect(banner).not.toHaveAttribute('role');expect(banner.textContent).toContain("Your reaction couldn't be saved.");await click(within(banner).getByRole('button', {name: 'Retry'}));await flush();expect(onReact).toHaveBeenCalledTimes(2);- expect(errorBanner()).toBeUndefined();+ expect(document.querySelector('[data-comment-action-error]')).toBeNull();});it('copies a link to the comment', async () => {@@ -1005,7 +1029,8 @@ describe('Comments threads', () => {/></Sized>,);- const banner = errorBanner()!;+ const banner = bannerByData('data-comment-delivery-error');+ expect(banner).not.toHaveAttribute('role');expect(banner.textContent).toContain("Couldn't post this comment.");await click(within(banner).getByRole('button', {name: 'Retry'}));await flush();@@ -1028,7 +1053,8 @@ describe('Comments threads', () => {);await click(screen.getByRole('button', {name: 'Load earlier comments'}));await flush();- const banner = errorBanner()!;+ const banner = bannerByData('data-comments-older-error');+ expect(banner).not.toHaveAttribute('role');expect(banner.textContent).toContain("Earlier comments couldn't load");await click(within(banner).getByRole('button', {name: 'Retry'}));await flush();@@ -1250,6 +1276,133 @@ describe('Comments keyboard and focus', () => {).toHaveFocus();});+ it('announces a failed delete once when no chat log wraps the row', async () => {+ const onDelete = vi.fn().mockRejectedValue(new Error('offline'));+ render(+ <Sized>+ <Comments+ layout="embedded"+ comments={COMMENTS}+ currentUser={OTHER}+ onDelete={onDelete}+ selectedThreadId="root-1"+ onSelectedThreadChange={vi.fn()}+ />+ </Sized>,+ );+ await click(+ within(articleByAuthor('Maya Chen')).getByRole('button', {+ name: "Actions for Maya Chen's comment",+ }),+ );+ await flush();+ await click(menuItem('Delete'));+ const dialog = document.querySelector('dialog[open]');+ if (!(dialog instanceof HTMLDialogElement)) {+ throw new Error('Delete confirmation not found');+ }+ announce.mockClear();+ await click(within(dialog).getByRole('button', {name: 'Delete'}));+ await flush();+ await nextFrame();++ // The dialog owns the announcement; the row's stored failure is silent.+ const deleteAnnouncements = announce.mock.calls.filter(([message]) =>+ /couldn't be deleted/.test(message),+ );+ expect(deleteAnnouncements).toEqual([+ ["This comment couldn't be deleted. Try again.", 'assertive'],+ ]);+ });++ it('announces a failed delete once when onDelete throws synchronously', async () => {+ const onDelete = vi.fn(() => {+ throw new Error('offline');+ });+ render(+ <Sized>+ <Comments+ layout="embedded"+ comments={COMMENTS}+ currentUser={OTHER}+ onDelete={onDelete}+ selectedThreadId="root-1"+ onSelectedThreadChange={vi.fn()}+ />+ </Sized>,+ );+ await click(+ within(articleByAuthor('Maya Chen')).getByRole('button', {+ name: "Actions for Maya Chen's comment",+ }),+ );+ await flush();+ await click(menuItem('Delete'));+ const dialog = document.querySelector('dialog[open]');+ if (!(dialog instanceof HTMLDialogElement)) {+ throw new Error('Delete confirmation not found');+ }+ announce.mockClear();+ await click(within(dialog).getByRole('button', {name: 'Delete'}));+ await flush();+ await nextFrame();++ // The dialog owns the announcement; the row's stored failure is silent.+ const deleteAnnouncements = announce.mock.calls.filter(([message]) =>+ /couldn't be deleted/.test(message),+ );+ expect(deleteAnnouncements).toEqual([+ ["This comment couldn't be deleted. Try again.", 'assertive'],+ ]);+ });++ it('announces a failed delete of a failed post once', async () => {+ const onDelete = vi.fn().mockRejectedValue(new Error('offline'));+ render(+ <Sized>+ <Comments+ layout="embedded"+ comments={[+ {+ id: 'failed',+ author: VIEWER,+ body: 'Kept text',+ createdAt: '2026-09-30T19:00:00Z',+ status: 'error',+ errorMessage: "Couldn't post this comment.",+ },+ ]}+ currentUser={VIEWER}+ onDelete={onDelete}+ />+ </Sized>,+ );+ await click(+ within(articleByAuthor('Avery Kim')).getByRole('button', {+ name: "Actions for Avery Kim's comment",+ }),+ );+ await flush();+ await click(menuItem('Delete'));+ const dialog = document.querySelector('dialog[open]');+ if (!(dialog instanceof HTMLDialogElement)) {+ throw new Error('Delete confirmation not found');+ }+ announce.mockClear();+ await click(within(dialog).getByRole('button', {name: 'Delete'}));+ await flush();+ await nextFrame();++ // The dialog owns the announcement; the failed post's Banner shows the+ // failure as its description without saying it a second time.+ const deleteAnnouncements = announce.mock.calls.filter(([message]) =>+ /couldn't be deleted/.test(message),+ );+ expect(deleteAnnouncements).toEqual([+ ["This comment couldn't be deleted. Try again.", 'assertive'],+ ]);+ });+it('moves focus to the thread after deleting a reply, and announces a failure once', async () => {const onDelete = vi.fn()@@ -1330,3 +1483,176 @@ describe('Comments keyboard and focus', () => {).toHaveFocus();});});++describe('Comments status announcements (spec:AST-086)', () => {+ const FAILED_COMMENT = {+ id: 'failed',+ author: VIEWER,+ body: 'Kept text',+ createdAt: '2026-09-30T19:00:00Z',+ status: 'error' as const,+ errorMessage: "Couldn't post this comment.",+ };++ it('announces a load failure once, assertively, and the Banner has no live role', async () => {+ const {rerender} = render(+ <Sized>+ <Comments comments={[]} loadError="Server unreachable" />+ </Sized>,+ );+ await flush();+ // Only the shared channel's own region is an alert; the Banner is not.+ expect(+ document.querySelectorAll(+ '[role="alert"]:not([data-astryx-live-region])',+ ),+ ).toHaveLength(0);+ expect(screen.getByText('Server unreachable')).toBeTruthy();+ expect(announce.mock.calls).toEqual([+ ["Comments couldn't load Server unreachable", 'assertive'],+ ]);++ rerender(+ <Sized>+ <Comments comments={[]} loadError="Server unreachable" />+ </Sized>,+ );+ await flush();+ expect(announce).toHaveBeenCalledTimes(1);+ });++ it('leaves an in-timeline failure to the chat log', async () => {+ render(+ <Sized>+ <Comments comments={[FAILED_COMMENT]} currentUser={VIEWER} />+ </Sized>,+ );+ const banner = bannerByData('data-comment-delivery-error');+ expect(banner.closest('[role="log"]')).not.toBeNull();+ expect(announce).not.toHaveBeenCalled();+ });++ it('announces a failure itself when no chat log wraps it', async () => {+ render(+ <Sized>+ <Comments+ layout="embedded"+ comments={[FAILED_COMMENT]}+ currentUser={VIEWER}+ />+ </Sized>,+ );+ const banner = bannerByData('data-comment-delivery-error');+ expect(banner.closest('[role="log"]')).toBeNull();+ expect(announce.mock.calls).toEqual([+ [expect.stringContaining("Couldn't post this comment."), 'assertive'],+ ]);+ });++ it('does not repeat a failure when a retry starts, and announces each failed retry', async () => {+ const onRetryComment = vi.fn().mockRejectedValue(new Error('offline'));+ render(+ <Sized>+ <Comments+ layout="embedded"+ comments={[FAILED_COMMENT]}+ currentUser={VIEWER}+ onRetryComment={onRetryComment}+ />+ </Sized>,+ );+ await flush();+ const first = ["Couldn't post this comment.", 'assertive'];+ const failed = [+ "Couldn't post this comment. Retrying didn't work.",+ 'assertive',+ ];+ expect(announce.mock.calls).toEqual([first]);++ const banner = () => bannerByData('data-comment-delivery-error');+ const retry = () => within(banner()).getByRole('button', {name: 'Retry'});+ await click(retry());+ await flush();+ expect(announce.mock.calls).toEqual([first, failed]);++ // Starting a retry says nothing; its failure, a new occasion, speaks.+ await click(retry());+ await flush();+ expect(announce.mock.calls).toEqual([first, failed, failed]);+ });++ it('does not repeat a failure when an unrelated post settles', async () => {+ let finishPost!: () => void;+ const onSubmit = vi.fn(() => new Promise<void>(r => (finishPost = r)));+ render(+ <Sized>+ <Comments+ layout="embedded"+ comments={[FAILED_COMMENT]}+ currentUser={VIEWER}+ onSubmit={onSubmit}+ renderComposer={renderComposer}+ />+ </Sized>,+ );+ const composer = screen.getByRole('region', {name: 'New comment'});+ await click(within(composer).getByText('Set draft'));+ await click(within(composer).getByText('Submit composer'));+ await act(async () => finishPost());+ await flush();+ expect(announce.mock.calls).toEqual([+ ["Couldn't post this comment.", 'assertive'],+ ]);+ });++ it('announces a comment still being written, politely, outside a chat log', async () => {+ render(+ <Sized>+ <Comments+ layout="embedded"+ comments={[+ {+ id: 'agent',+ author: AGENT,+ body: '',+ createdAt: '2026-09-30T19:00:00Z',+ progress: {label: 'Checking the rollout…'},+ },+ ]}+ currentUser={VIEWER}+ />+ </Sized>,+ );+ await flush();+ expect(announce.mock.calls).toEqual([['Checking the rollout…', 'polite']]);+ });++ it('delivers a history failure through an alert slot that exists before the Banner', async () => {+ let rejectVersions!: (error: Error) => void;+ const loadVersions = vi.fn(+ () => new Promise<never>((_, reject) => (rejectVersions = reject)),+ );+ render(+ <Sized>+ <Comments comments={COMMENTS} loadVersions={loadVersions} />+ </Sized>,+ );+ await click(screen.getByRole('button', {name: 'View edit history'}));+ await flush();+ // While the history loads, the slot is already mounted, and empty.+ const slot = document.querySelector<HTMLElement>('dialog [role="alert"]');+ if (slot == null) {+ throw new Error('History alert slot not found while loading');+ }+ expect(slot.textContent).toBe('');++ await act(async () => {+ rejectVersions(new Error('nope'));+ });+ await flush();+ // The failure lands in that slot; the Banner has no live role of its own.+ expect(document.querySelector('dialog [role="alert"]')).toBe(slot);+ expect(slot.textContent).toContain("Edit history couldn't load");+ expect(slot.querySelector('[role]')).toBeNull();+ });+});diff --git a/packages/lab/src/Comments/Comments.tsx b/packages/lab/src/Comments/Comments.tsxindex a7af237d43..cf3856d011 100644--- a/packages/lab/src/Comments/Comments.tsx+++ b/packages/lab/src/Comments/Comments.tsx@@ -44,6 +44,7 @@ import {ErrorBanner,} from './CommentParts';import {CommentRow, THREAD_DIVIDERS, type ThreadDivider} from './CommentRow';+import {useStatusAnnouncement} from './useStatusAnnouncement';import {CommentsContextProvider,useCommentsController,@@ -249,6 +250,20 @@ export function Comments({const loadingOlderRef = useRef(false);const loadOlderButtonRef = useRef<HTMLButtonElement>(null);const olderRetryRef = useRef<HTMLButtonElement>(null);+ // The load-failure Banner carries no live role: it mounts already holding+ // its text. It is announced once, assertively, through the shared channel+ // (spec:AST-086 FR2, FR5).+ const loadErrorRef = useRef<HTMLDivElement>(null);+ useStatusAnnouncement(+ loadErrorRef,+ loadError != null+ ? t('@astryx.comments.errorAnnouncement', {+ title: t('@astryx.comments.loadFailed'),+ description: loadError,+ })+ : null,+ 'assertive',+ );const rootRef = useRef<HTMLElement | null>(null);const setRootRef = useCallback((element: HTMLElement | null) => {@@ -571,8 +586,8 @@ export function Comments({)}>{loadError != null && (<Banner+ ref={loadErrorRef}status="error"- role="alert"title={t('@astryx.comments.loadFailed')}description={loadError}container="section"diff --git a/packages/lab/src/Comments/CommentsContext.tsx b/packages/lab/src/Comments/CommentsContext.tsxindex 24acb8a081..5b7f8d6aec 100644--- a/packages/lab/src/Comments/CommentsContext.tsx+++ b/packages/lab/src/Comments/CommentsContext.tsx@@ -78,7 +78,12 @@ function editComposerContext(comment: AnyComment): CommentComposerContext {}/** A failed comment action and how to run it again. */-export type ActionFailure = {message: string; retry?: () => void};+export type ActionFailure = {+ message: string;+ retry?: () => void;+ /** Already spoken by whoever raised it, so the row's Banner stays silent. */+ isAnnounced?: boolean;+};type FocusTarget = 'reply' | 'actions' | 'history' | 'article' | 'thread';@@ -348,6 +353,9 @@ export function useCommentsController({action: () => MaybePromise,failureMessage: string,retry?: () => void,+ /** True when another owner announces this failure, so the row's banner+ * stays silent from its first render. */+ isAnnounced?: boolean,): Promise<boolean> => {setPendingActionIds(previous => new Set(previous).add(commentId));clearActionError(commentId);@@ -362,6 +370,7 @@ export function useCommentsController({retry:retry ??(() => void runCommentAction(commentId, action, failureMessage)),+ isAnnounced,},}));return false;@@ -480,6 +489,9 @@ export function useCommentsController({t('@astryx.comments.deleteFailed'),// Retrying a delete asks for confirmation again.() => setDeleteTarget(target),+ // The dialog announces a failed delete (AST-086 FR1, FR6), so the stored+ // failure the row shows is marked before it first renders.+ true,);if (succeeded) {commitAndFocus(diff --git a/packages/lab/src/Comments/useStatusAnnouncement.ts b/packages/lab/src/Comments/useStatusAnnouncement.tsnew file mode 100644index 0000000000..eaa436b45c--- /dev/null+++ b/packages/lab/src/Comments/useStatusAnnouncement.ts@@ -0,0 +1,57 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useStatusAnnouncement.ts+ * @input Uses React, useAnnounce from core hooks+ * @output Exports useStatusAnnouncement hook+ * @position Internal to Comments; announces a transient status element+ * (error banner, progress label) once instead of mounting it as a live region+ *+ * A live region that mounts already holding its text may not be announced, so+ * the visible element carries no live role (spec:AST-086 FR2). This hook says+ * the words once through the shared channel instead, unless a live container+ * such as a chat log already delivers content added inside it (FR4).+ */++import {useEffect, useRef, type RefObject} from 'react';+import {useAnnounce} from '@astryxdesign/core/hooks';+import type {AnnouncePoliteness} from '@astryxdesign/core/hooks';++const LIVE_CONTAINER_SELECTOR =+ '[role="log"], [role="status"], [role="alert"], [aria-live="polite"], [aria-live="assertive"]';++/**+ * Announce `message` once per occasion: when the element first shows it, and+ * again whenever the message changes. A rerender or a StrictMode effect replay+ * does not repeat it, and a message that goes away and comes back is a new+ * occasion (spec:AST-086 FR6).+ *+ * @param ref The visible element, used to find an enclosing live container.+ * @param message The words to say, or `null` for nothing.+ * @param politeness Errors are `'assertive'`, progress is `'polite'` (FR5).+ */+export function useStatusAnnouncement(+ ref: RefObject<HTMLElement | null>,+ message: string | null,+ politeness: AnnouncePoliteness,+): void {+ const announce = useAnnounce();+ const announcedRef = useRef<string | null>(null);+ useEffect(() => {+ if (message == null || message === '') {+ announcedRef.current = null;+ return;+ }+ if (announcedRef.current === message) {+ return;+ }+ announcedRef.current = message;+ const isInsideLiveContainer =+ ref.current?.parentElement?.closest(LIVE_CONTAINER_SELECTOR) != null;+ if (!isInsideLiveContainer) {+ announce(message, politeness);+ }+ }, [announce, message, politeness, ref]);+}