chat: fold an agent turn into one reply, split reasoning from answer, keep tool name/input

The phone's chat transcript rendered one agent reply as ~36 bubbles, each with
its own thinking block, and a finished tool call lost its name and its input.

- Turn fold (android): ChatFormat.kt gains the pure ChatTurn / TranscriptRow /
  transcriptRows fold - each run of consecutive assistant messages between two of
  the operator's messages is one agent turn - and ChatTranscript renders one
  bubble per turn: the turn's single collapsible thinking block (all its
  reasoning, in order, growing live while it streams), then its tool-call chips,
  then one answer block of just the turn's text parts. AssistantParts/MessagePart
  are replaced by AgentTurnItem/UserMessageItem; ChatConversationPane counts the
  folded rows.
- Delta part ids (server + client): internal/protocol/chat.go adds
  ChatDeltaPartID(messageID, kind, ordinal), mirrored as ChatProtocol.deltaPartId
  in data/protocol/Chat.kt, and NormalizeChatEvent keys a text or reasoning delta
  on it. OpenCode numbers a message's text and reasoning parts independently from
  0, so the old "%s#%d" gave the first text delta and first reasoning part the
  same id: the answer was appended into the thinking block, and the server's
  retained state (chat_hub.go) re-collided on resume. ChatStore's upsert now
  routes a delta through the kind-aware deltaPartId fold, so it stays robust even
  against a peer that still shares one id.
- Tool fields (server + client): NormalizeChatEvent takes a call's arguments from
  session.tool.input.ended's text as well as session.tool.called's input object
  (toolInput), and chat_hub.go's new mergeChatToolPart folds each tool frame onto
  the retained part so the progress/success frames that omit name and input never
  blank them. ChatFormat.kt's mergeToolPart mirrors that on the client, so the
  chip and panel header keep the real tool name and the panel shows INPUT beside
  OUTPUT.

Tests: chat_v2_test.go and chat_test.go add the text/reasoning id-collision and
the tool name+input retention cases; ChatReasoningTurnTest, ChatTranscriptTest
and ChatRunningWorkTest cover the turn fold, the collision and the tool lifecycle.

Checks: Go build, vet, gofmt and the package tests pass (go build ./... &&
go vet ./...; gofmt -l . empty; go test ./internal/server ./internal/opencode
./internal/protocol ./internal/stage ./internal/pipeline; go test ./...).
Android passes offline with --no-daemon (assembleDebug and the full
testDebugUnitTest suite, 660 tests). The on-phone observation was not performed:
the device lock was held by another run and adb was not available here.

