diff --git a/agent/message_sanitization.py b/agent/message_sanitization.py index b5c82f1c1d..0d64fefded 100644 --- a/agent/message_sanitization.py +++ b/agent/message_sanitization.py @@ -285,7 +285,7 @@ def _repair_tool_call_arguments(raw_args: str, tool_name: str = "?") -> str: return "{}" -def close_interrupted_tool_sequence(messages: list, final_response: Any = None) -> bool: +def close_interrupted_tool_sequence(messages: list, final_response: Any = None, *, stopped: bool = False) -> bool: """Append a synthetic assistant turn when an interrupted tail is a tool result: a transcript ending on a raw ``tool`` message makes the next user message land as ``tool → user``, an alternation violation strict providers (Gemini, Claude) answer by hallucinating a @@ -297,7 +297,11 @@ def close_interrupted_tool_sequence(messages: list, final_response: Any = None) ``display_kind="hidden"`` keep it out of rendered transcripts, matching the ``_INTERRUPTED_PLACEHOLDER`` shape in ``turn_api_call.py``. A caller-supplied banner (truncation notices, partial-delivery text) stays visible: it is the turn's only - user-facing explanation.""" + user-facing explanation. + + ``stopped`` (a user stop, not a truncation or overflow exit) puts the stopped mark on the + closing row, as ``turn_api_call.py`` does on a partial reply: it is the turn's last stored + row, so a reopened transcript still says the turn was stopped.""" last = messages[-1] if messages else None if not isinstance(last, dict) or last.get("role") != "tool": return False @@ -306,9 +310,12 @@ def close_interrupted_tool_sequence(messages: list, final_response: Any = None) stripped = text.strip() if not stripped or stripped == _INTERRUPTED_PLACEHOLDER: - append_message(messages, hidden_interrupt_placeholder_row()) + row = hidden_interrupt_placeholder_row() else: - append_message(messages, {"role": "assistant", "content": stripped}) + row = {"role": "assistant", "content": stripped} + if stopped: + row["display_metadata"] = {"interrupted": True} + append_message(messages, row) return True diff --git a/agent/turn_finalizer.py b/agent/turn_finalizer.py index 8890e6040f..51f52c550f 100644 --- a/agent/turn_finalizer.py +++ b/agent/turn_finalizer.py @@ -244,7 +244,7 @@ def _close_transcript_tail(agent, messages, final_response, interrupted, _recove # providers don't see ``tool → user`` (placeholder: final_response is usually empty). if interrupted: from agent.message_sanitization import close_interrupted_tool_sequence - close_interrupted_tool_sequence(messages, final_response) + close_interrupted_tool_sequence(messages, final_response, stopped=True) # Recovery ``break`` sites can return a final_response with no closing assistant # row; enforce "delivered final_response ⇒ assistant row" here. Compare content, diff --git a/agent/turn_recovery.py b/agent/turn_recovery.py index 5be3ad8658..fdcb3cacf6 100644 --- a/agent/turn_recovery.py +++ b/agent/turn_recovery.py @@ -1379,7 +1379,7 @@ def abort_turn_on_interrupt( # already-executed tool result. Strip only that request-local scaffold before # closing, so this exit owner can persist its specific interrupt reason. agent._drop_trailing_empty_response_scaffolding(messages) - close_interrupted_tool_sequence(messages, interrupt_text) + close_interrupted_tool_sequence(messages, interrupt_text, stopped=True) agent._persist_session(messages, conversation_history) # The turn was stopped, not rebuilt: a pending steer was aimed at this turn's next # tool iteration, which will no longer happen — drop it (hard-cancel semantics). diff --git a/apps/desktop/src/lib/chat-messages.stopped-tool-fold.test.ts b/apps/desktop/src/lib/chat-messages.stopped-tool-fold.test.ts index 56da1eb8ad..9290c0f4e3 100644 --- a/apps/desktop/src/lib/chat-messages.stopped-tool-fold.test.ts +++ b/apps/desktop/src/lib/chat-messages.stopped-tool-fold.test.ts @@ -30,6 +30,23 @@ describe('stopped reply folded into its tool bubble', () => { expect(replies[0].interrupted).toBe(true) }) + it('keeps the stopped mark of a turn stopped during its tool run', () => { + // Stored by the backend's close of an interrupted tool tail: no reply, an empty hidden row. + const closing: SessionMessage = { + id: 4, + role: 'assistant', + content: '', + display_kind: 'hidden', + timestamp: 4, + display_metadata: '{"interrupted": true}' + } + + const stoppedInTool = [...rows.slice(0, 2), { ...rows[2], content: '[Command interrupted]' }, closing] + const replies = toChatMessages(stoppedInTool).filter(message => message.role === 'assistant') + + expect(replies.map(message => [chatMessageText(message), message.interrupted])).toEqual([['Looking.', true]]) + }) + it('leaves a finished tool turn unmarked', () => { const finished = rows.map(row => (row.id === 4 ? { ...row, display_metadata: undefined } : row)) const replies = toChatMessages(finished).filter(message => message.role === 'assistant') diff --git a/apps/desktop/src/lib/chat-messages/hydration.ts b/apps/desktop/src/lib/chat-messages/hydration.ts index 54d0abc026..933344c739 100644 --- a/apps/desktop/src/lib/chat-messages/hydration.ts +++ b/apps/desktop/src/lib/chat-messages/hydration.ts @@ -439,6 +439,22 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] { clearPendingTools() } + // The empty row closing a turn stopped during its tool run draws nothing, but it is + // the turn's last stored row and the one that says it was stopped: the mark goes on + // the bubble that row closes, as a folded reply's does (foldIntoToolBubble). + const lendStoppedMark = (message: SessionMessage, index: number) => { + if (!messageInterrupted(message.display_metadata)) { + return + } + + flushPendingTools(index) + const bubble = activeAssistantIndex === null ? undefined : result[activeAssistantIndex] + + if (bubble?.role === 'assistant') { + bubble.interrupted = true + } + } + // `index` stays the stored row position (it keys tool-part and message ids), so skipped merges shift nothing. const painted = messages.flatMap((message, index) => (isPainted(message) ? [{ index, message }] : [])) @@ -561,7 +577,9 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] { } if (!parts.length && !extractedAttachmentRefs?.length) { - if (message.role !== 'assistant') { + if (message.role === 'assistant') { + lendStoppedMark(message, index) + } else { flushPendingTools(index) activeAssistantIndex = null }