Skip to content

fix(ai): streamed devops ai chat turns send the user's message #874

Closed

Description

@dan-petty

Problem Statement

devops ai chat streams a turn only when streaming is on and tools are off (src/devops_cli/commands/ai.py:1090, if stream and not tools:). Both options default to on (:990-991), so the streamed path runs under --no-tools.

That path, _stream_interactive_chat_turn (commands/ai.py:926-953), builds its request from agent.memory.to_chat_messages() (:940) and never adds the user's prompt to memory: only the reply is added (:953). The other path, agent.run, adds the prompt itself (src/devops_cli/ai/agents/agent.py:821). A probe at ef21785 with a fake client that records what it is sent showed:

  • turn 1 sent no messages at all;
  • turn 2 sent only turn 1's reply;
  • memory then held two assistant entries and no user entry.

When a turn fails, the loop removes the last memory entry (commands/ai.py:1106-1109). In the streamed path that entry is the previous reply, not the failed turn. Since #599 (merged as 8b1e8d4), a stream cut before its final frame raises AIClientError instead of returning partial text, so this handler now runs for every cut stream and silently deletes the previous reply. A Ctrl-C mid-turn is handled separately (except KeyboardInterrupt, :1104-1105): it prints "Interrupted." and pops nothing, so on the tools path a dangling user entry (added at agent.py:821 before the request) stays behind and the next turn sends two consecutive user messages.

