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
+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)
}
}