Skip to content

Fix Agent session lost <think></think> tag - #16670

Merged
wangq8 merged 1 commit into
infiniflow:mainfrom
wangq8:bugfix/fix-agent-session-lost-think-tag
Jul 6, 2026
Merged

wangq8 merged 1 commit into
infiniflow:mainfrom
wangq8:bugfix/fix-agent-session-lost-think-tag

Conversation

@wangq8

@wangq8 wangq8 commented Jul 6, 2026 •

Copy link
Copy Markdown
Collaborator

Session:
image
Log:
image

@wangq8
wangq8 requested review from buua436 and yuzhichang July 6, 2026 09:08
@wangq8 wangq8 added the ci Continue Integration label Jul 6, 2026
@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Jul 6, 2026
@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds two unrelated changes: workflow message handlers in agent_api.py now inject ""/"" markers based on start_to_think/end_to_think flags, and agent.go's RunAgent now persists conversation sessions (user input, answer, references) via a new persistAgentRunSession helper at three completion points.

Changes

Think Tag Markers in Workflow Streaming

Layer / File(s) Summary
Think markers in message accumulation
api/apps/restful_apis/agent_api.py
SSE and non-SSE workflow message handling append ""/"" markers to full_content when start_to_think/end_to_think flags are present; a nearby whitespace boundary was also adjusted.

Estimated code review effort: 1 (Trivial) | ~5 minutes

Agent Run Session Persistence

Layer / File(s) Summary
persistAgentRunSession helper
internal/service/agent.go
New persistAgentRunSession method loads a conversation session, appends user/assistant messages and reference chunks, JSON-encodes updated Message/Reference, and writes via api4ConversationDAO.Update; new stringifyAgentUserInput helper serializes user input.
Wiring into RunAgent completion paths
internal/service/agent.go
Calls to persistAgentRunSession are added before SSE emissions on the interrupt-error, completed-loop, and normal completion paths in RunAgent.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant RunAgent
  participant persistAgentRunSession
  participant api4ConversationDAO
  participant SSEClient

  RunAgent->>RunAgent: detect completion path (interrupt, loop, or normal)
  RunAgent->>persistAgentRunSession: persist(sessionID, messageID, userInput, answer, reference)
  persistAgentRunSession->>api4ConversationDAO: load conversation session
  api4ConversationDAO-->>persistAgentRunSession: session data
  persistAgentRunSession->>persistAgentRunSession: append user/assistant messages, encode JSON
  persistAgentRunSession->>api4ConversationDAO: Update(session)
  RunAgent->>SSEClient: emit message/message_end/workflow_finished
Loading

Poem

A rabbit hops through streaming thought,
With tags now neatly caught,
Sessions saved before they end,
Each answer stored, each turn a friend,
Two burrows dug, one hop away! 🐇✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description omits the required Summary and only contains screenshots, so it doesn't explain the PR purpose or context. Add a Summary section describing the problem, the fix, and relevant context; keep the screenshots as optional supporting evidence.
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly matches the main change: preserving tags in agent session handling.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
api/apps/restful_apis/agent_api.py (1)

316-321: 🎯 Functional Correctness | 🔵 Trivial

Potential double-append if content and think flags coexist.

Content is appended unconditionally on Line 317, then think markers are appended separately based on flags. This differs from the upstream Go contract in chat_session.go (context snippet 1), which treats StartToThink/EndToThink/Answer as mutually exclusive via an if/elif/elif chain. If an event ever carries both a non-empty content and a think flag, this code would append both, producing malformed output (e.g., "foo<think>" instead of just "<think>"). Given the current backend always sends these as mutually exclusive, this is currently safe, but the assumption isn't enforced here.

Also, this same block is duplicated verbatim in the non-SSE path (Lines 378-381); consider extracting a small helper to keep the two loops in sync.
[medium_effort_and_medium_reward]

♻️ Suggested consolidation
+def _apply_think_markers(content: str, data: dict) -> str:
+    if data.get("start_to_think", False):
+        return content + "<think>"
+    elif data.get("end_to_think", False):
+        return content + "</think>"
+    return content

Then use full_content = _apply_think_markers(full_content + ans.get("data", {}).get("content", ""), ans.get("data", {})) in both loops.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/restful_apis/agent_api.py` around lines 316 - 321, The message
assembly in agent_api.py can double-append content and think markers when a
payload includes both content and start/end_think flags, unlike the mutually
exclusive handling in chat_session.go. Update the logic in the message-handling
block (and the duplicated non-SSE path) so the event data is processed through a
single mutually exclusive branch or shared helper that handles
Answer/StartToThink/EndToThink consistently, preventing malformed output and
keeping both loops in sync.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/service/agent.go`:
- Around line 1196-1218: The session update flow in the agent run path is doing
a read/append/save on the full Message and Reference blobs, so concurrent
completions can overwrite each other. Update the logic around the session load
and save in the agent service to use a transaction with row-level locking or a
DAO method that atomically appends the new turn and reference data. Keep the fix
centered on the existing GetBySessionID, parseAgentSessionMessages,
parseAgentSessionReferences, and api4ConversationDAO.Update flow so both Message
and Reference are updated safely under concurrency.
- Around line 1201-1202: The session lookup helper in RunAgent currently returns
early when GetBySessionID misses, which causes brand-new runs with a generated
sessionID to be dropped instead of persisted. Update the helper around the
session/sessionID check to create an API4Conversation row when session is nil,
and change the helper signature/call sites to accept userID so the new row can
be owned correctly for later resume checks. Keep the existing session reuse path
intact, but ensure the miss path initializes and persists the conversation
instead of returning immediately.

