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
+158 -7
View File
@@ -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