Observe native Claude automations and preserve pending timers
This commit is contained in:
@@ -0,0 +1,143 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/claudehost"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
type automationInput struct{ bytes.Buffer }
|
||||
|
||||
func (*automationInput) Close() error { return nil }
|
||||
|
||||
func TestAutomationCallbacksAcknowledgeUnknownMetadataAndPreserveUnsupported(t *testing.T) {
|
||||
c := newChat(context.Background())
|
||||
defer c.cancel()
|
||||
s := c.sessionFor("callback-cron", t.TempDir())
|
||||
p := newProcess(s, "")
|
||||
s.proc = p
|
||||
input := &automationInput{}
|
||||
p.stdin = input
|
||||
call := func(id string, metadata map[string]any) map[string]any {
|
||||
input.Reset()
|
||||
request, _ := json.Marshal(map[string]any{"subtype": "hook_callback", "callback_id": id, "input": metadata})
|
||||
s.handleControlRequest(p, lineEnvelope{RequestID: "hook", Request: request})
|
||||
var response struct {
|
||||
Response map[string]any `json:"response"`
|
||||
}
|
||||
if err := json.Unmarshal(input.Bytes(), &response); err != nil {
|
||||
t.Fatal("callback was not acknowledged:", err)
|
||||
}
|
||||
return response.Response
|
||||
}
|
||||
metadata := map[string]any{"session_id": s.id, "hook_event_name": "Stop", "session_crons": []map[string]string{{"id": "timer"}}}
|
||||
if r := call(claudehost.NativeAutomationCallbackID, metadata); r["subtype"] != "success" || s.automations == nil {
|
||||
t.Fatalf("native observation failed: %+v", r)
|
||||
}
|
||||
delete(metadata, "session_crons")
|
||||
if r := call(claudehost.NativeAutomationCallbackID, metadata); r["subtype"] != "success" || s.automations != nil {
|
||||
t.Fatalf("absent metadata retained stale count or delayed ACK: %+v", r)
|
||||
}
|
||||
if r := call("unrelated-sdk-hook", metadata); r["subtype"] != "error" {
|
||||
t.Fatalf("unrelated callback lost prior unsupported response: %+v", r)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeAutomationsPreventIdleAndExcessProcessReaping(t *testing.T) {
|
||||
c := newChat(context.Background())
|
||||
defer c.cancel()
|
||||
for i := range maxLiveProcesses + 1 {
|
||||
s := c.sessionFor(string(rune('a'+i)), t.TempDir())
|
||||
p := newProcess(s, "")
|
||||
s.proc, s.automationProcess = p, p
|
||||
s.automations = &claudehost.AutomationSnapshot{SessionID: s.id, IDs: []string{"timer"}, ObservedAtMS: 123}
|
||||
s.lastUsed = time.Now().Add(-2 * idleProcessExpiry)
|
||||
}
|
||||
c.reapIdleAt(time.Now())
|
||||
for _, s := range c.sessions {
|
||||
if s.proc == nil {
|
||||
t.Fatal("native future work was reaped as idle or excess")
|
||||
}
|
||||
before := s.proc
|
||||
s.releaseIdleProcess()
|
||||
if s.proc != before {
|
||||
t.Fatal("idle release bypassed native automation retention")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationReadRejectsDeadAndReplacedDirectProcesses(t *testing.T) {
|
||||
c := newChat(context.Background())
|
||||
defer c.cancel()
|
||||
s := c.sessionFor("direct-cron", t.TempDir())
|
||||
p := newProcess(s, "")
|
||||
s.proc, s.automationProcess = p, p
|
||||
s.automations = &claudehost.AutomationSnapshot{SessionID: s.id, IDs: []string{"timer"}, ObservedAtMS: 123}
|
||||
info, err := c.Automations(context.Background(), s.id)
|
||||
if err != nil || info.ActiveCount == nil || *info.ActiveCount != 1 {
|
||||
t.Fatalf("live native snapshot: %+v, %v", info, err)
|
||||
}
|
||||
for _, state := range []string{"exited", "missing", "replacement"} {
|
||||
s.proc = p
|
||||
p.exited = state == "exited"
|
||||
if state == "missing" {
|
||||
s.proc = nil
|
||||
} else if state == "replacement" {
|
||||
s.proc = newProcess(s, "")
|
||||
}
|
||||
info, err = c.Automations(context.Background(), s.id)
|
||||
if err != nil || info.Status != protocol.ChatAutomationUnavailable || info.ActiveCount != nil {
|
||||
t.Fatalf("%s process reused stale timers: %+v, %v", state, info, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationRecordFallbackRejectsExitedHost(t *testing.T) {
|
||||
dir, err := os.MkdirTemp("/tmp", "pcron")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.RemoveAll(dir)
|
||||
id := "exited-cron"
|
||||
socket := filepath.Join(dir, "fixture.sock")
|
||||
listener, err := net.Listen("unix", socket)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
record, _ := json.Marshal(claudehost.Record{SessionID: id, Socket: socket})
|
||||
if err := os.WriteFile(claudehost.PathsFor(dir, id).Record, record, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
conn, err := listener.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
var request claudehost.Frame
|
||||
_ = json.NewDecoder(conn).Decode(&request)
|
||||
_ = json.NewEncoder(conn).Encode(claudehost.Frame{Op: claudehost.OpStatus, Status: &claudehost.Status{
|
||||
SessionID: id, Exited: true,
|
||||
Automations: &claudehost.AutomationSnapshot{SessionID: id, IDs: []string{"dead"}, ObservedAtMS: 123},
|
||||
}})
|
||||
}()
|
||||
c := newChat(context.Background())
|
||||
defer c.cancel()
|
||||
c.hostDir = dir
|
||||
info, err := c.Automations(context.Background(), id)
|
||||
if err != nil || info.Status != protocol.ChatAutomationUnavailable || info.ActiveCount != nil {
|
||||
t.Fatalf("exited host reused a stale native snapshot: %+v, %v", info, err)
|
||||
}
|
||||
<-done
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/claudehost"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// Automations reports only the last native Stop-hook snapshot. It never starts
|
||||
// or resumes Claude, sends a prompt, or attaches a delivery reader.
|
||||
func (c *Chat) Automations(ctx context.Context, sessionID string) (protocol.ChatAutomationInfo, error) {
|
||||
info := protocol.ChatAutomationInfo{SessionID: sessionID, Provider: Backend, Status: protocol.ChatAutomationUnavailable,
|
||||
Reason: "Claude Code has not reported a native Stop snapshot for this session"}
|
||||
if sessionID == "" {
|
||||
return info, nil
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
var snapshot *claudehost.AutomationSnapshot
|
||||
var socket string
|
||||
direct := false
|
||||
s := c.session(sessionID)
|
||||
if s != nil {
|
||||
s.mu.Lock()
|
||||
p := s.proc
|
||||
cached := s.automations
|
||||
cachedProcess := s.automationProcess
|
||||
s.mu.Unlock()
|
||||
if p == nil || cachedProcess != p || processExited(p) {
|
||||
cached = nil
|
||||
}
|
||||
if p != nil && p.link != nil {
|
||||
socket = p.link.record.Socket
|
||||
} else if p != nil {
|
||||
direct = true
|
||||
snapshot = cached
|
||||
}
|
||||
}
|
||||
if socket == "" && !direct && c.hostDir != "" {
|
||||
path := claudehost.PathsFor(c.hostDir, sessionID).Record
|
||||
if data, err := os.ReadFile(path); err == nil {
|
||||
var record claudehost.Record
|
||||
if json.Unmarshal(data, &record) == nil && record.SessionID == sessionID && record.Socket != "" {
|
||||
socket = record.Socket
|
||||
}
|
||||
}
|
||||
}
|
||||
if socket != "" {
|
||||
statusCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
status, err := claudehost.ReadStatus(statusCtx, socket)
|
||||
cancel()
|
||||
if err == nil && status != nil && !status.Exited && status.SessionID == sessionID {
|
||||
snapshot = status.Automations
|
||||
}
|
||||
}
|
||||
if snapshot == nil || snapshot.SessionID != sessionID || snapshot.ObservedAtMS <= 0 {
|
||||
return info, nil
|
||||
}
|
||||
count := len(snapshot.IDs)
|
||||
info.Status, info.ActiveCount, info.ObservedAtMS = protocol.ChatAutomationSupported, &count, snapshot.ObservedAtMS
|
||||
info.Reason = "last native Claude Code Stop snapshot; not a live query"
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// Native future wakeups are live work even while no model turn is running.
|
||||
// A replacement process cannot inherit its predecessor's in-memory timers.
|
||||
// The caller holds s.mu.
|
||||
func (s *session) hasAutomationsLocked() bool {
|
||||
return s.proc != nil && s.automationProcess == s.proc &&
|
||||
s.automations != nil && len(s.automations.IDs) > 0
|
||||
}
|
||||
|
||||
func processExited(p *process) bool {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
return p.exited
|
||||
}
|
||||
@@ -90,20 +90,6 @@ func (c *Chat) Sessions(ctx context.Context) ([]protocol.ChatSession, error) {
|
||||
return sessions, nil
|
||||
}
|
||||
|
||||
// Automations reports Claude Code's current limitation honestly. Claude's
|
||||
// scheduled-task metadata is emitted through stop-hook/task events, but the
|
||||
// installed control protocol has no authoritative read-only session schedule
|
||||
// operation. Starting a process or inspecting transcripts would not establish
|
||||
// the current schedule set, so this method never does either.
|
||||
func (c *Chat) Automations(ctx context.Context, sessionID string) (protocol.ChatAutomationInfo, error) {
|
||||
return protocol.ChatAutomationInfo{
|
||||
SessionID: sessionID,
|
||||
Provider: Backend,
|
||||
Status: protocol.ChatAutomationUnavailable,
|
||||
Reason: "Claude Code exposes scheduled-task metadata through events, but no authoritative read-only session schedule API is available",
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *session) chatSessionLocked() protocol.ChatSession {
|
||||
model := s.modelActual
|
||||
if model == "" {
|
||||
|
||||
@@ -288,7 +288,7 @@ func (c *Chat) reapIdleAt(now time.Time) {
|
||||
sort.Slice(live, func(i, j int) bool { return live[i].used.Before(live[j].used) })
|
||||
for _, entry := range live {
|
||||
entry.s.mu.Lock()
|
||||
busy := entry.s.running
|
||||
busy := entry.s.running || entry.s.hasAutomationsLocked()
|
||||
for _, task := range entry.s.shells {
|
||||
if task.shell.Status == protocol.ChatShellRunning {
|
||||
busy = true
|
||||
@@ -352,8 +352,10 @@ type session struct {
|
||||
shellTranscriptMtime int64
|
||||
shellTranscriptTargets map[string]bool
|
||||
|
||||
usage *protocol.ChatEventFrame
|
||||
compaction *protocol.ChatEventFrame
|
||||
usage *protocol.ChatEventFrame
|
||||
compaction *protocol.ChatEventFrame
|
||||
automations *claudehost.AutomationSnapshot
|
||||
automationProcess *process
|
||||
// account is the signed-in account the live process reported.
|
||||
account accountIdentity
|
||||
prompts []promptRecord
|
||||
@@ -471,7 +473,7 @@ func (s *session) unsubscribe(ch chan protocol.ChatEventFrame) {
|
||||
// an explicit operator close remains the hard-close path below.
|
||||
func (s *session) releaseIdleProcess() {
|
||||
s.mu.Lock()
|
||||
if s.running || len(s.subs) > 0 {
|
||||
if s.running || len(s.subs) > 0 || s.hasAutomationsLocked() {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -249,6 +249,7 @@ func (c *Chat) connectHostContext(ctx context.Context, record claudehost.Record)
|
||||
p.link.tasksIncomplete.Store(status.Tasks == nil && status.Base > 0)
|
||||
p.stderr.WriteString(status.Stderr)
|
||||
p.models, p.account, p.appliedModel = models, account, status.Model
|
||||
p.automations = status.Automations
|
||||
plan := replayPlan{base: status.Base, silentUntil: status.Acked, catchUpEnd: status.End, pending: map[string]bool{}, busyAtAcked: status.BusyAtAcked, restore: true, tasks: status.Tasks}
|
||||
for _, pending := range status.Pending {
|
||||
plan.pending[pending.ID] = true
|
||||
@@ -267,6 +268,10 @@ func (c *Chat) connectHostContext(ctx context.Context, record claudehost.Record)
|
||||
func (s *session) adoptLocked(p *process) {
|
||||
s.models, s.account = p.models, p.account
|
||||
s.appliedModel = p.appliedModel
|
||||
if p.automations != nil {
|
||||
s.automations = p.automations
|
||||
s.automationProcess = p
|
||||
}
|
||||
if s.model == "" {
|
||||
s.model = p.appliedModel
|
||||
}
|
||||
|
||||
@@ -62,6 +62,7 @@ type process struct {
|
||||
models []protocol.ChatModel
|
||||
account accountIdentity
|
||||
appliedModel string
|
||||
automations *claudehost.AutomationSnapshot
|
||||
}
|
||||
|
||||
func newProcess(s *session, mode string) *process {
|
||||
@@ -192,7 +193,12 @@ func (s *session) startDirect(args []string, mode string, env []string) (*proces
|
||||
}
|
||||
|
||||
func (p *process) initialize(ctx context.Context) ([]protocol.ChatModel, accountIdentity, error) {
|
||||
raw, err := p.request(ctx, "initialize", map[string]any{"subtype": "initialize"})
|
||||
raw, err := p.request(ctx, "initialize", map[string]any{
|
||||
"hooks": map[string]any{"Stop": []any{map[string]any{
|
||||
"hookCallbackIds": []string{claudehost.NativeAutomationCallbackID},
|
||||
"timeout": 5, "onFailure": "continue",
|
||||
}}},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, accountIdentity{}, fmt.Errorf("initialize Claude Code: %w%s", err, p.diagnostic())
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/claudehost"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
@@ -69,6 +70,7 @@ type messageBody struct {
|
||||
|
||||
type toolRequest struct {
|
||||
Subtype string `json:"subtype"`
|
||||
CallbackID string `json:"callback_id"`
|
||||
ToolName string `json:"tool_name"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Description string `json:"description"`
|
||||
@@ -174,7 +176,22 @@ func (s *session) handleControlRequest(p *process, envelope lineEnvelope) {
|
||||
switch request.Subtype {
|
||||
case "can_use_tool":
|
||||
s.receivePermission(p, envelope.RequestID, request)
|
||||
case "hook_callback", "mcp_message":
|
||||
case "hook_callback":
|
||||
if !claudehost.IsAutomationHook(request.CallbackID) {
|
||||
s.respondUnsupported(p, envelope.RequestID)
|
||||
return
|
||||
}
|
||||
snapshot, _ := claudehost.ParseAutomationHook(request.CallbackID, s.id, request.Input, time.Now().UnixMilli())
|
||||
s.mu.Lock()
|
||||
s.automations = snapshot
|
||||
s.automationProcess = p
|
||||
s.mu.Unlock()
|
||||
// A detachable host observes and acknowledges its own callback before
|
||||
// the server is involved. Direct processes need the adapter response.
|
||||
if p.link == nil {
|
||||
_ = p.respond(envelope.RequestID, map[string]any{})
|
||||
}
|
||||
case "mcp_message":
|
||||
s.respondUnsupported(p, envelope.RequestID)
|
||||
default:
|
||||
s.respondUnsupported(p, envelope.RequestID)
|
||||
|
||||
Reference in New Issue
Block a user