---

Nitpick comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 316-321: The message assembly in agent_api.py can double-append
content and think markers when a payload includes both content and
start/end_think flags, unlike the mutually exclusive handling in
chat_session.go. Update the logic in the message-handling block (and the
duplicated non-SSE path) so the event data is processed through a single
mutually exclusive branch or shared helper that handles
Answer/StartToThink/EndToThink consistently, preventing malformed output and
keeping both loops in sync.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: dc41a35c-bbf2-4451-af8f-132aaa00c98d

📥 Commits

Reviewing files that changed from the base of the PR and between 57625c9 and 70e5ada.

📒 Files selected for processing (2)
  • api/apps/restful_apis/agent_api.py
  • internal/service/agent.go

Comment thread internal/service/agent.go
Comment on lines +1196 to +1218
session, err := s.api4ConversationDAO.GetBySessionID(sessionID, agentID)
if err != nil {
common.Warn("agent run: load session for update failed", zap.String("agent_id", agentID), zap.String("session_id", sessionID), zap.Error(err))
return
}
if session == nil {
return
}
messages := parseAgentSessionMessages(session.Message)
now := time.Now().Unix()
if text := stringifyAgentUserInput(userInput); text != "" {
messages = append(messages, map[string]interface{}{"role": "user", "content": text, "id": strings.ReplaceAll(uuid.New().String(), "-", ""), "created_at": now})
}
messages = append(messages, map[string]interface{}{"role": "assistant", "content": answer, "id": messageID, "created_at": now})
if raw, err := json.Marshal(messages); err == nil {
session.Message = raw
}
references := parseAgentSessionReferences(session.Reference)
references = append(references, normalizeAgentReferenceEntry(map[string]interface{}{"chunks": reference}))
if raw, err := json.Marshal(references); err == nil {
session.Reference = raw
}
if err := s.api4ConversationDAO.Update(session); err != nil {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Avoid lost turns on concurrent session updates.

This load/append/save flow rewrites the full Message and Reference JSON blobs. Two runs finishing for the same session can both read the same row, append independently, and the later Update overwrites the earlier turn. Move this into a transaction with row locking or a DAO-level atomic append/update.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/service/agent.go` around lines 1196 - 1218, The session update flow
in the agent run path is doing a read/append/save on the full Message and
Reference blobs, so concurrent completions can overwrite each other. Update the
logic around the session load and save in the agent service to use a transaction
with row-level locking or a DAO method that atomically appends the new turn and
reference data. Keep the fix centered on the existing GetBySessionID,
parseAgentSessionMessages, parseAgentSessionReferences, and
api4ConversationDAO.Update flow so both Message and Reference are updated safely
under concurrency.

Comment thread internal/service/agent.go
Comment on lines +1201 to +1202
if session == nil {
return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Create the session row instead of dropping new runs.

When RunAgent generates a new sessionID, GetBySessionID will miss and this helper returns, so the run is never persisted. Create an API4Conversation row on miss and pass userID into this helper so resume checks have a populated owner.

Possible fix shape
-func (s *AgentService) persistAgentRunSession(agentID, sessionID, messageID string, userInput any, answer string, reference []interface{}) {
+func (s *AgentService) persistAgentRunSession(agentID, sessionID, messageID, userID string, userInput any, answer string, reference []interface{}) {
@@
-	if session == nil {
-		return
+	isNewSession := false
+	if session == nil {
+		isNewSession = true
+		session = &entity.API4Conversation{
+			ID:       sessionID,
+			DialogID: agentID,
+			UserID:   userID,
+		}
 	}
@@
-	if err := s.api4ConversationDAO.Update(session); err != nil {
+	if isNewSession {
+		err = s.api4ConversationDAO.Create(session)
+	} else {
+		err = s.api4ConversationDAO.Update(session)
+	}
+	if err != nil {
 		common.Warn("agent run: update session failed", zap.String("agent_id", agentID), zap.String("session_id", sessionID), zap.Error(err))
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if session == nil {
return
isNewSession := false
if session == nil {
isNewSession = true
session = &entity.API4Conversation{
ID: sessionID,
DialogID: agentID,
UserID: userID,
}
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/service/agent.go` around lines 1201 - 1202, The session lookup
helper in RunAgent currently returns early when GetBySessionID misses, which
causes brand-new runs with a generated sessionID to be dropped instead of
persisted. Update the helper around the session/sessionID check to create an
API4Conversation row when session is nil, and change the helper signature/call
sites to accept userID so the new row can be owned correctly for later resume
checks. Keep the existing session reuse path intact, but ensure the miss path
initializes and persists the conversation instead of returning immediately.

@wangq8
wangq8 marked this pull request as draft July 6, 2026 09:15
@wangq8
wangq8 marked this pull request as ready for review July 6, 2026 09:15
@dosubot dosubot Bot added the 🐞 bug Something isn't working, pull request that fix bug. label Jul 6, 2026
@wangq8
wangq8 marked this pull request as draft July 6, 2026 09:17
@wangq8
wangq8 marked this pull request as ready for review July 6, 2026 09:17
@codecov

codecov Bot commented Jul 6, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (98189cd) to head (70e5ada).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16670   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@wangq8
wangq8 merged commit ed52255 into infiniflow:main Jul 6, 2026
9 of 15 checks passed
@dosubot dosubot Bot mentioned this pull request Jul 7, 2026
4 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant