Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🧱 refactor: Split the Chat Step Reducer Into Stream Modules (#17105)
Marco Beretta510cf9efc95b
diff --git a/packages/chat/src/core/reducer.ts b/packages/chat/src/core/reducer.tsindex 89bdafba33..b8fa103de3 100644--- a/packages/chat/src/core/reducer.ts+++ b/packages/chat/src/core/reducer.ts@@ -1,33 +1,39 @@-import {- Constants,- StepTypes,- StepEvents,- ContentTypes,- getToolTimingDurations,-} from 'librechat-data-provider';-import type {- Agents,- TMessage,- EventSubmission,- PtcToolCallEvent,- SubagentUpdateEvent,- SandboxStartingEvent,- TMessageContentParts,-} from 'librechat-data-provider';+import { Constants, StepTypes, StepEvents } from 'librechat-data-provider';+import type { TMessage, TMessageContentParts } from 'librechat-data-provider';+import type { StepEvent, StepEffect, StepContext, StreamState } from './stream/state';import {getEditPrefix,applyAgentUpdate,applySummaryStep,applyMessageDelta,finalizeSummaries,- applyRunStepClosed,applyToolCallsStep,- applyToolCallDelta,applyReasoningDelta,applySummarizeDelta,applyToolCallCompleted,isSkillAuthoringToolCall,} from './steps';+import {+ ensureUserMessagePresent,+ getEventMessages,+ getResponseBaseMessages,+ mergeResponseMessage,+ shouldRemoveInitialResponse,+ shouldRemoveRegenerateResponse,+} from './stream/merge';+import {+ applyRunStepDelta,+ applyToolPreparation,+ applyToolCallsDispatched,+ applyRunStepClosedTiming,+} from './stream/timing';+import { toolTimingKey, resolveResponseId, bufferDelta } from './stream/state';+import { claimSubagentUpdate } from './stream/subagent';++export type { StepEvent, StepEffect, StepContext, StreamState } from './stream/state';+export { createStreamState, resetStreamState, subagentProgressKey } from './stream/state';+export { mergeResponseMessage, flushResponses, flushSummary } from './stream/merge';+export { syncStreamMessage } from './stream/subagent';/*** The step reducer behind `useStepHandler`: folds one agent step event into the response message@@ -41,370 +47,6 @@ import {* prefix. Nothing here splices content mid-stream.*/-export type StepEvent =- | { event: StepEvents.ON_RUN_STEP; data: Agents.RunStep }- | { event: StepEvents.ON_AGENT_UPDATE; data: Agents.AgentUpdate }- | { event: StepEvents.ON_MESSAGE_DELTA; data: Agents.MessageDeltaEvent }- | { event: StepEvents.ON_REASONING_DELTA; data: Agents.ReasoningDeltaEvent }- | { event: StepEvents.ON_RUN_STEP_DELTA; data: Agents.RunStepDeltaEvent }- | { event: StepEvents.ON_TOOL_CALLS_DISPATCHED; data: Agents.ToolCallsDispatchedEvent }- | { event: StepEvents.ON_TOOL_PREPARATION; data: Agents.ToolPreparationMarker }- | { event: StepEvents.ON_RUN_STEP_COMPLETED; data: { result: Agents.ToolEndEvent } }- | { event: StepEvents.ON_RUN_STEP_CLOSED; data: Agents.RunStepClosedEvent }- | { event: StepEvents.ON_SUMMARIZE_START; data: Agents.SummarizeStartEvent }- | { event: StepEvents.ON_SUMMARIZE_DELTA; data: Agents.SummarizeDeltaEvent }- | { event: StepEvents.ON_SUMMARIZE_COMPLETE; data: Agents.SummarizeCompleteEvent }- | { event: StepEvents.ON_SUBAGENT_UPDATE; data: SubagentUpdateEvent }- | { event: StepEvents.ON_SANDBOX_STARTING; data: SandboxStartingEvent }- | { event: StepEvents.ON_PTC_TOOL_CALL; data: PtcToolCallEvent };--/**- * Side channels of one step event, in the order the event produced them.- *- * `flush` and `summary` ask the binding to merge the response into the list later (deltas are- * coalesced per frame); `messages` is the list the event read, which the flush merges onto.- */-export type StepEffect =- | { type: 'flush'; messageId: string; messages: TMessage[] }- | { type: 'summary'; messageId: string; messages: TMessage[] }- | { type: 'announce'; message: 'summarize_started' | 'summarize_completed' | 'summarize_failed' }- | { type: 'sandbox-starting'; toolCallId: string }- | { type: 'sandbox-settled'; toolCallId?: string }- | { type: 'skill-authored' }- | { type: 'ptc'; event: PtcToolCallEvent; parentMessageId: string }- | { type: 'subagent'; invocationKey: string; events: SubagentUpdateEvent[] }- | { type: 'subagent-index'; conversationId: string };--/** The message list the reducer reads and writes; the React Query cache in the app. */-export type StepContext = {- submission: EventSubmission;- getMessages: () => TMessage[] | undefined;- setMessages: (messages: TMessage[]) => void;-};--type PendingSubagent = { parentMessageId: string; events: SubagentUpdateEvent[] };--/** Per-run bookkeeping. Mutable by design: deltas arrive per token. */-export type StreamState = {- /** Authoritative streaming copy of each response, ahead of the cache while a flush is queued. */- messages: Map<string, TMessage>;- steps: Map<string, Agents.RunStep>;- toolCallIds: Map<string, string | undefined>;- firstFragmentByCall: Map<string, number>;- firstFragmentByStep: Map<string, number>;- dispatchedByCall: Map<string, number>;- completedByCall: Map<string, number>;- /** Deltas that arrived before their run step, replayed when it lands. */- pendingDeltas: Map<string, StepEvent[]>;- /**- * `subagentRunId` to one concrete parent content-part occurrence. Provider ids repeat across- * and within messages, so the claim is by occurrence, oldest first.- */- subagentInvocations: Map<string, string>;- claimedInvocations: Set<string>;- /** Subagent envelopes that arrived before their parent tool call was in `messages`. */- pendingSubagents: Map<string, PendingSubagent>;-};--export function createStreamState(): StreamState {- return {- messages: new Map(),- steps: new Map(),- toolCallIds: new Map(),- firstFragmentByCall: new Map(),- firstFragmentByStep: new Map(),- dispatchedByCall: new Map(),- completedByCall: new Map(),- pendingDeltas: new Map(),- subagentInvocations: new Map(),- claimedInvocations: new Set(),- pendingSubagents: new Map(),- };-}--export function resetStreamState(state: StreamState): void {- state.messages.clear();- state.steps.clear();- state.toolCallIds.clear();- state.firstFragmentByCall.clear();- state.firstFragmentByStep.clear();- state.dispatchedByCall.clear();- state.completedByCall.clear();- state.pendingDeltas.clear();- state.subagentInvocations.clear();- state.claimedInvocations.clear();- state.pendingSubagents.clear();-}--/** Atom identity of one subagent tool-call content-part occurrence. */-export const subagentProgressKey = (- parentMessageId: string,- toolCallId: string,- partIndex: number,-): string => `${parentMessageId}\u0000${toolCallId}\u0000${partIndex}`;--const toolTimingKey = (stepId: string, callId: string) => `${stepId}\u0000${callId}`;--const isValidTime = (at: unknown): at is number =>- typeof at === 'number' && Number.isFinite(at) && at >= 0;--const getCurrentMessages = (ctx: StepContext, messages: TMessage[]): TMessage[] => {- const freshMessages = ctx.getMessages();- return freshMessages && freshMessages.length >= messages.length ? freshMessages : messages;-};--const getEventMessages = (ctx: StepContext, messages: TMessage[]): TMessage[] =>- ctx.submission.isRegenerate ? messages : getCurrentMessages(ctx, messages);--const getRegenerateResponseIds = (submission: EventSubmission, responseMessageId: string) => {- const ids = new Set<string>();- const addId = (id?: string | null) => {- if (!id) {- return;- }- ids.add(id);- ids.add(id.replace(/_+$/, ''));- };- addId(responseMessageId);- addId(submission.initialResponse?.messageId);- addId(submission.userMessage?.responseMessageId);- return ids;-};--const shouldRemoveRegenerateResponse = (- submission: EventSubmission,- message: TMessage,- responseMessageId: string,-) =>- submission.isRegenerate &&- !message.isCreatedByUser &&- /** A compaction's preliminary response is `${anchorId}_`. The ordinary regenerate alias set- * strips that suffix, but here the base ID is the assistant ANCHOR, not a response being- * replaced. Keep it so the summary remains its child instead of becoming an orphan root. */- (submission.compact !== true || message.messageId !== submission.userMessage.messageId) &&- getRegenerateResponseIds(submission, responseMessageId).has(message.messageId);--const shouldRemoveInitialResponse = (- submission: EventSubmission,- message: TMessage,- responseMessageId: string,-) => {- const initialResponseId = submission.initialResponse?.messageId;- return (- !submission.isRegenerate &&- !message.isCreatedByUser &&- initialResponseId != null &&- initialResponseId !== responseMessageId &&- message.messageId === initialResponseId &&- message.parentMessageId === submission.userMessage.messageId- );-};--const ensureUserMessagePresent = (- submission: EventSubmission,- candidateMessages: TMessage[],- responseMessageId: string,-): TMessage[] => {- const { userMessage } = submission;- if (- submission.isRegenerate ||- !userMessage?.messageId ||- candidateMessages.some((message) => message.messageId === userMessage.messageId)- ) {- return candidateMessages;- }-- /** Insert before the row's first CHILD as well as before the response row: abandoned responses- * from preempted attempts are children of this user message and may already sit in the list.- * Landing the parent after them orders children before their parent, which the message tree- * renders as phantom root branches (a folded thread). */- let insertIndex = candidateMessages.length;- for (let i = 0; i < candidateMessages.length; i++) {- const message = candidateMessages[i];- if (- message.messageId === responseMessageId ||- message.parentMessageId === userMessage.messageId- ) {- insertIndex = i;- break;- }- }- if (insertIndex >= candidateMessages.length) {- return [...candidateMessages, userMessage as TMessage];- }-- const nextMessages = [...candidateMessages];- nextMessages.splice(insertIndex, 0, userMessage as TMessage);- return nextMessages;-};--const getResponseBaseMessages = (- ctx: StepContext,- candidateMessages: TMessage[],- responseMessageId: string,- ensureUserMessage = false,-): TMessage[] => {- const { submission } = ctx;- const currentMessages = getEventMessages(ctx, candidateMessages);- if (!submission.isRegenerate) {- const nextMessages = currentMessages.filter(- (message) => !shouldRemoveInitialResponse(submission, message, responseMessageId),- );- return ensureUserMessage- ? ensureUserMessagePresent(submission, nextMessages, responseMessageId)- : nextMessages;- }- return currentMessages.filter(- (message) => !shouldRemoveRegenerateResponse(submission, message, responseMessageId),- );-};--/** Replaces (or appends) the response in the list, dropping the placeholder it supersedes. */-export function mergeResponseMessage(- ctx: StepContext,- candidateMessages: TMessage[],- updatedResponse: TMessage,- responseMessageId: string,- options?: { ensureUserMessage?: boolean },-): TMessage[] {- const currentMessages = getResponseBaseMessages(- ctx,- candidateMessages,- responseMessageId,- options?.ensureUserMessage === true,- );- const hasResponseMessage = currentMessages.some((msg) => msg.messageId === responseMessageId);- return hasResponseMessage- ? currentMessages.map((msg) => (msg.messageId === responseMessageId ? updatedResponse : msg))- : [...currentMessages, updatedResponse];-}--/** Writes the coalesced delta state of each response, merging onto the list the event read. */-export function flushResponses(- state: StreamState,- ctx: StepContext,- messageIds: Iterable<string>,- messages: TMessage[],-): void {- let candidate = messages;- for (const id of messageIds) {- const latest = state.messages.get(id);- if (!latest) {- continue;- }- candidate = mergeResponseMessage(ctx, candidate, latest, id, { ensureUserMessage: true });- ctx.setMessages(candidate);- }-}--/** Writes the coalesced summarize-delta state of one response. */-export function flushSummary(- state: StreamState,- ctx: StepContext,- messageId: string,- messages: TMessage[],-): void {- const latest = state.messages.get(messageId);- if (!latest) {- return;- }- const currentMessages = ctx.submission.isRegenerate ? messages : ctx.getMessages() || [];- ctx.setMessages(mergeResponseMessage(ctx, currentMessages, latest, messageId));-}--const resolveSubagentInvocationKey = (- state: StreamState,- payload: SubagentUpdateEvent,- parentMessageId: string,-): string | undefined => {- const cached = state.subagentInvocations.get(payload.subagentRunId);- if (cached != null) return cached;- if (parentMessageId === '') return undefined;-- /** `runId` names the expected parent message. Until it arrives, buffer instead of claiming a- * same-ID call from another parallel response; the claim is permanent once made. */- const content = state.messages.get(parentMessageId)?.content;- if (!Array.isArray(content)) return undefined;- for (let i = 0; i < content.length; i++) {- const part = content[i];- if (part?.type !== ContentTypes.TOOL_CALL) continue;- const tc = (part as { [ContentTypes.TOOL_CALL]?: { id?: string; name?: string } })[- ContentTypes.TOOL_CALL- ];- if (- tc?.name === Constants.SUBAGENT &&- tc.id &&- (payload.parentToolCallId == null || tc.id === payload.parentToolCallId) &&- !state.claimedInvocations.has(subagentProgressKey(parentMessageId, tc.id, i))- ) {- const invocationKey = subagentProgressKey(parentMessageId, tc.id, i);- state.subagentInvocations.set(payload.subagentRunId, invocationKey);- state.claimedInvocations.add(invocationKey);- return invocationKey;- }- }- return undefined;-};--/**- * Routes a subagent envelope to its parent invocation, buffering it until the parent tool call- * is known and releasing the buffer, in arrival order, once it is.- */-function claimSubagentUpdate(- state: StreamState,- payload: SubagentUpdateEvent,- parentMessageId: string,-): StepEffect[] {- const invocationKey = resolveSubagentInvocationKey(state, payload, parentMessageId);- const pending = state.pendingSubagents.get(payload.subagentRunId);-- if (!invocationKey) {- const buffer = pending ?? { parentMessageId, events: [] };- buffer.events.push(payload);- state.pendingSubagents.set(payload.subagentRunId, buffer);- return [];- }-- if (pending && pending.events.length > 0) {- state.pendingSubagents.delete(payload.subagentRunId);- }- const events = pending ? [...pending.events, payload] : [payload];- return [{ type: 'subagent', invocationKey, events }];-}--/**- * Seeds the streaming copy of a message from a sync snapshot, so later deltas build on it, and- * releases subagent envelopes that were waiting for it.- */-export function syncStreamMessage(state: StreamState, message: TMessage): StepEffect[] {- if (!message?.messageId) return [];- state.messages.set(message.messageId, { ...message });- const effects: StepEffect[] = [];- const ready = [...state.pendingSubagents.entries()].filter(- ([, pending]) => pending.parentMessageId === message.messageId,- );- for (const [subagentRunId, pending] of ready) {- state.pendingSubagents.delete(subagentRunId);- for (const event of pending.events) {- effects.push(...claimSubagentUpdate(state, event, message.messageId));- }- }- return effects;-}--/** The response a step writes to; a preliminary id resolves to the submission's response. */-const resolveResponseId = (submission: EventSubmission, runId: string | undefined): string =>- runId === Constants.USE_PRELIM_RESPONSE_MESSAGE_ID- ? (submission.initialResponse?.messageId ?? '')- : (runId ?? '');--const bufferDelta = (state: StreamState, stepId: string, event: StepEvent) => {- const buffer = state.pendingDeltas.get(stepId) ?? [];- buffer.push(event);- state.pendingDeltas.set(stepId, buffer);-};--/** Folds one step event into `state` and the message list; returns its side channels in order. */export function reduceStep(state: StreamState, event: StepEvent, ctx: StepContext): StepEffect[] {const { submission } = ctx;const messages = getEventMessages(ctx, submission.messages ?? []);@@ -567,144 +209,17 @@ export function reduceStep(state: StreamState, event: StepEvent, ctx: StepContex}if (event.event === StepEvents.ON_TOOL_PREPARATION) {- const { id, index, toolCallId, observed_at: at } = event.data;- if (!id || !isValidTime(at)) return effects;- const runStep = state.steps.get(id);- const declaredCalls =- runStep?.stepDetails.type === StepTypes.TOOL_CALLS- ? runStep.stepDetails.tool_calls- : undefined;- const resolvedId =- toolCallId ?? (index === 0 && declaredCalls?.length === 1 ? declaredCalls[0]?.id : undefined);- if (resolvedId) {- const key = toolTimingKey(id, resolvedId);- state.firstFragmentByCall.set(key, Math.min(state.firstFragmentByCall.get(key) ?? at, at));- } else if (index === 0) {- state.firstFragmentByStep.set(id, Math.min(state.firstFragmentByStep.get(id) ?? at, at));- }- if (!runStep?.runId || (runStep.status && runStep.status !== 'in_progress')) return effects;- const responseId = resolveResponseId(submission, runStep.runId);- const response = state.messages.get(responseId);- const contentIndex = runStep.index + editPrefixOffset;- const part = response?.content?.[contentIndex];- if (- !response ||- part?.type !== ContentTypes.TOOL_CALL ||- part.tool_call.runStepStatus != null ||- (resolvedId && part.tool_call.id !== resolvedId)- ) {- return effects;- }- const content = [...(response.content ?? [])];- content[contentIndex] = {- ...part,- tool_call: {- ...part.tool_call,- toolPreparationStartedAt: Math.min(part.tool_call.toolPreparationStartedAt ?? at, at),- },- };- const updated = { ...response, content };- state.messages.set(responseId, updated);- merge(updated, responseId);+ applyToolPreparation({ state, data: event.data, ctx, merge, editPrefixOffset });return effects;}if (event.event === StepEvents.ON_RUN_STEP_DELTA) {- const runStepDelta = event.data;- const at = runStepDelta.observed_at;- if (typeof at === 'number' && Number.isFinite(at) && at >= 0) {- for (const chunk of runStepDelta.delta.tool_calls ?? []) {- if (chunk.id) {- const first =- chunk.index === 0 ? state.firstFragmentByStep.get(runStepDelta.id) : undefined;- const key = toolTimingKey(runStepDelta.id, chunk.id);- state.firstFragmentByCall.set(- key,- Math.min(state.firstFragmentByCall.get(key) ?? at, first ?? at, at),- );- if (first != null) state.firstFragmentByStep.delete(runStepDelta.id);- } else if (chunk.index === 0 && runStepDelta.delta.tool_calls?.length === 1) {- const declared = state.steps.get(runStepDelta.id)?.stepDetails;- const firstCallId =- declared?.type === StepTypes.TOOL_CALLS && declared.tool_calls?.length === 1- ? declared.tool_calls[0]?.id- : undefined;- if (firstCallId) {- const key = toolTimingKey(runStepDelta.id, firstCallId);- state.firstFragmentByCall.set(- key,- Math.min(state.firstFragmentByCall.get(key) ?? at, at),- );- } else {- state.firstFragmentByStep.set(- runStepDelta.id,- Math.min(state.firstFragmentByStep.get(runStepDelta.id) ?? at, at),- );- }- }- }- }- const runStep = state.steps.get(runStepDelta.id);- const responseMessageId = resolveResponseId(submission, runStep?.runId);- if (!runStep || !responseMessageId) {- bufferDelta(state, runStepDelta.id, event);- return effects;- }-- const response = state.messages.get(responseMessageId);- const updatedResponse =- response &&- applyToolCallDelta(- response,- runStep,- runStepDelta,- state.toolCallIds.get(runStepDelta.id) ?? '',- editPrefixOffset,- (callId, index) => ({- toolPreparationStartedAt:- state.firstFragmentByCall.get(toolTimingKey(runStepDelta.id, callId)) ??- (index === 0 ? state.firstFragmentByStep.get(runStepDelta.id) : undefined),- toolDispatchedAt: state.dispatchedByCall.get(toolTimingKey(runStepDelta.id, callId)),- }),- );- if (updatedResponse) {- state.messages.set(responseMessageId, updatedResponse);- merge(updatedResponse, responseMessageId);- }+ applyRunStepDelta({ state, data: event.data, ctx, merge, editPrefixOffset, event });return effects;}if (event.event === StepEvents.ON_TOOL_CALLS_DISPATCHED) {- const { dispatched_at: at, toolCalls } = event.data;- if (!isValidTime(at)) return effects;- for (const call of toolCalls ?? []) {- if (!call.id || !call.stepId) continue;- const key = toolTimingKey(call.stepId, call.id);- const dispatchedAt = Math.min(state.dispatchedByCall.get(key) ?? at, at);- state.dispatchedByCall.set(key, dispatchedAt);- const runStep = state.steps.get(call.stepId);- if (!runStep?.runId) continue;- const responseId = resolveResponseId(submission, runStep.runId);- const response = state.messages.get(responseId);- const index = runStep.index + editPrefixOffset;- const part = response?.content?.[index];- if (- !response ||- part?.type !== ContentTypes.TOOL_CALL ||- part.tool_call.id !== call.id ||- part.tool_call.runStepStatus != null- ) {- continue;- }- const content = [...(response.content ?? [])];- content[index] = {- ...part,- tool_call: { ...part.tool_call, toolDispatchedAt: dispatchedAt },- };- const updated = { ...response, content };- state.messages.set(responseId, updated);- merge(updated, responseId);- }+ applyToolCallsDispatched({ state, data: event.data, ctx, merge, editPrefixOffset });return effects;}@@ -742,43 +257,7 @@ export function reduceStep(state: StreamState, event: StepEvent, ctx: StepContex}if (event.event === StepEvents.ON_RUN_STEP_CLOSED) {- const closed = event.data;- const runStep = state.steps.get(closed.id);- const responseMessageId = resolveResponseId(submission, runStep?.runId);- /** A closure for a step this client never saw opened happens on reconnect, where the replay- * may start after the step was created; it is not an error worth surfacing. */- if (!runStep || !responseMessageId) {- return effects;- }- const response = state.messages.get(responseMessageId);- const existing = response?.content?.[runStep.index + editPrefixOffset];- if (!response || existing?.type !== ContentTypes.TOOL_CALL || !existing.tool_call) {- return effects;- }- const existingToolCall = existing.tool_call;- const key = toolTimingKey(closed.id, existingToolCall.id ?? '');- const singleCallStep =- runStep.stepDetails.type === StepTypes.TOOL_CALLS &&- (runStep.stepDetails.tool_calls?.length ?? 0) <= 1;- const observedAt = Math.min(- state.firstFragmentByCall.get(key) ?? Infinity,- existingToolCall.toolPreparationStartedAt ?? Infinity,- singleCallStep ? (state.firstFragmentByStep.get(closed.id) ?? Infinity) : Infinity,- );- const timing = getToolTimingDurations({- observedAt: Number.isFinite(observedAt) ? observedAt : undefined,- dispatchedAt: existingToolCall.toolDispatchedAt ?? state.dispatchedByCall.get(key),- completedAt: state.completedByCall.get(key),- });- state.firstFragmentByCall.delete(key);- state.firstFragmentByStep.delete(closed.id);- state.dispatchedByCall.delete(key);- state.completedByCall.delete(key);- const updatedResponse = applyRunStepClosed(response, runStep, closed, editPrefixOffset, timing);- if (updatedResponse) {- state.messages.set(responseMessageId, updatedResponse);- merge(updatedResponse, responseMessageId);- }+ applyRunStepClosedTiming({ state, data: event.data, ctx, merge, editPrefixOffset });return effects;}diff --git a/packages/chat/src/core/stream/__tests__/merge.spec.ts b/packages/chat/src/core/stream/__tests__/merge.spec.tsnew file mode 100644index 0000000000..ea257c072c--- /dev/null+++ b/packages/chat/src/core/stream/__tests__/merge.spec.ts@@ -0,0 +1,45 @@+import type { TMessage, EventSubmission } from 'librechat-data-provider';+import type { StepContext } from '../state';+import { ensureUserMessagePresent, mergeResponseMessage } from '../merge';++const msg = (fields: Partial<TMessage>): TMessage => ({ text: '', ...fields }) as TMessage;++const makeCtx = (submission: Partial<EventSubmission>, list: TMessage[] = []): StepContext => ({+ submission: submission as EventSubmission,+ getMessages: () => list,+ setMessages: () => undefined,+});++describe('stream merge', () => {+ const userMessage = msg({ messageId: 'u1', isCreatedByUser: true });++ it('inserts the user message before the first child of it', () => {+ const child = msg({ messageId: 'old', parentMessageId: 'u1' });+ const submission = { userMessage } as EventSubmission;+ const result = ensureUserMessagePresent(submission, [child], 'r1');+ expect(result.map((m) => m.messageId)).toEqual(['u1', 'old']);+ });++ it('leaves the list alone for a regenerate', () => {+ const list = [msg({ messageId: 'a' })];+ const submission = { userMessage, isRegenerate: true } as EventSubmission;+ expect(ensureUserMessagePresent(submission, list, 'r1')).toBe(list);+ });++ it('replaces the placeholder response with the updated response', () => {+ const placeholder = msg({ messageId: 'p', parentMessageId: 'u1' });+ const ctx = makeCtx({ userMessage, initialResponse: placeholder, messages: [] });+ const updated = msg({ messageId: 'r1', parentMessageId: 'u1' });+ const result = mergeResponseMessage(ctx, [userMessage, placeholder], updated, 'r1');+ expect(result.map((m) => m.messageId)).toEqual(['u1', 'r1']);+ });++ it('drops the regenerated response and appends the new one', () => {+ const old = msg({ messageId: 'r1' });+ const ctx = makeCtx({ userMessage, isRegenerate: true });+ const updated = msg({ messageId: 'r1', text: 'new' });+ const result = mergeResponseMessage(ctx, [userMessage, old], updated, 'r1');+ expect(result.find((m) => m.messageId === 'r1')?.text).toBe('new');+ expect(result).toHaveLength(2);+ });+});diff --git a/packages/chat/src/core/stream/merge.ts b/packages/chat/src/core/stream/merge.tsnew file mode 100644index 0000000000..8c4af94480--- /dev/null+++ b/packages/chat/src/core/stream/merge.ts@@ -0,0 +1,166 @@+import type { TMessage, EventSubmission } from 'librechat-data-provider';+import type { StepContext, StreamState } from './state';++const getCurrentMessages = (ctx: StepContext, messages: TMessage[]): TMessage[] => {+ const freshMessages = ctx.getMessages();+ return freshMessages && freshMessages.length >= messages.length ? freshMessages : messages;+};++export const getEventMessages = (ctx: StepContext, messages: TMessage[]): TMessage[] =>+ ctx.submission.isRegenerate ? messages : getCurrentMessages(ctx, messages);++const getRegenerateResponseIds = (submission: EventSubmission, responseMessageId: string) => {+ const ids = new Set<string>();+ const addId = (id?: string | null) => {+ if (!id) {+ return;+ }+ ids.add(id);+ ids.add(id.replace(/_+$/, ''));+ };+ addId(responseMessageId);+ addId(submission.initialResponse?.messageId);+ addId(submission.userMessage?.responseMessageId);+ return ids;+};++export const shouldRemoveRegenerateResponse = (+ submission: EventSubmission,+ message: TMessage,+ responseMessageId: string,+): boolean =>+ submission.isRegenerate === true &&+ !message.isCreatedByUser &&+ /** A compaction's preliminary response is `${anchorId}_`. The ordinary regenerate alias set+ * strips that suffix, but here the base ID is the assistant ANCHOR, not a response being+ * replaced. Keep it so the summary remains its child instead of becoming an orphan root. */+ (submission.compact !== true || message.messageId !== submission.userMessage.messageId) &&+ getRegenerateResponseIds(submission, responseMessageId).has(message.messageId);++export const shouldRemoveInitialResponse = (+ submission: EventSubmission,+ message: TMessage,+ responseMessageId: string,+): boolean => {+ const initialResponseId = submission.initialResponse?.messageId;+ return (+ !submission.isRegenerate &&+ !message.isCreatedByUser &&+ initialResponseId != null &&+ initialResponseId !== responseMessageId &&+ message.messageId === initialResponseId &&+ message.parentMessageId === submission.userMessage.messageId+ );+};++export const ensureUserMessagePresent = (+ submission: EventSubmission,+ candidateMessages: TMessage[],+ responseMessageId: string,+): TMessage[] => {+ const { userMessage } = submission;+ if (+ submission.isRegenerate ||+ !userMessage?.messageId ||+ candidateMessages.some((message) => message.messageId === userMessage.messageId)+ ) {+ return candidateMessages;+ }++ /** Insert before the row's first CHILD as well as before the response row: abandoned responses+ * from preempted attempts are children of this user message and may already sit in the list.+ * Landing the parent after them orders children before their parent, which the message tree+ * renders as phantom root branches (a folded thread). */+ let insertIndex = candidateMessages.length;+ for (let i = 0; i < candidateMessages.length; i++) {+ const message = candidateMessages[i];+ if (+ message.messageId === responseMessageId ||+ message.parentMessageId === userMessage.messageId+ ) {+ insertIndex = i;+ break;+ }+ }+ if (insertIndex >= candidateMessages.length) {+ return [...candidateMessages, userMessage as TMessage];+ }++ const nextMessages = [...candidateMessages];+ nextMessages.splice(insertIndex, 0, userMessage as TMessage);+ return nextMessages;+};++export const getResponseBaseMessages = (+ ctx: StepContext,+ candidateMessages: TMessage[],+ responseMessageId: string,+ ensureUserMessage = false,+): TMessage[] => {+ const { submission } = ctx;+ const currentMessages = getEventMessages(ctx, candidateMessages);+ if (!submission.isRegenerate) {+ const nextMessages = currentMessages.filter(+ (message) => !shouldRemoveInitialResponse(submission, message, responseMessageId),+ );+ return ensureUserMessage+ ? ensureUserMessagePresent(submission, nextMessages, responseMessageId)+ : nextMessages;+ }+ return currentMessages.filter(+ (message) => !shouldRemoveRegenerateResponse(submission, message, responseMessageId),+ );+};++/** Replaces (or appends) the response in the list, dropping the placeholder it supersedes. */+export function mergeResponseMessage(+ ctx: StepContext,+ candidateMessages: TMessage[],+ updatedResponse: TMessage,+ responseMessageId: string,+ options?: { ensureUserMessage?: boolean },+): TMessage[] {+ const currentMessages = getResponseBaseMessages(+ ctx,+ candidateMessages,+ responseMessageId,+ options?.ensureUserMessage === true,+ );+ const hasResponseMessage = currentMessages.some((msg) => msg.messageId === responseMessageId);+ return hasResponseMessage+ ? currentMessages.map((msg) => (msg.messageId === responseMessageId ? updatedResponse : msg))+ : [...currentMessages, updatedResponse];+}++/** Writes the coalesced delta state of each response, merging onto the list the event read. */+export function flushResponses(+ state: StreamState,+ ctx: StepContext,+ messageIds: Iterable<string>,+ messages: TMessage[],+): void {+ let candidate = messages;+ for (const id of messageIds) {+ const latest = state.messages.get(id);+ if (!latest) {+ continue;+ }+ candidate = mergeResponseMessage(ctx, candidate, latest, id, { ensureUserMessage: true });+ ctx.setMessages(candidate);+ }+}++/** Writes the coalesced summarize-delta state of one response. */+export function flushSummary(+ state: StreamState,+ ctx: StepContext,+ messageId: string,+ messages: TMessage[],+): void {+ const latest = state.messages.get(messageId);+ if (!latest) {+ return;+ }+ const currentMessages = ctx.submission.isRegenerate ? messages : ctx.getMessages() || [];+ ctx.setMessages(mergeResponseMessage(ctx, currentMessages, latest, messageId));+}diff --git a/packages/chat/src/core/stream/state.ts b/packages/chat/src/core/stream/state.tsnew file mode 100644index 0000000000..9dbeff04db--- /dev/null+++ b/packages/chat/src/core/stream/state.ts@@ -0,0 +1,132 @@+import { Constants } from 'librechat-data-provider';+import type {+ Agents,+ StepEvents,+ TMessage,+ EventSubmission,+ PtcToolCallEvent,+ SubagentUpdateEvent,+ SandboxStartingEvent,+} from 'librechat-data-provider';++export type StepEvent =+ | { event: StepEvents.ON_RUN_STEP; data: Agents.RunStep }+ | { event: StepEvents.ON_AGENT_UPDATE; data: Agents.AgentUpdate }+ | { event: StepEvents.ON_MESSAGE_DELTA; data: Agents.MessageDeltaEvent }+ | { event: StepEvents.ON_REASONING_DELTA; data: Agents.ReasoningDeltaEvent }+ | { event: StepEvents.ON_RUN_STEP_DELTA; data: Agents.RunStepDeltaEvent }+ | { event: StepEvents.ON_TOOL_CALLS_DISPATCHED; data: Agents.ToolCallsDispatchedEvent }+ | { event: StepEvents.ON_TOOL_PREPARATION; data: Agents.ToolPreparationMarker }+ | { event: StepEvents.ON_RUN_STEP_COMPLETED; data: { result: Agents.ToolEndEvent } }+ | { event: StepEvents.ON_RUN_STEP_CLOSED; data: Agents.RunStepClosedEvent }+ | { event: StepEvents.ON_SUMMARIZE_START; data: Agents.SummarizeStartEvent }+ | { event: StepEvents.ON_SUMMARIZE_DELTA; data: Agents.SummarizeDeltaEvent }+ | { event: StepEvents.ON_SUMMARIZE_COMPLETE; data: Agents.SummarizeCompleteEvent }+ | { event: StepEvents.ON_SUBAGENT_UPDATE; data: SubagentUpdateEvent }+ | { event: StepEvents.ON_SANDBOX_STARTING; data: SandboxStartingEvent }+ | { event: StepEvents.ON_PTC_TOOL_CALL; data: PtcToolCallEvent };++/**+ * Side channels of one step event, in the order the event produced them.+ *+ * `flush` and `summary` ask the binding to merge the response into the list later (deltas are+ * coalesced per frame); `messages` is the list the event read, which the flush merges onto.+ */+export type StepEffect =+ | { type: 'flush'; messageId: string; messages: TMessage[] }+ | { type: 'summary'; messageId: string; messages: TMessage[] }+ | { type: 'announce'; message: 'summarize_started' | 'summarize_completed' | 'summarize_failed' }+ | { type: 'sandbox-starting'; toolCallId: string }+ | { type: 'sandbox-settled'; toolCallId?: string }+ | { type: 'skill-authored' }+ | { type: 'ptc'; event: PtcToolCallEvent; parentMessageId: string }+ | { type: 'subagent'; invocationKey: string; events: SubagentUpdateEvent[] }+ | { type: 'subagent-index'; conversationId: string };++/** The message list the reducer reads and writes; the React Query cache in the app. */+export type StepContext = {+ submission: EventSubmission;+ getMessages: () => TMessage[] | undefined;+ setMessages: (messages: TMessage[]) => void;+};++type PendingSubagent = { parentMessageId: string; events: SubagentUpdateEvent[] };++/** Per-run bookkeeping. Mutable by design: deltas arrive per token. */+export type StreamState = {+ /** Authoritative streaming copy of each response, ahead of the cache while a flush is queued. */+ messages: Map<string, TMessage>;+ steps: Map<string, Agents.RunStep>;+ toolCallIds: Map<string, string | undefined>;+ firstFragmentByCall: Map<string, number>;+ firstFragmentByStep: Map<string, number>;+ dispatchedByCall: Map<string, number>;+ completedByCall: Map<string, number>;+ /** Deltas that arrived before their run step, replayed when it lands. */+ pendingDeltas: Map<string, StepEvent[]>;+ /**+ * `subagentRunId` to one concrete parent content-part occurrence. Provider ids repeat across+ * and within messages, so the claim is by occurrence, oldest first.+ */+ subagentInvocations: Map<string, string>;+ claimedInvocations: Set<string>;+ /** Subagent envelopes that arrived before their parent tool call was in `messages`. */+ pendingSubagents: Map<string, PendingSubagent>;+};++export function createStreamState(): StreamState {+ return {+ messages: new Map(),+ steps: new Map(),+ toolCallIds: new Map(),+ firstFragmentByCall: new Map(),+ firstFragmentByStep: new Map(),+ dispatchedByCall: new Map(),+ completedByCall: new Map(),+ pendingDeltas: new Map(),+ subagentInvocations: new Map(),+ claimedInvocations: new Set(),+ pendingSubagents: new Map(),+ };+}++export function resetStreamState(state: StreamState): void {+ state.messages.clear();+ state.steps.clear();+ state.toolCallIds.clear();+ state.firstFragmentByCall.clear();+ state.firstFragmentByStep.clear();+ state.dispatchedByCall.clear();+ state.completedByCall.clear();+ state.pendingDeltas.clear();+ state.subagentInvocations.clear();+ state.claimedInvocations.clear();+ state.pendingSubagents.clear();+}++/** Atom identity of one subagent tool-call content-part occurrence. */+export const subagentProgressKey = (+ parentMessageId: string,+ toolCallId: string,+ partIndex: number,+): string => `${parentMessageId}\u0000${toolCallId}\u0000${partIndex}`;++export const toolTimingKey = (stepId: string, callId: string) => `${stepId}\u0000${callId}`;++export const isValidTime = (at: unknown): at is number =>+ typeof at === 'number' && Number.isFinite(at) && at >= 0;++/** The response a step writes to; a preliminary id resolves to the submission's response. */+export const resolveResponseId = (+ submission: EventSubmission,+ runId: string | undefined,+): string =>+ runId === Constants.USE_PRELIM_RESPONSE_MESSAGE_ID+ ? (submission.initialResponse?.messageId ?? '')+ : (runId ?? '');++export const bufferDelta = (state: StreamState, stepId: string, event: StepEvent): void => {+ const buffer = state.pendingDeltas.get(stepId) ?? [];+ buffer.push(event);+ state.pendingDeltas.set(stepId, buffer);+};diff --git a/packages/chat/src/core/stream/subagent.ts b/packages/chat/src/core/stream/subagent.tsnew file mode 100644index 0000000000..951a4853dd--- /dev/null+++ b/packages/chat/src/core/stream/subagent.ts@@ -0,0 +1,84 @@+import { Constants, ContentTypes } from 'librechat-data-provider';+import type { TMessage, SubagentUpdateEvent } from 'librechat-data-provider';+import type { StreamState, StepEffect } from './state';+import { subagentProgressKey } from './state';++const resolveSubagentInvocationKey = (+ state: StreamState,+ payload: SubagentUpdateEvent,+ parentMessageId: string,+): string | undefined => {+ const cached = state.subagentInvocations.get(payload.subagentRunId);+ if (cached != null) return cached;+ if (parentMessageId === '') return undefined;++ /** `runId` names the expected parent message. Until it arrives, buffer instead of claiming a+ * same-ID call from another parallel response; the claim is permanent once made. */+ const content = state.messages.get(parentMessageId)?.content;+ if (!Array.isArray(content)) return undefined;+ for (let i = 0; i < content.length; i++) {+ const part = content[i];+ if (part?.type !== ContentTypes.TOOL_CALL) continue;+ const tc = (part as { [ContentTypes.TOOL_CALL]?: { id?: string; name?: string } })[+ ContentTypes.TOOL_CALL+ ];+ if (+ tc?.name === Constants.SUBAGENT &&+ tc.id &&+ (payload.parentToolCallId == null || tc.id === payload.parentToolCallId) &&+ !state.claimedInvocations.has(subagentProgressKey(parentMessageId, tc.id, i))+ ) {+ const invocationKey = subagentProgressKey(parentMessageId, tc.id, i);+ state.subagentInvocations.set(payload.subagentRunId, invocationKey);+ state.claimedInvocations.add(invocationKey);+ return invocationKey;+ }+ }+ return undefined;+};++/**+ * Routes a subagent envelope to its parent invocation, buffering it until the parent tool call+ * is known and releasing the buffer, in arrival order, once it is.+ */+export function claimSubagentUpdate(+ state: StreamState,+ payload: SubagentUpdateEvent,+ parentMessageId: string,+): StepEffect[] {+ const invocationKey = resolveSubagentInvocationKey(state, payload, parentMessageId);+ const pending = state.pendingSubagents.get(payload.subagentRunId);++ if (!invocationKey) {+ const buffer = pending ?? { parentMessageId, events: [] };+ buffer.events.push(payload);+ state.pendingSubagents.set(payload.subagentRunId, buffer);+ return [];+ }++ if (pending && pending.events.length > 0) {+ state.pendingSubagents.delete(payload.subagentRunId);+ }+ const events = pending ? [...pending.events, payload] : [payload];+ return [{ type: 'subagent', invocationKey, events }];+}++/**+ * Seeds the streaming copy of a message from a sync snapshot, so later deltas build on it, and+ * releases subagent envelopes that were waiting for it.+ */+export function syncStreamMessage(state: StreamState, message: TMessage): StepEffect[] {+ if (!message?.messageId) return [];+ state.messages.set(message.messageId, { ...message });+ const effects: StepEffect[] = [];+ const ready = [...state.pendingSubagents.entries()].filter(+ ([, pending]) => pending.parentMessageId === message.messageId,+ );+ for (const [subagentRunId, pending] of ready) {+ state.pendingSubagents.delete(subagentRunId);+ for (const event of pending.events) {+ effects.push(...claimSubagentUpdate(state, event, message.messageId));+ }+ }+ return effects;+}diff --git a/packages/chat/src/core/stream/timing.ts b/packages/chat/src/core/stream/timing.tsnew file mode 100644index 0000000000..4434b73d45--- /dev/null+++ b/packages/chat/src/core/stream/timing.ts@@ -0,0 +1,222 @@+import { StepTypes, ContentTypes, getToolTimingDurations } from 'librechat-data-provider';+import type { Agents, TMessage } from 'librechat-data-provider';+import type { StepEvent, StepContext, StreamState } from './state';+import { toolTimingKey, isValidTime, resolveResponseId, bufferDelta } from './state';+import { applyToolCallDelta, applyRunStepClosed } from '../steps';++/** Writes `updated` into the list as the response `responseMessageId`. */+export type MergeResponse = (updated: TMessage, responseMessageId: string) => void;++type TimingArgs<T> = {+ state: StreamState;+ data: T;+ ctx: StepContext;+ merge: MergeResponse;+ editPrefixOffset: number;+};++export function applyToolPreparation({+ state,+ data,+ ctx,+ merge,+ editPrefixOffset,+}: TimingArgs<Agents.ToolPreparationMarker>): void {+ const { submission } = ctx;+ const { id, index, toolCallId, observed_at: at } = data;+ if (!id || !isValidTime(at)) return;+ const runStep = state.steps.get(id);+ const declaredCalls =+ runStep?.stepDetails.type === StepTypes.TOOL_CALLS ? runStep.stepDetails.tool_calls : undefined;+ const resolvedId =+ toolCallId ?? (index === 0 && declaredCalls?.length === 1 ? declaredCalls[0]?.id : undefined);+ if (resolvedId) {+ const key = toolTimingKey(id, resolvedId);+ state.firstFragmentByCall.set(key, Math.min(state.firstFragmentByCall.get(key) ?? at, at));+ } else if (index === 0) {+ state.firstFragmentByStep.set(id, Math.min(state.firstFragmentByStep.get(id) ?? at, at));+ }+ if (!runStep?.runId || (runStep.status && runStep.status !== 'in_progress')) return;+ const responseId = resolveResponseId(submission, runStep.runId);+ const response = state.messages.get(responseId);+ const contentIndex = runStep.index + editPrefixOffset;+ const part = response?.content?.[contentIndex];+ if (+ !response ||+ part?.type !== ContentTypes.TOOL_CALL ||+ part.tool_call.runStepStatus != null ||+ (resolvedId && part.tool_call.id !== resolvedId)+ ) {+ return;+ }+ const content = [...(response.content ?? [])];+ content[contentIndex] = {+ ...part,+ tool_call: {+ ...part.tool_call,+ toolPreparationStartedAt: Math.min(part.tool_call.toolPreparationStartedAt ?? at, at),+ },+ };+ const updated = { ...response, content };+ state.messages.set(responseId, updated);+ merge(updated, responseId);+}++export function applyRunStepDelta({+ state,+ data,+ ctx,+ merge,+ editPrefixOffset,+ event,+}: TimingArgs<Agents.RunStepDeltaEvent> & { event: StepEvent }): void {+ const { submission } = ctx;+ const runStepDelta = data;+ const at = runStepDelta.observed_at;+ if (typeof at === 'number' && Number.isFinite(at) && at >= 0) {+ for (const chunk of runStepDelta.delta.tool_calls ?? []) {+ if (chunk.id) {+ const first =+ chunk.index === 0 ? state.firstFragmentByStep.get(runStepDelta.id) : undefined;+ const key = toolTimingKey(runStepDelta.id, chunk.id);+ state.firstFragmentByCall.set(+ key,+ Math.min(state.firstFragmentByCall.get(key) ?? at, first ?? at, at),+ );+ if (first != null) state.firstFragmentByStep.delete(runStepDelta.id);+ } else if (chunk.index === 0 && runStepDelta.delta.tool_calls?.length === 1) {+ const declared = state.steps.get(runStepDelta.id)?.stepDetails;+ const firstCallId =+ declared?.type === StepTypes.TOOL_CALLS && declared.tool_calls?.length === 1+ ? declared.tool_calls[0]?.id+ : undefined;+ if (firstCallId) {+ const key = toolTimingKey(runStepDelta.id, firstCallId);+ state.firstFragmentByCall.set(+ key,+ Math.min(state.firstFragmentByCall.get(key) ?? at, at),+ );+ } else {+ state.firstFragmentByStep.set(+ runStepDelta.id,+ Math.min(state.firstFragmentByStep.get(runStepDelta.id) ?? at, at),+ );+ }+ }+ }+ }+ const runStep = state.steps.get(runStepDelta.id);+ const responseMessageId = resolveResponseId(submission, runStep?.runId);+ if (!runStep || !responseMessageId) {+ bufferDelta(state, runStepDelta.id, event);+ return;+ }++ const response = state.messages.get(responseMessageId);+ const updatedResponse =+ response &&+ applyToolCallDelta(+ response,+ runStep,+ runStepDelta,+ state.toolCallIds.get(runStepDelta.id) ?? '',+ editPrefixOffset,+ (callId, index) => ({+ toolPreparationStartedAt:+ state.firstFragmentByCall.get(toolTimingKey(runStepDelta.id, callId)) ??+ (index === 0 ? state.firstFragmentByStep.get(runStepDelta.id) : undefined),+ toolDispatchedAt: state.dispatchedByCall.get(toolTimingKey(runStepDelta.id, callId)),+ }),+ );+ if (updatedResponse) {+ state.messages.set(responseMessageId, updatedResponse);+ merge(updatedResponse, responseMessageId);+ }+}++export function applyToolCallsDispatched({+ state,+ data,+ ctx,+ merge,+ editPrefixOffset,+}: TimingArgs<Agents.ToolCallsDispatchedEvent>): void {+ const { submission } = ctx;+ const { dispatched_at: at, toolCalls } = data;+ if (!isValidTime(at)) return;+ for (const call of toolCalls ?? []) {+ if (!call.id || !call.stepId) continue;+ const key = toolTimingKey(call.stepId, call.id);+ const dispatchedAt = Math.min(state.dispatchedByCall.get(key) ?? at, at);+ state.dispatchedByCall.set(key, dispatchedAt);+ const runStep = state.steps.get(call.stepId);+ if (!runStep?.runId) continue;+ const responseId = resolveResponseId(submission, runStep.runId);+ const response = state.messages.get(responseId);+ const index = runStep.index + editPrefixOffset;+ const part = response?.content?.[index];+ if (+ !response ||+ part?.type !== ContentTypes.TOOL_CALL ||+ part.tool_call.id !== call.id ||+ part.tool_call.runStepStatus != null+ ) {+ continue;+ }+ const content = [...(response.content ?? [])];+ content[index] = {+ ...part,+ tool_call: { ...part.tool_call, toolDispatchedAt: dispatchedAt },+ };+ const updated = { ...response, content };+ state.messages.set(responseId, updated);+ merge(updated, responseId);+ }+}++export function applyRunStepClosedTiming({+ state,+ data,+ ctx,+ merge,+ editPrefixOffset,+}: TimingArgs<Agents.RunStepClosedEvent>): void {+ const { submission } = ctx;+ const closed = data;+ const runStep = state.steps.get(closed.id);+ const responseMessageId = resolveResponseId(submission, runStep?.runId);+ /** A closure for a step this client never saw opened happens on reconnect, where the replay+ * may start after the step was created; it is not an error worth surfacing. */+ if (!runStep || !responseMessageId) {+ return;+ }+ const response = state.messages.get(responseMessageId);+ const existing = response?.content?.[runStep.index + editPrefixOffset];+ if (!response || existing?.type !== ContentTypes.TOOL_CALL || !existing.tool_call) {+ return;+ }+ const existingToolCall = existing.tool_call;+ const key = toolTimingKey(closed.id, existingToolCall.id ?? '');+ const singleCallStep =+ runStep.stepDetails.type === StepTypes.TOOL_CALLS &&+ (runStep.stepDetails.tool_calls?.length ?? 0) <= 1;+ const observedAt = Math.min(+ state.firstFragmentByCall.get(key) ?? Infinity,+ existingToolCall.toolPreparationStartedAt ?? Infinity,+ singleCallStep ? (state.firstFragmentByStep.get(closed.id) ?? Infinity) : Infinity,+ );+ const timing = getToolTimingDurations({+ observedAt: Number.isFinite(observedAt) ? observedAt : undefined,+ dispatchedAt: existingToolCall.toolDispatchedAt ?? state.dispatchedByCall.get(key),+ completedAt: state.completedByCall.get(key),+ });+ state.firstFragmentByCall.delete(key);+ state.firstFragmentByStep.delete(closed.id);+ state.dispatchedByCall.delete(key);+ state.completedByCall.delete(key);+ const updatedResponse = applyRunStepClosed(response, runStep, closed, editPrefixOffset, timing);+ if (updatedResponse) {+ state.messages.set(responseMessageId, updatedResponse);+ merge(updatedResponse, responseMessageId);+ }+}