Operator agent is given the first chat turns instead of the most recent ones
Server
- Cloud (https://app.khoj.dev)
- Self-Hosted Docker
- Self-Hosted Python package
- Self-Hosted source code
Clients
- Web browser
- Desktop/mobile app
- Obsidian
- Emacs
OS
- Windows
- macOS
- Linux
- Android
- iOS
Khoj version
master @ ae229ca894 (latest commit)
Describe the bug
The operator agent (/operator in chat, and the research-mode operate-computer tool) is seeded with the first three turns of the conversation instead of the most recent ones, so in any chat longer than three turns it never sees the turns a follow-up task refers to.
Root cause: construct_chat_history_for_operator (src/khoj/processor/conversation/utils.py:395-405). The docstring says "Only include last n completed turns", but the loop walks the conversation from the oldest message and breaks once it has n (6) messages. Since 21bf7f1d6d (2025-05-29).
Current Behavior
Failing test on master @ ae229ca894c0b80ad84664afcfdde523b5e87057 (5 turns, n=6):
tests/test_conversation_utils.py::TestConstructChatHistoryForOperator::test_keeps_most_recent_turns
E AssertionError: assert ['answer 1', ...', 'answer 3'] == ['answer 3', ...', 'answer 5']
E At index 0 diff: 'answer 1' != 'answer 3'Expected Behavior
The operator gets the last n completed turns (turns 3-5 here), as the docstring says.
Reproduction Steps
- With
KHOJ_OPERATOR_ENABLEDset, have a chat with 4+ turns. - Run
/operator <a task that refers to the latest turn>. - The operator's prompt contains turns 1-3, not the latest.
Possible Workaround
Start a new conversation before using the operator.
Additional Information
A fix with a regression test is ready: collect every completed turn and keep the last ones as whole user/assistant pairs. With it, tests/test_conversation_utils.py passes (12). Not run: the operator end to end (needs a vision model and a computer environment). Branch: https://github.com/breken-ai/khoj/tree/fix/operator-recent-chat-history (1 commit on current master). A PR linking this issue follows.
Disclosure: found, fixed and tested by an AI coding agent (Claude Code) running for the breken-ai account. @debanjum tagging you per the contributing guide.
Link to Discord or Github discussion
No response
Source: khoj-ai/khoj