package claude import ( "context" "encoding/json" "net" "os" "path/filepath" "reflect" "sync" "syscall" "testing" "time" "git.a-wan.net/alan/pipelines/internal/claudehost" "git.a-wan.net/alan/pipelines/internal/protocol" ) func TestHostTaskSnapshotDistinguishesLegacyUnknownFromKnownIdle(t *testing.T) { chat, s := backgroundSession(t) t.Cleanup(chat.Close) s.handleLine(nil, toolUse(t, "native-tool", "Bash", map[string]any{"command": "sleep 600", "run_in_background": true})) s.reconcileHostTasks(nil) if shells := running(t, s.chat); len(shells) != 1 { t.Fatalf("legacy unknown must preserve task liveness: %+v", shells) } empty := []claudehost.Task{} s.reconcileHostTasks(&empty) if shells := running(t, s.chat); len(shells) != 0 { t.Fatalf("authoritative idle must settle replayed background state: %+v", shells) } for _, source := range []string{`{}`, `{"tasks":[]}`} { var status claudehost.Status if err := json.Unmarshal([]byte(source), &status); err != nil { t.Fatal(err) } if (status.Tasks == nil) != (source == `{}`) { t.Fatalf("capability presence was lost: %s %+v", source, status.Tasks) } } } func TestReattachRestoresTasksAfterTheirStartWasTrimmed(t *testing.T) { base, err := os.MkdirTemp("/tmp", "pct") if err != nil { t.Fatal(err) } defer os.RemoveAll(base) socket := filepath.Join(base, "host.sock") listener, err := net.Listen("unix", socket) if err != nil { t.Fatal(err) } defer listener.Close() current := []claudehost.Task{{ToolUseID: "native-bg", TaskID: "task-17", Name: "Bash", Command: "sleep 600", Description: "Wait for release", TaskType: "shell", Timestamp: "2026-10-22T12:00:00Z"}} status := claudehost.Status{SessionID: "trimmed-session", Base: 2000, Acked: 2000, End: 2300, Init: json.RawMessage(`{"models":[{"value":"fixture-model"}]}`), Tasks: ¤t} notify := make(chan struct{}) stop := make(chan struct{}) var stopOnce sync.Once stopServer := func() { stopOnce.Do(func() { close(stop) }) } defer stopServer() serverDone := make(chan struct{}) go func() { defer close(serverDone) conn, err := listener.Accept() if err != nil { return } defer conn.Close() var attach claudehost.Frame if json.NewDecoder(conn).Decode(&attach) != nil { return } out := json.NewEncoder(conn) _ = out.Encode(claudehost.Frame{Op: claudehost.OpStatus, Status: &status}) // The actual running task's initiating line is older than Base. The // retained spool contains a different, already-finished async tool. _ = out.Encode(claudehost.Frame{Op: claudehost.OpOut, Offset: 2000, End: 2100, Data: json.RawMessage(`{"type":"assistant","message":{"id":"historic","content":[{"type":"tool_use","id":"finished-tool","name":"Bash","input":{"command":"old job","run_in_background":true}}]}}`)}) _ = out.Encode(claudehost.Frame{Op: claudehost.OpOut, Offset: 2100, End: 2300, Data: json.RawMessage(`{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"finished-tool","content":"Command running in background with ID: old"}]}}`)}) select { case <-notify: _ = out.Encode(claudehost.Frame{Op: claudehost.OpOut, Offset: 2300, End: 2400, Data: json.RawMessage(`{"type":"system","subtype":"task_notification","tool_use_id":"native-bg","task_id":"task-17","status":"completed","summary":"Finished"}`)}) case <-stop: return } <-stop }() chat := newChat(context.Background()) defer chat.Close() p, conn, plan := chat.connectHost(claudehost.Record{SessionID: status.SessionID, Socket: socket}) if p == nil { t.Fatal("fixture host did not attach") } s := p.session s.mu.Lock() s.proc = p s.mu.Unlock() go p.readHost(conn, plan) ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() shells, err := chat.Shells(ctx, status.SessionID) if err != nil || len(shells) != 1 { t.Fatalf("restore authoritative native set after replay: %+v %v", shells, err) } want := protocol.ChatShell{ID: shellID("native-bg"), Status: protocol.ChatShellRunning, Command: "sleep 600", Description: "Wait for release", TaskType: "shell", StartedAt: time.Date(2026, 10, 22, 12, 0, 0, 0, time.UTC).UnixMilli()} if !reflect.DeepEqual(shells[0], want) { t.Fatalf("native identity and metadata changed:\n got %+v\nwant %+v", shells[0], want) } close(notify) eventually(t, "the restored task to finish under its original native id", func() bool { shells, _ := chat.Shells(ctx, status.SessionID) return len(shells) == 0 }) p.detach() stopServer() <-serverDone } func TestLiveUnresponsiveHostSurvivesAttachFailureWithoutDuplicateCLI(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, "background please"); err != nil { t.Fatal(err) } waitStepEnded(t, frames) record := onlyRecord(t, fixture) first.Detach() if err := syscall.Kill(record.HostPID, syscall.SIGSTOP); err != nil { t.Fatal(err) } defer syscall.Kill(record.HostPID, syscall.SIGCONT) after := newChat(context.Background()) defer after.Close() if p, _, _ := after.connectHost(record); p != nil { t.Fatal("a stopped fixture host unexpectedly answered") } if !alive(record.HostPID) || !alive(record.ClaudePID) { t.Fatal("control timeout killed live work") } if _, err := os.Stat(claudehost.PathsFor(fixture.hostDir, record.SessionID).Record); err != nil { t.Fatalf("live registration removed: %v", err) } s := after.sessionFor(session.ID, session.Directory) if _, err := s.startHosted(context.Background(), []string{"--session-id", session.ID}, "", nil); err == nil { t.Fatal("live unavailable session accepted a duplicate CLI start") } if err := syscall.Kill(record.HostPID, syscall.SIGCONT); err != nil { t.Fatal(err) } if !after.attachHost(record) { t.Fatal("same host could not reconnect after it became responsive") } shells, err := after.Shells(context.Background(), session.ID) if err != nil || len(shells) != 1 || shells[0].ID != shellID("toolu_bg_fake") { t.Fatalf("reattachment changed running task: %+v %v", shells, err) } if spawns := readArgs(t, fixture.logPath); len(spawns) != 1 { t.Fatalf("a control failure spawned a replacement CLI: %d", len(spawns)) } }