From 42f9737e592fdff1681c20ce5e6fc3e451530583 Mon Sep 17 00:00:00 2001 From: Peter Steinberger Date: Sat, 14 Mar 2026 00:22:58 +0000 Subject: [PATCH] refactor: share gateway chat text normalization --- src/gateway/server-chat.ts | 29 ++++++++++++----------------- 1 file changed, 12 insertions(+), 17 deletions(-) diff --git a/src/gateway/server-chat.ts b/src/gateway/server-chat.ts index b1a065684..21e252abc 100644 --- a/src/gateway/server-chat.ts +++ b/src/gateway/server-chat.ts @@ -390,12 +390,7 @@ export function createAgentEventHandler({ nodeSendToSession(sessionKey, "chat", payload); }; - const flushBufferedChatDeltaIfNeeded = ( - sessionKey: string, - clientRunId: string, - sourceRunId: string, - seq: number, - ) => { + const resolveBufferedChatTextState = (clientRunId: string, sourceRunId: string) => { const bufferedText = stripInlineDirectiveTagsForDisplay( chatRunState.buffers.get(clientRunId) ?? "", ).text.trim(); @@ -407,6 +402,16 @@ export function createAgentEventHandler({ const text = normalizedHeartbeatText.text.trim(); const shouldSuppressSilent = normalizedHeartbeatText.suppress || isSilentReplyText(text, SILENT_REPLY_TOKEN); + return { text, shouldSuppressSilent }; + }; + + const flushBufferedChatDeltaIfNeeded = ( + sessionKey: string, + clientRunId: string, + sourceRunId: string, + seq: number, + ) => { + const { text, shouldSuppressSilent } = resolveBufferedChatTextState(clientRunId, sourceRunId); const shouldSuppressSilentLeadFragment = isSilentReplyLeadFragment(text); const shouldSuppressHeartbeatStreaming = shouldHideHeartbeatChatOutput( clientRunId, @@ -453,17 +458,7 @@ export function createAgentEventHandler({ error?: unknown, stopReason?: string, ) => { - const bufferedText = stripInlineDirectiveTagsForDisplay( - chatRunState.buffers.get(clientRunId) ?? "", - ).text.trim(); - const normalizedHeartbeatText = normalizeHeartbeatChatFinalText({ - runId: clientRunId, - sourceRunId, - text: bufferedText, - }); - const text = normalizedHeartbeatText.text.trim(); - const shouldSuppressSilent = - normalizedHeartbeatText.suppress || isSilentReplyText(text, SILENT_REPLY_TOKEN); + const { text, shouldSuppressSilent } = resolveBufferedChatTextState(clientRunId, sourceRunId); // Flush any throttled delta so streaming clients receive the complete text // before the final event. The 150 ms throttle in emitChatDelta may have // suppressed the most recent chunk, leaving the client with stale text.