🛋️ feat: Open Subagents Directly from Background Tasks (#17020)
Some checks failed
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/chat (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Sync Locize Translations & Create Translation PR / Sync Translation Keys with Locize (push) Has been cancelled
Sync Locize Translations & Create Translation PR / Create Translation PR on Version Published (push) Has been cancelled

* 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 <lia@librechat.ai>
This commit is contained in:
lia-by-librechat[bot] 2026-10-17 00:58:22 -04:00 • committed by GitHub
parent e081b566a4
commit 147aa29807
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
24 changed files with 923 additions and 170 deletions

View file

@ -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<HTMLButtonElement>(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<HTMLElement>(
'[data-event-subagent-conversation] [data-subagent-thread]',
),
).filter(
(element) =>
element.dataset.subagentThread === row.threadId &&
element.dataset.subagentParentMessage === row.messageId &&
element.closest<HTMLElement>('[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<HTMLButtonElement>('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;

View file

@ -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 (
<li className="bg-surface-tertiary rounded-lg px-3 py-2" data-testid="background-task-row">
@ -125,14 +130,14 @@ function TaskCard({
</p>
</div>
<TooltipAnchor
description={localize('com_ui_background_tasks_go_to_tool')}
description={openLabel}
portalElement={portalElement}
render={
<IconButton
variant="ghost"
size="xs"
shape="inset"
label={`${localize('com_ui_background_tasks_go_to_tool')}: ${title}`}
label={`${openLabel}: ${title}`}
onClick={() => setJumpUnavailable(!onJump(row))}
>
<ArrowUpRight className="size-3.5" aria-hidden="true" />
@ -174,7 +179,11 @@ function TaskCard({
)}
{jumpUnavailable && (
<p role="status" className="text-text-secondary mt-1 text-xs">
{localize('com_ui_background_tasks_tool_unavailable')}
{localize(
row.kind === 'subagent'
? 'com_ui_background_tasks_subagent_unavailable'
: 'com_ui_background_tasks_tool_unavailable',
)}
</p>
)}
</li>

View file

@ -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(
<RecoilRoot>
<QueryClientProvider client={queryClient}>
<ParentSubagentsProvider conversationId={conversationId} enabled>
<BackgroundTasksButton conversationId={conversationId} isSubmitting={false} />
</ParentSubagentsProvider>
</QueryClientProvider>
</RecoilRoot>,
<ChatSurfaceHarness
seed={(store) => {
atoms = store;
}}
>
<RecoilRoot>
<QueryClientProvider client={queryClient}>
<ParentSubagentsProvider conversationId={conversationId} enabled>
<BackgroundTasksButton conversationId={conversationId} isSubmitting={false} />
</ParentSubagentsProvider>
</QueryClientProvider>
</RecoilRoot>
</ChatSurfaceHarness>,
);
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 () => {

View file

@ -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');
});
});

View file

@ -131,6 +131,7 @@ const subagentRow = (child: ParentSubagentSummary, stopping: ReadonlySet<string>
id: `subagent:${subagentTaskKey(child.threadId, taskId)}`,
kind: 'subagent',
name: child.title,
taskId,
messageId: child.parentMessageId,
toolCallId: child.parentToolCallId,
threadId: child.threadId,

View file

@ -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;

View file

@ -140,6 +140,7 @@ function renderWithState(args: {
toolArgs?: Record<string, unknown>;
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) => (
<MemoryRouter>
<ChatSurfaceHarness>
<ChatSurfaceHarness seed={(store) => store.set(activeSubagentPanel, args.selection ?? null)}>
<RecoilRoot>
<SeedHelper />
<SelectionObserver />
@ -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',

View file

@ -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: () => <aside>{mockChildPanelLabel}</aside>,
}));
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 (
<aside>
{mockChildPanelLabel}
<span data-testid="panel-parent">{parent.conversationId}</span>
<input aria-label="Panel draft" />
</aside>
);
},
};
});
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(
<ChatSurfaceHarness>
<RecoilRoot>
<Presentation>
<OpenSubagentPanel />
<SelectAgentConversation />
</Presentation>
</RecoilRoot>
</ChatSurfaceHarness>,
);
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(
<ChatSurfaceHarness
seed={(store) => {
atoms = store;
}}
>
<RecoilRoot>
<Presentation>
<OpenSubagentPanel />
</Presentation>
</RecoilRoot>
</ChatSurfaceHarness>,
);
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(
<ChatSurfaceHarness>
<RecoilRoot>
<Presentation>
<OpenSubagentPanel durable={false} />
<SelectAgentConversation />
</Presentation>
</RecoilRoot>
</ChatSurfaceHarness>,
);
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(
<ChatSurfaceHarness>

View file

@ -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 (
<Suspense fallback={null}>
<SubagentThreadPanel selection={selectedSubagent} />
</Suspense>
<ParentSubagentsProvider conversationId={selectedSubagent.parentConversationId} enabled>
<Suspense fallback={null}>
<SubagentThreadPanel selection={selectedSubagent} />
</Suspense>
</ParentSubagentsProvider>
);
}, [conversationId, selectedSubagent]);

