From 7de790fbf236193191a33482793ee3ec5943d62d Mon Sep 17 00:00:00 2001
From: Marat Boshernitsan <maratb@nitsan.org>
Date: Tue, 3 Jun 2025 23:01:26 -0700
Subject: Fix several bugs in prompt history (#734)

Co-authored-by: Marat Boshernitsan <maratb@google.com>
---
 packages/cli/src/ui/App.tsx | 43 +++++++++++++++++++++++++++++--------------
 1 file changed, 29 insertions(+), 14 deletions(-)

(limited to 'packages/cli/src/ui/App.tsx')

diff --git a/packages/cli/src/ui/App.tsx b/packages/cli/src/ui/App.tsx
index 9ebefaa9..ddaf2f02 100644
--- a/packages/cli/src/ui/App.tsx
+++ b/packages/cli/src/ui/App.tsx
@@ -227,21 +227,36 @@ export const App = ({
 
   useEffect(() => {
     const fetchUserMessages = async () => {
-      const pastMessages = (await logger?.getPreviousUserMessages()) || [];
-      if (pastMessages.length > 0) {
-        setUserMessages(pastMessages.reverse());
-      } else {
-        setUserMessages(
-          history
-            .filter(
-              (item): item is HistoryItem & { type: 'user'; text: string } =>
-                item.type === 'user' &&
-                typeof item.text === 'string' &&
-                item.text.trim() !== '',
-            )
-            .map((item) => item.text),
-        );
+      const pastMessagesRaw = (await logger?.getPreviousUserMessages()) || []; // Newest first
+
+      const currentSessionUserMessages = history
+        .filter(
+          (item): item is HistoryItem & { type: 'user'; text: string } =>
+            item.type === 'user' &&
+            typeof item.text === 'string' &&
+            item.text.trim() !== '',
+        )
+        .map((item) => item.text)
+        .reverse(); // Newest first, to match pastMessagesRaw sorting
+
+      // Combine, with current session messages being more recent
+      const combinedMessages = [
+        ...currentSessionUserMessages,
+        ...pastMessagesRaw,
+      ];
+
+      // Deduplicate consecutive identical messages from the combined list (still newest first)
+      const deduplicatedMessages: string[] = [];
+      if (combinedMessages.length > 0) {
+        deduplicatedMessages.push(combinedMessages[0]); // Add the newest one unconditionally
+        for (let i = 1; i < combinedMessages.length; i++) {
+          if (combinedMessages[i] !== combinedMessages[i - 1]) {
+            deduplicatedMessages.push(combinedMessages[i]);
+          }
+        }
       }
+      // Reverse to oldest first for useInputHistory
+      setUserMessages(deduplicatedMessages.reverse());
     };
     fetchUserMessages();
   }, [history, logger]);
-- 
cgit v1.2.3

