Files
pipelines/internal/claude/phantom_tasks_test.go
T
alan 64e51ee751 Claude tasks: stop listing finished subagent/foreground calls as running
The host counted any tool_result containing "running in background with ID"
as a launch acknowledgement, so a subagent's foreground `sed` of
fake-claude.py (or translate.go) became a background task that never ends.
A subagent's background command whose completion notification preceded its
launch result was also revived. Both stayed "Running" in the chat for days.

- claudehost: only a Bash/Agent/Task call's own first-line acknowledgement
  starts a task; finished ids are never revived by late acks/progress;
  background_tasks_changed (the CLI's running set) ends unlisted tasks;
  tool output no longer counts as a task notification.
- claude: same strict acknowledgement; background_tasks_changed settles
  tracked tasks; on reattach, host tasks without a native id are checked
  against the main and subagent transcripts, so phantoms from hosts still
  running the old build disappear.
- Fake CLI "subagent" turn and regression tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 00:27:50 +00:00

125 lines
6.4 KiB
Go

package claude
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/claudehost"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// Seen live: a subagent's foreground `sed -n 1,230p fake-claude.py` printed
// the fixture's "Command running in background with ID" line, so the host
// listed it as a background task forever ("Running 1d 20h, no output yet").
// The fake CLI streams a background subagent whose own calls (that sed, and a
// background command completed before its launch result) are sidechain lines.
func TestSubagentToolCallsAreNotOperatorBackgroundTasks(t *testing.T) {
fixture := hostedSetup(t)
first := hostedChat(t)
session := newCreatedChat(t, first)
frames := subscribe(t, first, session.ID)
if err := first.Prompt(context.Background(), session.ID, "subagent please"); err != nil {
t.Fatal(err)
}
waitStepEnded(t, frames)
onlyAgent := func(shells []protocol.ChatShell, err error) bool {
return err == nil && len(shells) == 1 && shells[0].ID == shellID("toolu_agent_fake")
}
if shells, err := first.Shells(context.Background(), session.ID); !onlyAgent(shells, err) {
t.Fatalf("the background agent alone is running: %+v %v", shells, err)
}
record := onlyRecord(t, fixture)
first.Detach()
control, status, err := claudehost.Attach(record.Socket, 0, hostAttachTimeout)
if err != nil {
t.Fatal(err)
}
_ = control.Close()
if status.Tasks == nil || len(*status.Tasks) != 1 || (*status.Tasks)[0].ToolUseID != "toolu_agent_fake" {
t.Fatalf("host lists subagent tool calls as running tasks: %+v", status.Tasks)
}
second := hostedChat(t)
if shells, err := second.Shells(context.Background(), session.ID); !onlyAgent(shells, err) {
t.Fatalf("reattached task list changed: %+v %v", shells, err)
}
frames = subscribe(t, second, session.ID)
if err := second.Prompt(context.Background(), session.ID, "agent-done"); err != nil {
t.Fatal(err)
}
waitStepEnded(t, frames)
if shells, err := second.Shells(context.Background(), session.ID); err != nil || len(shells) != 0 {
t.Fatalf("finished agent still listed: %+v %v", shells, err)
}
}
// Hosts already running an older build keep phantom entries (no native task
// id). Reattaching settles each from the transcripts — the main one and the
// subagents' — while a genuine background command still shows until it ends.
func TestReattachSettlesLegacyPhantomTasksFromTranscripts(t *testing.T) {
config := t.TempDir()
t.Setenv("CLAUDE_CONFIG_DIR", config)
chat, s := backgroundSession(t)
t.Cleanup(chat.Close)
project := filepath.Join(config, "projects", "-repo")
write := func(path string, lines ...string) {
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil {
t.Fatal(err)
}
}
write(filepath.Join(project, s.id+".jsonl"),
`{"type":"assistant","isSidechain":false,"message":{"content":[{"type":"tool_use","id":"main-bg","name":"Bash","input":{"command":"sleep 600","run_in_background":true}}]}}`,
`{"type":"user","isSidechain":false,"message":{"content":[{"type":"tool_result","tool_use_id":"main-bg","content":"Command running in background with ID: b9. Output is being written to: /tmp/b9.output"}]}}`,
`{"type":"assistant","isSidechain":false,"message":{"content":[{"type":"tool_use","id":"main-cat","name":"Bash","input":{"command":"cat translate.go"}}]}}`,
`{"type":"user","isSidechain":false,"message":{"content":[{"type":"tool_result","tool_use_id":"main-cat","content":[{"type":"text","text":"func launched() {\n\treturn \"running in background with ID\"\n}"}]}]}}`,
)
write(filepath.Join(project, s.id, "subagents", "agent-a1.jsonl"),
`{"type":"assistant","isSidechain":true,"message":{"content":[{"type":"tool_use","id":"sub-sed","name":"Bash","input":{"command":"sed -n 1,230p internal/claude/testdata/fake-claude.py"}}]}}`,
`{"type":"user","isSidechain":true,"message":{"content":[{"type":"tool_result","tool_use_id":"sub-sed","content":"#!/usr/bin/env python3\n\"content\": \"Command running in background with ID: b1.\""}]}}`,
`{"type":"user","isSidechain":true,"message":{"content":[{"type":"tool_result","tool_use_id":"sub-xvfb","content":"Command running in background with ID: bz. Output is being written to: /tmp/bz.output"}]}}`,
`{"type":"attachment","isSidechain":true,"attachment":{"type":"queued_command","prompt":"<task-notification>\n<task-id>bz</task-id>\n<tool-use-id>sub-xvfb</tool-use-id>\n<status>completed</status>\n</task-notification>"}}`,
)
legacy := []claudehost.Task{
{ToolUseID: "main-bg", Name: "Bash", Command: "sleep 600"},
{ToolUseID: "main-cat", Name: "Bash", Command: "cat translate.go"},
{ToolUseID: "sub-sed", Name: "Bash", Command: "sed -n 1,230p internal/claude/testdata/fake-claude.py"},
{ToolUseID: "sub-xvfb", Name: "Bash", Command: "Xvfb :99 &"},
}
s.reconcileHostTasks(&legacy)
shells := running(t, chat)
if len(shells) != 1 || shells[0].ID != shellID("main-bg") {
t.Fatalf("only the genuine background command is running: %+v", shells)
}
}
func TestBackgroundTasksChangedSettlesUnlistedTasks(t *testing.T) {
chat, s := backgroundSession(t)
t.Cleanup(chat.Close)
for _, id := range []string{"a", "b"} {
s.handleLine(nil, toolUse(t, "tool-"+id, "Bash", map[string]any{"command": "sleep 600", "run_in_background": true}))
s.handleLine(nil, []byte(`{"type":"system","subtype":"task_started","task_id":"native-`+id+`","tool_use_id":"tool-`+id+`"}`))
s.handleLine(nil, toolResult(t, "tool-"+id, "Command running in background with ID: native-"+id))
}
s.handleLine(nil, []byte(`{"type":"system","subtype":"background_tasks_changed","tasks":[{"task_id":"native-b"}]}`))
if shells := running(t, chat); len(shells) != 1 || shells[0].ID != shellID("tool-b") {
t.Fatalf("unlisted task still running: %+v", shells)
}
}
// A foreground subagent's report (its tool_result) may quote a launch
// acknowledgement; only the result's first line acknowledges a launch.
func TestForegroundAgentReportQuotingLaunchFinishes(t *testing.T) {
chat, s := backgroundSession(t)
t.Cleanup(chat.Close)
s.handleLine(nil, toolUse(t, "sync-agent", "Agent", map[string]any{"description": "Review"}))
s.handleLine(nil, toolResult(t, "sync-agent", "Root cause: the host matched\n\"Command running in background with ID\" anywhere in output."))
if shells := running(t, chat); len(shells) != 0 {
t.Fatalf("finished foreground agent still running: %+v", shells)
}
}