Documentation inventory checked: no packaged OpenCode skill reference in
internal/author/skill/references/ and no packaged template documents the app's
chat transcript, this delta part-id derivation or the tool-field retention, and
no internal/author/ managed file inventory entry names any touched file, so none
of them needs updating. The shared android/README.md behaviour statements are
made stale by this change and are recorded instead in
docs/notes/chat-transcript-turn-fold.md for the docs-fold writer, per the repo
rule that an item never edits a shared document itself.
This commit is contained in:
2026-10-18 01:47:52 +01:00
parent 0d1ddc73a4
commit 798e958cb7
14 changed files with 801 additions and 161 deletions
+47 -3
View File
@@ -267,8 +267,8 @@ func chatFrame(kind, delta string, part *protocol.ChatPart, step *protocol.ChatS
func scriptedChat() *fakeChat {
return &fakeChat{script: []protocol.ChatEventFrame{
chatFrame(protocol.ChatEventText, "hello ", &protocol.ChatPart{Type: protocol.ChatPartText, ID: "msg_1#0"}, nil),
chatFrame(protocol.ChatEventText, "world", &protocol.ChatPart{Type: protocol.ChatPartText, ID: "msg_1#0"}, nil),
chatFrame(protocol.ChatEventText, "hello ", &protocol.ChatPart{Type: protocol.ChatPartText, ID: protocol.ChatDeltaPartID("msg_1", protocol.ChatPartText, 0)}, nil),
chatFrame(protocol.ChatEventText, "world", &protocol.ChatPart{Type: protocol.ChatPartText, ID: protocol.ChatDeltaPartID("msg_1", protocol.ChatPartText, 0)}, nil),
chatFrame(protocol.ChatEventTool, "", &protocol.ChatPart{Type: protocol.ChatPartTool, ID: "call_1", Name: "shell", State: &protocol.ChatToolState{Status: protocol.ChatToolCompleted, Input: []byte(`{"command":"ls"}`)}}, nil),
chatFrame(protocol.ChatEventStep, "", nil, &protocol.ChatStep{Status: protocol.ChatStepEnded, Index: 1}),
}}
@@ -451,7 +451,7 @@ func TestChatMessagesResumesRetainedState(t *testing.T) {
if message.ID != "msg_1" || message.Role != protocol.ChatRoleAssistant || len(message.Parts) != 2 {
t.Fatalf("resumed message = %+v", message)
}
if message.Parts[0].Type != protocol.ChatPartText || message.Parts[0].ID != "msg_1#0" || message.Parts[0].Text != "hello world" {
if message.Parts[0].Type != protocol.ChatPartText || message.Parts[0].ID != protocol.ChatDeltaPartID("msg_1", protocol.ChatPartText, 0) || message.Parts[0].Text != "hello world" {
t.Fatalf("resumed text part = %+v", message.Parts[0])
}
if message.Parts[1].Type != protocol.ChatPartTool || message.Parts[1].State == nil || message.Parts[1].State.Status != protocol.ChatToolCompleted {
@@ -895,6 +895,50 @@ func TestChatHubChargesToolStateBytes(t *testing.T) {
}
}
// TestChatHubRetainsToolNameAndInputAcrossLifecycle pins that a tool call keeps
// its name and its input for its whole lifecycle in the retained state a resume
// serves: the name arrives only in input.started, the arguments in input.ended's
// text or called's input, and then progress/success carry neither, so no later
// frame may blank a field the hub already learned.
func TestChatHubRetainsToolNameAndInputAcrossLifecycle(t *testing.T) {
hub := newChatHub()
apply := func(part *protocol.ChatPart) {
hub.apply(protocol.ChatEventFrame{SessionID: "ses_1", MessageID: "msg_1", Kind: protocol.ChatEventTool, Part: part})
}
// input.started: the name, no arguments yet.
apply(&protocol.ChatPart{Type: protocol.ChatPartTool, ID: "call_1", Name: "shell", State: &protocol.ChatToolState{Status: protocol.ChatToolStreaming}})
// input.ended/called: the arguments, no name.
apply(&protocol.ChatPart{Type: protocol.ChatPartTool, ID: "call_1", State: &protocol.ChatToolState{Status: protocol.ChatToolRunning, Input: json.RawMessage(`{"command":"ls"}`)}})
// progress: metadata only.
apply(&protocol.ChatPart{Type: protocol.ChatPartTool, ID: "call_1", State: &protocol.ChatToolState{Status: protocol.ChatToolRunning, Metadata: map[string]any{"exit": 0}}})
// success: the output, no name and no input.
apply(&protocol.ChatPart{Type: protocol.ChatPartTool, ID: "call_1", State: &protocol.ChatToolState{Status: protocol.ChatToolCompleted, Content: []protocol.ChatToolContent{{Type: "text", Text: "ok"}}}})
messages := hub.snapshot("ses_1")
if len(messages) != 1 || len(messages[0].Parts) != 1 {
t.Fatalf("snapshot = %+v", messages)
}
part := messages[0].Parts[0]
if part.Name != "shell" {
t.Fatalf("tool name was blanked by a later frame: %+v", part)
}
if part.State == nil || part.State.Status != protocol.ChatToolCompleted {
t.Fatalf("tool state = %+v", part.State)
}
var input struct {
Command string `json:"command"`
}
if err := json.Unmarshal(part.State.Input, &input); err != nil || input.Command != "ls" {
t.Fatalf("tool input was blanked by a later frame: %s (err %v)", part.State.Input, err)
}
if len(part.State.Content) != 1 || part.State.Content[0].Text != "ok" {
t.Fatalf("tool content = %+v", part.State.Content)
}
if part.State.Metadata["exit"] == nil {
t.Fatalf("tool metadata was blanked by a later frame: %+v", part.State.Metadata)
}
}
// TestChatPromptSubscribesBeforePrompt pins the subscribe-before-prompt order:
// the firehose has no replay cursor, so the subscription must be attached before
// the prompt is posted or deltas emitted in between are lost.