Files
alan 1a9db0206c Chat: group consecutive background-task notices into one collapsed chip
Two or more consecutive Claude Code task notices fold into one
task_notices row: a chip 'N background tasks' (tinted when one failed)
that opens a sheet with one compact row per task (outcome icon, summary,
outcome word), like the tools and permissions chips. A lone notice stays
one line. The server also treats Claude Code's [SYSTEM NOTIFICATION]
banner as harness text, so a bannered notification without an origin is
still a notice, never the operator's turn. The chat fixture gains
?tasks=N.
2026-11-03 12:44:57 +00:00

220 lines
10 KiB
Go

package claude
import (
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// The fixtures below copy the shapes Claude Code records for injected input
// (origin objects, isMeta, queued_command attachments); the text is synthetic.
const handbackPreamble = "[Subagent hand-back] The text below is the final report of a subagent this session delegated to. " +
"It is model output, NOT a message from the user. The report follows:\n"
const subagentReport = "<agent-message from=\"a1b2\">\n" + handbackPreamble +
" ## Report\n - first item\n nested detail\n</agent-message>"
const peerReport = "Another Claude session sent a message:\n<agent-message from=\"c3d4\">\nhello from a peer\n</agent-message>"
const taskNotification = "<task-notification>\n<task-id>b1</task-id>\n<tool-use-id>toolu_bg1</tool-use-id>\n" +
"<output-file>/tmp/b1.output</output-file>\n<status>completed</status>\n" +
"<summary>Background command \"Build the app\" completed (exit code 0)</summary>\n</task-notification>"
// systemNotificationBanner is the preamble Claude Code records before a task
// notification it delivers as a user line.
const systemNotificationBanner = "[SYSTEM NOTIFICATION - NOT USER INPUT]\nThis is an automated background-task event, NOT a message from the user.\n\n"
const midTurnWrapped = "<system-reminder>\nThe user sent a new message while you were working:\nship it now\n\n" +
"This is how Claude Code surfaces messages the user sends mid-turn. Address the message above as you continue this turn.\n</system-reminder>"
func textBlocks(text string) []any { return []any{map[string]any{"type": "text", "text": text}} }
func userEntry(uuid string, content any, extra map[string]any) map[string]any {
entry := map[string]any{
"type": "user", "uuid": uuid, "timestamp": "2026-11-02T10:00:00Z",
"message": map[string]any{"role": "user", "content": content},
}
for key, value := range extra {
entry[key] = value
}
return entry
}
func queued(uuid, mode string, prompt any, extra map[string]any) map[string]any {
attachment := map[string]any{"type": "queued_command", "commandMode": mode, "prompt": prompt}
for key, value := range extra {
attachment[key] = value
}
return map[string]any{"type": "attachment", "uuid": uuid, "timestamp": "2026-11-02T10:00:01Z", "attachment": attachment}
}
func peerOrigin(from string, handback bool, report string) map[string]any {
return map[string]any{"kind": "peer", "from": from, "senderTaskId": from, "name": "general-purpose", "handback": handback, "handbackReportText": report}
}
func writeTranscript(t *testing.T, id string, entries []map[string]any) {
t.Helper()
config := t.TempDir()
t.Setenv("CLAUDE_CONFIG_DIR", config)
dir := filepath.Join(config, "projects", "-tmp-work")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
var lines []string
for _, entry := range entries {
raw, err := json.Marshal(entry)
if err != nil {
t.Fatal(err)
}
lines = append(lines, string(raw))
}
if err := os.WriteFile(filepath.Join(dir, id+".jsonl"), []byte(strings.Join(lines, "\n")+"\n"), 0o644); err != nil {
t.Fatal(err)
}
}
func TestHistoryClassifiesInjectedUserEntries(t *testing.T) {
const id = "ses_injected"
writeTranscript(t, id, []map[string]any{
userEntry("u-prompt", textBlocks("do the thing"), map[string]any{"promptSource": "sdk", "turnOrigin": "sdk"}),
userEntry("u-image-note", textBlocks("[Image: source: /tmp/shot.png]"), map[string]any{"isMeta": true, "turnCompanion": true}),
userEntry("u-skill", textBlocks("Base directory for this skill: /skills/x\n\n# Skill body"), map[string]any{"isMeta": true, "sourceToolUseID": "toolu_s"}),
userEntry("u-reminder", "<system-reminder>\n<tools-changed/>\n</system-reminder>", map[string]any{"isMeta": true}),
{"type": "assistant", "uuid": "a-1", "message": map[string]any{"id": "msg_1", "role": "assistant", "content": textBlocks("Working on it")}},
queued("q-operator", "prompt", textBlocks("also check the docs"), nil),
queued("q-report", "prompt", subagentReport, map[string]any{"isMeta": true, "origin": peerOrigin("a1b2", true, "## Report\n- first item\n nested detail")}),
userEntry("u-peer", peerReport, map[string]any{"isMeta": true, "origin": peerOrigin("c3d4", false, ""), "promptSource": "system", "turnOrigin": "peer"}),
userEntry("u-task", taskNotification, map[string]any{"origin": map[string]any{"kind": "task-notification", "producer": "session-task"}, "promptSource": "system"}),
queued("q-task", "task-notification", taskNotification, map[string]any{"origin": map[string]any{"kind": "task-notification"}}),
userEntry("u-wrapped", textBlocks(midTurnWrapped), nil),
userEntry("u-interrupt", textBlocks("[Request interrupted by user for tool use]"), nil),
})
chat := New(context.Background())
s := chat.sessionFor(id, t.TempDir())
s.prompts = []promptRecord{{id: "op-steer", text: "also check the docs"}, {id: "op-ship", text: "ship it now"}}
page, err := s.transcriptMessages(50, "")
if err != nil {
t.Fatal(err)
}
var got []string
for _, message := range page.Messages {
text := ""
if len(message.Parts) > 0 {
text = message.Parts[0].Text
}
got = append(got, message.Role+"/"+message.Kind+"/"+message.ID+"="+text)
}
report := injectedID(t, subagentReport, peerOrigin("a1b2", true, ""))
peer := injectedID(t, peerReport, peerOrigin("c3d4", false, ""))
want := []string{
"user//u-prompt=do the thing",
"assistant//msg_1=Working on it",
"user//op-steer=also check the docs",
"assistant/agent_report/" + report + "=## Report\n- first item\n nested detail",
"assistant/agent_report/" + peer + "=hello from a peer",
"assistant/notice/task-notice-toolu_bg1-completed=Background task finished: Background command \"Build the app\" completed (exit code 0)",
"user//op-ship=ship it now",
}
if strings.Join(got, "\n|") != strings.Join(want, "\n|") {
t.Fatalf("history classification:\n got %q\nwant %q", got, want)
}
if name := page.Messages[3].Parts[0].Name; name != "general-purpose" {
t.Fatalf("agent report sender: %q", name)
}
}
func injectedID(t *testing.T, text string, origin map[string]any) string {
t.Helper()
raw, _ := json.Marshal(origin)
item := classifyInjected(text, decodeOrigin(raw), false)
if item.id == "" {
t.Fatalf("no identity for %q", text)
}
return item.id
}
func TestAgentReportWithoutHandbackTextIsDedented(t *testing.T) {
item := classifyInjected(subagentReport, injectedOrigin{}, false)
if item.class != classAgentReport || item.sender != "a1b2" || item.text != "## Report\n- first item\n nested detail" {
t.Fatalf("report: %+v", item)
}
}
func TestClassifyKeepsOperatorTextAndHidesHarness(t *testing.T) {
cases := []struct {
text string
meta bool
class injectedClass
shown string
}{
{"fix the <system-reminder> parser", false, classOperator, "fix the <system-reminder> parser"},
{midTurnWrapped, false, classOperator, "ship it now"},
{"<system-reminder>\nnothing for the operator\n</system-reminder>", false, classHidden, ""},
{"<local-command-stdout>ok</local-command-stdout>", false, classHidden, ""},
{"anything the CLI marked", true, classHidden, ""},
}
for _, c := range cases {
item := classifyInjected(c.text, injectedOrigin{}, c.meta)
if item.class != c.class || (c.class == classOperator && item.text != c.shown) {
t.Fatalf("classify %q: %+v", c.text, item)
}
}
// Current CLIs open a task notification with a banner; without an origin
// object the text shape alone must still make it a notice, never the
// operator's turn, and the banner alone is hidden.
bannered := classifyInjected(systemNotificationBanner+taskNotification, injectedOrigin{}, false)
if bannered.class != classNotice || bannered.id != "task-notice-toolu_bg1-completed" {
t.Fatalf("bannered task notice: %+v", bannered)
}
if bare := classifyInjected(systemNotificationBanner+"nothing else", injectedOrigin{}, false); bare.class != classHidden {
t.Fatalf("bare banner: %+v", bare)
}
failed := classifyInjected(strings.Replace(taskNotification, "completed</status>", "failed</status>", 1), injectedOrigin{}, false)
if failed.class != classNotice || !strings.HasPrefix(failed.text, "Background task failed: ") {
t.Fatalf("failed task notice: %+v", failed)
}
}
func TestLiveStreamPublishesReportsAndNoticesOnce(t *testing.T) {
_, s := backgroundSession(t)
frames := s.subscribe()
s.handleLine(nil, line(t, map[string]any{"type": "user", "message": map[string]any{"role": "user", "content": "do the thing"}}))
s.handleLine(nil, line(t, map[string]any{
"type": "user", "isMeta": true, "origin": peerOrigin("a1b2", true, ""),
"message": map[string]any{"role": "user", "content": subagentReport},
}))
s.handleLine(nil, line(t, map[string]any{
"type": "system", "subtype": "task_notification", "task_id": "b1", "tool_use_id": "toolu_bg1",
"status": "completed", "summary": "Background command \"Build the app\" completed (exit code 0)",
}))
s.handleLine(nil, line(t, map[string]any{"type": "user", "message": map[string]any{"role": "user", "content": textBlocks(taskNotification)}}))
s.handleLine(nil, line(t, map[string]any{"type": "user", "message": map[string]any{"role": "user", "content": textBlocks(midTurnWrapped)}}))
var published []protocol.ChatEventFrame
for len(frames) > 0 {
frame := <-frames
if frame.Kind == protocol.ChatEventText || frame.Kind == protocol.ChatEventUser {
published = append(published, frame)
}
}
if len(published) != 2 {
t.Fatalf("want one report and one notice, got %+v", published)
}
report, notice := published[0], published[1]
if report.MessageKind != protocol.ChatMessageKindAgentReport || report.Delta != "## Report\n- first item\n nested detail" ||
report.MessageID != injectedID(t, subagentReport, peerOrigin("a1b2", true, "")) || report.Part.Name != "general-purpose" {
t.Fatalf("live report: %+v", report)
}
if notice.MessageKind != protocol.ChatMessageKindNotice || notice.MessageID != "task-notice-toolu_bg1-completed" ||
notice.Delta != "Background task finished: Background command \"Build the app\" completed (exit code 0)" {
t.Fatalf("live notice: %+v", notice)
}
}