From a9f0153c0f0142825412be142844546f2129bf02 Mon Sep 17 00:00:00 2001 From: Jabber Developer Date: Thu, 14 May 2026 03:50:12 +0000 Subject: [PATCH] fix(ai): prevent duplicate user message in AI JSON payload The user message was being added to session->history before calling _build_json_payload_from_list(), which independently appends the prompt to the JSON payload. This caused the same message to appear twice in the API request. Fix: Build JSON payload first, then add user message to history under the same lock to maintain atomicity. --- src/ai/ai_client.c | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/ai/ai_client.c b/src/ai/ai_client.c index e3d09823..320cc98f 100644 --- a/src/ai/ai_client.c +++ b/src/ai/ai_client.c @@ -1441,20 +1441,18 @@ _ai_request_thread(gpointer data) return NULL; } - /* Add user message to history FIRST (under lock) */ + /* Build JSON payload from history + prompt (under lock), then add user message to history */ + log_debug("[AI-THREAD] Building JSON payload..."); pthread_mutex_lock(&session->lock); + auto_gchar gchar* json_payload = _build_json_payload_from_list(local_model, session->history, prompt); + + /* Add user message to history now (it's in JSON but not yet in history) */ AIMessage* user_msg = g_new0(AIMessage, 1); user_msg->role = g_strdup("user"); user_msg->content = g_strdup(prompt); session->history = g_list_append(session->history, user_msg); pthread_mutex_unlock(&session->lock); log_debug("[AI-THREAD] Added user message to history"); - - /* Build JSON payload from local history copy (under lock) */ - log_debug("[AI-THREAD] Building JSON payload..."); - pthread_mutex_lock(&session->lock); - auto_gchar gchar* json_payload = _build_json_payload_from_list(local_model, session->history, prompt); - pthread_mutex_unlock(&session->lock); log_debug("[AI-THREAD] JSON payload: %s", json_payload); /* Build headers using shared helper */