Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion api/server/routes/convos.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ const subagentThreadViewHandler = createSubagentThreadViewHandler({
const childThreadMessagesHandler = createChildThreadMessagesHandler({
getConvoOwnership: db.getConvoOwnership,
getSubagentThreadForParent: db.getSubagentThreadForParent,
getMessages: db.getMessages,
getMessagesByCursor: db.getMessagesByCursor,
previewToolCalls: (req) => prepareToolCallPreviews(req, { getAppConfig }),
});
const childThreadToolCallPartHandler = createChildThreadToolCallPartHandler({
Expand Down
3 changes: 2 additions & 1 deletion client/src/Providers/SubagentsHostContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -140,9 +140,10 @@ function useThreadChat(
[transport, token],
);
const loadMessages = useCallback(
() =>
(cursor?: string) =>
dataService.getSubagentThreadMessages(parentConversationId, threadId, {
toolPreviews: true,
cursor,
}),
[parentConversationId, threadId],
);
Expand Down
36 changes: 34 additions & 2 deletions client/src/Providers/__tests__/SubagentsHostFollow.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react';
import { RecoilRoot } from 'recoil';
import { renderHook, waitFor } from '@testing-library/react';
import { TaskContentScopeContext } from '@librechat/chat/react';
import { act, renderHook, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { TMessage, ToolCallPartParams } from 'librechat-data-provider';

Expand Down Expand Up @@ -61,7 +61,7 @@ describe("the app's subagents host, following a child thread", () => {

it("reads the thread's messages through its parent, with tool previews", async () => {
mockStreamStatus.mockResolvedValue({ active: false });
mockThreadMessages.mockResolvedValue([brief]);
mockThreadMessages.mockResolvedValue({ messages: [brief], earlier: null });

const { result } = renderHook(
() =>
Expand All @@ -77,8 +77,40 @@ describe("the app's subagents host, following a child thread", () => {
expect(mockStreamStatus).toHaveBeenCalledWith('child-thread');
expect(mockThreadMessages).toHaveBeenCalledWith('parent-conversation', 'child-thread', {
toolPreviews: true,
cursor: undefined,
});
expect(result.current.isLoading).toBe(false);
expect(result.current.hasEarlier).toBe(false);
});

it('reads a long thread a page at a time, each earlier page by the cursor before it', async () => {
mockStreamStatus.mockResolvedValue({ active: false });
const older = { ...brief, messageId: 'earlier:user' };
mockThreadMessages.mockImplementation(async (_parent, _thread, options) =>
options.cursor == null
? { messages: [brief], earlier: 'cursor-1' }
: { messages: [older], earlier: null },
);

const { result } = renderHook(
() =>
appSubagentsHost.useThreadChat('parent-conversation', 'child-thread', {
live: false,
enabled: true,
}),
{ wrapper: wrapper() },
);
await waitFor(() => expect(result.current.hasEarlier).toBe(true));
expect(result.current.messages).toEqual([brief]);

act(() => result.current.loadEarlier());

await waitFor(() => expect(result.current.messages).toEqual([older, brief]));
expect(mockThreadMessages).toHaveBeenLastCalledWith('parent-conversation', 'child-thread', {
toolPreviews: true,
cursor: 'cursor-1',
});
expect(result.current.hasEarlier).toBe(false);
});

it('reports messages it could not read instead of an empty thread', async () => {
Expand Down
2 changes: 2 additions & 0 deletions client/src/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -1904,6 +1904,8 @@
"com_ui_tool_content_error": "Couldn't load the full tool call.",
"com_ui_tool_content_loading": "Loading the full tool call…",
"com_ui_during_run_actions": "More send options",
"com_ui_earlier_messages_error": "Earlier messages couldn't be loaded.",
"com_ui_earlier_messages_show": "Show earlier messages",
"com_ui_edit": "Edit",
"com_ui_edit_editing_image": "Editing image",
"com_ui_edit_files_removed": "Rerun to send without the removed files. Your original message stays available as an earlier version.",
Expand Down
98 changes: 98 additions & 0 deletions e2e/specs/mock/subagent-activity.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,104 @@ test.describe('detached subagent activity', () => {
}
}
});
test('reads a long child thread a page at a time, and the rest on request @scenario:subagent-panel-pages-child-history', async ({
page,
}) => {
test.setTimeout(120_000);
const label = `paged-${Date.now().toString(36)}`;
const childNames = [uniqueAgentName('E2E Paged Child A'), uniqueAgentName('E2E Paged Child B')];
const parentName = uniqueAgentName('E2E Paged Parent');
const createdAgentIds: string[] = [];
const cursor = '2026-01-01T00:00:00.000Z|64d4f005d73ef522e1f48818';
/** The cursors the page asked the thread's messages with, `null` for its newest page. */
const asked: Array<string | null> = [];

try {
await page.goto('/c/new');
const token = await getAccessToken(page);
const children: AgentDetail[] = [];
for (const childName of childNames) {
const child = await createAgent(page, token, childName);
children.push(child);
createdAgentIds.push(child.id);
}
const parent = await createAgent(page, token, parentName, {
enabled: true,
allowSelf: false,
agent_ids: children.map((child) => child.id),
});
createdAgentIds.push(parent.id);

await selectAgent(page, parentName);
const response = await sendMessageAndWaitForCompletion(
page,
`${DETACHED_ACTIVITY_MARKER}${children.map((child) => child.id).join(',')}:${label}`,
);
expect(response.ok()).toBeTruthy();

/** Both children run to their end, so the thread is read from storage alone. */
await page.getByRole('button', { name: 'Ran 2 agents' }).click();
const running = page.locator('[data-subagent-tool-call^="call_e2e_subagent_activity_"]');
await expect(running).toHaveCount(2, { timeout: 30_000 });
await expect(running.first()).toContainText('Completed', { timeout: 60_000 });
await expect(running.nth(1)).toContainText('Completed', { timeout: 60_000 });

/**
* The fixture's thread is two rows, which the server sends as one page. To see a thread
* longer than a page, its real rows are served as two pages of one: the reply first, and
* the brief behind a cursor. The paging itself (bounds, cursor, order) is the server's and
* is covered where it lives; this is the reader's side of it, in the real list.
*/
await page.route(
(url) => THREAD_MESSAGES_PATH.test(url.pathname),
async (route) => {
const url = new URL(route.request().url());
const asksFor = url.searchParams.get('cursor');
asked.push(asksFor);
url.searchParams.delete('cursor');
const upstream = await route.fetch({ url: url.toString() });
const body = (await upstream.json()) as { messages: TMessage[]; earlier: string | null };
expect(body.earlier).toBeNull();
const rows = body.messages;
await route.fulfill({
response: upstream,
json:
asksFor == null
? { messages: rows.slice(-1), earlier: cursor }
: { messages: rows.slice(0, -1), earlier: null },
});
},
);
await page.reload();

await page.getByRole('button', { name: 'Ran 2 agents' }).click();
const cards = page.locator('[data-subagent-tool-call^="call_e2e_subagent_activity_"]');
await expect(cards).toHaveCount(2, { timeout: 30_000 });
await cards.first().click();
const panel = childActivityPanel(page);
await expect(panel).toContainText(`E2E detached child 1 complete ${label}`, {
timeout: 30_000,
});

/** The newest page is on screen, and the reader is told there is more above it. */
const earlier = panel.getByRole('button', { name: 'Show earlier messages' });
await expect(earlier).toBeVisible();
await expect(panel.locator('.message-render')).toHaveCount(1);
expect(asked.filter((value) => value != null)).toHaveLength(0);

await earlier.click();

/** The page before it is read by its cursor and drawn above; nothing is left to offer. */
await expect(panel.locator('.message-render')).toHaveCount(2);
await expect(earlier).toHaveCount(0);
expect(asked.filter((value) => value != null)).toEqual([cursor]);
await expect(panel).toContainText(`E2E detached child 1 complete ${label}`);
} finally {
for (const agentId of createdAgentIds.reverse()) {
await cleanupAgent(page, agentId);
}
}
});
});

/** A subagent card's row is a picture of the child's thread, not part of this one: its folds
Expand Down
85 changes: 81 additions & 4 deletions packages/api/src/agents/view.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import type { ServerRequest } from '~/types';
import {
createChildThreadToolCallPartHandler,
createChildThreadMessagesHandler,
MAX_CHILD_MESSAGES_PAGE,
MAX_CHILD_MESSAGES_PAGE_BYTES,
createParentSubagentIndexHandler,
createSubagentThreadViewHandler,
PARENT_SUBAGENT_INDEX_LIMITS,
Expand Down Expand Up @@ -1588,7 +1590,10 @@ describe('child thread messages read through the parent', () => {
const deps = {
getConvoOwnership: jest.fn().mockResolvedValue(parent),
getSubagentThreadForParent: jest.fn().mockResolvedValue(child),
getMessages: jest.fn().mockResolvedValue(rows),
/** The reader returns a page newest first. */
getMessagesByCursor: jest
.fn()
.mockResolvedValue({ messages: [...rows].reverse(), nextCursor: null }),
previewToolCalls: jest.fn(() => (messages: unknown[]) => messages),
...overrides,
} as unknown as Parameters<typeof createChildThreadMessagesHandler>[0];
Expand All @@ -1605,9 +1610,17 @@ describe('child thread messages read through the parent', () => {

expect(status).toHaveBeenCalledWith(200);
expect(json).toHaveBeenCalledWith([...rows, { previewed: true }]);
expect(deps.getMessages).toHaveBeenCalledWith(
/** One bounded page, however much the thread holds. */
expect(deps.getMessagesByCursor).toHaveBeenCalledWith(
{ conversationId: threadId, user: 'user-1' },
'-_id -user',
{
sortField: 'createdAt',
sortOrder: -1,
limit: MAX_CHILD_MESSAGES_PAGE,
maxBytes: MAX_CHILD_MESSAGES_PAGE_BYTES,
cursor: null,
select: '-_id -user',
},
);
expect(deps.getSubagentThreadForParent).toHaveBeenCalledWith({
user: 'user-1',
Expand All @@ -1617,6 +1630,70 @@ describe('child thread messages read through the parent', () => {
});
});

const earlierCursor = '2026-11-15T10:00:00.000Z|64d4f005d73ef522e1f48818';

it('answers a paged request with the page, oldest first, and the cursor of the one before it', async () => {
const { deps, handler } = messagesHandler({
getMessagesByCursor: jest
.fn()
.mockResolvedValue({ messages: [...rows].reverse(), nextCursor: earlierCursor }),
});
const { response, status, json } = createResponse();

await handler(createRequest({}, { limit: '20' }), response);

expect(status).toHaveBeenCalledWith(200);
expect(json).toHaveBeenCalledWith({ messages: rows, earlier: earlierCursor });
expect(deps.getMessagesByCursor).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ limit: 20, cursor: null }),
);
});

it('reads the page before a cursor, and says when there is none before that', async () => {
const { deps, handler } = messagesHandler();
const { response, json } = createResponse();

await handler(createRequest({}, { cursor: earlierCursor }), response);

expect(json).toHaveBeenCalledWith({ messages: rows, earlier: null });
expect(deps.getMessagesByCursor).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ cursor: earlierCursor, limit: MAX_CHILD_MESSAGES_PAGE }),
);
});

it('never reads more than a page, whatever is asked for', async () => {
const { deps, handler } = messagesHandler();
const { response } = createResponse();

await handler(createRequest({}, { limit: '5000' }), response);

expect(deps.getMessagesByCursor).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
limit: MAX_CHILD_MESSAGES_PAGE,
maxBytes: MAX_CHILD_MESSAGES_PAGE_BYTES,
}),
);
});

it.each([
['a limit that is not a count', { limit: 'many' }],
['a limit below one', { limit: '0' }],
['a cursor that is not a page position', { cursor: 'latest' }],
['a cursor given twice', { cursor: [earlierCursor, earlierCursor] }],
])('answers 400 and reads nothing for %s', async (_name, query) => {
const { deps, handler } = messagesHandler();
const { response, status } = createResponse();

await handler(createRequest({}, query as Record<string, string>), response);

expect(status).toHaveBeenCalledWith(400);
expect(deps.getMessagesByCursor).not.toHaveBeenCalled();
expect(deps.getConvoOwnership).not.toHaveBeenCalled();
});

it("never sends an event thread's input, and keeps the row in place", async () => {
const { handler } = messagesHandler({
getSubagentThreadForParent: jest.fn().mockResolvedValue(eventChild),
Expand Down Expand Up @@ -1682,7 +1759,7 @@ describe('child thread messages read through the parent', () => {

it('answers 500 without the error text when the read fails', async () => {
const { handler } = messagesHandler({
getMessages: jest.fn().mockRejectedValue(new Error('mongo: secret detail')),
getMessagesByCursor: jest.fn().mockRejectedValue(new Error('mongo: secret detail')),
});
const { response, status, json } = createResponse();

Expand Down
Loading
Loading