fix(chat): recover web approvals and questions across clients and reconnects

This commit is contained in:
2026-10-20 17:23:07 +01:00
parent ed0abb976d
commit c78def70dd
16 changed files with 420 additions and 54 deletions
+4
View File
@@ -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)
}
+78 -3
View File
@@ -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)
}
}
+13
View File
@@ -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 {
+92 -19
View File
@@ -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
}
+3
View File
@@ -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
+2 -2
View File
@@ -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":