From 097c7215ab147c75f84f0d2ffe53c1802f4f4818 Mon Sep 17 00:00:00 2001 From: aakashb95 Date: Fri, 17 Jul 2026 18:06:42 +0530 Subject: [PATCH] fix(captain): preserve customer turn during response rewrite --- .../app/services/captain/assistant/agent_runner_service.rb | 7 +++++++ .../services/captain/assistant/session_capture_service.rb | 3 +++ 2 files changed, 10 insertions(+) diff --git a/enterprise/app/services/captain/assistant/agent_runner_service.rb b/enterprise/app/services/captain/assistant/agent_runner_service.rb index 059b11fc1..271e201d6 100644 --- a/enterprise/app/services/captain/assistant/agent_runner_service.rb +++ b/enterprise/app/services/captain/assistant/agent_runner_service.rb @@ -20,6 +20,7 @@ class Captain::Assistant::AgentRunnerService def generate_response(message_history: []) message_to_process, context = run_payload(message_history) @last_run_result = runner.run(message_to_process, context: context, max_turns: 10) + record_turn_start(@last_run_result) @last_run_result = rewrite_oversized_response(@last_run_result) if response_too_long?(@last_run_result) raise "Captain response exceeds the channel limit of #{message_length_limit} characters" if response_too_long?(@last_run_result) @@ -106,6 +107,12 @@ class Captain::Assistant::AgentRunnerService ) end + def record_turn_start(result) + history = Array(result.context&.dig(:conversation_history)) + turn_start_index = history.rindex { |message| message[:role].to_s == 'user' } + result.context[:captain_v2_turn_start_index] = turn_start_index if turn_start_index + end + def response_too_long?(result) message_length_limit && response_text(result).length > message_length_limit end diff --git a/enterprise/app/services/captain/assistant/session_capture_service.rb b/enterprise/app/services/captain/assistant/session_capture_service.rb index 36af50308..d41a1b874 100644 --- a/enterprise/app/services/captain/assistant/session_capture_service.rb +++ b/enterprise/app/services/captain/assistant/session_capture_service.rb @@ -58,6 +58,9 @@ class Captain::Assistant::SessionCaptureService # (assistant replies, tool calls/results, handoff hops). def current_turn_history history = Array(context[:conversation_history]) + turn_start_index = context[:captain_v2_turn_start_index] + return history[turn_start_index..] if turn_start_index + last_user_index = history.rindex { |message| message[:role].to_s == 'user' } last_user_index ? history[last_user_index..] : history end