diff --git a/internal/author/skill/references/operations.md b/internal/author/skill/references/operations.md index 2359e8b5..e1a5f039 100644 --- a/internal/author/skill/references/operations.md +++ b/internal/author/skill/references/operations.md @@ -178,17 +178,39 @@ traversal, absolute paths, symlink escapes and unknown runs/steps. ## Brokered OpenCode chat (unshipped) The protocol declares the brokered `chat_*` surface (`chat_sessions`, -`chat_create`, `chat_prompt`, `chat_messages`, `chat_interrupt`, `chat_reply`). The -server dispatches `chat_prompt`, `chat_messages`, `chat_interrupt` and `chat_reply`, -answers the declared `chat_sessions`/`chat_create` with an explicit protocol error -because they are not yet brokered, and pushes `chat_event` frames derived from -OpenCode's global `/api/event` firehose, with retained per-session/per-message state -so a reconnecting client re-syncs instead of replaying deltas. This is an internal, unshipped capability: no client consumes it, -and chat is enabled only when the OpenCode connection exposes a URL-bearing SSE -endpoint (the owned v1 serve process). On a V2 CLI (`opencode api`, no owned serve) -that endpoint is absent, so every dispatched `chat_*` request returns a protocol error -naming the missing configuration. Do not describe brokered chat as a finished or -user-facing feature. +`chat_create`, `chat_prompt`, `chat_messages`, `chat_interrupt`, `chat_permission`, +`chat_reply`). The server dispatches `chat_prompt`, `chat_messages`, `chat_interrupt` +and `chat_reply`, answers the declared `chat_sessions`/`chat_create` with an explicit +protocol error because they are not yet brokered, and pushes `chat_event` frames +derived from OpenCode's global `/api/event` firehose, with retained +per-session/per-message state so a reconnecting client re-syncs instead of replaying +deltas. + +While a `chat_prompt` subscription is open the server also polls +`GET /api/permission/request` on a fixed small interval (first poll immediately) and +pushes one `chat_permission` frame per newly pending approval request, deduped by +request id so a repeated poll never re-pushes the same request. The app answers with +`chat_reply`, which the server forwards as +`POST /api/session/{id}/permission/{requestID}/reply` with +`{"decision":"once"|"always"|"reject"}`. A missing session/request id or an invalid +decision is rejected before any OpenCode call, and the poller stops when the stream +ends or the client disconnects. + +The permission list and reply are implemented against the V2 HTTP API only: their +field names match the service's `Permission.Request`/`Permission.Reply` schemas +(verified against the installed service's `/openapi.json`), and the native v1 serve +translation rejects them explicitly instead of guessing an endpoint. Because this +build enables brokered chat only when the OpenCode connection exposes a URL-bearing +SSE endpoint (the owned v1 serve process), the approval flow is not reachable on the +backend that currently enables chat; on that backend the permission poller stops +quietly rather than reporting the documented limitation as a per-prompt error. This is +an internal, unshipped capability: no client consumes it, and on a V2 CLI +(`opencode api`, no owned serve) that endpoint is absent, so every dispatched `chat_*` +request returns a protocol error naming the missing configuration. The live +end-to-end approval flow has NOT been tested against a real OpenCode service; the wire +shapes and the exact reply path/body are covered by unit tests over an httptest +fixture, not against a live pending request. Do not describe brokered chat as a +finished or user-facing feature. ## Debug and retry diff --git a/internal/opencode/chat.go b/internal/opencode/chat.go index 75a89f2c..130ee793 100644 --- a/internal/opencode/chat.go +++ b/internal/opencode/chat.go @@ -5,13 +5,22 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "strings" + "sync" "git.a-wan.net/alan/pipelines/internal/protocol" ) +// ErrPermissionUnsupported reports that the connected OpenCode backend does not +// expose the brokered approval surface. The native v1 serve translation returns +// it; callers treat it as a documented limitation rather than an operational +// failure, so a chat prompt does not emit a permission error frame on a backend +// that cannot answer one. +var ErrPermissionUnsupported = errors.New("OpenCode permission approval is not implemented for the native serve backend") + // Chat is the brokered OpenCode chat adapter (route B in the research): the // Pipelines server owns the OpenCode endpoint and credentials and turns the v2 // HTTP API into protocol.ChatEventFrame frames. It reuses the owned-endpoint @@ -19,6 +28,11 @@ import ( // no second transport or credential path is introduced. type Chat struct { conn *Connection + // mu serializes the adapter's HTTP calls. Connection records its last + // operation and status on the shared connection, so two calls must not + // overlap; the permission poller runs alongside the read loop's + // prompt/interrupt/reply calls. + mu sync.Mutex } // NewChat brokers chat for one owned OpenCode endpoint. The connection must be @@ -31,6 +45,15 @@ func NewChat(conn *Connection) *Chat { return &Chat{conn: conn} } // chat adapter and callers that must reject a request before any OpenCode call. func ValidSessionID(id string) bool { return sessionID.MatchString(id) } +// call serializes the adapter's HTTP calls and forwards them through the shared +// Connection, so no second transport is introduced and Connection's recorded +// last operation/status is never written by two goroutines at once. +func (c *Chat) call(ctx context.Context, method, path string, body any) ([]byte, error) { + c.mu.Lock() + defer c.mu.Unlock() + return c.conn.Call(ctx, method, path, body) +} + // Prompt forwards one chat prompt through the existing Call translation // (authenticated, bounded, directory-scoped). The endpoint returns the inbox // envelope immediately; the reply arrives on Stream. @@ -42,7 +65,7 @@ func (c *Chat) Prompt(ctx context.Context, id, text string) error { return fmt.Errorf("empty chat prompt") } body := map[string]any{"parts": []map[string]string{{"type": "text", "text": text}}} - if _, err := c.conn.Call(ctx, "post", "/api/session/"+id+"/prompt", body); err != nil { + if _, err := c.call(ctx, "post", "/api/session/"+id+"/prompt", body); err != nil { return err } return nil @@ -53,7 +76,7 @@ func (c *Chat) Interrupt(ctx context.Context, id string) error { if !sessionID.MatchString(id) { return fmt.Errorf("invalid OpenCode session id") } - if _, err := c.conn.Call(ctx, "post", "/api/session/"+id+"/interrupt", map[string]any{}); err != nil { + if _, err := c.call(ctx, "post", "/api/session/"+id+"/interrupt", map[string]any{}); err != nil { return err } return nil @@ -69,6 +92,7 @@ func (c *Chat) Messages(ctx context.Context, id string, limit int) ([]protocol.C } var data []byte var err error + c.mu.Lock() if c.conn.Backend == "v1" { data, err = c.conn.Messages(ctx, id) } else { @@ -78,6 +102,7 @@ func (c *Chat) Messages(ctx context.Context, id string, limit int) ([]protocol.C } data, err = c.conn.Call(ctx, "get", path, nil) } + c.mu.Unlock() if err != nil { return nil, err } @@ -101,12 +126,108 @@ func (c *Chat) Reply(ctx context.Context, request protocol.ChatReplyRequest) err body["message"] = request.Message } path := "/api/session/" + request.SessionID + "/permission/" + request.RequestID + "/reply" - if _, err := c.conn.Call(ctx, "post", path, body); err != nil { + if _, err := c.call(ctx, "post", path, body); err != nil { return err } return nil } +// Permissions lists the session's pending OpenCode approval requests, mirroring +// GET /api/permission/request. The endpoint is global, so the decoded list is +// filtered to sessionID; a malformed response is an error, never an empty +// success. It reuses Connection.Call so the request keeps the shared bounds, +// auth and translation, and reuses ValidSessionID for the same rejection the +// other chat calls apply. +func (c *Chat) Permissions(ctx context.Context, id string) ([]protocol.ChatPermissionFrame, error) { + if !sessionID.MatchString(id) { + return nil, fmt.Errorf("invalid OpenCode session id") + } + data, err := c.call(ctx, "get", "/api/permission/request", nil) + if err != nil { + return nil, err + } + return decodeChatPermissions(id, data) +} + +// nativeChatPermission is one pending approval request matching the V2 +// Permission.Request schema verified against the service's /openapi.json: id, +// sessionID, action and resources are required; save, metadata, source and +// message are optional, so the decoder tolerates any of them being absent. +type nativeChatPermission struct { + ID string `json:"id"` + SessionID string `json:"sessionID"` + Action string `json:"action"` + Resources []string `json:"resources"` + Save []string `json:"save"` + Metadata map[string]any `json:"metadata"` + Source *nativeChatPermissionSource `json:"source"` + Message string `json:"message"` +} + +// nativeChatPermissionSource is the incoming Permission.Source union; its single +// (tool) member carries type plus the message id and call id (the protocol frame +// renames messageID to message_id). +type nativeChatPermissionSource struct { + Type string `json:"type"` + MessageID string `json:"messageID"` + ID string `json:"id"` +} + +// chatEnvelope unwraps the {"data":[...]} envelope the V2 HTTP API returns and +// reports whether the body was that envelope with a non-nil data array; a bare +// array or a malformed body returns ok=false. It is the single envelope rule the +// message and permission decoders share instead of each re-deriving it. +func chatEnvelope[T any](data []byte) ([]T, bool) { + var response struct { + Data []T `json:"data"` + } + if err := json.Unmarshal(data, &response); err != nil || response.Data == nil { + return nil, false + } + return response.Data, true +} + +// chatPermissionRecords reads the {"data":[...]} envelope the V2 endpoint +// returns. An unparseable body or a missing data array is an error, never an +// empty list. +func chatPermissionRecords(data []byte) ([]nativeChatPermission, error) { + records, ok := chatEnvelope[nativeChatPermission](data) + if !ok { + return nil, fmt.Errorf("invalid OpenCode permission response") + } + return records, nil +} + +// decodeChatPermissions maps the pending-request list onto protocol frames, +// keeping only the requested session's requests (a request with no id cannot be +// answered and is dropped). +func decodeChatPermissions(sessionID string, data []byte) ([]protocol.ChatPermissionFrame, error) { + records, err := chatPermissionRecords(data) + if err != nil { + return nil, err + } + frames := make([]protocol.ChatPermissionFrame, 0, len(records)) + for _, record := range records { + if record.SessionID != sessionID || record.ID == "" { + continue + } + frame := protocol.ChatPermissionFrame{ + SessionID: sessionID, + RequestID: record.ID, + Action: record.Action, + Resources: record.Resources, + Save: record.Save, + Metadata: record.Metadata, + Message: record.Message, + } + if record.Source != nil { + frame.Source = &protocol.ChatPermissionSource{Type: record.Source.Type, MessageID: record.Source.MessageID, ID: record.Source.ID} + } + frames = append(frames, frame) + } + return frames, nil +} + // Stream subscribes to the OpenCode event firehose and invokes emit for every // frame belonging to sessionID. It reads one bounded SSE frame at a time and // never polls the per-session message log; the global firehose is the only @@ -388,11 +509,8 @@ func (m nativeChatMessage) contentParts() []nativeChatPart { // the V2 HTTP API wraps them in {"data":[...]} while the native serve readback // returns a bare array. An unrecognised body is an error, never empty history. func chatMessageRecords(data []byte) ([]nativeChatMessage, error) { - var response struct { - Data []nativeChatMessage `json:"data"` - } - if err := json.Unmarshal(data, &response); err == nil && response.Data != nil { - return response.Data, nil + if records, ok := chatEnvelope[nativeChatMessage](data); ok { + return records, nil } var records []nativeChatMessage if err := json.Unmarshal(data, &records); err != nil { diff --git a/internal/opencode/chat_test.go b/internal/opencode/chat_test.go index 63edb2b4..b3c5a579 100644 --- a/internal/opencode/chat_test.go +++ b/internal/opencode/chat_test.go @@ -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 diff --git a/internal/opencode/connection.go b/internal/opencode/connection.go index fca80cb3..c5cd7074 100644 --- a/internal/opencode/connection.go +++ b/internal/opencode/connection.go @@ -262,6 +262,11 @@ func (c *Connection) Native(ctx context.Context, method, path string, body any) evidence, _ := io.ReadAll(io.LimitReader(response.Body, 16<<10)) return evidence, fmt.Errorf("OpenCode %s %s failed (HTTP %d)", method, path, response.StatusCode) } + // A successful no-content operation (the permission-reply endpoint returns + // 204) carries no JSON body to validate. + if response.StatusCode == http.StatusNoContent { + return nil, nil + } if !strings.HasPrefix(response.Header.Get("Content-Type"), "application/json") { return nil, fmt.Errorf("OpenCode %s %s returned a non-JSON API response", method, path) } diff --git a/internal/opencode/native.go b/internal/opencode/native.go index 5a4ed4fe..e613a381 100644 --- a/internal/opencode/native.go +++ b/internal/opencode/native.go @@ -116,6 +116,16 @@ func (c *Connection) Call(ctx context.Context, method, path string, body any) ([ return json.Marshal(map[string]any{"data": map[string]string{"id": session.ID}}) } clean := strings.SplitN(path, "?", 2)[0] + // The brokered approval surface is implemented against the V2 HTTP API: the + // documented endpoints are GET /api/permission/request and POST + // /api/session/{id}/permission/{requestID}/reply. This native serve + // translation does not implement them, so answer with an actionable gate + // error instead of the generic unsupported-operation error; the permission + // poller surfaces that limitation rather than silently reporting no pending + // requests. + if clean == "/api/permission/request" { + return nil, fmt.Errorf("permission listing: %w", ErrPermissionUnsupported) + } parts := strings.Split(strings.TrimPrefix(clean, "/api/session/"), "/") if strings.HasPrefix(clean, "/api/experimental/session/") { parts = strings.Split(strings.TrimPrefix(clean, "/api/experimental/session/"), "/") @@ -124,6 +134,11 @@ func (c *Connection) Call(ctx context.Context, method, path string, body any) ([ return nil, fmt.Errorf("unsupported native OpenCode operation") } id := parts[0] + // The approval reply is V2-only in this translation (see the permission-list + // gate above); the V2 path has four trailing segments. + if len(parts) == 4 && parts[1] == "permission" && parts[3] == "reply" { + return nil, fmt.Errorf("permission reply: %w", ErrPermissionUnsupported) + } if len(parts) == 1 && method == "delete" { data, err := c.Native(ctx, "delete", "/session/"+id, nil) if err != nil { diff --git a/internal/protocol/chat.go b/internal/protocol/chat.go index 9d411210..2d848f19 100644 --- a/internal/protocol/chat.go +++ b/internal/protocol/chat.go @@ -22,9 +22,12 @@ const ( ChatMessages = "chat_messages" ChatInterrupt = "chat_interrupt" ChatReply = "chat_reply" - // ChatEvent is the server-pushed frame; it is the only type the server - // sends without a matching request. + // ChatEvent and ChatPermission are the server-pushed frames; they are the + // only types the server sends without a matching request. ChatEvent = "chat_event" + // ChatPermission carries one pending OpenCode approval request the phone + // answers with chat_reply. + ChatPermission = "chat_permission" ) // Content part types carried by ChatPart.Type and ChatEvent.Kind. @@ -200,6 +203,35 @@ type ChatUsage struct { Cost float64 `json:"cost,omitempty"` } +// ChatPermissionFrame is the server-pushed chat_permission payload: one pending +// OpenCode permission request the phone must approve or reject. It is a distinct +// Message field (like ChatEvent) rather than a ChatEvent.Kind, so it does not +// overload the turn-progress kinds. Its field names match the service's +// Permission.Request schema, verified against the installed service's +// /openapi.json (id, sessionID, action and resources required; save, metadata, +// source and message optional), with id -> RequestID and sessionID -> SessionID. +// The wire shape is spec-verified; a live pending request has not been observed. +// Every optional field is omitempty so older peers ignore it. +type ChatPermissionFrame struct { + SessionID string `json:"session_id"` + RequestID string `json:"request_id"` + Action string `json:"action,omitempty"` + Resources []string `json:"resources,omitempty"` + Save []string `json:"save,omitempty"` + Metadata map[string]any `json:"metadata,omitempty"` + Source *ChatPermissionSource `json:"source,omitempty"` + Message string `json:"message,omitempty"` +} + +// ChatPermissionSource identifies what raised a permission request, matching the +// Permission.Source union (currently only a tool call: type "tool" plus the +// message and call id) verified against the service's /openapi.json. +type ChatPermissionSource struct { + Type string `json:"type,omitempty"` + MessageID string `json:"message_id,omitempty"` + ID string `json:"id,omitempty"` +} + // ChatReplyRequest is the chat_reply request body: the phone's decision on a // pending permission request, mirroring // POST /api/session/{id}/permission/{requestID}/reply. diff --git a/internal/protocol/chat_test.go b/internal/protocol/chat_test.go index f4dbc4bd..8b71040c 100644 --- a/internal/protocol/chat_test.go +++ b/internal/protocol/chat_test.go @@ -55,6 +55,13 @@ func chatSamples() []struct { }}, {"event_step", ChatEventFrame{SessionID: "ses_1", Kind: ChatEventStep, Step: &ChatStep{Status: ChatStepEnded, Index: 2}}}, {"event_usage", ChatEventFrame{SessionID: "ses_1", Kind: ChatEventUsage, Usage: &ChatUsage{InputTokens: 12, OutputTokens: 34, Cost: 0.001}}}, + {"permission", ChatPermissionFrame{ + SessionID: "ses_1", RequestID: "per_1", Action: "bash", + Resources: []string{"rm -rf /tmp"}, Save: []string{"bash:rm -rf /tmp"}, + Metadata: map[string]any{"command": "rm -rf /tmp"}, + Source: &ChatPermissionSource{Type: "tool", MessageID: "msg_1", ID: "call_1"}, + Message: "wants to run a command", + }}, {"reply", ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: ChatDecisionOnce, Message: "ok"}}, } } @@ -114,6 +121,32 @@ func TestChatEventGoldenJSON(t *testing.T) { } } +// TestChatPermissionGoldenJSON pins the exact wire shape of the pushed +// chat_permission frame so a JSON tag change cannot silently alter what the +// phone parses. +func TestChatPermissionGoldenJSON(t *testing.T) { + frame := ChatPermissionFrame{ + SessionID: "ses_1", RequestID: "per_1", Action: "bash", + Resources: []string{"rm -rf /tmp"}, + Source: &ChatPermissionSource{Type: "tool", MessageID: "msg_1", ID: "call_1"}, + } + encoded, err := json.Marshal(frame) + if err != nil { + t.Fatal(err) + } + want := `{"session_id":"ses_1","request_id":"per_1","action":"bash","resources":["rm -rf /tmp"],"source":{"type":"tool","message_id":"msg_1","id":"call_1"}}` + if string(encoded) != want { + t.Fatalf("golden mismatch\n got %s\nwant %s", encoded, want) + } + var decoded ChatPermissionFrame + if err := json.Unmarshal([]byte(want), &decoded); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(decoded, frame) { + t.Fatalf("golden did not decode back: %+v", decoded) + } +} + func TestChatEnvelopeRoundTrip(t *testing.T) { session := ChatSession{ID: "ses_1", Title: "demo"} message := Message{ @@ -125,7 +158,10 @@ func TestChatEnvelopeRoundTrip(t *testing.T) { ChatPrompt: &ChatPromptRequest{SessionID: "ses_1", Text: "hi"}, ChatMessages: []ChatMessage{{ID: "msg_1", SessionID: "ses_1", Role: ChatRoleUser, Parts: []ChatPart{{Type: ChatPartText, Text: "hi"}}}}, ChatEvent: &ChatEventFrame{SessionID: "ses_1", Kind: ChatEventText, Delta: "hi"}, - ChatReply: &ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: ChatDecisionReject}, + ChatPermission: &ChatPermissionFrame{ + SessionID: "ses_1", RequestID: "per_1", Action: "bash", Resources: []string{"rm -rf /"}, + }, + ChatReply: &ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: ChatDecisionReject}, } encoded, err := json.Marshal(message) if err != nil { @@ -145,6 +181,7 @@ func TestChatEnvelopeRoundTrip(t *testing.T) { !reflect.DeepEqual(decoded.ChatPrompt, message.ChatPrompt) || !reflect.DeepEqual(decoded.ChatMessages, message.ChatMessages) || !reflect.DeepEqual(decoded.ChatEvent, message.ChatEvent) || + !reflect.DeepEqual(decoded.ChatPermission, message.ChatPermission) || !reflect.DeepEqual(decoded.ChatReply, message.ChatReply) { t.Fatalf("chat payloads lost: %+v", decoded) } @@ -155,7 +192,7 @@ func TestChatFieldsOmittedWhenUnused(t *testing.T) { if err != nil { t.Fatal(err) } - for _, absent := range []string{"chat_sessions", "chat_session", "chat_create", "chat_query", "chat_prompt", "chat_messages", "chat_event", "chat_reply"} { + for _, absent := range []string{"chat_sessions", "chat_session", "chat_create", "chat_query", "chat_prompt", "chat_messages", "chat_event", "chat_permission", "chat_reply"} { if strings.Contains(string(minimal), absent) { t.Fatalf("absent %q must be omitted: %s", absent, minimal) } diff --git a/internal/protocol/message.go b/internal/protocol/message.go index f80556fa..7b63b470 100644 --- a/internal/protocol/message.go +++ b/internal/protocol/message.go @@ -135,12 +135,13 @@ type Message struct { Workspace string `json:"workspace,omitempty"` // Chat is the brokered OpenCode chat traffic (route B). See chat.go for the // per-type payload structs and the wire shapes they mirror. - ChatSessions []ChatSession `json:"chat_sessions,omitempty"` - ChatSession *ChatSession `json:"chat_session,omitempty"` - ChatCreate *ChatCreateRequest `json:"chat_create,omitempty"` - ChatQuery *ChatQuery `json:"chat_query,omitempty"` - ChatPrompt *ChatPromptRequest `json:"chat_prompt,omitempty"` - ChatMessages []ChatMessage `json:"chat_messages,omitempty"` - ChatEvent *ChatEventFrame `json:"chat_event,omitempty"` - ChatReply *ChatReplyRequest `json:"chat_reply,omitempty"` + ChatSessions []ChatSession `json:"chat_sessions,omitempty"` + ChatSession *ChatSession `json:"chat_session,omitempty"` + ChatCreate *ChatCreateRequest `json:"chat_create,omitempty"` + ChatQuery *ChatQuery `json:"chat_query,omitempty"` + ChatPrompt *ChatPromptRequest `json:"chat_prompt,omitempty"` + ChatMessages []ChatMessage `json:"chat_messages,omitempty"` + ChatEvent *ChatEventFrame `json:"chat_event,omitempty"` + ChatPermission *ChatPermissionFrame `json:"chat_permission,omitempty"` + ChatReply *ChatReplyRequest `json:"chat_reply,omitempty"` } diff --git a/internal/server/chat.go b/internal/server/chat.go index 08b579cc..ecc759db 100644 --- a/internal/server/chat.go +++ b/internal/server/chat.go @@ -2,6 +2,7 @@ package server import ( "context" + "errors" "log" "strings" "sync" @@ -22,9 +23,22 @@ type chatBroker interface { Stream(ctx context.Context, sessionID string, ready func(), emit func(protocol.ChatEventFrame) error) error Interrupt(ctx context.Context, sessionID string) error Messages(ctx context.Context, sessionID string, limit int) ([]protocol.ChatMessage, error) + // Permissions lists the session's pending OpenCode approval requests so the + // handler can push chat_permission frames. + Permissions(ctx context.Context, sessionID string) ([]protocol.ChatPermissionFrame, error) Reply(ctx context.Context, request protocol.ChatReplyRequest) error } +// chatPermissionPollInterval is the fixed interval between permission polls: one +// GET per poll through the shared Connection bounds, never a busy loop. The first +// poll runs immediately so a request pending when the prompt is sent is surfaced +// without waiting a full interval. +const chatPermissionPollInterval = 2 * time.Second + +// chatPermissionRetainedLimit bounds the dedup set of already-pushed permission +// request ids one session retains, so a long turn cannot grow it without limit. +const chatPermissionRetainedLimit = 256 + // chatRetainedLimit bounds the state one session may retain so a stalled reader // or a runaway turn cannot grow memory without limit. It matches the OpenCode // response bound (1 MiB). @@ -69,6 +83,11 @@ type chatTurn struct { size int overflow bool updated time.Time + // permissions holds the request ids already pushed to the client so a + // repeated poll cannot push the same pending request twice; permissionOrder + // bounds it to chatPermissionRetainedLimit. + permissions map[string]struct{} + permissionOrder []string } func newChatHub() *chatHub { @@ -93,13 +112,7 @@ func (h *chatHub) apply(frame protocol.ChatEventFrame) { } h.mu.Lock() defer h.mu.Unlock() - turn := h.turns[frame.SessionID] - if turn == nil { - h.evictLocked() - turn = &chatTurn{sessionID: frame.SessionID, messages: map[string]*chatMessage{}} - h.turns[frame.SessionID] = turn - } - turn.updated = h.clock() + turn := h.turnLocked(frame.SessionID) switch frame.Kind { case protocol.ChatEventStep: turn.step = frame.Step @@ -210,6 +223,21 @@ func (h *chatHub) evictLocked() { } } +// turnLocked returns the session's retained turn, creating it (and evicting the +// least-recently-updated turn first when the cap is reached) and refreshing its +// update time. It is the shared turn-initialization path for apply and +// seenPermission, so the two cannot drift. Callers must hold h.mu. +func (h *chatHub) turnLocked(sessionID string) *chatTurn { + turn := h.turns[sessionID] + if turn == nil { + h.evictLocked() + turn = &chatTurn{sessionID: sessionID, messages: map[string]*chatMessage{}} + h.turns[sessionID] = turn + } + turn.updated = h.clock() + return turn +} + // retain records n more bytes and reports whether the turn is still within the // bound. The first overflow records one diagnostic and then drops further state // instead of growing without limit. @@ -265,6 +293,55 @@ func (h *chatHub) snapshot(sessionID string) []protocol.ChatMessage { return messages } +// seenPermission records requestID as pushed for the session and reports whether +// it is newly seen (true) or a duplicate (false). The retained ids are bounded: +// the oldest is dropped once the session exceeds chatPermissionRetainedLimit, so +// the same pending request is pushed at most once while the state stays bounded. +func (h *chatHub) seenPermission(sessionID, requestID string) bool { + if sessionID == "" || requestID == "" { + return false + } + h.mu.Lock() + defer h.mu.Unlock() + turn := h.turnLocked(sessionID) + if turn.permissions == nil { + turn.permissions = map[string]struct{}{} + } + if _, ok := turn.permissions[requestID]; ok { + return false + } + turn.permissions[requestID] = struct{}{} + turn.permissionOrder = append(turn.permissionOrder, requestID) + if len(turn.permissionOrder) > chatPermissionRetainedLimit { + oldest := turn.permissionOrder[0] + turn.permissionOrder = turn.permissionOrder[1:] + delete(turn.permissions, oldest) + } + return true +} + +// forgetPermission releases a request id reserved by seenPermission when its +// frame could not be written, so a later poll re-pushes it instead of the id +// staying "seen" while the phone never received the request. +func (h *chatHub) forgetPermission(sessionID, requestID string) { + if sessionID == "" || requestID == "" { + return + } + h.mu.Lock() + defer h.mu.Unlock() + turn := h.turns[sessionID] + if turn == nil { + return + } + delete(turn.permissions, requestID) + for i, id := range turn.permissionOrder { + if id == requestID { + turn.permissionOrder = append(turn.permissionOrder[:i], turn.permissionOrder[i+1:]...) + break + } + } +} + // handleChat dispatches one chat_* request. It returns true when the request was // a chat type and has been fully answered (the caller must not fall through to // the generic response). Frames are pushed after the ack, each through the @@ -388,6 +465,70 @@ func handleChatPrompt(ctx context.Context, request protocol.Message, broker chat } bufferMu.Unlock() go drainChatStream(ctx, streamResult, streamCancel, sessionID, write) + // Poll for pending approval requests alongside the event stream, sharing + // streamCtx so the poller stops when the stream ends or the client + // disconnects. The first poll runs immediately. + go pollChatPermissions(streamCtx, broker, hub, sessionID, write) +} + +// pollChatPermissions polls the broker's pending-approval list on a fixed +// interval, sharing the chat subscription's context so it stops on disconnect or +// when the turn's stream ends. The hub dedups the request ids, so each pending +// request is pushed at most once; a poll failure is surfaced once through the +// same write closure instead of staying silent. A backend that does not expose +// the approval surface (opencode.ErrPermissionUnsupported) stops the poller +// quietly, so the documented limitation is not reported as a per-prompt error. +func pollChatPermissions(ctx context.Context, broker chatBroker, hub *chatHub, sessionID string, write func(protocol.Message) error) { + ticker := time.NewTicker(chatPermissionPollInterval) + defer ticker.Stop() + reported := false + for { + if err := pushChatPermissions(ctx, broker, hub, sessionID, write); err != nil { + if ctx.Err() != nil { + return + } + if errors.Is(err, opencode.ErrPermissionUnsupported) { + log.Printf("chat permission poll session=%s: %v", sessionID, err) + return + } + if reported { + log.Printf("chat permission poll session=%s: %v", sessionID, err) + } else { + reported = true + _ = write(protocol.Message{Type: protocol.Error, Error: "chat permission poll: " + err.Error()}) + } + } + select { + case <-ctx.Done(): + return + case <-ticker.C: + } + } +} + +// pushChatPermissions performs one poll and writes a chat_permission frame for +// every newly seen request of the session, through the same connection-scoped +// write closure as the chat stream. It never re-pushes a request id, and releases +// the reservation on a write failure so the frame is not silently dropped. +func pushChatPermissions(ctx context.Context, broker chatBroker, hub *chatHub, sessionID string, write func(protocol.Message) error) error { + pending, err := broker.Permissions(ctx, sessionID) + if err != nil { + return err + } + for _, request := range pending { + if request.SessionID != sessionID || request.RequestID == "" { + continue + } + if !hub.seenPermission(sessionID, request.RequestID) { + continue + } + frame := request + if err := write(protocol.Message{Type: protocol.ChatPermission, ChatPermission: &frame}); err != nil { + hub.forgetPermission(sessionID, request.RequestID) + return err + } + } + return nil } // drainChatStream reports the terminal error of a chat subscription and releases @@ -450,6 +591,16 @@ func handleChatSimple(ctx context.Context, request protocol.Message, broker chat _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"}) return } + if strings.TrimSpace(reply.RequestID) == "" { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a permission request id is required"}) + return + } + switch reply.Decision { + case protocol.ChatDecisionOnce, protocol.ChatDecisionAlways, protocol.ChatDecisionReject: + default: + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid permission decision is required"}) + return + } if err := broker.Reply(ctx, *reply); err != nil { _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) return diff --git a/internal/server/chat_test.go b/internal/server/chat_test.go index 7516faa1..d7184520 100644 --- a/internal/server/chat_test.go +++ b/internal/server/chat_test.go @@ -26,10 +26,19 @@ type fakeChat struct { promptCalls int interrupts int replies int + replyRequest protocol.ChatReplyRequest + replyErr error messageCalls int messageSessionID string messageLimit int messages []protocol.ChatMessage + permissionCalls int + permissionSessionID string + permissions []protocol.ChatPermissionFrame + permissionErr error + permBlock bool + permDone chan struct{} + permOnce sync.Once script []protocol.ChatEventFrame started chan struct{} done chan struct{} @@ -102,11 +111,49 @@ func (f *fakeChat) messageQuery() (int, string, int) { return f.messageCalls, f.messageSessionID, f.messageLimit } -func (f *fakeChat) Reply(context.Context, protocol.ChatReplyRequest) error { +func (f *fakeChat) Reply(_ context.Context, request protocol.ChatReplyRequest) error { f.mu.Lock() defer f.mu.Unlock() f.replies++ - return nil + f.replyRequest = request + return f.replyErr +} + +// Permissions returns the seeded pending requests, or blocks until the caller's +// context is canceled when permBlock is set (used to prove the poller stops on +// disconnect). Every call is counted so a test can assert polling happened. +func (f *fakeChat) Permissions(ctx context.Context, sessionID string) ([]protocol.ChatPermissionFrame, error) { + f.mu.Lock() + f.permissionCalls++ + f.permissionSessionID = sessionID + frames := append([]protocol.ChatPermissionFrame(nil), f.permissions...) + err := f.permissionErr + block := f.permBlock + done := f.permDone + f.mu.Unlock() + if block { + <-ctx.Done() + if done != nil { + f.permOnce.Do(func() { close(done) }) + } + return nil, ctx.Err() + } + return frames, err +} + +// permissionQuery reports the recorded permission poll count and session id. +func (f *fakeChat) permissionQuery() (int, string) { + f.mu.Lock() + defer f.mu.Unlock() + return f.permissionCalls, f.permissionSessionID +} + +// replyQuery reports the recorded chat_reply count and the last forwarded +// request, so a test can assert the exact session/request/decision. +func (f *fakeChat) replyQuery() (int, protocol.ChatReplyRequest) { + f.mu.Lock() + defer f.mu.Unlock() + return f.replies, f.replyRequest } func (f *fakeChat) counts() (int, int, int) { @@ -508,6 +555,9 @@ func TestChatInterruptEndsRunningPrompt(t *testing.T) { mu.Unlock() w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"data":{"id":"msg_1","sessionID":"ses_1","type":"user"}}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/permission/request": + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"location":{"directory":"/work"},"data":[]}`)) case r.Method == http.MethodGet && r.URL.Path == "/api/event": flusher, ok := w.(http.Flusher) if !ok { @@ -758,6 +808,9 @@ func realAdapterChat(t *testing.T, frames []string) []protocol.ChatEventFrame { prompts.Add(1) w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"data":{"id":"msg_1","sessionID":"ses_1","type":"user"}}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/permission/request": + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"location":{"directory":"/work"},"data":[]}`)) case r.Method == http.MethodGet && r.URL.Path == "/api/event": streams.Add(1) w.Header().Set("Content-Type", "text/event-stream") @@ -894,3 +947,270 @@ func TestChatSessionsAndCreateAnswerExplicitly(t *testing.T) { } } } + +// TestChatPromptPushesPermissionAndForwardsReply is the task evidence: with a +// blocking scripted stream keeping the subscription open, a seeded pending +// approval request is pushed as a chat_permission frame carrying the seeded +// session/request id after the prompt ack, and a chat_reply with Decision "once" +// is forwarded to the broker with the matching SessionID/RequestID/Decision. +// +// The live end-to-end approval flow against the real OpenCode service is NOT +// tested: this broker is the same interface seam the production handler uses, and +// the adapter's exact reply path/body are covered by the opencode package tests +// over an httptest fixture. +func TestChatPromptPushesPermissionAndForwardsReply(t *testing.T) { + broker := scriptedChat() + broker.block = true + broker.started = make(chan struct{}) + broker.permissions = []protocol.ChatPermissionFrame{{ + SessionID: "ses_1", RequestID: "req_1", Action: "bash", Resources: []string{"rm -rf /tmp"}, + }} + ctx, _, conn := dialChat(t, broker) + if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: "r1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "run it"}}); err != nil { + t.Fatal(err) + } + var ack protocol.Message + if err := wsjson.Read(ctx, conn, &ack); err != nil { + t.Fatal(err) + } + if ack.Type != protocol.ChatPrompt || ack.ID != "r1" { + t.Fatalf("prompt ack = %+v", ack) + } + var permission protocol.Message + if err := wsjson.Read(ctx, conn, &permission); err != nil { + t.Fatal(err) + } + if permission.Type == protocol.Error { + t.Fatalf("unexpected error frame: %s", permission.Error) + } + if permission.Type != protocol.ChatPermission || permission.ChatPermission == nil { + t.Fatalf("expected a chat_permission frame, got %+v", permission) + } + if permission.ChatPermission.SessionID != "ses_1" || permission.ChatPermission.RequestID != "req_1" || permission.ChatPermission.Action != "bash" { + t.Fatalf("permission frame = %+v", permission.ChatPermission) + } + + if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatReply, ID: "p1", ChatReply: &protocol.ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: protocol.ChatDecisionOnce}}); err != nil { + t.Fatal(err) + } + var response protocol.Message + if err := wsjson.Read(ctx, conn, &response); err != nil { + t.Fatal(err) + } + if response.Type != protocol.ChatReply || response.ID != "p1" { + t.Fatalf("reply response = %+v", response) + } + count, forwarded := broker.replyQuery() + if count != 1 { + t.Fatalf("reply forwarded %d times, want 1", count) + } + if forwarded.SessionID != "ses_1" || forwarded.RequestID != "req_1" || forwarded.Decision != protocol.ChatDecisionOnce { + t.Fatalf("forwarded reply = %+v", forwarded) + } +} + +// TestChatPermissionDedupesRepeatedPolls pins that the poller pushes each +// pending request at most once even though it re-reads the same list, and that a +// foreign session's request is never surfaced. +func TestChatPermissionDedupesRepeatedPolls(t *testing.T) { + broker := scriptedChat() + broker.permissions = []protocol.ChatPermissionFrame{ + {SessionID: "ses_1", RequestID: "req_1", Action: "bash"}, + {SessionID: "ses_other", RequestID: "req_x", Action: "edit"}, + } + hub := newChatHub() + var mu sync.Mutex + var pushed []protocol.Message + write := func(message protocol.Message) error { + mu.Lock() + pushed = append(pushed, message) + mu.Unlock() + return nil + } + for i := 0; i < 3; i++ { + if err := pushChatPermissions(context.Background(), broker, hub, "ses_1", write); err != nil { + t.Fatal(err) + } + } + mu.Lock() + defer mu.Unlock() + if len(pushed) != 1 { + t.Fatalf("pushed %d permission frames, want 1: %+v", len(pushed), pushed) + } + if pushed[0].Type != protocol.ChatPermission || pushed[0].ChatPermission == nil || pushed[0].ChatPermission.RequestID != "req_1" { + t.Fatalf("pushed frame = %+v", pushed[0]) + } + if calls, sessionID := broker.permissionQuery(); calls != 3 || sessionID != "ses_1" { + t.Fatalf("permission polls = %d/%q, want 3/ses_1", calls, sessionID) + } +} + +// TestChatDisconnectCancelsPermissionPoller pins that the permission poller is +// canceled on disconnect (reusing the stream's context), so it cannot leak a +// goroutine after the client goes away. +func TestChatDisconnectCancelsPermissionPoller(t *testing.T) { + broker := scriptedChat() + broker.block = true + broker.started = make(chan struct{}) + broker.done = make(chan struct{}) + broker.permBlock = true + broker.permDone = make(chan struct{}) + ctx, _, conn := dialChat(t, broker) + if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: "r1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "hi"}}); err != nil { + t.Fatal(err) + } + var ack protocol.Message + if err := wsjson.Read(ctx, conn, &ack); err != nil { + t.Fatal(err) + } + select { + case <-broker.started: + case <-time.After(2 * time.Second): + t.Fatal("stream never started") + } + select { + case <-broker.permDone: + t.Fatal("permission poller returned before disconnect") + default: + } + conn.CloseNow() + select { + case <-broker.permDone: + case <-time.After(3 * time.Second): + t.Fatal("permission poller was not canceled on disconnect") + } + select { + case <-broker.done: + case <-time.After(3 * time.Second): + t.Fatal("chat stream was not canceled on disconnect") + } +} + +// TestChatPermissionPollErrorSurfaced pins that a malformed permission list is +// reported to the client as an error frame rather than silence. +func TestChatPermissionPollErrorSurfaced(t *testing.T) { + broker := scriptedChat() + broker.block = true + broker.started = make(chan struct{}) + broker.permissionErr = fmt.Errorf("invalid OpenCode permission response") + ctx, _, conn := dialChat(t, broker) + if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: "r1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "hi"}}); err != nil { + t.Fatal(err) + } + var ack protocol.Message + if err := wsjson.Read(ctx, conn, &ack); err != nil { + t.Fatal(err) + } + var response protocol.Message + if err := wsjson.Read(ctx, conn, &response); err != nil { + t.Fatal(err) + } + if response.Type != protocol.Error || !strings.Contains(response.Error, "permission poll") { + t.Fatalf("malformed permission list not surfaced: %+v", response) + } +} + +// TestChatReplyRejectsInvalidInput pins that a missing session id, an empty +// request id and an invalid decision are rejected with a protocol.Error before +// any broker call. +func TestChatReplyRejectsInvalidInput(t *testing.T) { + broker := scriptedChat() + ctx, _, conn := dialChat(t, broker) + cases := []*protocol.ChatReplyRequest{ + nil, + {SessionID: "", RequestID: "req_1", Decision: protocol.ChatDecisionOnce}, + {SessionID: "not-a-session", RequestID: "req_1", Decision: protocol.ChatDecisionOnce}, + {SessionID: "ses_1", RequestID: "", Decision: protocol.ChatDecisionOnce}, + {SessionID: "ses_1", RequestID: "req_1", Decision: ""}, + {SessionID: "ses_1", RequestID: "req_1", Decision: "maybe"}, + } + for _, reply := range cases { + if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatReply, ID: "bad", ChatReply: reply}); err != nil { + t.Fatal(err) + } + var response protocol.Message + if err := wsjson.Read(ctx, conn, &response); err != nil { + t.Fatal(err) + } + if response.Type != protocol.Error || response.ID != "bad" { + t.Fatalf("reply %+v not rejected: %+v", reply, response) + } + } + if count, _ := broker.replyQuery(); count != 0 { + t.Fatalf("invalid replies reached the broker: %d", count) + } +} + +// TestChatReplyWithoutBroker pins that an unconfigured server answers chat_reply +// with the existing "not configured" error. +func TestChatReplyWithoutBroker(t *testing.T) { + ctx, _, conn := dialChat(t, nil) + if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatReply, ID: "p1", ChatReply: &protocol.ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: protocol.ChatDecisionOnce}}); err != nil { + t.Fatal(err) + } + var response protocol.Message + if err := wsjson.Read(ctx, conn, &response); err != nil { + t.Fatal(err) + } + if response.Type != protocol.Error || !strings.Contains(response.Error, "not configured") { + t.Fatalf("unconfigured reply not rejected: %+v", response) + } +} + +// TestChatPermissionUnsupportedBackendIsQuiet pins that a backend which does not +// expose the approval surface (the documented native v1 limitation, reported as +// opencode.ErrPermissionUnsupported) stops the poller without writing a +// per-prompt error frame, so a working prompt is not misread as a failure. +func TestChatPermissionUnsupportedBackendIsQuiet(t *testing.T) { + broker := scriptedChat() + broker.block = true + broker.started = make(chan struct{}) + broker.permissionErr = opencode.ErrPermissionUnsupported + ctx, _, conn := dialChat(t, broker) + if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: "r1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "hi"}}); err != nil { + t.Fatal(err) + } + var ack protocol.Message + if err := wsjson.Read(ctx, conn, &ack); err != nil { + t.Fatal(err) + } + if ack.Type != protocol.ChatPrompt || ack.ID != "r1" { + t.Fatalf("prompt ack = %+v", ack) + } + // No error frame may follow: a read with a short deadline must time out. + readCtx, cancel := context.WithTimeout(ctx, 300*time.Millisecond) + defer cancel() + var unexpected protocol.Message + if err := wsjson.Read(readCtx, conn, &unexpected); err == nil { + t.Fatalf("unsupported permission surface must not write a frame, got %+v", unexpected) + } + if calls, _ := broker.permissionQuery(); calls != 1 { + t.Fatalf("permission polls = %d, want 1 (the poller must stop on the documented limitation)", calls) + } +} + +// TestChatPermissionWriteFailureDoesNotDropRequest pins that a request id is not +// retained as "seen" when its frame could not be written, so the next poll +// re-pushes it instead of silently dropping the approval request. +func TestChatPermissionWriteFailureDoesNotDropRequest(t *testing.T) { + broker := scriptedChat() + broker.permissions = []protocol.ChatPermissionFrame{{SessionID: "ses_1", RequestID: "req_1", Action: "bash"}} + hub := newChatHub() + attempts := 0 + write := func(protocol.Message) error { + attempts++ + if attempts == 1 { + return fmt.Errorf("connection closed") + } + return nil + } + if err := pushChatPermissions(context.Background(), broker, hub, "ses_1", write); err == nil { + t.Fatal("a failed write must surface an error") + } + if err := pushChatPermissions(context.Background(), broker, hub, "ses_1", write); err != nil { + t.Fatalf("retry after a failed write: %v", err) + } + if attempts != 2 { + t.Fatalf("push attempts = %d, want the request re-pushed after the failure", attempts) + } +}