fix(desktop): a turn stopped during its tool run keeps its stopped mark once stored

A Stop during a tool run leaves no reply: the finalizer closes the tool tail with
the empty hidden placeholder row and wrote no stopped mark anywhere, so once the
stored copy replaced the live one (the refresh after the stop in a short chat, a
later turn's refresh in a long one, every reload) "Response stopped" was gone.

The user-stop callers of close_interrupted_tool_sequence (the finalizer's
interrupted close and abort_turn_on_interrupt) now record interrupted on the
closing row, as turn_api_call.py does on a partial reply; truncation/overflow
closes stay unmarked. Hydration lends that empty row's mark to the bubble it
closes, the same rule as a reply folded into its tool bubble.
This commit is contained in:
Teknium
2026-10-26 05:22:20 -07:00
parent 29e8f90b04
commit 674f2d680d
5 changed files with 49 additions and 7 deletions

View File

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

View File

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

View File

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

View File

@@ -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')

View File

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