π€― 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
π fix(conversation): measure workflow fold time as its own wall clock (#19702)
Arvin Xu4b03949a6533
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.test.tsx b/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.test.tsxindex 5a3f1ca174d..964e763d75f 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.test.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.test.tsx@@ -10,6 +10,7 @@ import type { AssistantContentBlock } from '@/types/index';import WorkflowCollapse from './WorkflowCollapse';let mockIsGenerating = true;+let mockDbMessages: { createdAt?: Date; id: string; updatedAt?: Date }[] = [];vi.mock('@lobehub/ui', async (importOriginal) => ({...(await importOriginal<object>()),@@ -109,7 +110,8 @@ vi.mock('../../../store', () => ({isAssistantGroupItemGenerating: () => () => mockIsGenerating,isMessageGenerating: () => () => mockIsGenerating,},- useConversationStore: (selector: (state: unknown) => unknown) => selector({}),+ useConversationStore: (selector: (state: unknown) => unknown) =>+ selector({ dbMessages: mockDbMessages }),}));vi.mock('./WorkflowExpandedList', () => ({@@ -140,6 +142,7 @@ describe('WorkflowCollapse', () => {afterEach(() => {cleanup();mockIsGenerating = true;+ mockDbMessages = [];vi.useRealTimers();});@@ -320,6 +323,102 @@ describe('WorkflowCollapse', () => {expect(screen.getByText('(4s)')).toBeInTheDocument();});+ it("counts elapsed time from this collapse's first step, not the whole run", () => {+ // Regression: a long turn folds into several collapses. Anchoring the timer+ // to the operation start made every fold print the same run-long number β+ // the elapsed time must cover this fold's own steps only.+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-09-20T10:00:00Z'));+ mockDbMessages = [+ { createdAt: new Date('2026-09-20T09:00:00Z'), id: 'block-0' },+ { createdAt: new Date('2026-09-20T09:59:50Z'), id: 'block-1' },+ ];++ render(<WorkflowCollapse assistantMessageId="msg-1" blocks={makeBlocks()} />);++ expect(screen.getByText('(10s)')).toBeInTheDocument();++ act(() => {+ vi.advanceTimersByTime(2000);+ });++ expect(screen.getByText('(12s)')).toBeInTheDocument();+ });++ it('reports a finished fold as wall-clock time, not summed model duration', () => {+ // Regression: `performance.duration` only counts model output, so a fold+ // that sat in tool calls for two minutes advertised a few seconds.+ mockIsGenerating = false;+ mockDbMessages = [+ { createdAt: new Date('2026-09-20T09:00:00Z'), id: 'block-1' },+ { createdAt: new Date('2026-09-20T09:02:00Z'), id: 'tool-result-1' },+ ];++ const blocks = makeBlocks({ result: { content: 'ok' }, result_msg_id: 'tool-result-1' });+ blocks[0]!.performance = { duration: 4000 } as any;++ render(<WorkflowCollapse assistantMessageId="msg-1" blocks={blocks} />);++ expect(screen.getByText('2m')).toBeInTheDocument();+ expect(screen.queryByText('4s')).not.toBeInTheDocument();+ });++ it('counts a client-executed tool from its result write, not from its start', () => {+ // Regression: the client runtime creates the tool row BEFORE invoking the+ // tool and writes the result into it afterwards, so `createdAt` is when the+ // tool STARTED. Ending the fold there left the tool's whole runtime out.+ mockIsGenerating = false;+ mockDbMessages = [+ { createdAt: new Date('2026-09-20T09:00:00Z'), id: 'block-1' },+ {+ createdAt: new Date('2026-09-20T09:00:05Z'),+ id: 'tool-result-1',+ updatedAt: new Date('2026-09-20T09:03:05Z'),+ },+ ];++ const blocks = makeBlocks({ result: { content: 'ok' }, result_msg_id: 'tool-result-1' });++ render(<WorkflowCollapse assistantMessageId="msg-1" blocks={blocks} />);++ expect(screen.getByText('3m 5s')).toBeInTheDocument();+ expect(screen.queryByText('5s')).not.toBeInTheDocument();+ });++ it('ignores a later edit of the assistant step itself', () => {+ // An assistant row's `updatedAt` also moves when the message is edited long+ // after the turn; only tool results may extend the fold.+ mockIsGenerating = false;+ mockDbMessages = [+ {+ createdAt: new Date('2026-09-20T09:00:00Z'),+ id: 'block-1',+ updatedAt: new Date('2026-09-21T09:00:00Z'),+ },+ { createdAt: new Date('2026-09-20T09:02:00Z'), id: 'tool-result-1' },+ ];++ const blocks = makeBlocks({ result: { content: 'ok' }, result_msg_id: 'tool-result-1' });++ render(<WorkflowCollapse assistantMessageId="msg-1" blocks={blocks} />);++ expect(screen.getByText('2m')).toBeInTheDocument();+ });++ it('falls back to model duration when the raw messages are unavailable', () => {+ // Share pages / portals render blocks without `dbMessages`; a rough number+ // still beats no number at all.+ mockIsGenerating = false;+ mockDbMessages = [];++ const blocks = makeBlocks({ result: { content: 'ok' } });+ blocks[0]!.performance = { duration: 4000 } as any;++ render(<WorkflowCollapse assistantMessageId="msg-1" blocks={blocks} />);++ expect(screen.getByText('4s')).toBeInTheDocument();+ });+it('cycles expand levels via the toggle button', () => {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 2c766088169..39729d6d51b 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.tsx@@ -32,6 +32,7 @@ import {getWorkflowSummaryText,shapeProseForWorkflowHeadline,} from '../toolDisplayNames';+import { getBlocksEndCreatedAt, getFirstBlockCreatedAt } from './groupChain';import type { RenderableAssistantContentBlock } from './types';import WorkflowExpandedList from './WorkflowExpandedList';@@ -167,17 +168,38 @@ const WorkflowCollapse = memo<WorkflowCollapseProps>(if (ops.length === 0) return undefined;return ops.reduce((min, op) => Math.min(min, op.metadata.startTime), Infinity);});+ /** Wall-clock bounds of this collapse's own steps. A long turn folds into+ * several collapses, so anchoring to the op start makes every one of them+ * read the same run-long number; both the live timer and the finished+ * header should cover this fold only. Read as two primitives so the+ * selectors stay reference-stable across streaming re-renders. */+ const segmentStartTime = useConversationStore((s) =>+ getFirstBlockCreatedAt(s.dbMessages, blocks),+ );+ const segmentEndTime = useConversationStore((s) => getBlocksEndCreatedAt(s.dbMessages, blocks));+ /** Falls back to the op start (then to mount time) when the blocks don't+ * resolve against the raw messages. */+ const workingStartTime = segmentStartTime ?? opStartTime;const allComplete = toolsPhaseComplete && (workflowChromeComplete || !isGenerating);const summaryText = useMemo(() => getWorkflowSummaryText(blocks), [blocks]);const completionStatus = useMemo(() => getWorkflowCompletionStatus(allTools), [allTools]);- /** Sum of per-round model output duration (not reasoning-only); see ModelPerformance.duration */+ /** How long this fold actually occupied: last step (or tool result) minus+ * first step. `performance.duration` only sums per-round model output, so+ * a fold that spent minutes inside tool calls or waiting between rounds+ * under-reported badly β it is kept solely as a fallback for hosts that+ * render blocks without the raw `dbMessages` (share pages, portals). */+ const wallClockMs =+ segmentStartTime !== undefined && segmentEndTime !== undefined+ ? segmentEndTime - segmentStartTime+ : 0;const totalWorkflowMs = useMemo(() => blocks.reduce((sum, b) => sum + (b.performance?.duration ?? 0), 0),[blocks],);- const durationText = totalWorkflowMs > 0 ? formatReasoningDuration(totalWorkflowMs) : undefined;+ const durationMs = wallClockMs > 0 ? wallClockMs : totalWorkflowMs;+ const durationText = durationMs > 0 ? formatReasoningDuration(durationMs) : undefined;const { streaming: streamingDefault, completion: completionDefault } = useMemo(() => resolveExpandDefaults(defaultWorkflowExpandLevel),[defaultWorkflowExpandLevel],@@ -309,11 +331,12 @@ const WorkflowCollapse = memo<WorkflowCollapseProps>(}if (activeWorkingStartedAtRef.current === null) {- // Initial/remount seeds from op start so elapsed reflects wall-clock- // since the op began. Intervention resume seeds from now so pause- // time stays excluded from the accumulator.+ // Initial/remount seeds from this collapse's first step so elapsed+ // reflects wall-clock since the fold began. Intervention resume seeds+ // from now so pause time stays excluded from the accumulator.const isInitial = accumulatedWorkingMsRef.current === 0;- activeWorkingStartedAtRef.current = isInitial && opStartTime ? opStartTime : Date.now();+ activeWorkingStartedAtRef.current =+ isInitial && workingStartTime ? workingStartTime : Date.now();}const tick = () => {@@ -329,7 +352,7 @@ const WorkflowCollapse = memo<WorkflowCollapseProps>(const interval = setInterval(tick, 1000);return () => clearInterval(interval);- }, [opStartTime, pendingInterventionPresent, streaming]);+ }, [workingStartTime, pendingInterventionPresent, streaming]);const showWorkingElapsed =!pendingInterventionPresent &&diff --git a/src/features/Conversation/Messages/AssistantGroup/components/groupChain.ts b/src/features/Conversation/Messages/AssistantGroup/components/groupChain.tsindex 5d3f0d43fae..1530ad75151 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/groupChain.ts+++ b/src/features/Conversation/Messages/AssistantGroup/components/groupChain.ts@@ -15,7 +15,15 @@ import type { RenderableAssistantContentBlock } from './types';const ANSWER_DOM_ID_SUFFIX = '__answer';const WORKFLOW_DOM_ID_SUFFIX = '__workflow';-type DbMessageLike = { createdAt?: Date | number | string | null; id: string };+type DbMessageLike = {+ createdAt?: Date | number | string | null;+ id: string;+ updatedAt?: Date | number | string | null;+};++/** Anything that resolves to step rows in `dbMessages` β blocks, or their+ * rendered projections, which keep the source block id. */+type BlockTimeSource = { id: string; tools?: { result_msg_id?: string | null }[] };export interface GroupChainInput {blocks: AssistantContentBlock[];@@ -65,37 +73,86 @@ export const getTurnDurationMs = (};/**- * `createdAt` of the turn's last step, normalized to epoch ms. Used to anchor the- * tail running indicator's elapsed timer to "time since the last step" instead of- * the whole run β the operation's own startTime marks the run's beginning.+ * Earliest `createdAt` among a set of steps, normalized to epoch ms. Anchors a+ * workflow collapse to the fold's own first entry instead of the operation+ * start β a long run folds into several collapses, and anchoring them all to+ * the op would print the same run-long number on each.+ */+export const getFirstBlockCreatedAt = (+ dbMessages: DbMessageLike[] | undefined,+ blocks: BlockTimeSource[],+): number | undefined => {+ if (!Array.isArray(dbMessages) || blocks.length === 0) return undefined;++ const ids = new Set(blocks.map((block) => block.id));+ let earliest: number | undefined;+ for (const message of dbMessages) {+ if (!ids.has(message.id)) continue;+ const time = toEpochMs(message.createdAt);+ if (time === undefined) continue;+ if (earliest === undefined || time < earliest) earliest = time;+ }+ return earliest;+};++/**+ * When a set of steps finished, normalized to epoch ms.+ *+ * When a step ends on tool calls, its freshest message is the tool RESULT row+ * (`result_msg_id`) β not the assistant block that issued the call. Taking the+ * block ids alone would end the span before the tools it is waiting on, so the+ * result rows join the candidates.*- * When the last block ends on tool calls, its freshest message is the tool RESULT- * row (`result_msg_id`), created when the tool finished β not the assistant block- * that issued the call. Anchoring to the block id alone would fold the tool's- * runtime back into the elapsed time, defeating the point. So we take the latest- * `createdAt` across the block and its tool-result rows.+ * A result row's own end is `updatedAt`, not `createdAt`: the client runtime+ * creates the row BEFORE invoking the tool (`ClientToolTransport.execute`) and+ * writes the result into it afterwards, so `createdAt` there marks when the+ * tool STARTED and would leave a slow tool's whole runtime outside the span.+ * The server runtime writes the row once, on completion, where the two stamps+ * coincide β so the later of the two is right on both paths. Assistant blocks+ * keep `createdAt` only: their `updatedAt` also moves when the message is+ * edited later, which has nothing to do with how long the step took.*/-export const getLastBlockCreatedAt = (+export const getBlocksEndCreatedAt = (dbMessages: DbMessageLike[] | undefined,- lastBlock: AssistantContentBlock | undefined,+ blocks: BlockTimeSource[],): number | undefined => {- if (!Array.isArray(dbMessages) || !lastBlock) return undefined;+ if (!Array.isArray(dbMessages) || blocks.length === 0) return undefined;- const candidateIds = new Set<string>([lastBlock.id]);- for (const tool of lastBlock.tools ?? []) {- if (tool.result_msg_id) candidateIds.add(tool.result_msg_id);+ const blockIds = new Set<string>();+ const resultIds = new Set<string>();+ for (const block of blocks) {+ blockIds.add(block.id);+ for (const tool of block.tools ?? []) {+ if (tool.result_msg_id) resultIds.add(tool.result_msg_id);+ }}let latest: number | undefined;for (const message of dbMessages) {- if (!candidateIds.has(message.id)) continue;- const time = toEpochMs(message.createdAt);- if (time === undefined) continue;- if (latest === undefined || time > latest) latest = time;+ const isResult = resultIds.has(message.id);+ if (!isResult && !blockIds.has(message.id)) continue;++ const created = toEpochMs(message.createdAt);+ const settled = isResult ? toEpochMs(message.updatedAt) : undefined;+ for (const time of [created, settled]) {+ if (time === undefined) continue;+ if (latest === undefined || time > latest) latest = time;+ }}return latest;};+/**+ * When the turn's last step finished. Used to anchor the tail running+ * indicator's elapsed timer to "time since the last step" instead of the whole+ * run β the operation's own startTime marks the run's beginning, and folding a+ * finished tool's runtime back into the elapsed time defeats the point.+ */+export const getLastBlockCreatedAt = (+ dbMessages: DbMessageLike[] | undefined,+ lastBlock: AssistantContentBlock | undefined,+): number | undefined => getBlocksEndCreatedAt(dbMessages, lastBlock ? [lastBlock] : []);+export const isEmptyBlock = (block: RenderableAssistantContentBlock) =>(!block.content || block.content === LOADING_FLAT) &&(!block.tools || block.tools.length === 0) &&