Skip to content

🤯 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.

Fix tool call timer reset on collapse and expand (#14513)

AmAzing-26da6b9ad411
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ExecutionTime.test.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ExecutionTime.test.tsx
new file mode 100644
index 00000000000..d5f40d8a851
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ExecutionTime.test.tsx
@@ -0,0 +1,113 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, cleanup, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import ExecutionTime from './ExecutionTime';
+
+vi.mock('@lobehub/ui', () => ({
+ Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
+}));
+
+describe('ExecutionTime', () => {
+ afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ });
+
+ it('uses the provided operation start time after remounting', () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(10_000);
+
+ const { unmount } = render(
+ <ExecutionTime isExecuting startTime={8000} timerKey="tool-with-operation" />,
+ );
+
+ expect(screen.getByText('2.0s')).toBeTruthy();
+
+ unmount();
+
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+
+ render(<ExecutionTime isExecuting startTime={8000} timerKey="tool-with-operation" />);
+
+ expect(screen.getByText('3.0s')).toBeTruthy();
+ });
+
+ it('keeps the cached start time when the timer remounts without operation metadata', () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(10_000);
+
+ const { unmount } = render(<ExecutionTime isExecuting timerKey="tool-with-cache" />);
+
+ expect(screen.getByText('0ms')).toBeTruthy();
+
+ act(() => {
+ vi.advanceTimersByTime(2500);
+ });
+
+ expect(screen.getByText('2.5s')).toBeTruthy();
+
+ unmount();
+
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+
+ render(<ExecutionTime isExecuting timerKey="tool-with-cache" />);
+
+ expect(screen.getByText('3.5s')).toBeTruthy();
+ });
+
+ it('clears the cached start time when an active timer stays unmounted', () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(10_000);
+
+ const { unmount } = render(<ExecutionTime isExecuting timerKey="tool-active-unmount" />);
+
+ act(() => {
+ vi.advanceTimersByTime(1500);
+ });
+
+ expect(screen.getByText('1.5s')).toBeTruthy();
+
+ unmount();
+
+ act(() => {
+ vi.runOnlyPendingTimers();
+ });
+
+ render(<ExecutionTime isExecuting timerKey="tool-active-unmount" />);
+
+ expect(screen.getByText('0ms')).toBeTruthy();
+ });
+
+ it('clears the cached start time when execution stops', () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(10_000);
+
+ const { rerender } = render(<ExecutionTime isExecuting timerKey="tool-stop" />);
+
+ act(() => {
+ vi.advanceTimersByTime(1500);
+ });
+
+ expect(screen.getByText('1.5s')).toBeTruthy();
+
+ rerender(<ExecutionTime isExecuting={false} timerKey="tool-stop" />);
+
+ expect(screen.queryByText('1.5s')).toBeNull();
+
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+
+ rerender(<ExecutionTime isExecuting timerKey="tool-stop" />);
+
+ expect(screen.getByText('0ms')).toBeTruthy();
+ });
+});
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ExecutionTime.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ExecutionTime.tsx
index 05f44d6f92b..f356a573e72 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ExecutionTime.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ExecutionTime.tsx
@@ -1,10 +1,36 @@
import { Text } from '@lobehub/ui';
-import { memo, useEffect, useRef, useState } from 'react';
+import { memo, useEffect, useState } from 'react';
interface ExecutionTimeProps {
isExecuting: boolean;
+ startTime?: number;
+ timerKey: string;
}
+const UPDATE_INTERVAL_MS = 100;
+const START_TIME_CACHE_TTL_MS = 60_000;
+const executionStartTimeCache = new Map<string, number>();
+const executionStartTimeCleanupTimers = new Map<string, number>();
+
+const clearExecutionStartTimeCleanup = (timerKey: string) => {
+ const cleanupTimer = executionStartTimeCleanupTimers.get(timerKey);
+ if (cleanupTimer === undefined) return;
+
+ window.clearTimeout(cleanupTimer);
+ executionStartTimeCleanupTimers.delete(timerKey);
+};
+
+const scheduleExecutionStartTimeCleanup = (timerKey: string) => {
+ clearExecutionStartTimeCleanup(timerKey);
+
+ const cleanupTimer = window.setTimeout(() => {
+ executionStartTimeCache.delete(timerKey);
+ executionStartTimeCleanupTimers.delete(timerKey);
+ }, START_TIME_CACHE_TTL_MS);
+
+ executionStartTimeCleanupTimers.set(timerKey, cleanupTimer);
+};
+
const formatElapsedTime = (ms: number): string => {
if (ms < 1000) return `${ms}ms`;
@@ -15,35 +41,34 @@ const formatElapsedTime = (ms: number): string => {
return `${minutes.toFixed(1)}min`;
};
-const ExecutionTime = memo<ExecutionTimeProps>(({ isExecuting }) => {
+const ExecutionTime = memo<ExecutionTimeProps>(({ isExecuting, startTime, timerKey }) => {
const [elapsed, setElapsed] = useState(0);
- const startTimeRef = useRef(Date.now());
- const rafRef = useRef<number | null>(null);
- const lastUpdateRef = useRef(0);
useEffect(() => {
if (!isExecuting) {
- if (rafRef.current) cancelAnimationFrame(rafRef.current);
+ clearExecutionStartTimeCleanup(timerKey);
+ executionStartTimeCache.delete(timerKey);
+ setElapsed(0);
return;
}
- startTimeRef.current = Date.now();
- setElapsed(0);
+ clearExecutionStartTimeCleanup(timerKey);
+
+ const resolvedStartTime = startTime ?? executionStartTimeCache.get(timerKey) ?? Date.now();
+ executionStartTimeCache.set(timerKey, resolvedStartTime);
- const update = (timestamp: number) => {
- if (timestamp - lastUpdateRef.current >= 100) {
- setElapsed(Date.now() - startTimeRef.current);
- lastUpdateRef.current = timestamp;
- }
- rafRef.current = requestAnimationFrame(update);
+ const update = () => {
+ setElapsed(Math.max(0, Date.now() - resolvedStartTime));
};
- rafRef.current = requestAnimationFrame(update);
+ update();
+ const interval = window.setInterval(update, UPDATE_INTERVAL_MS);
return () => {
- if (rafRef.current) cancelAnimationFrame(rafRef.current);
+ window.clearInterval(interval);
+ scheduleExecutionStartTimeCleanup(timerKey);
};
- }, [isExecuting]);
+ }, [isExecuting, startTime, timerKey]);
if (!isExecuting) return null;
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/index.tsx
index efd5cc347a8..ab258736450 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/index.tsx
@@ -26,6 +26,8 @@ interface InspectorProps {
*/
isToolCalling?: boolean;
result?: { content: string | null; error?: any; state?: any };
+ toolCallId: string;
+ toolCallStartTime?: number;
}
const Inspectors = memo<InspectorProps>(
@@ -37,6 +39,8 @@ const Inspectors = memo<InspectorProps>(
intervention,
isArgumentsStreaming,
isToolCalling,
+ toolCallId,
+ toolCallStartTime,
}) => {
const isPending = intervention?.status === 'pending';
const isAborted = intervention?.status === 'aborted';
@@ -93,7 +97,11 @@ const Inspectors = memo<InspectorProps>(
result={result}
/>
</SafeBoundary>
- <ExecutionTime isExecuting={showExecutionTimer} />
+ <ExecutionTime
+ isExecuting={showExecutionTimer}
+ startTime={toolCallStartTime}
+ timerKey={toolCallId}
+ />
</Flexbox>
);
}
@@ -117,7 +125,11 @@ const Inspectors = memo<InspectorProps>(
isLoading={isTitleLoading}
partialArgs={partialJson || undefined}
/>
- <ExecutionTime isExecuting={showExecutionTimer} />
+ <ExecutionTime
+ isExecuting={showExecutionTimer}
+ startTime={toolCallStartTime}
+ timerKey={toolCallId}
+ />
</Flexbox>
);
},
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx
index 8910a328afb..28f990951ea 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx
@@ -94,6 +94,7 @@ const Tool = memo<GroupToolProps>(({ assistantMessageId, disableEditing, id }) =
const looksLikeWaitingForToolResult = !hasError && !isArgumentsStreaming && !hasFinishedResult;
const isToolCallingFallback = looksLikeWaitingForToolResult && isAssistantMessageBusy;
const isToolCalling = !hasFinishedResult && (isToolCallingFromOperation || isToolCallingFallback);
+ const toolCallStartTime = useChatStore(operationSelectors.getRunningToolCallStartTime(id));
const hasCustomRender = !!getBuiltinRender(identifier, apiName);
// Only allow toggle when has custom render and not in pending/reject/abort state
@@ -151,6 +152,8 @@ const Tool = memo<GroupToolProps>(({ assistantMessageId, disableEditing, id }) =
isArgumentsStreaming={isArgumentsStreaming}
isToolCalling={isToolCalling}
result={result}
+ toolCallId={id}
+ toolCallStartTime={toolCallStartTime}
/>
}
onExpandChange={handleExpand}
diff --git a/src/features/Conversation/Messages/Tool/Tool/index.tsx b/src/features/Conversation/Messages/Tool/Tool/index.tsx
index 08ea0866063..8861c1ee9d5 100644
--- a/src/features/Conversation/Messages/Tool/Tool/index.tsx
+++ b/src/features/Conversation/Messages/Tool/Tool/index.tsx
@@ -82,7 +82,6 @@ const Tool = memo<InspectorProps>(
itemKey={'tool'}
paddingBlock={4}
paddingInline={4}
- title={<Inspectors apiName={apiName} identifier={identifier} result={result} />}
action={
!disableEditing && (
<Actions
@@ -96,6 +95,14 @@ const Tool = memo<InspectorProps>(
/>
)
}
+ title={
+ <Inspectors
+ apiName={apiName}
+ identifier={identifier}
+ result={result}
+ toolCallId={toolCallId}
+ />
+ }
>
<Flexbox gap={8} paddingBlock={8}>
{showDebug && !disableEditing && (
diff --git a/src/store/chat/slices/operation/__tests__/selectors.test.ts b/src/store/chat/slices/operation/__tests__/selectors.test.ts
index 6880a32c9ba..c1fe1f314b8 100644
--- a/src/store/chat/slices/operation/__tests__/selectors.test.ts
+++ b/src/store/chat/slices/operation/__tests__/selectors.test.ts
@@ -509,6 +509,73 @@ describe('Operation Selectors', () => {
});
});
+ describe('getRunningToolCallStartTime', () => {
+ it('should prefer the running executeToolCall start time', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ const parentOpId = result.current.startOperation({
+ type: 'toolCalling',
+ context: { agentId: 'session1', messageId: 'assistant_msg' },
+ metadata: { startTime: 1000, tool_call_id: 'tool-1' },
+ }).operationId;
+
+ result.current.startOperation({
+ type: 'executeToolCall',
+ context: { agentId: 'session1', messageId: 'tool_msg' },
+ metadata: { startTime: 1500, tool_call_id: 'tool-1' },
+ parentOperationId: parentOpId,
+ });
+
+ result.current.startOperation({
+ type: 'toolCalling',
+ context: { agentId: 'session1', messageId: 'assistant_msg' },
+ metadata: { startTime: 900, tool_call_id: 'tool-2' },
+ });
+ });
+
+ expect(operationSelectors.getRunningToolCallStartTime('tool-1')(result.current)).toBe(1500);
+ });
+
+ it('should fall back to the running toolCalling start time when execution has not started', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ result.current.startOperation({
+ type: 'toolCalling',
+ context: { agentId: 'session1', messageId: 'assistant_msg' },
+ metadata: { startTime: 1000, tool_call_id: 'tool-1' },
+ });
+ });
+
+ expect(operationSelectors.getRunningToolCallStartTime('tool-1')(result.current)).toBe(1000);
+ });
+
+ it('should ignore completed and unrelated tool operations', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ const completedOpId = result.current.startOperation({
+ type: 'toolCalling',
+ context: { agentId: 'session1', messageId: 'assistant_msg' },
+ metadata: { startTime: 1000, tool_call_id: 'tool-1' },
+ }).operationId;
+
+ result.current.completeOperation(completedOpId);
+
+ result.current.startOperation({
+ type: 'createToolMessage',
+ context: { agentId: 'session1', messageId: 'tool_msg' },
+ metadata: { startTime: 1200, tool_call_id: 'tool-1' },
+ });
+ });
+
+ expect(operationSelectors.getRunningToolCallStartTime('tool-1')(result.current)).toBe(
+ undefined,
+ );
+ });
+ });
+
describe('isAgentRunning', () => {
it('should return false when no operations exist', () => {
const { result } = renderHook(() => useChatStore());
diff --git a/src/store/chat/slices/operation/selectors.ts b/src/store/chat/slices/operation/selectors.ts
index 982f369f08b..dfb1238ef0e 100644
--- a/src/store/chat/slices/operation/selectors.ts
+++ b/src/store/chat/slices/operation/selectors.ts
@@ -445,6 +445,50 @@ const isMessageInToolCalling =
return operations.some((op) => op.type === 'toolCalling' && op.status === 'running');
};
+/**
+ * Find a running tool operation start time by operation type.
+ */
+const getRunningToolOperationStartTime = (
+ type: OperationType,
+ toolCallId: string,
+ s: ChatStoreState,
+) => {
+ const operationIds = s.operationsByType[type] ?? [];
+ let startTime: number | undefined;
+
+ for (const id of operationIds) {
+ const operation = s.operations[id];
+ if (
+ !operation ||
+ operation.status !== 'running' ||
+ operation.metadata.tool_call_id !== toolCallId
+ ) {
+ continue;
+ }
+
+ startTime =
+ startTime === undefined
+ ? operation.metadata.startTime
+ : Math.min(startTime, operation.metadata.startTime);
+ }
+
+ return startTime;
+};
+
+/**
+ * Get the stable start time for a running tool call.
+ * Prefer the actual execution phase; fall back to the parent tool call while
+ * the execution operation has not been created yet.
+ */
+const getRunningToolCallStartTime =
+ (toolCallId: string) =>
+ (s: ChatStoreState): number | undefined => {
+ return (
+ getRunningToolOperationStartTime('executeToolCall', toolCallId, s) ??
+ getRunningToolOperationStartTime('toolCalling', toolCallId, s)
+ );
+ };
+
/**
* Check if currently aborting (cleaning up after user cancellation)
* Used to show "Cleaning up tool calls..." message
@@ -563,6 +607,7 @@ export const operationSelectors = {
getOperationsByMessage,
getOperationsByType,
getRunningOperations,
+ getRunningToolCallStartTime,
hasAnyRunningOperation,
hasRunningOperationByContext,
hasRunningOperationType,