🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
⚡️ perf(conversation): keep long workflows responsive when opened and while streaming (#23176)
Bryan9c06c8eeae5d
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex ab2f1e24cf8..3f2f9840f85 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -3291,6 +3291,7 @@"workflow.collapse": "Collapse","workflow.expandFull": "Expand fully","workflow.failedSuffix": "(failed)",+ "workflow.showEarlierSteps": "Show earlier steps ({{count}})","workflow.summaryCallsTotal_one": "{{count}} call","workflow.summaryCallsTotal_other": "{{count}} calls","workflow.summaryFailed": "{{count}} failed",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 69f3454bae9..0ddf0ed19e2 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -3291,6 +3291,7 @@"workflow.collapse": "收起","workflow.expandFull": "全部展开","workflow.failedSuffix": "(失败)",+ "workflow.showEarlierSteps": "查看更早的步骤({{count}})","workflow.summaryCallsTotal_one": "共 {{count}} 次调用","workflow.summaryCallsTotal_other": "共 {{count}} 次调用","workflow.summaryFailed": "{{count}} 次失败",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 4a8a60c97ca..254847b3c36 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -3719,6 +3719,7 @@ export default {'viewSwitcher.page': 'Page','viewSwitcher.task': 'Task','workflow.failedSuffix': '(failed)',+ 'workflow.showEarlierSteps': 'Show earlier steps ({{count}})','workflow.summaryCallsTotal_one': '{{count}} call','workflow.summaryCallsTotal_other': '{{count}} calls','workflow.summaryFailed': '{{count}} failed',diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsxindex cbc011bff30..2af4c576b29 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx@@ -1,7 +1,6 @@import { getBuiltinRender } from '@lobechat/builtin-tools/renders';import { getBuiltinStreaming } from '@lobechat/builtin-tools/streamings';import { Accordion, Divider, Flexbox, Skeleton } from '@lobehub/ui';-import isEqual from 'fast-deep-equal';import { memo, useState } from 'react';import SafeBoundary from '@/components/ErrorBoundary';@@ -21,6 +20,7 @@ import Actions from './Actions';import Detail from './Detail';import Inspectors from './Inspector';import { hasToolResultBody } from './toolResultBody';+import { useArmOnInteraction } from './useArmOnInteraction';import { useToolExpandState } from './useToolExpandState';const Debug = dynamic(() => import('./Debug'), {@@ -37,7 +37,13 @@ export interface GroupToolProps {const Tool = memo<GroupToolProps>(({ assistantMessageId, disableEditing, id }) => {// Subscribe directly to this tool's data so a streaming chunk that only// updates a sibling tool does not push new props through this subtree.- const tool = useConversationStore(dataSelectors.getToolInBlock(assistantMessageId, id), isEqual);+ // `stabilizeReferences` keeps an unchanged tool's object across snapshots, so+ // identity is enough here — a deep compare of every tool's result on every+ // chunk is what made long workflows freeze.+ const tool = useConversationStore(+ dataSelectors.getToolInBlock(assistantMessageId, id),+ Object.is,+ );// Stable defaults so downstream hook ordering is preserved even on the brief// window where the tool is not yet present in the store snapshot.@@ -76,6 +82,10 @@ const Tool = memo<GroupToolProps>(({ assistantMessageId, disableEditing, id }) =});// Controls switching between custom render and fallback ArgumentRenderconst [showCustomToolRender, setShowCustomToolRender] = useState(true);+ // The row actions only show on hover/focus, yet they are most of a collapsed+ // row's DOM (≈28 of ≈46 nodes). Mount them the first time the row is pointed+ // at or focused, so a list of hundreds of finished calls mounts titles only.+ const { armed: actionsArmed, armProps } = useArmOnInteraction();let isArgumentsStreaming = false;try {@@ -118,80 +128,83 @@ const Tool = memo<GroupToolProps>(({ assistantMessageId, disableEditing, id }) =if (!tool) return null;const isToolDetailExpand = forceShowStreamingRender || showToolRender || showDebug;+ const mountActions = !disableEditing && (actionsArmed || isToolDetailExpand);return (- <Accordion- hideIndicator={isAlwaysExpand}- indicatorPlacement="inline"- styles={{ trigger: { paddingBlock: 4, paddingInline: 4 } }}- value={isToolDetailExpand ? [id] : []}- items={[- {- action: !disableEditing && (- <Actions- assistantMessageId={assistantMessageId}- canToggleCustomToolRender={canToggleCustomToolRender}- identifier={identifier}- setShowCustomToolRender={setShowCustomToolRender}- setShowDebug={setShowDebug}- showCustomToolRender={showCustomToolRender}- showDebug={showDebug}- />- ),- children: (- <Flexbox gap={8} paddingBlock={8}>- {showDebug && (- <Debug- apiName={apiName}- identifier={identifier}- intervention={intervention}- requestArgs={requestArgs}- result={result}- toolCallId={id}- toolMessageId={toolMessageId}- type={type}- />- )}- <SafeBoundary alertTitle={`${identifier} / ${apiName}`} variant="alert">- <Detail- apiName={apiName}- arguments={requestArgs}- disableEditing={disableEditing}- identifier={identifier}- intervention={intervention}- isArgumentsStreaming={isArgumentsStreaming}- isToolCalling={isToolCalling}- messageId={assistantMessageId}- result={result}- showCustomToolRender={showCustomToolRender}- toolCallId={id}- toolMessageId={toolMessageId}- type={type}- />- </SafeBoundary>- <Divider dashed style={{ marginBottom: 0, marginTop: 8 }} />- </Flexbox>- ),- key: id,- title: (- <Inspectors- apiName={apiName}- arguments={requestArgs}- identifier={identifier}- intervention={intervention}- isArgumentsStreaming={isArgumentsStreaming}- isExpanded={isToolDetailExpand}- isToolCalling={isToolCalling}- messageId={assistantMessageId}- result={result}- toolCallId={id}- toolCallStartTime={toolCallStartTime}- />- ),- },- ]}- onValueChange={(value) => handleExpand(value.includes(id))}- />+ <div {...armProps}>+ <Accordion+ hideIndicator={isAlwaysExpand}+ indicatorPlacement="inline"+ styles={{ trigger: { paddingBlock: 4, paddingInline: 4 } }}+ value={isToolDetailExpand ? [id] : []}+ items={[+ {+ action: mountActions && (+ <Actions+ assistantMessageId={assistantMessageId}+ canToggleCustomToolRender={canToggleCustomToolRender}+ identifier={identifier}+ setShowCustomToolRender={setShowCustomToolRender}+ setShowDebug={setShowDebug}+ showCustomToolRender={showCustomToolRender}+ showDebug={showDebug}+ />+ ),+ children: (+ <Flexbox gap={8} paddingBlock={8}>+ {showDebug && (+ <Debug+ apiName={apiName}+ identifier={identifier}+ intervention={intervention}+ requestArgs={requestArgs}+ result={result}+ toolCallId={id}+ toolMessageId={toolMessageId}+ type={type}+ />+ )}+ <SafeBoundary alertTitle={`${identifier} / ${apiName}`} variant="alert">+ <Detail+ apiName={apiName}+ arguments={requestArgs}+ disableEditing={disableEditing}+ identifier={identifier}+ intervention={intervention}+ isArgumentsStreaming={isArgumentsStreaming}+ isToolCalling={isToolCalling}+ messageId={assistantMessageId}+ result={result}+ showCustomToolRender={showCustomToolRender}+ toolCallId={id}+ toolMessageId={toolMessageId}+ type={type}+ />+ </SafeBoundary>+ <Divider dashed style={{ marginBottom: 0, marginTop: 8 }} />+ </Flexbox>+ ),+ key: id,+ title: (+ <Inspectors+ apiName={apiName}+ arguments={requestArgs}+ identifier={identifier}+ intervention={intervention}+ isArgumentsStreaming={isArgumentsStreaming}+ isExpanded={isToolDetailExpand}+ isToolCalling={isToolCalling}+ messageId={assistantMessageId}+ result={result}+ toolCallId={id}+ toolCallStartTime={toolCallStartTime}+ />+ ),+ },+ ]}+ onValueChange={(value) => handleExpand(value.includes(id))}+ />+ </div>);});diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/useArmOnInteraction.test.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/useArmOnInteraction.test.tsnew file mode 100644index 00000000000..7150ae2a14f--- /dev/null+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/useArmOnInteraction.test.ts@@ -0,0 +1,37 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook } from '@testing-library/react';+import { describe, expect, it } from 'vitest';++import { useArmOnInteraction } from './useArmOnInteraction';++describe('useArmOnInteraction', () => {+ /** @example Hover-only row actions were most of each row's DOM in a 500-step workflow. */+ it('starts unarmed until the row is pointed at', () => {+ const { result } = renderHook(() => useArmOnInteraction());++ expect(result.current.armed).toBe(false);++ act(() => result.current.armProps.onPointerEnter?.());++ expect(result.current.armed).toBe(true);+ });++ it('arms on keyboard focus too', () => {+ const { result } = renderHook(() => useArmOnInteraction());++ act(() => result.current.armProps.onFocus?.());++ expect(result.current.armed).toBe(true);+ });++ it('stays armed and stops listening once armed', () => {+ const { result } = renderHook(() => useArmOnInteraction());++ act(() => result.current.armProps.onPointerEnter?.());++ expect(result.current.armProps).toEqual({});+ expect(result.current.armed).toBe(true);+ });+});diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/useArmOnInteraction.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/useArmOnInteraction.tsnew file mode 100644index 00000000000..23753dbb7fb--- /dev/null+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/useArmOnInteraction.ts@@ -0,0 +1,24 @@+import { useCallback, useMemo, useState } from 'react';++export interface ArmOnInteraction {+ armed: boolean;+ /** Spread on the row's wrapper; empty once armed so later events cost nothing. */+ armProps: { onFocus?: () => void; onPointerEnter?: () => void };+}++/**+ * Flips to `armed` the first time the user points at or focuses the element,+ * and stays armed. Lets a row defer hover-only UI (its action buttons) until+ * someone could actually see it: a list of hundreds of rows otherwise mounts+ * all of it up front. Focus covers keyboard users tabbing into the row.+ */+export const useArmOnInteraction = (): ArmOnInteraction => {+ const [armed, setArmed] = useState(false);+ const arm = useCallback(() => setArmed(true), []);+ const armProps = useMemo(+ () => (armed ? {} : { onFocus: arm, onPointerEnter: arm }),+ [arm, armed],+ );++ return { armProps, armed };+};diff --git a/src/features/Conversation/Messages/AssistantGroup/Tools.tsx b/src/features/Conversation/Messages/AssistantGroup/Tools.tsxindex 44d74663027..01b0fef832e 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tools.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tools.tsx@@ -1,5 +1,4 @@import { Flexbox } from '@lobehub/ui';-import isEqual from 'fast-deep-equal';import { memo } from 'react';import { dataSelectors, useConversationStore } from '../../store';@@ -16,13 +15,14 @@ export const Tools = memo<ToolsRendererProps>(({ disableEditing, messageId, tool// Subscribe only to the visible tool ids of this block. Streaming chunks that// change a single tool's args/result do not invalidate this string array, so// sibling Tool components stay isolated and only the changed one re-renders.+ // The store's default equality is `shallow`, which compares the ids by value.const visibleToolCallIds = useConversationStore((s) => {const tools = dataSelectors.getToolsInBlock(messageId)(s);if (!tools || tools.length === 0) return [];return tools.filter((t) => shouldRenderToolCall(t) && (!toolIds || toolIds.includes(t.id))).map((t) => t.id);- }, isEqual);+ });if (visibleToolCallIds.length === 0) return null;diff --git a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsxindex a51468ded7d..2e444f990d9 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx@@ -120,6 +120,8 @@ vi.mock('../../../store', () => ({topicId: () => undefined,},dataSelectors: {+ getDbMessageById: (id: string) => (s: { dbMessages: { id: string }[] }) =>+ s.dbMessages.find((message) => message.id === id),getDisplayMessageById: () => () => ({ parentId: 'user-1' }),},messageStateSelectors: {diff --git a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsxindex 4cce33886da..eb96ad204ff 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx@@ -52,7 +52,7 @@ const ContentBlock = memo<ContentBlockProps>();/** The persisted reason may arrive after the grouped projection without changing its props. */const persistedFinishType = useConversationStore(- (s) => s.dbMessages.find((message) => message.id === id)?.metadata?.finishType,+ (s) => dataSelectors.getDbMessageById(id)(s)?.metadata?.finishType,);const finishType = metadata?.finishType ?? persistedFinishType;// The call that launched the finished task can sit in an earlier step ordiff --git a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlocksScroll.tsx b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlocksScroll.tsxindex 99d72d75116..2b3b6776e48 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlocksScroll.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlocksScroll.tsx@@ -3,7 +3,7 @@import type { UIChatMessage } from '@lobechat/types';import { Flexbox, ScrollArea } from '@lobehub/ui';import * as stylex from '@stylexjs/stylex';-import type { RefObject } from 'react';+import type { ReactNode, RefObject } from 'react';import { memo, useMemo } from 'react';import { resolveAssistantGroupFromMessages } from '../utils/resolveAssistantGroupFromMessages';@@ -26,6 +26,8 @@ const styles = stylex.create({interface ContentBlocksScrollBaseProps {disableEditing?: boolean;+ /** Rendered above the first block, inside the scroll area (e.g. a "show earlier" control). */+ leading?: ReactNode;onScroll?: () => void;scroll?: boolean;scrollRef?: RefObject<HTMLDivElement | null>;@@ -48,7 +50,7 @@ export type ContentBlocksScrollProps =ContentBlocksScrollFromBlocks | ContentBlocksScrollFromMessages;const ContentBlocksScroll = memo<ContentBlocksScrollProps>((props) => {- const { disableEditing, onScroll, scroll = true, scrollRef, variant } = props;+ const { disableEditing, leading, onScroll, scroll = true, scrollRef, variant } = props;const messagesList = 'messages' in props ? props.messages : undefined;const assistantIdFromProps = 'messages' in props ? undefined : props.assistantId;@@ -69,6 +71,7 @@ const ContentBlocksScroll = memo<ContentBlocksScrollProps>((props) => {const list = (<Flexbox gap={variant === 'workflow' ? 8 : undefined}>+ {leading}{blocks.map((block) => (<ContentBlockkey={block.renderKey ?? block.id}diff --git a/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.test.tsx b/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.test.tsxindex 1f17b00cc34..94223e55c13 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.test.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.test.tsx@@ -35,15 +35,21 @@ vi.mock('@lobehub/ui', async (importOriginal) => {Accordion: ({items,onValueChange,+ styles,value,}: {items?: { action?: ReactNode; children?: ReactNode; key: string; title?: ReactNode }[];onValueChange?: (keys: string[]) => void;+ styles?: { panel?: { transitionDuration?: string } };value?: string[];}) => {const isExpanded = (value ?? []).includes('workflow');return (- <div data-expanded-keys={JSON.stringify(value ?? [])} data-testid="workflow-accordion">+ <div+ data-expanded-keys={JSON.stringify(value ?? [])}+ data-panel-transition={styles?.panel?.transitionDuration}+ data-testid="workflow-accordion"+ ><buttonaria-label="toggle-accordion-header"type="button"@@ -152,6 +158,33 @@ describe('WorkflowCollapse', () => {vi.useRealTimers();});+ /** @example Animating a 500-step panel's height re-laid out every row per frame. */+ it('opens and closes a long tool list without the height animation', () => {+ mockIsGenerating = false;+ const manyTools: AssistantContentBlock[] = Array.from({ length: 101 }, (_, i) => ({+ content: '',+ id: `block-${i}`,+ tools: [+ {+ apiName: 'search',+ arguments: '{}',+ id: `tool-${i}`,+ identifier: 'search',+ result: { content: 'ok' },+ type: 'builtin',+ } as any,+ ],+ }));++ const { rerender } = render(+ <WorkflowCollapse assistantMessageId="msg-1" blocks={makeBlocks()} />,+ );+ expect(screen.getByTestId('workflow-accordion')).not.toHaveAttribute('data-panel-transition');++ rerender(<WorkflowCollapse assistantMessageId="msg-1" blocks={manyTools} />);+ expect(screen.getByTestId('workflow-accordion')).toHaveAttribute('data-panel-transition', '0s');+ });+it('defaults to the full list while streaming', () => {render(<WorkflowCollapse assistantMessageId="msg-1" blocks={makeBlocks()} />);diff --git a/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.tsx b/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.tsxindex dbb395c4a25..f352b1df5b5 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.tsx@@ -14,6 +14,7 @@ import { shinyTextStyles } from '@/styles';import { messageStateSelectors, useConversationStore } from '../../../store';import {TIME_MS_PER_SECOND,+ WORKFLOW_ANIMATED_MAX_TOOLS,WORKFLOW_EXPANDED_SCROLL_THRESHOLD_PX,WORKFLOW_HEADLINE_DEBOUNCE_MS,WORKFLOW_PROSE_IDLE_COMMIT_MS,@@ -39,6 +40,14 @@ const WORKFLOW_EXPAND_TOGGLE_TRANSITION = {ease: [0.4, 0, 0.2, 1],} as const;+const DEFAULT_STYLES = { trigger: { paddingBlock: 4, paddingInline: 4 } };+// Animating the panel height re-lays out every mounted row on each frame; a+// long list opens and closes in one step instead.+const LARGE_LIST_STYLES = {+ ...DEFAULT_STYLES,+ panel: { transitionDuration: '0s' },+};+export type WorkflowExpandLevel = 'collapsed' | 'semi' | 'full';/** Per-phase initial level. Pass an object when streaming and completion@@ -541,7 +550,7 @@ const WorkflowCollapse = memo<WorkflowCollapseProps>(return (<AccordionindicatorPlacement="inline"- styles={{ trigger: { paddingBlock: 4, paddingInline: 4 } }}+ styles={allTools.length > WORKFLOW_ANIMATED_MAX_TOOLS ? LARGE_LIST_STYLES : DEFAULT_STYLES}value={expandedKeys}variant="borderless"items={[diff --git a/src/features/Conversation/Messages/AssistantGroup/components/WorkflowExpandedList.tsx b/src/features/Conversation/Messages/AssistantGroup/components/WorkflowExpandedList.tsxindex 755022ed10d..e93dc164764 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/WorkflowExpandedList.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/WorkflowExpandedList.tsx@@ -1,7 +1,11 @@+import { Button } from '@lobehub/ui';import { memo, type RefObject } from 'react';+import { useTranslation } from 'react-i18next';+import { WORKFLOW_LIST_INITIAL_STEPS, WORKFLOW_LIST_LOAD_MORE_STEPS } from '../constants';import ContentBlocksScroll from './ContentBlocksScroll';import type { RenderableAssistantContentBlock } from './types';+import { useStepWindow } from './useStepWindow';interface WorkflowExpandedListProps {assistantId: string;@@ -13,17 +17,38 @@ interface WorkflowExpandedListProps {}const WorkflowExpandedList = memo<WorkflowExpandedListProps>(- ({ assistantId, blocks, constrained, disableEditing, onScroll, scrollRef }) => (- <ContentBlocksScroll- assistantId={assistantId}- blocks={blocks}- disableEditing={disableEditing}- scroll={!!constrained}- scrollRef={scrollRef}- variant="workflow"- onScroll={onScroll}- />- ),+ ({ assistantId, blocks, constrained, disableEditing, onScroll, scrollRef }) => {+ const { t } = useTranslation('chat');+ const { hiddenCount, showEarlier, visible } = useStepWindow(+ blocks,+ WORKFLOW_LIST_INITIAL_STEPS,+ WORKFLOW_LIST_LOAD_MORE_STEPS,+ );++ return (+ <ContentBlocksScroll+ assistantId={assistantId}+ blocks={visible}+ disableEditing={disableEditing}+ scroll={!!constrained}+ scrollRef={scrollRef}+ variant="workflow"+ leading={+ hiddenCount > 0 ? (+ <Button+ size={'small'}+ style={{ alignSelf: 'center' }}+ type={'text'}+ onClick={showEarlier}+ >+ {t('workflow.showEarlierSteps', { count: hiddenCount })}+ </Button>+ ) : undefined+ }+ onScroll={onScroll}+ />+ );+ },);WorkflowExpandedList.displayName = 'WorkflowExpandedList';diff --git a/src/features/Conversation/Messages/AssistantGroup/components/largeWorkflow.bench.tsx b/src/features/Conversation/Messages/AssistantGroup/components/largeWorkflow.bench.tsxnew file mode 100644index 00000000000..6141b87eba1--- /dev/null+++ b/src/features/Conversation/Messages/AssistantGroup/components/largeWorkflow.bench.tsx@@ -0,0 +1,181 @@+/**+ * Performance probe for a very long workflow (hundreds of tool calls in one+ * assistant group). Run it on its own, from the repo root:+ *+ * bunx vitest bench --run --project 'app*' --maxWorkers=1 --no-file-parallelism \+ * src/features/Conversation/Messages/AssistantGroup/components/largeWorkflow.bench.tsx+ *+ * It mounts the real expanded workflow list (`WorkflowExpandedList`, what+ * opening a workflow row renders) against a real conversation store and+ * reports: the mount time of the opened list (median of 3), the average cost of+ * one streaming chunk (a content update on the last step) while the list is+ * mounted next to the same chunk with nothing mounted (parse + reference+ * stabilisation only), and the cost of one "show earlier steps" click when the+ * list is windowed. `LOBE_PERF_TOOLS` sets the number of tool calls (600).+ * happy-dom timings are not browser timings; compare runs of this file against+ * each other, not against the browser.+ */+import type { UIChatMessage } from '@lobechat/types';+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { createStore, Provider } from '@/features/Conversation/store';+import { ServerConfigStoreProvider } from '@/store/serverConfig/Provider';++import type { RenderableAssistantContentBlock } from './types';+import WorkflowExpandedList from './WorkflowExpandedList';++vi.mock('react-i18next', () => ({+ Trans: ({ children }: PropsWithChildren) => children,+ useTranslation: () => ({ i18n: { language: 'en-US' }, t: (key: string) => key }),+}));+vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: true }) }));++const TOOL_COUNT = Number(process.env.LOBE_PERF_TOOLS ?? 600);+const CHUNKS = 20;+const RESULT_TEXT = 'line of tool output\n'.repeat(200);++const buildTranscript = (count: number): UIChatMessage[] => {+ const rows: any[] = [{ content: 'go', createdAt: 0, id: 'u1', role: 'user', updatedAt: 0 }];+ let parentId = 'u1';+ for (let i = 0; i < count; i++) {+ const assistantId = `a${i}`;+ const toolCallId = `call_${i}`;+ rows.push({+ content: '',+ createdAt: 10 + i * 2,+ id: assistantId,+ parentId,+ role: 'assistant',+ tools: [+ {+ apiName: 'Bash',+ arguments: JSON.stringify({ command: `ls -la /tmp/dir-${i}`, description: `step ${i}` }),+ id: toolCallId,+ identifier: 'claude-code',+ type: 'builtin',+ },+ ],+ updatedAt: 10 + i * 2,+ });+ rows.push({+ content: `${RESULT_TEXT}${i}`,+ createdAt: 11 + i * 2,+ id: `t${i}`,+ parentId: assistantId,+ role: 'tool',+ tool_call_id: toolCallId,+ updatedAt: 11 + i * 2,+ });+ parentId = `t${i}`;+ }+ rows.push({+ content: 'streaming',+ createdAt: 10 + count * 2,+ id: 'a-last',+ parentId,+ role: 'assistant',+ updatedAt: 10 + count * 2,+ });+ return rows as UIChatMessage[];+};++const newStore = () =>+ createStore({+ context: { agentId: 'agent', threadId: null, topicId: 'topic' },+ messages: buildTranscript(TOOL_COUNT),+ });++const groupBlocks = (store: ReturnType<typeof newStore>) => {+ const group = store.getState().displayMessages.find((m) => m.role === 'assistantGroup');+ if (!group?.children) throw new Error('no assistant group');+ return { blocks: group.children as RenderableAssistantContentBlock[], groupId: group.id };+};++const streamChunks = (store: ReturnType<typeof newStore>) => {+ const start = performance.now();+ for (let i = 0; i < CHUNKS; i++) {+ act(() => {+ store.getState().internal_dispatchMessage({+ id: 'a-last',+ type: 'updateMessage',+ value: { content: `streaming ${i}` },+ });+ });+ }+ return (performance.now() - start) / CHUNKS;+};++const fmt = (ms: number) => `${ms.toFixed(1)}ms`;++const mountList = (store: ReturnType<typeof newStore>, limit?: number) => {+ const { blocks, groupId } = groupBlocks(store);+ return render(+ <ServerConfigStoreProvider>+ <Provider createStore={() => store}>+ <WorkflowExpandedList+ assistantId={groupId}+ blocks={limit ? blocks.slice(0, limit) : blocks}+ />+ </Provider>+ </ServerConfigStoreProvider>,+ );+};++const median = (values: number[]) =>+ [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)];++describe(`large workflow (${TOOL_COUNT} tools)`, () => {+ afterEach(() => cleanup());++ it('measures mount and per-chunk cost of the expanded list', { timeout: 600_000 }, () => {+ // Warm module caches (builtin renders, i18n stubs) with a small mount.+ mountList(newStore(), 5).unmount();++ const bareChunkMs = streamChunks(newStore());++ const mounts: number[] = [];+ for (let i = 0; i < 3; i++) {+ const store = newStore();+ const start = performance.now();+ mountList(store).unmount();+ mounts.push(performance.now() - start);+ }++ const store = newStore();+ const { blocks } = groupBlocks(store);+ const mountStart = performance.now();+ const { container } = mountList(store);+ mounts.push(performance.now() - mountStart);+ const mountedNodes = container.querySelectorAll('*').length;++ const mountedChunkMs = streamChunks(store);++ const showEarlier = screen.queryByText('workflow.showEarlierSteps');+ let showEarlierMs: number | undefined;+ if (showEarlier) {+ const start = performance.now();+ act(() => {+ fireEvent.click(showEarlier);+ });+ showEarlierMs = performance.now() - start;+ }++ process.stderr.write(+ `${[+ `[perf] tools=${TOOL_COUNT} blocks=${blocks.length} dom=${mountedNodes}`,+ `[perf] mount opened list (median of ${mounts.length}): ${fmt(median(mounts))}`,+ `[perf] chunk, nothing mounted: ${fmt(bareChunkMs)}`,+ `[perf] chunk, list mounted: ${fmt(mountedChunkMs)} (list overhead ${fmt(mountedChunkMs - bareChunkMs)})`,+ showEarlierMs === undefined+ ? '[perf] show earlier: not windowed'+ : `[perf] show earlier (+100 steps): ${fmt(showEarlierMs)}`,+ ].join('\n')}\n`,+ );++ // A crashed row renders SafeBoundary's fallback instead of the tool card.+ expect(container.textContent).not.toContain('Render Error');+ expect(mountedNodes).toBeGreaterThan(0);+ });+});diff --git a/src/features/Conversation/Messages/AssistantGroup/components/useStepWindow.test.ts b/src/features/Conversation/Messages/AssistantGroup/components/useStepWindow.test.tsnew file mode 100644index 00000000000..66d394df247--- /dev/null+++ b/src/features/Conversation/Messages/AssistantGroup/components/useStepWindow.test.ts@@ -0,0 +1,63 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook } from '@testing-library/react';+import { describe, expect, it } from 'vitest';++import { clampWindowStart, useStepWindow } from './useStepWindow';++const steps = (count: number) => Array.from({ length: count }, (_, i) => i);++describe('clampWindowStart', () => {+ it('keeps the start while it still leaves the initial tail loaded', () => {+ expect(clampWindowStart(20, 100, 50)).toBe(20);+ });++ it('moves the start down when the list shrinks below it', () => {+ expect(clampWindowStart(70, 100, 50)).toBe(50);+ expect(clampWindowStart(70, 30, 50)).toBe(0);+ });+});++describe('useStepWindow', () => {+ it('loads only the tail of a long list', () => {+ const { result } = renderHook(() => useStepWindow(steps(120), 50, 100));++ expect(result.current.visible).toEqual(steps(120).slice(70));+ expect(result.current.hiddenCount).toBe(70);+ });++ it('loads a short list whole, with nothing hidden', () => {+ const items = steps(30);+ const { result } = renderHook(() => useStepWindow(items, 50, 100));++ expect(result.current.visible).toBe(items);+ expect(result.current.hiddenCount).toBe(0);+ });++ it('grows the window upward by one batch per click', () => {+ const { result } = renderHook(() => useStepWindow(steps(300), 50, 100));++ act(() => result.current.showEarlier());+ expect(result.current.hiddenCount).toBe(150);+ expect(result.current.visible[0]).toBe(150);++ act(() => result.current.showEarlier());+ act(() => result.current.showEarlier());+ expect(result.current.hiddenCount).toBe(0);+ expect(result.current.visible).toHaveLength(300);+ });++ /** @example A streaming turn appends steps; the oldest loaded step must not slide out. */+ it('appends steps that stream in after it opened', () => {+ const { result, rerender } = renderHook(({ items }) => useStepWindow(items, 50, 100), {+ initialProps: { items: steps(120) },+ });++ rerender({ items: steps(125) });++ expect(result.current.hiddenCount).toBe(70);+ expect(result.current.visible).toHaveLength(55);+ expect(result.current.visible.at(-1)).toBe(124);+ });+});diff --git a/src/features/Conversation/Messages/AssistantGroup/components/useStepWindow.ts b/src/features/Conversation/Messages/AssistantGroup/components/useStepWindow.tsnew file mode 100644index 00000000000..cf676837356--- /dev/null+++ b/src/features/Conversation/Messages/AssistantGroup/components/useStepWindow.ts@@ -0,0 +1,43 @@+import { useCallback, useMemo, useState } from 'react';++export interface StepWindow<T> {+ /** Steps above the loaded ones. */+ hiddenCount: number;+ /** Load up to `loadMoreCount` more steps above the loaded ones. */+ showEarlier: () => void;+ visible: T[];+}++/**+ * Index of the first loaded step. `start` is anchored to the list's head, so+ * steps that stream in later append to the loaded range instead of pushing the+ * oldest loaded step out. It only moves down when the list shrinks below it,+ * and then still leaves the last `initialCount` steps loaded.+ */+export const clampWindowStart = (start: number, total: number, initialCount: number) =>+ Math.max(0, Math.min(start, total - initialCount));++/**+ * Render only the tail of a long step list and grow it upward on demand.+ * The window resets whenever the owner unmounts (e.g. the workflow folds).+ */+export const useStepWindow = <T>(+ items: T[],+ initialCount: number,+ loadMoreCount: number,+): StepWindow<T> => {+ const [start, setStart] = useState(() => Math.max(0, items.length - initialCount));+ const effectiveStart = clampWindowStart(start, items.length, initialCount);++ const showEarlier = useCallback(+ () => setStart(Math.max(0, effectiveStart - loadMoreCount)),+ [effectiveStart, loadMoreCount],+ );++ const visible = useMemo(+ () => (effectiveStart === 0 ? items : items.slice(effectiveStart)),+ [effectiveStart, items],+ );++ return { hiddenCount: effectiveStart, showEarlier, visible };+};diff --git a/src/features/Conversation/Messages/AssistantGroup/constants.ts b/src/features/Conversation/Messages/AssistantGroup/constants.tsindex be7f1587b5f..90cb43e459a 100644--- a/src/features/Conversation/Messages/AssistantGroup/constants.ts+++ b/src/features/Conversation/Messages/AssistantGroup/constants.ts@@ -194,3 +194,19 @@ export const TOOL_API_DISPLAY_NAMES: Record<string, string> = {showAgentMarketplace: 'workflow.toolDisplayName.showAgentMarketplace',submitAgentPick: 'workflow.toolDisplayName.submitAgentPick',};++/**+ * Steps an opened workflow list mounts at first. A long turn can run hundreds+ * of steps; mounting them all in one commit froze the page, so the list starts+ * from its tail and earlier steps load on demand.+ */+export const WORKFLOW_LIST_INITIAL_STEPS = 50;++/** Steps one "show earlier steps" click adds above the loaded ones. */+export const WORKFLOW_LIST_LOAD_MORE_STEPS = 100;++/**+ * Above this many tool calls the workflow skips its open/close height+ * animation: animating the height re-lays out the whole list on every frame.+ */+export const WORKFLOW_ANIMATED_MAX_TOOLS = 100;diff --git a/src/features/Conversation/store/slices/data/messageIndex.test.ts b/src/features/Conversation/store/slices/data/messageIndex.test.tsnew file mode 100644index 00000000000..ad5550bfc1c--- /dev/null+++ b/src/features/Conversation/store/slices/data/messageIndex.test.ts@@ -0,0 +1,158 @@+import type { UIChatMessage } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { createStore } from '../../index';+import type { State } from '../../initialState';+import { findBlockInDisplayMessages, indexDbMessages } from './messageIndex';+import { dataSelectors } from './selectors';++const msgs = (rows: unknown[]) => rows as UIChatMessage[];+const stateOf = (displayMessages: unknown[], dbMessages: unknown[] = []) =>+ ({ dbMessages, displayMessages }) as unknown as State;++/** An array that counts how many times it is walked (iteration or `find`). */+const countedArray = <T>(items: T[]) => {+ const counter = { walks: 0 };+ const array = [...items];+ const iterate = array[Symbol.iterator].bind(array);+ const find = array.find.bind(array);+ Object.defineProperty(array, Symbol.iterator, {+ value: () => {+ counter.walks += 1;+ return iterate();+ },+ });+ Object.defineProperty(array, 'find', {+ value: (...args: Parameters<typeof find>) => {+ counter.walks += 1;+ return find(...args);+ },+ });+ return { array, counter };+};++describe('findBlockInDisplayMessages', () => {+ it('resolves blocks from standalone rows, groups, compressed groups and council members', () => {+ const messages = msgs([+ { content: 'solo', id: 'a1', role: 'assistant', tools: [{ id: 'c1' }] },+ { children: [{ content: 'child', id: 'b1' }], id: 'g1', role: 'assistantGroup' },+ {+ compressedMessages: [+ { children: [{ content: 'folded', id: 'b2' }], id: 'g2', role: 'assistantGroup' },+ ],+ id: 'cg',+ role: 'compressedGroup',+ },+ {+ id: 'council',+ members: [{ content: 'member', id: 'm1', role: 'assistant' }],+ role: 'agentCouncil',+ },+ ]);++ expect(findBlockInDisplayMessages(messages, 'a1')).toMatchObject({+ content: 'solo',+ tools: [{ id: 'c1' }],+ });+ expect(findBlockInDisplayMessages(messages, 'b1')?.content).toBe('child');+ expect(findBlockInDisplayMessages(messages, 'b2')?.content).toBe('folded');+ expect(findBlockInDisplayMessages(messages, 'm1')?.content).toBe('member');+ expect(findBlockInDisplayMessages(messages, 'missing')).toBeUndefined();+ });++ it('keeps the first match in walk order when an id repeats', () => {+ const messages = msgs([+ { children: [{ content: 'first', id: 'dup' }], id: 'g1', role: 'assistantGroup' },+ { children: [{ content: 'second', id: 'dup' }], id: 'g2', role: 'assistantGroup' },+ ]);++ expect(findBlockInDisplayMessages(messages, 'dup')?.content).toBe('first');+ });++ it('returns the same block object for an unchanged standalone row in a new snapshot', () => {+ const row = { content: 'solo', id: 'a1', role: 'assistant', tools: [{ id: 'c1' }] };+ const before = findBlockInDisplayMessages(msgs([row]), 'a1');+ const after = findBlockInDisplayMessages(msgs([{ id: 'u1', role: 'user' }, row]), 'a1');++ expect(after).toBe(before);+ });++ /** @example A long turn re-ran this walk for every row on every chunk. */+ it('walks a snapshot once no matter how many rows look blocks up', () => {+ const { array: children, counter } = countedArray(+ Array.from({ length: 50 }, (_, i) => ({ id: `b${i}`, tools: [{ id: `c${i}` }] })),+ );+ const state = stateOf([{ children, id: 'g1', role: 'assistantGroup' }]);++ for (let i = 0; i < 50; i++) {+ expect(dataSelectors.getToolInBlock(`b${i}`, `c${i}`)(state)?.id).toBe(`c${i}`);+ }++ expect(counter.walks).toBe(1);+ });+});++describe('indexDbMessages', () => {+ it('looks rows up by id and by tool call id, first row wins', () => {+ const rows = msgs([+ { id: 'm1', role: 'user' },+ { id: 't1', role: 'tool', tool_call_id: 'call_1' },+ { id: 't2', role: 'tool', tool_call_id: 'call_1' },+ ]);+ const state = stateOf([], rows);++ expect(dataSelectors.getDbMessageById('t2')(state)?.id).toBe('t2');+ expect(dataSelectors.getDbMessageByToolCallId('call_1')(state)?.id).toBe('t1');+ expect(dataSelectors.getDbMessageById('missing')(state)).toBeUndefined();+ });++ it('builds the index once per rows snapshot', () => {+ const rows = msgs([{ id: 'm1', role: 'user' }]);++ expect(indexDbMessages(rows)).toBe(indexDbMessages(rows));+ expect(indexDbMessages([...rows])).not.toBe(indexDbMessages(rows));+ });+});++describe('tool identity across streaming chunks', () => {+ const transcript = msgs([+ { content: 'go', createdAt: 0, id: 'u1', role: 'user', updatedAt: 0 },+ {+ content: '',+ createdAt: 1,+ id: 'a1',+ parentId: 'u1',+ role: 'assistant',+ tools: [{ apiName: 'run', arguments: '{}', id: 'call_1', identifier: 'x', type: 'default' }],+ updatedAt: 1,+ },+ {+ content: 'done',+ createdAt: 2,+ id: 't1',+ parentId: 'a1',+ role: 'tool',+ tool_call_id: 'call_1',+ updatedAt: 2,+ },+ { content: 'stream', createdAt: 3, id: 'a2', parentId: 't1', role: 'assistant', updatedAt: 3 },+ ]);++ /** @example Rows subscribe with `Object.is`, so an untouched tool must keep its object. */+ it('keeps an untouched tool reference when another step streams', () => {+ const store = createStore({+ context: { agentId: 'agent', threadId: null, topicId: 'topic' },+ messages: transcript,+ });+ const before = dataSelectors.getToolInBlock('a1', 'call_1')(store.getState());++ store.getState().internal_dispatchMessage({+ id: 'a2',+ type: 'updateMessage',+ value: { content: 'stream more' },+ });++ expect(dataSelectors.getBlockContent('a2')(store.getState())).toBe('stream more');+ expect(dataSelectors.getToolInBlock('a1', 'call_1')(store.getState())).toBe(before);+ });+});diff --git a/src/features/Conversation/store/slices/data/messageIndex.ts b/src/features/Conversation/store/slices/data/messageIndex.tsindex 9eed6d8dc0e..af207bd0662 100644--- a/src/features/Conversation/store/slices/data/messageIndex.ts+++ b/src/features/Conversation/store/slices/data/messageIndex.ts@@ -1,4 +1,19 @@-import type { UIChatMessage } from '@lobechat/types';+import type {+ AssistantContentBlock,+ ChatToolPayloadWithResult,+ UIChatMessage,+} from '@lobechat/types';++/**+ * Snapshot indexes over the conversation's message arrays.+ *+ * Every row of a long transcript subscribes to the store with a few selectors,+ * and every streaming chunk re-runs all of them. A selector that walks the+ * transcript makes one chunk cost rows × messages — a few hundred tool calls+ * in one turn is enough to freeze the page. Both arrays are replaced (never+ * mutated) on each dispatch, so an index keyed on the array identity is built+ * once per snapshot no matter how many rows read it, and each lookup is O(1).+ */interface DisplayMessageIndex {byId: Map<string, UIChatMessage>;@@ -30,3 +45,117 @@ export const indexDisplayMessages = (messages: UIChatMessage[]): DisplayMessageI}return index;};++// ===== Assistant content blocks =====++export const toAssistantContentBlock = (message: UIChatMessage): AssistantContentBlock => ({+ content: message.content,+ error: message.error,+ fileList: message.fileList,+ id: message.id,+ imageList: message.imageList,+ metadata: message.metadata ?? undefined,+ performance: message.performance,+ reasoning: message.reasoning ?? undefined,+ tasks: message.tasks as AssistantContentBlock['tasks'],+ tools: message.tools as ChatToolPayloadWithResult[],+ usage: message.usage,+});++// `stabilizeReferences` keeps an unchanged message object across snapshots, so+// caching its block projection per object keeps the block (and its `tools`)+// reference-stable too — selectors can then compare by identity.+const standaloneBlockCache = new WeakMap<UIChatMessage, AssistantContentBlock>();++const standaloneBlockOf = (message: UIChatMessage): AssistantContentBlock => {+ let block = standaloneBlockCache.get(message);+ if (!block) {+ block = toAssistantContentBlock(message);+ standaloneBlockCache.set(message, block);+ }+ return block;+};++/**+ * Index every assistant content block reachable from the display list:+ * standalone assistant rows, group children, compressed groups and agent+ * council members. Walk order and "first match wins" mirror a depth-first+ * search, so a duplicated id resolves to the same block a linear search would.+ */+const buildBlockIndex = (messages: UIChatMessage[], index: Map<string, AssistantContentBlock>) => {+ for (const message of messages) {+ if (message.role === 'assistant' && !index.has(message.id)) {+ index.set(message.id, standaloneBlockOf(message));+ }+ if (message.children) {+ for (const child of message.children) {+ if (!index.has(child.id)) index.set(child.id, child);+ }+ }+ if (message.compressedMessages) buildBlockIndex(message.compressedMessages, index);+ if (message.role === 'agentCouncil' && (message as any).members) {+ buildBlockIndex((message as any).members, index);+ }+ }+ return index;+};++const blockIndexCache = new WeakMap<UIChatMessage[], Map<string, AssistantContentBlock>>();++export const findBlockInDisplayMessages = (+ messages: UIChatMessage[],+ blockId: string,+): AssistantContentBlock | undefined => {+ let index = blockIndexCache.get(messages);+ if (!index) {+ index = buildBlockIndex(messages, new Map());+ blockIndexCache.set(messages, index);+ }+ return index.get(blockId);+};++// A block normally carries a handful of tools, but a parallel fan-out can carry+// hundreds; index them per `tools` array (stable while the block is unchanged).+const toolIndexCache = new WeakMap<+ ChatToolPayloadWithResult[],+ Map<string, ChatToolPayloadWithResult>+>();++export const findToolInList = (+ tools: ChatToolPayloadWithResult[],+ toolCallId: string,+): ChatToolPayloadWithResult | undefined => {+ let index = toolIndexCache.get(tools);+ if (!index) {+ index = new Map();+ for (const tool of tools) if (!index.has(tool.id)) index.set(tool.id, tool);+ toolIndexCache.set(tools, index);+ }+ return index.get(toolCallId);+};++// ===== Raw db rows =====++interface DbMessageIndex {+ byId: Map<string, UIChatMessage>;+ byToolCallId: Map<string, UIChatMessage>;+}++const dbIndexCache = new WeakMap<UIChatMessage[], DbMessageIndex>();++export const indexDbMessages = (messages: UIChatMessage[]): DbMessageIndex => {+ let index = dbIndexCache.get(messages);+ if (!index) {+ const byId = new Map<string, UIChatMessage>();+ const byToolCallId = new Map<string, UIChatMessage>();+ for (const message of messages) {+ if (!byId.has(message.id)) byId.set(message.id, message);+ if (message.tool_call_id && !byToolCallId.has(message.tool_call_id)) {+ byToolCallId.set(message.tool_call_id, message);+ }+ }+ index = { byId, byToolCallId };+ dbIndexCache.set(messages, index);+ }+ return index;+};diff --git a/src/features/Conversation/store/slices/data/selectors.ts b/src/features/Conversation/store/slices/data/selectors.tsindex 05ff9ad631b..7f3215784f3 100644--- a/src/features/Conversation/store/slices/data/selectors.ts+++ b/src/features/Conversation/store/slices/data/selectors.ts@@ -8,6 +8,13 @@ import { useChatStore } from '@/store/chat';import { topicSelectors } from '@/store/chat/selectors';import { type State } from '../../initialState';+import {+ findBlockInDisplayMessages,+ findToolInList,+ indexDbMessages,+ indexDisplayMessages,+ toAssistantContentBlock,+} from './messageIndex';import { getPendingInterventions } from './pendingInterventions';import { collectSteerChains } from './steerChains';import { getWorkSummariesByRootOperationId } from './workSummaries';@@ -21,7 +28,7 @@ const hasLaterMessages = (s: State) => s.hasLaterMessages;const getDisplayMessageById = (id: string) => (s: State) => {// First, try to find in top-level displayMessages- const topLevelMessage = s.displayMessages.find((m) => m.id === id);+ const topLevelMessage = indexDisplayMessages(s.displayMessages).byId.get(id);if (topLevelMessage) return topLevelMessage;// If not found, search in agentCouncil members@@ -34,9 +41,9 @@ const getDisplayMessageById = (id: string) => (s: State) => {return undefined;};-const getDbMessageById = (id: string) => (s: State) => s.dbMessages.find((m) => m.id === id);+const getDbMessageById = (id: string) => (s: State) => indexDbMessages(s.dbMessages).byId.get(id);const getDbMessageByToolCallId = (id: string) => (s: State) =>- s.dbMessages.find((m) => m.tool_call_id === id);+ indexDbMessages(s.dbMessages).byToolCallId.get(id);/*** `createdAt` is typed as a number but arrives as a `Date` after a DB rehydrate@@ -217,20 +224,6 @@ const deletableRowMessageIds = (id: string) => (s: State) => [),];-const toAssistantContentBlock = (message: UIChatMessage): AssistantContentBlock => ({- content: message.content,- error: message.error,- fileList: message.fileList,- id: message.id,- imageList: message.imageList,- metadata: message.metadata ?? undefined,- performance: message.performance,- reasoning: message.reasoning ?? undefined,- tasks: message.tasks as AssistantContentBlock['tasks'],- tools: message.tools as ChatToolPayloadWithResult[],- usage: message.usage,-});-const getRowLatestMessageWithoutTools = (id: string) => (s: State) => {const tailId = rowMemberIds(id)(s).at(-1) ?? id;const tail = getDisplayMessageById(tailId)(s);@@ -242,34 +235,16 @@ const getRowLatestMessageWithoutTools = (id: string) => (s: State) => {};/**- * Walk displayMessages (including compressed groups and agentCouncil members)- * to find an assistant content block by its id. Used to let tool subtrees- * self-subscribe to their own data instead of receiving it as props from the- * message-level renderer.+ * Find an assistant content block by its id anywhere in displayMessages+ * (including compressed groups and agentCouncil members). Used to let tool+ * subtrees self-subscribe to their own data instead of receiving it as props+ * from the message-level renderer. O(1) per call: the index is built once per+ * displayMessages snapshot (see `messageIndex.ts`).*/const findBlockById = (blockId: string,messages: UIChatMessage[],-): AssistantContentBlock | undefined => {- for (const message of messages) {- if (message.role === 'assistant' && message.id === blockId) {- return toAssistantContentBlock(message);- }- if (message.children) {- const block = message.children.find((child) => child.id === blockId);- if (block) return block;- }- if (message.compressedMessages) {- const inCompressedMessages = findBlockById(blockId, message.compressedMessages);- if (inCompressedMessages) return inCompressedMessages;- }- if (message.role === 'agentCouncil' && (message as any).members) {- const inMembers = findBlockById(blockId, (message as any).members);- if (inMembers) return inMembers;- }- }- return undefined;-};+): AssistantContentBlock | undefined => findBlockInDisplayMessages(messages, blockId);const getToolsInBlock =(blockId: string) =>@@ -282,7 +257,7 @@ const getToolInBlock =(blockId: string, toolCallId: string) =>(s: State): ChatToolPayloadWithResult | undefined => {const tools = getToolsInBlock(blockId)(s);- return tools?.find((t) => t.id === toolCallId);+ return tools ? findToolInList(tools, toolCallId) : undefined;};const getBlockContent =