From 147aa29807523686db05aaaffac12a75d1fc5946 Mon Sep 17 00:00:00 2001 From: "lia-by-librechat[bot]" <328778573+lia-by-librechat[bot]@users.noreply.github.com> Date: Sat, 17 Oct 2026 00:58:22 -0400 Subject: [PATCH] =?UTF-8?q?=F0=9F=9B=8B=EF=B8=8F=20feat:=20Open=20Subagent?= =?UTF-8?q?s=20Directly=20from=20Background=20Tasks=20(#17020)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: open durable subagents from background tasks * fix: isolate subagent focus and discovery from navigation * fix: retain subagent task identity through navigation * test: verify task opening without changing the rendered popup * fix: preserve retained task activity across navigation * fix: import the core progress key after dev integration * fix: refresh subagent panel return focus on explicit open * fix: prefer the subagent panel opener when restoring focus * test: retain the actual reply stamp across permission grant * test: scope permission-grant notifications to the target reply * test: observe the pending reply before granting notification permission --------- Co-authored-by: Lia --- .../Chat/BackgroundTasks/Button.tsx | 47 ++-- .../components/Chat/BackgroundTasks/Card.tsx | 15 +- .../BackgroundTasks/__tests__/Button.test.tsx | 155 +++++++---- .../BackgroundTasks/__tests__/rows.test.ts | 1 + .../components/Chat/BackgroundTasks/rows.ts | 1 + .../Messages/Content/Parts/SubagentCall.tsx | 19 +- .../Parts/__tests__/SubagentCall.test.tsx | 35 ++- .../src/components/Chat/Presentation.test.tsx | 90 +++++- client/src/components/Chat/Presentation.tsx | 22 +- .../EventSubagentActivityGroup.test.tsx | 51 ++++ .../Subagents/EventSubagentActivityGroup.tsx | 1 + .../ParentSubagentsProvider.test.tsx | 45 +++ .../Subagents/ParentSubagentsProvider.tsx | 8 +- .../Subagents/SubagentThreadPanel.test.tsx | 257 ++++++++++++++++++ .../Chat/Subagents/SubagentThreadPanel.tsx | 66 ++++- .../components/Chat/Subagents/state.spec.ts | 26 ++ client/src/components/Chat/Subagents/state.ts | 11 +- .../src/components/Chat/Subagents/surface.tsx | 6 +- .../useEventHandlers.cancel.spec.tsx | 48 +++- .../SSE/__tests__/useStepHandler.spec.ts | 98 +++++++ client/src/hooks/SSE/useEventHandlers.ts | 2 +- client/src/hooks/SSE/useStepHandler.ts | 51 ++-- client/src/locales/en/translation.json | 3 + .../mock/scenarios/unseen-replies.spec.ts | 35 ++- 24 files changed, 923 insertions(+), 170 deletions(-) diff --git a/client/src/components/Chat/BackgroundTasks/Button.tsx b/client/src/components/Chat/BackgroundTasks/Button.tsx index ace336d4ee..9739557b90 100644 --- a/client/src/components/Chat/BackgroundTasks/Button.tsx +++ b/client/src/components/Chat/BackgroundTasks/Button.tsx @@ -3,6 +3,9 @@ import * as Ariakit from '@ariakit/react'; import { Button, IconButton, TooltipAnchor } from '@librechat/client'; import { ListTodo, Maximize2, Minimize2, Square, X } from 'lucide-react'; import type { TaskRow } from './rows'; +import { useParentSubagents } from '~/components/Chat/Subagents/ParentSubagentsProvider'; +import { durableSubagentSelection } from '~/components/Chat/Subagents/eventSelection'; +import { useOpenSubagentPanel } from '~/components/Chat/Subagents/surface'; import { RECENT_SUBAGENT_WINDOW_MS } from './rows'; import useBackgroundTasks from './useTasks'; import { useLocalize } from '~/hooks'; @@ -24,6 +27,8 @@ function BackgroundTasksButton({ isSubmitting: boolean; }) { const localize = useLocalize(); + const openSubagentPanel = useOpenSubagentPanel(); + const parent = useParentSubagents(); const popover = Ariakit.usePopoverStore({ placement: 'bottom-end' }); const open = Ariakit.useStoreState(popover, 'open'); const disclosureRef = useRef(null); @@ -85,35 +90,23 @@ function BackgroundTasksButton({ stopAllLabel = localize('com_ui_background_tasks_stop_available'); } const jumpToTool = (row: TaskRow): boolean => { - if (row.eventOrigin && row.threadId != null) { - const events = Array.from( - document.querySelectorAll( - '[data-event-subagent-conversation] [data-subagent-thread]', - ), - ).filter( - (element) => - element.dataset.subagentThread === row.threadId && - element.dataset.subagentParentMessage === row.messageId && - element.closest('[data-event-subagent-conversation]')?.dataset - .eventSubagentConversation === conversationId, - ); - if (events.length !== 1) return false; - const target = events[0]; - if (target.matches(':disabled')) return false; - const group = target.closest('[data-event-subagent-conversation]'); - group?.querySelector('button[aria-expanded="false"]')?.click(); + if (row.kind === 'subagent') { + if ( + openSubagentPanel == null || + parent.conversationId !== conversationId || + row.threadId == null || + row.taskId == null + ) { + return false; + } + const child = parent.byThreadId.get(row.threadId); + if (child == null) return false; + const selection = durableSubagentSelection(conversationId, child, row.taskId); + if (selection == null) return false; finalFocusRef.current = null; + disclosureRef.current?.focus({ preventScroll: true }); popover.hide(); - window.requestAnimationFrame(() => { - if (!target.isConnected || popover.getState().open) return; - target.focus({ preventScroll: true }); - target.scrollIntoView?.({ - block: 'center', - behavior: window.matchMedia?.('(prefers-reduced-motion: reduce)').matches - ? 'instant' - : 'smooth', - }); - }); + openSubagentPanel({ ...selection, isSubmitting: false }); return true; } if (row.messageId == null) return false; diff --git a/client/src/components/Chat/BackgroundTasks/Card.tsx b/client/src/components/Chat/BackgroundTasks/Card.tsx index 4987da9641..6653924bff 100644 --- a/client/src/components/Chat/BackgroundTasks/Card.tsx +++ b/client/src/components/Chat/BackgroundTasks/Card.tsx @@ -66,6 +66,11 @@ function TaskCard({ : undefined; const stopLabel = localize('com_ui_background_tasks_stop'); const expandable = row.detail != null; + const openLabel = localize( + row.kind === 'subagent' + ? 'com_ui_background_tasks_open_subagent' + : 'com_ui_background_tasks_go_to_tool', + ); return (
  • @@ -125,14 +130,14 @@ function TaskCard({

    setJumpUnavailable(!onJump(row))} >
  • diff --git a/client/src/components/Chat/BackgroundTasks/__tests__/Button.test.tsx b/client/src/components/Chat/BackgroundTasks/__tests__/Button.test.tsx index 6a3e8afacc..260587d593 100644 --- a/client/src/components/Chat/BackgroundTasks/__tests__/Button.test.tsx +++ b/client/src/components/Chat/BackgroundTasks/__tests__/Button.test.tsx @@ -5,7 +5,10 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { act, render, screen, waitFor, within } from '@testing-library/react'; import { ContentTypes, QueryKeys, dataService } from 'librechat-data-provider'; import type { ParentSubagentSummary, BackgroundTaskIndex, TMessage } from 'librechat-data-provider'; +import type { JotaiStore } from 'test/harness'; import { ParentSubagentsProvider } from '~/components/Chat/Subagents/ParentSubagentsProvider'; +import { activeSubagentPanel } from '~/components/Chat/Subagents/state'; +import { ChatSurfaceHarness } from 'test/harness'; import BackgroundTasksButton from '../Button'; jest.mock('librechat-data-provider', () => { @@ -89,16 +92,23 @@ const renderButton = (children: ParentSubagentSummary[] = [], initialMessages = children, childrenTruncated: false, }); + let atoms!: JotaiStore; const rendered = render( - - - - - - - , + { + atoms = store; + }} + > + + + + + + + + , ); - return { ...rendered, queryClient }; + return { ...rendered, queryClient, getSelection: () => atoms.get(activeSubagentPanel) }; }; afterEach(() => jest.restoreAllMocks()); @@ -420,13 +430,16 @@ describe('BackgroundTasksButton', () => { expect(screen.getByText('npx jest tasks.spec.ts').closest('[inert]')).not.toBeNull(); }); - it('provides a tool destination action on every task', async () => { + it('provides the appropriate open action for each task kind', async () => { jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index()); renderButton([runningChild]); await userEvent.click(await screen.findByTestId('header-background-tasks-button')); expect( await screen.findAllByRole('button', { name: /^com_ui_background_tasks_go_to_tool:/ }), - ).toHaveLength(3); + ).toHaveLength(2); + expect( + screen.getAllByRole('button', { name: /^com_ui_background_tasks_open_subagent:/ }), + ).toHaveLength(1); }); it('renders tool navigation as an icon without visible button text', async () => { @@ -470,32 +483,69 @@ describe('BackgroundTasksButton', () => { expect(row.querySelector('[inert]')).not.toBeNull(); }); - it('prioritizes the exact subagent thread over a reused call id', async () => { - jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index({ tasks: [] })); - renderButton([runningChild]); - const message = document.createElement('section'); - message.id = 'parent-message'; - const targets = ['thread-1', 'other-thread'].map((thread) => { - const wrapper = document.createElement('div'); - wrapper.dataset.taskToolCall = 'call-subagent'; - const target = document.createElement('button'); - target.dataset.subagentThread = thread; - target.dataset.subagentToolCall = 'call-subagent'; - target.scrollIntoView = jest.fn(); - wrapper.append(target); - message.append(wrapper); - return target; - }); - document.body.append(message); - try { - await userEvent.click(await screen.findByTestId('header-background-tasks-button')); + it.each(['running', 'completed', 'failed', 'cancelled'] as const)( + 'opens a %s subagent without needing its originating message', + async (status) => { + jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index({ tasks: [] })); + const before = window.location.href; + const { getSelection } = renderButton([ + { + ...runningChild, + status, + tasks: [{ taskId: 'sub-task-1', status, createdAt: startedAt }], + updatedAt: new Date().toISOString(), + }, + ]); + const trigger = await screen.findByTestId('header-background-tasks-button'); + await userEvent.click(trigger); await userEvent.click( - await screen.findByRole('button', { name: /^com_ui_background_tasks_go_to_tool:/ }), + await screen.findByRole('button', { name: /^com_ui_background_tasks_open_subagent:/ }), ); - expect(targets[0].scrollIntoView).toHaveBeenCalled(); - } finally { - message.remove(); - } + expect(getSelection()).toMatchObject({ + parentConversationId: conversationId, + parentMessageId: 'parent-message', + toolCallId: 'call-subagent', + isSubmitting: false, + durable: { threadId: 'thread-1', taskId: 'sub-task-1' }, + }); + expect(window.location.href).toBe(before); + expect(document.getElementById('parent-message')).toBeNull(); + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()); + expect(trigger).toHaveFocus(); + }, + ); + + it('opens the exact thread when provider call ids are reused', async () => { + jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index({ tasks: [] })); + const { getSelection } = renderButton([ + runningChild, + { ...runningChild, threadId: 'other-thread', title: 'Other researcher' }, + ]); + await userEvent.click(await screen.findByTestId('header-background-tasks-button')); + await userEvent.click( + await screen.findByRole('button', { + name: 'com_ui_background_tasks_open_subagent: Other researcher', + }), + ); + expect(getSelection()).toMatchObject({ + durable: { threadId: 'other-thread', taskId: 'sub-task-1' }, + }); + }); + + it('explains an unaddressable subagent without falling back to a tool jump', async () => { + jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index({ tasks: [] })); + const { getSelection } = renderButton([ + { ...runningChild, latestTaskId: undefined, tasks: [] }, + ]); + await userEvent.click(await screen.findByTestId('header-background-tasks-button')); + await userEvent.click( + await screen.findByRole('button', { name: /^com_ui_background_tasks_open_subagent:/ }), + ); + expect(getSelection()).toBeNull(); + expect(screen.getByRole('status')).toHaveTextContent( + 'com_ui_background_tasks_subagent_unavailable', + ); + expect(screen.getByRole('dialog')).toBeInTheDocument(); }); it('rejects identity-less durable completions even when a visible call id matches', async () => { @@ -517,30 +567,21 @@ describe('BackgroundTasksButton', () => { } }); - it('reveals an event activity destination outside its parent message', async () => { + it('opens event subagents with the actor timeline pinned to the requested task', async () => { jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index({ tasks: [] })); - renderButton([{ ...runningChild, origin: 'event', parentToolCallId: undefined }]); - const group = document.createElement('section'); - group.dataset.eventSubagentConversation = conversationId; - const header = document.createElement('button'); - header.setAttribute('aria-expanded', 'false'); - const target = document.createElement('button'); - target.dataset.subagentThread = 'thread-1'; - target.dataset.subagentParentMessage = 'parent-message'; - target.scrollIntoView = jest.fn(); - header.onclick = () => header.setAttribute('aria-expanded', 'true'); - group.append(header, target); - document.body.append(group); - try { - await userEvent.click(await screen.findByTestId('header-background-tasks-button')); - await userEvent.click( - await screen.findByRole('button', { name: /^com_ui_background_tasks_go_to_tool:/ }), - ); - expect(header).toHaveAttribute('aria-expanded', 'true'); - await waitFor(() => expect(target.scrollIntoView).toHaveBeenCalled()); - } finally { - group.remove(); - } + const { getSelection } = renderButton([ + { ...runningChild, origin: 'event', actorId: 'actor-1', parentToolCallId: undefined }, + ]); + await userEvent.click(await screen.findByTestId('header-background-tasks-button')); + await userEvent.click( + await screen.findByRole('button', { name: /^com_ui_background_tasks_open_subagent:/ }), + ); + expect(getSelection()).toMatchObject({ + durable: { threadId: 'thread-1', taskId: 'sub-task-1' }, + event: { actorId: 'actor-1', pinnedTask: true }, + isSubmitting: false, + }); + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()); }); it('keeps the panel open when its exact destination is inert', async () => { diff --git a/client/src/components/Chat/BackgroundTasks/__tests__/rows.test.ts b/client/src/components/Chat/BackgroundTasks/__tests__/rows.test.ts index 8ff2ecb313..b1535b2ea7 100644 --- a/client/src/components/Chat/BackgroundTasks/__tests__/rows.test.ts +++ b/client/src/components/Chat/BackgroundTasks/__tests__/rows.test.ts @@ -116,6 +116,7 @@ describe('buildTaskRows', () => { ]); expect(rows[0].subagent).toEqual({ threadId: 'running-child', taskId: 'task' }); expect(rows[3].subagent).toBeUndefined(); + expect(rows[3].taskId).toBe('task'); }); }); diff --git a/client/src/components/Chat/BackgroundTasks/rows.ts b/client/src/components/Chat/BackgroundTasks/rows.ts index bedf32706c..0ef17c7cc5 100644 --- a/client/src/components/Chat/BackgroundTasks/rows.ts +++ b/client/src/components/Chat/BackgroundTasks/rows.ts @@ -131,6 +131,7 @@ const subagentRow = (child: ParentSubagentSummary, stopping: ReadonlySet id: `subagent:${subagentTaskKey(child.threadId, taskId)}`, kind: 'subagent', name: child.title, + taskId, messageId: child.parentMessageId, toolCallId: child.parentToolCallId, threadId: child.threadId, diff --git a/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx b/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx index 09f474ccda..fb8932da1c 100644 --- a/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx +++ b/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx @@ -386,13 +386,26 @@ export default function SubagentCall({ useEffect(() => { setSelectedSubagent((current) => - current?.parentMessageId === parentMessageId && + current?.host === panelSelection.host && + current.shareId === panelSelection.shareId && + current.parentConversationId === parentConversationId && + current.parentMessageId === parentMessageId && current.toolCallId === toolCallId && - current.partIndex === partIndex + current.partIndex === partIndex && + (current.durable == null || + (current.durable.threadId === panelSelection.durable?.threadId && + current.durable.taskId === panelSelection.durable?.taskId)) ? panelSelection : current, ); - }, [panelSelection, parentMessageId, partIndex, setSelectedSubagent, toolCallId]); + }, [ + panelSelection, + parentConversationId, + parentMessageId, + partIndex, + setSelectedSubagent, + toolCallId, + ]); const openDetails = useCallback(() => { if (!canOpenDetails || openPanel == null) return; diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/SubagentCall.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/SubagentCall.test.tsx index f1c981b3dd..538f1badf7 100644 --- a/client/src/components/Chat/Messages/Content/Parts/__tests__/SubagentCall.test.tsx +++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/SubagentCall.test.tsx @@ -140,6 +140,7 @@ function renderWithState(args: { toolArgs?: Record; subagentIdentity?: SubagentIdentity; runStepStatus?: PartMetadata['runStepStatus']; + selection?: ActiveSubagentPanel; }) { const setter = { current: null as null | ((next: SubagentProgress | null) => void) }; let selection: ActiveSubagentPanel | null = null; @@ -158,7 +159,7 @@ function renderWithState(args: { }; const tree = (tick: number) => ( - + store.set(activeSubagentPanel, args.selection ?? null)}> @@ -493,6 +494,38 @@ describe('SubagentCall', () => { expect((selection as ActiveSubagentPanel | null)?.durable).toBeUndefined(); }); + it.each([ + { threadId: 'child-thread-1', taskId: 'task-2', parentConversationId: 'parent-conversation' }, + { threadId: 'child-thread-2', taskId: 'task-1', parentConversationId: 'parent-conversation' }, + { threadId: 'child-thread-1', taskId: 'task-1', parentConversationId: 'other-conversation' }, + ])('does not replace a retained task on dispatch remount: %p', (identity) => { + const retained: ActiveSubagentPanel = { + host: 'conversation', + parentConversationId: identity.parentConversationId, + parentMessageId: 'parent-message', + toolCallId: 'detached-call', + partIndex: 0, + subagentType: 'self', + initialProgress: 0, + isSubmitting: false, + durable: { threadId: identity.threadId, taskId: identity.taskId }, + }; + const rendered = renderWithState({ + toolCallId: 'detached-call', + initialProgress: 1, + output: JSON.stringify({ + background_task_id: 'task-1', + subagent_thread_id: 'child-thread-1', + tool: 'subagent', + subagent_type: 'self', + status: 'running', + }), + toolArgs: { subagent_type: 'self', run_in_background: true }, + selection: retained, + }); + expect(rendered.getSelection()).toBe(retained); + }); + it('opens an exact host-issued detached invocation in the same panel', () => { const output = JSON.stringify({ background_task_id: 'task-1', diff --git a/client/src/components/Chat/Presentation.test.tsx b/client/src/components/Chat/Presentation.test.tsx index d68713382a..536f33e5d0 100644 --- a/client/src/components/Chat/Presentation.test.tsx +++ b/client/src/components/Chat/Presentation.test.tsx @@ -5,6 +5,7 @@ import { isSubmittingFamily } from '@librechat/chat/react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import type { TConversation } from 'librechat-data-provider'; +import type { JotaiStore } from 'test/harness'; import type { Artifact } from '~/common'; import { prepareUndockedDocument } from '~/components/Artifacts/undockedWindow'; import { activeSubagentPanel } from '~/components/Chat/Subagents/state'; @@ -48,10 +49,24 @@ jest.mock('~/components/Artifacts/Artifacts', () => { }; }); -jest.mock('~/components/Chat/Subagents/SubagentThreadPanel', () => ({ - __esModule: true, - default: () => , -})); +jest.mock('~/components/Chat/Subagents/SubagentThreadPanel', () => { + const { useParentSubagents } = jest.requireActual< + typeof import('~/components/Chat/Subagents/ParentSubagentsProvider') + >('~/components/Chat/Subagents/ParentSubagentsProvider'); + return { + __esModule: true, + default: function MockSubagentThreadPanel() { + const parent = useParentSubagents(); + return ( + + ); + }, + }; +}); jest.mock('~/components/Chat/Input/Files/DragDropWrapper', () => ({ __esModule: true, @@ -117,7 +132,7 @@ const OpenArtifactPanel = () => { ); }; -const OpenSubagentPanel = () => { +const OpenSubagentPanel = ({ durable = true }: { durable?: boolean }) => { const setConversation = useSetRecoilState(store.conversationByIndex(0)); const setSelection = useSetAtom(activeSubagentPanel); const open = () => { @@ -131,10 +146,7 @@ const OpenSubagentPanel = () => { subagentType: 'researcher', initialProgress: 1, isSubmitting: false, - durable: { - threadId: 'child-thread', - taskId: 'background-task', - }, + durable: durable ? { threadId: 'child-thread', taskId: 'background-task' } : undefined, }); }; return ( @@ -223,6 +235,66 @@ describe('Presentation Artifact loading', () => { ); }); + it('keeps durable activity and its draft bound to the original parent after navigation', async () => { + renderPresentation( + + + + + + + + , + ); + fireEvent.click(screen.getByRole('button', { name: mockOpenChildLabel })); + expect(await screen.findByText(mockChildPanelLabel)).toBeInTheDocument(); + const draft = screen.getByLabelText('Panel draft'); + fireEvent.change(draft, { target: { value: 'Keep this guidance.' } }); + fireEvent.click(screen.getByRole('button', { name: mockSelectAgentConversationLabel })); + expect(screen.getByText(mockChildPanelLabel)).toBeInTheDocument(); + expect(screen.getByTestId('panel-parent')).toHaveTextContent('parent-conversation'); + expect(screen.getByLabelText('Panel draft')).toBe(draft); + expect(draft).toHaveValue('Keep this guidance.'); + }); + + it('clears the durable selection when its authenticated chat host unmounts', async () => { + let atoms: JotaiStore; + const view = renderPresentation( + { + atoms = store; + }} + > + + + + + + , + ); + fireEvent.click(screen.getByRole('button', { name: mockOpenChildLabel })); + expect(await screen.findByText(mockChildPanelLabel)).toBeInTheDocument(); + view.unmount(); + expect(atoms!.get(activeSubagentPanel)).toBeNull(); + }); + + it('still closes non-durable activity when leaving its parent chat', async () => { + renderPresentation( + + + + + + + + , + ); + fireEvent.click(screen.getByRole('button', { name: mockOpenChildLabel })); + expect(await screen.findByText(mockChildPanelLabel)).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: mockSelectAgentConversationLabel })); + expect(screen.queryByText(mockChildPanelLabel)).not.toBeInTheDocument(); + }); + it('uses one panel slot and lets an opened artifact replace child activity', async () => { renderPresentation( diff --git a/client/src/components/Chat/Presentation.tsx b/client/src/components/Chat/Presentation.tsx index f1da81f9d6..e8c9e14963 100644 --- a/client/src/components/Chat/Presentation.tsx +++ b/client/src/components/Chat/Presentation.tsx @@ -54,12 +54,20 @@ export default function Presentation({ useArtifactsRegistryLifetime(conversationId); + useEffect( + () => () => + setSelectedSubagent((current) => (current?.host === 'conversation' ? null : current)), + [setSelectedSubagent], + ); + useEffect(() => { const previous = previousConversationIdRef.current; const next = conversationId ?? null; previousConversationIdRef.current = next; - if (previous != null && previous !== next) resetSelectedSubagent(); - }, [conversationId, resetSelectedSubagent]); + if (previous != null && previous !== next) { + setSelectedSubagent((current) => (current?.durable == null ? null : current)); + } + }, [conversationId, setSelectedSubagent]); const setFilesToDelete = useSetFilesToDelete(); @@ -153,14 +161,16 @@ export default function Presentation({ if ( selectedSubagent == null || selectedSubagent.host !== 'conversation' || - selectedSubagent.parentConversationId !== conversationId + (selectedSubagent.durable == null && selectedSubagent.parentConversationId !== conversationId) ) { return null; } return ( - - - + + + + + ); }, [conversationId, selectedSubagent]); diff --git a/client/src/components/Chat/Subagents/EventSubagentActivityGroup.test.tsx b/client/src/components/Chat/Subagents/EventSubagentActivityGroup.test.tsx index 05b059b35e..40f607c236 100644 --- a/client/src/components/Chat/Subagents/EventSubagentActivityGroup.test.tsx +++ b/client/src/components/Chat/Subagents/EventSubagentActivityGroup.test.tsx @@ -5,6 +5,7 @@ import type { ParentSubagentSummary } from 'librechat-data-provider'; import type { ActiveSubagentPanel } from './state'; import EventSubagentActivityGroup from './EventSubagentActivityGroup'; import { ChatSurfaceHarness, testChatSurface } from 'test/harness'; +import { durableSubagentSelection } from './eventSelection'; import { activeSubagentPanel } from './state'; const mockRefresh = jest.fn().mockResolvedValue(undefined); @@ -259,6 +260,56 @@ describe('EventSubagentActivityGroup', () => { expect(completed.firstElementChild).not.toHaveClass('shimmer'); }); + it('keeps a pinned task when an earlier row refresh finishes', async () => { + let selection: ActiveSubagentPanel | null = null; + let resolveRefresh!: (value: { children: ParentSubagentSummary[] }) => void; + mockRefresh.mockReturnValueOnce( + new Promise((resolve) => { + resolveRefresh = resolve; + }), + ); + const Observer = () => { + selection = useAtomValue(activeSubagentPanel); + return null; + }; + const PinTask = () => { + const setSelection = useSetAtom(activeSubagentPanel); + return ( + + ); + }; + render( + + + + + , + ); + screen.getByLabelText('Main chat draft').focus(); + fireEvent.click(screen.getByRole('button', { name: 'Open task' })); + expect(screen.getByRole('region', { name: 'com_ui_subagent_thread_panel' })).toHaveFocus(); + }); + + it.each(['same', 'different'] as const)( + 'returns focus to the latest opener after explicitly opening the %s task', + async (target) => { + mockUseSubagentThreadQuery.mockReturnValue({ + data: completedView, + isLoading: false, + isError: false, + isReadinessPending: false, + }); + const firstOpener = document.createElement('button'); + const latestOpener = document.createElement('button'); + firstOpener.id = 'first-opener'; + latestOpener.id = 'latest-opener'; + document.body.append(firstOpener, latestOpener); + firstOpener.focus(); + const nextSelection: ActiveSubagentPanel = + target === 'same' + ? selection + : { + ...selection, + parentMessageId: 'unloaded-message', + toolCallId: 'other-call', + durable: { threadId: 'other-thread', taskId: 'other-task' }, + }; + const openTaskLabel = 'Open task'; + const PanelHost = () => { + const selected = useAtomValue(activeSubagentPanel); + const open = useOpenSubagentPanel(); + return ( + <> + + {selected != null && } + + ); + }; + try { + render( + store.set(activeSubagentPanel, selection)}> + + , + ); + const panel = screen.getByRole('region', { name: 'com_ui_subagent_thread_panel' }); + expect(panel).toHaveFocus(); + fireEvent.click(screen.getByRole('button', { name: openTaskLabel })); + expect(screen.getByRole('region', { name: 'com_ui_subagent_thread_panel' })).toBe(panel); + expect(panel).toHaveFocus(); + fireEvent.click(screen.getByRole('button', { name: 'com_ui_close' })); + await waitFor(() => expect(latestOpener).toHaveFocus()); + expect(firstOpener).not.toHaveFocus(); + } finally { + firstOpener.remove(); + latestOpener.remove(); + } + }, + ); + + describe.each([false, true])('focus return with mobile = %s', (mobile) => { + it.each([ + 'available', + 'hidden', + 'inert', + 'aria-hidden', + 'aria-disabled', + 'disabled', + 'removed', + ])( + 'prefers the explicit opener when it is %s, otherwise falls back to the message card', + async (openerState) => { + mockIsMobile = mobile; + mockUseSubagentThreadQuery.mockReturnValue({ + data: completedView, + isLoading: false, + isError: false, + isReadinessPending: false, + }); + const disclosure = document.createElement('button'); + const messageCard = document.createElement('button'); + disclosure.id = 'popup-opener'; + disclosure.dataset.testid = 'header-background-tasks-button'; + messageCard.id = 'loaded-message-card'; + messageCard.dataset.subagentToolCall = selection.toolCallId; + messageCard.dataset.subagentParentMessage = selection.parentMessageId; + messageCard.dataset.subagentPartIndex = String(selection.partIndex); + document.body.append(disclosure, messageCard); + disclosure.focus(); + const PanelHost = () => { + const selected = useAtomValue(activeSubagentPanel); + return selected == null ? null : ; + }; + try { + render( + store.set(activeSubagentPanel, selection)}> + + , + ); + if (openerState === 'removed') disclosure.remove(); + else if (openerState === 'disabled') disclosure.disabled = true; + else if (openerState !== 'available') { + disclosure.setAttribute(openerState, openerState.startsWith('aria-') ? 'true' : ''); + } + fireEvent.click(screen.getByRole('button', { name: 'com_ui_close' })); + const destination = openerState === 'available' ? disclosure : messageCard; + await waitFor(() => expect(destination).toHaveFocus()); + } finally { + disclosure.remove(); + messageCard.remove(); + } + }, + ); + }); + + it('does not steal main-chat focus when the selected task advances', () => { + mockUseSubagentThreadQuery.mockReturnValue({ + data: completedView, + isLoading: false, + isError: false, + isReadinessPending: false, + }); + const tree = (taskId: string) => ( + + + + + ); + const view = render(tree('task')); + const composer = screen.getByLabelText('Main chat draft'); + composer.focus(); + view.rerender(tree('next-task')); + expect(composer).toHaveFocus(); + }); + + it('only navigates to the parent chat when explicitly requested', () => { + mockUseSubagentThreadQuery.mockReturnValue({ + data: completedView, + isLoading: false, + isError: false, + isReadinessPending: false, + }); + render( + + + , + ); + expect(screen.getByRole('region', { name: 'com_ui_subagent_thread_panel' })).toHaveFocus(); + expect(mockNavigate).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole('button', { name: 'com_ui_subagent_go_to_parent' })); + expect(mockNavigate).toHaveBeenCalledWith('/c/parent-conversation'); + }); + + it('returns focus to the task disclosure when its originating call is not loaded', async () => { + mockUseSubagentThreadQuery.mockReturnValue({ + data: completedView, + isLoading: false, + isError: false, + isReadinessPending: false, + }); + const disclosure = document.createElement('button'); + disclosure.dataset.testid = 'header-background-tasks-button'; + document.body.append(disclosure); + disclosure.focus(); + try { + render( + + + , + ); + expect(screen.getByRole('region', { name: 'com_ui_subagent_thread_panel' })).toHaveFocus(); + fireEvent.click(screen.getByRole('button', { name: 'com_ui_close' })); + await waitFor(() => expect(disclosure).toHaveFocus()); + expect(mockNavigateToConvo).not.toHaveBeenCalled(); + } finally { + disclosure.remove(); + } + }); + + it.each(['hidden', 'inert', 'aria-hidden', 'disabled'])( + 'skips an originating trigger blocked by %s when returning focus', + async (blocked) => { + mockUseSubagentThreadQuery.mockReturnValue({ + data: completedView, + isLoading: false, + isError: false, + isReadinessPending: false, + }); + const disclosure = document.createElement('button'); + const group = document.createElement('section'); + const trigger = document.createElement('button'); + trigger.dataset.subagentToolCall = 'tool-call'; + trigger.dataset.subagentParentMessage = 'parent-message'; + trigger.dataset.subagentPartIndex = '2'; + if (blocked === 'disabled') trigger.disabled = true; + else group.setAttribute(blocked, blocked === 'aria-hidden' ? 'true' : ''); + group.append(trigger); + document.body.append(disclosure, group); + disclosure.focus(); + try { + render( + + + , + ); + fireEvent.click(screen.getByRole('button', { name: 'com_ui_close' })); + await waitFor(() => expect(disclosure).toHaveFocus()); + } finally { + disclosure.remove(); + group.remove(); + } + }, + ); + it('renders a bounded read-only activity timeline and closes its selection', async () => { mockUseSubagentThreadQuery.mockReturnValue({ data: completedView, diff --git a/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx b/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx index 89aa688573..414b73aa99 100644 --- a/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx +++ b/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx @@ -1,8 +1,9 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { v4 } from 'uuid'; -import { useAtom, useSetAtom, useStore } from 'jotai'; -import { Clock, OctagonPause, X, Zap } from 'lucide-react'; +import { useNavigate } from 'react-router-dom'; import { dataService, ForkOptions } from 'librechat-data-provider'; +import { useAtom, useAtomValue, useSetAtom, useStore } from 'jotai'; +import { ArrowUpRight, Clock, OctagonPause, X, Zap } from 'lucide-react'; import { Alert, Button, @@ -37,6 +38,14 @@ import { mergeChildConversationTurns, retainBoundedMovingWindowTurns, } from './adapters'; +import { + activeSubagentPanel, + subagentPanelFocusRequest, + subagentControlStateByTask, + subagentControlStateKey, + subagentProgressKey, + useSubagentProgress, +} from './state'; import { agentAuthor, resolveSubagentAuthor, @@ -45,13 +54,6 @@ import { readableSubagentType, useParentAuthor, } from './author'; -import { - activeSubagentPanel, - subagentControlStateByTask, - subagentControlStateKey, - subagentProgressKey, - useSubagentProgress, -} from './state'; import useSubagentActivityStream from '~/data-provider/Subagents/useSubagentActivityStream'; import SubagentActivity, { SubagentActivityScrollSurface } from './SubagentActivity'; import ApprovalProvider from '~/components/Chat/Messages/Content/ApprovalContext'; @@ -127,9 +129,12 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu const clearsFooter = useConfiguredFooter(); const localize = useLocalize(); const panelStore = useStore(); + const focusRequest = useAtomValue(subagentPanelFocusRequest); const { showToast } = useToastContext(); const { navigateToConvo } = useNavigateToConvo(); + const navigate = useNavigate(); const panelRef = useRef(null); + const returnFocusRef = useRef(null); const isMobile = useScaledMaxWidth(ARTIFACTS_SHEET_MAX_WIDTH); /** Two reasons the send control's action list cannot be used where it hangs. * Without hover, a tap on its anchor submits instead of opening it. And @@ -775,24 +780,51 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu const close = useCallback(() => { resetSelection(); requestAnimationFrame(() => { + const available = (element: HTMLElement | null | undefined) => + element != null && + element.isConnected && + !element.matches(':disabled, [aria-disabled="true"]') && + element.closest('[hidden], [inert], [aria-hidden="true"]') == null; const trigger = Array.from( document.querySelectorAll('[data-subagent-tool-call]'), ).find( (element) => element.dataset.subagentToolCall === selection.toolCallId && element.dataset.subagentParentMessage === selection.parentMessageId && - element.dataset.subagentPartIndex === String(selection.partIndex), + element.dataset.subagentPartIndex === String(selection.partIndex) && + available(element), ); - trigger?.focus(); + const disclosure = document.querySelector( + '[data-testid="header-background-tasks-button"]', + ); + const destination = + (available(returnFocusRef.current) ? returnFocusRef.current : null) ?? + trigger ?? + (available(disclosure) ? disclosure : null); + destination?.focus({ preventScroll: true }); }); }, [resetSelection, selection.parentMessageId, selection.partIndex, selection.toolCallId]); + useEffect(() => { + const activeElement = document.activeElement; + if ( + activeElement instanceof HTMLElement && + activeElement !== document.body && + !panelRef.current?.contains(activeElement) + ) { + returnFocusRef.current = activeElement; + } + }, [focusRequest]); + /** Escape is handled on the element rather than through the trap's own * native listener: that listener sits on this `aside`, so it runs BEFORE any * React handler inside it and would close the whole panel out from under a * nested popover that meant to dismiss only itself. As a React handler it * bubbles in DOM order, so an inner control can stop it or mark it handled. */ useFocusTrap(panelRef, isMobile); + useEffect(() => { + if (!isMobile) panelRef.current?.focus({ preventScroll: true }); + }, [focusRequest, isMobile]); const handlePanelKeyDown = useCallback( (event: ReactKeyboardEvent) => { if (!isMobile || event.key !== 'Escape' || event.defaultPrevented) return; @@ -1528,6 +1560,7 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu return (