fix(chat): recover web approvals and questions across clients and reconnects
This commit is contained in:
@@ -442,8 +442,9 @@ func (c *Chat) Reply(ctx context.Context, request protocol.ChatReplyRequest) err
|
||||
}
|
||||
|
||||
// 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
|
||||
// GET /api/session/{id}/permission. The location-wide endpoint can silently
|
||||
// miss chats in another directory. Results are still 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.
|
||||
@@ -451,7 +452,7 @@ func (c *Chat) Permissions(ctx context.Context, id string) ([]protocol.ChatPermi
|
||||
if !sessionID.MatchString(id) {
|
||||
return nil, fmt.Errorf("invalid OpenCode session id")
|
||||
}
|
||||
data, err := c.call(ctx, "get", "/api/permission/request", nil)
|
||||
data, err := c.call(ctx, "get", "/api/session/"+id+"/permission", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -874,6 +875,36 @@ type chatFormPayload struct {
|
||||
Fields []chatFormField `json:"fields"`
|
||||
}
|
||||
|
||||
// Forms recovers pending questions even when their creation event preceded the
|
||||
// browser connection or the Pipelines process. Session ownership is explicit.
|
||||
func (c *Chat) Forms(ctx context.Context, id string) ([]protocol.ChatForm, error) {
|
||||
if !ValidSessionID(id) {
|
||||
return nil, fmt.Errorf("invalid OpenCode session id")
|
||||
}
|
||||
data, err := c.call(ctx, "get", "/api/session/"+id+"/form", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
forms, ok := chatEnvelope[chatFormPayload](data)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("invalid OpenCode form response")
|
||||
}
|
||||
result := make([]protocol.ChatForm, 0, len(forms))
|
||||
for _, form := range forms {
|
||||
if form.ID == "" || form.SessionID != id {
|
||||
continue
|
||||
}
|
||||
frame, valid, err := normalizeFormEvent("form.created", chatEvent{Form: &form}, id, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if valid {
|
||||
result = append(result, *frame.Form)
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
type chatFormField struct {
|
||||
Key string `json:"key"`
|
||||
Title string `json:"title"`
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package opencode
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestChatFormsReadbackUsesSessionOwnership(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/session/ses_otherdir/form" {
|
||||
t.Errorf("wrong session path: %s", r.URL.Path)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(`{"data":[{"id":"f_1","sessionID":"ses_otherdir","title":"Pending before connect","metadata":{"kind":"question"},"fields":[{"key":"answer","type":"text","required":true}]},{"id":"foreign","sessionID":"ses_foreign"}]}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL, Directory: "/unrelated"})
|
||||
forms, err := chat.Forms(context.Background(), "ses_otherdir")
|
||||
if err != nil || len(forms) != 1 || forms[0].ID != "f_1" || len(forms[0].Fields) != 1 || !forms[0].Fields[0].Required {
|
||||
t.Fatalf("forms=%+v err=%v", forms, err)
|
||||
}
|
||||
}
|
||||
@@ -182,13 +182,13 @@ func TestChatRejectsInvalidSessionWithoutCalling(t *testing.T) {
|
||||
}
|
||||
|
||||
// TestChatPermissionsListsAndFilters loads a pending-request fixture in the
|
||||
// verified V2 envelope (GET /api/permission/request) and asserts the adapter
|
||||
// verified V2 session-owned envelope 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" {
|
||||
if r.Method != http.MethodGet || r.URL.Path != "/api/session/ses_1/permission" {
|
||||
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -158,6 +158,9 @@ func (c *Connection) Call(ctx context.Context, method, path string, body any) ([
|
||||
return nil, fmt.Errorf("unsupported native OpenCode operation")
|
||||
}
|
||||
id := parts[0]
|
||||
if len(parts) == 2 && parts[1] == "permission" {
|
||||
return nil, fmt.Errorf("permission listing: %w", ErrPermissionUnsupported)
|
||||
}
|
||||
// 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" {
|
||||
|
||||
@@ -76,6 +76,10 @@ type chatAnswerer interface {
|
||||
Answer(context.Context, protocol.ChatAnswerRequest) error
|
||||
}
|
||||
|
||||
type chatFormReader interface {
|
||||
Forms(context.Context, string) ([]protocol.ChatForm, error)
|
||||
}
|
||||
|
||||
type chatShellOutputReader interface {
|
||||
ShellOutput(ctx context.Context, query protocol.ChatShellOutputQuery) (protocol.ChatShellOutputPage, error)
|
||||
}
|
||||
|
||||
@@ -3,11 +3,13 @@ package server
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -15,7 +17,53 @@ import (
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
type browserModelFixture struct{ *fakeChat }
|
||||
type browserModelFixture struct {
|
||||
*fakeChat
|
||||
forms *browserForms
|
||||
}
|
||||
|
||||
type browserForms struct {
|
||||
mu sync.Mutex
|
||||
pending []protocol.ChatForm
|
||||
answered int
|
||||
}
|
||||
|
||||
func (b browserModelFixture) Forms(context.Context, string) ([]protocol.ChatForm, error) {
|
||||
b.forms.mu.Lock()
|
||||
defer b.forms.mu.Unlock()
|
||||
return append([]protocol.ChatForm(nil), b.forms.pending...), nil
|
||||
}
|
||||
|
||||
func (b browserModelFixture) Answer(_ context.Context, answer protocol.ChatAnswerRequest) error {
|
||||
b.forms.mu.Lock()
|
||||
defer b.forms.mu.Unlock()
|
||||
if answer.Answers["answer"] != "Browser answer" {
|
||||
return fmt.Errorf("unexpected answer")
|
||||
}
|
||||
for i, form := range b.forms.pending {
|
||||
if form.ID == answer.FormID {
|
||||
b.forms.pending = append(b.forms.pending[:i], b.forms.pending[i+1:]...)
|
||||
b.forms.answered++
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("unknown form")
|
||||
}
|
||||
|
||||
func (b browserModelFixture) Reply(ctx context.Context, answer protocol.ChatReplyRequest) error {
|
||||
if err := b.fakeChat.Reply(ctx, answer); err != nil {
|
||||
return err
|
||||
}
|
||||
b.fakeChat.mu.Lock()
|
||||
defer b.fakeChat.mu.Unlock()
|
||||
for i, p := range b.fakeChat.permissions {
|
||||
if p.RequestID == answer.RequestID {
|
||||
b.fakeChat.permissions = append(b.fakeChat.permissions[:i], b.fakeChat.permissions[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b browserModelFixture) Models(ctx context.Context, id string) ([]protocol.ChatModel, error) {
|
||||
select {
|
||||
@@ -57,9 +105,27 @@ func TestChatBrowserLifecycleAndModelDialog(t *testing.T) {
|
||||
{ID: "msg_user", Role: protocol.ChatRoleUser, Parts: []protocol.ChatPart{{Type: "text", Text: strings.Repeat("Earlier scratch prompt line\n", 100)}}},
|
||||
{ID: "msg_answer", Role: protocol.ChatRoleAssistant, Parts: []protocol.ChatPart{{Type: "reasoning", Text: "Controlled reasoning evidence"}, {Type: "text", Text: "Controlled answer"}}},
|
||||
}
|
||||
handler := HandlerWithOptions(ctx, Options{Chat: browserModelFixture{fake}}, store)
|
||||
forms := &browserForms{}
|
||||
handler := HandlerWithOptions(ctx, Options{Chat: browserModelFixture{fake, forms}}, store)
|
||||
defer func() { cancel(); WaitRuns(handler) }()
|
||||
srv := httptest.NewServer(handler)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||
if req.URL.Path == "/fixture-attention" && req.Method == http.MethodPost {
|
||||
fake.mu.Lock()
|
||||
fake.permissions = []protocol.ChatPermissionFrame{
|
||||
{SessionID: session.ID, RequestID: "per_first", Action: "shell", Resources: []string{"Controlled first command"}},
|
||||
{SessionID: session.ID, RequestID: "per_second", Action: "edit", Resources: []string{"Controlled second path"}},
|
||||
}
|
||||
fake.mu.Unlock()
|
||||
forms.mu.Lock()
|
||||
for _, id := range []string{"form_first", "form_second"} {
|
||||
forms.pending = append(forms.pending, protocol.ChatForm{ID: id, SessionID: session.ID, Title: "Recovered question", Fields: []protocol.ChatFormField{{Key: "answer", Type: "text", Title: "Your answer", Required: true}}})
|
||||
}
|
||||
forms.mu.Unlock()
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
handler.ServeHTTP(w, req)
|
||||
}))
|
||||
defer srv.Close()
|
||||
cmd := exec.CommandContext(ctx, "node", "../../web/test/chat-hardening-probe.mjs", strings.TrimPrefix(srv.URL, "http://"), session.ID)
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
@@ -67,4 +133,13 @@ func TestChatBrowserLifecycleAndModelDialog(t *testing.T) {
|
||||
} else {
|
||||
t.Log(string(output))
|
||||
}
|
||||
fake.mu.Lock()
|
||||
replies := fake.replies
|
||||
fake.mu.Unlock()
|
||||
forms.mu.Lock()
|
||||
answers := forms.answered
|
||||
forms.mu.Unlock()
|
||||
if replies != 2 || answers != 2 {
|
||||
t.Fatalf("browser did not deliver all interactions: approvals=%d answers=%d", replies, answers)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,6 +172,19 @@ func (m *chatManager) PromptWithMessageIDFiles(ctx context.Context, sessionID, t
|
||||
}
|
||||
|
||||
var errChatAttachmentsUnsupported = errors.New("this chat harness does not support attachments")
|
||||
var errChatFormReadbackUnsupported = errors.New("this chat harness does not support pending question readback")
|
||||
|
||||
func (m *chatManager) Forms(ctx context.Context, sessionID string) ([]protocol.ChatForm, error) {
|
||||
adapter, err := m.brokerFor(ctx, sessionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if reader, ok := adapter.(chatFormReader); ok {
|
||||
return reader.Forms(ctx, sessionID)
|
||||
}
|
||||
return nil, errChatFormReadbackUnsupported
|
||||
}
|
||||
|
||||
var errChatInstructionsUnsupported = errors.New("this chat harness does not support session instructions")
|
||||
|
||||
func (m *chatManager) CheckAttachments(ctx context.Context, sessionID string) error {
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -595,25 +597,27 @@ func (h *chatHub) pushPermission(sessionID string, frame protocol.ChatPermission
|
||||
if frame.RequestID == "" || frame.Resolved {
|
||||
return
|
||||
}
|
||||
if !h.seenPermission(sessionID, frame.RequestID) {
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
// Deduplicate the active room, not the lifetime turn cache: the last
|
||||
// subscriber leaving destroys the room, and a reconnect must replay pending
|
||||
// approvals from the harness even if an earlier room already saw them.
|
||||
if turn := h.turns[sessionID]; turn != nil {
|
||||
if resolution := turn.resolutions[frame.RequestID]; resolution != nil {
|
||||
h.mu.Unlock()
|
||||
return
|
||||
}
|
||||
}
|
||||
var targets []*chatSub
|
||||
if room := h.rooms[sessionID]; room != nil {
|
||||
known := false
|
||||
for i := range room.pending {
|
||||
if room.pending[i].RequestID == frame.RequestID {
|
||||
room.pending[i] = frame
|
||||
known = true
|
||||
break
|
||||
h.mu.Unlock()
|
||||
return
|
||||
}
|
||||
}
|
||||
if !known {
|
||||
room.pending = append(room.pending, frame)
|
||||
if len(room.pending) > chatRoomPendingLimit {
|
||||
room.pending = room.pending[len(room.pending)-chatRoomPendingLimit:]
|
||||
}
|
||||
room.pending = append(room.pending, frame)
|
||||
if len(room.pending) > chatRoomPendingLimit {
|
||||
room.pending = room.pending[len(room.pending)-chatRoomPendingLimit:]
|
||||
}
|
||||
for _, sub := range room.subs {
|
||||
targets = append(targets, sub)
|
||||
@@ -719,13 +723,7 @@ func (h *chatHub) runTurn(room *chatRoom, p *chatQueuedPrompt, done chan struct{
|
||||
h.flushBuffered(room.sessionID)
|
||||
// Start the approval poller once, after the first ack, so a pending request
|
||||
// is surfaced after the prompt is acknowledged and shared with every client.
|
||||
h.mu.Lock()
|
||||
startPoller := !room.pollerStarted
|
||||
room.pollerStarted = true
|
||||
h.mu.Unlock()
|
||||
if startPoller {
|
||||
go h.pollRoom(room, broker)
|
||||
}
|
||||
h.startRoomPoller(room, broker)
|
||||
select {
|
||||
case <-done:
|
||||
case <-room.ctx.Done():
|
||||
@@ -819,6 +817,16 @@ func (h *chatHub) drainStream(room *chatRoom, result <-chan error) {
|
||||
// pollRoom polls the broker's pending-approval list for the room on a fixed
|
||||
// interval and pushes each newly seen request to every attached client. The
|
||||
// first poll runs immediately; the loop stops with the room's context.
|
||||
func (h *chatHub) startRoomPoller(room *chatRoom, broker chatBroker) {
|
||||
h.mu.Lock()
|
||||
start := !room.pollerStarted && room.ctx.Err() == nil
|
||||
room.pollerStarted = true
|
||||
h.mu.Unlock()
|
||||
if start {
|
||||
go h.pollRoom(room, broker)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *chatHub) pollRoom(room *chatRoom, broker chatBroker) {
|
||||
ticker := time.NewTicker(chatPermissionPollInterval)
|
||||
defer ticker.Stop()
|
||||
@@ -850,6 +858,7 @@ func (h *chatHub) pollRoom(room *chatRoom, broker chatBroker) {
|
||||
// pollPermissionsOnce performs one poll and pushes each newly seen request of the
|
||||
// session to every client watching it.
|
||||
func (h *chatHub) pollPermissionsOnce(ctx context.Context, broker chatBroker, sessionID string) error {
|
||||
beforePermissions := h.pendingFrames(sessionID)
|
||||
pending, err := broker.Permissions(ctx, sessionID)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -860,6 +869,70 @@ func (h *chatHub) pollPermissionsOnce(ctx context.Context, broker chatBroker, se
|
||||
}
|
||||
h.pushPermission(sessionID, request)
|
||||
}
|
||||
for _, old := range beforePermissions {
|
||||
found := false
|
||||
for _, request := range pending {
|
||||
if request.SessionID == sessionID && request.RequestID == old.RequestID {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
h.confirmPermission(sessionID, old.RequestID, "the harness", "")
|
||||
}
|
||||
}
|
||||
if reader, ok := broker.(chatFormReader); ok {
|
||||
h.mu.Lock()
|
||||
room := h.rooms[sessionID]
|
||||
var before []protocol.ChatForm
|
||||
if room != nil {
|
||||
before = slices.Clone(room.forms)
|
||||
}
|
||||
h.mu.Unlock()
|
||||
forms, err := reader.Forms(ctx, sessionID)
|
||||
if errors.Is(err, errChatFormReadbackUnsupported) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("question readback: %w", err)
|
||||
}
|
||||
// Do not overwrite a live event that raced this readback. The next poll
|
||||
// retries from an authoritative snapshot instead.
|
||||
h.mu.Lock()
|
||||
current := h.rooms[sessionID]
|
||||
unchanged := current == room && room != nil && reflect.DeepEqual(before, room.forms)
|
||||
h.mu.Unlock()
|
||||
if unchanged {
|
||||
for _, form := range forms {
|
||||
if form.SessionID != sessionID || form.ID == "" {
|
||||
continue
|
||||
}
|
||||
found := false
|
||||
for _, old := range before {
|
||||
if reflect.DeepEqual(old, form) {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
h.emitRoom(room, protocol.ChatEventFrame{SessionID: sessionID, Kind: protocol.ChatEventForm, Form: &form})
|
||||
}
|
||||
}
|
||||
for _, old := range before {
|
||||
found := false
|
||||
for _, form := range forms {
|
||||
if form.ID == old.ID && form.SessionID == sessionID {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
old.Resolved = true
|
||||
h.emitRoom(room, protocol.ChatEventFrame{SessionID: sessionID, Kind: protocol.ChatEventForm, Form: &old})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -206,6 +206,9 @@ func handleChatSubscribe(request protocol.Message, broker chatBroker, hub *chatH
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "could not observe session " + query.SessionID})
|
||||
return
|
||||
}
|
||||
// Observe requests from CLI-originated turns and recover after reload; do
|
||||
// not require the browser to send another prompt just to start polling.
|
||||
hub.startRoomPoller(sub.room, broker)
|
||||
// A turn already in flight when this client attaches has no `step started`
|
||||
// frame in its future, so replay the live marker. The composer's Stop control
|
||||
// and the transcript's one activity row read it; the later `step ended` frame
|
||||
|
||||
@@ -851,7 +851,7 @@ 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":
|
||||
case r.Method == http.MethodGet && (r.URL.Path == "/api/session/ses_1/permission" || r.URL.Path == "/api/session/ses_1/form"):
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"location":{"directory":"/work"},"data":[]}`))
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/api/shell":
|
||||
@@ -1384,7 +1384,7 @@ 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":
|
||||
case r.Method == http.MethodGet && (r.URL.Path == "/api/session/ses_1/permission" || r.URL.Path == "/api/session/ses_1/form"):
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"location":{"directory":"/work"},"data":[]}`))
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/api/shell":
|
||||
|
||||
Reference in New Issue
Block a user