From 2308b59f135e4c2da11eabdf2306e55a5dd4e9fb Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Mon, 29 Jun 2026 02:21:24 -0500 Subject: [PATCH] refac --- src/lib/utils/index.ts | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/src/lib/utils/index.ts b/src/lib/utils/index.ts index 163acbc576..5a6eb64a36 100644 --- a/src/lib/utils/index.ts +++ b/src/lib/utils/index.ts @@ -254,6 +254,23 @@ export const sanitizeHistory = (history) => { } } + // Recover currentId before role reconstruction can make a malformed node + // look valid. + const currentMessage = history.messages?.[history.currentId]; + if (!currentMessage?.id || !currentMessage?.role) { + let latestLeafId = null; + let latestTimestamp = -1; + + for (const [id, message] of Object.entries(history.messages)) { + if (message.childrenIds.length === 0 && (message.timestamp ?? 0) > latestTimestamp) { + latestLeafId = id; + latestTimestamp = message.timestamp ?? 0; + } + } + + history.currentId = latestLeafId ?? Object.keys(history.messages)[0] ?? null; + } + // Reconstruct missing parentId and role for (const [id, message] of Object.entries(history.messages)) { // Well-formed: has role and explicit parentId (null is valid for root) @@ -280,20 +297,6 @@ export const sanitizeHistory = (history) => { for (const message of Object.values(history.messages)) { message.childrenIds = message.childrenIds.filter((childId) => history.messages[childId]); } - - // Recover currentId if it points to a missing or incomplete node - const currentMessage = history.messages?.[history.currentId]; - if (!currentMessage?.id || !currentMessage?.role) { - let latestLeafId = null; - let latestTimestamp = -1; - for (const [id, message] of Object.entries(history.messages)) { - if (message.childrenIds.length === 0 && (message.timestamp ?? 0) > latestTimestamp) { - latestLeafId = id; - latestTimestamp = message.timestamp ?? 0; - } - } - history.currentId = latestLeafId ?? Object.keys(history.messages)[0] ?? null; - } }; export const getGravatarURL = (email) => {