diff --git a/api/server/routes/__test-utils__/convos-route-mocks.js b/api/server/routes/__test-utils__/convos-route-mocks.js index 33cd3fdf38..51cf415de0 100644 --- a/api/server/routes/__test-utils__/convos-route-mocks.js +++ b/api/server/routes/__test-utils__/convos-route-mocks.js @@ -156,6 +156,9 @@ module.exports = { }), createSubagentThreadViewHandler: jest.fn(() => (_req, res) => res.status(200).json({})), createSubagentTaskContentHandler: jest.fn(() => (_req, res) => res.status(200).json({})), + createChildThreadMessagesHandler: jest.fn(() => (_req, res) => res.status(200).json([])), + createChildThreadToolCallPartHandler: jest.fn(() => (_req, res) => res.status(200).json({})), + prepareToolCallPreviews: jest.fn(() => (messages) => messages), createSubagentControlHandler: jest.fn(() => (_req, res) => res.status(200).json({})), createSubagentControlReceiptHandler: () => jest.fn(), createBackgroundTaskIndexHandler: jest.fn( diff --git a/api/server/routes/convos.js b/api/server/routes/convos.js index 23c435c763..c1476d7f44 100644 --- a/api/server/routes/convos.js +++ b/api/server/routes/convos.js @@ -14,6 +14,9 @@ const { createArchiveHandler, createSubagentActivityStreamHandler, createSubagentTaskContentHandler, + createChildThreadMessagesHandler, + createChildThreadToolCallPartHandler, + prepareToolCallPreviews, createSubagentControlHandler, createSubagentControlReceiptHandler, isValidSubagentControlRequest, @@ -90,6 +93,17 @@ const subagentThreadViewHandler = createSubagentThreadViewHandler({ getSubagentThreadForParent: db.getSubagentThreadForParent, getMessagesForSubagentThreadView: db.getMessagesForSubagentThreadView, }); +const childThreadMessagesHandler = createChildThreadMessagesHandler({ + getConvoOwnership: db.getConvoOwnership, + getSubagentThreadForParent: db.getSubagentThreadForParent, + getMessages: db.getMessages, + previewToolCalls: (req) => prepareToolCallPreviews(req, { getAppConfig }), +}); +const childThreadToolCallPartHandler = createChildThreadToolCallPartHandler({ + getConvoOwnership: db.getConvoOwnership, + getSubagentThreadForParent: db.getSubagentThreadForParent, + getMessages: db.getMessages, +}); const parentSubagentIndexHandler = createParentSubagentIndexHandler({ getConvoOwnership: db.getConvoOwnership, listSubagentThreadsForParent: db.listSubagentThreadsForParent, @@ -312,6 +326,11 @@ router.post( backgroundTaskPolicy, backgroundTaskCancelHandler, ); +router.get('/:parentConversationId/subagents/:threadId/messages', childThreadMessagesHandler); +router.get( + '/:parentConversationId/subagents/:threadId/messages/:messageId/parts/:partIndex', + childThreadToolCallPartHandler, +); router.get('/:parentConversationId/subagents/:threadId', subagentThreadViewHandler); router.get( diff --git a/packages/api/src/agents/view.spec.ts b/packages/api/src/agents/view.spec.ts index b32f3ee4be..d7591cc2b2 100644 --- a/packages/api/src/agents/view.spec.ts +++ b/packages/api/src/agents/view.spec.ts @@ -2,6 +2,8 @@ import type { IConversation, IMessage } from '@librechat/data-schemas'; import type { Response } from 'express'; import type { ServerRequest } from '~/types'; import { + createChildThreadToolCallPartHandler, + createChildThreadMessagesHandler, createParentSubagentIndexHandler, createSubagentThreadViewHandler, PARENT_SUBAGENT_INDEX_LIMITS, @@ -1552,3 +1554,195 @@ describe('parent child-thread index', () => { expect(json.mock.calls[0][0].children).toEqual([]); }); }); + +describe('child thread messages read through the parent', () => { + const rows = [ + { + messageId: 'task-1:user', + conversationId: threadId, + parentMessageId: '00000000-0000-0000-0000-000000000000', + sender: 'User', + text: 'Investigate this.', + isCreatedByUser: true, + createdAt: '2026-11-15T10:00:00.000Z', + files: [{ file_id: 'file-1' }], + }, + { + messageId: 'task-1:assistant', + conversationId: threadId, + parentMessageId: 'task-1:user', + sender: 'researcher', + text: 'Finished the research.', + isCreatedByUser: false, + content: [{ type: 'text', text: 'Finished the research.' }], + }, + ]; + const eventChild = { + ...child, + subagentThread: { ...child.subagentThread, parentToolCallId: 'event-binding:binding-1' }, + } as IConversation; + + const messagesHandler = ( + overrides: Partial[0]> = {}, + ) => { + const deps = { + getConvoOwnership: jest.fn().mockResolvedValue(parent), + getSubagentThreadForParent: jest.fn().mockResolvedValue(child), + getMessages: jest.fn().mockResolvedValue(rows), + previewToolCalls: jest.fn(() => (messages: unknown[]) => messages), + ...overrides, + } as unknown as Parameters[0]; + return { deps, handler: createChildThreadMessagesHandler(deps) }; + }; + + it('returns the thread rows with the conversation projection and previews', async () => { + const { deps, handler } = messagesHandler({ + previewToolCalls: () => (messages) => [...messages, { previewed: true }], + }); + const { response, status, json } = createResponse(); + + await handler(createRequest(), response); + + expect(status).toHaveBeenCalledWith(200); + expect(json).toHaveBeenCalledWith([...rows, { previewed: true }]); + expect(deps.getMessages).toHaveBeenCalledWith( + { conversationId: threadId, user: 'user-1' }, + '-_id -user', + ); + expect(deps.getSubagentThreadForParent).toHaveBeenCalledWith({ + user: 'user-1', + parentConversationId, + conversationId: threadId, + tenantId: 'tenant-1', + }); + }); + + it("never sends an event thread's input, and keeps the row in place", async () => { + const { handler } = messagesHandler({ + getSubagentThreadForParent: jest.fn().mockResolvedValue(eventChild), + }); + const { response, json } = createResponse(); + + await handler(createRequest(), response); + + const [input, answer] = json.mock.calls[0][0]; + expect(input).toEqual({ + messageId: 'task-1:user', + conversationId: threadId, + parentMessageId: '00000000-0000-0000-0000-000000000000', + sender: 'User', + isCreatedByUser: true, + createdAt: '2026-11-15T10:00:00.000Z', + text: '', + }); + expect(JSON.stringify(input)).not.toContain('Investigate'); + expect(answer).toEqual(rows[1]); + }); + + it.each([ + ["the parent is not the requester's", { getConvoOwnership: jest.fn().mockResolvedValue(null) }], + [ + 'the thread is not found under that parent', + { getSubagentThreadForParent: jest.fn().mockResolvedValue(null) }, + ], + [ + 'the thread belongs to another parent', + { + getSubagentThreadForParent: jest.fn().mockResolvedValue({ + ...child, + subagentThread: { ...child.subagentThread, parentConversationId: 'someone-else' }, + }), + }, + ], + [ + 'the thread is in another tenant', + { + getSubagentThreadForParent: jest.fn().mockResolvedValue({ ...child, tenantId: 'tenant-2' }), + }, + ], + ])('answers 404 and sends no rows when %s', async (_name, overrides) => { + const { handler } = messagesHandler(overrides); + const { response, status, json } = createResponse(); + + await handler(createRequest(), response); + + expect(status).toHaveBeenCalledWith(404); + expect(JSON.stringify(json.mock.calls)).not.toContain('Finished the research.'); + }); + + it('answers 404 without reading anything when the thread is its own parent', async () => { + const { deps, handler } = messagesHandler(); + const { response, status } = createResponse(); + + await handler(createRequest({ threadId: parentConversationId }), response); + + expect(status).toHaveBeenCalledWith(404); + expect(deps.getConvoOwnership).not.toHaveBeenCalled(); + }); + + it('answers 500 without the error text when the read fails', async () => { + const { handler } = messagesHandler({ + getMessages: jest.fn().mockRejectedValue(new Error('mongo: secret detail')), + }); + const { response, status, json } = createResponse(); + + await handler(createRequest(), response); + + expect(status).toHaveBeenCalledWith(500); + expect(JSON.stringify(json.mock.calls)).not.toContain('secret detail'); + }); + + describe('a full tool-call part', () => { + const toolMessage = { + messageId: 'task-1:assistant', + content: [ + { + type: 'tool_call', + tool_call: { id: 'call-1', name: 'lookup', args: '{}', output: 'full' }, + }, + ], + }; + const partHandler = ( + overrides: Partial[0]> = {}, + ) => { + const deps = { + getConvoOwnership: jest.fn().mockResolvedValue(parent), + getSubagentThreadForParent: jest.fn().mockResolvedValue(child), + getMessages: jest.fn().mockResolvedValue([toolMessage]), + ...overrides, + } as unknown as Parameters[0]; + return { deps, handler: createChildThreadToolCallPartHandler(deps) }; + }; + const partRequest = () => + createRequest({ messageId: 'task-1:assistant', partIndex: '0' }, { toolCallId: 'call-1' }); + + it('reads the part from the thread once the parent check passes', async () => { + const { deps, handler } = partHandler(); + const { response, status, json } = createResponse(); + + await handler(partRequest(), response); + + expect(status).toHaveBeenCalledWith(200); + expect(json).toHaveBeenCalledWith({ + conversationId: threadId, + messageId: 'task-1:assistant', + partIndex: 0, + tool_call: toolMessage.content[0].tool_call, + }); + expect(deps.getMessages).toHaveBeenCalledWith( + { user: 'user-1', conversationId: threadId, messageId: 'task-1:assistant' }, + '-_id -user', + ); + }); + + it('answers 404 and sends no part when the parent check fails', async () => { + const { handler } = partHandler({ getConvoOwnership: jest.fn().mockResolvedValue(null) }); + const { response, status, json } = createResponse(); + + await handler(partRequest(), response); + + expect(status).toHaveBeenCalledWith(404); + expect(JSON.stringify(json.mock.calls)).not.toContain('full'); + }); + }); +}); diff --git a/packages/api/src/agents/view.ts b/packages/api/src/agents/view.ts index 5ee6b9e37d..bf2bdf52f1 100644 --- a/packages/api/src/agents/view.ts +++ b/packages/api/src/agents/view.ts @@ -1,4 +1,8 @@ -import { logger, SUBAGENT_TRANSCRIPT_SOURCE_BYTE_LIMIT } from '@librechat/data-schemas'; +import { + logger, + CLIENT_MESSAGE_SELECT, + SUBAGENT_TRANSCRIPT_SOURCE_BYTE_LIMIT, +} from '@librechat/data-schemas'; import type { ParentSubagentIndex, ParentSubagentSummary, @@ -17,6 +21,8 @@ import type { SubagentThreadViewMessageRecord, } from '@librechat/data-schemas'; import type { Response } from 'express'; +import type { MessageRequestValidation } from '~/middleware/messageValidation'; +import type { ToolCallPartDeps, ToolCallPartRequest } from '~/messages/parts'; import type { ServerRequest } from '~/types'; import { projectPersistedMessageActivity, @@ -24,6 +30,7 @@ import { projectSubagentActivity, SUBAGENT_ACTIVITY_LIMITS, } from './activity'; +import { createToolCallPartHandler } from '~/messages/parts'; const MAX_THREAD_MESSAGES = 50; const MAX_MESSAGE_TEXT_BYTES = 32 * 1024; @@ -839,3 +846,161 @@ export const PARENT_SUBAGENT_INDEX_LIMITS: Readonly<{ tasksPerChild: MAX_PARENT_TASKS_PER_CHILD, responseBytes: MAX_PARENT_INDEX_BYTES, }); + +type ChildThreadAccessDependencies = Pick< + ConversationMethods, + 'getConvoOwnership' | 'getSubagentThreadForParent' +>; + +type ChildThreadAccess = { + /** An event binding's thread, whose inputs are the raw payloads of external events. */ + eventThread: boolean; +}; + +/** The same parent, lineage and tenant check the durable thread view runs. Null refuses. */ +async function authorizeChildThread( + deps: ChildThreadAccessDependencies, + req: ServerRequest, +): Promise<(ChildThreadAccess & { threadId: string; userId: string }) | null> { + const userId = req.user?.id; + const tenantId = req.user?.tenantId || undefined; + const { parentConversationId, threadId } = req.params as SubagentThreadViewParams; + if ( + !userId || + !validConversationId(parentConversationId) || + !validConversationId(threadId) || + parentConversationId === threadId + ) { + return null; + } + const [parent, child] = await Promise.all([ + deps.getConvoOwnership(userId, parentConversationId, tenantId ?? null), + deps.getSubagentThreadForParent({ + user: userId, + parentConversationId, + conversationId: threadId, + ...(tenantId == null ? {} : { tenantId }), + }), + ]); + const lineage = child?.subagentThread; + if ( + parent == null || + child == null || + lineage == null || + lineage.parentConversationId !== parentConversationId || + !tenantMatches(parent.tenantId, tenantId) || + !tenantMatches(child.tenantId, tenantId) + ) { + return null; + } + return { threadId, userId, eventThread: lineage.parentToolCallId.startsWith('event-binding:') }; +} + +type ChildThreadMessage = { isCreatedByUser?: boolean; [field: string]: unknown }; + +/** What an event thread's input row may show: who and when, never the external payload. */ +const EVENT_INPUT_FIELDS = [ + 'messageId', + 'parentMessageId', + 'conversationId', + 'sender', + 'isCreatedByUser', + 'endpoint', + 'createdAt', + 'updatedAt', +] as const; + +/** + * An event thread's input is the raw payload of an external event. The durable thread view + * never sends it, and neither does this read: the row keeps its place in the thread with + * empty text. + */ +function withoutEventInput(message: ChildThreadMessage): ChildThreadMessage { + if (message.isCreatedByUser !== true) return message; + const visible: Record = { text: '' }; + for (const field of EVENT_INPUT_FIELDS) { + if (message[field] !== undefined) visible[field] = message[field]; + } + return visible; +} + +export type ChildThreadMessagesDependencies = ChildThreadAccessDependencies & { + getMessages: ( + filter: { conversationId: string; user: string }, + select: string, + ) => Promise; + /** The conversation messages route's tool-call previewer for this request. */ + previewToolCalls: ( + req: ServerRequest, + ) => (messages: ChildThreadMessage[]) => Promise | ChildThreadMessage[]; +}; + +/** + * `GET /api/convos/:parentConversationId/subagents/:threadId/messages`: a child thread's rows + * as the conversation messages route would send them, with the same projection and tool-call + * previews, reachable only through the parent the requester owns. The rows are read beside + * the access check and sent only once it passes. + */ +export function createChildThreadMessagesHandler(deps: ChildThreadMessagesDependencies) { + return async (req: ServerRequest, res: Response): Promise => { + try { + const previewToolCalls = deps.previewToolCalls(req); + const userId = req.user?.id; + const { threadId } = req.params as SubagentThreadViewParams; + const reading = + userId && validConversationId(threadId) + ? deps + .getMessages({ conversationId: threadId, user: userId }, CLIENT_MESSAGE_SELECT) + .then( + (messages) => ({ ok: true as const, messages }), + (error: unknown) => ({ ok: false as const, error }), + ) + : null; + const access = await authorizeChildThread(deps, req); + if (access == null || reading == null) { + notFound(res); + return; + } + const read = await reading; + if (!read.ok) throw read.error; + const messages = read.messages ?? []; + res + .status(200) + .json( + await previewToolCalls(access.eventThread ? messages.map(withoutEventInput) : messages), + ); + } catch (error) { + logger.error('[subagentThreads] Failed to read child thread messages', error); + res.status(500).json({ error: 'Failed to load child messages' }); + } + }; +} + +export type ChildThreadToolCallPartDependencies = ChildThreadAccessDependencies & ToolCallPartDeps; + +/** + * `GET /api/convos/:parentConversationId/subagents/:threadId/messages/:messageId/parts/:partIndex`: + * the full stored tool call behind a preview, read the way the conversation route reads it but + * authorized through the parent. + */ +export function createChildThreadToolCallPartHandler(deps: ChildThreadToolCallPartDependencies) { + const validate = (req: ToolCallPartRequest): MessageRequestValidation => ({ + shouldFetchMessages: true, + promise: authorizeChildThread(deps, req as unknown as ServerRequest).then((access) => + access == null + ? { ok: false, status: 404, body: { error: 'Tool call not found' } } + : { ok: true }, + ), + }); + const readPart = createToolCallPartHandler({ + getMessages: deps.getMessages, + validate, + sendValidationResponse: (res, result) => res.status(result.status).json(result.body), + }); + return (req: ServerRequest, res: Response): Promise => { + /** The shared reader addresses a message by its conversation, which here is the thread. */ + const params = req.params as SubagentThreadViewParams & { conversationId?: string }; + params.conversationId = params.threadId; + return readPart(req as unknown as ToolCallPartRequest, res); + }; +} diff --git a/packages/data-provider/specs/api-endpoints.spec.ts b/packages/data-provider/specs/api-endpoints.spec.ts index cd23d3403f..615a7bfe1a 100644 --- a/packages/data-provider/specs/api-endpoints.spec.ts +++ b/packages/data-provider/specs/api-endpoints.spec.ts @@ -11,6 +11,9 @@ import { acknowledgeTwoFactorSetup, finalizeTwoFactorSetup, cancelTwoFactorSetup, + messageToolCallPart, + subagentThreadMessages, + subagentThreadToolCallPart, } from '../src/api-endpoints'; describe('buildLoginRedirectUrl', () => { @@ -132,3 +135,38 @@ describe('required two-factor setup endpoints', () => { expect(cancelTwoFactorSetup()).toBe('/api/auth/2fa/setup/cancel'); }); }); + +describe('child thread read endpoints', () => { + it('reads a child thread through its parent, encoding both ids', () => { + expect(subagentThreadMessages('parent/1', 'thread 2')).toBe( + '/api/convos/parent%2F1/subagents/thread%202/messages', + ); + }); + + it('addresses a tool-call part under the thread, with the same identity query as a chat', () => { + const params = { + conversationId: 'thread 2', + messageId: 'task:assistant', + partIndex: 3, + toolCallId: 'call/1', + stepId: 'step 1', + }; + + expect(subagentThreadToolCallPart('parent/1', params)).toBe( + '/api/convos/parent%2F1/subagents/thread%202/messages/task%3Aassistant/parts/3?toolCallId=call%2F1&stepId=step%201', + ); + expect(messageToolCallPart(params)).toBe( + '/api/messages/thread%202/task%3Aassistant/parts/3?toolCallId=call%2F1&stepId=step%201', + ); + }); + + it('omits the query when the part has no identity', () => { + expect( + subagentThreadToolCallPart('parent', { + conversationId: 'thread', + messageId: 'm', + partIndex: 0, + }), + ).toBe('/api/convos/parent/subagents/thread/messages/m/parts/0'); + }); +}); diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.ts index f6d554a6f3..0603693a67 100644 --- a/packages/data-provider/src/api-endpoints.ts +++ b/packages/data-provider/src/api-endpoints.ts @@ -102,15 +102,11 @@ export const messageSubagentAttachmentCalls = ({ `${messagesRoot}/${encodeURIComponent(conversationId)}/${encodeURIComponent(messageId)}/subagent-calls?files=${encodeURIComponent(JSON.stringify(files))}`; /** One tool-call part of a stored message, in full. */ -export const messageToolCallPart = ({ - conversationId, - messageId, - partIndex, - toolCallId, - stepId, - agentId, -}: q.ToolCallPartParams) => { - const path = `${messagesRoot}/${encodeURIComponent(conversationId)}/${encodeURIComponent(messageId)}/parts/${partIndex}`; +/** The identity a stored tool-call part is read by, as a query string appended to `path`. */ +const withToolCallIdentity = ( + path: string, + { toolCallId, stepId, agentId }: Pick, +) => { const query = [ ['toolCallId', toolCallId], ['stepId', stepId], @@ -122,6 +118,12 @@ export const messageToolCallPart = ({ return query === '' ? path : `${path}?${query}`; }; +export const messageToolCallPart = (params: q.ToolCallPartParams) => + withToolCallIdentity( + `${messagesRoot}/${encodeURIComponent(params.conversationId)}/${encodeURIComponent(params.messageId)}/parts/${params.partIndex}`, + params, + ); + export const messagesBranch = () => `${messagesRoot}/branch`; const shareRoot = `${BASE_URL}/api/share`; @@ -184,6 +186,20 @@ export const subagentThread = ( return cursor == null ? endpoint : `${endpoint}?cursor=${encodeURIComponent(cursor)}`; }; +/** A child thread's messages, read through the parent conversation that owns it. */ +export const subagentThreadMessages = (parentConversationId: string, threadId: string) => + `${parentSubagents(parentConversationId)}/${encodeURIComponent(threadId)}/messages`; + +/** One full tool-call part of a child thread's message; `conversationId` is the thread. */ +export const subagentThreadToolCallPart = ( + parentConversationId: string, + params: q.ToolCallPartParams, +) => + withToolCallIdentity( + `${subagentThreadMessages(parentConversationId, params.conversationId)}/${encodeURIComponent(params.messageId)}/parts/${params.partIndex}`, + params, + ); + export const subagentTaskContent = ( parentConversationId: string, threadId: string, diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.ts index 92791db818..c1007b9523 100644 --- a/packages/data-provider/src/data-service.ts +++ b/packages/data-provider/src/data-service.ts @@ -1523,6 +1523,24 @@ export function getSubagentThread( return request.get(endpoints.subagentThread(parentConversationId, threadId, taskId, cursor)); } +/** A child thread's messages, in the shape and with the previews of a conversation load. */ +export function getSubagentThreadMessages( + parentConversationId: string, + threadId: string, + options?: { toolPreviews?: boolean }, +): Promise { + const url = endpoints.subagentThreadMessages(parentConversationId, threadId); + return request.get(options?.toolPreviews === true ? withToolCallPreviews(url) : url); +} + +/** The full tool call behind a preview in a child thread; `params.conversationId` is the thread. */ +export function getSubagentThreadToolCallPart( + parentConversationId: string, + params: q.ToolCallPartParams, +): Promise { + return request.get(endpoints.subagentThreadToolCallPart(parentConversationId, params)); +} + export function getSubagentTaskContent( parentConversationId: string, threadId: string,