Poll OpenCode permission requests and forward chat_reply

This commit is contained in:
2026-10-16 08:06:39 +01:00
parent 9d1676df0a
commit 3ff5cd8838
10 changed files with 889 additions and 40 deletions
+148
View File
@@ -3,6 +3,7 @@ package opencode
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
@@ -161,11 +162,158 @@ func TestChatRejectsInvalidSessionWithoutCalling(t *testing.T) {
if err := chat.Interrupt(ctx, "bad id"); err == nil {
t.Fatal("invalid interrupt session id must be rejected")
}
if _, err := chat.Permissions(ctx, "not-a-session"); err == nil {
t.Fatal("invalid permission session id must be rejected")
}
if err := chat.Reply(ctx, protocol.ChatReplyRequest{SessionID: "not-a-session", RequestID: "req_1", Decision: protocol.ChatDecisionOnce}); err == nil {
t.Fatal("invalid reply session id must be rejected")
}
if err := chat.Reply(ctx, protocol.ChatReplyRequest{SessionID: "ses_1", RequestID: "", Decision: protocol.ChatDecisionOnce}); err == nil {
t.Fatal("empty reply request id must be rejected")
}
if err := chat.Reply(ctx, protocol.ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: "maybe"}); err == nil {
t.Fatal("invalid reply decision must be rejected")
}
if calls.Load() != 0 {
t.Fatalf("invalid requests reached the service: %d", calls.Load())
}
}
// TestChatPermissionsListsAndFilters loads a pending-request fixture in the
// verified V2 envelope (GET /api/permission/request) and asserts the adapter
// returns the requested session's request with its fields intact, filters out a
// foreign session's request, and reads the endpoint once.
func TestChatPermissionsListsAndFilters(t *testing.T) {
var reads atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet || r.URL.Path != "/api/permission/request" {
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
return
}
reads.Add(1)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"location":{"directory":"/work"},"data":[
{"id":"per_1","sessionID":"ses_1","action":"bash","resources":["rm -rf /tmp"],"save":["bash:rm -rf /tmp"],"metadata":{"command":"rm -rf /tmp"},"source":{"type":"tool","messageID":"msg_1","id":"call_1"},"message":"wants to run a command"},
{"id":"per_2","sessionID":"ses_other","action":"edit","resources":["/etc/hosts"]}
]}`))
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
frames, err := chat.Permissions(ctx, "ses_1")
if err != nil {
t.Fatalf("permissions: %v", err)
}
if reads.Load() != 1 {
t.Fatalf("permission endpoint read %d times, want 1", reads.Load())
}
if len(frames) != 1 {
t.Fatalf("frames = %+v, want the foreign request filtered", frames)
}
got := frames[0]
if got.SessionID != "ses_1" || got.RequestID != "per_1" || got.Action != "bash" {
t.Fatalf("frame = %+v", got)
}
if len(got.Resources) != 1 || got.Resources[0] != "rm -rf /tmp" || len(got.Save) != 1 || got.Message != "wants to run a command" {
t.Fatalf("frame detail = %+v", got)
}
if got.Metadata["command"] != "rm -rf /tmp" {
t.Fatalf("frame metadata = %+v", got.Metadata)
}
if got.Source == nil || got.Source.Type != "tool" || got.Source.MessageID != "msg_1" || got.Source.ID != "call_1" {
t.Fatalf("frame source = %+v", got.Source)
}
}
// TestChatPermissionsRejectsMalformedList pins that a response without the data
// array is an error, not an empty success.
func TestChatPermissionsRejectsMalformedList(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"location":{"directory":"/work"}}`))
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
if _, err := chat.Permissions(context.Background(), "ses_1"); err == nil {
t.Fatal("a malformed permission response must be an error, not empty success")
}
}
// TestChatPermissionReplyPostsReplyEndpoint pins the outbound approval reply: the
// adapter must POST exactly once to
// /api/session/{id}/permission/{requestID}/reply with the exact decision body,
// accept the documented 204 No Content success, and surface a non-2xx failure.
func TestChatPermissionReplyPostsReplyEndpoint(t *testing.T) {
for _, decision := range []string{protocol.ChatDecisionOnce, protocol.ChatDecisionAlways, protocol.ChatDecisionReject} {
t.Run(decision, func(t *testing.T) {
type request struct{ method, path, body string }
var mu sync.Mutex
var requests []request
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
data, _ := io.ReadAll(r.Body)
mu.Lock()
requests = append(requests, request{method: r.Method, path: r.URL.Path, body: string(data)})
mu.Unlock()
w.WriteHeader(http.StatusNoContent)
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := chat.Reply(ctx, protocol.ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: decision}); err != nil {
t.Fatalf("reply: %v", err)
}
mu.Lock()
got := append([]request(nil), requests...)
mu.Unlock()
if len(got) != 1 {
t.Fatalf("reply requests = %d, want 1: %+v", len(got), got)
}
if got[0].method != http.MethodPost || got[0].path != "/api/session/ses_1/permission/req_1/reply" {
t.Fatalf("reply request = %+v", got[0])
}
if got[0].body != `{"decision":"`+decision+`"}` {
t.Fatalf("reply body = %q, want decision %q", got[0].body, decision)
}
})
}
t.Run("failure", func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
if err := chat.Reply(context.Background(), protocol.ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: protocol.ChatDecisionOnce}); err == nil {
t.Fatal("a failing reply endpoint must return an error")
}
})
}
// TestChatPermissionV1TranslationGated pins the declared backend limitation: the
// permission list and reply are implemented against the V2 HTTP API, and the
// native serve translation rejects them explicitly (an actionable error, no
// guessed endpoint, no HTTP call) so the caller can see the limitation.
func TestChatPermissionV1TranslationGated(t *testing.T) {
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v1", URL: srv.URL, Directory: "/repo", models: map[string]map[string]string{}, responses: map[string][]byte{}})
ctx := context.Background()
if _, err := chat.Permissions(ctx, "ses_1"); !errors.Is(err, ErrPermissionUnsupported) {
t.Fatalf("v1 permission list must return the gate sentinel, got %v", err)
}
if err := chat.Reply(ctx, protocol.ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: protocol.ChatDecisionOnce}); !errors.Is(err, ErrPermissionUnsupported) {
t.Fatalf("v1 permission reply must return the gate sentinel, got %v", err)
}
if calls.Load() != 0 {
t.Fatalf("gated permission requests reached the service: %d", calls.Load())
}
}
// TestChatInterruptPostsInterruptEndpoint pins the outbound interrupt call: the
// adapter must POST an empty JSON body to /api/session/{id}/interrupt exactly
// once and return nil, and it must surface a non-nil error when the endpoint