fix(chat): settle authoritative turns and make capabilities explicit

This commit is contained in:
2026-10-20 15:45:09 +01:00
parent 016fcb552a
commit e504780976
16 changed files with 615 additions and 56 deletions
+65 -2
View File
@@ -12,6 +12,7 @@ import (
"sort"
"strings"
"sync"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
@@ -729,10 +730,71 @@ func (c *Chat) Stream(ctx context.Context, id string, ready func(), emit func(pr
return err
}
defer body.Close()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
var delivery sync.Mutex
state.mu.Lock()
busy := state.Active
state.mu.Unlock()
setBusy := func(value bool) {
busy = value
state.mu.Lock()
state.Active = value
state.mu.Unlock()
}
deliver := func(frame protocol.ChatEventFrame) error {
delivery.Lock()
defer delivery.Unlock()
if frame.Kind == protocol.ChatEventStep || frame.Kind == protocol.ChatEventText || frame.Kind == protocol.ChatEventTool || frame.Kind == protocol.ChatEventReasoning {
setBusy(true)
}
return emit(frame)
}
// V2 /api/session/active describes foreground drains, not individual
// provider steps. Poll it even after reconnect: a busy drain may have
// started before this SSE subscription. Failed readbacks never imply idle.
watchDone := make(chan struct{})
go func() {
defer close(watchDone)
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
}
delivery.Lock()
readCtx, readCancel := context.WithTimeout(ctx, 5*time.Second)
data, err := c.call(readCtx, "get", "/api/session/active", nil)
readCancel()
var emitErr error
var response struct {
Data *map[string]json.RawMessage `json:"data"`
}
if err == nil && json.Unmarshal(data, &response) == nil && response.Data != nil {
_, active := (*response.Data)[id]
if active && !busy {
setBusy(true)
emitErr = emit(protocol.ChatEventFrame{SessionID: id, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepStarted}})
} else if !active && busy {
setBusy(false)
emitErr = emit(protocol.ChatEventFrame{SessionID: id, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded}})
}
}
delivery.Unlock()
if emitErr != nil {
cancel()
_ = body.Close()
return
}
}
}()
defer func() { cancel(); <-watchDone }()
if ready != nil {
ready()
}
return c.scanChatEventsWithState(ctx, body, id, state, emit)
return c.scanChatEventsWithState(ctx, body, id, state, deliver)
}
// scanChatEvents turns an SSE body into protocol frames, one bounded frame at a
@@ -905,6 +967,7 @@ func (i *chatShellInfo) shellSessionID() string {
// (which carry no session) can be attributed to the right chat.
type ChatStreamState struct {
mu sync.Mutex
Active bool // last observed foreground drain, retained across SSE reconnects
LastMessageID string
Shells map[string]struct{}
Forms map[string]string
@@ -1056,7 +1119,7 @@ func NormalizeChatEvent(payload []byte, sessionID string, stream *ChatStreamStat
frame.Part = &protocol.ChatPart{Type: protocol.ChatPartReasoning, ID: protocol.ChatDeltaPartID(messageID, protocol.ChatPartReasoning, data.Ordinal)}
case outer.Type == "session.step.started" || outer.Type == "session.step.streamed" || outer.Type == "session.step.ended":
frame.Kind = protocol.ChatEventStep
frame.Step = &protocol.ChatStep{Status: strings.TrimPrefix(outer.Type, "session.step."), Index: stepIndex(data)}
frame.Step = &protocol.ChatStep{Status: strings.TrimPrefix(outer.Type, "session.step."), Index: stepIndex(data), Intermediate: outer.Type == "session.step.ended"}
case strings.HasPrefix(outer.Type, "session.tool."):
status, ok := toolStatus(outer.Type)
if !ok {
+109
View File
@@ -0,0 +1,109 @@
package opencode
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// The active endpoint, not finish/tool-calls or a step boundary, owns the
// foreground drain. Reconnecting after the last event must still settle it.
func TestChatActivityMultiStepAndReconnect(t *testing.T) {
var active atomic.Bool
var invalid atomic.Bool
active.Store(true)
events := make(chan string, 8)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/session/active":
w.Header().Set("Content-Type", "application/json")
if invalid.Load() {
fmt.Fprint(w, `{"data":null}`)
return
}
if active.Load() {
fmt.Fprint(w, `{"data":{"ses_1":{"type":"running"}}}`)
} else {
fmt.Fprint(w, `{"data":{}}`)
}
case "/api/event":
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(200)
w.(http.Flusher).Flush()
for {
select {
case <-r.Context().Done():
return
case event := <-events:
fmt.Fprintf(w, "data: %s\n\n", event)
w.(http.Flusher).Flush()
}
}
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
frames := make(chan protocol.ChatEventFrame, 32)
start := func() (context.CancelFunc, <-chan error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
done := make(chan error, 1)
go func() {
done <- chat.Stream(ctx, "ses_1", nil, func(frame protocol.ChatEventFrame) error { frames <- frame; return nil })
}()
return cancel, done
}
next := func() protocol.ChatEventFrame {
t.Helper()
select {
case frame := <-frames:
return frame
case <-time.After(3 * time.Second):
t.Fatal("no activity frame")
return protocol.ChatEventFrame{}
}
}
cancel, done := start()
defer cancel()
// Active readback restores Running even with no SSE replay on reconnect.
if frame := next(); frame.Step == nil || frame.Step.Status != protocol.ChatStepStarted {
t.Fatalf("active = %+v", frame)
}
for i := 0; i < 2; i++ {
events <- `{"type":"session.step.ended","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","finish":"tool-calls"}}`
frame := next()
if frame.Step == nil || !frame.Step.Intermediate {
t.Fatalf("step must be intermediate: %+v", frame)
}
}
select {
case frame := <-frames:
t.Fatalf("premature completion: %+v", frame)
case <-time.After(650 * time.Millisecond):
}
cancel()
<-done
active.Store(false)
invalid.Store(true)
cancel2, done2 := start()
defer cancel2()
select {
case frame := <-frames:
t.Fatalf("invalid readback settled turn: %+v", frame)
case <-time.After(650 * time.Millisecond):
}
invalid.Store(false)
frame := next()
if frame.Step == nil || frame.Step.Status != protocol.ChatStepEnded || frame.Step.Intermediate {
t.Fatalf("idle after reconnect = %+v", frame)
}
cancel2()
<-done2
}