Skip to content

fix(agent): return session_id when chat completion produces no events (#15169) - #15228

Merged
yuzhichang merged 2 commits into
infiniflow:mainfrom
Rene0422:fix/agent-completion-empty-response-missing-session-id
Jun 30, 2026
Merged

yuzhichang merged 2 commits into
infiniflow:mainfrom
Rene0422:fix/agent-completion-empty-response-missing-session-id

Conversation

@Rene0422

Copy link
Copy Markdown
Contributor

Summary

Fixes #15169 — POST /api/v1/agents/chat/completions returned
data: {} with no session_id when the agent produced no events
(e.g. the reporter's payload sent "query": "").

Root cause

For {"agent_id": "...", "query": "", "stream": false}:

  1. No session_id in the request → new-session branch at
    agent_api.py:1278.

  2. session_id = get_uuid() at agent_api.py:1294.

  3. Falls into _run_workflow_session.

  4. canvas.run(query="") produces no events, so final_ans
    stays {}.

  5. Non-streaming path then hit:

    if not final_ans:
        await commit_runtime_replica()
        return get_result(data={})

    session_id was allocated but silently dropped on the way out.

The streaming path had the same shape (only a bare [DONE] was
yielded — no SSE event carrying session_id). The
session-continuation path at agent_api.py:1463 had the same bug
for callers that passed session_id and got {} back.

The successful (non-empty) paths were fine because every canvas
event has ans["session_id"] = session_id attached before being
yielded / captured into final_ans (see
agent_api.py:255 and :303).

Fix

Three minimal changes, all in
api/apps/restful_apis/agent_api.py:

  1. _run_workflow_session (non-streaming):
    return get_result(data={"session_id": session_id}) instead of
    data={}.
  2. _run_workflow_session (SSE): if the canvas loop emits no
    events, yield one
    data:{"session_id": "...", "data": {}} event before
    [DONE], so the client receives the id over the wire.
  3. agent_chat_completion session-continuation: echo the
    caller-supplied session_id back in the empty-events case
    instead of {}.

No change needed on the happy paths — they already attach
session_id to every event.

Test plan

  • Repro from the issue: POST /api/v1/agents/chat/completions
    with {"agent_id": "<id>", "query": "", "stream": false}.
    Response data should now contain session_id.
  • Same payload with "stream": true. SSE stream should
    contain one event with session_id before data:[DONE].
  • Same shape but with a real, non-empty "query" (new
    session). Response should be unchanged from before — every
    event still carries session_id, final response still
    includes it on final_ans.
  • Pass an existing session_id plus "query": "". Response
    should echo that session_id back instead of {}.
  • Pass an existing session_id plus a normal query. Response
    should be unchanged from before.
  • openai-compatible: true path is untouched — sanity-check
    it still works.
  • Run uv run pytest to make sure no existing tests regress.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)
  • New Feature (non-breaking change which adds functionality)
  • Documentation Update
  • Refactoring
  • Performance Improvement
  • Other (please describe):

@dosubot dosubot Bot added the size:S This PR changes 10-29 lines, ignoring generated files. label May 26, 2026
@coderabbitai

coderabbitai Bot commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f57fda37-531d-499e-9021-201939b79b2f

📥 Commits

Reviewing files that changed from the base of the PR and between 12389d6 and a9ccdb6.

📒 Files selected for processing (1)
  • api/apps/restful_apis/agent_api.py

📝 Walkthrough

Walkthrough

Adds session-id fallback handling for empty workflow and continuation responses. Streaming paths now emit a final SSE payload containing session_id; non-stream paths return get_result(data={"session_id": session_id}), with workflow execution also committing the runtime replica.

Changes

Session ID Guarantee on Empty Workflow Responses

Layer / File(s) Summary
Workflow session execution fallback contract
api/apps/restful_apis/agent_api.py
_run_workflow_session emits a fallback SSE payload with session_id when canvas.run produces no events; non-stream mode commits the runtime replica and returns get_result(data={"session_id": session_id}).
Chat completion endpoint fallback contract
api/apps/restful_apis/agent_api.py
agent_chat_completion tracks whether any events were emitted and, if none, emits a fallback SSE payload with session_id in stream mode or returns get_result(data={"session_id": session_id}) in non-stream mode.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • infiniflow/ragflow#14589: Modifies the same agent chat completion event pipeline in api/apps/restful_apis/agent_api.py, including how completion events are forwarded and aggregated.

Suggested labels

🐞 bug

Suggested reviewers

  • Magicbook1108
  • yuzhichang

Poem

🐰 A quiet stream went soft and small,
Then session_id hopped through it all.
No events? Still a path appears,
To guide the run through logs and gears.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main fix: returning session_id when chat completion emits no events.
Description check ✅ Passed The PR description satisfies the template with a clear summary and enough context about the bug and fix.
Linked Issues check ✅ Passed The changes address #15169 by returning or echoing session_id in empty-event cases for both new and resumed sessions.
Out of Scope Changes check ✅ Passed The edits stay within agent_api.py and are directly scoped to the session_id fallback bug.

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: 1

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

285-294: ⚡ Quick win

Add logging for the new empty-events fallback path.

These branches silently take a new control flow that now defines the endpoint contract for empty agent output. A small info/debug log with agent_id, session_id, and stream would make these cases diagnosable in production.

As per coding guidelines, **/*.py: Add logging for new flows.

Also applies to: 338-343, 1478-1482

🤖 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 285 - 294, The new fallback
branches that yield an empty SSE payload (the code that yields
json.dumps({"session_id": session_id, "data": {}})) should log the event so
these silent control flows are diagnosable; add a logger call (e.g., logger.info
or logger.debug) immediately before each yield that includes agent_id,
session_id, and stream (use the existing variable names agent_id, session_id,
stream) and a short message like "empty agent output - returning session_id";
apply the same logging change to the other analogous fallback locations that
produce the empty data JSON so all three branches consistently log this info.
🤖 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 `@api/apps/restful_apis/agent_api.py`:
- Around line 1478-1482: When handling existing-session streaming (the path that
calls _iter_session_completion_events with stream=true), ensure the stream does
not end with a bare [DONE] when the generator yields nothing by emitting an echo
event containing the session_id before completing; i.e., detect when
_iter_session_completion_events yields no events for the given session_id and
yield a final event with {"session_id": session_id} (the same shape returned by
get_result) prior to closing the stream so clients using stream=true can recover
the session_id.

---

Nitpick comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 285-294: The new fallback branches that yield an empty SSE payload
(the code that yields json.dumps({"session_id": session_id, "data": {}})) should
log the event so these silent control flows are diagnosable; add a logger call
(e.g., logger.info or logger.debug) immediately before each yield that includes
agent_id, session_id, and stream (use the existing variable names agent_id,
session_id, stream) and a short message like "empty agent output - returning
session_id"; apply the same logging change to the other analogous fallback
locations that produce the empty data JSON so all three branches consistently
log this info.
🪄 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: 32a4eb6c-5071-41c3-97e4-fa69a7ff1d5d

📥 Commits

Reviewing files that changed from the base of the PR and between c3b38d3 and 4047d62.

📒 Files selected for processing (1)
  • api/apps/restful_apis/agent_api.py

Comment thread api/apps/restful_apis/agent_api.py Resolved
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:S This PR changes 10-29 lines, ignoring generated files. labels May 26, 2026
@coderabbitai

coderabbitai Bot commented May 28, 2026

Copy link
Copy Markdown
Contributor

Actionable comments posted: 0

@yuzhichang
yuzhichang self-requested a review June 28, 2026 00:49
@yuzhichang
yuzhichang force-pushed the main branch 2 times, most recently from 78db4e9 to f86a0e7 Compare June 29, 2026 01:47
@yuzhichang
yuzhichang force-pushed the fix/agent-completion-empty-response-missing-session-id branch from 12389d6 to a9ccdb6 Compare June 29, 2026 05:58

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
api/apps/restful_apis/agent_api.py (1)

493-505: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Authorize session read/delete with tenant_id.

Binding the session to agent_id prevents cross-agent access, but any authenticated caller who knows a valid agent_id/session_id pair can still read or delete it because tenant_id is unused here. Mirror the access check used in agent_chat_completion before returning or deleting the session.

Proposed fix
 def get_agent_session(agent_id, session_id, tenant_id):
     exists, conv = API4ConversationService.get_by_id(session_id)
     if not exists or conv.dialog_id != agent_id:
         return get_data_error_result(message="Session not found!")
+    if not UserCanvasService.accessible(agent_id, tenant_id):
+        logging.warning(
+            "get_agent_session denied: tenant_id=%s agent_id=%s session_id=%s",
+            tenant_id,
+            agent_id,
+            session_id,
+        )
+        return get_data_error_result(message="Session not found!")
     return get_json_result(data=conv.to_dict())
@@
 def delete_agent_session_item(agent_id, session_id, tenant_id):
     exists, conv = API4ConversationService.get_by_id(session_id)
     if not exists or conv.dialog_id != agent_id:
         return get_data_error_result(message="Session not found!")
+    if not UserCanvasService.accessible(agent_id, tenant_id):
+        logging.warning(
+            "delete_agent_session_item denied: tenant_id=%s agent_id=%s session_id=%s",
+            tenant_id,
+            agent_id,
+            session_id,
+        )
+        return get_data_error_result(message="Session not found!")
     return get_json_result(data=API4ConversationService.delete_by_id(session_id))
🤖 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 493 - 505, The session
read/delete handlers in agent_api.py only verify session ownership by agent_id,
so they still allow cross-tenant access when tenant_id is ignored. Update the
logic in get_agent_session_item and delete_agent_session_item to mirror the
tenant authorization used in agent_chat_completion by checking that the fetched
conversation matches tenant_id before returning data or deleting it, alongside
the existing session_id/dialog_id validation.
🤖 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 `@api/apps/restful_apis/agent_api.py`:
- Around line 600-607: `workflow_finished` is being forwarded in the streaming
path but not preserved as the final payload in the non-stream response flow, so
it can fall through to the empty fallback. Update the response handling in
`agent_api.py` so the same final-answer selection logic used around the
`message_end`/`user_inputs` branch also treats `workflow_finished` as a terminal
non-stream result, and verify the code paths around the event forwarding block
and the non-stream fallback preserve the actual payload instead of discarding
it.
- Around line 326-340: The empty streaming fallback in agent_api’s session
handling returns a session_id but never commits the runtime replica because
persist_workflow_session() exits early when final_ans is empty. Update the
workflow in the empty-output branch to ensure the runtime replica is committed
on this path as well, matching the non-streaming fallback behavior in
persist_workflow_session() and the surrounding agent output handling logic.

---

Outside diff comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 493-505: The session read/delete handlers in agent_api.py only
verify session ownership by agent_id, so they still allow cross-tenant access
when tenant_id is ignored. Update the logic in get_agent_session_item and
delete_agent_session_item to mirror the tenant authorization used in
agent_chat_completion by checking that the fetched conversation matches
tenant_id before returning data or deleting it, alongside the existing
session_id/dialog_id validation.
🪄 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: f57fda37-531d-499e-9021-201939b79b2f

📥 Commits

Reviewing files that changed from the base of the PR and between 12389d6 and a9ccdb6.

📒 Files selected for processing (1)
  • api/apps/restful_apis/agent_api.py

@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.

Caution

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
api/apps/restful_apis/agent_api.py (1)

493-505: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Authorize session read/delete with tenant_id.

Binding the session to agent_id prevents cross-agent access, but any authenticated caller who knows a valid agent_id/session_id pair can still read or delete it because tenant_id is unused here. Mirror the access check used in agent_chat_completion before returning or deleting the session.

Proposed fix
 def get_agent_session(agent_id, session_id, tenant_id):
     exists, conv = API4ConversationService.get_by_id(session_id)
     if not exists or conv.dialog_id != agent_id:
         return get_data_error_result(message="Session not found!")
+    if not UserCanvasService.accessible(agent_id, tenant_id):
+        logging.warning(
+            "get_agent_session denied: tenant_id=%s agent_id=%s session_id=%s",
+            tenant_id,
+            agent_id,
+            session_id,
+        )
+        return get_data_error_result(message="Session not found!")
     return get_json_result(data=conv.to_dict())
@@
 def delete_agent_session_item(agent_id, session_id, tenant_id):
     exists, conv = API4ConversationService.get_by_id(session_id)
     if not exists or conv.dialog_id != agent_id:
         return get_data_error_result(message="Session not found!")
+    if not UserCanvasService.accessible(agent_id, tenant_id):
+        logging.warning(
+            "delete_agent_session_item denied: tenant_id=%s agent_id=%s session_id=%s",
+            tenant_id,
+            agent_id,
+            session_id,
+        )
+        return get_data_error_result(message="Session not found!")
     return get_json_result(data=API4ConversationService.delete_by_id(session_id))
🤖 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 493 - 505, The session
read/delete handlers in agent_api.py only verify session ownership by agent_id,
so they still allow cross-tenant access when tenant_id is ignored. Update the
logic in get_agent_session_item and delete_agent_session_item to mirror the
tenant authorization used in agent_chat_completion by checking that the fetched
conversation matches tenant_id before returning data or deleting it, alongside
the existing session_id/dialog_id validation.
🤖 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 `@api/apps/restful_apis/agent_api.py`:
- Around line 600-607: `workflow_finished` is being forwarded in the streaming
path but not preserved as the final payload in the non-stream response flow, so
it can fall through to the empty fallback. Update the response handling in
`agent_api.py` so the same final-answer selection logic used around the
`message_end`/`user_inputs` branch also treats `workflow_finished` as a terminal
non-stream result, and verify the code paths around the event forwarding block
and the non-stream fallback preserve the actual payload instead of discarding
it.
- Around line 326-340: The empty streaming fallback in agent_api’s session
handling returns a session_id but never commits the runtime replica because
persist_workflow_session() exits early when final_ans is empty. Update the
workflow in the empty-output branch to ensure the runtime replica is committed
on this path as well, matching the non-streaming fallback behavior in
persist_workflow_session() and the surrounding agent output handling logic.

---

Outside diff comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 493-505: The session read/delete handlers in agent_api.py only
verify session ownership by agent_id, so they still allow cross-tenant access
when tenant_id is ignored. Update the logic in get_agent_session_item and
delete_agent_session_item to mirror the tenant authorization used in
agent_chat_completion by checking that the fetched conversation matches
tenant_id before returning data or deleting it, alongside the existing
session_id/dialog_id validation.
🪄 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: f57fda37-531d-499e-9021-201939b79b2f

📥 Commits

Reviewing files that changed from the base of the PR and between 12389d6 and a9ccdb6.

📒 Files selected for processing (1)
  • api/apps/restful_apis/agent_api.py
🛑 Comments failed to post (2)
api/apps/restful_apis/agent_api.py (2)

326-340: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Commit the runtime replica on the empty streaming path.

Line 340 calls persist_workflow_session(), but that helper returns immediately when final_ans is empty, so this streaming fallback never reaches commit_runtime_replica(). The non-streaming fallback commits at Line 391; keep the stream path consistent.

Proposed fix
                 else:
                     # Canvas produced no events (e.g. empty query). Still
                     # surface the session_id so the client can resume the
                     # conversation — without it the SSE stream is just a
                     # bare [DONE] (fixes `#15169`).
                     logging.info(
                         "empty agent output - returning session_id (agent_id=%s session_id=%s stream=%s)",
                         agent_id, session_id, True,
                     )
+                    await commit_runtime_replica()
                     yield (
                         "data:"
                         + json.dumps({"session_id": session_id, "data": {}}, ensure_ascii=False)
                         + "\n\n"
                     )
📝 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.

                else:
                    # Canvas produced no events (e.g. empty query). Still
                    # surface the session_id so the client can resume the
                    # conversation — without it the SSE stream is just a
                    # bare [DONE] (fixes `#15169`).
                    logging.info(
                        "empty agent output - returning session_id (agent_id=%s session_id=%s stream=%s)",
                        agent_id, session_id, True,
                    )
                    await commit_runtime_replica()
                    yield (
                        "data:"
                         json.dumps({"session_id": session_id, "data": {}}, ensure_ascii=False)
                         "\n\n"
                    )
                await persist_workflow_session()
🧰 Tools
🪛 ast-grep (0.44.0)

[info] 336-336: use jsonify instead of json.dumps for JSON output
Context: json.dumps({"session_id": session_id, "data": {}}, ensure_ascii=False)
Note: [CWE-116] Improper Encoding or Escaping of Output.

(use-jsonify)

🤖 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 326 - 340, The empty
streaming fallback in agent_api’s session handling returns a session_id but
never commits the runtime replica because persist_workflow_session() exits early
when final_ans is empty. Update the workflow in the empty-output branch to
ensure the runtime replica is committed on this path as well, matching the
non-streaming fallback behavior in persist_workflow_session() and the
surrounding agent output handling logic.

600-607: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Treat workflow_finished as a final non-stream answer.

Line 600 now forwards workflow_finished, but Lines 1620-1623 only preserve message_end or user_inputs. If a continuation emits workflow_finished without message_end, the non-stream response falls through to the empty fallback and drops the actual payload.

Proposed fix
-            if ans.get("event") == "message_end":
+            if ans.get("event") in ["message_end", "workflow_finished"]:
                 final_ans = ans
             elif ans.get("event") == "user_inputs" and not final_ans:
                 final_ans = ans

Also applies to: 1620-1636

🤖 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 600 - 607,
`workflow_finished` is being forwarded in the streaming path but not preserved
as the final payload in the non-stream response flow, so it can fall through to
the empty fallback. Update the response handling in `agent_api.py` so the same
final-answer selection logic used around the `message_end`/`user_inputs` branch
also treats `workflow_finished` as a terminal non-stream result, and verify the
code paths around the event forwarding block and the non-stream fallback
preserve the actual payload instead of discarding it.

@yuzhichang yuzhichang added the ci Continue Integration label Jun 29, 2026
@codecov

codecov Bot commented Jun 29, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (6e82e27) to head (a9ccdb6).
⚠️ Report is 15 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15228   +/-   ##
=======================================
  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.

@yuzhichang
yuzhichang merged commit 09dc4c8 into infiniflow:main Jun 30, 2026
6 checks passed
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 1, 2026
…infiniflow#15169) (infiniflow#15228)

## Summary

Fixes infiniflow#15169 — `POST /api/v1/agents/chat/completions` returned
`data: {}` with no `session_id` when the agent produced no events
(e.g. the reporter's payload sent `"query": ""`).

## Root cause

For `{"agent_id": "...", "query": "", "stream": false}`:

1. No `session_id` in the request → new-session branch at
   `agent_api.py:1278`.
2. `session_id = get_uuid()` at `agent_api.py:1294`.
3. Falls into `_run_workflow_session`.
4. `canvas.run(query="")` produces no events, so `final_ans`
   stays `{}`.
5. Non-streaming path then hit:

   ```python
   if not final_ans:
       await commit_runtime_replica()
       return get_result(data={})
   ```

   `session_id` was allocated but silently dropped on the way out.

The streaming path had the same shape (only a bare `[DONE]` was
yielded — no SSE event carrying `session_id`). The
session-continuation path at `agent_api.py:1463` had the same bug
for callers that passed `session_id` and got `{}` back.

The successful (non-empty) paths were fine because every canvas
event has `ans["session_id"] = session_id` attached before being
yielded / captured into `final_ans` (see
`agent_api.py:255` and `:303`).

## Fix

Three minimal changes, all in
`api/apps/restful_apis/agent_api.py`:

1. **`_run_workflow_session` (non-streaming)**:
   `return get_result(data={"session_id": session_id})` instead of
   `data={}`.
2. **`_run_workflow_session` (SSE)**: if the canvas loop emits no
   events, yield one
   `data:{"session_id": "...", "data": {}}` event before
   `[DONE]`, so the client receives the id over the wire.
3. **`agent_chat_completion` session-continuation**: echo the
   caller-supplied `session_id` back in the empty-events case
   instead of `{}`.

No change needed on the happy paths — they already attach
`session_id` to every event.

## Test plan

- [ ] Repro from the issue: `POST /api/v1/agents/chat/completions`
      with `{"agent_id": "<id>", "query": "", "stream": false}`.
      Response `data` should now contain `session_id`.
- [ ] Same payload with `"stream": true`. SSE stream should
      contain one event with `session_id` before `data:[DONE]`.
- [ ] Same shape but with a real, non-empty `"query"` (new
      session). Response should be unchanged from before — every
      event still carries `session_id`, final response still
      includes it on `final_ans`.
- [ ] Pass an existing `session_id` plus `"query": ""`. Response
      should echo that `session_id` back instead of `{}`.
- [ ] Pass an existing `session_id` plus a normal query. Response
      should be unchanged from before.
- [ ] `openai-compatible: true` path is untouched — sanity-check
      it still works.
- [ ] Run `uv run pytest` to make sure no existing tests regress.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
- [ ] New Feature (non-breaking change which adds functionality)
- [ ] Documentation Update
- [ ] Refactoring
- [ ] Performance Improvement
- [ ] Other (please describe):
yuzhichang pushed a commit that referenced this pull request Jul 2, 2026
### Summary

Port the following PRs to GO in this PR

#14210
#14641
#15220
#15228
#15384
#15754
#16413
#16483
#16419
#16361   
#16050
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

[Bug]: resetful api /api/v1/agents/chat/completions can not return session_id

2 participants