From f8ab7fe67ceade6333d4a80558dc914abdbf5491 Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Tue, 10 Nov 2026 15:56:09 +0100 Subject: [PATCH] =?UTF-8?q?=E2=8F=B1=EF=B8=8F=20fix:=20Preserve=20Running?= =?UTF-8?q?=20Tool=20Timers=20Across=20Disclosure=20Remounts=20(#17997)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: Preserve Running Tool Timers Across Disclosure Remounts * test: Cover Running Tool Timer Disclosure Lifecycles --- .../Chat/Messages/Content/ProgressText.tsx | 14 ++++- .../Chat/Messages/Content/ToolCall.tsx | 1 + .../Content/__tests__/ProgressText.test.tsx | 33 ++++++++++ .../SSE/__tests__/useStepHandler.spec.ts | 62 ++++++++++++++++++- e2e/specs/mock/scenarios/tool-timer.spec.ts | 49 +++++++++++++++ packages/chat/src/react.ts | 1 + packages/chat/src/react/stream/receipt.ts | 59 ++++++++++++++++++ packages/chat/src/react/stream/step.ts | 36 ++++++++++- 8 files changed, 249 insertions(+), 6 deletions(-) create mode 100644 e2e/specs/mock/scenarios/tool-timer.spec.ts create mode 100644 packages/chat/src/react/stream/receipt.ts diff --git a/client/src/components/Chat/Messages/Content/ProgressText.tsx b/client/src/components/Chat/Messages/Content/ProgressText.tsx index 5808d16939..b0ccb1c56e 100644 --- a/client/src/components/Chat/Messages/Content/ProgressText.tsx +++ b/client/src/components/Chat/Messages/Content/ProgressText.tsx @@ -1,7 +1,9 @@ import { useCallback, useRef } from 'react'; +import { useStore } from 'jotai'; import { ChevronDown } from 'lucide-react'; import { useTranslation } from 'react-i18next'; import * as Popover from '@radix-ui/react-popover'; +import { phaseReceipts } from '@librechat/chat/react'; import { Button, disclosureChevronVariants } from '@librechat/client'; import { isReportableRunStepDuration } from 'librechat-data-provider'; import { @@ -62,6 +64,7 @@ export default function ProgressText({ toolPreparationDurationMs, toolExecutionDurationMs, phaseStartAt, + phaseStepId, hasInput = true, popover = false, isExpanded = false, @@ -89,6 +92,7 @@ export default function ProgressText({ toolPreparationDurationMs?: number; toolExecutionDurationMs?: number; phaseStartAt?: number; + phaseStepId?: string; hasInput?: boolean; popover?: boolean; isExpanded?: boolean; @@ -102,15 +106,21 @@ export default function ProgressText({ const { i18n } = useTranslation(); const preparationText = useToolPreparation(); const isRunning = phase === 'running'; + const receiptStore = useStore(); + /** Stream receipts are recorded before the matching phase reaches the message renderer. */ + const receivedAt = + phaseStepId != null && phaseStartAt != null + ? receiptStore.get(phaseReceipts).get(phaseStepId)?.get(phaseStartAt) + : undefined; /** A server-authored phase stamp is an identity, not a browser clock origin. * On reconnect we can only time from local receipt, never infer cross-host skew. */ const phaseTimer = useRef<{ stamp?: number; receivedAt: number } | null>(null); if (!isRunning || phaseStartAt == null) { phaseTimer.current = null; } else if (phaseTimer.current?.stamp !== phaseStartAt) { - phaseTimer.current = { stamp: phaseStartAt, receivedAt: Date.now() }; + phaseTimer.current = { stamp: phaseStartAt, receivedAt: receivedAt ?? Date.now() }; } - const localPhaseStart = phaseTimer.current?.receivedAt; + const localPhaseStart = receivedAt ?? phaseTimer.current?.receivedAt; const rootRef = useRef(null); /** A header above asked for its failures. This control is the disclosure * every card renders, so answering here reaches a failed bash, code, diff --git a/client/src/components/Chat/Messages/Content/ToolCall.tsx b/client/src/components/Chat/Messages/Content/ToolCall.tsx index ea2c5b185f..3e81c2bb87 100644 --- a/client/src/components/Chat/Messages/Content/ToolCall.tsx +++ b/client/src/components/Chat/Messages/Content/ToolCall.tsx @@ -476,6 +476,7 @@ export default function ToolCall({ toolPreparationDurationMs={toolPreparationDurationMs} toolExecutionDurationMs={toolExecutionDurationMs} phaseStartAt={toolDispatchedAt ?? toolPreparationStartedAt} + phaseStepId={stepId} icon={ > = {}) => render(); describe('ProgressText duration', () => { + it('includes time before the first expansion', () => { + const store = createStore(); + store.set(phaseReceipts, new Map([['late-step', new Map([[1_000, 20_000]])]])); + jest.spyOn(Date, 'now').mockReturnValue(28_000); + render( + + + , + ); + expect(screen.getByTestId('stream-elapsed')).toHaveTextContent('8s'); + }); + + it('keeps elapsed time when a running card is unmounted and reopened', () => { + const clock = jest.spyOn(Date, 'now').mockReturnValue(20_000); + const store = createStore(); + store.set(phaseReceipts, new Map([['timer-step', new Map([[9_000, 20_000]])]])); + const card = () => + render( + + + , + ); + const { unmount } = card(); + expect(screen.getByTestId('stream-elapsed')).toHaveTextContent('0s'); + unmount(); + clock.mockReturnValue(28_000); + card(); + expect(screen.getByTestId('stream-elapsed')).toHaveTextContent('8s'); + }); + it('renders the compact duration on a settled card', () => { renderProgressText({ durationMs: 3500 }); expect(screen.getByText('3.5s')).toBeInTheDocument(); diff --git a/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts b/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts index dda7737a63..3c663e9bc9 100644 --- a/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts +++ b/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts @@ -1,8 +1,8 @@ import React from 'react'; import { RecoilRoot } from 'recoil'; -import { useStepHandler } from '@librechat/chat/react'; import { renderHook, act } from '@testing-library/react'; import { resolveAskUserQuestionPart } from '@librechat/chat'; +import { useStepHandler, phaseReceipts } from '@librechat/chat/react'; import { useStore, useAtomValue, createStore, Provider as JotaiProvider } from 'jotai'; import { Constants, @@ -1823,6 +1823,66 @@ describe('useStepHandler', () => { }); describe('on_run_step_delta event', () => { + it('records browser phase receipt before rendering, preserves duplicates, and clears on reset', () => { + const store = createStore(); + const wrapper = ({ children }: { children: React.ReactNode }) => + React.createElement(JotaiProvider, { store }, children); + const { result } = renderHook(() => useStepHandler(createHookParams()), { wrapper }); + const submission = createSubmission(); + const clock = jest.spyOn(Date, 'now').mockReturnValue(20_000); + const receipt = () => store.get(phaseReceipts).get('step-tool-1')?.get(1_000); + const event = { + event: StepEvents.ON_TOOL_CALLS_DISPATCHED as const, + data: { + dispatched_at: 1_000, + toolCalls: [{ id: 'tool-call-1', name: 'test_tool', stepId: 'step-tool-1' }], + }, + }; + act(() => result.current.stepHandler(event, submission)); + expect(receipt()).toBe(20_000); + clock.mockReturnValue(28_000); + act(() => result.current.stepHandler(event, submission)); + expect(receipt()).toBe(20_000); + act(() => { + result.current.stepHandler( + { event: StepEvents.ON_RUN_STEP, data: createToolCallRunStep() }, + submission, + ); + for (const stamp of [100, 200, 300]) { + result.current.stepHandler( + { + event: StepEvents.ON_RUN_STEP_DELTA, + data: { + id: 'step-tool-1', + observed_at: stamp, + delta: { + type: StepTypes.TOOL_CALLS, + tool_calls: [{ id: 'tool-call-1', index: 0, args: '{' }], + }, + }, + }, + submission, + ); + } + result.current.stepHandler( + { + ...event, + data: { + ...event.data, + toolCalls: [{ ...event.data.toolCalls[0], stepId: 'other-step' }], + }, + }, + submission, + ); + }); + expect(store.get(phaseReceipts).get('step-tool-1')?.size).toBe(2); + expect(store.get(phaseReceipts).get('step-tool-1')?.get(100)).toBe(28_000); + expect(store.get(phaseReceipts).get('other-step')?.get(1_000)).toBe(28_000); + act(() => result.current.clearStepMaps()); + expect(receipt()).toBeUndefined(); + expect(store.get(phaseReceipts).size).toBe(0); + }); + it('separates streamed preparation, dispatch, and this call’s result', () => { mockGetMessages.mockReturnValue([createResponseMessage()]); const { result } = renderHook(() => useStepHandler(createHookParams())); diff --git a/e2e/specs/mock/scenarios/tool-timer.spec.ts b/e2e/specs/mock/scenarios/tool-timer.spec.ts new file mode 100644 index 0000000000..2a931815fc --- /dev/null +++ b/e2e/specs/mock/scenarios/tool-timer.spec.ts @@ -0,0 +1,49 @@ +import { expect, test } from '@playwright/test'; +import { NEW_CHAT_PATH, messagesView, modelSelectorTrigger, sendMessage } from '../helpers'; + +test('a running tool includes hidden time before and after expansion @scenario:running-tool-timer-keeps-hidden-time', async ({ + page, +}) => { + test.setTimeout(120_000); + const label = `timer-${Date.now()}`; + await page.goto(NEW_CHAT_PATH); + const modelSelector = modelSelectorTrigger(page); + await modelSelector.click(); + await page.getByRole('option', { name: 'Mock Provider F', exact: true }).click(); + /** Mobile includes the nested Pin action in the option's accessible name. */ + await page.getByRole('option', { name: /^mock-model-f(?: Pin)?$/ }).click(); + await expect(modelSelector).toContainText('mock-model-f'); + await expect(modelSelector).toHaveAttribute('aria-expanded', 'false'); + await page.getByRole('button', { name: 'Attach and tools' }).click(); + await page + .getByRole('dialog', { name: 'Attach and tools' }) + .getByRole('button', { name: /^E2E Memory\b/ }) + .click(); + await page.keyboard.press('Escape'); + const start = await page.evaluate(() => Date.now()); + await page.clock.setFixedTime(start); + await sendMessage(page, `E2E_INTERRUPT_TOOL_REPLY:${label}`); + + const view = messagesView(page); + const card = view.getByTestId('activity-phase-card').last(); + const disclosure = card.locator('button[aria-expanded]').first(); + await expect(disclosure).toContainText(/Running/); + await expect(disclosure).toHaveAttribute('aria-expanded', 'false'); + const row = card.locator(`[data-tool-call-id="call_interrupt_slow_${label}"]`); + await expect(row).toHaveCount(0); + + await page.clock.setFixedTime(start + 8_000); + await disclosure.click(); + const timer = row.getByTestId('stream-elapsed'); + await expect(timer).toHaveText(/^\d+s$/); + const before = Number.parseInt((await timer.innerText()).trim(), 10); + expect(before).toBeGreaterThanOrEqual(8); + + await disclosure.click(); + await expect(row).toHaveCount(0); + await page.clock.setFixedTime(start + 11_000); + await disclosure.click(); + await expect(timer).toBeVisible(); + expect(Number.parseInt((await timer.innerText()).trim(), 10)).toBeGreaterThanOrEqual(before + 3); + await page.getByTestId('stop-generation-button').click(); +}); diff --git a/packages/chat/src/react.ts b/packages/chat/src/react.ts index eedeb5ce01..3c238e6c34 100644 --- a/packages/chat/src/react.ts +++ b/packages/chat/src/react.ts @@ -281,3 +281,4 @@ export { export { default as useProgress } from './react/parts/useProgress'; export { default as useThrottledValue } from './react/parts/useThrottledValue'; export { default as useLazyCollapseBody } from './react/parts/useLazyCollapseBody'; +export { phaseReceipts } from './react/stream/receipt'; diff --git a/packages/chat/src/react/stream/receipt.ts b/packages/chat/src/react/stream/receipt.ts new file mode 100644 index 0000000000..d383395236 --- /dev/null +++ b/packages/chat/src/react/stream/receipt.ts @@ -0,0 +1,59 @@ +import { atom } from 'jotai'; +import { StepEvents, StepTypes } from 'librechat-data-provider'; +import type { PrimitiveAtom } from 'jotai'; +import type { StepEvent, StreamState } from '../../core'; +import { toolTimingKey } from '../../core/stream/state'; + +/** Browser receipt times are transient and never persisted with server timing metadata. */ +export const phaseReceipts: PrimitiveAtom>> = atom< + ReadonlyMap> +>(new Map()); + +export function visitPhaseStamps( + event: StepEvent, + state: StreamState, + visit: (stepId: string, stamp: number) => void, +): void { + const record = (stepId: string, stamp: number | undefined, first?: number) => { + if ( + stepId && + stamp != null && + Number.isFinite(stamp) && + stamp >= 0 && + (first == null || stamp <= first) + ) { + visit(stepId, stamp); + } + }; + if (event.event === StepEvents.ON_TOOL_CALLS_DISPATCHED) { + for (const call of event.data.toolCalls ?? []) { + if (!call.stepId || !call.id) continue; + record( + call.stepId, + event.data.dispatched_at, + state.dispatchedByCall.get(toolTimingKey(call.stepId, call.id)), + ); + } + return; + } + if ( + event.event !== StepEvents.ON_TOOL_PREPARATION && + event.event !== StepEvents.ON_RUN_STEP_DELTA + ) + return; + const { id, observed_at: stamp } = event.data; + const details = state.steps.get(id)?.stepDetails; + const declared = details?.type === StepTypes.TOOL_CALLS ? details.tool_calls : undefined; + const calls = + event.event === StepEvents.ON_TOOL_PREPARATION + ? [{ id: event.data.toolCallId, index: event.data.index }] + : (event.data.delta.tool_calls ?? []); + for (const call of calls) { + const callId = + call.id ?? (call.index === 0 && declared?.length === 1 ? declared[0]?.id : undefined); + const first = callId + ? state.firstFragmentByCall.get(toolTimingKey(id, callId)) + : state.firstFragmentByStep.get(id); + record(id, stamp, first); + } +} diff --git a/packages/chat/src/react/stream/step.ts b/packages/chat/src/react/stream/step.ts index af6b3e4bbf..936c2c1598 100644 --- a/packages/chat/src/react/stream/step.ts +++ b/packages/chat/src/react/stream/step.ts @@ -1,4 +1,4 @@ -import { useCallback, useRef } from 'react'; +import { useCallback, useEffect, useRef } from 'react'; import { useStore } from 'jotai'; import type { TMessage, @@ -29,6 +29,7 @@ import { MESSAGE_UPDATE_INTERVAL, } from '../../core'; import { ptcTraceByToolCallId, EMPTY_PTC_TRACE, PTC_TRACE_MAX_ENTRIES, ptcTraceKey } from './ptc'; +import { phaseReceipts, visitPhaseStamps } from './receipt'; import { sandboxStartingByToolCallId } from './sandbox'; type TUseStepHandler = { @@ -67,6 +68,17 @@ export function useStepHandler({ }: TUseStepHandler): StepHandlers { const subagentStore = useStore(); const stream = useRef(createStreamState()); + const receiptKeys = useRef(new Set()); + const clearPhaseReceipts = useCallback(() => { + if (receiptKeys.current.size === 0) return; + subagentStore.set(phaseReceipts, (current) => { + const next = new Map(current); + for (const key of receiptKeys.current) next.delete(key); + return next; + }); + receiptKeys.current.clear(); + }, [subagentStore]); + useEffect(() => clearPhaseReceipts, [clearPhaseReceipts]); /** Coalesces rapid-fire summarize delta renders into a single rAF frame */ const summarizeDeltaRaf = useRef(null); /** Coalesces per-token message/reasoning delta cache writes into one rAF frame. @@ -338,6 +350,16 @@ export function useStepHandler({ const stepHandler = useCallback( (stepEvent: StepEvent, submission: EventSubmission) => { const currentTime = Date.now(); + visitPhaseStamps(stepEvent, stream.current, (stepId, stamp) => { + receiptKeys.current.add(stepId); + const current = subagentStore.get(phaseReceipts); + const stamps = current.get(stepId); + if (stamps?.has(stamp)) return; + subagentStore.set( + phaseReceipts, + new Map(current).set(stepId, new Map(stamps).set(stamp, currentTime)), + ); + }); if (currentTime - lastAnnouncementTimeRef.current > MESSAGE_UPDATE_INTERVAL) { announcePolite({ message: 'composing', isStatus: true }); lastAnnouncementTimeRef.current = currentTime; @@ -345,7 +367,14 @@ export function useStepHandler({ const ctx: StepContext = { submission, getMessages, setMessages }; applyEffects(reduceStep(stream.current, stepEvent, ctx), ctx); }, - [getMessages, setMessages, announcePolite, applyEffects, lastAnnouncementTimeRef], + [ + getMessages, + setMessages, + announcePolite, + applyEffects, + lastAnnouncementTimeRef, + subagentStore, + ], ); /** Cancels a queued delta flush so it can't overwrite a terminal write: @@ -385,6 +414,7 @@ export function useStepHandler({ summarizeDeltaRaf.current = null; } cancelPendingDeltaFlush(); + clearPhaseReceipts(); resetStreamState(stream.current); closeParentSubagentStreams(); /** Unlike subagent atoms below, sandbox-starting flags are transient @@ -400,7 +430,7 @@ export function useStepHandler({ * persisted `subagent_content` takes over for historical messages * once the conversation is saved, and we prevent unbounded * atomFamily growth across multi-conversation sessions. */ - }, [cancelPendingDeltaFlush, closeParentSubagentStreams, resetSandboxAtoms]); + }, [cancelPendingDeltaFlush, clearPhaseReceipts, closeParentSubagentStreams, resetSandboxAtoms]); /** * Sync a message into the step handler's streaming copy.