Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🎯 a11y: Hand Focus Back When an Agent Detail Refresh Removes the Focused Control (#16945)

Marco Beretta6d5b49a8cde9
diff --git a/client/src/components/Agents/AgentDetailContent.tsx b/client/src/components/Agents/AgentDetailContent.tsx
index 50c0870799..91c2470b1b 100644
--- a/client/src/components/Agents/AgentDetailContent.tsx
+++ b/client/src/components/Agents/AgentDetailContent.tsx
@@ -74,20 +74,24 @@ const AgentDetailContent: React.FC<AgentDetailContentProps> = ({
const reducedMotion = useReducedMotion();
const titleRef = useRef<HTMLHeadingElement>(null);
const unavailableRef = useRef<HTMLParagraphElement>(null);
- const focusedActionRef = useRef<HTMLElement | null>(null);
- const previousActionsUnavailable = useRef(actionsUnavailable);
+ const lastFocusedRef = useRef<HTMLElement | null>(null);
const id = useId();
const { isFavoriteAgent, toggleFavoriteAgent, isUpdating } = useFavorites();
const isFavorite = isFavoriteAgent(agent.id);
const favoriteLabel = localize(isFavorite ? 'com_ui_unpin' : 'com_ui_pin');
const FavoriteIcon = isFavorite ? PinOff : Pin;
+ /** Keyed by text and occurrence, so a refresh that drops an earlier starter keeps the
+ * later ones mounted, and focused, instead of re-keying them by position. */
const conversationStarters = useMemo(() => {
- const starters: string[] = [];
+ const starters: Array<{ text: string; key: string }> = [];
+ const occurrences = new Map<string, number>();
for (const value of agent.conversation_starters ?? []) {
const starter = value.trim();
if (starter) {
- starters.push(starter);
+ const occurrence = occurrences.get(starter) ?? 0;
+ occurrences.set(starter, occurrence + 1);
+ starters.push({ text: starter, key: `${starter}-${occurrence}` });
}
if (starters.length === Constants.MAX_CONVO_STARTERS) {
break;
@@ -173,22 +177,30 @@ const AgentDetailContent: React.FC<AgentDetailContentProps> = ({
),
...shared,
};
+ /**
+ * A revalidation can replace the agent with a record that drops the control the reader
+ * is on: a conversation starter the owner removed, or every action once access is
+ * revoked. Removing a focused element does not fire `blur` reliably across browsers,
+ * so the last focused control is remembered on focus alone and checked for
+ * `isConnected` after each commit. When it is gone and nothing else took focus, focus
+ * moves to the unavailable notice when it is shown, and to the dialog title otherwise.
+ */
useLayoutEffect(() => {
- const wasUnavailable = previousActionsUnavailable.current;
- previousActionsUnavailable.current = actionsUnavailable;
- if (!actionsUnavailable || wasUnavailable || focusedActionRef.current == null) {
+ const focused = lastFocusedRef.current;
+ if (focused == null || focused.isConnected) {
return;
}
- focusedActionRef.current = null;
- unavailableRef.current?.focus();
- }, [actionsUnavailable]);
- const handleActionFocusCapture = useCallback((event: React.FocusEvent<HTMLElement>) => {
- focusedActionRef.current = event.target;
- }, []);
- const handleActionBlurCapture = useCallback((event: React.FocusEvent<HTMLElement>) => {
- const relatedTarget = event.relatedTarget;
- if (!(relatedTarget instanceof Node) || !event.currentTarget.contains(relatedTarget)) {
- focusedActionRef.current = null;
+ lastFocusedRef.current = null;
+ const active = document.activeElement;
+ if (active != null && active !== document.body && active.isConnected) {
+ return;
+ }
+ (unavailableRef.current ?? titleRef.current)?.focus();
+ });
+ /** Focus inside a portaled child (a confirm dialog, a menu) is that child's to restore. */
+ const handleFocusCapture = useCallback((event: React.FocusEvent<HTMLElement>) => {
+ if (event.currentTarget.contains(event.target)) {
+ lastFocusedRef.current = event.target;
}
}, []);
@@ -205,6 +217,7 @@ const AgentDetailContent: React.FC<AgentDetailContentProps> = ({
dialog's mount so it can fade out across the whole contraction. */
overlayClassName={morphing ? 'bg-transparent' : undefined}
showCloseButton={false}
+ onFocusCapture={handleFocusCapture}
onOpenAutoFocus={(event) => {
event.preventDefault();
titleRef.current?.focus();
@@ -345,13 +358,7 @@ const AgentDetailContent: React.FC<AgentDetailContentProps> = ({
)}
{!actionsUnavailable && conversationStarters.length > 0 && (
- <motion.section
- {...detail}
- className="mt-8"
- aria-labelledby={`${id}-starters`}
- onFocusCapture={handleActionFocusCapture}
- onBlurCapture={handleActionBlurCapture}
- >
+ <motion.section {...detail} className="mt-8" aria-labelledby={`${id}-starters`}>
<h3 id={`${id}-starters`} className="text-text-primary text-sm font-semibold">
{localize('com_agents_starters_heading')}
</h3>
@@ -359,19 +366,19 @@ const AgentDetailContent: React.FC<AgentDetailContentProps> = ({
{localize('com_agents_starters_hint')}
</p>
<div className="mt-3 grid gap-2 sm:grid-cols-2">
- {conversationStarters.map((starter, index) => (
+ {conversationStarters.map((starter) => (
<Button
- key={`${starter}-${index}`}
+ key={starter.key}
variant="outline"
className="h-auto min-h-14 items-start justify-between gap-3 py-3 text-left whitespace-normal rtl:text-right"
aria-disabled={actionsDisabled || undefined}
onClick={() => {
if (!actionsDisabled) {
- handleStartChat(starter);
+ handleStartChat(starter.text);
}
}}
>
- <span className="min-w-0 break-words">{starter}</span>
+ <span className="min-w-0 break-words">{starter.text}</span>
<ArrowUpRight className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
</Button>
))}
@@ -398,8 +405,6 @@ const AgentDetailContent: React.FC<AgentDetailContentProps> = ({
<motion.div
{...detail}
className="grid gap-2 sm:ms-auto sm:flex sm:items-center sm:gap-2"
- onFocusCapture={handleActionFocusCapture}
- onBlurCapture={handleActionBlurCapture}
>
<div className="flex items-center gap-2">
<Button
diff --git a/client/src/components/Agents/tests/AgentDetailContent.spec.tsx b/client/src/components/Agents/tests/AgentDetailContent.spec.tsx
index 42d886fabb..f59262b25b 100644
--- a/client/src/components/Agents/tests/AgentDetailContent.spec.tsx
+++ b/client/src/components/Agents/tests/AgentDetailContent.spec.tsx
@@ -471,6 +471,35 @@ describe('AgentDetailContent', () => {
expect(document.body).not.toHaveFocus();
});
+ it('moves focus to the title when a refreshed agent drops the focused starter', () => {
+ const agent = {
+ ...baseAgent,
+ conversation_starters: ['Ask about the latest changes', 'Keep this one'],
+ };
+ const rendered = renderDetail(agent);
+ screen.getByRole('button', { name: /Ask about the latest changes/ }).focus();
+
+ rendered.setAgent({ ...agent, conversation_starters: ['Keep this one'] });
+
+ expect(screen.queryByRole('button', { name: /Ask about the latest changes/ })).toBeNull();
+ expect(screen.getByRole('heading', { name: 'Agent One' })).toHaveFocus();
+ expect(document.body).not.toHaveFocus();
+ });
+
+ it('keeps focus on a starter that survives the refresh', () => {
+ const agent = {
+ ...baseAgent,
+ conversation_starters: ['Ask about the latest changes', 'Keep this one'],
+ };
+ const rendered = renderDetail(agent);
+ const kept = screen.getByRole('button', { name: /Keep this one/ });
+ kept.focus();
+
+ rendered.setAgent({ ...agent, conversation_starters: ['Keep this one'] });
+
+ expect(screen.getByRole('button', { name: /Keep this one/ })).toHaveFocus();
+ });
+
it('leaves focus elsewhere when revalidation removes unavailable actions', () => {
const rendered = renderDetail();
const title = screen.getByRole('heading', { name: 'Agent One' });
diff --git a/e2e/specs/mock/scenarios/agent-detail-focus-handoff.spec.ts b/e2e/specs/mock/scenarios/agent-detail-focus-handoff.spec.ts
new file mode 100644
index 0000000000..ed9e8a25d0
--- /dev/null
+++ b/e2e/specs/mock/scenarios/agent-detail-focus-handoff.spec.ts
@@ -0,0 +1,108 @@
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+import { cleanupAgent, uniqueAgentName, waitForPersistedAgent } from '../agents.helpers';
+import { getAccessToken, MOCK_ENDPOINTS, NEW_CHAT_PATH, requestJson } from '../helpers';
+
+/**
+ * The open agent dialog revalidates its agent when the window regains focus. When the fresh
+ * record drops the conversation starter the reader is on, the dialog hands focus to its title
+ * instead of letting it fall to the page behind the modal.
+ */
+const STARTERS = ['Summarize the latest release', 'Draft a changelog entry'];
+
+async function createAgent(page: Page, token: string) {
+ const name = uniqueAgentName('E2E Focus Handoff');
+ const description = 'An agent whose conversation starters change while its dialog is open.';
+ const agent = await requestJson<{ id: string }>(page, {
+ path: '/api/agents',
+ token,
+ method: 'POST',
+ body: {
+ name,
+ description,
+ instructions: 'Use the mock model and answer deterministically for this scenario.',
+ provider: MOCK_ENDPOINTS[0].label,
+ model: MOCK_ENDPOINTS[0].model,
+ model_parameters: {},
+ tools: [],
+ conversation_starters: STARTERS,
+ category: 'general',
+ },
+ });
+ await waitForPersistedAgent(page, name, description);
+ return { id: agent.id, name };
+}
+
+/** What a reader switching back to the window does: the query client revalidates on focus. */
+async function returnToWindow(page: Page) {
+ await page.evaluate(() => {
+ document.dispatchEvent(new Event('visibilitychange'));
+ window.dispatchEvent(new Event('focus'));
+ });
+}
+
+test.describe('agent detail focus handoff', () => {
+ test('a refresh that removes the focused starter hands focus to the dialog title @scenario:agent-detail-refresh-hands-focus-to-title', async ({
+ page,
+ }) => {
+ let agentId: string | undefined;
+ try {
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ const token = await getAccessToken(page);
+ const agent = await createAgent(page, token);
+ agentId = agent.id;
+
+ await page.goto(`/agents/all?q=${encodeURIComponent(agent.name)}`, { timeout: 10000 });
+ const trigger = page.getByRole('button', { name: agent.name, exact: true });
+ await expect(trigger).toBeVisible({ timeout: 30000 });
+ await trigger.focus();
+ await trigger.press('Enter');
+
+ const dialog = page.getByRole('dialog');
+ const title = dialog.getByRole('heading', { name: agent.name, exact: true });
+ await expect(title).toBeFocused();
+
+ const starter = dialog.getByRole('button', { name: STARTERS[0] });
+ await expect(starter).toBeVisible();
+ for (let step = 0; step < 20; step++) {
+ if (await starter.evaluate((node) => node === document.activeElement)) {
+ break;
+ }
+ await page.keyboard.press('Tab');
+ }
+ await expect(starter).toBeFocused();
+
+ const refreshed = page.waitForResponse(async (response) => {
+ if (
+ response.request().method() !== 'GET' ||
+ !response.url().includes(`/api/agents/${agent.id}`) ||
+ !response.ok()
+ ) {
+ return false;
+ }
+ const body = (await response.json()) as { conversation_starters?: string[] };
+ return (body.conversation_starters ?? []).length === 0;
+ });
+ await requestJson(page, {
+ path: `/api/agents/${encodeURIComponent(agent.id)}`,
+ token,
+ method: 'PATCH',
+ body: { conversation_starters: [] },
+ });
+ await returnToWindow(page);
+ await refreshed;
+
+ await expect(dialog.getByRole('button', { name: STARTERS[0] })).toHaveCount(0);
+ await expect(dialog).toBeVisible();
+ await expect(title).toBeFocused();
+ await expect(title).toBeVisible();
+ expect(await page.evaluate(() => document.activeElement === document.body)).toBe(false);
+
+ /* Keyboard navigation continues from the title into the dialog's remaining controls. */
+ await page.keyboard.press('Tab');
+ expect(await dialog.evaluate((node) => node.contains(document.activeElement))).toBe(true);
+ } finally {
+ await cleanupAgent(page, agentId);
+ }
+ });
+});