From b664c756bb1dd661f0ec632571e7732ac9fd8ac8 Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:37:32 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=B7=20refactor:=20Move=20Subagent=20Di?= =?UTF-8?q?spatch=20and=20Attachment=20Routing=20Into=20@librechat/chat=20?= =?UTF-8?q?(#17632)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * refactor: Move Subagent Dispatch and Attachment Routing Into @librechat/chat * refactor: Keep Only the Stored Attachment Query Hook in the Client --- .../Chat/Messages/Content/ContentParts.tsx | 17 +- .../components/Chat/Messages/ui/WakeupRow.tsx | 2 +- .../components/Chat/Subagents/attachments.ts | 295 +---------------- .../src/components/Chat/Subagents/author.tsx | 2 +- .../core/subagents/__tests__/dispatch.spec.ts | 2 +- .../chat/src/core/subagents}/dispatch.ts | 8 +- packages/chat/src/core/subagents/index.ts | 1 + .../subagents/__tests__/attachments.spec.ts | 6 +- .../chat/src/react/subagents/attachments.ts | 304 ++++++++++++++++++ packages/chat/src/react/subagents/index.ts | 1 + 10 files changed, 328 insertions(+), 310 deletions(-) rename client/src/components/Chat/Subagents/dispatch.test.ts => packages/chat/src/core/subagents/__tests__/dispatch.spec.ts (97%) rename {client/src/components/Chat/Subagents => packages/chat/src/core/subagents}/dispatch.ts (90%) rename client/src/components/Chat/Subagents/attachments.test.ts => packages/chat/src/react/subagents/__tests__/attachments.spec.ts (98%) create mode 100644 packages/chat/src/react/subagents/attachments.ts diff --git a/client/src/components/Chat/Messages/Content/ContentParts.tsx b/client/src/components/Chat/Messages/Content/ContentParts.tsx index 48cd329a47..628197b08e 100644 --- a/client/src/components/Chat/Messages/Content/ContentParts.tsx +++ b/client/src/components/Chat/Messages/Content/ContentParts.tsx @@ -7,6 +7,11 @@ import { ToolDisclosureContext, ToolDisclosureKeyContext, SoleToolContext, + assignNestedAttachments, + useLiveSubagentToolCalls, + SubagentAttachmentsContext, + selectExactlyNestedAttachments, + selectUnclaimedAttachments, } from '@librechat/chat/react'; import type { SubagentAttachmentFile, @@ -15,20 +20,11 @@ import type { TAttachment, Agents, } from 'librechat-data-provider'; -import type { ReasoningDisclosures, ToolDisclosures } from '@librechat/chat/react'; +import type { ReasoningDisclosures, ToolDisclosures, NestedCall } from '@librechat/chat/react'; import type { ReactNode, ReactElement } from 'react'; -import type { NestedCall } from '~/components/Chat/Subagents/attachments'; import type { ToolCallGroupExpansionState } from './ToolCallGroup'; import type { ActivityPhaseSegment } from '~/utils/activityLabels'; import type { MCPAppResourceOccurrence } from '~/utils/mcpApps'; -import { - assignNestedAttachments, - useLiveSubagentToolCalls, - SubagentAttachmentsContext, - useStoredSubagentHints, - selectExactlyNestedAttachments, - selectUnclaimedAttachments, -} from '~/components/Chat/Subagents/attachments'; import { mapAttachments, getPartKeyIndex, @@ -44,6 +40,7 @@ import { } from '~/utils/activityLabels'; import WorkspaceChanges, { partitionWorkspaceChanges } from './Parts/WorkspaceChanges'; import { MCPAppSuppressionContext, MCPAppViews } from '~/components/MCPUIResource'; +import { useStoredSubagentHints } from '~/components/Chat/Subagents/attachments'; import { ParallelContentRenderer, type PartWithIndex } from './ParallelContent'; import { isPreviewedToolCallPart, PreviewedToolCallPart } from './hydration'; import { MediaContext, MessageContext, SearchContext } from '~/Providers'; diff --git a/client/src/components/Chat/Messages/ui/WakeupRow.tsx b/client/src/components/Chat/Messages/ui/WakeupRow.tsx index fe55b7dd24..dfaae433a9 100644 --- a/client/src/components/Chat/Messages/ui/WakeupRow.tsx +++ b/client/src/components/Chat/Messages/ui/WakeupRow.tsx @@ -1,4 +1,5 @@ import { useMemo } from 'react'; +import { findSubagentDispatch } from '@librechat/chat'; import { MessageRow } from '@librechat/chat/components'; import type { WakeupTask } from '@librechat/chat'; import type { ComponentProps } from 'react'; @@ -10,7 +11,6 @@ import { } from '~/components/Chat/Subagents/author'; import { useParentSubagents } from '~/components/Chat/Subagents/ParentSubagentsProvider'; import { useOptionalMessagesOperations } from '~/Providers/MessagesViewContext'; -import { findSubagentDispatch } from '~/components/Chat/Subagents/dispatch'; import { useShareContext } from '~/Providers/ShareContext'; import { useAgentsMapContext } from '~/Providers'; import { useLocalize } from '~/hooks'; diff --git a/client/src/components/Chat/Subagents/attachments.ts b/client/src/components/Chat/Subagents/attachments.ts index 4ac6789407..32b38a3d56 100644 --- a/client/src/components/Chat/Subagents/attachments.ts +++ b/client/src/components/Chat/Subagents/attachments.ts @@ -1,270 +1,13 @@ -import { createContext, useEffect, useMemo, useRef } from 'react'; -import { Constants } from 'librechat-data-provider'; -import { atom, useStore, useAtomValue } from 'jotai'; -import { - nestedToolCallOf, - collectNestedCalls, - subagentProgressKey, - retainSubagentProgress, - rememberSubagentChildCalls, - rememberedSubagentChildCalls, - subagentProgressByToolCallId, -} from '@librechat/chat/react'; +import { useMemo } from 'react'; +import { hasOmittedSubagentContent, routeStoredSubagentHints } from '@librechat/chat/react'; import type { - Agents, - TAttachment, - FullToolCall, TMessageContentParts, SubagentAttachmentFile, SubagentAttachmentCallsResponse, } from 'librechat-data-provider'; -import type { SubagentContentPart } from '@librechat/chat'; +import type { NestedCall } from '@librechat/chat/react'; import { useSubagentAttachmentCallsQueries } from '~/data-provider'; -export { collectNestedCalls }; -import { getPartKeyIndex } from '~/utils/messages'; - -type NestedPart = TMessageContentParts | SubagentContentPart | undefined; -/** A tool call inside a subagent run, with the scope its files may carry. */ -export type NestedCall = Agents.SubagentAttachmentCall; - -const EMPTY: TAttachment[] = []; -const NO_LIVE_CALLS: ReadonlyMap = new Map(); -const NO_NESTED: ReadonlyMap = new Map(); - -/** - * The files each tool call part of the message owns through its subagent run, - * keyed by the part. A tool run inside a subagent saves its files under the - * child tool call id, which only appears inside the parent `subagent` call. The - * message assigns them once, so every body it splits into reads one answer. - */ -export const SubagentAttachmentsContext = - createContext>(NO_NESTED); - -/** - * The ownership rule top-level parts apply: a scope both sides carry must - * agree. `exact` also requires the call to carry every scope the file does, so - * a call whose scope is still unknown cannot take a file a scoped call owns. - */ -const ownsAttachment = (call: NestedCall, attachment: TAttachment, exact: boolean): boolean => { - const { agentId, stepId } = attachment as { agentId?: string; stepId?: string }; - const agrees = (own: string | undefined, file: string | undefined) => - file == null || (own == null ? !exact : own === file); - return ( - call.id === attachment.toolCallId && - agrees(call.agentId, agentId) && - agrees(call.stepId, stepId) - ); -}; - -/** Tool attachments that `claimed` (what the top-level parts accept) leaves out. */ -export function selectUnclaimedAttachments( - attachments: TAttachment[], - claimed: ReadonlySet, -): TAttachment[] { - const unclaimed = attachments.filter( - (attachment) => attachment.toolCallId != null && !claimed.has(attachment), - ); - return unclaimed.length > 0 ? unclaimed : EMPTY; -} - -/** Each tool call part of `content` with the child calls of its stored, previewed or live run. */ -function collectNestedOwners( - content: ReadonlyArray | undefined, - live: ReadonlyMap, -): Array<[NestedPart, NestedCall[]]> { - const owners: Array<[NestedPart, NestedCall[]]> = []; - (content ?? []).forEach((part, index) => { - const toolCall = nestedToolCallOf(part); - if (toolCall == null) { - return; - } - const calls = collectNestedCalls( - toolCall.subagent_content, - [], - toolCall.subagentIdentity?.subagentAgentId, - ); - calls.push(...(toolCall.subagentAttachmentCalls ?? []), ...(live.get(index) ?? [])); - if (calls.length > 0) { - owners.push([part, calls]); - } - }); - return owners; -} - -/** - * Attachments a child call inside some subagent run owns under its full scope. - * A top-level call that only matches them by id, without that scope, must not - * take them first. - */ -export function selectExactlyNestedAttachments( - content: ReadonlyArray | undefined, - attachments: TAttachment[], - live: ReadonlyMap, -): ReadonlySet { - const owners = collectNestedOwners(content, live); - const reserved = new Set(); - if (owners.length === 0) { - return reserved; - } - for (const attachment of attachments) { - if (owners.some(([, calls]) => calls.some((call) => ownsAttachment(call, attachment, true)))) { - reserved.add(attachment); - } - } - return reserved; -} - -/** - * Hands each unclaimed attachment to one tool call part of the message whose - * transcript (stored, previewed, or streaming in `live`, keyed by content - * index) holds the tool call it was saved under. A part whose call matches the - * file's full scope is preferred over one whose scope is still unknown; within - * each pass the first part in message order wins, so a child id two subagents - * share renders the file once. The map is keyed by the part itself, so two - * calls sharing an id keep their own files. - */ -export function assignNestedAttachments( - content: ReadonlyArray | undefined, - unclaimed: TAttachment[], - live: ReadonlyMap, -): ReadonlyMap { - if (unclaimed.length === 0) { - return NO_NESTED; - } - const owners = collectNestedOwners(content, live); - const assigned = new Map(); - for (const attachment of unclaimed) { - const owner = - owners.find(([, calls]) => calls.some((call) => ownsAttachment(call, attachment, true))) ?? - owners.find(([, calls]) => calls.some((call) => ownsAttachment(call, attachment, false))); - if (owner == null) { - continue; - } - const files = assigned.get(owner[0]) ?? []; - files.push(attachment); - assigned.set(owner[0], files); - } - return assigned.size > 0 ? assigned : NO_NESTED; -} - -/** - * Child tool calls the live progress of each subagent call in `content` holds, - * keyed by the call's index in `content`. Until the run is saved, and for a - * file a background task delivers after the message settled, those calls exist - * only there. The atom yields a signature string so the caller re-renders when - * a child call appears, not on every delta. Each member it reads is retained - * like a card's, so one no update ever reached is freed on unmount. Calls - * already seen are kept with the invocation (`rememberSubagentChildCalls`), - * since the bounded live activity evicts early parts before the transcript is - * saved. - */ -export function useLiveSubagentToolCalls( - content: ReadonlyArray | undefined, - attachments: ReadonlyArray | undefined, - messageId: string, - contentIndices: ReadonlyArray | undefined, - contentIndexOffset: number, -): ReadonlyMap { - /** Only calls a file of this message names matter for routing, so the - * signature carries those rather than the invocation's whole history. */ - const idSignature = useMemo( - () => - [...new Set((attachments ?? []).map((attachment) => attachment.toolCallId ?? ''))] - .filter(Boolean) - .sort() - .join('\u0000'), - [attachments], - ); - /** A string, so the keys (and the atom reading them) survive the content - * array changing on every streamed delta. */ - const keySignature = useMemo(() => { - const entries: Array<[number, string]> = []; - (content ?? []).forEach((part, index) => { - const toolCall = nestedToolCallOf(part); - if (toolCall?.id && toolCall.name === Constants.SUBAGENT) { - entries.push([ - index, - subagentProgressKey( - messageId, - toolCall.id, - getPartKeyIndex(part, contentIndices?.[index] ?? index + contentIndexOffset), - ), - ]); - } - }); - return entries.length === 0 ? '' : JSON.stringify(entries); - }, [content, messageId, contentIndices, contentIndexOffset]); - const keys = useMemo( - () => (keySignature === '' ? [] : (JSON.parse(keySignature) as Array<[number, string]>)), - [keySignature], - ); - const store = useStore(); - /** Retained one key at a time: releasing a key that is still read would free - * the member under the atom subscribed to it. */ - const retained = useRef(new Map void>()); - useEffect(() => { - const next = new Set(keys.map(([, key]) => key)); - for (const [key, release] of retained.current) { - if (!next.has(key)) { - release(); - retained.current.delete(key); - } - } - for (const key of next) { - if (!retained.current.has(key)) { - retained.current.set(key, retainSubagentProgress(store, key)); - } - } - }, [keys, store]); - useEffect(() => { - const held = retained.current; - return () => { - held.forEach((release) => release()); - held.clear(); - }; - }, []); - /** Built from everything the invocation has shown, not only its current - * activity: a write the progress setter remembered and a later write that - * evicted the same call can land in one batch. */ - const signatureAtom = useMemo( - () => - atom((get) => { - const ids = new Set(idSignature === '' ? [] : idSignature.split('\u0000')); - const live: Array<[number, NestedCall[]]> = []; - for (const [index, key] of keys) { - const progress = get(subagentProgressByToolCallId(key)); - const owners = rememberedSubagentChildCalls(key, ids); - /** The owners of this message's files are refreshed as the newest - * entries, so the bounded history cannot age them out while it shows. */ - rememberSubagentChildCalls(key, owners, true); - rememberSubagentChildCalls( - key, - collectNestedCalls(progress?.contentParts, [], progress?.subagentAgentId), - ); - const calls = rememberedSubagentChildCalls(key, ids); - if (calls.length > 0) { - live.push([index, calls]); - } - } - return live.length === 0 ? '' : JSON.stringify(live); - }), - [keys, idSignature], - ); - const signature = useAtomValue(signatureAtom); - return useMemo( - () => - signature === '' - ? NO_LIVE_CALLS - : new Map(JSON.parse(signature) as Array<[number, NestedCall[]]>), - [signature], - ); -} - -/** The identity a stored part and its cached preview share. */ -const identityOf = (toolCallId: string, stepId?: string, agentId?: string) => - [toolCallId, stepId ?? '', agentId ?? ''].join('\u0000'); - /** * Child calls of the stored transcripts of the previewed subagent calls in `content`, for the * files whose owner is in doubt, keyed by the call's index in `content`. A file a background task @@ -277,14 +20,7 @@ export function useStoredSubagentHints( conversationId: string | null | undefined, messageId: string, ): ReadonlyMap { - const previewed = useMemo( - () => - (content ?? []).some( - (part) => - (nestedToolCallOf(part) as FullToolCall | undefined)?.subagentContentOmitted === true, - ), - [content], - ); + const previewed = useMemo(() => hasOmittedSubagentContent(content), [content]); const results = useSubagentAttachmentCallsQueries( { conversationId: conversationId ?? '', messageId, files }, previewed && files.length > 0 && !!conversationId && !!messageId, @@ -295,27 +31,6 @@ export function useStoredSubagentHints( const parts = ( JSON.parse(answers) as Array ).flatMap((batch) => batch ?? []); - if (parts.length === 0 || !previewed) { - return NO_LIVE_CALLS; - } - const byIdentity = new Map(); - for (const entry of parts) { - const identity = identityOf(entry.toolCallId, entry.stepId, entry.agentId); - byIdentity.set(identity, [...(byIdentity.get(identity) ?? []), ...entry.calls]); - } - const byIndex = new Map(); - (content ?? []).forEach((part, index) => { - const toolCall = nestedToolCallOf(part) as FullToolCall | undefined; - if (toolCall?.subagentContentOmitted !== true || !toolCall.id) { - return; - } - const calls = byIdentity.get( - identityOf(toolCall.id, toolCall.stepId, (part as { agentId?: string }).agentId), - ); - if (calls != null) { - byIndex.set(index, calls); - } - }); - return byIndex.size > 0 ? byIndex : NO_LIVE_CALLS; + return routeStoredSubagentHints(previewed ? content : undefined, parts); }, [answers, previewed, content]); } diff --git a/client/src/components/Chat/Subagents/author.tsx b/client/src/components/Chat/Subagents/author.tsx index 04361280a0..5dc9821410 100644 --- a/client/src/components/Chat/Subagents/author.tsx +++ b/client/src/components/Chat/Subagents/author.tsx @@ -1,12 +1,12 @@ import { useMemo, useSyncExternalStore } from 'react'; import { useQueryClient } from '@tanstack/react-query'; +import { findSubagentDispatch } from '@librechat/chat'; import { isDocumentId } from '@librechat/chat/components'; import { EModelEndpoint, QueryKeys, ContentTypes } from 'librechat-data-provider'; import type { Agent, TMessage } from 'librechat-data-provider'; import type { ReactNode } from 'react'; import MessageIcon from '~/components/Chat/Messages/MessageIcon'; import { useAgentsMapContext } from '~/Providers'; -import { findSubagentDispatch } from './dispatch'; /** Who wrote a turn, in the form main chat's message header shows an author. */ export type TurnAuthor = { name: string; icon: ReactNode; agent?: Agent; agentId?: string }; diff --git a/client/src/components/Chat/Subagents/dispatch.test.ts b/packages/chat/src/core/subagents/__tests__/dispatch.spec.ts similarity index 97% rename from client/src/components/Chat/Subagents/dispatch.test.ts rename to packages/chat/src/core/subagents/__tests__/dispatch.spec.ts index dc1755ef6e..8b6549011f 100644 --- a/client/src/components/Chat/Subagents/dispatch.test.ts +++ b/packages/chat/src/core/subagents/__tests__/dispatch.spec.ts @@ -1,6 +1,6 @@ import { ContentTypes } from 'librechat-data-provider'; import type { TMessage } from 'librechat-data-provider'; -import { findSubagentDispatch } from './dispatch'; +import { findSubagentDispatch } from '../dispatch'; const output = JSON.stringify({ background_task_id: 'task', diff --git a/client/src/components/Chat/Subagents/dispatch.ts b/packages/chat/src/core/subagents/dispatch.ts similarity index 90% rename from client/src/components/Chat/Subagents/dispatch.ts rename to packages/chat/src/core/subagents/dispatch.ts index 33bf42dd68..c0baf64658 100644 --- a/client/src/components/Chat/Subagents/dispatch.ts +++ b/packages/chat/src/core/subagents/dispatch.ts @@ -1,22 +1,22 @@ -import { parseSubagentBackgroundHandle } from '@librechat/chat'; import { Constants, ContentTypes } from 'librechat-data-provider'; import type { SubagentIdentity, TMessage } from 'librechat-data-provider'; +import { parseSubagentBackgroundHandle } from '../parts'; -type Dispatch = { +export type SubagentDispatch = { message: TMessage; subagentType: string; identity?: SubagentIdentity; agentId?: string; }; -const indexes = new WeakMap>(); +const indexes = new WeakMap>(); /** Public transcripts carry dispatch metadata instead of an authenticated child * index. Match the host-issued handle, sharing one scan per transcript snapshot. */ export function findSubagentDispatch( messages: TMessage[] | undefined, threadId: string | undefined, -): Dispatch | undefined { +): SubagentDispatch | undefined { if (messages == null || !threadId) return undefined; let index = indexes.get(messages); if (index == null) { diff --git a/packages/chat/src/core/subagents/index.ts b/packages/chat/src/core/subagents/index.ts index 7b367d1463..cde3238865 100644 --- a/packages/chat/src/core/subagents/index.ts +++ b/packages/chat/src/core/subagents/index.ts @@ -1 +1,2 @@ export * from './content'; +export * from './dispatch'; diff --git a/client/src/components/Chat/Subagents/attachments.test.ts b/packages/chat/src/react/subagents/__tests__/attachments.spec.ts similarity index 98% rename from client/src/components/Chat/Subagents/attachments.test.ts rename to packages/chat/src/react/subagents/__tests__/attachments.spec.ts index fd8f10f16e..db5a0ad52f 100644 --- a/client/src/components/Chat/Subagents/attachments.test.ts +++ b/packages/chat/src/react/subagents/__tests__/attachments.spec.ts @@ -1,10 +1,10 @@ import type { TAttachment, TMessageContentParts } from 'librechat-data-provider'; import { - collectNestedCalls, assignNestedAttachments, selectUnclaimedAttachments, selectExactlyNestedAttachments, -} from './attachments'; +} from '../attachments'; +import { collectNestedCalls } from '../state'; const file = (toolCallId?: string) => ({ file_id: `file-${toolCallId}`, toolCallId }) as TAttachment; @@ -142,7 +142,7 @@ describe('subagent attachments', () => { } const calls = collectNestedCalls([deepest]); expect(calls).toHaveLength(10_001); - expect(calls.at(-1)).toEqual({ id: 'deepest-call' }); + expect(calls[calls.length - 1]).toEqual({ id: 'deepest-call' }); }); it('uses the run owner for its own top-level calls only', () => { diff --git a/packages/chat/src/react/subagents/attachments.ts b/packages/chat/src/react/subagents/attachments.ts new file mode 100644 index 0000000000..8d5a60adf3 --- /dev/null +++ b/packages/chat/src/react/subagents/attachments.ts @@ -0,0 +1,304 @@ +import { createContext, useEffect, useMemo, useRef } from 'react'; +import { Constants } from 'librechat-data-provider'; +import { atom, useStore, useAtomValue } from 'jotai'; +import type { + Agents, + TAttachment, + FullToolCall, + TMessageContentParts, + SubagentAttachmentCallsResponse, +} from 'librechat-data-provider'; +import type { Context } from 'react'; +import type { SubagentContentPart } from '../../core/subagents'; +import { + nestedToolCallOf, + collectNestedCalls, + subagentProgressKey, + retainSubagentProgress, + rememberSubagentChildCalls, + rememberedSubagentChildCalls, + subagentProgressByToolCallId, +} from './state'; +import { getPartKeyIndex } from '../../core/content'; + +export type NestedPart = TMessageContentParts | SubagentContentPart | undefined; +/** A tool call inside a subagent run, with the scope its files may carry. */ +export type NestedCall = Agents.SubagentAttachmentCall; + +const EMPTY: TAttachment[] = []; +const NO_LIVE_CALLS: ReadonlyMap = new Map(); +const NO_NESTED: ReadonlyMap = new Map(); + +/** + * The files each tool call part of the message owns through its subagent run, + * keyed by the part. A tool run inside a subagent saves its files under the + * child tool call id, which only appears inside the parent `subagent` call. The + * message assigns them once, so every body it splits into reads one answer. + */ +export const SubagentAttachmentsContext: Context> = + createContext>(NO_NESTED); + +/** + * The ownership rule top-level parts apply: a scope both sides carry must + * agree. `exact` also requires the call to carry every scope the file does, so + * a call whose scope is still unknown cannot take a file a scoped call owns. + */ +const ownsAttachment = (call: NestedCall, attachment: TAttachment, exact: boolean): boolean => { + const { agentId, stepId } = attachment as { agentId?: string; stepId?: string }; + const agrees = (own: string | undefined, file: string | undefined) => + file == null || (own == null ? !exact : own === file); + return ( + call.id === attachment.toolCallId && + agrees(call.agentId, agentId) && + agrees(call.stepId, stepId) + ); +}; + +/** Tool attachments that `claimed` (what the top-level parts accept) leaves out. */ +export function selectUnclaimedAttachments( + attachments: TAttachment[], + claimed: ReadonlySet, +): TAttachment[] { + const unclaimed = attachments.filter( + (attachment) => attachment.toolCallId != null && !claimed.has(attachment), + ); + return unclaimed.length > 0 ? unclaimed : EMPTY; +} + +/** Each tool call part of `content` with the child calls of its stored, previewed or live run. */ +function collectNestedOwners( + content: ReadonlyArray | undefined, + live: ReadonlyMap, +): Array<[NestedPart, NestedCall[]]> { + const owners: Array<[NestedPart, NestedCall[]]> = []; + (content ?? []).forEach((part, index) => { + const toolCall = nestedToolCallOf(part); + if (toolCall == null) { + return; + } + const calls = collectNestedCalls( + toolCall.subagent_content, + [], + toolCall.subagentIdentity?.subagentAgentId, + ); + calls.push(...(toolCall.subagentAttachmentCalls ?? []), ...(live.get(index) ?? [])); + if (calls.length > 0) { + owners.push([part, calls]); + } + }); + return owners; +} + +/** + * Attachments a child call inside some subagent run owns under its full scope. + * A top-level call that only matches them by id, without that scope, must not + * take them first. + */ +export function selectExactlyNestedAttachments( + content: ReadonlyArray | undefined, + attachments: TAttachment[], + live: ReadonlyMap, +): ReadonlySet { + const owners = collectNestedOwners(content, live); + const reserved = new Set(); + if (owners.length === 0) { + return reserved; + } + for (const attachment of attachments) { + if (owners.some(([, calls]) => calls.some((call) => ownsAttachment(call, attachment, true)))) { + reserved.add(attachment); + } + } + return reserved; +} + +/** + * Hands each unclaimed attachment to one tool call part of the message whose + * transcript (stored, previewed, or streaming in `live`, keyed by content + * index) holds the tool call it was saved under. A part whose call matches the + * file's full scope is preferred over one whose scope is still unknown; within + * each pass the first part in message order wins, so a child id two subagents + * share renders the file once. The map is keyed by the part itself, so two + * calls sharing an id keep their own files. + */ +export function assignNestedAttachments( + content: ReadonlyArray | undefined, + unclaimed: TAttachment[], + live: ReadonlyMap, +): ReadonlyMap { + if (unclaimed.length === 0) { + return NO_NESTED; + } + const owners = collectNestedOwners(content, live); + const assigned = new Map(); + for (const attachment of unclaimed) { + const owner = + owners.find(([, calls]) => calls.some((call) => ownsAttachment(call, attachment, true))) ?? + owners.find(([, calls]) => calls.some((call) => ownsAttachment(call, attachment, false))); + if (owner == null) { + continue; + } + const files = assigned.get(owner[0]) ?? []; + files.push(attachment); + assigned.set(owner[0], files); + } + return assigned.size > 0 ? assigned : NO_NESTED; +} + +/** + * Child tool calls the live progress of each subagent call in `content` holds, + * keyed by the call's index in `content`. Until the run is saved, and for a + * file a background task delivers after the message settled, those calls exist + * only there. The atom yields a signature string so the caller re-renders when + * a child call appears, not on every delta. Each member it reads is retained + * like a card's, so one no update ever reached is freed on unmount. Calls + * already seen are kept with the invocation (`rememberSubagentChildCalls`), + * since the bounded live activity evicts early parts before the transcript is + * saved. + */ +export function useLiveSubagentToolCalls( + content: ReadonlyArray | undefined, + attachments: ReadonlyArray | undefined, + messageId: string, + contentIndices: ReadonlyArray | undefined, + contentIndexOffset: number, +): ReadonlyMap { + /** Only calls a file of this message names matter for routing, so the + * signature carries those rather than the invocation's whole history. */ + const idSignature = useMemo( + () => + [...new Set((attachments ?? []).map((attachment) => attachment.toolCallId ?? ''))] + .filter(Boolean) + .sort() + .join('\u0000'), + [attachments], + ); + /** A string, so the keys (and the atom reading them) survive the content + * array changing on every streamed delta. */ + const keySignature = useMemo(() => { + const entries: Array<[number, string]> = []; + (content ?? []).forEach((part, index) => { + const toolCall = nestedToolCallOf(part); + if (toolCall?.id && toolCall.name === Constants.SUBAGENT) { + entries.push([ + index, + subagentProgressKey( + messageId, + toolCall.id, + getPartKeyIndex(part, contentIndices?.[index] ?? index + contentIndexOffset), + ), + ]); + } + }); + return entries.length === 0 ? '' : JSON.stringify(entries); + }, [content, messageId, contentIndices, contentIndexOffset]); + const keys = useMemo( + () => (keySignature === '' ? [] : (JSON.parse(keySignature) as Array<[number, string]>)), + [keySignature], + ); + const store = useStore(); + /** Retained one key at a time: releasing a key that is still read would free + * the member under the atom subscribed to it. */ + const retained = useRef(new Map void>()); + useEffect(() => { + const next = new Set(keys.map(([, key]) => key)); + for (const [key, release] of retained.current) { + if (!next.has(key)) { + release(); + retained.current.delete(key); + } + } + for (const key of next) { + if (!retained.current.has(key)) { + retained.current.set(key, retainSubagentProgress(store, key)); + } + } + }, [keys, store]); + useEffect(() => { + const held = retained.current; + return () => { + held.forEach((release) => release()); + held.clear(); + }; + }, []); + /** Built from everything the invocation has shown, not only its current + * activity: a write the progress setter remembered and a later write that + * evicted the same call can land in one batch. */ + const signatureAtom = useMemo( + () => + atom((get) => { + const ids = new Set(idSignature === '' ? [] : idSignature.split('\u0000')); + const live: Array<[number, NestedCall[]]> = []; + for (const [index, key] of keys) { + const progress = get(subagentProgressByToolCallId(key)); + const owners = rememberedSubagentChildCalls(key, ids); + /** The owners of this message's files are refreshed as the newest + * entries, so the bounded history cannot age them out while it shows. */ + rememberSubagentChildCalls(key, owners, true); + rememberSubagentChildCalls( + key, + collectNestedCalls(progress?.contentParts, [], progress?.subagentAgentId), + ); + const calls = rememberedSubagentChildCalls(key, ids); + if (calls.length > 0) { + live.push([index, calls]); + } + } + return live.length === 0 ? '' : JSON.stringify(live); + }), + [keys, idSignature], + ); + const signature = useAtomValue(signatureAtom); + return useMemo( + () => + signature === '' + ? NO_LIVE_CALLS + : new Map(JSON.parse(signature) as Array<[number, NestedCall[]]>), + [signature], + ); +} + +/** The identity a stored part and its cached preview share. */ +const identityOf = (toolCallId: string, stepId?: string, agentId?: string): string => + [toolCallId, stepId ?? '', agentId ?? ''].join('\u0000'); + +/** Whether `content` holds a subagent call whose transcript the server left out of the preview. */ +export function hasOmittedSubagentContent( + content: ReadonlyArray | undefined, +): boolean { + return (content ?? []).some( + (part) => (nestedToolCallOf(part) as FullToolCall | undefined)?.subagentContentOmitted === true, + ); +} + +/** + * Routes the stored child calls the server returned for previewed subagent calls back to each + * call's index in `content`, matching a part and its cached preview by their shared identity. + */ +export function routeStoredSubagentHints( + content: ReadonlyArray | undefined, + parts: SubagentAttachmentCallsResponse['parts'], +): ReadonlyMap { + if (parts.length === 0) { + return NO_LIVE_CALLS; + } + const byIdentity = new Map(); + for (const entry of parts) { + const identity = identityOf(entry.toolCallId, entry.stepId, entry.agentId); + byIdentity.set(identity, [...(byIdentity.get(identity) ?? []), ...entry.calls]); + } + const byIndex = new Map(); + (content ?? []).forEach((part, index) => { + const toolCall = nestedToolCallOf(part) as FullToolCall | undefined; + if (toolCall?.subagentContentOmitted !== true || !toolCall.id) { + return; + } + const calls = byIdentity.get( + identityOf(toolCall.id, toolCall.stepId, (part as { agentId?: string }).agentId), + ); + if (calls != null) { + byIndex.set(index, calls); + } + }); + return byIndex.size > 0 ? byIndex : NO_LIVE_CALLS; +} diff --git a/packages/chat/src/react/subagents/index.ts b/packages/chat/src/react/subagents/index.ts index b8359db813..18d310ac33 100644 --- a/packages/chat/src/react/subagents/index.ts +++ b/packages/chat/src/react/subagents/index.ts @@ -7,3 +7,4 @@ export * from './identity'; export * from './adapters'; export * from './recovery'; export * from './eventSelection'; +export * from './attachments';