The code has been like this since v0.2.0 (491907c); it is not a regression. The only later change to commands/ai.py on this branch (7192da0, #961) touched audit_library_usage_cmd, not the chat loop. The defect affects only the non-default --no-tools mode and has no security impact, so it is not a critical fix.

Proposed Solution

All changes are in src/devops_cli/commands/ai.py and tests/test_ai_cmd.py.

  • _stream_interactive_chat_turn adds the user's prompt to memory (agent.memory.add_interaction("user", effective_prompt)) before it calls agent.memory.to_chat_messages(), so the model receives it. The stored text is effective_prompt (the prompt with any RAG snippet prepended, commands/ai.py:1076-1080), the same text agent.run stores on the tools path.
  • A failed or interrupted turn leaves memory as it was before the turn, on both paths. Both loop handlers (except KeyboardInterrupt, :1104-1105, and except Exception, :1106-1109) remove a trailing user entry only: if agent.memory.entries and agent.memory.entries[-1].role == "user": agent.memory.entries.pop(). The stream raises or is interrupted, the handler's role-checked pop removes the user entry that was just added, and a pop can never remove a previous reply. The helper does not roll back itself. This also closes the tools path's existing Ctrl-C gap for free, since agent.run leaves its user entry behind when it raises or is interrupted after agent.py:821.
  • When the model put its whole reply in thinking, the fallback (:945-951) calls agent.run, which adds the prompt again (agent.py:821) and then the reply (agent.py:1024). The streamed path removes its own user entry first, so the prompt is stored once.
  • The existing test test_a_cut_stream_stores_no_reply_in_chat_memory (tests/test_ai_cmd.py:579-598, added by feat(ai): finish reasons and stream completeness for model replies #599) pre-seeds a user entry, calls the helper directly and asserts ["user"] afterwards. Under this fix the helper adds the user entry itself, so that test is rewritten to the new contract: no pre-seeded entry, the helper raises, and the loop-level rollback is covered by the CliRunner test below.
  • A changelog fragment changelog.d/874.md (under ### Fixed) and the task file docs/agent/tasks/task-874-streamed-chat-turns-send-the-users-message.md are written in the delivering pull request. CHANGELOG.md and docs/ROADMAP.md are not edited.

Scope

One pull request. Touched files: src/devops_cli/commands/ai.py (the helper at :926-953 and the two except handlers in the chat loop at :1104-1109), tests/test_ai_cmd.py, changelog.d/874.md, the task file. No change to AgentMemory, PydanticAgent or the client.

Key Questions

  • Use agent.run_stream instead? No. It sends only the current prompt and no history (agent.py:1130, messages = [ChatMessage(role="user", content=user_prompt)]), so a multi-turn chat would lose its context.
  • Is this a critical fix for the current release? No. It breaks only the non-default --no-tools mode and has no security impact. Placed in v0.2.27 by grooming on 2026-10-02 (value High, effort Low).
  • Who rolls memory back when a streamed turn fails? The loop's handlers (:1104-1109), not the helper. The helper only adds the user entry and lets the error or interrupt propagate; the handler's pop then removes that entry. This keeps one rollback for both paths (agent.run also leaves its user entry behind when it raises after agent.py:821).
  • Which text is stored as the user entry? effective_prompt, including the RAG snippet when --rag is on, matching what agent.run stores on the tools path and matching what is sent to the model.
  • Does a Ctrl-C mid-stream also roll back, and does the pop check what it removes? Answered (owner decision, 2026-10-02): yes to both. Both handlers (except KeyboardInterrupt, :1104-1105, and except Exception, :1106-1109) remove a trailing user entry only (if agent.memory.entries and agent.memory.entries[-1].role == "user": agent.memory.entries.pop()), so an interrupt rolls back too and a pop can never remove a previous reply. Before this fix an interrupt on the streamed path was harmless (nothing had been added); after it, without this change, the path would inherit the tools path's gap (agent.run adds the user entry at agent.py:821 before the request). It is a two-line change in the same function, it makes the "memory as it was before the turn" promise hold for every way a turn can end, and it closes the tools path's gap for free. The CliRunner test below gains one parametrized case where the fake stream raises KeyboardInterrupt.

Acceptance Criteria

  • The model receives the prompt and the history. test_a_streamed_turn_sends_the_user_message_and_history (tests/test_ai_cmd.py) runs _stream_interactive_chat_turn twice against MagicMock(memory=AgentMemory()) (the shape of tests/test_ai_cmd.py:589-592) and a fake client whose chat_messages_stream records the messages argument and yields a reply. The structural tuple assertion is [(m.role, m.content) for m in sent] == [("user", "p1")] for turn 1 and [("user", "p1"), ("assistant", "r1"), ("user", "p2")] for turn 2, and memory afterwards reads [("user", "p1"), ("assistant", "r1"), ("user", "p2"), ("assistant", "r2")]. It fails on today's code (turn 1 sends []).
  • A failed or interrupted streamed turn leaves memory as it was. test_a_failed_streamed_turn_leaves_memory_as_it_was, parametrized over two cases, drives runner.invoke(ai_app, ["chat", "--no-tools", "--no-rag", "--no-prewarm"]) with devops_cli.commands.ai.get_console patched to a console whose input.side_effect is ["p1", "p2", "exit"] (the shape of tests/test_ai_cmd.py:430-443) and LLMClient.chat_messages_stream patched to a fake that records each call's messages, yields one chunk then raises on the first call, and yields "r2" on the second. Case 1 raises AIClientError("Provider stream ended before its final frame.") and asserts the output contains Error: and before its final frame; case 2 raises KeyboardInterrupt and asserts the output contains Interrupted.. In both cases: exit code 0, the second call was sent [("user", "p2")] only, and the agent's memory afterwards reads [("user", "p2"), ("assistant", "r2")] (captured by wrapping devops_cli.ai.agents.PydanticAgent or by patching AgentMemory). Case 1 fails on today's code (the second call is sent []); case 2 fails on the helper fix alone without the role-checked pop in the interrupt handler (the second call is sent [("user", "p1"), ("user", "p2")]).
  • The thinking-only fallback stores the prompt once. test_a_thinking_only_stream_stores_the_prompt_once runs _stream_interactive_chat_turn with a real PydanticAgent(client=fake, system_prompt="...", tools=[]) (the shape of tests/test_pydantic_agent.py:77-98) whose fake client's chat_messages_stream records its messages and yields only <think>…</think>, and whose chat_messages returns "r1" for the agent.run fallback (agent.py:887), with devops_cli.ai.rag.investigator.investigate_rag_context patched to return None. The stream call was sent [("user", "p1")] (fails today: []), and memory afterwards reads [("user", "p1"), ("assistant", "r1")]: exactly one user entry (guards the fix against storing it twice).
  • The feat(ai): finish reasons and stream completeness for model replies #599 test matches the new contract. test_a_cut_stream_stores_no_reply_in_chat_memory (tests/test_ai_cmd.py:579-598) no longer pre-seeds a user entry; it asserts the error propagates and that, under the helper alone, memory holds the one user entry the helper added and no assistant entry (the loop's rollback is the second criterion's job).
  • No network. The new tests use fakes for chat_messages_stream and chat_messages and patch investigate_rag_context; the autouse guard prevent_external_network_calls (tests/conftest.py:98-160) turns any stray connect or external DNS lookup into an error, so a test that reached the network would fail.
  • Speed. uv run pytest tests/test_ai_cmd.py -n0 --durations=0 -k "streamed_turn or failed_streamed or thinking_only or cut_stream" shows every new or rewritten test under 0.25 s serially. (The issue's "under 1 s" is kept as intent; feat(ai): finish reasons and stream completeness for model replies #599's task file records why a summed figure under pyproject's -n logical is not meaningful.)
  • Gate. uv run devops ci passes (it runs ruff format, ruff check, mypy --strict src and the test suite).
  • Fragment and task file. changelog.d/874.md exists with a ### Fixed entry; docs/agent/tasks/task-874-streamed-chat-turns-send-the-users-message.md exists with **Status**: Done; tests/test_agent_task_files.py passes; the pull request does not touch CHANGELOG.md or docs/ROADMAP.md (devops pr check-readiness blocks either).
  • Pending a person: in uv run devops ai chat --no-tools, ask "What is 2+2?". The reply answers that question. Then ask "And times 3?"; the reply uses the first answer, showing the history was sent. Then ask a third question and press Ctrl-C while the reply streams; "Interrupted." prints, and a fourth question gets a reply that still follows the earlier answers.

Out of Scope

Dependencies

Readiness check (2026-10-04)

Checked against release/v0.2.26 at b61e5a0. The defect is unchanged: the helper still never adds the user entry, and except Exception still pops whatever entry is last.

Line corrections (commands/ai.py moved +9, agent.py +22):

  • src/devops_cli/commands/ai.py: _stream_interactive_chat_turn :935-962 (was :926-953); to_chat_messages() :949 (was :940); reply add_interaction :962 (was :953); thinking-only fallback :954-960 (was :945-951); --stream/--tools :999-1000 (was :990-991); RAG prepend :1085-1089 (was :1076-1080); if stream and not tools: :1099 (was :1090); except KeyboardInterrupt :1113-1114 and except Exception :1115-1118 (were :1104-1105, :1106-1109); chat constructor :1054-1056 (was :1045-1047); agents command :853-929 (was :849-920), still ending six lines above the helper; pipeline command :1155 onward (was :1146).
  • src/devops_cli/ai/agents/agent.py: user entry :843 (was :821); RAG step :849-862, the fallback's second lookup :852-858 (was :827-840, :830-836); chat_messages call :909 (was :887); assistant entry :1046 (was :1024); run_stream :1129-1155 with its single-message list at :1152 (was :1107-1133, :1130).
  • tests/conftest.py: the guard fixture starts at :99. The tests/test_ai_cmd.py anchors (:430-443, :579-598) and tests/test_pydantic_agent.py:77-98 are unchanged.

Dependencies:

Rules: the item fits one PR. It uses offline fakes, adds changelog.d/874.md, makes no shared-file edits and has no dry-run surface (interactive chat). No acceptance criterion changes.

Activity

  1. added
    type/bug
    scope/ai
    priority/p1-high
    on Oct 1, 2026
  2. added this to the v0.2.27 milestone on Oct 2, 2026
  3. dan-petty commented on Oct 2, 2026

    @dan-petty
    OwnerAuthor

    Grooming (2026-10-02): Placed in v0.2.27, one of its slots held for P1 work that surfaced after it was planned. Value High, effort Low. Ready.

    Checked against the code at the release/v0.2.25 tip.

  4. dan-petty-bot commented on Oct 5, 2026

    @dan-petty-bot
    Collaborator

    What changed

    #1196, merged into release/v0.2.27 as 107580e.

    Summary

    Fixes #874.

    Prior to this fix, _stream_interactive_chat_turn compiled chat messages from agent.memory before adding the current user prompt, causing streamed turns to send empty or missing user prompt messages to the model. In addition, chat error handlers unconditionally modified memory or failed to roll back interrupted turns, and thinking-only stream turns could duplicate user entries upon fallback to agent.run.

    4 file(s) changed.

    How it was verified

    Check runs at 8ee2819:

    • Prune PR DevContainer Images: pass
    • CodeQL: pass
    • Service Image: skipping
    • Static Analysis: pass
    • Analyze (actions): pass
    • Analyze (python): pass
    • Tests & Coverage: pass
    • DevContainer Image: skipping
    • Dependency Freshness: skipping

    Acceptance Criteria of docs/agent/tasks/task-874-streamed-chat-turns-send-the-users-message.md:

    • Streamed turns send the user's message and history: On turn 1, messages contains [("user", "p1")]. On turn 2, messages contains [("user", "p1"), ("assistant", "r1"), ("user", "p2")], and memory records both turns.
    • A failed or interrupted streamed turn leaves memory as it was before the turn: When a streamed turn fails with AIClientError or is aborted with KeyboardInterrupt, memory is rolled back to its pre-turn state and subsequent turns proceed cleanly.
    • The thinking-only fallback stores the prompt once: Stream turns producing only thinking blocks fall back to agent.run and record exactly one user entry in memory.
    • The feat(ai): finish reasons and stream completeness for model replies #599 test matches the new contract: test_a_cut_stream_stores_no_reply_in_chat_memory verifies that a cut stream under the helper alone leaves the single user entry and no assistant reply.
    • No network: All tests utilize offline fakes for chat_messages_stream and chat_messages, patched investigate_rag_context, and respect prevent_external_network_calls.
    • Speed: All new and updated tests execute under 0.25 s serially in pytest.
    • Gate: uv run devops ci completes with 100% passing quality gates.
    • Fragment and task file: changelog.d/874.md exists with ### Fixed; docs/agent/tasks/task-874-streamed-chat-turns-send-the-users-message.md exists with **Status**: Done; CHANGELOG.md and docs/ROADMAP.md remain untouched.
    • Pending a person: in uv run devops ai chat --no-tools, ask "What is 2+2?". The reply answers that question. Then ask "And times 3?"; the reply uses the first answer, showing the history was sent. Then ask a third question and press Ctrl-C while the reply streams; "Interrupted." prints, and a fourth question gets a reply that still follows the earlier answers.
  5. added a commit that references this issue on Oct 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority/p1-highscope/aitype/bug

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions