Repository navigation
Description
Bug
In `routers/public.py`, the user message is persisted to the database before `build_public_chat_context` reads from it to construct the agent prompt. This causes the current user message to appear twice in the context sent to the agent on every single turn.
Root Cause
```python
Line ~498 — stores user message in DB
db.add_public_chat_message(session_id=chat_session.id, role="user", content=chat_request.message)
Line ~512 — reads SAME DB to build context (now includes the just-stored message)
context_prompt = db.build_public_chat_context(
session_id=chat_session.id,
new_message=chat_request.message, # ← also appended as "Current message:"
max_turns=10
)
```
`build_context_prompt` in `db/public_chat.py` does two things:
- Reads the last N messages from the DB → includes the just-stored user message under "Previous conversation:"
- Appends the `new_message` again under "Current message:"
Result — the agent receives every turn as:
```
Trinity: Public Link Access Mode
Previous conversation:
...
User: Tell me a joke. ← current message (already in history)
Current message:
User: Tell me a joke. ← same message again!
```
For the very first message the history section reads as if the question has already been asked before the conversation even starts.
Impact
- Every agent response is generated with a duplicate of the user's message in context
- Wastes context tokens on every turn (worse for long conversations)
- Can subtly degrade response quality (agent sees contradictory context signals)
- Affects both sync and async public chat modes
Fix
Swap the call order — build context before persisting the user message:
```python
Build context from prior history only
context_prompt = db.build_public_chat_context(session_id=chat_session.id, new_message=chat_request.message, max_turns=10)
Then persist user message
db.add_public_chat_message(session_id=chat_session.id, role="user", content=chat_request.message)
```
Acceptance Criteria
- Context sent to agent contains the user message exactly once
- History (n-1 turns) appears in "Previous conversation:"; new message appears in "Current message:" only
- Fix applied to both sync and async code paths in `routers/public.py`
- Unit test: assert context string does not contain the new message in the history block
Activity
vybe commentedon Apr 27, 2026
/claim
github-actions commentedon Apr 27, 2026
Claimed by @vybe. Label
status-in-progressadded.Next steps:
feature/539-<short-slug>Fixes #539docs(feature-flows): update public-agent-links with #539 context orde…
fix(public-chat): build context before storing user message to preven…
Release: v0.5.0 (#608)
vybe commentedon Jun 1, 2026
Shipped in v0.6.0 (released via #998).