View file

@ -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 (
<button
type="button"
data-testid="pin-task"
onClick={() =>
setSelection(durableSubagentSelection('parent-conversation', mockChild, 'task-1'))
}
/>
);
};
render(
<ChatSurfaceHarness>
<Observer />
<PinTask />
<EventSubagentActivityGroup
conversationId="parent-conversation"
parentMessageIds={['parent-message']}
/>
</ChatSurfaceHarness>,
);
fireEvent.click(screen.getByRole('button', { name: /com_ui_subagent_activity/ }));
fireEvent.click(screen.getByRole('button', { name: /Visible Agent/ }));
fireEvent.click(screen.getByTestId('pin-task'));
await act(async () => {
resolveRefresh({
children: [{ ...mockChild, latestTaskId: 'task-2' }],
});
});
expect(selection).toEqual(
expect.objectContaining({
durable: { threadId: 'event-thread', taskId: 'task-1' },
event: expect.objectContaining({ pinnedTask: true }),
}),
);
});
it('does not reopen a child after the user closes it while refresh is pending', async () => {
let selection: ActiveSubagentPanel | null = null;
let resolveRefresh!: (value: unknown) => void;

View file

@ -130,6 +130,7 @@ function EventSubagentRows({
if (freshSelection != null) {
setSelected((current) => {
if (
current?.event?.pinnedTask === true ||
current?.durable?.threadId !== selection.durable?.threadId ||
current?.durable?.taskId !== selection.durable?.taskId
) {

View file

@ -82,6 +82,51 @@ describe('ParentSubagentsProvider', () => {
expect(result).toEqual(refreshed);
});
it('reuses its parent index while chats match and owns discovery after navigation', () => {
mockUseParentSubagentsQuery.mockImplementation((conversationId: string) => ({
data: {
parentConversationId: conversationId,
children: conversationId === 'parent-conversation' ? [eventChild] : [],
childrenTruncated: false,
},
refetch: jest.fn(),
}));
let outer: ReturnType<typeof useParentSubagents> | undefined;
let panel: ReturnType<typeof useParentSubagents> | undefined;
const OuterProbe = () => {
outer = useParentSubagents();
return null;
};
const PanelProbe = () => {
panel = useParentSubagents();
return null;
};
const tree = (visibleConversation: string) => (
<ParentSubagentsProvider conversationId={visibleConversation} enabled>
<OuterProbe />
<ParentSubagentsProvider conversationId="parent-conversation" enabled>
<PanelProbe />
</ParentSubagentsProvider>
</ParentSubagentsProvider>
);
const view = renderProvider(tree('parent-conversation'));
expect(panel).toBe(outer);
expect(mockUseParentSubagentsQuery).toHaveBeenLastCalledWith(
'parent-conversation',
{ enabled: false },
false,
);
view.rerender(tree('other-conversation'));
expect(panel?.conversationId).toBe('parent-conversation');
expect(panel?.byThreadId.get('event-thread')).toEqual(eventChild);
expect(outer?.conversationId).toBe('other-conversation');
expect(mockUseParentSubagentsQuery).toHaveBeenLastCalledWith(
'parent-conversation',
{ enabled: true },
false,
);
});
it('marks an active parent run for prompt discovery', () => {
mockUseParentSubagentsQuery.mockReturnValue({ data: undefined, refetch: jest.fn() });
renderProvider(

View file

@ -43,6 +43,9 @@ export function ParentSubagentsProvider({
children: React.ReactNode;
}) {
const queryClient = useQueryClient();
const parent = useContext(ParentSubagentsContext);
const inherited =
parent.conversationId === conversationId && parent.discoveryEnabled ? parent : null;
// Observe already-loaded history without fetching it or rerendering on streamed text.
const { data: hasAgentHistory = false } = useQuery<TMessage[], unknown, boolean>(
[QueryKeys.messages, conversationId],
@ -70,7 +73,7 @@ export function ParentSubagentsProvider({
}
const { data, refetch, isError } = useParentSubagentsQuery(
conversationId,
{ enabled: discoveryEnabled },
{ enabled: discoveryEnabled && inherited == null },
isSubmitting,
);
const refresh = useCallback(async () => {
@ -78,6 +81,7 @@ export function ParentSubagentsProvider({
return result.data;
}, [refetch]);
const value = useMemo<ParentSubagentsContextValue>(() => {
if (inherited != null) return inherited;
const byMessageId = new Map<string, ParentSubagentSummary[]>();
const byThreadId = new Map<string, ParentSubagentSummary>();
for (const child of data?.children ?? []) {
@ -94,7 +98,7 @@ export function ParentSubagentsProvider({
});
}
return { conversationId, byMessageId, byThreadId, refresh, isError, discoveryEnabled };
}, [conversationId, data, refresh, isError, discoveryEnabled]);
}, [conversationId, data, refresh, isError, discoveryEnabled, inherited]);
return (
<ParentSubagentsContext.Provider value={value}>{children}</ParentSubagentsContext.Provider>

View file

@ -15,6 +15,7 @@ import { activeSubagentPanel, subagentProgressByToolCallId, subagentProgressKey
import { initSubagentAggregatorState, initSubagentTickerState } from '~/utils/subagentContent';
import { ChatSurfaceHarness, testChatSurface } from 'test/harness';
import SubagentThreadPanel from './SubagentThreadPanel';
import { useOpenSubagentPanel } from './surface';
import { getDraft } from '~/utils';
const mockUseSubagentThreadQuery = jest.fn();
@ -30,6 +31,7 @@ const mockUseSubagentActivityStream = jest.fn();
const mockForkMutate = jest.fn();
const mockControlMutate = jest.fn();
const mockNavigateToConvo = jest.fn();
const mockNavigate = jest.fn();
const mockShowToast = jest.fn();
const mockGetSubagentThread = jest.fn();
const mockApprovalProviderMounted = jest.fn();
@ -74,6 +76,11 @@ function Root({
);
}
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: () => mockNavigate,
}));
jest.mock('librechat-data-provider', () => {
const actual = jest.requireActual('librechat-data-provider');
return {
@ -444,6 +451,7 @@ jest.mock('@librechat/client', () => ({
jest.mock('lucide-react', () => ({
AlertCircle: () => null,
ArrowUpRight: () => null,
CornerUpLeft: () => null,
CheckCircle2: () => null,
Clock: () => null,
@ -525,6 +533,7 @@ describe('SubagentThreadPanel', () => {
mockForkMutate.mockClear();
mockControlMutate.mockClear();
mockNavigateToConvo.mockClear();
mockNavigate.mockClear();
mockShowToast.mockClear();
mockGetSubagentThread.mockReset();
mockRefreshParentChildren.mockClear();
@ -1208,6 +1217,254 @@ describe('SubagentThreadPanel', () => {
},
);
it('focuses the panel when the same task is explicitly reopened', () => {
mockUseSubagentThreadQuery.mockReturnValue({
data: completedView,
isLoading: false,
isError: false,
isReadinessPending: false,
});
const openTaskLabel = 'Open task';
const OpenPanel = () => {
const open = useOpenSubagentPanel();
return (
<button type="button" onClick={() => open?.(selection)}>
{openTaskLabel}
</button>
);
};
render(
<Root>
<input aria-label="Main chat draft" />
<OpenPanel />
<SubagentThreadPanel selection={selection} />
</Root>,
);
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 (
<>
<button
type="button"
onClick={() => {
latestOpener.focus();
open?.(nextSelection);
}}
>
{openTaskLabel}
</button>
{selected != null && <SubagentThreadPanel selection={selected} />}
</>
);
};
try {
render(
<Root seed={(store) => store.set(activeSubagentPanel, selection)}>
<PanelHost />
</Root>,
);
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 : <SubagentThreadPanel selection={selected} />;
};
try {
render(
<Root seed={(store) => store.set(activeSubagentPanel, selection)}>
<PanelHost />
</Root>,
);
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) => (
<Root>
<input aria-label="Main chat draft" />
<SubagentThreadPanel
selection={{ ...selection, durable: { threadId: 'child-thread', taskId } }}
/>
</Root>
);
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(
<Root>
<SubagentThreadPanel selection={selection} />
</Root>,
);
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(
<Root>
<SubagentThreadPanel selection={selection} />
</Root>,
);
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(
<Root>
<SubagentThreadPanel selection={selection} />
</Root>,
);
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,

View file

@ -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<HTMLDivElement>(null);
const returnFocusRef = useRef<HTMLElement | null>(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<HTMLElement>('[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<HTMLElement>(
'[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<HTMLElement>) => {
if (!isMobile || event.key !== 'Escape' || event.defaultPrevented) return;
@ -1528,6 +1560,7 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
return (
<aside
ref={panelRef}
tabIndex={-1}
role={isMobile ? 'dialog' : 'region'}
aria-modal={isMobile || undefined}
aria-label={localize('com_ui_subagent_thread_panel')}
@ -1587,6 +1620,17 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
</h2>
</>
)}
<Button
type="button"
variant="ghost"
size="icon"
onClick={() => navigate(`/c/${encodeURIComponent(selection.parentConversationId)}`)}
aria-label={localize('com_ui_subagent_go_to_parent')}
title={localize('com_ui_subagent_go_to_parent')}
className="h-8 w-8 shrink-0"
>
<ArrowUpRight className="size-[1.0625rem]" aria-hidden="true" />
</Button>
<Button
type="button"
variant="ghost"

View file

@ -465,6 +465,32 @@ describe('useSubagentProgress', () => {
expect(subagentProgressByToolCallId(key)).not.toBe(held);
});
it('keeps retained readers and stream writers together after navigation', () => {
const key = subagentProgressKey('retained-message', 'retained-call', 0);
const store = createStore();
const wrapper = ({ children }: { children: React.ReactNode }) =>
React.createElement(JotaiProvider, { store }, children);
const { result, unmount } = renderHook(() => useSubagentProgress(key), { wrapper });
const held = subagentProgressByToolCallId(key);
const streamOpen = subagentParentStreamOpenByToolCallId(key);
registerSubagentProgressKey(key);
act(() => {
for (const drained of takeRegisteredSubagentProgressKeys()) {
store.set(subagentProgressByToolCallId(drained), null);
store.set(subagentParentStreamOpenByToolCallId(drained), false);
removeSubagentProgressAtoms(drained);
}
});
expect(subagentProgressByToolCallId(key)).toBe(held);
expect(subagentParentStreamOpenByToolCallId(key)).toBe(streamOpen);
act(() => store.set(held, reduceSubagentProgress(null, [update()])));
expect(result.current?.contentParts).toEqual([{ type: ContentTypes.TEXT, text: 'Working.' }]);
act(() => store.set(held, null));
unmount();
expect(subagentProgressByToolCallId(key)).not.toBe(held);
expect(subagentParentStreamOpenByToolCallId(key)).not.toBe(streamOpen);
});
/** The drain owns a streaming key; freeing it here would race that boundary. */
it('leaves a key the stream registered to the drain', () => {
const key = subagentProgressKey('live-message', 'live-call', 0);

View file

@ -327,6 +327,7 @@ export type ActiveSubagentPanel = {
};
export const activeSubagentPanel = atom<ActiveSubagentPanel | null>(null);
export const subagentPanelFocusRequest = atom(0);
export type SubagentControlUiReceipt = Omit<SubagentControlReceipt, 'status'> & {
status: SubagentControlReceipt['status'] | 'submitted';
@ -506,15 +507,9 @@ export function listRegisteredSubagentProgressKeys(): string[] {
return [...registeredSubagentProgressKeys];
}
/**
* Frees the family members held for one invocation. An `atomFamily` caches a
* member per key for the life of the tab, and every invocation key is unique,
* so the drain boundary has to release them or a long session accumulates two
* atom configurations per subagent call it ever saw. Callers clear the values
* first: `remove` drops the cached member without telling anything subscribed
* to it.
*/
/** Frees idle invocation members; mounted readers retain their stream identity. */
export function removeSubagentProgressAtoms(invocationKey: string): void {
if (subagentProgressReaders.has(invocationKey)) return;
subagentProgressByToolCallId.remove(invocationKey);
subagentParentStreamOpenByToolCallId.remove(invocationKey);
}

View file

@ -3,7 +3,7 @@ import { useSetAtom } from 'jotai';
import type { ReactNode } from 'react';
import type { ComposerBindings } from '~/hooks/Input/useComposerBindings';
import type { ActiveSubagentPanel } from './state';
import { activeSubagentPanel } from './state';
import { activeSubagentPanel, subagentPanelFocusRequest } from './state';
/**
* Everything this feature needs from the application hosting it, and nothing
@ -64,11 +64,13 @@ export function useOptionalChatSurface(): ChatSurface | null {
export function useOpenSubagentPanel(): ((selection: ActiveSubagentPanel) => void) | null {
const claimForeground = useOptionalChatSurface()?.claimForeground;
const setSelection = useSetAtom(activeSubagentPanel);
const requestFocus = useSetAtom(subagentPanelFocusRequest);
return useMemo(() => {
if (claimForeground == null) return null;
return (selection: ActiveSubagentPanel) => {
claimForeground();
setSelection(selection);
requestFocus((current) => current + 1);
};
}, [claimForeground, setSelection]);
}, [claimForeground, requestFocus, setSelection]);
}

View file

@ -8,6 +8,10 @@ import type { ReactNode } from 'react';
import { useIsReplacingConversationCodeEnvironment } from '~/data-provider/CodeEnvironments';
import useEventHandlers from '../useEventHandlers';
let mockConversationId = 'saved';
const mockResetSubagentAtoms = jest.fn();
const mockResetPtcAtoms = jest.fn();
jest.mock('librechat-data-provider', () => {
const actual = jest.requireActual('librechat-data-provider');
return { ...actual, dataService: { ...actual.dataService, getConversationById: jest.fn() } };
@ -17,7 +21,7 @@ jest.mock('recoil', () => ({
useRecoilCallback: () => jest.fn(),
}));
jest.mock('react-router-dom', () => ({
useParams: () => ({ conversationId: 'saved' }),
useParams: () => ({ conversationId: mockConversationId }),
useNavigate: () => jest.fn(),
useLocation: () => ({ pathname: '/c/saved' }),
}));
@ -37,8 +41,8 @@ jest.mock('../useAttachmentHandler', () => () => jest.fn());
jest.mock('../useStepHandler', () => () => ({
stepHandler: jest.fn(),
clearStepMaps: jest.fn(),
resetSubagentAtoms: jest.fn(),
resetPtcAtoms: jest.fn(),
resetSubagentAtoms: mockResetSubagentAtoms,
resetPtcAtoms: mockResetPtcAtoms,
prunePtcTraces: jest.fn(),
syncStepMessage: jest.fn(),
cancelPendingDeltaFlush: jest.fn(),
@ -102,9 +106,45 @@ const submission = {
} as EventSubmission;
describe('local cancellation decision reconciliation', () => {
beforeEach(() => jest.clearAllMocks());
beforeEach(() => {
jest.clearAllMocks();
mockConversationId = 'saved';
});
afterEach(() => jest.restoreAllMocks());
it('preserves the selected task only for navigation, not host teardown', () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const wrapper = ({ children }: { children: ReactNode }) =>
createElement(
Provider,
null,
createElement(QueryClientProvider, { client: queryClient }, children),
);
const { rerender, unmount } = renderHook(
() =>
useEventHandlers({
getMessages: () => [],
setMessages: jest.fn(),
setCompleted: jest.fn(),
setConversation: jest.fn(),
setIsSubmitting: jest.fn(),
setShowStopButton: jest.fn(),
newConversation: jest.fn(),
}),
{ wrapper },
);
expect(mockResetSubagentAtoms).not.toHaveBeenCalled();
mockConversationId = 'other';
rerender();
expect(mockResetSubagentAtoms).toHaveBeenCalledTimes(1);
expect(mockResetSubagentAtoms).toHaveBeenCalledWith({ preserveSelectedTask: true });
expect(mockResetPtcAtoms).toHaveBeenCalledTimes(1);
unmount();
expect(mockResetSubagentAtoms).toHaveBeenCalledTimes(2);
expect(mockResetSubagentAtoms).toHaveBeenLastCalledWith();
expect(mockResetPtcAtoms).toHaveBeenCalledTimes(2);
});
it.each(['streamed', 'minimal', 'navigated'])(
'does not use a synthetic %s cancel as evidence that the server settled',
async (kind) => {

View file

@ -20,8 +20,14 @@ import type {
PtcToolCallEvent,
Agents,
} from 'librechat-data-provider';
import type { ActiveSubagentPanel } from '~/components/Chat/Subagents/state';
import type { PtcTrace, PtcTraceEntry } from '~/common';
import {
activeSubagentPanel,
listRegisteredSubagentProgressKeys,
reduceSubagentProgress,
registerSubagentProgressKey,
subagentParentStreamOpenByToolCallId,
subagentProgressByToolCallId,
subagentProgressKey,
} from '~/components/Chat/Subagents/state';
@ -3778,6 +3784,98 @@ describe('useStepHandler', () => {
expect(subagentProgressByToolCallId(invocationKey)).not.toBe(held);
});
it.each(['tool', 'event'] as const)(
'keeps retained %s activity through navigation and releases it on host teardown',
(origin) => {
const { result } = renderHook(
() => ({ ...useStepHandler(createHookParams()), store: useStore() }),
{ wrapper: subagentStoreWrapper },
);
const selected: ActiveSubagentPanel = {
host: 'conversation',
parentConversationId: 'conv-1',
parentMessageId: 'response-msg-1',
toolCallId: 'call_A',
partIndex: 0,
subagentType: 'self',
initialProgress: 0,
isSubmitting: false,
durable: { threadId: 'child-thread', taskId: 'task' },
...(origin === 'event'
? { event: { actorId: 'actor', progressKey: 'event-task:child-thread:task' } }
: {}),
};
const key = subagentProgressKey(
selected.parentMessageId,
selected.event?.progressKey ?? selected.toolCallId,
selected.partIndex,
);
const otherKey = subagentProgressKey('other-message', 'call_B', 1);
const store = result.current.store;
const held = subagentProgressByToolCallId(key);
const earlier = makeUpdate({
phase: 'message_delta',
activityEventId: 'earlier',
activitySequence: 0,
data: { delta: { content: [{ type: ContentTypes.TEXT, text: 'Earlier work.' }] } },
});
const tool = makeUpdate({
phase: 'run_step',
activityEventId: 'tool',
activitySequence: 1,
data: {
stepDetails: {
type: 'tool_calls',
tool_calls: [{ id: 'inner-call', name: 'calculator', args: '{"value":4}' }],
},
},
});
act(() => {
store.set(activeSubagentPanel, selected);
registerSubagentProgressKey(key);
registerSubagentProgressKey(otherKey);
store.set(held, reduceSubagentProgress(null, [earlier, tool], 'parent', true));
store.set(
subagentProgressByToolCallId(otherKey),
reduceSubagentProgress(null, [earlier]),
);
store.set(subagentParentStreamOpenByToolCallId(key), true);
});
const before = store.get(held)?.contentParts;
act(() => result.current.resetSubagentAtoms({ preserveSelectedTask: true }));
expect(store.get(held)?.contentParts).toEqual(before);
expect(subagentProgressByToolCallId(key)).toBe(held);
expect(store.get(subagentParentStreamOpenByToolCallId(key))).toBe(false);
expect(listRegisteredSubagentProgressKeys()).toEqual([key]);
expect(store.get(subagentProgressByToolCallId(otherKey))).toBeNull();
act(() => {
store.set(held, (progress) =>
reduceSubagentProgress(
progress,
[
makeUpdate({
phase: 'message_delta',
activityEventId: 'later',
activitySequence: 2,
data: { delta: { content: [{ type: ContentTypes.TEXT, text: 'Later work.' }] } },
}),
],
'detached',
false,
),
);
});
expect(store.get(held)?.contentParts).toEqual([
...(before ?? []),
{ type: ContentTypes.TEXT, text: 'Later work.' },
]);
act(() => result.current.resetSubagentAtoms());
expect(store.get(held)).toBeNull();
expect(subagentProgressByToolCallId(key)).not.toBe(held);
expect(listRegisteredSubagentProgressKeys()).toEqual([]);
},
);
it('falls back to oldest-unclaimed tool call when parentToolCallId is absent', () => {
const { result, getProgress } = renderStepHandlerWithReader();
/** Two subagent tool calls seeded in creation order. Without

View file

@ -549,7 +549,7 @@ export default function useEventHandlers({
if (
shouldResetSubagentAtomsOnConversationChange(previous, paramId, preserveNewConversationId)
) {
resetSubagentAtoms();
resetSubagentAtoms({ preserveSelectedTask: true });
/** PTC traces are live-only for the same reason and share the boundary:
* keep them through a run so a finished program stays auditable, drop
* them when the conversation changes. */

View file

@ -8,6 +8,7 @@ import {
resetStreamState,
syncStreamMessage,
createStreamState,
subagentProgressKey,
} from '@librechat/chat';
import type {
TMessage,
@ -18,6 +19,7 @@ import type {
import type { StepEvent, StepEffect, StepContext, StreamState } from '@librechat/chat';
import type { AnnounceOptions } from '~/common';
import {
activeSubagentPanel,
closeParentSubagentProgress,
listRegisteredSubagentProgressKeys,
reduceSubagentProgress,
@ -86,27 +88,34 @@ export default function useStepHandler({
[subagentStore],
);
/**
* Resets all accumulated subagent state. Kept for conversation-switch
* cleanup (see top-level hook usage) but NOT called from `clearStepMaps`:
* the collapsed SubagentCall ticker and its panel read from these atoms to
* render the child's content parts, and we want that history to remain
* visible after the stream ends so the user can reopen the panel for
* auditability. The atoms are bounded by aggregated structure and
* per-conversation (one atom per subagent spawn), so growth is proportional
* to messages: the same growth profile as the rest of the conversation
* state.
*/
const resetSubagentAtoms = useCallback((): void => {
for (const invocationKey of takeRegisteredSubagentProgressKeys()) {
/** Clear before freeing: `remove` drops the cached family member but
* tells nothing still subscribed to it, so anything mounted at this
* boundary has to see the empty value first. */
subagentStore.set(subagentProgressByToolCallId(invocationKey), null);
subagentStore.set(subagentParentStreamOpenByToolCallId(invocationKey), false);
removeSubagentProgressAtoms(invocationKey);
}
}, [subagentStore]);
/** Navigation retains the selected durable task; host teardown drains every invocation. */
const resetSubagentAtoms = useCallback(
({ preserveSelectedTask = false }: { preserveSelectedTask?: boolean } = {}): void => {
const selected = preserveSelectedTask ? subagentStore.get(activeSubagentPanel) : null;
const retainedKey =
selected?.host === 'conversation' && selected.durable != null
? subagentProgressKey(
selected.parentMessageId,
selected.event?.progressKey ?? selected.toolCallId,
selected.partIndex,
)
: null;
for (const invocationKey of takeRegisteredSubagentProgressKeys()) {
subagentStore.set(subagentParentStreamOpenByToolCallId(invocationKey), false);
if (invocationKey === retainedKey) {
registerSubagentProgressKey(invocationKey);
subagentStore.set(
subagentProgressByToolCallId(invocationKey),
closeParentSubagentProgress,
);
continue;
}
subagentStore.set(subagentProgressByToolCallId(invocationKey), null);
removeSubagentProgressAtoms(invocationKey);
}
},
[subagentStore],
);
const closeParentSubagentStreams = useCallback((): void => {
for (const invocationKey of listRegisteredSubagentProgressKeys()) {

View file

@ -46,6 +46,8 @@
"com_ui_attachments": "Attachments",
"com_ui_no_schedules_match": "No schedules match your search",
"com_ui_background_tasks_go_to_tool": "Take me to that tool",
"com_ui_background_tasks_open_subagent": "Open subagent",
"com_ui_background_tasks_subagent_unavailable": "This subagent task is unavailable. Refresh the task list and try again.",
"com_ui_background_tasks_tool_unavailable": "This tool is not in the loaded messages. Load earlier messages to find it.",
"com_ui_background_tasks": "Background tasks",
"com_ui_background_tasks_cancel_disabled": "Stopping background tools is not enabled on this server",
@ -3145,6 +3147,7 @@
"com_ui_storage": "Storage",
"com_ui_storage_filter_sort": "Filter and Sort by Storage",
"com_ui_subagent_back_to_parent": "Back to parent chat",
"com_ui_subagent_go_to_parent": "Go to parent chat",
"com_ui_subagent_activity": "Agent activity",
"com_ui_subagent_progress": "Progress",
"com_ui_subagent_progress_counts": "Turns {{0}} · Tool calls {{1}} · Failed {{2}}",

View file

@ -491,6 +491,7 @@ test.describe('unseen replies', () => {
const id = conversationId();
const title = `Withheld reply ${id.slice(0, 8)}`;
const replyAt = new Date(Date.now() - 2_000);
let completedReplyAt: Date;
await page.addInitScript(() => {
const constructions: string[] = [];
const calls: string[] = [];
@ -506,8 +507,8 @@ test.describe('unseen replies', () => {
}
close() {}
onclick: (() => void) | null = null;
constructor() {
constructions.push('notification');
constructor(_title: string, options?: NotificationOptions) {
constructions.push(options?.tag ?? '');
}
}
Object.defineProperty(window, 'Notification', {
@ -569,11 +570,19 @@ test.describe('unseen replies', () => {
await second.bringToFront();
await unfocus(page);
await sendMessageAndWaitForCompletion(second, `E2E_REPLY:withheld-${id.slice(0, 8)}`);
await restoreUnreadBaseline(id, now(), replyAt);
const completed = await readConversation(id);
if (completed?.lastResponseAt == null) throw new Error('Reply timestamp was not saved');
completedReplyAt = new Date(completed.lastResponseAt);
await restoreUnreadBaseline(id, completedReplyAt, replyAt);
} finally {
await second.evaluate(() => window.dispatchEvent(new Event('blur'))).catch(() => {});
await second.close();
}
/* The reply tab may collapse the shared sidebar; observe the arrival before granting. */
await openSidebar(page);
await expect(row.locator('span[aria-hidden="true"].bg-status-info')).toBeVisible({
timeout: 45_000,
});
await expect
.poll(() =>
page.evaluate(
@ -589,23 +598,19 @@ test.describe('unseen replies', () => {
window as Window & { __grantNotificationPermission: () => void }
).__grantNotificationPermission();
});
await restoreUnreadBaseline(id, now(), replyAt);
/* `sidebarExpanded` is stored per browser, so the reply tab's own mobile shell closed this
list while it was open. Looking at the list again is what a reader does, and it is where
the dot has to show. */
await openSidebar(page);
await expect(row.locator('span[aria-hidden="true"].bg-status-info')).toBeVisible({
timeout: 45_000,
});
await restoreUnreadBaseline(id, completedReplyAt, replyAt);
/* Other scenarios leave unseen history for this user; only this reply must notify once. */
await expect
.poll(() =>
page.evaluate(
() =>
(window as Window & { __notificationConstructions: string[] })
.__notificationConstructions,
(conversationId) =>
(
window as Window & { __notificationConstructions: string[] }
).__notificationConstructions.filter((tag) => tag === conversationId),
id,
),
)
.toEqual(['notification']);
.toEqual([id]);
} finally {
await cleanup(id);
}