From f7989dafa4e2ace52d832737bdff643f080c9c07 Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Tue, 17 Nov 2026 14:00:27 -0500 Subject: [PATCH 1/8] =?UTF-8?q?=F0=9F=AA=9F=20feat:=20Show=20a=20Running?= =?UTF-8?q?=20Subagent's=20Current=20Row=20on=20Its=20Card?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Messages/Content/Parts/SubagentCall.tsx | 3 - client/src/locales/en/translation.json | 5 - e2e/specs/mock/subagent-activity.spec.ts | 36 +- .../src/components/parts/SubagentCall.tsx | 503 ++++++++---------- .../__tests__/SubagentCall.share.spec.tsx | 1 - .../parts/__tests__/SubagentCall.spec.tsx | 202 +++++-- .../chat/src/components/subagents/panel.tsx | 13 +- .../subagents/__tests__/follows.spec.tsx | 186 +++++++ packages/chat/src/react/subagents/follows.tsx | 273 ++++++++++ packages/chat/src/react/subagents/parents.tsx | 50 +- 10 files changed, 923 insertions(+), 349 deletions(-) create mode 100644 packages/chat/src/react/subagents/__tests__/follows.spec.tsx create mode 100644 packages/chat/src/react/subagents/follows.tsx diff --git a/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx b/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx index 2de3f86059b..c96c500e746 100644 --- a/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx +++ b/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx @@ -9,7 +9,6 @@ import { useMessageContext } from '~/Providers/MessageContext'; import { useShareContext } from '~/Providers/ShareContext'; import MessageIcon from '~/components/Share/MessageIcon'; import { MCPAppViews } from '~/components/MCPUIResource'; -import { useMCPServerNames } from '~/hooks/MCP'; import { useLocalize } from '~/hooks'; const agentMessage = { endpoint: EModelEndpoint.agents, isCreatedByUser: false } as TMessage; @@ -28,7 +27,6 @@ export default function SubagentCall(props: SubagentCallProps) { const message = useMessageContext(); const share = useShareContext(); const agentsMap = useAgentsMapContext(); - const mcpServerNames = useMCPServerNames(); const translate = useLocalize(); const localize = useCallback( (key, values) => translate(key as TranslationKeys, values), @@ -40,7 +38,6 @@ export default function SubagentCall(props: SubagentCallProps) { {...share} message={message} agentsMap={agentsMap} - mcpServerNames={mcpServerNames} localize={localize} renderAgentIcon={renderAgentIcon} renderAttachments={renderAttachments} diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json index 4b76bf489ee..b16750f5454 100644 --- a/client/src/locales/en/translation.json +++ b/client/src/locales/en/translation.json @@ -3500,11 +3500,6 @@ "com_ui_subagent_trigger_truncated": "Trigger summary shortened for display.", "com_ui_subagent_turn": "Turn", "com_ui_subagent_running": "Running agent", - "com_ui_subagent_ticker_error": "Error", - "com_ui_subagent_ticker_reasoning": "Reasoning", - "com_ui_subagent_ticker_tool_done": "done", - "com_ui_subagent_ticker_using": "Using", - "com_ui_subagent_ticker_writing": "Writing", "com_ui_subagent_waiting": "Working…", "com_ui_submit": "Submit", "com_ui_submit_decisions": "Submit {{0}} decisions", diff --git a/e2e/specs/mock/subagent-activity.spec.ts b/e2e/specs/mock/subagent-activity.spec.ts index 28c03824061..81b4f40f97e 100644 --- a/e2e/specs/mock/subagent-activity.spec.ts +++ b/e2e/specs/mock/subagent-activity.spec.ts @@ -164,16 +164,29 @@ test.describe('detached subagent activity', () => { await expect(cards).toHaveCount(2, { timeout: 30_000 }); await expect(cards.first()).toHaveAttribute('data-subagent-thread', /.+/); const firstThreadId = (await cards.first().getAttribute('data-subagent-thread')) ?? ''; - const threadReadPromise = page.waitForResponse((candidate) => { - const read = THREAD_MESSAGES_PATH.exec(new URL(candidate.url()).pathname); - return read != null && decodeURIComponent(read[1]) === firstThreadId; - }); + const attachesOf = (threadId: string) => + streamAttaches.filter((attached) => attached === threadId).length; + + /** With no panel open, each running child's card shows the row its thread is on: the + * thread's own content, drawn by the thread's renderer, one row at a time. The page + * follows each child once for that. */ + const rows = page.locator('[data-subagent-preview]'); + await expect(rows).toHaveCount(2, { timeout: 30_000 }); + await expect(rows.first()).toContainText(/child-1-phase-\d+/); + await expect(rows.nth(1)).toContainText(/child-2-phase-\d+/); + await expect(cards.first()).toContainText('Running'); + await expect.poll(() => messageReads).toContain(firstThreadId); + /** A collapsed group shows no cards and follows nothing, so the count so far depends on + * how long the group stood open before the parent's turn ended. What is fixed is that the + * child is being followed now, and that opening it adds no stream of its own. */ + const followedByCard = attachesOf(firstThreadId); + expect(followedByCard).toBeGreaterThanOrEqual(1); await cards.first().click(); /** The child's thread opens as a conversation: its messages, read through the parent, and - * its own generation stream while it runs. The bounded activity feed is not read at all. */ + * the generation stream the card was already reading. The bounded activity feed is not + * read at all. */ const panel = childActivityPanel(page); - expect((await threadReadPromise).ok()).toBeTruthy(); await expect(panel).toBeVisible(); await expect(panel).toContainText('child-1-phase-10'); await expect(panel.getByText('Running', { exact: true })).toHaveCount(0); @@ -182,12 +195,13 @@ test.describe('detached subagent activity', () => { timeout: 30_000, }); await expect(panel.getByText('Completed', { exact: true })).toHaveCount(0); - const attachesOf = (threadId: string) => - streamAttaches.filter((attached) => attached === threadId).length; - /** At most one attachment, and none added once the run is over: a finished child is read - * from its stored messages, and a running one is followed by a single stream. */ + /** One attachment for the card and the panel together, and none added once the run is + * over: a finished child is read from its stored messages. Its card drops its row. */ const attaches = attachesOf(firstThreadId); - expect(attaches).toBeLessThanOrEqual(1); + expect(attaches).toBe(followedByCard); + await expect( + cards.first().locator('xpath=..').locator('[data-subagent-preview]'), + ).toHaveCount(0); await page.waitForTimeout(ACTIVITY_RECONNECT_GUARD_MS); expect(attachesOf(firstThreadId)).toBe(attaches); expect(messageReads).toContain(firstThreadId); diff --git a/packages/chat/src/components/parts/SubagentCall.tsx b/packages/chat/src/components/parts/SubagentCall.tsx index ff103b2d7f4..eb0b820e485 100644 --- a/packages/chat/src/components/parts/SubagentCall.tsx +++ b/packages/chat/src/components/parts/SubagentCall.tsx @@ -3,27 +3,32 @@ import { useSetAtom } from 'jotai'; import { Button, cn } from '@librechat/client'; import { ChevronRight, Users } from 'lucide-react'; import { ContentTypes } from 'librechat-data-provider'; -import type { PartMetadata, TAttachment, TMessageContentParts } from 'librechat-data-provider'; +import type { + TMessage, + PartMetadata, + TAttachment, + TMessageContentParts, +} from 'librechat-data-provider'; import type { Agent } from 'librechat-data-provider'; import type { ReactNode } from 'react'; import type { MessagePartMessage, MessagePartsHost, ToolCallChrome } from '../../react/host'; import type { SubagentContentPreview } from '../../react/subagents/state'; -import type { SubagentTickerLine } from '../../core/subagents/content'; import { activeSubagentPanel, subagentProgressKey, useSubagentProgress, } from '../../react/subagents/state'; +import { isLiveSubagentStatus, subagentStatusLabelKey } from '../../react/subagents/status'; import { isSelfSpawn as isSelfSpawnType } from '../../react/subagents/author'; import { parseSubagentBackgroundHandle } from '../../core/parts/handle'; import { resolveSubagentAgentId } from '../../react/subagents/identity'; -import { subagentStatusLabelKey } from '../../react/subagents/status'; -import { tailOverflowDirection } from '../../core/subagents/content'; import { useOpenSubagentPanel } from '../../react/subagents/surface'; import { useParentSubagents } from '../../react/subagents/parents'; +import { useThreadInterest } from '../../react/subagents/follows'; import { getSubagentPrompt } from '../../react/subagents/prompt'; import { useToolCallIntent } from '../../react/parts/intent'; -import { parseToolName } from '../../core/parts/toolLabels'; +import { useBranchTailSelect } from '../../react/latest'; +import { useMessagePartsHost } from '../../react/host'; import { useToolPreparation } from './preparation'; import { isError } from '../../core/parts/output'; import { useFailedReveal } from './reveal'; @@ -55,10 +60,7 @@ export interface SubagentCallProps { } /** App subscriptions arrive as values; render callbacks contain no card behavior. */ -export type SubagentCallContext = Pick< - ToolCallChrome, - 'localize' | 'mcpServerNames' | 'renderAttachments' -> & +export type SubagentCallContext = Pick & Pick & { message: Pick; isSharedConvo?: boolean; @@ -66,7 +68,6 @@ export type SubagentCallContext = Pick< agentsMap?: Record; }; -const TICKER_MAX_LINES = 3; /** Trailing-edge refresh window for the live preview once the ticker has * enough text to fill the row. Keeps long streaming lines from repainting * every token while still letting the collapsed subagent UI feel responsive. */ @@ -76,7 +77,7 @@ export const SUBAGENT_TICKER_THROTTLE_MS = 400; * streams the rest of the sentence. The pass-through lets early * tokens appear right away, and throttling only kicks in once the * preview is long enough to "fill the container". */ -const TICKER_PASSTHROUGH_CHARS = 120; +const PREVIEW_PASSTHROUGH_CHARS = 120; /** * Trailing-edge throttle for the ticker. Forwards `value` at most once per @@ -188,7 +189,6 @@ export default function SubagentCall({ isSharedConvo, shareId, localize, - mcpServerNames, agentsMap, renderAgentIcon, renderAttachments, @@ -211,7 +211,13 @@ export default function SubagentCall({ subagentType, progress?.subagentKind ?? subagentIdentity?.subagentKind, ); - const subagentAgentId = resolveSubagentAgentId(progress, subagentIdentity); + /** A detached child's identity as the parent's index reports it, once the parent's own stream + * that named it is gone. */ + const { byThreadId } = useParentSubagents(); + const indexedChild = + backgroundHandle == null ? undefined : byThreadId.get(backgroundHandle.subagent_thread_id); + const subagentAgentId = + resolveSubagentAgentId(progress, subagentIdentity) ?? indexedChild?.agentId; const subagentAgent = subagentAgentId ? agentsMap?.[subagentAgentId] : undefined; /** * Tri-state status resolution, aligned with `ToolCall.tsx`: @@ -250,33 +256,30 @@ export default function SubagentCall({ const running = !finished && !cancelled; const detachedStatusUnknown = backgroundHandle != null && progress == null && !isSubmitting; - /** Last `TICKER_MAX_LINES` lines from the atom's incrementally-built - * ticker state, so history isn't lost to any event trimming. */ - const tickerLines = useMemo(() => { - const lines = progress?.tickerState?.lines ?? []; - return lines.slice(-TICKER_MAX_LINES); - }, [progress?.tickerState?.lines]); - - /** Only throttle once the running buffer is wide enough to "fill the - * container". Pre-threshold updates pass through so the user sees - * early tokens immediately, not a static "Reasoning: I" while more - * text piles up behind the throttle. */ - const shouldThrottleTicker = useMemo(() => { - if (!running) return false; - const liveBody = tickerLines.reduce((max, line) => { - if (line.kind === 'writing' || line.kind === 'reasoning') { - return Math.max(max, line.body.length); + /** The child's newest part: the row it is on right now. */ + const tailPart = useMemo(() => { + const parts = progress?.contentParts ?? []; + for (let index = parts.length - 1; index >= 0; index--) { + if (parts[index] != null) { + return { part: parts[index] as TMessageContentParts, index }; } - return max; - }, 0); - return liveBody >= TICKER_PASSTHROUGH_CHARS; - }, [running, tickerLines]); - - const displayedTickerLines = useTickerThrottle( - tickerLines, - SUBAGENT_TICKER_THROTTLE_MS, - shouldThrottleTicker, - ); + } + return undefined; + }, [progress?.contentParts]); + + /** Only throttle once the live text is long enough to fill the row. Earlier updates pass + * through so the first tokens appear right away, not after the throttle window. */ + const shouldThrottlePreview = useMemo(() => { + if (!running || tailPart == null) return false; + const { part } = tailPart; + let text: unknown = ''; + if (part.type === ContentTypes.TEXT) text = part.text; + else if (part.type === ContentTypes.THINK) text = part.think; + return typeof text === 'string' && text.length >= PREVIEW_PASSTHROUGH_CHARS; + }, [running, tailPart]); + + const preview = useTickerThrottle(tailPart, SUBAGENT_TICKER_THROTTLE_MS, shouldThrottlePreview); + const showPreview = running && preview != null; const prompt = getSubagentPrompt(args); @@ -419,100 +422,107 @@ export default function SubagentCall({ return ( <> - + + {showPreview ? ( + + ) : null} + {!showPreview && canOpenDurablePanel && backgroundHandle != null ? ( + + ) : null} + {!hideAttachments && attachments != null && attachments.length > 0 ? renderAttachments(attachments) @@ -538,12 +548,53 @@ function DetachedTaskStatus({ taskId: string; fallback: string; }): ReactNode { - const { byThreadId } = useParentSubagents(); + const status = useDetachedStatus(threadId, taskId); + return <>{status == null ? fallback : localize(subagentStatusLabelKey(status))}; +} + +/** A detached task's status in the parent's subagent index, when the index has one. */ +function useDetachedStatus(threadId: string, taskId: string) { + const { byThreadId, discover } = useParentSubagents(); const child = byThreadId.get(threadId); - const status = + /** A child dispatched after the index was last read is not in it; the index is told. */ + useEffect(() => { + if (child == null) { + discover(threadId); + } + }, [child, discover, threadId]); + return ( child?.tasks.find((task) => task.taskId === taskId)?.status ?? - (child?.latestTaskId === taskId ? child.status : undefined); - return <>{status == null ? fallback : localize(subagentStatusLabelKey(status))}; + (child?.latestTaskId === taskId ? child.status : undefined) + ); +} + +const pickTailPart = (tail: TMessage | null): TMessageContentParts | null => { + if (tail == null || tail.isCreatedByUser) return null; + const parts = tail.content ?? []; + for (let index = parts.length - 1; index >= 0; index--) { + const part = parts[index]; + if (part != null) return part; + } + return null; +}; + +const pickTailLength = (tail: TMessage | null): number | null => tail?.content?.length ?? null; + +/** + * A detached child's row, read from its thread's messages wherever something is following that + * thread. Its own leaf, so a streamed token re-renders this row alone and never the card. + */ +function DetachedPreview({ threadId, taskId }: { threadId: string; taskId: string }): ReactNode { + const status = useDetachedStatus(threadId, taskId); + const live = status != null && isLiveSubagentStatus(status); + /** A running child is followed for its row; the page follows it once, with or without a panel. */ + useThreadInterest(threadId, { live: true, enabled: live, passive: true }); + const part = useBranchTailSelect(threadId, threadId, pickTailPart); + const length = useBranchTailSelect(threadId, threadId, pickTailLength); + if (part == null || !live) { + return null; + } + return ; } function extractSubagentType(args: SubagentCallProps['args']): string { @@ -559,148 +610,58 @@ function extractSubagentType(args: SubagentCallProps['args']): string { return a?.subagent_type ?? 'agent'; } -/** Stable key for a ticker line. Helps React reuse the DOM node across - * in-place updates to the same live `writing` / `reasoning` line, and - * gives tool-call lines a stable identity by tool name. */ -function tickerLineKey(line: SubagentTickerLine): string { - switch (line.kind) { - case 'writing': - case 'reasoning': - return line.kind; - case 'using_tool': - return `using:${line.toolNames.join(',')}`; - case 'tool_complete': - return `done:${line.toolName}`; - case 'error': - return `error:${line.message ?? ''}`; - } -} - -/** Inline code-style tool-name badge. Matches the monospace styling of - * the ticker itself but with a subtle background so the tool identifier - * reads as a "code" token rather than plain prose. */ -function ToolNameBadge({ name }: { name: string }): ReactNode { - return ( - {name} - ); -} - -/** Render a single tool id as a compact JSX fragment: MCP tools split - * into ` · toolName`, native tools resolve their - * friendly name via `FRIENDLY_NAME_KEYS`, unknown ids fall back to a - * bare code badge of the raw name. */ -function ToolIdentifier({ - rawName, - localize, - mcpServerNames, -}: { - rawName: string; - localize: (key: string) => string; - mcpServerNames?: readonly string[]; -}): ReactNode { - const parsed = parseToolName(rawName, mcpServerNames); - if (parsed.mcpServer) { - return ( - - {parsed.mcpServer} - {'\u00b7'} - - - ); - } - if (parsed.friendlyKey) { - return {localize(parsed.friendlyKey)}; - } - return ; -} +const PREVIEW_ROW_HEIGHT = 'h-8'; +/** + * The line above the row dissolves at the top edge instead of being cut through. A mask stencil, + * not paint: only its alpha is read, so it is not a theme color. + */ +const PREVIEW_FADE = + '[mask-image:linear-gradient(to_bottom,transparent,rgb(var(--black)/1)_0.625rem)]'; +/** Room under the header for the row, kept by the card only while a row is drawn over it. */ +const PREVIEW_ROOM = '[&:has([data-subagent-preview])>button]:pb-11'; +/** `inert` as an attribute: React 18's types do not know it. */ +const INERT: Record = { inert: '' }; /** - * Renderer for one ticker line. Writing is the default visible activity, so - * it renders without a redundant prefix. Reasoning retains its semantic label. - * Streaming bodies run the outer box opposite to the text direction so the - * oldest characters clip and the newest stay visible; `text-end` of that box is - * the text's own start, so a line that fits stays where it reads from. The text - * sits in an isolated `dir="auto"` span so its punctuation is never reordered. - * - * Tool lines (`using_tool`, `tool_complete`) go through `ToolIdentifier` - * so MCP-hosted tools render as ` · ` badges and native - * tools use their friendly names, matching the delimiter-aware - * rendering the main tool UI already uses. + * The row the child is on right now, drawn by the renderer the thread itself uses and shown one + * row at a time: the same tool row, reasoning row or text a reader sees after opening the child, + * held to the card's last line. It is a picture of that row, not a control: it sits over the + * card instead of inside its button, takes no pointer or focus, and is hidden from assistive + * technology, which reads the card's label. */ -function TailText({ text }: { text: string }): ReactNode { +function SubagentPreview({ + part, + messageId, +}: { + part: TMessageContentParts; + messageId: string; +}): ReactNode { + const host = useMessagePartsHost(); + const content = useMemo(() => [part], [part]); return ( - - ); -} - -function TickerLineView({ - line, - localize, - mcpServerNames, -}: { line: SubagentTickerLine } & Pick< - SubagentCallContext, - 'localize' | 'mcpServerNames' ->): ReactNode { - if (line.kind === 'writing') { - return ( -
  • - -
  • - ); - } - if (line.kind === 'reasoning') { - return ( -
  • - {`${localize('com_ui_subagent_ticker_reasoning')}:`} - -
  • - ); - } - if (line.kind === 'using_tool') { - const prefix = localize('com_ui_subagent_ticker_using'); - return ( -
  • - {prefix} - - {line.toolNames.map((name, i) => ( - - {i > 0 && {','}} - - - ))} - {line.argsSnippet && ( - {`(${line.argsSnippet})`} - )} - -
  • - ); - } - if (line.kind === 'tool_complete') { - return ( -
  • - - {'\u2192'} - -
  • - ); - } - /* error */ - const errorPrefix = localize('com_ui_subagent_ticker_error'); - return ( -
  • - {`${errorPrefix}:`} - {line.message ?? ''} -
  • + {/* Held to its last line: what the child wrote most recently is the part in view. */} +
    + {host.renderContentParts({ + content, + messageId, + conversationId: null, + isCreatedByUser: false, + showThinking: false, + isSubmitting: true, + isLast: true, + isLatestMessage: false, + })} +
    + ); } diff --git a/packages/chat/src/components/parts/__tests__/SubagentCall.share.spec.tsx b/packages/chat/src/components/parts/__tests__/SubagentCall.share.spec.tsx index 2a66bb6caae..867529f64c7 100644 --- a/packages/chat/src/components/parts/__tests__/SubagentCall.share.spec.tsx +++ b/packages/chat/src/components/parts/__tests__/SubagentCall.share.spec.tsx @@ -36,7 +36,6 @@ function SubagentCall(props: SubagentCallProps) { isSharedConvo shareId="share-1" localize={localize} - mcpServerNames={[]} renderAgentIcon={() => null} renderAttachments={() => null} /> diff --git a/packages/chat/src/components/parts/__tests__/SubagentCall.spec.tsx b/packages/chat/src/components/parts/__tests__/SubagentCall.spec.tsx index 39ed5e2113f..131fedb3515 100644 --- a/packages/chat/src/components/parts/__tests__/SubagentCall.spec.tsx +++ b/packages/chat/src/components/parts/__tests__/SubagentCall.spec.tsx @@ -46,7 +46,6 @@ import { FailedRevealContext } from '../reveal'; import { FOLD_GLYPH_SELECTOR } from '../rows'; import { litFoldPath } from '../rail'; -const mockMCPServerNames: string[] = []; let mockIndexedChildren = new Map(); type CardMessage = { @@ -96,7 +95,6 @@ function SubagentCall(props: SubagentCallProps) { message={currentMessage} agentsMap={agents} localize={localize} - mcpServerNames={mockMCPServerNames} renderAgentIcon={(agent) => agent?.avatar?.filepath != null ? ( {agent.name @@ -111,10 +109,32 @@ function SubagentCall(props: SubagentCallProps) { /> ); } -const partsHost = createMessagePartsHost(); +/** A part as one line, so a spec reads which row the thread's renderer was handed. */ +const partLine = (part: object | undefined): string => { + const { + text, + think, + tool_call: toolCall, + } = (part ?? {}) as { + text?: string; + think?: string; + tool_call?: { name?: string }; + }; + return toolCall?.name ?? text ?? think ?? ''; +}; +const partsHost = createMessagePartsHost({ + renderContentParts: ({ content }) => ( +
    {content.map(partLine).join('|')}
    + ), +}); + +const mockUseThreadChat = jest.fn(); +const mockRefetchIndex = jest.fn(async () => ({ data: undefined })); +let seedQueries: ((client: QueryClient) => void) | undefined; const subagentsHost = createSubagentsHost({ useAgentsMap: () => agents, + useThreadChat: (...args) => mockUseThreadChat(...args), }); const streamHost = { @@ -125,7 +145,7 @@ const streamHost = { childrenTruncated: false, }, isError: false, - refetch: async () => ({ data: undefined }), + refetch: mockRefetchIndex, }), } as unknown as StreamHost; @@ -158,9 +178,11 @@ function Providers({ seed?.(created); return created; }); - const [queryClient] = useState( - () => new QueryClient({ defaultOptions: { queries: { retry: false } } }), - ); + const [queryClient] = useState(() => { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + seedQueries?.(client); + return client; + }); const card = ( true }}> {children} @@ -169,17 +191,18 @@ function Providers({ return ( - - - + {/* The page's followers read the subagents host, so it sits above the index provider. */} + + + {withSurface ? ( {card} ) : ( card )} - - - + + + ); @@ -187,9 +210,11 @@ function Providers({ afterEach(() => { jest.useRealTimers(); - mockMCPServerNames.length = 0; mockIndexedChildren = new Map(); currentMessage = defaultMessage; + seedQueries = undefined; + mockUseThreadChat.mockReset(); + mockRefetchIndex.mockClear(); }); function foldEvents(events: SubagentUpdateEvent[]): { @@ -477,7 +502,7 @@ describe('SubagentCall', () => { expect(rendered.getSelection()).toBeNull(); }); - it('keeps the compact semantic ticker while selecting the shared panel', async () => { + it('shows the row the child is on, drawn by the thread renderer, over the card and not in its button', () => { const progress = progressFromEvents({ subagentRunId: 'child-run', subagentType: 'self', @@ -499,10 +524,16 @@ describe('SubagentCall', () => { progress, }); - await waitFor(() => expect(screen.getByText('Using')).toBeInTheDocument()); - expect(screen.getByText('Working…')).toBeInTheDocument(); - expect(screen.queryByText('Writing')).not.toBeInTheDocument(); - fireEvent.click(screen.getByRole('button', { name: 'Running agent' })); + /** One row: the newest part, not the ones before it. */ + const row = screen.getByTestId('thread-row'); + expect(row).toHaveTextContent('calculator'); + expect(row).not.toHaveTextContent('Working…'); + const preview = row.closest('[data-subagent-preview]'); + expect(preview).toHaveAttribute('aria-hidden', 'true'); + expect(preview).toHaveAttribute('inert'); + const card = screen.getByRole('button', { name: 'Running agent' }); + expect(card.contains(row)).toBe(false); + fireEvent.click(card); expect(rendered.getSelection()).toEqual( expect.objectContaining({ @@ -516,43 +547,28 @@ describe('SubagentCall', () => { expect(rendered.getSelection()?.durable).toBeUndefined(); }); - it('preserves a configured MCP server boundary in the live ticker', () => { - mockMCPServerNames.push('Google_mcp_Workspace'); - renderWithState({ - toolCallId: 'call_mcp_ticker', + it('says it is waiting until the child has a row, and shows none once it is done', () => { + const rendered = renderWithState({ + toolCallId: 'call-waiting', initialProgress: 0.3, isSubmitting: true, - progress: progressFromEvents({ - subagentRunId: 'run_a', - subagentType: 'self', - status: 'run_step', - events: [ - { - runId: 'p', - subagentRunId: 'run_a', - subagentType: 'self', - phase: 'run_step', - data: { - stepDetails: { - type: 'tool_calls', - tool_calls: [ - { - id: 'c1', - name: 'search_documents_mcp_Google_mcp_Workspace', - }, - ], - }, - }, - timestamp: '', - } as SubagentUpdateEvent, - ], - }), }); + expect(screen.getByText('Waiting for first update…')).toBeInTheDocument(); + expect(screen.queryByTestId('thread-row')).toBeNull(); - expect(screen.getByText('Google_mcp_Workspace')).toBeInTheDocument(); + rendered.setProgress( + progressFromEvents({ + subagentRunId: 'child-run', + subagentType: 'self', + status: 'stop', + events: [event('message_delta', { delta: { content: [{ type: 'text', text: 'Done' }] } })], + }), + ); + expect(screen.queryByText('Waiting for first update…')).toBeNull(); + expect(screen.queryByTestId('thread-row')).toBeNull(); }); - it('refreshes a long ticker preview only after the throttle window', () => { + it('refreshes a long live row only after the throttle window', () => { jest.useFakeTimers(); const progressFor = (text: string) => progressFromEvents({ @@ -569,11 +585,91 @@ describe('SubagentCall', () => { isSubmitting: true, progress: progressFor(first), }); - const card = within(screen.getByRole('button', { name: 'Running agent' })); rendered.setProgress(progressFor(second)); - expect(card.getByText(first)).toBeInTheDocument(); + expect(screen.getByTestId('thread-row')).toHaveTextContent(first); act(() => jest.advanceTimersByTime(SUBAGENT_TICKER_THROTTLE_MS)); - expect(card.getByText(second)).toBeInTheDocument(); + expect(screen.getByTestId('thread-row')).toHaveTextContent(second); + }); + + describe('a detached child', () => { + const detachedOutput = JSON.stringify({ + background_task_id: 'task-1', + subagent_thread_id: 'child-thread-1', + tool: 'subagent', + subagent_type: 'agent_reviewer', + status: 'running', + message: 'Started subagent background task. Poll with background_task_id task-1.', + }); + const indexed = (status: ParentSubagentSummary['status']) => + new Map([ + [ + 'child-thread-1', + { + threadId: 'child-thread-1', + status, + latestTaskId: 'task-1', + agentId: 'agent_reviewer', + tasks: [{ taskId: 'task-1', status }], + } as ParentSubagentSummary, + ], + ]); + const threadMessages = [ + { messageId: 'task-1:user', isCreatedByUser: true, text: 'Review it' }, + { + messageId: 'task-1:assistant', + parentMessageId: 'task-1:user', + isCreatedByUser: false, + text: '', + content: [ + { type: 'text', text: 'Reading the diff' }, + { type: 'tool_call', tool_call: { id: 'c1', name: 'read_file', args: '{}' } }, + ], + }, + ]; + const mountDetached = () => + renderWithState({ + toolCallId: 'detached-live', + initialProgress: 1, + output: detachedOutput, + toolArgs: { subagent_type: 'agent_reviewer', run_in_background: true }, + }); + + beforeEach(() => { + mockUseThreadChat.mockReturnValue({ messages: [], isLoading: true }); + seedQueries = (client) => client.setQueryData(['messages', 'child-thread-1'], threadMessages); + }); + + it('is followed while it runs, once, and shows the row its thread is on', () => { + mockIndexedChildren = indexed('running'); + mountDetached(); + + expect(mockUseThreadChat).toHaveBeenCalledWith('parent-conversation', 'child-thread-1', { + live: true, + enabled: true, + }); + expect(screen.getByTestId('thread-row')).toHaveTextContent('read_file'); + /** Named by the index, which is all that names a child once the parent's stream is gone. */ + expect( + screen.getByRole('button', { + name: 'Code Reviewer com_ui_subagent_thread_status_running', + }), + ).toBeInTheDocument(); + }); + + it('is not followed and shows no row once it has finished', () => { + mockIndexedChildren = indexed('completed'); + mountDetached(); + + expect(mockUseThreadChat).not.toHaveBeenCalled(); + expect(screen.queryByTestId('thread-row')).toBeNull(); + }); + + it('asks the index to look again for a child it does not list, once', async () => { + mountDetached(); + + await waitFor(() => expect(mockRefetchIndex).toHaveBeenCalledTimes(1)); + expect(mockUseThreadChat).not.toHaveBeenCalled(); + }); }); it('opens a foreground legacy invocation in the shared panel with persisted activity', () => { diff --git a/packages/chat/src/components/subagents/panel.tsx b/packages/chat/src/components/subagents/panel.tsx index 83836e119e9..01fa7879f50 100644 --- a/packages/chat/src/components/subagents/panel.tsx +++ b/packages/chat/src/components/subagents/panel.tsx @@ -53,6 +53,7 @@ import { useSubagentPanelState, useSubagentPanelActions, } from '../../react/subagents/surface'; +import { useFollowedThread, useThreadFollows } from '../../react/subagents/follows'; import { SubagentActivity, SubagentActivityScrollSurface } from './transcript'; import { eventSubagentSelection } from '../../react/subagents/eventSelection'; import { isMacPlatform, resolveComposerKeyDown } from '../../core/shortcuts'; @@ -317,10 +318,18 @@ export default function SubagentThreadPanel({ selection.event == null && threadId !== ''; const followLive = followable && taskView?.status === 'running'; - const followed = host.useThreadChat?.(selection.parentConversationId, threadId, { + /** One follower per thread on the page: where the page shares them, the card previewing this + * child and this panel read the same stream; elsewhere the panel follows the thread itself. */ + const sharedFollows = useThreadFollows(); + const ownFollowed = host.useThreadChat?.(selection.parentConversationId, threadId, { live: followLive, - enabled: followable, + enabled: followable && sharedFollows == null, }); + const sharedFollowed = useFollowedThread(threadId, { + live: followLive, + enabled: followable && sharedFollows != null, + }); + const followed = sharedFollows == null ? ownFollowed : sharedFollowed; /** Rows that are not being streamed into: the stored ones, as first read or as read again at * a run's end. */ const followedSettled = followed != null && !followed.isLoading && !followed.isFollowing; diff --git a/packages/chat/src/react/subagents/__tests__/follows.spec.tsx b/packages/chat/src/react/subagents/__tests__/follows.spec.tsx new file mode 100644 index 00000000000..75ed6d6bc7d --- /dev/null +++ b/packages/chat/src/react/subagents/__tests__/follows.spec.tsx @@ -0,0 +1,186 @@ +/** + * @jest-environment jsdom + */ +import { useEffect } from 'react'; +import { act, render } from '@testing-library/react'; +import type { ReactElement } from 'react'; +import type { FollowedChat } from '../../follow'; +import { + useFollowedThread, + useThreadInterest, + ThreadFollowsProvider, + THREAD_LINGER_MS, + MAX_PREVIEWED_THREADS, +} from '../follows'; +import { createSubagentsHost } from '../../../__fixtures__/subagentsHost'; +import { SubagentsHostProvider } from '../host'; + +const followed = (overrides: Partial = {}): FollowedChat => ({ + chat: undefined, + messages: [], + status: 'ready', + connection: 'idle', + error: undefined, + isLoading: false, + isFollowing: false, + isUnattached: false, + isLoadError: false, + retry: () => undefined, + ...overrides, +}); + +/** Each thread's follower as the host sees it: which are mounted, and how each was last asked. */ +let asked: Record; +let results: Record; +let mounted: Set; +let unmounts: number; + +const host = createSubagentsHost({ + useThreadChat: (_parent, threadId, options) => { + asked[threadId] = options; + useEffect(() => { + mounted.add(threadId); + return () => { + mounted.delete(threadId); + unmounts += 1; + }; + }, [threadId]); + return results[threadId] ?? followed({ isLoading: true }); + }, +}); + +const page = (ui: ReactElement) => ( + + {ui} + +); + +function Reader({ threadId, live = false }: { threadId: string; live?: boolean }): null { + seen[threadId] = useFollowedThread(threadId, { live, enabled: true }); + return null; +} + +function Preview({ threadId }: { threadId: string }): null { + useThreadInterest(threadId, { live: true, enabled: true, passive: true }); + return null; +} + +let seen: Record; + +beforeEach(() => { + asked = {}; + results = {}; + seen = {}; + mounted = new Set(); + unmounts = 0; + jest.useFakeTimers(); +}); + +afterEach(() => { + jest.useRealTimers(); +}); + +describe('ThreadFollowsProvider', () => { + it('follows a thread once for every reader and lets it go when the last one leaves', () => { + const view = render( + page( + <> + + + , + ), + ); + /** One follower, live for the page as soon as any reader knows a run is going. */ + expect([...mounted]).toEqual(['thread-1']); + expect(asked['thread-1']).toEqual({ live: true, enabled: true }); + + view.rerender(page()); + expect([...mounted]).toEqual(['thread-1']); + expect(asked['thread-1']).toEqual({ live: false, enabled: true }); + + view.rerender(page(<>)); + /** Kept for a moment, so a reader that is only being replaced finds it still open. */ + expect([...mounted]).toEqual(['thread-1']); + act(() => jest.advanceTimersByTime(THREAD_LINGER_MS)); + expect([...mounted]).toEqual([]); + }); + + it('keeps one follower through a reader being replaced', () => { + const view = render(page()); + view.rerender(page()); + act(() => jest.advanceTimersByTime(THREAD_LINGER_MS * 2)); + expect([...mounted]).toEqual(['thread-1']); + expect(unmounts).toBe(0); + }); + + it('hands a reader an opening state until the follower reports, then what it reports', () => { + results['thread-1'] = followed({ isLoading: true }); + const view = render(page()); + expect(seen['thread-1']).toMatchObject({ isLoading: true, messages: [] }); + + const streaming = followed({ status: 'streaming', isFollowing: true }); + results['thread-1'] = streaming; + act(() => view.rerender(page())); + expect(seen['thread-1']).toBe(streaming); + }); + + it('previews only as many threads as the page has room for, and always follows an opened one', () => { + const previews = Array.from({ length: MAX_PREVIEWED_THREADS + 1 }, (_, n) => `preview-${n}`); + const view = render( + page( + <> + {previews.map((threadId) => ( + + ))} + + , + ), + ); + const overflow = previews[MAX_PREVIEWED_THREADS]; + expect([...mounted].sort()).toEqual( + [...previews.slice(0, MAX_PREVIEWED_THREADS), 'opened'].sort(), + ); + + /** Opening a preview that had no room follows it. */ + view.rerender( + page( + <> + {previews.map((threadId) => ( + + ))} + + + , + ), + ); + expect(mounted.has(overflow)).toBe(true); + expect(asked[overflow]).toEqual({ live: true, enabled: true }); + + /** A preview that ends gives its room to the next one waiting. */ + view.rerender( + page( + <> + {previews.slice(1).map((threadId) => ( + + ))} + , + ), + ); + act(() => jest.advanceTimersByTime(THREAD_LINGER_MS)); + expect([...mounted].sort()).toEqual(previews.slice(1).sort()); + }); + + it('follows nothing where no page shares followers', () => { + function Lone(): null { + seen.lone = useFollowedThread('thread-1', { live: true, enabled: true }); + return null; + } + render( + + + , + ); + expect(seen.lone).toBeUndefined(); + expect([...mounted]).toEqual([]); + }); +}); diff --git a/packages/chat/src/react/subagents/follows.tsx b/packages/chat/src/react/subagents/follows.tsx new file mode 100644 index 00000000000..a9711a6a253 --- /dev/null +++ b/packages/chat/src/react/subagents/follows.tsx @@ -0,0 +1,273 @@ +import { useMemo, useEffect, useContext, createContext, useSyncExternalStore } from 'react'; +import type { Context, ReactNode } from 'react'; +import type { FollowedChat } from '../follow'; +import { useSubagentsHost } from './host'; + +/** + * How many threads a page follows only to preview them. A followed thread holds a stream open, + * and over HTTP/1.1 a browser allows six connections to an origin, which main chat's own stream + * and every request share. A thread someone opened is always followed; previews take what is + * left of this many. + */ +export const MAX_PREVIEWED_THREADS = 3; + +/** + * How long a thread stays followed after its last reader leaves. A reader that is replaced, not + * removed, leaves and returns within one commit: when a reply settles, its row is drawn again + * under the reply's stored id, and the card in it with it. Letting go at once would close the + * child's stream and open it again for that. + */ +export const THREAD_LINGER_MS = 250; + +/** One reader's interest in a thread. */ +export type ThreadInterest = { + /** Whether this reader knows a generation is running under the thread. */ + live: boolean; + /** A preview: followed only while the page has room for it. */ + passive: boolean; +}; + +type FollowedThread = { threadId: string; live: boolean }; +type Listener = () => void; + +const noThreads: readonly FollowedThread[] = []; +const unsubscribed = (): void => undefined; + +/** What a reader holds until the thread's follower has something to report. */ +const opening: FollowedChat = { + chat: undefined, + messages: [], + status: 'ready', + connection: 'idle', + error: undefined, + isLoading: true, + isFollowing: false, + isUnattached: false, + isLoadError: false, + retry: () => undefined, +}; + +/** + * The threads one page follows, each once, however many readers want it: the panel showing a + * child's conversation and the card previewing the same child read one stream. A thread is + * followed while any reader is interested and let go when the last one leaves. + */ +export class ThreadFollows { + private readonly interests = new Map>(); + /** What each thread's readers last asked for, which holds while none of them is present. */ + private readonly asked = new Map(); + private readonly results = new Map(); + private readonly threadListeners = new Set(); + private readonly resultListeners = new Map>(); + private followed: readonly FollowedThread[] = noThreads; + + /** Registers a reader's interest; the result lets it go. */ + acquire(threadId: string, interest: ThreadInterest): () => void { + const readers = this.interests.get(threadId) ?? new Set(); + readers.add(interest); + this.interests.set(threadId, readers); + this.changed(); + return () => { + readers.delete(interest); + if (readers.size > 0) { + this.changed(); + return; + } + setTimeout(() => { + if (readers.size === 0 && this.interests.get(threadId) === readers) { + this.interests.delete(threadId); + this.asked.delete(threadId); + this.changed(); + } + }, THREAD_LINGER_MS); + }; + } + + subscribeThreads = (listener: Listener): (() => void) => { + this.threadListeners.add(listener); + return () => { + this.threadListeners.delete(listener); + }; + }; + + /** The threads to follow now: every opened one, then previews in the order they asked. */ + getThreads = (): readonly FollowedThread[] => { + const next: FollowedThread[] = []; + let previews = 0; + for (const [threadId, readers] of this.interests) { + let { live, opened } = this.asked.get(threadId) ?? { live: false, opened: false }; + if (readers.size > 0) { + live = false; + opened = false; + for (const reader of readers) { + live ||= reader.live; + opened ||= !reader.passive; + } + this.asked.set(threadId, { live, opened }); + } + if (!opened) { + if (previews >= MAX_PREVIEWED_THREADS) { + continue; + } + previews += 1; + } + next.push({ threadId, live }); + } + const same = + next.length === this.followed.length && + next.every( + (thread, index) => + thread.threadId === this.followed[index].threadId && + thread.live === this.followed[index].live, + ); + if (!same) { + this.followed = next; + } + return this.followed; + }; + + subscribeResult(threadId: string, listener: Listener): () => void { + const listeners = this.resultListeners.get(threadId) ?? new Set(); + listeners.add(listener); + this.resultListeners.set(threadId, listeners); + return () => { + listeners.delete(listener); + }; + } + + /** What the thread's follower last reported; `opening` until it has. */ + getResult(threadId: string): FollowedChat { + return this.results.get(threadId) ?? opening; + } + + /** Called by the thread's follower with each state it reaches, and with nothing when it ends. */ + publish(threadId: string, result: FollowedChat | undefined): void { + if (result == null) { + this.results.delete(threadId); + } else { + this.results.set(threadId, result); + } + for (const listener of this.resultListeners.get(threadId) ?? []) { + listener(); + } + } + + private changed(): void { + for (const listener of this.threadListeners) { + listener(); + } + } +} + +const ThreadFollowsContext: Context = createContext< + ThreadFollows | undefined +>(undefined); + +/** The page's shared followers, when a provider above offers them. */ +export const useThreadFollows = (): ThreadFollows | undefined => useContext(ThreadFollowsContext); + +/** Follows one thread for everyone on the page and reports what it holds. */ +function ThreadFollower({ + follows, + parentConversationId, + threadId, + live, +}: { + follows: ThreadFollows; + parentConversationId: string; + threadId: string; + live: boolean; +}): null { + const host = useSubagentsHost(); + const followed = host.useThreadChat?.(parentConversationId, threadId, { live, enabled: true }); + useEffect(() => { + follows.publish(threadId, followed); + }); + useEffect(() => () => follows.publish(threadId, undefined), [follows, threadId]); + return null; +} + +function ThreadFollowers({ + follows, + parentConversationId, +}: { + follows: ThreadFollows; + parentConversationId: string; +}): ReactNode { + const threads = useSyncExternalStore( + follows.subscribeThreads, + follows.getThreads, + follows.getThreads, + ); + return threads.map((thread) => ( + + )); +} + +/** + * Shares one follower per child thread among every reader under it, for the children of one + * parent conversation. Nothing is followed until a reader asks. + */ +export function ThreadFollowsProvider({ + parentConversationId, + children, +}: { + parentConversationId: string; + children: ReactNode; +}): ReactNode { + const follows = useMemo( + () => ({ parentConversationId, store: new ThreadFollows() }), + [parentConversationId], + ).store; + return ( + + + {children} + + ); +} + +/** + * Says this reader wants a thread followed, without reading what the follower holds: a card + * reads its row from the thread's messages and has no use for every other change. + */ +export function useThreadInterest( + threadId: string, + { live, enabled, passive = false }: { live: boolean; enabled: boolean; passive?: boolean }, +): void { + const follows = useThreadFollows(); + useEffect(() => { + if (follows == null || !enabled || threadId === '') { + return; + } + return follows.acquire(threadId, { live, passive }); + }, [follows, threadId, live, enabled, passive]); +} + +/** + * The page's shared follower of a thread, and this reader's interest in it. Nothing while no + * provider offers shared followers, or while `enabled` is false. + */ +export function useFollowedThread( + threadId: string, + options: { live: boolean; enabled: boolean; passive?: boolean }, +): FollowedChat | undefined { + const follows = useThreadFollows(); + useThreadInterest(threadId, options); + const subscribe = useMemo( + () => + follows == null + ? () => unsubscribed + : (listener: Listener) => follows.subscribeResult(threadId, listener), + [follows, threadId], + ); + const read = (): FollowedChat | undefined => follows?.getResult(threadId); + const result = useSyncExternalStore(subscribe, read, read); + return options.enabled ? result : undefined; +} diff --git a/packages/chat/src/react/subagents/parents.tsx b/packages/chat/src/react/subagents/parents.tsx index 4e9c9ae6cfc..81ed38541d2 100644 --- a/packages/chat/src/react/subagents/parents.tsx +++ b/packages/chat/src/react/subagents/parents.tsx @@ -8,6 +8,7 @@ import type { ParentSubagentSummary, } from 'librechat-data-provider'; import type { ReactNode } from 'react'; +import { ThreadFollowsProvider, useThreadFollows } from './follows'; import { useStreamHost } from '../stream/host'; export type ParentSubagentsContextValue = { @@ -15,6 +16,12 @@ export type ParentSubagentsContextValue = { byMessageId: ReadonlyMap; byThreadId: ReadonlyMap; refresh: () => Promise; + /** + * Says the page shows a child this index does not list, as one dispatched after the index was + * last read is. The index is read again, once per child and once for every child named in the + * same commit. + */ + discover: (threadId: string) => void; isError: boolean; discoveryEnabled: boolean; }; @@ -26,6 +33,7 @@ const defaultValue: ParentSubagentsContextValue = { byMessageId: emptyMap, byThreadId: emptyThreadMap, refresh: async () => undefined, + discover: () => undefined, isError: false, discoveryEnabled: false, }; @@ -46,6 +54,7 @@ export function ParentSubagentsProvider({ const queryClient = useQueryClient(); const { useParentSubagentIndex } = useStreamHost(); const parent = useContext(ParentSubagentsContext); + const sharedFollows = useThreadFollows(); const inherited = parent.conversationId === conversationId && parent.discoveryEnabled ? parent : null; // Observe already-loaded history without fetching it or rerendering on streamed text. @@ -82,6 +91,24 @@ export function ParentSubagentsProvider({ const result = await refetch(); return result.data; }, [refetch]); + /** Children already asked about under this conversation, and whether a read is scheduled. */ + const asks = useMemo( + () => ({ conversationId, asked: new Set(), scheduled: false }), + [conversationId], + ); + const discover = useCallback( + (threadId: string) => { + if (!discoveryEnabled || asks.asked.has(threadId)) return; + asks.asked.add(threadId); + if (asks.scheduled) return; + asks.scheduled = true; + queueMicrotask(() => { + asks.scheduled = false; + void refetch(); + }); + }, + [discoveryEnabled, asks, refetch], + ); const value = useMemo(() => { if (inherited != null) return inherited; const byMessageId = new Map(); @@ -99,11 +126,28 @@ export function ParentSubagentsProvider({ return updated === 0 ? left.threadId.localeCompare(right.threadId) : updated; }); } - return { conversationId, byMessageId, byThreadId, refresh, isError, discoveryEnabled }; - }, [conversationId, data, refresh, isError, discoveryEnabled, inherited]); + return { + conversationId, + byMessageId, + byThreadId, + refresh, + discover, + isError, + discoveryEnabled, + }; + }, [conversationId, data, refresh, discover, isError, discoveryEnabled, inherited]); + /** A provider nested under one for the same conversation shares that one's followers. */ + const followers = + inherited != null && sharedFollows != null ? ( + children + ) : ( + + {children} + + ); return ( - {children} + {followers} ); } From d0e4c8ab46e60d97f09a156ef89cb91d92d5312f Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Wed, 18 Nov 2026 06:15:40 -0500 Subject: [PATCH 2/8] =?UTF-8?q?=F0=9F=AA=9F=20fix:=20Draw=20the=20Card's?= =?UTF-8?q?=20Row=20Live=20and=20Skip=20Label=20Reservations=20That=20Draw?= =?UTF-8?q?=20Nothing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- e2e/specs/mock/subagent-activity.spec.ts | 7 +++- .../src/components/parts/SubagentCall.tsx | 37 ++++++++++--------- .../parts/__tests__/SubagentCall.spec.tsx | 29 ++++++++++++++- 3 files changed, 51 insertions(+), 22 deletions(-) diff --git a/e2e/specs/mock/subagent-activity.spec.ts b/e2e/specs/mock/subagent-activity.spec.ts index 81b4f40f97e..4e68426f92e 100644 --- a/e2e/specs/mock/subagent-activity.spec.ts +++ b/e2e/specs/mock/subagent-activity.spec.ts @@ -242,9 +242,12 @@ test.describe('detached subagent activity', () => { }); }); +/** A subagent card's row is a picture of the child's thread, not part of this one: its folds + * take no pointer and are not this history's to expand. */ +const NOT_A_PREVIEW = ':not([data-subagent-preview] *)'; const HISTORY_FOLDS = - '[data-fold-root] > div > button[aria-expanded="false"]:visible, ' + - '[data-testid="activity-phase-card"] > div > div > button[aria-expanded="false"]:visible'; + `[data-fold-root] > div > button[aria-expanded="false"]${NOT_A_PREVIEW}:visible, ` + + `[data-testid="activity-phase-card"] > div > div > button[aria-expanded="false"]${NOT_A_PREVIEW}:visible`; /** How long a click waits for a fold that was counted a moment ago. */ const FOLD_CLICK_TIMEOUT_MS = 1_000; diff --git a/packages/chat/src/components/parts/SubagentCall.tsx b/packages/chat/src/components/parts/SubagentCall.tsx index eb0b820e485..5dd1e8ee353 100644 --- a/packages/chat/src/components/parts/SubagentCall.tsx +++ b/packages/chat/src/components/parts/SubagentCall.tsx @@ -21,6 +21,7 @@ import { import { isLiveSubagentStatus, subagentStatusLabelKey } from '../../react/subagents/status'; import { isSelfSpawn as isSelfSpawnType } from '../../react/subagents/author'; import { parseSubagentBackgroundHandle } from '../../core/parts/handle'; +import { lastVisibleContentIdx } from '../../core/parts/activityLabels'; import { resolveSubagentAgentId } from '../../react/subagents/identity'; import { useOpenSubagentPanel } from '../../react/subagents/surface'; import { useParentSubagents } from '../../react/subagents/parents'; @@ -258,13 +259,9 @@ export default function SubagentCall({ /** The child's newest part: the row it is on right now. */ const tailPart = useMemo(() => { - const parts = progress?.contentParts ?? []; - for (let index = parts.length - 1; index >= 0; index--) { - if (parts[index] != null) { - return { part: parts[index] as TMessageContentParts, index }; - } - } - return undefined; + const parts = (progress?.contentParts ?? []) as TMessageContentParts[]; + const index = lastVisibleContentIdx(parts); + return index < 0 ? undefined : { part: parts[index], index }; }, [progress?.contentParts]); /** Only throttle once the live text is long enough to fill the row. Earlier updates pass @@ -568,17 +565,20 @@ function useDetachedStatus(threadId: string, taskId: string) { ); } -const pickTailPart = (tail: TMessage | null): TMessageContentParts | null => { +/** + * Where a reply's newest row is: its last part that draws something. A batch of tool calls ends + * with an empty label reservation, which draws nothing until its label arrives. + */ +const pickTailIndex = (tail: TMessage | null): number | null => { if (tail == null || tail.isCreatedByUser) return null; - const parts = tail.content ?? []; - for (let index = parts.length - 1; index >= 0; index--) { - const part = parts[index]; - if (part != null) return part; - } - return null; + const index = lastVisibleContentIdx(tail.content); + return index < 0 ? null : index; }; -const pickTailLength = (tail: TMessage | null): number | null => tail?.content?.length ?? null; +const pickTailPart = (tail: TMessage | null): TMessageContentParts | null => { + const index = pickTailIndex(tail); + return index == null ? null : (tail?.content?.[index] ?? null); +}; /** * A detached child's row, read from its thread's messages wherever something is following that @@ -590,11 +590,11 @@ function DetachedPreview({ threadId, taskId }: { threadId: string; taskId: strin /** A running child is followed for its row; the page follows it once, with or without a panel. */ useThreadInterest(threadId, { live: true, enabled: live, passive: true }); const part = useBranchTailSelect(threadId, threadId, pickTailPart); - const length = useBranchTailSelect(threadId, threadId, pickTailLength); + const index = useBranchTailSelect(threadId, threadId, pickTailIndex); if (part == null || !live) { return null; } - return ; + return ; } function extractSubagentType(args: SubagentCallProps['args']): string { @@ -659,7 +659,8 @@ function SubagentPreview({ showThinking: false, isSubmitting: true, isLast: true, - isLatestMessage: false, + /** The row is live: a renderer told otherwise draws a tool still running as stopped. */ + isLatestMessage: true, })} diff --git a/packages/chat/src/components/parts/__tests__/SubagentCall.spec.tsx b/packages/chat/src/components/parts/__tests__/SubagentCall.spec.tsx index 131fedb3515..99e22014769 100644 --- a/packages/chat/src/components/parts/__tests__/SubagentCall.spec.tsx +++ b/packages/chat/src/components/parts/__tests__/SubagentCall.spec.tsx @@ -123,8 +123,10 @@ const partLine = (part: object | undefined): string => { return toolCall?.name ?? text ?? think ?? ''; }; const partsHost = createMessagePartsHost({ - renderContentParts: ({ content }) => ( -
    {content.map(partLine).join('|')}
    + renderContentParts: ({ content, isSubmitting, isLatestMessage }) => ( +
    + {content.map(partLine).join('|')} +
    ), }); @@ -528,6 +530,8 @@ describe('SubagentCall', () => { const row = screen.getByTestId('thread-row'); expect(row).toHaveTextContent('calculator'); expect(row).not.toHaveTextContent('Working…'); + /** Drawn as a live row, or a tool still running would read as one that was stopped. */ + expect(row).toHaveAttribute('data-live', 'true'); const preview = row.closest('[data-subagent-preview]'); expect(preview).toHaveAttribute('aria-hidden', 'true'); expect(preview).toHaveAttribute('inert'); @@ -656,6 +660,27 @@ describe('SubagentCall', () => { ).toBeInTheDocument(); }); + it('keeps the last row that draws something when an empty label reservation follows it', () => { + mockIndexedChildren = indexed('running'); + seedQueries = (client) => + client.setQueryData( + ['messages', 'child-thread-1'], + [ + threadMessages[0], + { + ...threadMessages[1], + content: [ + ...(threadMessages[1].content ?? []), + { type: 'activity_label', activity_label: '' }, + ], + }, + ], + ); + mountDetached(); + + expect(screen.getByTestId('thread-row')).toHaveTextContent('read_file'); + }); + it('is not followed and shows no row once it has finished', () => { mockIndexedChildren = indexed('completed'); mountDetached(); From b358ec0cf3e1d2a28e8b114301ac85c2884f4200 Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Wed, 18 Nov 2026 07:23:36 -0500 Subject: [PATCH 3/8] =?UTF-8?q?=F0=9F=AA=9F=20fix:=20Show=20a=20Card's=20R?= =?UTF-8?q?ow=20Only=20While=20Its=20Thread=20Is=20Followed,=20and=20Throt?= =?UTF-8?q?tle=20a=20Detached=20Row=20Too?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/components/parts/SubagentCall.tsx | 56 ++++++++++++------ .../parts/__tests__/SubagentCall.spec.tsx | 57 +++++++++++++++++++ .../subagents/__tests__/follows.spec.tsx | 30 +++++++++- packages/chat/src/react/subagents/follows.tsx | 15 ++++- 4 files changed, 139 insertions(+), 19 deletions(-) diff --git a/packages/chat/src/components/parts/SubagentCall.tsx b/packages/chat/src/components/parts/SubagentCall.tsx index 5dd1e8ee353..328ea27c8f2 100644 --- a/packages/chat/src/components/parts/SubagentCall.tsx +++ b/packages/chat/src/components/parts/SubagentCall.tsx @@ -264,18 +264,7 @@ export default function SubagentCall({ return index < 0 ? undefined : { part: parts[index], index }; }, [progress?.contentParts]); - /** Only throttle once the live text is long enough to fill the row. Earlier updates pass - * through so the first tokens appear right away, not after the throttle window. */ - const shouldThrottlePreview = useMemo(() => { - if (!running || tailPart == null) return false; - const { part } = tailPart; - let text: unknown = ''; - if (part.type === ContentTypes.TEXT) text = part.text; - else if (part.type === ContentTypes.THINK) text = part.think; - return typeof text === 'string' && text.length >= PREVIEW_PASSTHROUGH_CHARS; - }, [running, tailPart]); - - const preview = useTickerThrottle(tailPart, SUBAGENT_TICKER_THROTTLE_MS, shouldThrottlePreview); + const preview = useThrottledRow(tailPart, running); const showPreview = running && preview != null; const prompt = getSubagentPrompt(args); @@ -587,14 +576,49 @@ const pickTailPart = (tail: TMessage | null): TMessageContentParts | null => { function DetachedPreview({ threadId, taskId }: { threadId: string; taskId: string }): ReactNode { const status = useDetachedStatus(threadId, taskId); const live = status != null && isLiveSubagentStatus(status); - /** A running child is followed for its row; the page follows it once, with or without a panel. */ - useThreadInterest(threadId, { live: true, enabled: live, passive: true }); + /** + * A running child is followed for its row; the page follows it once, with or without a panel. + * Its messages outlive the following: a child the page has no room to preview keeps what was + * last read for it, which is not what it is doing now, so its row is shown only while it is + * being followed. + */ + const followed = useThreadInterest(threadId, { live: true, enabled: live, passive: true }); const part = useBranchTailSelect(threadId, threadId, pickTailPart); const index = useBranchTailSelect(threadId, threadId, pickTailIndex); - if (part == null || !live) { + const row = useMemo( + () => (part == null || index == null ? undefined : { part, index }), + [part, index], + ); + const shown = useThrottledRow(row, live && followed); + if (shown == null || !live || !followed) { return null; } - return ; + return ( + + ); +} + +type PreviewRow = { part: TMessageContentParts; index: number }; + +/** + * A child's row at the pace the card redraws it. Short text passes straight through, so the + * first tokens appear at once; once the live text is long enough to fill the row it refreshes on + * the throttle, wherever the row comes from, instead of on every token. + */ +function useThrottledRow(row: PreviewRow | undefined, running: boolean): PreviewRow | undefined { + const throttled = useMemo(() => { + if (!running || row == null) return false; + const { part } = row; + let text: unknown = ''; + if (part.type === ContentTypes.TEXT) text = part.text; + else if (part.type === ContentTypes.THINK) text = part.think; + return typeof text === 'string' && text.length >= PREVIEW_PASSTHROUGH_CHARS; + }, [running, row]); + return useTickerThrottle(row, SUBAGENT_TICKER_THROTTLE_MS, throttled); } function extractSubagentType(args: SubagentCallProps['args']): string { diff --git a/packages/chat/src/components/parts/__tests__/SubagentCall.spec.tsx b/packages/chat/src/components/parts/__tests__/SubagentCall.spec.tsx index 99e22014769..4762c0a1aad 100644 --- a/packages/chat/src/components/parts/__tests__/SubagentCall.spec.tsx +++ b/packages/chat/src/components/parts/__tests__/SubagentCall.spec.tsx @@ -35,6 +35,7 @@ import { subagentProgressKey, } from '../../../react/subagents/state'; import PackageSubagentCall, { SUBAGENT_TICKER_THROTTLE_MS } from '../SubagentCall'; +import { MAX_PREVIEWED_THREADS, useThreadInterest } from '../../../react/subagents/follows'; import { ParentSubagentsProvider } from '../../../react/subagents/parents'; import { createSubagentsHost } from '../../../__fixtures__/subagentsHost'; import { createMessagePartsHost } from '../../../__fixtures__/partsHost'; @@ -133,6 +134,14 @@ const partsHost = createMessagePartsHost({ const mockUseThreadChat = jest.fn(); const mockRefetchIndex = jest.fn(async () => ({ data: undefined })); let seedQueries: ((client: QueryClient) => void) | undefined; +/** Other readers on the page, mounted ahead of the card under the same providers. */ +let neighbours: ReactNode; + +/** Another running child's card, as far as the page's followers are concerned. */ +function OtherPreview({ threadId }: { threadId: string }): null { + useThreadInterest(threadId, { live: true, enabled: true, passive: true }); + return null; +} const subagentsHost = createSubagentsHost({ useAgentsMap: () => agents, @@ -197,6 +206,7 @@ function Providers({ + {neighbours} {withSurface ? ( {card} ) : ( @@ -215,6 +225,7 @@ afterEach(() => { mockIndexedChildren = new Map(); currentMessage = defaultMessage; seedQueries = undefined; + neighbours = undefined; mockUseThreadChat.mockReset(); mockRefetchIndex.mockClear(); }); @@ -681,6 +692,52 @@ describe('SubagentCall', () => { expect(screen.getByTestId('thread-row')).toHaveTextContent('read_file'); }); + it('shows no row for a child the page has no room to follow, whatever was last read for it', () => { + mockIndexedChildren = indexed('running'); + neighbours = Array.from({ length: MAX_PREVIEWED_THREADS }, (_, n) => ( + + )); + mountDetached(); + + /** Its messages are in the cache, but nothing is reading its stream, so they are stale. */ + expect(mockUseThreadChat).not.toHaveBeenCalledWith( + 'parent-conversation', + 'child-thread-1', + expect.anything(), + ); + expect(screen.queryByTestId('thread-row')).toBeNull(); + }); + + it('refreshes a long live row on the throttle, as a foreground child does', async () => { + jest.useFakeTimers(); + mockIndexedChildren = indexed('running'); + const first = 'First live preview '.repeat(8).trim(); + const second = 'Second live preview '.repeat(8).trim(); + const withText = (text: string) => [ + threadMessages[0], + { ...threadMessages[1], content: [{ type: 'text', text }] }, + ]; + let cache: QueryClient | undefined; + seedQueries = (client) => { + cache = client; + client.setQueryData(['messages', 'child-thread-1'], withText(first)); + }; + mountDetached(); + expect(screen.getByTestId('thread-row')).toHaveTextContent(first); + + /** The cache tells its readers on a timer; a moment later the newer text has reached the + * card and is being held back. */ + await act(async () => { + cache?.setQueryData(['messages', 'child-thread-1'], withText(second)); + await jest.advanceTimersByTimeAsync(1); + }); + expect(screen.getByTestId('thread-row')).toHaveTextContent(first); + await act(async () => { + await jest.advanceTimersByTimeAsync(SUBAGENT_TICKER_THROTTLE_MS); + }); + expect(screen.getByTestId('thread-row')).toHaveTextContent(second); + }); + it('is not followed and shows no row once it has finished', () => { mockIndexedChildren = indexed('completed'); mountDetached(); diff --git a/packages/chat/src/react/subagents/__tests__/follows.spec.tsx b/packages/chat/src/react/subagents/__tests__/follows.spec.tsx index 75ed6d6bc7d..51e92183d15 100644 --- a/packages/chat/src/react/subagents/__tests__/follows.spec.tsx +++ b/packages/chat/src/react/subagents/__tests__/follows.spec.tsx @@ -61,10 +61,12 @@ function Reader({ threadId, live = false }: { threadId: string; live?: boolean } } function Preview({ threadId }: { threadId: string }): null { - useThreadInterest(threadId, { live: true, enabled: true, passive: true }); + admitted[threadId] = useThreadInterest(threadId, { live: true, enabled: true, passive: true }); return null; } +let admitted: Record; + let seen: Record; beforeEach(() => { @@ -73,6 +75,7 @@ beforeEach(() => { seen = {}; mounted = new Set(); unmounts = 0; + admitted = {}; jest.useFakeTimers(); }); @@ -170,6 +173,31 @@ describe('ThreadFollowsProvider', () => { expect([...mounted].sort()).toEqual(previews.slice(1).sort()); }); + it('tells a preview whether its thread is being followed, including once it loses its room', () => { + const previews = Array.from({ length: MAX_PREVIEWED_THREADS + 1 }, (_, n) => `preview-${n}`); + const overflow = previews[MAX_PREVIEWED_THREADS]; + const cards = previews.map((threadId) => ); + const view = render(page(<>{cards})); + expect(admitted[previews[0]]).toBe(true); + expect(admitted[overflow]).toBe(false); + + /** Opened, it is followed whatever the cap; closed again, it is back to having no room. */ + view.rerender( + page( + <> + {cards} + + , + ), + ); + expect(admitted[overflow]).toBe(true); + + view.rerender(page(<>{cards})); + act(() => jest.advanceTimersByTime(THREAD_LINGER_MS)); + expect(admitted[overflow]).toBe(false); + expect(mounted.has(overflow)).toBe(false); + }); + it('follows nothing where no page shares followers', () => { function Lone(): null { seen.lone = useFollowedThread('thread-1', { live: true, enabled: true }); diff --git a/packages/chat/src/react/subagents/follows.tsx b/packages/chat/src/react/subagents/follows.tsx index a9711a6a253..d81269b63b8 100644 --- a/packages/chat/src/react/subagents/follows.tsx +++ b/packages/chat/src/react/subagents/follows.tsx @@ -126,6 +126,11 @@ export class ThreadFollows { return this.followed; }; + /** Whether the thread is among those followed now, which a preview past the cap is not. */ + isFollowed(threadId: string): boolean { + return this.getThreads().some((thread) => thread.threadId === threadId); + } + subscribeResult(threadId: string, listener: Listener): () => void { const listeners = this.resultListeners.get(threadId) ?? new Set(); listeners.add(listener); @@ -233,14 +238,18 @@ export function ThreadFollowsProvider({ ); } +const noListener = (): (() => void) => unsubscribed; + /** * Says this reader wants a thread followed, without reading what the follower holds: a card - * reads its row from the thread's messages and has no use for every other change. + * reads its row from the thread's messages and has no use for every other change. Returns + * whether the thread is being followed, which a preview with no room on the page is not. Where + * no page shares followers there is nothing to be admitted to, and the answer is yes. */ export function useThreadInterest( threadId: string, { live, enabled, passive = false }: { live: boolean; enabled: boolean; passive?: boolean }, -): void { +): boolean { const follows = useThreadFollows(); useEffect(() => { if (follows == null || !enabled || threadId === '') { @@ -248,6 +257,8 @@ export function useThreadInterest( } return follows.acquire(threadId, { live, passive }); }, [follows, threadId, live, enabled, passive]); + const followed = (): boolean => follows == null || follows.isFollowed(threadId); + return useSyncExternalStore(follows?.subscribeThreads ?? noListener, followed, followed); } /** From 5a729ba4e5df855aac48c304eb00f39ed67ef929 Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Wed, 18 Nov 2026 07:24:17 -0500 Subject: [PATCH 4/8] =?UTF-8?q?=F0=9F=AA=9F=20chore:=20Sort=20the=20Card?= =?UTF-8?q?=20Spec's=20Imports?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chat/src/components/parts/__tests__/SubagentCall.spec.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/chat/src/components/parts/__tests__/SubagentCall.spec.tsx b/packages/chat/src/components/parts/__tests__/SubagentCall.spec.tsx index 4762c0a1aad..5e69edae7a1 100644 --- a/packages/chat/src/components/parts/__tests__/SubagentCall.spec.tsx +++ b/packages/chat/src/components/parts/__tests__/SubagentCall.spec.tsx @@ -34,8 +34,8 @@ import { subagentProgressByToolCallId, subagentProgressKey, } from '../../../react/subagents/state'; -import PackageSubagentCall, { SUBAGENT_TICKER_THROTTLE_MS } from '../SubagentCall'; import { MAX_PREVIEWED_THREADS, useThreadInterest } from '../../../react/subagents/follows'; +import PackageSubagentCall, { SUBAGENT_TICKER_THROTTLE_MS } from '../SubagentCall'; import { ParentSubagentsProvider } from '../../../react/subagents/parents'; import { createSubagentsHost } from '../../../__fixtures__/subagentsHost'; import { createMessagePartsHost } from '../../../__fixtures__/partsHost'; From cd577591c3e0470a44ccf3197f771095683e8270 Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Wed, 18 Nov 2026 07:32:27 -0500 Subject: [PATCH 5/8] =?UTF-8?q?=F0=9F=AA=9F=20fix:=20Draw=20the=20Card's?= =?UTF-8?q?=20Row=20as=20a=20Picture=20That=20Registers,=20Claims=20and=20?= =?UTF-8?q?Reveals=20Nothing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- client/src/components/Artifacts/Artifact.tsx | 6 +- .../__tests__/Artifact.preview.test.tsx | 76 +++++++++++++++++++ .../src/components/parts/SubagentCall.tsx | 47 ++++++++---- .../parts/__tests__/SubagentCall.spec.tsx | 47 ++++++++++-- packages/chat/src/react.ts | 1 + packages/chat/src/react/parts/preview.ts | 12 +++ 6 files changed, 169 insertions(+), 20 deletions(-) create mode 100644 client/src/components/Artifacts/__tests__/Artifact.preview.test.tsx create mode 100644 packages/chat/src/react/parts/preview.ts diff --git a/client/src/components/Artifacts/Artifact.tsx b/client/src/components/Artifacts/Artifact.tsx index e7993e2b35c..0d6634a7337 100644 --- a/client/src/components/Artifacts/Artifact.tsx +++ b/client/src/components/Artifacts/Artifact.tsx @@ -3,6 +3,7 @@ import throttle from 'lodash/throttle'; import { visit } from 'unist-util-visit'; import { useSetRecoilState } from 'recoil'; import { useLocation } from 'react-router-dom'; +import { useIsPartsPreview } from '@librechat/chat/react'; import type { Pluggable } from 'unified'; import type { Artifact } from '~/common'; import { useMessageContext, useArtifactContext } from '~/Providers'; @@ -48,6 +49,8 @@ export function Artifact({ node: unknown; }) { const location = useLocation(); + /** A picture of a row drawn elsewhere: the row itself registers the artifact. */ + const isPreview = useIsPartsPreview(); const { messageId } = useMessageContext(); const { getNextIndex, resetCounter } = useArtifactContext(); const artifactIndex = useRef(getNextIndex(false)).current; @@ -89,7 +92,7 @@ export function Artifact({ lastUpdateTime: now, }; - if (!isArtifactRoute(location.pathname)) { + if (isPreview || !isArtifactRoute(location.pathname)) { return setArtifact(currentArtifact); } @@ -118,6 +121,7 @@ export function Artifact({ messageId, artifactIndex, location.pathname, + isPreview, ]); useEffect(() => { diff --git a/client/src/components/Artifacts/__tests__/Artifact.preview.test.tsx b/client/src/components/Artifacts/__tests__/Artifact.preview.test.tsx new file mode 100644 index 00000000000..88ffc5dde8a --- /dev/null +++ b/client/src/components/Artifacts/__tests__/Artifact.preview.test.tsx @@ -0,0 +1,76 @@ +import React from 'react'; +import { MemoryRouter } from 'react-router-dom'; +import { RecoilRoot, useRecoilValue } from 'recoil'; +import { act, render } from '@testing-library/react'; +import { PartsPreviewContext } from '@librechat/chat/react'; +import type { ReactNode } from 'react'; +import { MessageContext, ArtifactProvider } from '~/Providers'; +import { artifactsState } from '~/store/artifacts'; +import { Artifact } from '../Artifact'; + +jest.mock('../ArtifactButton', () => ({ + __esModule: true, + default: () => null, +})); + +let registered: Record | null | undefined; + +function Registry(): null { + registered = useRecoilValue(artifactsState) as Record | null; + return null; +} + +const message = { + messageId: 'message-1', + conversationId: 'conversation-1', + partIndex: 0, + isExpanded: false, + isSubmitting: false, + isLatestMessage: false, +} as unknown as React.ContextType; + +const page = (ui: ReactNode) => ( + + + + + + {ui} + + + + +); + +const artifact = ( + + {'

    hello

    '} +
    +); + +const settle = () => + act(async () => { + await new Promise((resolve) => setTimeout(resolve, 80)); + }); + +describe('Artifact registration', () => { + beforeEach(() => { + registered = undefined; + }); + + it('registers an artifact a message row draws', async () => { + render(page(artifact)); + await settle(); + + expect(Object.keys(registered ?? {})).toEqual(['chart_text/html_chart_message-1']); + }); + + it('registers nothing for a picture of a row drawn elsewhere', async () => { + render( + page({artifact}), + ); + await settle(); + + expect(Object.keys(registered ?? {})).toEqual([]); + }); +}); diff --git a/packages/chat/src/components/parts/SubagentCall.tsx b/packages/chat/src/components/parts/SubagentCall.tsx index 328ea27c8f2..9e5c7250e91 100644 --- a/packages/chat/src/components/parts/SubagentCall.tsx +++ b/packages/chat/src/components/parts/SubagentCall.tsx @@ -9,8 +9,8 @@ import type { TAttachment, TMessageContentParts, } from 'librechat-data-provider'; +import type { Dispatch, ReactNode, SetStateAction } from 'react'; import type { Agent } from 'librechat-data-provider'; -import type { ReactNode } from 'react'; import type { MessagePartMessage, MessagePartsHost, ToolCallChrome } from '../../react/host'; import type { SubagentContentPreview } from '../../react/subagents/state'; import { @@ -19,6 +19,7 @@ import { useSubagentProgress, } from '../../react/subagents/state'; import { isLiveSubagentStatus, subagentStatusLabelKey } from '../../react/subagents/status'; +import { MessagePartsHostProvider, useMessagePartsHost } from '../../react/host'; import { isSelfSpawn as isSelfSpawnType } from '../../react/subagents/author'; import { parseSubagentBackgroundHandle } from '../../core/parts/handle'; import { lastVisibleContentIdx } from '../../core/parts/activityLabels'; @@ -27,12 +28,12 @@ import { useOpenSubagentPanel } from '../../react/subagents/surface'; import { useParentSubagents } from '../../react/subagents/parents'; import { useThreadInterest } from '../../react/subagents/follows'; import { getSubagentPrompt } from '../../react/subagents/prompt'; +import { PartsPreviewContext } from '../../react/parts/preview'; +import { FailedRevealContext, useFailedReveal } from './reveal'; import { useToolCallIntent } from '../../react/parts/intent'; import { useBranchTailSelect } from '../../react/latest'; -import { useMessagePartsHost } from '../../react/host'; import { useToolPreparation } from './preparation'; import { isError } from '../../core/parts/output'; -import { useFailedReveal } from './reveal'; import { FOLD_GLYPH_CLASS } from './rows'; export interface SubagentCallProps { @@ -635,6 +636,14 @@ function extractSubagentType(args: SubagentCallProps['args']): string { } const PREVIEW_ROW_HEIGHT = 'h-8'; +/** No request to reveal a failure reaches a picture, and it claims no focus. */ +const NO_REVEAL = { tick: 0, claimFocus: null }; +/** A tool artifact is always some other row's: a picture never draws it and never takes it. */ +const PICTURE_CLAIM: [string | null, Dispatch>] = [ + 'subagent-preview', + () => undefined, +]; +const useNoClaim = (): [string | null, Dispatch>] => PICTURE_CLAIM; /** * The line above the row dissolves at the top edge instead of being cut through. A mask stencil, * not paint: only its alpha is read, so it is not a theme color. @@ -662,6 +671,7 @@ function SubagentPreview({ }): ReactNode { const host = useMessagePartsHost(); const content = useMemo(() => [part], [part]); + const pictureHost = useMemo(() => ({ ...host, useToolArtifactClaim: useNoClaim }), [host]); return (
    {/* Held to its last line: what the child wrote most recently is the part in view. */}
    - {host.renderContentParts({ - content, - messageId, - conversationId: null, - isCreatedByUser: false, - showThinking: false, - isSubmitting: true, - isLast: true, - /** The row is live: a renderer told otherwise draws a tool still running as stopped. */ - isLatestMessage: true, - })} + {/* A picture of the child's row and nothing more: the row itself registers what it + holds with the app, owns its artifacts and answers a request to reveal a failure. */} + + + + {host.renderContentParts({ + content, + messageId, + conversationId: null, + isCreatedByUser: false, + showThinking: false, + isSubmitting: true, + isLast: true, + /** The row is live: a renderer told otherwise draws a tool still running as + * stopped. */ + isLatestMessage: true, + })} + + +
    ); diff --git a/packages/chat/src/components/parts/__tests__/SubagentCall.spec.tsx b/packages/chat/src/components/parts/__tests__/SubagentCall.spec.tsx index 5e69edae7a1..92a09490921 100644 --- a/packages/chat/src/components/parts/__tests__/SubagentCall.spec.tsx +++ b/packages/chat/src/components/parts/__tests__/SubagentCall.spec.tsx @@ -1,7 +1,7 @@ /** * @jest-environment jsdom */ -import React, { useState } from 'react'; +import React, { useState, useEffect, useContext } from 'react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { Provider as JotaiProvider, createStore, useAtomValue, useStore } from 'jotai'; import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; @@ -35,14 +35,15 @@ import { subagentProgressKey, } from '../../../react/subagents/state'; import { MAX_PREVIEWED_THREADS, useThreadInterest } from '../../../react/subagents/follows'; +import { MessagePartsHostProvider, useMessagePartsHost } from '../../../react/host'; import PackageSubagentCall, { SUBAGENT_TICKER_THROTTLE_MS } from '../SubagentCall'; import { ParentSubagentsProvider } from '../../../react/subagents/parents'; import { createSubagentsHost } from '../../../__fixtures__/subagentsHost'; import { createMessagePartsHost } from '../../../__fixtures__/partsHost'; import { ChatSurfaceProvider } from '../../../react/subagents/provider'; import { SubagentsHostProvider } from '../../../react/subagents/host'; +import { useIsPartsPreview } from '../../../react/parts/preview'; import { StreamHostProvider } from '../../../react/stream/host'; -import { MessagePartsHostProvider } from '../../../react/host'; import { FailedRevealContext } from '../reveal'; import { FOLD_GLYPH_SELECTOR } from '../rows'; import { litFoldPath } from '../rail'; @@ -123,11 +124,40 @@ const partLine = (part: object | undefined): string => { }; return toolCall?.name ?? text ?? think ?? ''; }; +/** What a row is told when it is drawn, read the way the app's parts read it. */ +function ThreadRow({ line, live }: { line: string; live: boolean }): ReactNode { + const [claim, setClaim] = useMessagePartsHost().useToolArtifactClaim('artifact-1'); + const reveal = useContext(FailedRevealContext); + useEffect(() => { + setClaim('thread-row'); + }, [setClaim]); + return ( +
    + {line} +
    + ); +} + +let claimedArtifact: string | null = null; const partsHost = createMessagePartsHost({ + /** One claim for the page, as the app keeps one per artifact. */ + useToolArtifactClaim: () => [ + claimedArtifact, + (next) => { + claimedArtifact = typeof next === 'function' ? next(claimedArtifact) : next; + }, + ], renderContentParts: ({ content, isSubmitting, isLatestMessage }) => ( -
    - {content.map(partLine).join('|')} -
    + ), }); @@ -226,6 +256,7 @@ afterEach(() => { currentMessage = defaultMessage; seedQueries = undefined; neighbours = undefined; + claimedArtifact = null; mockUseThreadChat.mockReset(); mockRefetchIndex.mockClear(); }); @@ -543,6 +574,12 @@ describe('SubagentCall', () => { expect(row).not.toHaveTextContent('Working…'); /** Drawn as a live row, or a tool still running would read as one that was stopped. */ expect(row).toHaveAttribute('data-live', 'true'); + /** And as a picture of that row: it is told so, it takes no artifact from the row it + * pictures, and a request to reveal a failure does not reach it. */ + expect(row).toHaveAttribute('data-preview', 'true'); + expect(claimedArtifact).toBeNull(); + rendered.reveal(); + expect(screen.getByTestId('thread-row')).toHaveAttribute('data-reveal', '0'); const preview = row.closest('[data-subagent-preview]'); expect(preview).toHaveAttribute('aria-hidden', 'true'); expect(preview).toHaveAttribute('inert'); diff --git a/packages/chat/src/react.ts b/packages/chat/src/react.ts index 9fde07ebc7e..0d0b6b5781c 100644 --- a/packages/chat/src/react.ts +++ b/packages/chat/src/react.ts @@ -213,6 +213,7 @@ export { useOptionalMessagesOperations, useOptionalMessagesConversation, } from './react/messages/view'; +export { PartsPreviewContext, useIsPartsPreview } from './react/parts/preview'; export type { MessagesEditing, MessagesOperations, diff --git a/packages/chat/src/react/parts/preview.ts b/packages/chat/src/react/parts/preview.ts new file mode 100644 index 00000000000..ebb47642506 --- /dev/null +++ b/packages/chat/src/react/parts/preview.ts @@ -0,0 +1,12 @@ +import { createContext, useContext } from 'react'; +import type { Context } from 'react'; + +/** + * Whether the parts under this are a picture of a row drawn somewhere else, as a subagent card's + * row is of its child's thread. A picture paints and nothing more: a part that would register + * itself with the app, claim something only one mounted row may hold, or act on the reader's + * behalf does none of that here, because the row it pictures already does. + */ +export const PartsPreviewContext: Context = createContext(false); + +export const useIsPartsPreview = (): boolean => useContext(PartsPreviewContext); From 00e4bf4362770fe4390453de4fa97282fb97f668 Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Wed, 18 Nov 2026 07:38:02 -0500 Subject: [PATCH 6/8] =?UTF-8?q?=F0=9F=AA=9F=20test:=20Give=20the=20Artifac?= =?UTF-8?q?t=20Preview=20Test=20the=20Props=20Its=20Type=20Requires?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../components/Artifacts/__tests__/Artifact.preview.test.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/components/Artifacts/__tests__/Artifact.preview.test.tsx b/client/src/components/Artifacts/__tests__/Artifact.preview.test.tsx index 88ffc5dde8a..27231965070 100644 --- a/client/src/components/Artifacts/__tests__/Artifact.preview.test.tsx +++ b/client/src/components/Artifacts/__tests__/Artifact.preview.test.tsx @@ -43,7 +43,7 @@ const page = (ui: ReactNode) => ( ); const artifact = ( - + {'

    hello

    '}
    ); From a6f41f34308e6501c60e4855cd8f612d542d28b3 Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Wed, 18 Nov 2026 07:53:38 -0500 Subject: [PATCH 7/8] =?UTF-8?q?=F0=9F=AA=9F=20refactor:=20Keep=20the=20Sha?= =?UTF-8?q?red=20Follower=20Registry=20in=20Provider-Scoped=20Jotai=20Atom?= =?UTF-8?q?s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/chat/src/react/subagents/follows.tsx | 292 +++++++++--------- 1 file changed, 143 insertions(+), 149 deletions(-) diff --git a/packages/chat/src/react/subagents/follows.tsx b/packages/chat/src/react/subagents/follows.tsx index d81269b63b8..be2f168173b 100644 --- a/packages/chat/src/react/subagents/follows.tsx +++ b/packages/chat/src/react/subagents/follows.tsx @@ -1,4 +1,7 @@ -import { useMemo, useEffect, useContext, createContext, useSyncExternalStore } from 'react'; +import { useMemo, useEffect, useContext, createContext } from 'react'; +import { selectAtom } from 'jotai/utils'; +import { atom, createStore, useAtomValue, useSetAtom } from 'jotai'; +import type { Atom, PrimitiveAtom } from 'jotai'; import type { Context, ReactNode } from 'react'; import type { FollowedChat } from '../follow'; import { useSubagentsHost } from './host'; @@ -27,142 +30,100 @@ export type ThreadInterest = { passive: boolean; }; +/** + * A thread's readers, and what they last asked for between them, which holds for the moment + * after the last one leaves. + */ +type ThreadReaders = { interests: readonly ThreadInterest[]; live: boolean; opened: boolean }; +type Readers = ReadonlyMap; type FollowedThread = { threadId: string; live: boolean }; -type Listener = () => void; - -const noThreads: readonly FollowedThread[] = []; -const unsubscribed = (): void => undefined; - -/** What a reader holds until the thread's follower has something to report. */ -const opening: FollowedChat = { - chat: undefined, - messages: [], - status: 'ready', - connection: 'idle', - error: undefined, - isLoading: true, - isFollowing: false, - isUnattached: false, - isLoadError: false, - retry: () => undefined, -}; /** * The threads one page follows, each once, however many readers want it: the panel showing a * child's conversation and the card previewing the same child read one stream. A thread is - * followed while any reader is interested and let go when the last one leaves. + * followed while any reader is interested and let go shortly after the last one leaves. The + * atoms belong to one provider, so two pages' followers never meet. */ -export class ThreadFollows { - private readonly interests = new Map>(); - /** What each thread's readers last asked for, which holds while none of them is present. */ - private readonly asked = new Map(); - private readonly results = new Map(); - private readonly threadListeners = new Set(); - private readonly resultListeners = new Map>(); - private followed: readonly FollowedThread[] = noThreads; +export type ThreadFollows = { + /** + * The store the atoms below are read and written in. Its own, so a reader under some other + * Jotai provider than the followers reads the same state they do. + */ + store: ReturnType; + readers: PrimitiveAtom; + /** The threads to follow now: every opened one, then previews in the order they asked. */ + followed: Atom; + /** What a thread's follower last reported; nothing until it has. */ + result: (threadId: string) => PrimitiveAtom; +}; - /** Registers a reader's interest; the result lets it go. */ - acquire(threadId: string, interest: ThreadInterest): () => void { - const readers = this.interests.get(threadId) ?? new Set(); - readers.add(interest); - this.interests.set(threadId, readers); - this.changed(); - return () => { - readers.delete(interest); - if (readers.size > 0) { - this.changed(); - return; - } - setTimeout(() => { - if (readers.size === 0 && this.interests.get(threadId) === readers) { - this.interests.delete(threadId); - this.asked.delete(threadId); - this.changed(); - } - }, THREAD_LINGER_MS); - }; - } +const noReaders: Readers = new Map(); - subscribeThreads = (listener: Listener): (() => void) => { - this.threadListeners.add(listener); - return () => { - this.threadListeners.delete(listener); - }; - }; +const sameThreads = (a: readonly FollowedThread[], b: readonly FollowedThread[]): boolean => + a.length === b.length && + a.every( + (thread, index) => thread.threadId === b[index].threadId && thread.live === b[index].live, + ); - /** The threads to follow now: every opened one, then previews in the order they asked. */ - getThreads = (): readonly FollowedThread[] => { - const next: FollowedThread[] = []; - let previews = 0; - for (const [threadId, readers] of this.interests) { - let { live, opened } = this.asked.get(threadId) ?? { live: false, opened: false }; - if (readers.size > 0) { - live = false; - opened = false; - for (const reader of readers) { - live ||= reader.live; - opened ||= !reader.passive; - } - this.asked.set(threadId, { live, opened }); +const selectFollowed = (readers: Readers): readonly FollowedThread[] => { + const followed: FollowedThread[] = []; + let previews = 0; + for (const [threadId, { live, opened }] of readers) { + if (!opened) { + if (previews >= MAX_PREVIEWED_THREADS) { + continue; } - if (!opened) { - if (previews >= MAX_PREVIEWED_THREADS) { - continue; - } - previews += 1; - } - next.push({ threadId, live }); - } - const same = - next.length === this.followed.length && - next.every( - (thread, index) => - thread.threadId === this.followed[index].threadId && - thread.live === this.followed[index].live, - ); - if (!same) { - this.followed = next; + previews += 1; } - return this.followed; - }; - - /** Whether the thread is among those followed now, which a preview past the cap is not. */ - isFollowed(threadId: string): boolean { - return this.getThreads().some((thread) => thread.threadId === threadId); + followed.push({ threadId, live }); } + return followed; +}; - subscribeResult(threadId: string, listener: Listener): () => void { - const listeners = this.resultListeners.get(threadId) ?? new Set(); - listeners.add(listener); - this.resultListeners.set(threadId, listeners); - return () => { - listeners.delete(listener); - }; - } +const withInterests = (interests: readonly ThreadInterest[], previous?: ThreadReaders) => + interests.length === 0 && previous != null + ? { ...previous, interests } + : { + interests, + live: interests.some((interest) => interest.live), + opened: interests.some((interest) => !interest.passive), + }; - /** What the thread's follower last reported; `opening` until it has. */ - getResult(threadId: string): FollowedChat { - return this.results.get(threadId) ?? opening; - } +const createThreadFollows = (): ThreadFollows => { + const readers = atom(noReaders); + const results = new Map>(); + return { + store: createStore(), + readers, + followed: selectAtom(readers, selectFollowed, sameThreads), + result: (threadId) => { + const known = results.get(threadId); + if (known != null) { + return known; + } + const created = atom(undefined); + results.set(threadId, created); + return created; + }, + }; +}; - /** Called by the thread's follower with each state it reaches, and with nothing when it ends. */ - publish(threadId: string, result: FollowedChat | undefined): void { - if (result == null) { - this.results.delete(threadId); - } else { - this.results.set(threadId, result); - } - for (const listener of this.resultListeners.get(threadId) ?? []) { - listener(); - } - } +/** Read where no page shares followers: nothing is ever written to these. */ +const unshared: ThreadFollows = createThreadFollows(); - private changed(): void { - for (const listener of this.threadListeners) { - listener(); - } - } -} +/** What a reader holds until the thread's follower has something to report. */ +const opening: FollowedChat = { + chat: undefined, + messages: [], + status: 'ready', + connection: 'idle', + error: undefined, + isLoading: true, + isFollowing: false, + isUnattached: false, + isLoadError: false, + retry: () => undefined, +}; const ThreadFollowsContext: Context = createContext< ThreadFollows | undefined @@ -185,10 +146,11 @@ function ThreadFollower({ }): null { const host = useSubagentsHost(); const followed = host.useThreadChat?.(parentConversationId, threadId, { live, enabled: true }); + const report = useSetAtom(follows.result(threadId), follows); useEffect(() => { - follows.publish(threadId, followed); + report(followed); }); - useEffect(() => () => follows.publish(threadId, undefined), [follows, threadId]); + useEffect(() => () => report(undefined), [report]); return null; } @@ -199,11 +161,7 @@ function ThreadFollowers({ follows: ThreadFollows; parentConversationId: string; }): ReactNode { - const threads = useSyncExternalStore( - follows.subscribeThreads, - follows.getThreads, - follows.getThreads, - ); + const threads = useAtomValue(follows.followed, follows); return threads.map((thread) => ( ({ parentConversationId, store: new ThreadFollows() }), + () => ({ parentConversationId, atoms: createThreadFollows() }), [parentConversationId], - ).store; + ).atoms; return ( @@ -238,8 +196,6 @@ export function ThreadFollowsProvider({ ); } -const noListener = (): (() => void) => unsubscribed; - /** * Says this reader wants a thread followed, without reading what the follower holds: a card * reads its row from the thread's messages and has no use for every other change. Returns @@ -250,15 +206,57 @@ export function useThreadInterest( threadId: string, { live, enabled, passive = false }: { live: boolean; enabled: boolean; passive?: boolean }, ): boolean { - const follows = useThreadFollows(); + const shared = useThreadFollows(); + const follows = shared ?? unshared; + const setReaders = useSetAtom(follows.readers, follows); useEffect(() => { - if (follows == null || !enabled || threadId === '') { + if (shared == null || !enabled || threadId === '') { return; } - return follows.acquire(threadId, { live, passive }); - }, [follows, threadId, live, enabled, passive]); - const followed = (): boolean => follows == null || follows.isFollowed(threadId); - return useSyncExternalStore(follows?.subscribeThreads ?? noListener, followed, followed); + const interest: ThreadInterest = { live, passive }; + setReaders((readers) => { + const previous = readers.get(threadId); + const next = new Map(readers); + next.set(threadId, withInterests([...(previous?.interests ?? []), interest], previous)); + return next; + }); + return () => { + setReaders((readers) => { + const previous = readers.get(threadId); + if (previous == null) { + return readers; + } + const next = new Map(readers); + next.set( + threadId, + withInterests( + previous.interests.filter((reader) => reader !== interest), + previous, + ), + ); + return next; + }); + setTimeout(() => { + setReaders((readers) => { + if (readers.get(threadId)?.interests.length !== 0) { + return readers; + } + const next = new Map(readers); + next.delete(threadId); + return next; + }); + }, THREAD_LINGER_MS); + }; + }, [shared, setReaders, threadId, live, enabled, passive]); + const admitted = useMemo( + () => + selectAtom(follows.followed, (threads) => + threads.some((thread) => thread.threadId === threadId), + ), + [follows, threadId], + ); + const followed = useAtomValue(admitted, follows); + return shared == null || followed; } /** @@ -269,16 +267,12 @@ export function useFollowedThread( threadId: string, options: { live: boolean; enabled: boolean; passive?: boolean }, ): FollowedChat | undefined { - const follows = useThreadFollows(); + const shared = useThreadFollows(); useThreadInterest(threadId, options); - const subscribe = useMemo( - () => - follows == null - ? () => unsubscribed - : (listener: Listener) => follows.subscribeResult(threadId, listener), - [follows, threadId], - ); - const read = (): FollowedChat | undefined => follows?.getResult(threadId); - const result = useSyncExternalStore(subscribe, read, read); - return options.enabled ? result : undefined; + const follows = shared ?? unshared; + const result = useAtomValue(follows.result(threadId), follows); + if (shared == null || !options.enabled) { + return undefined; + } + return result ?? opening; } From dfe281062c5c66ec60d84312dbac5bfe1161ac70 Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Wed, 18 Nov 2026 08:07:48 -0500 Subject: [PATCH 8/8] =?UTF-8?q?=F0=9F=91=80=20fix:=20Look=20Again=20for=20?= =?UTF-8?q?a=20Run=20the=20Caller=20Knows=20Of=20Before=20Taking=20It=20to?= =?UTF-8?q?=20Have=20No=20Stream?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chat/src/react/__tests__/follow.spec.tsx | 45 +++++++++++++++++-- packages/chat/src/react/follow.ts | 18 +++++++- 2 files changed, 58 insertions(+), 5 deletions(-) diff --git a/packages/chat/src/react/__tests__/follow.spec.tsx b/packages/chat/src/react/__tests__/follow.spec.tsx index d040bdc0bef..aebd5ec6996 100644 --- a/packages/chat/src/react/__tests__/follow.spec.tsx +++ b/packages/chat/src/react/__tests__/follow.spec.tsx @@ -9,7 +9,7 @@ import type { ReactNode } from 'react'; import type { ChatStream, ChatTransport, ChatStreamStatus } from '../../core'; import type { FollowChatOptions } from '../follow'; import { MAX_RETRIES, getReconnectDelay } from '../../core'; -import { useFollowChat } from '../follow'; +import { ABSENT_RETRIES, useFollowChat } from '../follow'; type TestStream = ChatStream & { push(event: ChatEvent): void; closed: boolean }; @@ -263,7 +263,7 @@ describe('useFollowChat', () => { expect(result.current.isUnattached).toBe(false); }); - it('says a run the caller knows of has no stream only once an attachment found none', async () => { + it('says a run the caller knows of has no stream only after looking for it again', async () => { const { transport } = createTransport(idle); let release: (messages: TMessage[]) => void = () => undefined; const loadMessages = jest.fn( @@ -277,10 +277,47 @@ describe('useFollowChat', () => { expect(result.current.isUnattached).toBe(false); loadMessages.mockResolvedValue([brief]); - await act(async () => release([brief])); + jest.useFakeTimers(); + try { + await act(async () => { + release([brief]); + await jest.advanceTimersByTimeAsync(getReconnectDelay(1)); + }); + /** Not found once is not yet nothing to attach to. */ + expect(result.current.isUnattached).toBe(false); + await act(async () => { + await jest.advanceTimersByTimeAsync(60_000); + }); + } finally { + jest.useRealTimers(); + } await waitFor(() => expect(result.current.isUnattached).toBe(true)); expect(result.current.isFollowing).toBe(false); - expect(transport.reconnectToStream).toHaveBeenCalledTimes(1); + expect(transport.reconnectToStream).toHaveBeenCalledTimes(1 + ABSENT_RETRIES); + }); + + it('follows a run whose stream opens a moment after the caller learns of it', async () => { + const { transport, streams, setStatus } = createTransport(idle); + const { result } = setup({ transport, live: true }); + await waitFor(() => expect(transport.reconnectToStream).toHaveBeenCalledTimes(1)); + expect(streams).toHaveLength(0); + + /** The run was announced first; its generation opens now. */ + setStatus(running); + jest.useFakeTimers(); + try { + await act(async () => { + await jest.advanceTimersByTimeAsync(getReconnectDelay(1)); + }); + } finally { + jest.useRealTimers(); + } + await waitFor(() => expect(streams).toHaveLength(1)); + act(() => streams[0].push(snapshot('Late start'))); + await settle(); + + expect(textOf(result.current.messages)).toEqual(['Late start']); + expect(result.current.isUnattached).toBe(false); }); it('says the stream is gone once a dropped one could not be attached again', async () => { diff --git a/packages/chat/src/react/follow.ts b/packages/chat/src/react/follow.ts index 88f14fe4acd..361e30918f1 100644 --- a/packages/chat/src/react/follow.ts +++ b/packages/chat/src/react/follow.ts @@ -73,6 +73,12 @@ type Load = { id: string; attempt: number; state: 'loading' | 'ready' | 'error' */ type Attachment = { finished?: ChatFinishResult; received: boolean }; +/** + * How many more times a run the caller knows of is looked for after it was not found. Short: a + * caller with another way to show the run is waiting on the answer. + */ +export const ABSENT_RETRIES = 2; + const noMessages: TMessage[] = []; const unsubscribed = (): (() => void) => () => undefined; @@ -206,9 +212,19 @@ export function useFollowChat({ /** Whether a generation was reached and not lost for good. */ let reached = false; try { - for (let failures = 0; !stale; ) { + for (let failures = 0, absences = 0; !stale; ) { const { finished, received } = await follow(); reached ||= received || finished != null; + /** + * The caller says a run is going and none was found. Its stream may not be open yet: + * a run is announced as running before its generation is, so the attachment is tried + * again shortly before it is taken to have nothing to attach to. + */ + if (!reached && host.current.live && absences < ABSENT_RETRIES) { + absences += 1; + await pause(getReconnectDelay(absences)); + continue; + } if (finished?.isDisconnect !== true) { break; }