Preserve background shell visibility across readback races

Reconcile authoritative shell snapshots with bounded lifecycle journals so concurrent exits and creates cannot be overwritten, coalesce observation setup, and retain verified ownership across reconnects. Add deterministic reconciliation and cancellation regressions plus stable limited-visibility handling.\n\nChecked packaged templates and authoring skill references: none need updating. The task-owned docs note records the stale shared chat documentation for docs-fold; shared documentation was not edited.
This commit is contained in:
2026-10-18 12:54:36 +01:00
parent 101e5e8dfe
commit e9d902213e
12 changed files with 1036 additions and 25 deletions
+96 -3
View File
@@ -3,6 +3,7 @@ package server
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
@@ -52,6 +53,8 @@ type fakeChat struct {
permissionSessionID string
permissions []protocol.ChatPermissionFrame
permissionErr error
shells []protocol.ChatShell
shellErr error
sessionCalls int
sessions []protocol.ChatSession
sessionErr error
@@ -62,6 +65,8 @@ type fakeChat struct {
started chan struct{}
done chan struct{}
startOnce sync.Once
streamCalls int
readyGate <-chan struct{}
block bool
subscribed bool
promptBeforeSubscribe bool
@@ -91,13 +96,18 @@ func (f *fakeChat) Prompt(context.Context, string, string) error {
func (f *fakeChat) Stream(ctx context.Context, _ string, ready func(), emit func(protocol.ChatEventFrame) error) error {
f.mu.Lock()
f.subscribed = true
f.streamCalls++
readyGate := f.readyGate
f.mu.Unlock()
if ready != nil {
ready()
}
if f.started != nil {
f.startOnce.Do(func() { close(f.started) })
}
if readyGate != nil {
<-readyGate
}
if ready != nil {
ready()
}
if f.block {
<-ctx.Done()
if f.done != nil {
@@ -116,6 +126,42 @@ func (f *fakeChat) Stream(ctx context.Context, _ string, ready func(), emit func
return nil
}
// TestChatHubConcurrentObserversShareStream pins the start-up handoff: two
// clients that subscribe before the broker says ready still share one firehose.
func TestChatHubConcurrentObserversShareStream(t *testing.T) {
broker := scriptedChat()
broker.block = true
broker.started = make(chan struct{})
gate := make(chan struct{})
broker.readyGate = gate
hub := newChatHub()
hub.mu.Lock()
room := hub.roomLocked("ses_1")
hub.mu.Unlock()
errs := make(chan error, 2)
go func() { errs <- hub.ensureObserving(room, broker) }()
select {
case <-broker.started:
case <-time.After(time.Second):
t.Fatal("first observer did not start the broker stream")
}
go func() { errs <- hub.ensureObserving(room, broker) }()
close(gate)
for range 2 {
if err := <-errs; err != nil {
t.Fatalf("ensureObserving: %v", err)
}
}
broker.mu.Lock()
calls := broker.streamCalls
broker.mu.Unlock()
if calls != 1 {
t.Fatalf("broker Stream calls = %d, want 1", calls)
}
room.cancel()
}
func (f *fakeChat) Interrupt(context.Context, string) error {
f.mu.Lock()
defer f.mu.Unlock()
@@ -151,6 +197,12 @@ func (f *fakeChat) Reply(_ context.Context, request protocol.ChatReplyRequest) e
// 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) Shells(context.Context, string) ([]protocol.ChatShell, error) {
f.mu.Lock()
defer f.mu.Unlock()
return append([]protocol.ChatShell(nil), f.shells...), f.shellErr
}
func (f *fakeChat) Permissions(ctx context.Context, sessionID string) ([]protocol.ChatPermissionFrame, error) {
f.mu.Lock()
f.permissionCalls++
@@ -682,6 +734,9 @@ func TestChatInterruptEndsRunningPrompt(t *testing.T) {
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/shell":
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":[]}`))
case r.Method == http.MethodGet && r.URL.Path == "/api/event":
flusher, ok := w.(http.Flusher)
if !ok {
@@ -995,6 +1050,7 @@ func TestChatPromptStreamsShellFrame(t *testing.T) {
// shows the background process instead of nothing until it exits.
func TestChatSubscribeReplaysRunningShell(t *testing.T) {
broker := scriptedChat()
broker.shells = []protocol.ChatShell{{ID: "sh_1", Status: protocol.ChatShellRunning, Command: "sleep 120"}}
broker.script = append([]protocol.ChatEventFrame{
{SessionID: "ses_1", Kind: protocol.ChatEventShell, Shell: &protocol.ChatShell{ID: "sh_1", Status: protocol.ChatShellRunning, Command: "sleep 120"}},
}, broker.script...)
@@ -1039,6 +1095,40 @@ func TestChatSubscribeReplaysRunningShell(t *testing.T) {
}
}
// TestChatSubscribeKeepsStreamWhenShellReadbackFails ensures a temporary
// authoritative readback failure does not make chat unavailable or replay a
// stale process as running. The subscriber receives an explicit limitation
// while its broker stream remains attached for future lifecycle events.
func TestChatSubscribeKeepsStreamWhenShellReadbackFails(t *testing.T) {
broker := scriptedChat()
broker.block = true
broker.shellErr = errors.New("shell endpoint unavailable: https://user:secret@example.invalid private response body")
ctx, _, conn := dialChat(t, broker)
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatSubscribe, ID: "sub1", ChatSubscribe: &protocol.ChatQuery{SessionID: "ses_1"}}); 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.ChatSubscribe || ack.ID != "sub1" {
t.Fatalf("subscribe ack = %+v", ack)
}
var limited protocol.Message
if err := wsjson.Read(ctx, conn, &limited); err != nil {
t.Fatal(err)
}
if limited.Type != protocol.Error || limited.Error != "background shell visibility is limited" {
t.Fatalf("limited visibility notice = %+v", limited)
}
broker.mu.Lock()
calls := broker.streamCalls
broker.mu.Unlock()
if calls != 1 {
t.Fatalf("broker Stream calls = %d, want 1", calls)
}
}
// TestChatPromptSubscribesBeforePrompt pins the subscribe-before-prompt order:
// the firehose has no replay cursor, so the subscription must be attached before
// the prompt is posted or deltas emitted in between are lost.
@@ -1079,6 +1169,9 @@ func realAdapterChat(t *testing.T, frames []string) []protocol.ChatEventFrame {
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/shell":
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":[]}`))
case r.Method == http.MethodGet && r.URL.Path == "/api/event":
streams.Add(1)
w.Header().Set("Content-Type", "text/event-stream")