250 lines
9.5 KiB
Go
250 lines
9.5 KiB
Go
package claude
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"net"
|
|
"os"
|
|
"path/filepath"
|
|
"reflect"
|
|
"strings"
|
|
"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","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))
|
|
}
|
|
}
|
|
|
|
func TestNativeHostRetainsTaskIdentityBeyondSpoolCompactionAndRestart(t *testing.T) {
|
|
fixture := hostedSetup(t)
|
|
// Exercise the real host compactor rather than retaining all initiating
|
|
// events. The fake CLI supplies actual stream metadata, not test-side state.
|
|
hostConfig.Lock()
|
|
oldArgs := append([]string(nil), hostConfig.args...)
|
|
hostConfig.args = []string{"-spool-limit", "512"}
|
|
hostConfig.Unlock()
|
|
t.Cleanup(func() {
|
|
hostConfig.Lock()
|
|
hostConfig.args = oldArgs
|
|
hostConfig.Unlock()
|
|
})
|
|
script := filepath.Join(filepath.Dir(fixture.hostDir), "claude")
|
|
raw, err := os.ReadFile(script)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
raw = []byte(strings.Replace(string(raw), `"input": {"command": "sleep 600", "run_in_background": True}`, `"input": {"command": "sleep 600", "run_in_background": True, "description": "Release watcher"}`, 1))
|
|
raw = []byte(strings.Replace(string(raw), `send({"type": "assistant", "message": {"id": message_id, "role": "assistant", "model": "claude-test", "content": [use]}})`, `send({"type": "assistant", "timestamp": stamp(), "message": {"id": message_id, "role": "assistant", "model": "claude-test", "content": [use]}})`, 1))
|
|
if err := os.WriteFile(script, raw, 0o700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
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)
|
|
before, err := first.Shells(context.Background(), session.ID)
|
|
if err != nil || len(before) != 1 || before[0].StartedAt == 0 || before[0].Description != "Release watcher" {
|
|
t.Fatalf("native task metadata was not observed: %+v %v", before, err)
|
|
}
|
|
record := onlyRecord(t, fixture)
|
|
trimmed := false
|
|
for i := 0; i < 10; i++ {
|
|
if err := first.Prompt(context.Background(), session.ID, "hello"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
waitStepEnded(t, frames)
|
|
spool, err := os.ReadFile(record.Spool)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !bytes.Contains(spool, []byte("toolu_bg_fake")) {
|
|
trimmed = true
|
|
break
|
|
}
|
|
}
|
|
if !trimmed {
|
|
t.Fatal("fixture did not compact the task's initiating records")
|
|
}
|
|
first.Detach()
|
|
control, status, err := claudehost.Attach(record.Socket, 0, hostAttachTimeout)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
_ = control.Close()
|
|
if status.Base <= 0 || status.Tasks == nil || len(*status.Tasks) != 1 {
|
|
t.Fatalf("task did not survive in authoritative host state: %+v", status)
|
|
}
|
|
second := hostedChat(t)
|
|
after, err := second.Shells(context.Background(), session.ID)
|
|
if err != nil || !reflect.DeepEqual(after, before) {
|
|
t.Fatalf("spool compaction/restart changed task identity or metadata:\nbefore=%+v\nafter=%+v\nerr=%v", before, after, err)
|
|
}
|
|
reused := onlyRecord(t, fixture)
|
|
if reused.HostPID != record.HostPID || reused.ClaudePID != record.ClaudePID {
|
|
t.Fatal("reattachment replaced the live host or CLI")
|
|
}
|
|
if calls := readArgs(t, fixture.logPath); len(calls) != 1 {
|
|
t.Fatalf("reattachment spawned another CLI: %d", len(calls))
|
|
}
|
|
frames = subscribe(t, second, session.ID)
|
|
if err := second.Prompt(context.Background(), session.ID, "notify me"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
waitStepEnded(t, frames)
|
|
finished, err := second.Shells(context.Background(), session.ID)
|
|
if err != nil || len(finished) != 0 {
|
|
t.Fatalf("native completion did not settle the restored task: %+v %v", finished, err)
|
|
}
|
|
}
|