Poll OpenCode permission requests and forward chat_reply
This commit is contained in:
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user