refactor(shared): dedupe chat content text extraction

This commit is contained in:
Peter Steinberger
2026-02-15 17:21:36 +00:00
parent ac3db098ab
commit b74c3d80cc
4 changed files with 71 additions and 61 deletions

View File

@@ -27,6 +27,7 @@ import { callGateway } from "../../gateway/call.js";
import { logVerbose } from "../../globals.js";
import { formatTimeAgo } from "../../infra/format-time/format-relative.ts";
import { parseAgentSessionKey } from "../../routing/session-key.js";
import { extractTextFromChatContent } from "../../shared/chat-content.js";
import {
formatDurationCompact,
formatTokenUsageDisplay,
@@ -202,45 +203,15 @@ function buildSubagentsHelp() {
type ChatMessage = {
role?: unknown;
content?: unknown;
name?: unknown;
toolName?: unknown;
};
function normalizeMessageText(text: string) {
return text.replace(/\s+/g, " ").trim();
}
export function extractMessageText(message: ChatMessage): { role: string; text: string } | null {
const role = typeof message.role === "string" ? message.role : "";
const shouldSanitize = role === "assistant";
const content = message.content;
if (typeof content === "string") {
const normalized = normalizeMessageText(
shouldSanitize ? sanitizeTextContent(content) : content,
);
return normalized ? { role, text: normalized } : null;
}
if (!Array.isArray(content)) {
return null;
}
const chunks: string[] = [];
for (const block of content) {
if (!block || typeof block !== "object") {
continue;
}
if ((block as { type?: unknown }).type !== "text") {
continue;
}
const text = (block as { text?: unknown }).text;
if (typeof text === "string") {
const value = shouldSanitize ? sanitizeTextContent(text) : text;
if (value.trim()) {
chunks.push(value);
}
}
}
const joined = normalizeMessageText(chunks.join(" "));
return joined ? { role, text: joined } : null;
const text = extractTextFromChatContent(message.content, {
sanitizeText: shouldSanitize ? sanitizeTextContent : undefined,
});
return text ? { role, text } : null;
}
function formatLogLines(messages: ChatMessage[]) {