Expose session-owned chat automation metadata

This commit is contained in:
2026-11-08 15:24:23 +00:00
parent cecfa39aac
commit 9d3358be47
12 changed files with 413 additions and 0 deletions
+14
View File
@@ -90,6 +90,20 @@ 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 == "" {
+77
View File
@@ -400,6 +400,83 @@ func (c *Chat) Sessions(ctx context.Context) ([]protocol.ChatSession, error) {
return decodeChatSessions(data)
}
// Automations reads the documented OpenCode experimental schedule surface. The
// endpoint is session-scoped by query parameter; the decoder still requires an
// exact sessionID match before counting anything. The older serve backend has
// no schedule API, so it reports unavailable without making a guessed request.
func (c *Chat) Automations(ctx context.Context, sessionID string) (protocol.ChatAutomationInfo, error) {
info := protocol.ChatAutomationInfo{SessionID: sessionID, Provider: "opencode"}
if !ValidSessionID(sessionID) {
return info, fmt.Errorf("invalid OpenCode session id")
}
if c == nil || c.conn == nil || c.conn.Backend == "v1" {
info.Status = protocol.ChatAutomationUnavailable
info.Reason = "this OpenCode backend does not expose the experimental schedule read API"
return info, nil
}
readCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
data, err := c.call(readCtx, "get", "/api/experimental/schedule?sessionID="+url.QueryEscape(sessionID), nil)
if err != nil {
if strings.Contains(err.Error(), "HTTP 404") || strings.Contains(err.Error(), "HTTP 405") {
info.Status = protocol.ChatAutomationUnavailable
info.Reason = "this OpenCode endpoint does not expose the experimental schedule read API"
return info, nil
}
return info, err
}
entries, err := decodeScheduleInfos(data)
if err != nil {
return info, err
}
count := 0
for _, entry := range entries {
if entry.SessionID == sessionID && entry.Status == "active" {
count++
}
}
info.Status = protocol.ChatAutomationSupported
info.ActiveCount = &count
return info, nil
}
type scheduleInfo struct {
SessionID string `json:"sessionID"`
Status string `json:"status"`
}
// decodeScheduleInfos accepts the documented array and the API's common data
// envelope, but rejects null/malformed bodies so a bad response never becomes a
// false empty count.
func decodeScheduleInfos(data []byte) ([]scheduleInfo, error) {
var entries []scheduleInfo
if err := json.Unmarshal(data, &entries); err == nil && entries != nil {
if err := validateScheduleInfos(entries); err != nil {
return nil, err
}
return entries, nil
}
var envelope struct {
Data []scheduleInfo `json:"data"`
}
if err := json.Unmarshal(data, &envelope); err != nil || envelope.Data == nil {
return nil, fmt.Errorf("invalid OpenCode schedule response")
}
if err := validateScheduleInfos(envelope.Data); err != nil {
return nil, err
}
return envelope.Data, nil
}
func validateScheduleInfos(entries []scheduleInfo) error {
for _, entry := range entries {
if entry.SessionID == "" || entry.Status == "" {
return fmt.Errorf("invalid OpenCode schedule response")
}
}
return nil
}
// Create creates one OpenCode session in the given directory, mirroring the
// verified V2 shape POST /api/session {"title":...,"location":{"directory":...}}.
// It deliberately sends no model or permission override here: the endpoint's own
@@ -0,0 +1,51 @@
package opencode
import (
"context"
"net/http"
"net/http/httptest"
"testing"
)
func TestDecodeScheduleInfos(t *testing.T) {
tests := []struct {
name string
raw string
want int
}{
{name: "array", raw: `[{"sessionID":"ses_a","status":"active"},{"sessionID":"ses_b","status":"done"}]`, want: 2},
{name: "data envelope", raw: `{"data":[{"sessionID":"ses_a","status":"active"}]}`, want: 1},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got, err := decodeScheduleInfos([]byte(test.raw))
if err != nil || len(got) != test.want {
t.Fatalf("decodeScheduleInfos = %#v, %v", got, err)
}
})
}
}
func TestDecodeScheduleInfosRejectsMalformedOrNull(t *testing.T) {
for _, raw := range []string{`{}`, `null`, `not-json`, `[{"status":"active"}]`} {
if _, err := decodeScheduleInfos([]byte(raw)); err == nil {
t.Fatalf("decodeScheduleInfos(%q) accepted malformed response", raw)
}
}
}
func TestChatAutomationsReadsOnlyActiveSessionSchedules(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/experimental/schedule" || r.URL.Query().Get("sessionID") != "ses_a" {
t.Fatalf("schedule request = %s?%s", r.URL.Path, r.URL.RawQuery)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":[{"sessionID":"ses_a","status":"active"},{"sessionID":"ses_a","status":"paused"},{"sessionID":"ses_b","status":"active"}]}`))
}))
defer server.Close()
info, err := NewChat(&Connection{Backend: "v2", URL: server.URL}).Automations(context.Background(), "ses_a")
if err != nil || info.Status != "supported" || info.ActiveCount == nil || *info.ActiveCount != 1 {
t.Fatalf("Automations = %+v, %v", info, err)
}
}
+20
View File
@@ -126,6 +126,10 @@ const (
// carries ChatAttachmentImageContent. Only regular image files inside the
// server's private chat attachment store are served.
ChatAttachmentImage = "chat_attachment_image"
// ChatAutomations reads provider-owned scheduled work for one operator chat.
// It is deliberately read-only; providers that cannot authoritatively expose
// this information return an unavailable status instead of an empty count.
ChatAutomations = "chat_automations"
// ChatEvent and ChatPermission are the server-pushed frames; they are the
// only types the server sends without a matching request.
ChatEvent = "chat_event"
@@ -141,6 +145,22 @@ const (
ChatPermission = "chat_permission"
)
const (
ChatAutomationSupported = "supported"
ChatAutomationUnavailable = "unavailable"
)
// ChatAutomationInfo is the bounded, per-session scheduled-work snapshot. A
// nil ActiveCount means the provider could not authoritatively report a count;
// zero is reserved for a supported provider with no active schedules.
type ChatAutomationInfo struct {
SessionID string `json:"session_id"`
Provider string `json:"provider"`
Status string `json:"status"`
ActiveCount *int `json:"active_count,omitempty"`
Reason string `json:"reason,omitempty"`
}
// Content part types carried by ChatPart.Type and ChatEvent.Kind.
const (
ChatPartText = "text"
+3
View File
@@ -270,6 +270,9 @@ type Message struct {
// ChatAttachmentImage its reply.
ChatAttachmentImageRequest *ChatAttachmentImageRequest `json:"chat_attachment_image_request,omitempty"`
ChatAttachmentImage *ChatAttachmentImageContent `json:"chat_attachment_image,omitempty"`
// ChatAutomations is the provider-owned scheduled-work readback for one
// operator session. ActiveCount is omitted when the count is unknown.
ChatAutomations *ChatAutomationInfo `json:"chat_automations,omitempty"`
// RunEvent is the server-pushed run state delta (see runevents.go) and
// RunIDs the optional subscribe scope, so a client asks for the runs it
// displays. Both are optional so older peers ignore them.
+10
View File
@@ -85,6 +85,13 @@ type chatShellOutputReader interface {
ShellOutput(ctx context.Context, query protocol.ChatShellOutputQuery) (protocol.ChatShellOutputPage, error)
}
// chatAutomationReader is optional so every broker and test fake does not need
// to grow a scheduler-shaped interface. Implementations must read only
// provider-owned, session-scoped metadata and return unavailable explicitly.
type chatAutomationReader interface {
Automations(ctx context.Context, sessionID string) (protocol.ChatAutomationInfo, error)
}
// chatShellReleaser is implemented by brokers that retain verified shell ids for
// attributing exit events. The hub calls it only after the last observer leaves
// a room; a later attach obtains a fresh authoritative snapshot.
@@ -251,6 +258,9 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
case protocol.ChatAttachmentImage:
handleChatAttachmentImage(request, broker, write)
return true
case protocol.ChatAutomations:
handleChatAutomations(ctx, request, broker, registry, write)
return true
}
return false
}
+64
View File
@@ -0,0 +1,64 @@
package server
import (
"context"
"fmt"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func validChatAutomationInfo(info protocol.ChatAutomationInfo, sessionID string) error {
if info.SessionID != "" && info.SessionID != sessionID {
return fmt.Errorf("provider returned automation metadata for another session")
}
if info.Status != protocol.ChatAutomationSupported && info.Status != protocol.ChatAutomationUnavailable {
return fmt.Errorf("provider returned an invalid automation status")
}
if info.ActiveCount != nil && *info.ActiveCount < 0 {
return fmt.Errorf("provider returned a negative automation count")
}
if info.Status == protocol.ChatAutomationUnavailable && info.ActiveCount != nil {
return fmt.Errorf("unavailable automation metadata must not include a count")
}
if info.Status == protocol.ChatAutomationSupported && info.ActiveCount == nil {
return fmt.Errorf("supported automation metadata is missing a count")
}
return nil
}
func handleChatAutomations(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry, write func(protocol.Message) error) {
if broker == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
return
}
query := request.ChatQuery
if query == nil || !validChatSessionID(query.SessionID) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid chat session id is required"})
return
}
if err := operatorChatSession(ctx, registry, query.SessionID); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
reader, ok := broker.(chatAutomationReader)
if !ok {
_ = write(protocol.Message{Type: protocol.ChatAutomations, ID: request.ID, ChatAutomations: &protocol.ChatAutomationInfo{
SessionID: query.SessionID, Status: protocol.ChatAutomationUnavailable,
Reason: "this chat provider has no authoritative scheduled-work read API",
}})
return
}
info, err := reader.Automations(ctx, query.SessionID)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: fmt.Sprintf("read chat automations: %v", err)})
return
}
if info.SessionID == "" {
info.SessionID = query.SessionID
}
if err := validChatAutomationInfo(info, query.SessionID); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "read chat automations: " + err.Error()})
return
}
_ = write(protocol.Message{Type: protocol.ChatAutomations, ID: request.ID, ChatAutomations: &info})
}
+90
View File
@@ -0,0 +1,90 @@
package server
import (
"context"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
type automationChat struct {
*fakeChat
info protocol.ChatAutomationInfo
readCalled int
}
func (c *automationChat) Automations(context.Context, string) (protocol.ChatAutomationInfo, error) {
c.readCalled++
return c.info, nil
}
func automationReply(t *testing.T, request protocol.Message, broker chatBroker, registry operatorRegistry) protocol.Message {
t.Helper()
var reply protocol.Message
handleChatAutomations(context.Background(), request, broker, registry, func(message protocol.Message) error {
reply = message
return nil
})
return reply
}
func TestChatAutomationsRequiresOwnedSession(t *testing.T) {
store := newOperatorStore(t)
if err := store.RecordOperatorSession(context.Background(), "ses_owned", t.TempDir(), "owned", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
broker := &automationChat{fakeChat: scriptedChat(), info: protocol.ChatAutomationInfo{Status: protocol.ChatAutomationSupported}}
reply := automationReply(t, protocol.Message{Type: protocol.ChatAutomations, ID: "a1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_foreign"}}, broker, store)
if reply.Type != protocol.Error || reply.Error != "operator session is not available" {
t.Fatalf("foreign automation read = %+v", reply)
}
if broker.readCalled != 0 {
t.Fatal("provider read happened before ownership check")
}
}
func TestChatAutomationsDistinguishesUnavailableFromEmpty(t *testing.T) {
store := newOperatorStore(t)
if err := store.RecordOperatorSession(context.Background(), "ses_empty", t.TempDir(), "empty", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
request := protocol.Message{Type: protocol.ChatAutomations, ID: "a2", ChatQuery: &protocol.ChatQuery{SessionID: "ses_empty"}}
unsupported := automationReply(t, request, scriptedChat(), store)
if unsupported.Type != protocol.ChatAutomations || unsupported.ChatAutomations == nil || unsupported.ChatAutomations.Status != protocol.ChatAutomationUnavailable || unsupported.ChatAutomations.ActiveCount != nil {
t.Fatalf("unsupported automation read = %+v", unsupported)
}
empty := 0
broker := &automationChat{fakeChat: scriptedChat(), info: protocol.ChatAutomationInfo{SessionID: "ses_empty", Provider: "opencode", Status: protocol.ChatAutomationSupported, ActiveCount: &empty}}
supported := automationReply(t, request, broker, store)
if supported.Type != protocol.ChatAutomations || supported.ChatAutomations == nil || supported.ChatAutomations.Status != protocol.ChatAutomationSupported || supported.ChatAutomations.ActiveCount == nil || *supported.ChatAutomations.ActiveCount != 0 {
t.Fatalf("empty automation read = %+v", supported)
}
}
func TestChatAutomationsRejectsMalformedSessionBounds(t *testing.T) {
broker := &automationChat{fakeChat: scriptedChat()}
for _, query := range []*protocol.ChatQuery{
nil,
{SessionID: ""},
{SessionID: "not-a-session"},
{SessionID: "ses_" + string(make([]byte, 201))},
} {
reply := automationReply(t, protocol.Message{Type: protocol.ChatAutomations, ID: "a3", ChatQuery: query}, broker, nil)
if reply.Type != protocol.Error {
t.Fatalf("malformed query %+v returned %+v", query, reply)
}
}
}
func TestChatAutomationsRejectsMalformedProviderMetadata(t *testing.T) {
store := newOperatorStore(t)
if err := store.RecordOperatorSession(context.Background(), "ses_bad", t.TempDir(), "bad", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
count := -1
broker := &automationChat{fakeChat: scriptedChat(), info: protocol.ChatAutomationInfo{SessionID: "ses_bad", Status: protocol.ChatAutomationSupported, ActiveCount: &count}}
reply := automationReply(t, protocol.Message{Type: protocol.ChatAutomations, ID: "a4", ChatQuery: &protocol.ChatQuery{SessionID: "ses_bad"}}, broker, store)
if reply.Type != protocol.Error {
t.Fatalf("malformed provider metadata = %+v", reply)
}
}
+15
View File
@@ -332,6 +332,21 @@ func (m *chatManager) brokerFor(ctx context.Context, sessionID string) (chatBrok
return adapter, nil
}
// Automations routes the optional readback capability without adding it to the
// base broker contract. The session's registry-selected provider remains the
// ownership boundary; no provider-wide or cwd-wide schedule list is consulted.
func (m *chatManager) Automations(ctx context.Context, sessionID string) (protocol.ChatAutomationInfo, error) {
adapter, err := m.brokerFor(ctx, sessionID)
if err != nil {
return protocol.ChatAutomationInfo{SessionID: sessionID, Status: protocol.ChatAutomationUnavailable, Reason: err.Error()}, nil
}
reader, ok := adapter.(chatAutomationReader)
if !ok {
return protocol.ChatAutomationInfo{SessionID: sessionID, Provider: m.backendFor(ctx, sessionID), Status: protocol.ChatAutomationUnavailable, Reason: "this chat provider has no authoritative scheduled-work read API"}, nil
}
return reader.Automations(ctx, sessionID)
}
// chatTitleSetter is a harness that names its own sessions from the operator's
// chat title (Claude Code passes it as --name on the next spawn). SetTitle
// records the title in memory only and does no I/O.